...

Source file src/github.com/opencontainers/image-spec/schema/error.go

Documentation: github.com/opencontainers/image-spec/schema

     1  // Copyright 2016 The Linux Foundation
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package schema
    16  
    17  import (
    18  	"bufio"
    19  	"encoding/json"
    20  	"errors"
    21  	"io"
    22  )
    23  
    24  // A SyntaxError is a description of a JSON syntax error
    25  // including line, column and offset in the JSON file.
    26  type SyntaxError struct {
    27  	msg       string
    28  	Line, Col int
    29  	Offset    int64
    30  }
    31  
    32  func (e *SyntaxError) Error() string { return e.msg }
    33  
    34  // WrapSyntaxError checks whether the given error is a *json.SyntaxError
    35  // and converts it into a *schema.SyntaxError containing line/col information using the given reader.
    36  // If the given error is not a *json.SyntaxError it is returned unchanged.
    37  func WrapSyntaxError(r io.Reader, err error) error {
    38  	var serr *json.SyntaxError
    39  	if errors.As(err, &serr) {
    40  		buf := bufio.NewReader(r)
    41  		line := 0
    42  		col := 0
    43  		for i := int64(0); i < serr.Offset; i++ {
    44  			b, berr := buf.ReadByte()
    45  			if berr != nil {
    46  				break
    47  			}
    48  			if b == '\n' {
    49  				line++
    50  				col = 1
    51  			} else {
    52  				col++
    53  			}
    54  		}
    55  		return &SyntaxError{serr.Error(), line, col, serr.Offset}
    56  	}
    57  
    58  	return err
    59  }
    60  

View as plain text