Skip to content

Commit

Permalink
Some spring cleaning
Browse files Browse the repository at this point in the history
Signed-off-by: Steve Coffman <steve@khanacademy.org>
  • Loading branch information
StevenACoffman committed Jun 6, 2023
1 parent 9f6a265 commit 4a18a29
Show file tree
Hide file tree
Showing 16 changed files with 69 additions and 1,246 deletions.
3 changes: 0 additions & 3 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ linters:
disable-all: true
enable:
- bodyclose
- deadcode
- depguard
- dupl
- errcheck
Expand All @@ -25,11 +24,9 @@ linters:
- nakedret
- prealloc
- staticcheck
- structcheck
- typecheck
- unconvert
- unused
- varcheck

issues:
exclude-rules:
Expand Down
4 changes: 2 additions & 2 deletions _examples/websocket-initfunc/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ import (

func webSocketInit(ctx context.Context, initPayload transport.InitPayload) (context.Context, error) {
// Get the token from payload
any := initPayload["authToken"]
token, ok := any.(string)
payload := initPayload["authToken"]
token, ok := payload.(string)
if !ok || token == "" {
return nil, errors.New("authToken not found in transport payload")
}
Expand Down
10 changes: 5 additions & 5 deletions codegen/args.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,19 +103,19 @@ nextArg:
return newArgs, nil
}

func (a *Data) Args() map[string][]*FieldArgument {
func (d *Data) Args() map[string][]*FieldArgument {
ret := map[string][]*FieldArgument{}
for _, o := range a.Objects {
for _, o := range d.Objects {
for _, f := range o.Fields {
if len(f.Args) > 0 {
ret[f.ArgsFunc()] = f.Args
}
}
}

for _, d := range a.Directives() {
if len(d.Args) > 0 {
ret[d.ArgsFunc()] = d.Args
for _, directive := range d.Directives() {
if len(directive.Args) > 0 {
ret[directive.ArgsFunc()] = directive.Args
}
}
return ret
Expand Down
74 changes: 37 additions & 37 deletions codegen/config/binder.go
Original file line number Diff line number Diff line change
Expand Up @@ -221,99 +221,99 @@ func (ref *TypeReference) Elem() *TypeReference {
return nil
}

func (t *TypeReference) IsPtr() bool {
_, isPtr := t.GO.(*types.Pointer)
func (ref *TypeReference) IsPtr() bool {
_, isPtr := ref.GO.(*types.Pointer)
return isPtr
}

// fix for https://github.com/golang/go/issues/31103 may make it possible to remove this (may still be useful)
func (t *TypeReference) IsPtrToPtr() bool {
if p, isPtr := t.GO.(*types.Pointer); isPtr {
func (ref *TypeReference) IsPtrToPtr() bool {
if p, isPtr := ref.GO.(*types.Pointer); isPtr {
_, isPtr := p.Elem().(*types.Pointer)
return isPtr
}
return false
}

func (t *TypeReference) IsNilable() bool {
return IsNilable(t.GO)
func (ref *TypeReference) IsNilable() bool {
return IsNilable(ref.GO)
}

func (t *TypeReference) IsSlice() bool {
_, isSlice := t.GO.(*types.Slice)
return t.GQL.Elem != nil && isSlice
func (ref *TypeReference) IsSlice() bool {
_, isSlice := ref.GO.(*types.Slice)
return ref.GQL.Elem != nil && isSlice
}

func (t *TypeReference) IsPtrToSlice() bool {
if t.IsPtr() {
_, isPointerToSlice := t.GO.(*types.Pointer).Elem().(*types.Slice)
func (ref *TypeReference) IsPtrToSlice() bool {
if ref.IsPtr() {
_, isPointerToSlice := ref.GO.(*types.Pointer).Elem().(*types.Slice)
return isPointerToSlice
}
return false
}

func (t *TypeReference) IsPtrToIntf() bool {
if t.IsPtr() {
_, isPointerToInterface := t.GO.(*types.Pointer).Elem().(*types.Interface)
func (ref *TypeReference) IsPtrToIntf() bool {
if ref.IsPtr() {
_, isPointerToInterface := ref.GO.(*types.Pointer).Elem().(*types.Interface)
return isPointerToInterface
}
return false
}

func (t *TypeReference) IsNamed() bool {
_, isSlice := t.GO.(*types.Named)
func (ref *TypeReference) IsNamed() bool {
_, isSlice := ref.GO.(*types.Named)
return isSlice
}

func (t *TypeReference) IsStruct() bool {
_, isStruct := t.GO.Underlying().(*types.Struct)
func (ref *TypeReference) IsStruct() bool {
_, isStruct := ref.GO.Underlying().(*types.Struct)
return isStruct
}

func (t *TypeReference) IsScalar() bool {
return t.Definition.Kind == ast.Scalar
func (ref *TypeReference) IsScalar() bool {
return ref.Definition.Kind == ast.Scalar
}

func (t *TypeReference) UniquenessKey() string {
func (ref *TypeReference) UniquenessKey() string {
nullability := "O"
if t.GQL.NonNull {
if ref.GQL.NonNull {
nullability = "N"
}

elemNullability := ""
if t.GQL.Elem != nil && t.GQL.Elem.NonNull {
if ref.GQL.Elem != nil && ref.GQL.Elem.NonNull {
// Fix for #896
elemNullability = "ᚄ"
}
return nullability + t.Definition.Name + "2" + templates.TypeIdentifier(t.GO) + elemNullability
return nullability + ref.Definition.Name + "2" + templates.TypeIdentifier(ref.GO) + elemNullability
}

func (t *TypeReference) MarshalFunc() string {
if t.Definition == nil {
panic(errors.New("Definition missing for " + t.GQL.Name()))
func (ref *TypeReference) MarshalFunc() string {
if ref.Definition == nil {
panic(errors.New("Definition missing for " + ref.GQL.Name()))
}

if t.Definition.Kind == ast.InputObject {
if ref.Definition.Kind == ast.InputObject {
return ""
}

return "marshal" + t.UniquenessKey()
return "marshal" + ref.UniquenessKey()
}

func (t *TypeReference) UnmarshalFunc() string {
if t.Definition == nil {
panic(errors.New("Definition missing for " + t.GQL.Name()))
func (ref *TypeReference) UnmarshalFunc() string {
if ref.Definition == nil {
panic(errors.New("Definition missing for " + ref.GQL.Name()))
}

if !t.Definition.IsInputType() {
if !ref.Definition.IsInputType() {
return ""
}

return "unmarshal" + t.UniquenessKey()
return "unmarshal" + ref.UniquenessKey()
}

func (t *TypeReference) IsTargetNilable() bool {
return IsNilable(t.Target)
func (ref *TypeReference) IsTargetNilable() bool {
return IsNilable(ref.Target)
}

func (b *Binder) PushRef(ret *TypeReference) {
Expand Down
8 changes: 4 additions & 4 deletions graphql/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,15 @@ type Cache interface {
type MapCache map[string]interface{}

// Get looks up a key's value from the cache.
func (m MapCache) Get(ctx context.Context, key string) (value interface{}, ok bool) {
func (m MapCache) Get(_ context.Context, key string) (value interface{}, ok bool) {
v, ok := m[key]
return v, ok
}

// Add adds a value to the cache.
func (m MapCache) Add(ctx context.Context, key string, value interface{}) { m[key] = value }
func (m MapCache) Add(_ context.Context, key string, value interface{}) { m[key] = value }

type NoCache struct{}

func (n NoCache) Get(ctx context.Context, key string) (value interface{}, ok bool) { return nil, false }
func (n NoCache) Add(ctx context.Context, key string, value interface{}) {}
func (n NoCache) Get(_ context.Context, _ string) (value interface{}, ok bool) { return nil, false }
func (n NoCache) Add(_ context.Context, _ string, _ interface{}) {}
2 changes: 0 additions & 2 deletions graphql/coercion_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
)

func TestCoerceList(t *testing.T) {

mapInput := map[string]interface{}{
"test": "value",
"nested": map[string]interface{}{
Expand All @@ -34,5 +33,4 @@ func TestCoerceList(t *testing.T) {
assert.Equal(t, []interface{}{mapInput}, CoerceList([]interface{}{mapInput}))
assert.Equal(t, []interface{}{mapInput}, CoerceList([]map[string]interface{}{mapInput}))
assert.Empty(t, CoerceList(nil))

}
8 changes: 4 additions & 4 deletions graphql/handler/extension/complexity.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,17 +59,17 @@ func (c *ComplexityLimit) Validate(schema graphql.ExecutableSchema) error {

func (c ComplexityLimit) MutateOperationContext(ctx context.Context, rc *graphql.OperationContext) *gqlerror.Error {
op := rc.Doc.Operations.ForName(rc.OperationName)
complexity := complexity.Calculate(c.es, op, rc.Variables)
complexityCalcs := complexity.Calculate(c.es, op, rc.Variables)

limit := c.Func(ctx, rc)

rc.Stats.SetExtension(complexityExtension, &ComplexityStats{
Complexity: complexity,
Complexity: complexityCalcs,
ComplexityLimit: limit,
})

if complexity > limit {
err := gqlerror.Errorf("operation has complexity %d, which exceeds the limit of %d", complexity, limit)
if complexityCalcs > limit {
err := gqlerror.Errorf("operation has complexity %d, which exceeds the limit of %d", complexityCalcs, limit)
errcode.Set(err, errComplexityLimit)
return err
}
Expand Down
2 changes: 1 addition & 1 deletion graphql/handler/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ func (t panicTransport) Supports(r *http.Request) bool {
return true
}

func (h panicTransport) Do(w http.ResponseWriter, r *http.Request, exec graphql.GraphExecutor) {
func (t panicTransport) Do(w http.ResponseWriter, r *http.Request, exec graphql.GraphExecutor) {
panic(fmt.Errorf("panic in transport"))
}

Expand Down
2 changes: 1 addition & 1 deletion graphql/handler/transport/sse_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ func TestSSE(t *testing.T) {
handler.SendNextSubscriptionMessage()
}()

var Client = &http.Client{}
Client := &http.Client{}
req, err := createHTTPRequest(srv.URL, `{"query":"subscription { name }"}`)
require.NoError(t, err, "Create request threw error -> %s", err)
res, err := Client.Do(req)
Expand Down
1 change: 0 additions & 1 deletion graphql/handler/transport/websocket_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,6 @@ func TestWebsocket(t *testing.T) {
} else {
assert.Contains(t, err.Error(), "timeout")
}

})
}

Expand Down
16 changes: 5 additions & 11 deletions internal/code/compare.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
)

// CompatibleTypes isnt a strict comparison, it allows for pointer differences
func CompatibleTypes(expected types.Type, actual types.Type) error {
func CompatibleTypes(expected, actual types.Type) error {
// Special case to deal with pointer mismatches
{
expectedPtr, expectedIsPtr := expected.(*types.Pointer)
Expand Down Expand Up @@ -84,11 +84,8 @@ func CompatibleTypes(expected types.Type, actual types.Type) error {
if err := CompatibleTypes(expected.Params(), actual.Params()); err != nil {
return err
}
if err := CompatibleTypes(expected.Results(), actual.Results()); err != nil {
return err
}

return nil
err := CompatibleTypes(expected.Results(), actual.Results())
return err
}
case *types.Interface:
if actual, ok := actual.(*types.Interface); ok {
Expand All @@ -114,11 +111,8 @@ func CompatibleTypes(expected types.Type, actual types.Type) error {
return err
}

if err := CompatibleTypes(expected.Elem(), actual.Elem()); err != nil {
return err
}

return nil
err := CompatibleTypes(expected.Elem(), actual.Elem())
return err
}

case *types.Chan:
Expand Down
4 changes: 2 additions & 2 deletions internal/code/imports.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ func extractModuleName(content []byte) string {
break
}
s := strings.Trim(string(tkn), " \t")
if len(s) != 0 && !strings.HasPrefix(s, "//") {
if s != "" && !strings.HasPrefix(s, "//") {
break
}
if advance <= len(content) {
Expand Down Expand Up @@ -171,4 +171,4 @@ func ImportPathForDir(dir string) (res string) {
return ""
}

var modregex = regexp.MustCompile(`module ([^\s]*)`)
var modregex = regexp.MustCompile(`module (\S*)`)
6 changes: 4 additions & 2 deletions internal/code/packages.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@ import (
"golang.org/x/tools/go/packages"
)

var once = sync.Once{}
var modInfo *debug.BuildInfo
var (
once = sync.Once{}
modInfo *debug.BuildInfo
)

var mode = packages.NeedName |
packages.NeedFiles |
Expand Down
2 changes: 1 addition & 1 deletion internal/code/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ func QualifyPackagePath(importPath string) string {
return pkg.ImportPath
}

var invalidPackageNameChar = regexp.MustCompile(`[^\w]`)
var invalidPackageNameChar = regexp.MustCompile(`\W`)

func SanitizePackageName(pkg string) string {
return invalidPackageNameChar.ReplaceAllLiteralString(filepath.Base(pkg), "_")
Expand Down
6 changes: 3 additions & 3 deletions internal/rewrite/rewriter.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ func (r *Rewriter) getFile(filename string) string {
return r.files[filename]
}

func (r *Rewriter) GetPrevDecl(structname string, methodname string) *ast.FuncDecl {
func (r *Rewriter) GetPrevDecl(structname, methodname string) *ast.FuncDecl {
for _, f := range r.pkg.Syntax {
for _, d := range f.Decls {
d, isFunc := d.(*ast.FuncDecl)
Expand Down Expand Up @@ -99,15 +99,15 @@ func (r *Rewriter) GetPrevDecl(structname string, methodname string) *ast.FuncDe
return nil
}

func (r *Rewriter) GetMethodComment(structname string, methodname string) string {
func (r *Rewriter) GetMethodComment(structname, methodname string) string {
d := r.GetPrevDecl(structname, methodname)
if d != nil {
return d.Doc.Text()
}
return ""
}

func (r *Rewriter) GetMethodBody(structname string, methodname string) string {
func (r *Rewriter) GetMethodBody(structname, methodname string) string {
d := r.GetPrevDecl(structname, methodname)
if d != nil {
return r.getSource(d.Body.Pos()+1, d.Body.End()-1)
Expand Down
Loading

0 comments on commit 4a18a29

Please sign in to comment.