fix staticcheck issues (#16828)

Fix the staticcheck problems that reported by golangci-line staticcheck

Signed-off-by: Wang Yan <wangyan@vmware.com>
This commit is contained in:
Wang Yan 2022-05-10 16:07:10 +08:00 committed by GitHub
parent 27ec871185
commit d3d4ad6a34
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
18 changed files with 33 additions and 25 deletions

View File

@ -127,7 +127,6 @@ func (c *Client) Post(url string, v ...interface{}) error {
func (c *Client) Put(url string, v ...interface{}) error {
var reader io.Reader
if len(v) > 0 {
data := []byte{}
data, err := json.Marshal(v[0])
if err != nil {
return err

View File

@ -41,6 +41,8 @@ import (
proModels "github.com/goharbor/harbor/src/pkg/project/models"
"github.com/goharbor/harbor/src/pkg/scan/vuln"
"github.com/goharbor/harbor/src/pkg/task"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
func init() {
@ -625,7 +627,8 @@ func overrideSecuritySettings(p *pol.Schema, pro *proModels.Project) [][]interfa
// Append vulnerability filter if vulnerability severity config is set at project configurations
if v, ok := pro.Metadata[proMetaKeyVulnerability]; ok && v == "true" {
if se, ok := pro.Metadata[proMetaKeySeverity]; ok && len(se) > 0 {
se = strings.Title(strings.ToLower(se))
title := cases.Title(language.Und)
se = title.String(strings.ToLower(se))
code := vuln.Severity(se).Code()
filters = append(filters, &pol.Filter{
Type: pol.FilterTypeVulnerability,

View File

@ -159,6 +159,10 @@ func (oc *OIDCController) Callback() {
return
}
_, t, err := secretAndToken(tokenBytes)
if err != nil {
oc.SendInternalServerError(err)
return
}
oidcUser := um.OIDCUserMeta
oidcUser.Token = t
if err := ctluser.Ctl.UpdateOIDCMeta(ctx, oidcUser); err != nil {

View File

@ -17,6 +17,7 @@ package hook
import (
"context"
"encoding/json"
"github.com/goharbor/harbor/src/lib/log"
"net/url"
"time"
@ -244,6 +245,7 @@ func (ba *basicAgent) isOutdated(evt *Event) (bool, error) {
case st.After(est):
return true, nil
case st.Equal(est):
log.Debugf("ignore the consistent status: %v", est)
// Continue to compare check in at timestamp
}

View File

@ -402,14 +402,12 @@ func (gc *GarbageCollector) deletedArt(ctx job.Context) (map[string][]model.Arti
// allTrashedArts contains the artifacts that actual removed and simulate removed(for dry run).
allTrashedArts := make([]model.ArtifactTrash, 0)
untaggedArts := make([]*artifact.Artifact, 0)
var err error
// artMap : map[digest : []ArtifactTrash list]
artMap := make(map[string][]model.ArtifactTrash)
// handle the optional ones, and the artifact controller will move them into trash.
if gc.deleteUntagged {
untaggedArts, err = gc.artCtl.List(ctx.SystemContext(), &q.Query{
untaggedArts, err := gc.artCtl.List(ctx.SystemContext(), &q.Query{
Keywords: map[string]interface{}{
"Tags": "nil",
},

View File

@ -231,14 +231,17 @@ func (bt *basicTracker) CheckIn(message string) error {
current := Status(bt.jobStats.Info.Status)
bt.refresh(current, message)
err := bt.fireHookEvent(current, message)
err = bt.Update(
errFireHE := bt.fireHookEvent(current, message)
err := bt.Update(
// skip checkin data here
"check_in_at", now,
"update_time", now,
)
if err != nil {
return errors.Wrap(err, errFireHE.Error())
}
return err
return nil
}
// Run job

View File

@ -219,7 +219,7 @@ func (bs *Bootstrap) LoadAndRun(ctx context.Context, cancel context.CancelFunc)
// Listen to the system signals
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt, syscall.SIGTERM, os.Kill)
signal.Notify(sig, os.Interrupt, syscall.SIGTERM)
terminated := false
go func(errChan chan error) {
defer func() {

View File

@ -173,7 +173,7 @@ func OIDCSetting(ctx context.Context) (*cfgModels.OIDCSetting, error) {
return nil, err
}
scopeStr := mgr.Get(ctx, common.OIDCScope).GetString()
extEndpoint := strings.TrimSuffix(mgr.Get(nil, common.ExtEndpoint).GetString(), "/")
extEndpoint := strings.TrimSuffix(mgr.Get(context.Background(), common.ExtEndpoint).GetString(), "/")
scope := SplitAndTrim(scopeStr, ",")
return &cfgModels.OIDCSetting{
Name: mgr.Get(ctx, common.OIDCName).GetString(),

View File

@ -130,8 +130,6 @@ func New(in interface{}) *Error {
switch in := in.(type) {
case error:
err = in
case *Error:
err = in.Cause
default:
err = fmt.Errorf("%v", in)
}

View File

@ -81,7 +81,7 @@ func GetRedisPool(name string, rawurl string, param *PoolParam) (*redis.Pool, er
knownPool.Store(name, pool)
return pool, nil
} else if u.Scheme == "redis+sentinel" {
pool, err := getSentinelPool(u, param, err, name)
pool, err := getSentinelPool(u, param, name)
if err != nil {
return nil, err
}
@ -92,7 +92,7 @@ func GetRedisPool(name string, rawurl string, param *PoolParam) (*redis.Pool, er
}
}
func getSentinelPool(u *url.URL, param *PoolParam, err error, name string) (*redis.Pool, error) {
func getSentinelPool(u *url.URL, param *PoolParam, name string) (*redis.Pool, error) {
ps := strings.Split(u.Path, "/")
if len(ps) < 2 {
return nil, fmt.Errorf("bad redis sentinel url: no master name, %s %s", name, u)
@ -126,7 +126,7 @@ func getSentinelPool(u *url.URL, param *PoolParam, err error, name string) (*red
// sentinel doesn't need select db
db := 0
if len(ps) > 2 {
db, err = strconv.Atoi(ps[2])
db, err := strconv.Atoi(ps[2])
if err != nil {
return nil, fmt.Errorf("invalid redis db: %s, %s", ps[1], name)
}

View File

@ -70,7 +70,7 @@ func (a *aliyunAuthCredential) Modify(r *http.Request) (err error) {
}
func (a *aliyunAuthCredential) isCacheTokenValid() bool {
if &a.cacheTokenExpiredAt == nil {
if a.cacheTokenExpiredAt.IsZero() {
return false
}
if a.cacheToken == nil {

View File

@ -47,7 +47,7 @@ func (a *authorizer) Modify(req *http.Request) error {
// resume path
req.URL.Path = oldPath
}()
req.URL.Path = strings.TrimRight(req.URL.Path, "_catalog")
req.URL.Path = strings.TrimSuffix(req.URL.Path, "_catalog")
}
return a.innerAuthorizer.Modify(req)

View File

@ -219,7 +219,6 @@ func (a *adapter) PrepareForPush(resources []*model.Resource) (err error) {
if err != nil {
return
}
return
}
return

View File

@ -29,7 +29,7 @@ func (q *qcloudAuthCredential) Modify(r *http.Request) (err error) {
}
func (q *qcloudAuthCredential) isCacheTokenValid() (ok bool) {
if &q.cacheTokenExpiredAt == nil {
if q.cacheTokenExpiredAt.IsZero() {
return
}
if q.cacheTokener == nil {

View File

@ -91,7 +91,7 @@ func (a *artifactTypeFilter) Filter(artifacts []*model.Artifact) ([]*model.Artif
var result []*model.Artifact
for _, artifact := range artifacts {
for _, t := range a.types {
if strings.ToLower(artifact.Type) == strings.ToLower(t) {
if strings.EqualFold(strings.ToLower(artifact.Type), strings.ToLower(t)) {
result = append(result, artifact)
continue
}

View File

@ -128,7 +128,7 @@ func (bcp *basicClientPool) deadCheck(key string, item *poolItem) {
// As we do not have a global context, let's watch the system signal to
// exit the goroutine correctly.
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt, syscall.SIGTERM, os.Kill)
signal.Notify(sig, os.Interrupt, syscall.SIGTERM)
tk := time.NewTicker(bcp.config.DeadCheckInterval)
defer tk.Stop()

View File

@ -15,7 +15,8 @@
package vuln
import (
"strings"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
const (
@ -73,7 +74,8 @@ func (s Severity) String() string {
// ParseSeverityVersion3 returns severity of CVSS v3.0 Ratings
func ParseSeverityVersion3(str string) Severity {
severity := Severity(strings.Title(str))
title := cases.Title(language.Und)
severity := Severity(title.String(str))
// There are `None`, `Low`, `Medium`, `High` and `Critical` severity rankings in CVSS v3.0 Ratings,
// so map `negligible` severity to `none`

View File

@ -64,7 +64,7 @@ func parseRepositoryName(p string) string {
return strings.TrimSuffix(parts[1], "/artifacts")
}
func copyArtifactResources(r *http.Request, reference, referenceID string) (types.ResourceList, error) {
func copyArtifactResources(r *http.Request, _, referenceID string) (types.ResourceList, error) {
query := r.URL.Query()
from := query.Get("from")
if from == "" {
@ -132,7 +132,7 @@ func copyArtifactResources(r *http.Request, reference, referenceID string) (type
}
func copyArtifactResourcesEvent(level int) func(*http.Request, string, string, string) event.Metadata {
return func(r *http.Request, reference, referenceID string, message string) event.Metadata {
return func(r *http.Request, _, referenceID string, message string) event.Metadata {
ctx := r.Context()
logger := log.G(ctx).WithFields(log.Fields{"middleware": "quota", "action": "request", "url": r.URL.Path})