fix: refactor code for golangci-lint whitespace (#17005)

Signed-off-by: Shengwen Yu <yshengwen@vmware.com>
This commit is contained in:
Shengwen YU 2022-06-16 17:42:46 +08:00 committed by GitHub
parent c2a9f5de64
commit e9fca3de45
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
68 changed files with 1 additions and 86 deletions

View File

@ -26,7 +26,7 @@ linters:
# - nakedret
# - nolintlint
# - revive
# - whitespace
- whitespace
- bodyclose
- deadcode
- errcheck

View File

@ -47,7 +47,6 @@ func main() {
case <-c:
case <-time.After(30 * time.Second):
log.Fatal("Failed to connect DB after 30 seconds, time out. \n")
}
row := db.QueryRow(pgSQLCheckColStmt)
var tblCount, colCount int

View File

@ -74,7 +74,6 @@ func InitDatabase(database *models.Database) error {
}
func getDatabase(database *models.Database) (db Database, err error) {
switch database.Type {
case "", "postgresql":
db = NewPGSQL(

View File

@ -44,7 +44,6 @@ func NewMySQL(host, port, usr, pwd, database string) Database {
// Register registers MySQL as the underlying database used
func (m *mysql) Register(alias ...string) error {
if err := utils.TestTCPConn(m.host+":"+m.port, 60, 2); err != nil {
return err
}

View File

@ -117,7 +117,6 @@ func NewJobServiceServer() *httptest.Server {
panic(err)
}
return
}
}
})

View File

@ -58,7 +58,6 @@ func NewBuilderForUser(user *models.User, ctl project.Controller) RBACUserBuilde
// NewBuilderForPolicies create a builder for the policies
func NewBuilderForPolicies(username string, policies []*types.Policy,
filters ...func(*proModels.Project, []*types.Policy) []*types.Policy) RBACUserBuilder {
return func(ctx context.Context, p *proModels.Project) types.RBACUser {
for _, filter := range filters {
policies = filter(p, policies)

View File

@ -115,7 +115,6 @@ func (s *SecurityContext) Can(ctx context.Context, action types.Action, resource
evaluators = evaluators.Add(rbac_project.NewEvaluator(s.ctl, rbac_project.NewBuilderForPolicies(s.GetUsername(), proPolicies)))
}
s.evaluator = evaluators
} else {
s.evaluator = rbac_project.NewEvaluator(s.ctl, rbac_project.NewBuilderForPolicies(s.GetUsername(), accesses, filterRobotPolicies))
}

View File

@ -29,7 +29,6 @@ import (
func Send(addr, identity, username, password string,
timeout int, tls, insecure bool, from string,
to []string, subject, message string) error {
client, err := newClient(addr, identity, username,
password, timeout, tls, insecure)
if err != nil {

View File

@ -74,7 +74,6 @@ func InitDatabaseFromEnv() {
if err := updateUserInitialPassword(1, adminPwd); err != nil {
log.Fatalf("failed to init password for admin: %v", err)
}
}
func updateUserInitialPassword(userID int, password string) error {

View File

@ -49,7 +49,6 @@ func Iterator(ctx context.Context, chunkSize int, query *q.Query, option *Option
clone.PageNumber++
}
}()
return ch

View File

@ -168,7 +168,6 @@ func (c *controller) Create(ctx context.Context, projectNameOrID interface{}, re
}
member.EntityID = groupID
}
} else if len(req.MemberGroup.GroupName) > 0 {
// all group type can be added to project member by name
ugs, err := usergroup.Mgr.List(ctx, q.New(q.KeyWords{"GroupName": req.MemberGroup.GroupName, "GroupType": req.MemberGroup.GroupType}))
@ -184,7 +183,6 @@ func (c *controller) Create(ctx context.Context, projectNameOrID interface{}, re
} else {
member.EntityID = ugs[0].ID
}
}
if member.EntityID <= 0 {
return 0, fmt.Errorf("can not get valid member entity, request: %+v", req)

View File

@ -372,7 +372,6 @@ func (c *controller) UpdatePolicy(ctx context.Context, schema *policyModels.Sche
needSch = true
}
}
}
// unschedule old

View File

@ -57,7 +57,6 @@ func ListAll(ctx context.Context, chunkSize int, query *q.Query, options ...Opti
query.PageNumber++
}
}()
return ch

View File

@ -185,7 +185,6 @@ func (c *controller) UseLocalManifest(ctx context.Context, art lib.ArtifactInfo,
}
log.Debugf("Get the manifest list with key=cache:%v", manifestListKey(art.Repository, string(desc.Digest)))
return true, &ManifestList{content, string(desc.Digest), contentType}, nil
}
func manifestListKey(repo, dig string) string {

View File

@ -97,7 +97,6 @@ func (m *ManifestListCache) cacheTrimmedDigest(ctx context.Context, newDig strin
return
}
log.Debugf("Saved key:%v, value:%v", key, newDig)
}
func (m *ManifestListCache) updateManifestList(ctx context.Context, repo string, manifest distribution.Manifest) (distribution.Manifest, error) {

View File

@ -56,7 +56,6 @@ func NewRemoteHelper(ctx context.Context, regID int64) (RemoteInterface, error)
}
func (r *remoteHelper) init(ctx context.Context) error {
if r.registry != nil {
return nil
}

View File

@ -101,7 +101,6 @@ func scanTaskStatusChange(ctx context.Context, taskID int64, status string) (err
notification.AddEvent(ctx, e)
}
}
}
return nil

View File

@ -23,7 +23,6 @@ func init() {
}
func cleanupCallBack(ctx context.Context, param string) error {
err := cleanupController.Start(ctx, true, task.ExecutionTriggerSchedule)
if err != nil {
logger.Errorf("System artifact cleanup job encountered errors: %v", err)

View File

@ -109,7 +109,6 @@ func (c *controller) createCleanupTask(ctx context.Context, jobParams job.Parame
}
func (c *controller) markError(ctx context.Context, executionID int64, err error) {
// try to stop the execution first in case that some tasks are already created
if err := c.execMgr.StopAndWait(ctx, executionID, 10*time.Second); err != nil {
logger.Errorf("failed to stop the execution %d: %v", executionID, err)

View File

@ -98,7 +98,6 @@ func (c *controller) Create(ctx context.Context, group model.UserGroup) (int, er
if err != nil {
return 0, err
}
}
id, err := c.mgr.Create(ctx, group)
if err != nil && err == usergroup.ErrDupUserGroup {

View File

@ -583,7 +583,6 @@ func (cra *ChartRepositoryAPI) rewriteFileContent(files []formFile, request *htt
if err != nil {
return fmt.Errorf("copy file stream in multipart form data failed with error: %s", err.Error())
}
}
request.Header.Set(headerContentType, w.FormDataContentType())

View File

@ -105,13 +105,11 @@ func (l *Auth) attachLDAPGroup(ctx context.Context, ldapUsers []model.User, u *m
groupAdminDN := utils.TrimLower(groupCfg.AdminDN)
// Attach user group
for _, groupDN := range ldapUsers[0].GroupDNList {
groupDN = utils.TrimLower(groupDN)
// Attach LDAP group admin
if len(groupAdminDN) > 0 && groupAdminDN == groupDN {
u.AdminRoleInAuth = true
}
}
// skip to attach group when ldap_group_search_filter is empty
if len(groupCfg.Filter) == 0 {
@ -182,7 +180,6 @@ func (l *Auth) SearchUser(ctx context.Context, username string) (*models.User, e
log.Warningf("There are more than one user found, return the first user")
}
if len(lUsers) > 0 {
user.Username = strings.TrimSpace(lUsers[0].Username)
user.Realname = strings.TrimSpace(lUsers[0].Realname)
user.Email = strings.TrimSpace(lUsers[0].Email)

View File

@ -154,5 +154,4 @@ func init() {
log.Errorf("failed to load app config: %v", err)
}
}
}

View File

@ -245,7 +245,6 @@ func (oc *OIDCController) Onboard() {
oc.DelSession(userInfoKey)
oc.PopulateUserSession(*user)
}
}
func secretAndToken(tokenBytes []byte) (string, string, error) {

View File

@ -51,5 +51,4 @@ func (h *Handler) Get() {
}
h.Data["json"] = token
h.ServeJSON()
}

View File

@ -245,7 +245,6 @@ func (dh *DefaultHandler) HandlePeriodicExecutions(w http.ResponseWriter, req *h
w.Header().Add(totalHeaderKey, fmt.Sprintf("%d", total))
dh.handleJSONData(w, req, http.StatusOK, executions)
}
// HandleGetJobsReq is implementation of method defined in interface 'Handler'

View File

@ -274,7 +274,6 @@ func (c *Configuration) loadEnvs() {
}
}
}
}
// Check if the configurations are valid settings.

View File

@ -7,7 +7,6 @@ import (
)
func parseLevel(lvl string) log.Level {
var level = log.WarningLevel
switch strings.ToLower(lvl) {

View File

@ -27,7 +27,6 @@ func FileFactory(options ...OptionItem) (Interface, error) {
case "depth":
depth = op.Int()
default:
}
}

View File

@ -59,7 +59,6 @@ func Instance() Encryptor {
}
log.Infof("the path of key used by key provider: %s", kp)
encryptInstance = NewAESEncryptor(NewFileKeyProvider(kp))
})
return encryptInstance
}

View File

@ -55,7 +55,6 @@ func (l Level) string() (lvl string) {
}
func parseLevel(lvl string) (level Level, err error) {
switch strings.ToLower(lvl) {
case "debug":
level = DebugLevel

View File

@ -46,7 +46,6 @@ func (a *LoggerManager) Init(ctx context.Context, logEndpoint string) {
}
a.remoteLogger = log.New(w, log.NewTextFormatter(), log.InfoLevel, 3)
a.remoteLogger.SetFallback(log.DefaultLogger())
}
// DefaultLogger ...

View File

@ -22,7 +22,6 @@ import (
// TokenReview ...
func TokenReview(rawToken string, authProxyConfig *cfgModels.HTTPAuthProxy) (k8s_api_v1beta1.TokenReviewStatus, error) {
emptyStatus := k8s_api_v1beta1.TokenReviewStatus{}
// Init auth client with the auth proxy endpoint.
authClientCfg := &rest.Config{
@ -67,7 +66,6 @@ func TokenReview(rawToken string, authProxyConfig *cfgModels.HTTPAuthProxy) (k8s
return emptyStatus, err
}
return tokenReviewResponse.Status, nil
}
func getTLSConfig(config *cfgModels.HTTPAuthProxy) rest.TLSClientConfig {

View File

@ -39,7 +39,6 @@ func (d *Database) Load(ctx context.Context) (map[string]interface{}, error) {
return resultMap, err
}
for _, item := range configEntries {
itemMetadata, ok := metadata.Instance().GetByName(item.Key)
if !ok {
log.Debugf("failed to get metadata, key:%v, error:%v, skip to load item", item.Key, err)

View File

@ -44,7 +44,6 @@ func InitBackendWorker(redisPoolConfig *RedisPoolConfig) {
jsNamespace = fmt.Sprintf("{%s}", redisPoolConfig.Namespace)
// Start the backend worker
jsClient = work.NewClient(jsNamespace, pool)
}
// GetBackendWorker ...

View File

@ -72,7 +72,6 @@ func NewSession(basicCfg models.LdapConf, groupCfg models.GroupConf) *Session {
}
func formatURL(ldapURL string) (string, error) {
var protocol, hostport string
_, err := url.Parse(ldapURL)
if err != nil {
@ -98,7 +97,6 @@ func formatURL(ldapURL string) (string, error) {
if port == "636" {
protocol = "ldaps"
}
} else {
switch protocol {
case "ldap":
@ -111,7 +109,6 @@ func formatURL(ldapURL string) (string, error) {
fLdapURL := protocol + "://" + hostport
return fLdapURL, nil
}
// TestConfig - test ldap session connection, out of the scope of normal session create/close
@ -184,7 +181,6 @@ func (s *Session) SearchUser(username string) ([]model.User, error) {
}
return ldapUsers, nil
}
// Bind with specified DN and password, used in authentication
@ -225,7 +221,6 @@ func (s *Session) Open() error {
}
return nil
}
// SearchLdap to search ldap with the provide filter
@ -247,7 +242,6 @@ func (s *Session) SearchLdap(filter string) (*goldap.SearchResult, error) {
// SearchLdapAttribute - to search ldap with the provide filter, with specified attributes
func (s *Session) SearchLdapAttribute(baseDN, filter string, attributes []string) (*goldap.SearchResult, error) {
if err := s.Bind(s.basicCfg.SearchDn, s.basicCfg.SearchPassword); err != nil {
return nil, fmt.Errorf("can not bind search dn, error: %v", err)
}
@ -285,7 +279,6 @@ func (s *Session) SearchLdapAttribute(baseDN, filter string, attributes []string
}
return result, nil
}
// createUserSearchFilter - create filter to search user with specified username

View File

@ -113,7 +113,6 @@ func (m *manager) ImportUser(ctx context.Context, sess *Session, ldapImportUsers
failedImportUser = append(failedImportUser, u)
log.Errorf("Can't import user %s, error: %s", tempUID, u.Error)
}
}
return failedImportUser, nil

View File

@ -438,7 +438,6 @@ type Conn struct {
// TestEndpoint tests whether the endpoint is a valid OIDC endpoint.
// The nil return value indicates the success of the test
func TestEndpoint(conn Conn) error {
// gooidc will try to call the discovery api when creating the provider and that's all we need to check
ctx := clientCtx(context.Background(), conn.VerifyCert)
_, err := gooidc.NewProvider(ctx, conn.URL)

View File

@ -22,7 +22,6 @@ func (fv *fakeVerifier) VerifySecret(ctx context.Context, name string, secret st
Subject: "subject",
Issuer: "issuer",
}, nil
}
// SetHardcodeVerifierForTest overwrite the default secret manager for testing.

View File

@ -107,7 +107,6 @@ func (d *dao) Update(ctx context.Context, instance *provider.Instance, props ...
return
}
return orm.WithTransaction(trans)(orm.SetTransactionOpNameToContext(ctx, "tx-prehead-update"))
}
// Delete deletes one distribution instance by id.

View File

@ -84,7 +84,6 @@ func (ps *PreheatingStatus) String() string {
}
default:
t = fmt.Sprintf("%s, start time=%s", t, ps.StartTime)
}
return t

View File

@ -89,7 +89,6 @@ func (man *mgr) delete(sec string) {
man.m.Delete(sec)
atomic.AddUint64(&man.size, ^uint64(0))
}
}
}

View File

@ -27,7 +27,6 @@ type Client struct {
// NewClient creates a new DTR client.
func NewClient(registry *model.Registry) *Client {
client := &Client{
url: registry.URL,
username: registry.Credential.AccessKey,

View File

@ -145,7 +145,6 @@ func (a *adapter) FetchArtifacts(filters []*model.Filter) (resources []*model.Re
index := i
repo := r
runner.AddTask(func() error {
artifacts, err := a.listArtifacts(repo, filters)
if err != nil {
return fmt.Errorf("failed to list artifacts of repository %s: %v", repo, err)

View File

@ -171,7 +171,6 @@ func (a *adapter) getProjectsByPattern(pattern string) ([]*Project, error) {
projectset := make(map[string]bool)
var err error
if len(pattern) > 0 {
names, ok := util.IsSpecificPath(pattern)
if ok {
for _, name := range names {

View File

@ -27,7 +27,6 @@ type Client struct {
// NewClient creates a new GitLab client.
func NewClient(registry *model.Registry) (*Client, error) {
realm, _, err := util.Ping(registry)
if err != nil && !liberrors.IsChallengesUnsupportedErr(err) {
return nil, err

View File

@ -283,7 +283,6 @@ func newAdapter(registry *model.Registry) (adp.Adapter, error) {
Transport: transport,
},
}, nil
}
type hwNamespaceList struct {

View File

@ -28,7 +28,6 @@ import (
// FetchArtifacts gets resources from Huawei SWR
func (a *adapter) FetchArtifacts(filters []*model.Filter) ([]*model.Resource, error) {
resources := []*model.Resource{}
urls := fmt.Sprintf("%s/dockyard/v2/repositories?filter=center::self", a.registry.URL)
@ -66,7 +65,6 @@ func (a *adapter) FetchArtifacts(filters []*model.Filter) ([]*model.Resource, er
resources = append(resources, resource)
}
return resources, nil
}
// ManifestExist check the manifest of Huawei SWR

View File

@ -104,7 +104,6 @@ func newAdapter(registry *model.Registry) (adp.Adapter, error) {
registry: registry,
client: newClient(registry),
}, nil
}
// PrepareForPush creates local docker repository in jfrog artifactory

View File

@ -113,7 +113,6 @@ func (a *adapter) fetchCharts(namespaces []string, filters []*model.Filter) (res
})
}
}
}
return

View File

@ -22,7 +22,6 @@ import (
// NewAuthorizer returns a null authorizer
func NewAuthorizer() lib.Authorizer {
return &authorizer{}
}
type authorizer struct{}

View File

@ -147,7 +147,6 @@ func (d *dao) AddPullCount(ctx context.Context, id int64, count uint64) error {
}
if num == 0 {
return errors.New(nil).WithMessage("failed to increase repository pull count: %d", id)
}
return nil
}

View File

@ -12,11 +12,9 @@ import (
)
func init() {
if err := task.RegisterCheckInProcessor(job.Retention, retentionTaskCheckInProcessor); err != nil {
log.Fatalf("failed to register the checkin processor for the retention job, error %v", err)
}
}
func retentionTaskCheckInProcessor(ctx context.Context, t *task.Task, sc *job.StatusChange) (err error) {

View File

@ -55,7 +55,6 @@ func NewNativeToRelationalSchemaConverter() NativeScanReportConverter {
// ToRelationalSchema converts the vulnerability report data present as JSON to the new relational VulnerabilityRecord instance
func (c *nativeToRelationalSchemaConverter) ToRelationalSchema(ctx context.Context, reportUUID string, registrationUUID string, digest string, reportData string) (string, string, error) {
if len(reportData) == 0 {
log.G(ctx).Infof("There is no vulnerability report to toSchema for report UUID : %s", reportUUID)
return reportUUID, "", nil
@ -95,7 +94,6 @@ func (c *nativeToRelationalSchemaConverter) FromRelationalSchema(ctx context.Con
}
func (c *nativeToRelationalSchemaConverter) toSchema(ctx context.Context, reportUUID string, registrationUUID string, digest string, rawReportData string) error {
var vulnReport vuln.Report
err := json.Unmarshal([]byte(rawReportData), &vulnReport)
if err != nil {

View File

@ -45,7 +45,6 @@ func (cleanupCriteria *defaultSelector) ListWithFilters(ctx context.Context, que
}
func (cleanupCriteria *defaultSelector) List(ctx context.Context) ([]*model.SystemArtifact, error) {
currentTime := time.Now()
duration := time.Duration(DefaultCleanupWindowSeconds) * time.Second
timeRange := q.Range{Max: currentTime.Add(-duration).Format(time.RFC3339)}

View File

@ -85,7 +85,6 @@ func NewManager() Manager {
}
func (mgr *systemArtifactManager) Create(ctx context.Context, artifactRecord *model.SystemArtifact, reader io.Reader) (int64, error) {
var artifactId int64
// the entire create operation is executed within a transaction to ensure that any failures
@ -122,7 +121,6 @@ func (mgr *systemArtifactManager) Read(ctx context.Context, vendor string, repos
}
func (mgr *systemArtifactManager) Delete(ctx context.Context, vendor string, repository string, digest string) error {
repoName := mgr.getRepositoryName(vendor, repository)
if err := mgr.regCli.DeleteBlob(repoName, digest); err != nil {
log.Errorf("Error deleting system artifact BLOB : %s. Error: %v", repoName, err)
@ -195,7 +193,6 @@ func (mgr *systemArtifactManager) Cleanup(ctx context.Context) (int64, int64, er
// after logging the error
logger.Errorf("Error when cleaning up system artifacts for 'vendor:artifactType':%s, %v", key, err)
}
}
logger.Info("Executing cleanup for default cleanup criteria")
@ -222,7 +219,6 @@ func (mgr *systemArtifactManager) cleanup(ctx context.Context, criteria Selector
records, err := criteria.List(ctx)
if err != nil {
return totalRecordsDeleted, totalReclaimedSize, err
}

View File

@ -135,5 +135,4 @@ func (c *Configuration) loadEnvs() {
if len(registryConf) != 0 {
c.RegistryConfig = registryConf
}
}

View File

@ -31,7 +31,6 @@ import (
// 1, As Put blob will always happen after head blob gets a 404, but the 404 could be caused by blob status is deleting, which is marked by GC.
// 2, It has to deal with the concurrence blob push.
func PutBlobUploadMiddleware() func(http.Handler) http.Handler {
before := middleware.BeforeRequest(func(r *http.Request) error {
v := r.URL.Query()
digest := v.Get("digest")

View File

@ -68,7 +68,6 @@ func BeforeRequest(hook func(*http.Request) error, skippers ...Skipper) func(htt
}
next.ServeHTTP(w, r)
}, skippers...)
}

View File

@ -176,7 +176,6 @@ func RequestMiddleware(config RequestConfig, skippers ...middleware.Skipper) fun
lib_http.SendError(res, err)
}
}
}, skippers...)
}

View File

@ -73,7 +73,6 @@ func (o *oidcCli) Generate(req *http.Request) security.Context {
}
func (o *oidcCli) valid(req *http.Request) bool {
path := strings.TrimSuffix(req.URL.Path, "/")
if path == "/service/token" ||

View File

@ -106,7 +106,6 @@ func (l *ldapAPI) SearchLdapGroup(ctx context.Context, params operation.SearchLd
var groupName, groupDN string
if params.Groupname != nil && len(*params.Groupname) > 0 {
groupName = *params.Groupname
}
if params.Groupdn != nil {
groupDN = *params.Groupdn

View File

@ -48,7 +48,6 @@ func (qa *quotaAPI) GetQuota(ctx context.Context, params operation.GetQuotaParam
quota, err := qa.quotaCtl.Get(ctx, params.ID, quota.WithReferenceObject())
if err != nil {
return qa.SendError(ctx, err)
}
return operation.NewGetQuotaOK().WithPayload(model.NewQuota(quota).ToSwagger(ctx))
}

View File

@ -159,7 +159,6 @@ func (r *retentionAPI) CreateRetention(ctx context.Context, params operation.Cre
case policy.ScopeLevelProject:
if p.Scope.Reference <= 0 {
return r.SendError(ctx, errors.BadRequestError(fmt.Errorf("invalid Project id %d", p.Scope.Reference)))
}
if _, err := r.projectCtl.Get(ctx, p.Scope.Reference); err != nil {

View File

@ -133,7 +133,6 @@ func (rAPI *robotAPI) ListRobot(ctx context.Context, params operation.ListRobotP
}
projectID = pid
}
} else {
level = robot.LEVELSYSTEM
query.Keywords["ProjectID"] = 0

View File

@ -97,7 +97,6 @@ func (s *statisticAPI) GetStatistic(ctx context.Context, params operation.GetSta
return s.SendError(ctx, err)
}
statistic.TotalStorageConsumption = sum
} else {
var privProjectIDs []interface{}
if sc, ok := securityCtx.(*local.SecurityContext); ok && sc.IsAuthenticated() {

View File

@ -95,5 +95,4 @@ func (s *sysInfoAPI) convertInfo(d *si.Data) *models.GeneralInfo {
res.CurrentTime = &currentTime
}
return res
}

View File

@ -94,7 +94,6 @@ func (u *usersAPI) CreateUser(ctx context.Context, params operation.CreateUserPa
}
location := fmt.Sprintf("%s/%d", strings.TrimSuffix(params.HTTPRequest.URL.Path, "/"), uid)
return operation.NewCreateUserCreated().WithLocation(location)
}
func (u *usersAPI) ListUsers(ctx context.Context, params operation.ListUsersParams) middleware.Responder {
@ -197,7 +196,6 @@ func (u *usersAPI) GetCurrentUserInfo(ctx context.Context, params operation.GetC
}
resp, err := u.getUserByID(ctx, lsc.User().UserID)
if err != nil {
return u.SendError(ctx, err)
}
return operation.NewGetCurrentUserInfoOK().WithPayload(resp)
@ -421,7 +419,6 @@ func (u *usersAPI) requireModifiable(ctx context.Context, id int) error {
func modifiable(ctx context.Context, authMode string, id int) bool {
sctx, _ := security.FromContext(ctx)
if authMode == common.DBAuth {
// In db auth, admin can update anyone's info, and regular user can update his own
return sctx.Can(ctx, rbac.ActionUpdate, userResource) || matchUserID(sctx, id)
}