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
}
if len(conf.SecretKey) != 0 {
if conf.SecretKey != "" {
sk := sha256.Sum256([]byte(conf.SecretKey))
conf.SecretKey = ""
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")
}
@ -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" `)
for _, s := range stmts {
if len(s.role.Match) == 0 &&
if s.role.Match == "" &&
s.role.Name != "user" && s.role.Name != "anon" {
continue
}
@ -150,7 +150,7 @@ func (sg *SuperGraph) renderUserQuery(md psql.Metadata, stmts []stmt) (string, e
io.WriteString(w, `(SELECT (CASE`)
for _, s := range stmts {
if len(s.role.Match) == 0 {
if s.role.Match == "" {
continue
}
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
// 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
for i := range c.Roles {

View File

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

View File

@ -146,7 +146,7 @@ func (al *List) Load() ([]Item, error) {
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 s scanner.Scanner

View File

@ -14,7 +14,7 @@ func TestGQLName1(t *testing.T) {
name := QueryName(q)
if len(name) != 0 {
if 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:
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)
io.WriteString(c.w, ` 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`)
}
if len(sel.Paging.Offset) != 0 {
if sel.Paging.Offset != "" {
//fmt.Fprintf(w, ` OFFSET ('%s') :: integer`, c.sel.Paging.Offset)
io.WriteString(c.w, ` 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
}
} else {
//fmt.Fprintf(w, `(("%s"."%s") `, c.sel.Name, val.Col)
if err := c.renderOp(val, ti); err != nil {
} else if err := c.renderOp(val, ti); err != nil {
return err
}
}
}
//qcode.FreeExp(val)
default:
@ -1077,7 +1074,7 @@ func (c *compilerContext) renderOp(ex *qcode.Exp, ti *DBTableInfo) error {
return nil
}
if len(ex.Col) != 0 {
if ex.Col != "" {
if col, ok = ti.ColMap[ex.Col]; !ok {
return fmt.Errorf("no column '%s' found ", ex.Col)
}
@ -1317,7 +1314,7 @@ func funcPrefixLen(fm map[string]*DBFunction, fn string) int {
return 0
}
func hasBit(n uint32, pos uint32) bool {
func hasBit(n, pos uint32) bool {
val := n & (1 << pos)
return (val > 0)
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -386,7 +386,7 @@ func (com *Compiler) compileQuery(qc *QCode, op *Operation, role string) error {
s.Type = STUnion
}
if len(field.Alias) != 0 {
if field.Alias != "" {
s.FieldName = field.Alias
} else {
s.FieldName = s.Name
@ -628,15 +628,13 @@ func (com *Compiler) compileArgNode(st *util.Stack, node *Node, usePool bool) (*
}
// Objects inside a list
if len(node.Name) == 0 {
if node.Name == "" {
pushChildren(st, node.exp, node)
continue
} else {
if _, ok := com.bl[node.Name]; ok {
} else if _, ok := com.bl[node.Name]; ok {
continue
}
}
ex, err := newExp(st, node, usePool)
if err != nil {
@ -1049,7 +1047,7 @@ func setWhereColName(ex *Exp, node *Node) {
if n.Type != NodeObj {
continue
}
if len(n.Name) != 0 {
if n.Name != "" {
k := n.Name
if 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)
for _, v := range list {
if len(v.Query) == 0 {
if v.Query == "" {
continue
}
@ -113,7 +113,7 @@ func (sg *SuperGraph) prepareRoleStmt() error {
io.WriteString(w, `(SELECT (CASE`)
for _, role := range sg.conf.Roles {
if len(role.Match) == 0 {
if role.Match == "" {
continue
}
io.WriteString(w, ` WHEN `)
@ -159,7 +159,7 @@ func (sg *SuperGraph) initAllowList() error {
}
// 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(role)
v := h.Sum64()

View File

@ -238,7 +238,7 @@ func (sg *SuperGraph) parentFieldIds(h *maphash.Hash, sel []qcode.Select, skippe
return fm, sm
}
func isSkipped(n uint32, pos uint32) bool {
func isSkipped(n, pos uint32) bool {
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
// use the primary key of the table as the id
if len(idcol) == 0 {
if idcol == "" {
pcol, err := sg.pc.IDColumn(t.Name)
if err != nil {
return err

View File

@ -3,7 +3,7 @@ package core
import "hash/maphash"
// 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(k2)
v := h.Sum64()

View File

@ -155,7 +155,7 @@ func cmdVersion(cmd *cobra.Command, args []string) {
}
func BuildDetails() string {
if len(version) == 0 {
if version == "" {
return `
Super Graph (unknown version)
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{} {
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)
}
@ -144,7 +144,7 @@ func (c *csvSource) Values() ([]interface{}, error) {
for _, v := range c.rows[c.i] {
switch {
case len(v) == 0:
case v == "":
vals = append(vals, "")
case isDigit(v):
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))
}
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))
}

View File

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

View File

@ -105,7 +105,7 @@ func apiV1(w http.ResponseWriter, r *http.Request) {
}
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)
}
//nolint: errcheck

View File

@ -47,17 +47,17 @@ func SimpleHandler(ac *Auth, next http.Handler) (http.HandlerFunc, error) {
ctx := r.Context()
userIDProvider := r.Header.Get("X-User-ID-Provider")
if len(userIDProvider) != 0 {
if userIDProvider != "" {
ctx = context.WithValue(ctx, core.UserIDProviderKey, userIDProvider)
}
userID := r.Header.Get("X-User-ID")
if len(userID) != 0 {
if userID != "" {
ctx = context.WithValue(ctx, core.UserIDKey, userID)
}
userRole := r.Header.Get("X-User-Role")
if len(userRole) != 0 {
if 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) {
hdr := ac.Header
if len(hdr.Name) == 0 {
if hdr.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)
}
@ -82,7 +82,7 @@ func HeaderHandler(ac *Auth, next http.Handler) (http.HandlerFunc, error) {
switch {
case hdr.Exists:
fo1 = (len(value) == 0)
fo1 = (value == "")
default:
fo1 = (value != hdr.Value)

View File

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

View File

@ -165,7 +165,7 @@ func railsAuth(ac *Auth) (*rails.Auth, error) {
}
version := ac.Rails.Version
if len(version) == 0 {
if version == "" {
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") {
// Only account for regular single line comment, empty line and space/comment combination
cleanString := strings.TrimSpace(v)
if len(cleanString) != 0 &&
if cleanString != "" &&
!strings.HasPrefix(cleanString, "--") {
containsSQL = true
break

View File

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