Files
genqlient/generate/errors.go
T
Ben Kraft e88305ecbd Add support for abstract-typed named fragments (#79)
## Summary:
In previous commits I added support to genqlient for interfaces,
inline fragments, and, most recently, named fragments of concrete
(object) type.  This leaves only named fragments of interface type!
Like other named fragments, these are useful for code-sharing,
especially if you want some code that can handle the same fields of
several different types.

As seems to be inevitable with genqlient, this was mostly pretty
straightforward, although there turned out to be surprisingly many
places we needed to add some handling; almost anywhere that touches
interfaces *or* named fragments needed some updates.  But it's all
hopefully fairly clear code.

As a part of this change I made three semi-related improvements:
1. I refactored the handling of descriptions (i.e. GoDoc), because it
   was getting more and more confusing and duplicative.  I'm still not
   sure how much of it it makes sense to inline vs. separate, but I
   think this is better than it was.  This resulted in some minor
   changes to descriptions, generally in the direction of making things
   more consistent.
2. I bumped the minimum Go version to 1.14 so we can guarantee support
   for duplicate interface methods.  These are useful for
   abstract-in-absstract spreads; we generate an interface for the
   fragment, and (if the fragment-type implements the scope-type) we
   embed it into the interface we generate for its spread-context, and
   if the two have a duplicated field we thus duplicate the method.  It
   wouldn't be impossible to support this on 1.13 (maybe just by
   omitting said embed) but it didn't seem worth it.  This also removes
   a few special-cases in tests.
3. I added a bunch of code to better format syntax errors in the
   generated code (which we see from `gofmt`).  This is mostly just an
   internal improvement; I wrote it because I got annoyed while hunting
   down a few such errors..

Fixes, at last, #8.

Issue: https://github.com/Khan/genqlient/issues/8

## Test plan:
make check


Author: benjaminjkraft

Reviewers: dnerdy, benjaminjkraft, aberkan, MiguelCastillo

Required Reviewers: 

Approved By: dnerdy

Checks:  Lint,  Test (1.17),  Test (1.16),  Test (1.15),  Test (1.14),  Test (1.17),  Test (1.16),  Test (1.15),  Test (1.14),  Lint

Pull Request URL: https://github.com/Khan/genqlient/pull/79
2021-09-09 09:48:18 -07:00

182 lines
4.1 KiB
Go

package generate
import (
"bytes"
"errors"
"fmt"
"go/scanner"
"math"
"strconv"
"strings"
"github.com/vektah/gqlparser/v2/ast"
"github.com/vektah/gqlparser/v2/gqlerror"
)
type errorPos struct {
filename string
line, col int
}
func (pos *errorPos) String() string {
filename, lineOffset := splitFilename(pos.filename)
line := lineOffset + pos.line
if line != 0 {
return fmt.Sprintf("%v:%v", filename, line)
} else {
return filename
}
}
type genqlientError struct {
pos *errorPos
msg string
wrapped error
}
func splitFilename(filename string) (name string, lineOffset int) {
split := strings.Split(filename, ":")
if len(split) != 2 {
return filename, 0
}
offset, err := strconv.Atoi(split[1])
if err != nil {
return split[0], 0
}
return split[0], offset - 1
}
func (err *genqlientError) Error() string {
if err.pos != nil {
return err.pos.String() + ": " + err.msg
} else {
return err.msg
}
}
func (err *genqlientError) Unwrap() error {
return err.wrapped
}
func errorf(pos *ast.Position, msg string, args ...interface{}) error {
// TODO: alternately accept a filename only, or maybe even a go-parser pos
// We do all our own wrapping, because if the wrapped error already has a
// pos, we want to extract it out and put it at the front, not in the
// middle.
var wrapped error
var wrapIndex int
for i, arg := range args {
if wrapped == nil {
var ok bool
wrapped, ok = arg.(error)
if ok {
wrapIndex = i
}
}
}
var wrappedGenqlient *genqlientError
isGenqlient := errors.As(wrapped, &wrappedGenqlient)
var wrappedGraphQL *gqlerror.Error
isGraphQL := errors.As(wrapped, &wrappedGraphQL)
if !isGraphQL {
var wrappedGraphQLList gqlerror.List
isGraphQLList := errors.As(wrapped, &wrappedGraphQLList)
if isGraphQLList && len(wrappedGraphQLList) > 0 {
isGraphQL = true
wrappedGraphQL = wrappedGraphQLList[0]
}
}
var errPos *errorPos
if pos != nil {
errPos = &errorPos{
filename: pos.Src.Name,
line: pos.Line,
col: pos.Column,
}
} else if isGenqlient {
errPos = wrappedGenqlient.pos
} else if isGraphQL {
filename, _ := wrappedGraphQL.Extensions["file"].(string)
if filename != "" {
var loc gqlerror.Location
if len(wrappedGraphQL.Locations) > 0 {
loc = wrappedGraphQL.Locations[0]
}
errPos = &errorPos{
filename: filename,
line: loc.Line,
col: loc.Column,
}
}
}
if wrapped != nil {
errText := wrapped.Error()
if isGenqlient {
errText = wrappedGenqlient.msg
} else if isGraphQL {
errText = wrappedGraphQL.Message
}
args[wrapIndex] = errText
}
msg = fmt.Sprintf(msg, args...)
return &genqlientError{
msg: msg,
pos: errPos,
wrapped: wrapped,
}
}
// goSourceError processes the error(s) returned by go tooling (gofmt, etc.)
// into a nice error message.
//
// In practice, such errors are genqlient internal errors, but it's still
// useful to format them nicely for debugging.
func goSourceError(
failedOperation string, // e.g. "gofmt", for the error message
source []byte,
err error,
) error {
var errTexts []string
var scanErrs scanner.ErrorList
var scanErr *scanner.Error
var badLines map[int]bool
if errors.As(err, &scanErrs) {
errTexts = make([]string, len(scanErrs))
badLines = make(map[int]bool, len(scanErrs))
for i, scanErr := range scanErrs {
errTexts[i] = err.Error()
badLines[scanErr.Pos.Line] = true
}
} else if errors.As(err, &scanErr) {
errTexts = []string{scanErr.Error()}
badLines = map[int]bool{scanErr.Pos.Line: true}
} else {
errTexts = []string{err.Error()}
}
lines := bytes.SplitAfter(source, []byte("\n"))
lineNoWidth := int(math.Ceil(math.Log10(float64(len(lines) + 1))))
for i, line := range lines {
prefix := " "
if badLines[i] {
prefix = "> "
}
lineNo := strconv.Itoa(i + 1)
padding := strings.Repeat(" ", lineNoWidth-len(lineNo))
lines[i] = []byte(fmt.Sprintf("%s%s%s | %s", prefix, padding, lineNo, line))
}
return errorf(nil,
"genqlient internal error: failed to %s code:\n\t%s---source code---\n%s",
failedOperation, strings.Join(errTexts, "\n\t"), bytes.Join(lines, nil))
}