github.com/authzed/spicedb@v1.32.1-0.20240520085336-ebda56537386/pkg/validationfile/blocks/errors.go (about)

     1  package blocks
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"regexp"
     7  	"strconv"
     8  	"strings"
     9  
    10  	"github.com/authzed/spicedb/pkg/spiceerrors"
    11  )
    12  
    13  var (
    14  	yamlLineRegex      = regexp.MustCompile(`line ([0-9]+): (.+)`)
    15  	yamlUnmarshalRegex = regexp.MustCompile("cannot unmarshal !!str `([^`]+)...`")
    16  )
    17  
    18  func convertYamlError(err error) error {
    19  	linePieces := yamlLineRegex.FindStringSubmatch(err.Error())
    20  	if len(linePieces) == 3 {
    21  		lineNumber, parseErr := strconv.ParseUint(linePieces[1], 10, 32)
    22  		if parseErr != nil {
    23  			lineNumber = 0
    24  		}
    25  
    26  		message := linePieces[2]
    27  		source := ""
    28  		unmarshalPieces := yamlUnmarshalRegex.FindStringSubmatch(message)
    29  		if len(unmarshalPieces) == 2 {
    30  			source = unmarshalPieces[1]
    31  			if strings.Contains(source, " ") {
    32  				source, _, _ = strings.Cut(source, " ")
    33  			}
    34  
    35  			message = fmt.Sprintf("unexpected value `%s`", source)
    36  		}
    37  
    38  		return spiceerrors.NewErrorWithSource(
    39  			errors.New(message),
    40  			source,
    41  			lineNumber,
    42  			0,
    43  		)
    44  	}
    45  
    46  	return err
    47  }