fix: implement various deepsource suggestions

This commit is contained in:
Vikram Rangnekar 2020-06-15 10:16:47 -04:00
parent 06214a3850
commit dd4accfdd2
26 changed files with 76 additions and 86 deletions

View File

@ -139,7 +139,7 @@ func newSuperGraph(conf *Config, db *sql.DB, dbinfo *psql.DBInfo) (*SuperGraph,
return nil, err return nil, err
} }
if len(conf.SecretKey) != 0 { if conf.SecretKey != "" {
sk := sha256.Sum256([]byte(conf.SecretKey)) sk := sha256.Sum256([]byte(conf.SecretKey))
conf.SecretKey = "" conf.SecretKey = ""
sg.encKey = sk sg.encKey = sk

View File

@ -82,7 +82,7 @@ func (sg *SuperGraph) buildMultiStmt(query, vars []byte) ([]stmt, error) {
} }
} }
if len(sg.conf.RolesQuery) == 0 { if sg.conf.RolesQuery == "" {
return nil, errors.New("roles_query not defined") return nil, errors.New("roles_query not defined")
} }
@ -133,7 +133,7 @@ func (sg *SuperGraph) renderUserQuery(md psql.Metadata, stmts []stmt) (string, e
io.WriteString(w, `SELECT "_sg_auth_info"."role", (CASE "_sg_auth_info"."role" `) io.WriteString(w, `SELECT "_sg_auth_info"."role", (CASE "_sg_auth_info"."role" `)
for _, s := range stmts { for _, s := range stmts {
if len(s.role.Match) == 0 && if s.role.Match == "" &&
s.role.Name != "user" && s.role.Name != "anon" { s.role.Name != "user" && s.role.Name != "anon" {
continue continue
} }
@ -150,7 +150,7 @@ func (sg *SuperGraph) renderUserQuery(md psql.Metadata, stmts []stmt) (string, e
io.WriteString(w, `(SELECT (CASE`) io.WriteString(w, `(SELECT (CASE`)
for _, s := range stmts { for _, s := range stmts {
if len(s.role.Match) == 0 { if s.role.Match == "" {
continue continue
} }
io.WriteString(w, ` WHEN `) io.WriteString(w, ` WHEN `)

View File

@ -152,7 +152,7 @@ type Delete struct {
// AddRoleTable function is a helper function to make it easy to add per-table // AddRoleTable function is a helper function to make it easy to add per-table
// row-level config // row-level config
func (c *Config) AddRoleTable(role string, table string, conf interface{}) error { func (c *Config) AddRoleTable(role, table string, conf interface{}) error {
var r *Role var r *Role
for i := range c.Roles { for i := range c.Roles {

View File

@ -305,7 +305,7 @@ func (c *scontext) resolveSQL() ([]byte, *stmt, error) {
err = row.Scan(&root) err = row.Scan(&root)
} }
if len(role) == 0 { if role == "" {
c.res.role = c.role c.res.role = c.role
} else { } else {
c.res.role = role c.res.role = role

View File

@ -146,7 +146,7 @@ func (al *List) Load() ([]Item, error) {
return parse(string(b), al.filepath) return parse(string(b), al.filepath)
} }
func parse(b string, filename string) ([]Item, error) { func parse(b, filename string) ([]Item, error) {
var items []Item var items []Item
var s scanner.Scanner var s scanner.Scanner

View File

@ -14,7 +14,7 @@ func TestGQLName1(t *testing.T) {
name := QueryName(q) name := QueryName(q)
if len(name) != 0 { if name != "" {
t.Fatal("Name should be empty, not ", name) t.Fatal("Name should be empty, not ", name)
} }
} }

View File

@ -774,7 +774,7 @@ func (c *compilerContext) renderBaseSelect(sel *qcode.Select, ti *DBTableInfo, r
case ti.IsSingular: case ti.IsSingular:
io.WriteString(c.w, ` LIMIT ('1') :: integer`) io.WriteString(c.w, ` LIMIT ('1') :: integer`)
case len(sel.Paging.Limit) != 0: case sel.Paging.Limit != "":
//fmt.Fprintf(w, ` LIMIT ('%s') :: integer`, c.sel.Paging.Limit) //fmt.Fprintf(w, ` LIMIT ('%s') :: integer`, c.sel.Paging.Limit)
io.WriteString(c.w, ` LIMIT ('`) io.WriteString(c.w, ` LIMIT ('`)
io.WriteString(c.w, sel.Paging.Limit) io.WriteString(c.w, sel.Paging.Limit)
@ -787,7 +787,7 @@ func (c *compilerContext) renderBaseSelect(sel *qcode.Select, ti *DBTableInfo, r
io.WriteString(c.w, ` LIMIT ('20') :: integer`) io.WriteString(c.w, ` LIMIT ('20') :: integer`)
} }
if len(sel.Paging.Offset) != 0 { if sel.Paging.Offset != "" {
//fmt.Fprintf(w, ` OFFSET ('%s') :: integer`, c.sel.Paging.Offset) //fmt.Fprintf(w, ` OFFSET ('%s') :: integer`, c.sel.Paging.Offset)
io.WriteString(c.w, ` OFFSET ('`) io.WriteString(c.w, ` OFFSET ('`)
io.WriteString(c.w, sel.Paging.Offset) io.WriteString(c.w, sel.Paging.Offset)
@ -1011,13 +1011,10 @@ func (c *compilerContext) renderExp(ex *qcode.Exp, ti *DBTableInfo, skipNested b
return err return err
} }
} else { } else if err := c.renderOp(val, ti); err != nil {
//fmt.Fprintf(w, `(("%s"."%s") `, c.sel.Name, val.Col)
if err := c.renderOp(val, ti); err != nil {
return err return err
} }
} }
}
//qcode.FreeExp(val) //qcode.FreeExp(val)
default: default:
@ -1077,7 +1074,7 @@ func (c *compilerContext) renderOp(ex *qcode.Exp, ti *DBTableInfo) error {
return nil return nil
} }
if len(ex.Col) != 0 { if ex.Col != "" {
if col, ok = ti.ColMap[ex.Col]; !ok { if col, ok = ti.ColMap[ex.Col]; !ok {
return fmt.Errorf("no column '%s' found ", ex.Col) return fmt.Errorf("no column '%s' found ", ex.Col)
} }
@ -1317,7 +1314,7 @@ func funcPrefixLen(fm map[string]*DBFunction, fn string) int {
return 0 return 0
} }
func hasBit(n uint32, pos uint32) bool { func hasBit(n, pos uint32) bool {
val := n & (1 << pos) val := n & (1 << pos)
return (val > 0) return (val > 0)
} }

View File

@ -381,25 +381,25 @@ func withFragment3(t *testing.T) {
compileGQLToPSQL(t, gql, nil, "anon") compileGQLToPSQL(t, gql, nil, "anon")
} }
func withInlineFragment(t *testing.T) { // func withInlineFragment(t *testing.T) {
gql := ` // gql := `
query { // query {
users { // users {
... on users { // ... on users {
id // id
email // email
} // }
created_at // created_at
... on user { // ... on user {
first_name // first_name
last_name // last_name
} // }
} // }
} // }
` // `
compileGQLToPSQL(t, gql, nil, "anon") // compileGQLToPSQL(t, gql, nil, "anon")
} // }
func withCursor(t *testing.T) { func withCursor(t *testing.T) {
gql := `query { gql := `query {

View File

@ -328,7 +328,7 @@ func (s *DBSchema) secondDegreeRels(t DBTable, cols []DBColumn) error {
for i := range cols { for i := range cols {
c := cols[i] c := cols[i]
if len(c.FKeyTable) == 0 { if c.FKeyTable == "" {
continue continue
} }

View File

@ -121,14 +121,12 @@ func (c *compilerContext) renderUpdateStmt(w io.Writer, qc *qcode.QCode, item re
} }
io.WriteString(w, `)`) io.WriteString(w, `)`)
} else { } else if qc.Selects[0].Where != nil {
if qc.Selects[0].Where != nil {
io.WriteString(w, `WHERE `) io.WriteString(w, `WHERE `)
if err := c.renderWhere(&qc.Selects[0], ti); err != nil { if err := c.renderWhere(&qc.Selects[0], ti); err != nil {
return err return err
} }
} }
}
io.WriteString(w, ` RETURNING `) io.WriteString(w, ` RETURNING `)
quoted(w, ti.Name) quoted(w, ti.Name)

View File

@ -141,8 +141,7 @@ func (l *lexer) current() (Pos, Pos) {
func (l *lexer) emit(t itemType) { func (l *lexer) emit(t itemType) {
l.items = append(l.items, item{t, l.start, l.pos, l.line}) l.items = append(l.items, item{t, l.start, l.pos, l.line})
// Some items contain text internally. If so, count their newlines. // Some items contain text internally. If so, count their newlines.
switch t { if t == itemStringVal {
case itemStringVal:
for i := l.start; i < l.pos; i++ { for i := l.start; i < l.pos; i++ {
if l.input[i] == '\n' { if l.input[i] == '\n' {
l.line++ l.line++
@ -404,15 +403,15 @@ func isAlphaNumeric(r rune) bool {
return r == '_' || unicode.IsLetter(r) || unicode.IsDigit(r) return r == '_' || unicode.IsLetter(r) || unicode.IsDigit(r)
} }
func equals(b []byte, s Pos, e Pos, val []byte) bool { func equals(b []byte, s, e Pos, val []byte) bool {
return bytes.EqualFold(b[s:e], val) return bytes.EqualFold(b[s:e], val)
} }
func contains(b []byte, s Pos, e Pos, chars string) bool { func contains(b []byte, s, e Pos, chars string) bool {
return bytes.ContainsAny(b[s:e], chars) return bytes.ContainsAny(b[s:e], chars)
} }
func lowercase(b []byte, s Pos, e Pos) { func lowercase(b []byte, s, e Pos) {
for i := s; i < e; i++ { for i := s; i < e; i++ {
if b[i] >= 'A' && b[i] <= 'Z' { if b[i] >= 'A' && b[i] <= 'Z' {
b[i] = ('a' + (b[i] - 'A')) b[i] = ('a' + (b[i] - 'A'))

View File

@ -574,11 +574,9 @@ func (p *Parser) parseList() (*Node, error) {
} }
if ty == 0 { if ty == 0 {
ty = node.Type ty = node.Type
} else { } else if ty != node.Type {
if ty != node.Type {
return nil, errors.New("All values in a list must be of the same type") return nil, errors.New("All values in a list must be of the same type")
} }
}
node.Parent = parent node.Parent = parent
nodes = append(nodes, node) nodes = append(nodes, node)
} }

View File

@ -386,7 +386,7 @@ func (com *Compiler) compileQuery(qc *QCode, op *Operation, role string) error {
s.Type = STUnion s.Type = STUnion
} }
if len(field.Alias) != 0 { if field.Alias != "" {
s.FieldName = field.Alias s.FieldName = field.Alias
} else { } else {
s.FieldName = s.Name s.FieldName = s.Name
@ -628,15 +628,13 @@ func (com *Compiler) compileArgNode(st *util.Stack, node *Node, usePool bool) (*
} }
// Objects inside a list // Objects inside a list
if len(node.Name) == 0 { if node.Name == "" {
pushChildren(st, node.exp, node) pushChildren(st, node.exp, node)
continue continue
} else { } else if _, ok := com.bl[node.Name]; ok {
if _, ok := com.bl[node.Name]; ok {
continue continue
} }
}
ex, err := newExp(st, node, usePool) ex, err := newExp(st, node, usePool)
if err != nil { if err != nil {
@ -1049,7 +1047,7 @@ func setWhereColName(ex *Exp, node *Node) {
if n.Type != NodeObj { if n.Type != NodeObj {
continue continue
} }
if len(n.Name) != 0 { if n.Name != "" {
k := n.Name k := n.Name
if k == "and" || k == "or" || k == "not" || if k == "and" || k == "or" || k == "not" ||
k == "_and" || k == "_or" || k == "_not" { k == "_and" || k == "_or" || k == "_not" {

View File

@ -75,7 +75,7 @@ func (sg *SuperGraph) initPrepared() error {
h.SetSeed(sg.hashSeed) h.SetSeed(sg.hashSeed)
for _, v := range list { for _, v := range list {
if len(v.Query) == 0 { if v.Query == "" {
continue continue
} }
@ -113,7 +113,7 @@ func (sg *SuperGraph) prepareRoleStmt() error {
io.WriteString(w, `(SELECT (CASE`) io.WriteString(w, `(SELECT (CASE`)
for _, role := range sg.conf.Roles { for _, role := range sg.conf.Roles {
if len(role.Match) == 0 { if role.Match == "" {
continue continue
} }
io.WriteString(w, ` WHEN `) io.WriteString(w, ` WHEN `)
@ -159,7 +159,7 @@ func (sg *SuperGraph) initAllowList() error {
} }
// nolint: errcheck // nolint: errcheck
func queryID(h *maphash.Hash, name string, role string) uint64 { func queryID(h *maphash.Hash, name, role string) uint64 {
h.WriteString(name) h.WriteString(name)
h.WriteString(role) h.WriteString(role)
v := h.Sum64() v := h.Sum64()

View File

@ -238,7 +238,7 @@ func (sg *SuperGraph) parentFieldIds(h *maphash.Hash, sel []qcode.Select, skippe
return fm, sm return fm, sm
} }
func isSkipped(n uint32, pos uint32) bool { func isSkipped(n, pos uint32) bool {
return ((n & (1 << pos)) != 0) return ((n & (1 << pos)) != 0)
} }

View File

@ -46,7 +46,7 @@ func (sg *SuperGraph) initRemotes(t Table) error {
// if no table column specified in the config then // if no table column specified in the config then
// use the primary key of the table as the id // use the primary key of the table as the id
if len(idcol) == 0 { if idcol == "" {
pcol, err := sg.pc.IDColumn(t.Name) pcol, err := sg.pc.IDColumn(t.Name)
if err != nil { if err != nil {
return err return err

View File

@ -3,7 +3,7 @@ package core
import "hash/maphash" import "hash/maphash"
// nolint: errcheck // nolint: errcheck
func mkkey(h *maphash.Hash, k1 string, k2 string) uint64 { func mkkey(h *maphash.Hash, k1, k2 string) uint64 {
h.WriteString(k1) h.WriteString(k1)
h.WriteString(k2) h.WriteString(k2)
v := h.Sum64() v := h.Sum64()

View File

@ -155,7 +155,7 @@ func cmdVersion(cmd *cobra.Command, args []string) {
} }
func BuildDetails() string { func BuildDetails() string {
if len(version) == 0 { if version == "" {
return ` return `
Super Graph (unknown version) Super Graph (unknown version)
For documentation, visit https://supergraph.dev For documentation, visit https://supergraph.dev

View File

@ -80,7 +80,7 @@ func cmdDBSeed(cmd *cobra.Command, args []string) {
func graphQLFunc(sg *core.SuperGraph, query string, data interface{}, opt map[string]string) map[string]interface{} { func graphQLFunc(sg *core.SuperGraph, query string, data interface{}, opt map[string]string) map[string]interface{} {
ct := context.Background() ct := context.Background()
if v, ok := opt["user_id"]; ok && len(v) != 0 { if v, ok := opt["user_id"]; ok && v != "" {
ct = context.WithValue(ct, core.UserIDKey, v) ct = context.WithValue(ct, core.UserIDKey, v)
} }
@ -144,7 +144,7 @@ func (c *csvSource) Values() ([]interface{}, error) {
for _, v := range c.rows[c.i] { for _, v := range c.rows[c.i] {
switch { switch {
case len(v) == 0: case v == "":
vals = append(vals, "") vals = append(vals, "")
case isDigit(v): case isDigit(v):
var n int var n int
@ -243,7 +243,7 @@ func avatarURL(size int) string {
return fmt.Sprintf("https://i.pravatar.cc/%d?%d", size, rand.Intn(5000)) return fmt.Sprintf("https://i.pravatar.cc/%d?%d", size, rand.Intn(5000))
} }
func imageURL(width int, height int) string { func imageURL(width, height int) string {
return fmt.Sprintf("https://picsum.photos/%d/%d?%d", width, height, rand.Intn(5000)) return fmt.Sprintf("https://picsum.photos/%d/%d?%d", width, height, rand.Intn(5000))
} }

View File

@ -90,7 +90,7 @@ func newViper(configPath, configFile string) *viper.Viper {
} }
func GetConfigName() string { func GetConfigName() string {
if len(os.Getenv("GO_ENV")) == 0 { if os.Getenv("GO_ENV") == "" {
return "dev" return "dev"
} }

View File

@ -105,7 +105,7 @@ func apiV1(w http.ResponseWriter, r *http.Request) {
} }
if err == nil { if err == nil {
if len(conf.CacheControl) != 0 && res.Operation() == core.OpQuery { if conf.CacheControl != "" && res.Operation() == core.OpQuery {
w.Header().Set("Cache-Control", conf.CacheControl) w.Header().Set("Cache-Control", conf.CacheControl)
} }
//nolint: errcheck //nolint: errcheck

View File

@ -47,17 +47,17 @@ func SimpleHandler(ac *Auth, next http.Handler) (http.HandlerFunc, error) {
ctx := r.Context() ctx := r.Context()
userIDProvider := r.Header.Get("X-User-ID-Provider") userIDProvider := r.Header.Get("X-User-ID-Provider")
if len(userIDProvider) != 0 { if userIDProvider != "" {
ctx = context.WithValue(ctx, core.UserIDProviderKey, userIDProvider) ctx = context.WithValue(ctx, core.UserIDProviderKey, userIDProvider)
} }
userID := r.Header.Get("X-User-ID") userID := r.Header.Get("X-User-ID")
if len(userID) != 0 { if userID != "" {
ctx = context.WithValue(ctx, core.UserIDKey, userID) ctx = context.WithValue(ctx, core.UserIDKey, userID)
} }
userRole := r.Header.Get("X-User-Role") userRole := r.Header.Get("X-User-Role")
if len(userRole) != 0 { if userRole != "" {
ctx = context.WithValue(ctx, core.UserRoleKey, userRole) ctx = context.WithValue(ctx, core.UserRoleKey, userRole)
} }
@ -68,11 +68,11 @@ func SimpleHandler(ac *Auth, next http.Handler) (http.HandlerFunc, error) {
func HeaderHandler(ac *Auth, next http.Handler) (http.HandlerFunc, error) { func HeaderHandler(ac *Auth, next http.Handler) (http.HandlerFunc, error) {
hdr := ac.Header hdr := ac.Header
if len(hdr.Name) == 0 { if hdr.Name == "" {
return nil, fmt.Errorf("auth '%s': no header.name defined", ac.Name) return nil, fmt.Errorf("auth '%s': no header.name defined", ac.Name)
} }
if !hdr.Exists && len(hdr.Value) == 0 { if !hdr.Exists && hdr.Value == "" {
return nil, fmt.Errorf("auth '%s': no header.value defined", ac.Name) return nil, fmt.Errorf("auth '%s': no header.value defined", ac.Name)
} }
@ -82,7 +82,7 @@ func HeaderHandler(ac *Auth, next http.Handler) (http.HandlerFunc, error) {
switch { switch {
case hdr.Exists: case hdr.Exists:
fo1 = (len(value) == 0) fo1 = (value == "")
default: default:
fo1 = (value != hdr.Value) fo1 = (value != hdr.Value)

View File

@ -44,10 +44,10 @@ func JwtHandler(ac *Auth, next http.Handler) (http.HandlerFunc, error) {
publicKeyFile := ac.JWT.PubKeyFile publicKeyFile := ac.JWT.PubKeyFile
switch { switch {
case len(secret) != 0: case secret != "":
key = []byte(secret) key = []byte(secret)
case len(publicKeyFile) != 0: case publicKeyFile != "":
kd, err := ioutil.ReadFile(publicKeyFile) kd, err := ioutil.ReadFile(publicKeyFile)
if err != nil { if err != nil {
return nil, err return nil, err
@ -74,7 +74,7 @@ func JwtHandler(ac *Auth, next http.Handler) (http.HandlerFunc, error) {
var tok string var tok string
if len(cookie) != 0 { if cookie != "" {
ck, err := r.Cookie(cookie) ck, err := r.Cookie(cookie)
if err != nil { if err != nil {
next.ServeHTTP(w, r) next.ServeHTTP(w, r)

View File

@ -165,7 +165,7 @@ func railsAuth(ac *Auth) (*rails.Auth, error) {
} }
version := ac.Rails.Version version := ac.Rails.Version
if len(version) == 0 { if version == "" {
return nil, errors.New("no auth.rails.version defined") return nil, errors.New("no auth.rails.version defined")
} }

View File

@ -199,7 +199,7 @@ func (m *Migrator) LoadMigrations(path string) error {
for _, v := range strings.Split(upSQL, "\n") { for _, v := range strings.Split(upSQL, "\n") {
// Only account for regular single line comment, empty line and space/comment combination // Only account for regular single line comment, empty line and space/comment combination
cleanString := strings.TrimSpace(v) cleanString := strings.TrimSpace(v)
if len(cleanString) != 0 && if cleanString != "" &&
!strings.HasPrefix(cleanString, "--") { !strings.HasPrefix(cleanString, "--") {
containsSQL = true containsSQL = true
break break

View File

@ -27,7 +27,7 @@ func initWatcher() {
} }
var d dir var d dir
if len(cpath) == 0 || cpath == "./" { if cpath == "" || cpath == "./" {
d = Dir("./config", ReExec) d = Dir("./config", ReExec)
} else { } else {
d = Dir(cpath, ReExec) d = Dir(cpath, ReExec)
@ -52,11 +52,11 @@ func startHTTP() {
hp := strings.SplitN(conf.HostPort, ":", 2) hp := strings.SplitN(conf.HostPort, ":", 2)
if len(hp) == 2 { if len(hp) == 2 {
if len(conf.Host) != 0 { if conf.Host != "" {
hp[0] = conf.Host hp[0] = conf.Host
} }
if len(conf.Port) != 0 { if conf.Port != "" {
hp[1] = conf.Port hp[1] = conf.Port
} }
@ -64,7 +64,7 @@ func startHTTP() {
} }
} }
if len(conf.hostPort) == 0 { if conf.hostPort == "" {
conf.hostPort = defaultHP conf.hostPort = defaultHP
} }
@ -123,7 +123,7 @@ func routeHandler() (http.Handler, error) {
return mux, nil return mux, nil
} }
if len(conf.APIPath) != 0 { if conf.APIPath != "" {
apiRoute = path.Join("/", conf.APIPath, "/v1/graphql") apiRoute = path.Join("/", conf.APIPath, "/v1/graphql")
} }