update golangci-lint for golang1.19 (#17817)

update golaci-lint for golang1.19

Signed-off-by: yminer <yminer@vmware.com>

update ci version to v1.50.1
This commit is contained in:
MinerYang 2022-11-18 11:40:01 +08:00 committed by GitHub
parent cbfffce413
commit 62223bd36d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
27 changed files with 177 additions and 160 deletions

View File

@ -34,7 +34,7 @@ linters:
- revive
- whitespace
- bodyclose
- deadcode
# - deadcode //deprecated since golangci-lint v1.49.0
- errcheck
# - gosec
- gosimple
@ -43,12 +43,12 @@ linters:
# - noctx
# - rowserrcheck
- staticcheck
- structcheck
# - structcheck //deprecated since golangci-lint v1.49.0
- stylecheck
# - unconvert
# - unparam
- unused
- varcheck
# - unused // disabled due to too many false positive check and limited support golang 1.19 https://github.com/dominikh/go-tools/issues/1282
# - varcheck //deprecated since golangci-lint v1.49.0
run:
skip-files:

View File

@ -85,8 +85,9 @@ func NewChartCache(config *ChartCacheConfig) *ChartCache {
// IsEnabled to indicate if the chart cache is successfully enabled
// The cache may be disabled if
// user does not set
// wrong configurations
//
// user does not set
// wrong configurations
func (chc *ChartCache) IsEnabled() bool {
return chc.isEnabled
}

View File

@ -248,16 +248,17 @@ func (b *BaseAPI) SendStatusServiceUnavailableError(err error) {
}
// SendError return the error defined in OCI spec: https://github.com/opencontainers/distribution-spec/blob/master/spec.md#errors
// {
// "errors:" [{
// "code": <error identifier>,
// "message": <message describing condition>,
// // optional
// "detail": <unstructured>
// },
// ...
// ]
// }
//
// {
// "errors:" [{
// "code": <error identifier>,
// "message": <message describing condition>,
// // optional
// "detail": <unstructured>
// },
// ...
// ]
// }
func (b *BaseAPI) SendError(err error) {
lib_http.SendError(b.Ctx.ResponseWriter, err)
}

View File

@ -65,32 +65,33 @@ func (d *defaultProcessor) ListAdditionTypes(ctx context.Context, artifact *arti
// AbstractMetadata will abstract data in a specific way.
// Annotation keys in artifact annotation will decide which content will be processed in artifact.
// Here is a manifest example:
// {
// "schemaVersion": 2,
// "config": {
// "mediaType": "application/vnd.caicloud.model.config.v1alpha1+json",
// "digest": "sha256:be948daf0e22f264ea70b713ea0db35050ae659c185706aa2fad74834455fe8c",
// "size": 187,
// "annotations": {
// "io.goharbor.artifact.v1alpha1.skip-list": "metrics,git"
// }
// },
// "layers": [
// {
// "mediaType": "image/png",
// "digest": "sha256:d923b93eadde0af5c639a972710a4d919066aba5d0dfbf4b9385099f70272da0",
// "size": 166015,
// "annotations": {
// "io.goharbor.artifact.v1alpha1.icon": ""
// }
// },
// {
// "mediaType": "application/tar+gzip",
// "digest": "sha256:d923b93eadde0af5c639a972710a4d919066aba5d0dfbf4b9385099f70272da0",
// "size": 166015
// }
// ]
// }
//
// {
// "schemaVersion": 2,
// "config": {
// "mediaType": "application/vnd.caicloud.model.config.v1alpha1+json",
// "digest": "sha256:be948daf0e22f264ea70b713ea0db35050ae659c185706aa2fad74834455fe8c",
// "size": 187,
// "annotations": {
// "io.goharbor.artifact.v1alpha1.skip-list": "metrics,git"
// }
// },
// "layers": [
// {
// "mediaType": "image/png",
// "digest": "sha256:d923b93eadde0af5c639a972710a4d919066aba5d0dfbf4b9385099f70272da0",
// "size": 166015,
// "annotations": {
// "io.goharbor.artifact.v1alpha1.icon": ""
// }
// },
// {
// "mediaType": "application/tar+gzip",
// "digest": "sha256:d923b93eadde0af5c639a972710a4d919066aba5d0dfbf4b9385099f70272da0",
// "size": 166015
// }
// ]
// }
func (d *defaultProcessor) AbstractMetadata(ctx context.Context, artifact *artifact.Artifact, manifest []byte) error {
if artifact.ManifestMediaType != v1.MediaTypeImageManifest && artifact.ManifestMediaType != schema2.MediaTypeManifest {
return nil

View File

@ -124,7 +124,6 @@ type Controller interface {
var _ Controller = (*controller)(nil)
// controller is the default implementation of Controller interface.
//
type controller struct {
// For instance
iManager instance.Manager

View File

@ -52,7 +52,7 @@ func (j *Job) Validate(params job.Parameters) error {
}
func (j *Job) parseParams(params job.Parameters) {
if params == nil || len(params) == 0 {
if len(params) == 0 {
return
}
retHr, exist := params[common.PurgeAuditRetentionHour]

View File

@ -44,7 +44,7 @@ func (j *Job) ShouldRetry() bool {
// Validate is implementation of same method in Interface.
func (j *Job) Validate(params job.Parameters) error {
if params == nil || len(params) == 0 {
if len(params) == 0 {
return errors.New("parameters required for replication job")
}
name, ok := params["image"]

View File

@ -47,7 +47,8 @@ func (sde *ScanDataExport) MaxCurrency() uint {
// still less that the number declared by the method 'MaxFails'.
//
// Returns:
// true for retry and false for none-retry
//
// true for retry and false for none-retry
func (sde *ScanDataExport) ShouldRetry() bool {
return true
}
@ -66,8 +67,8 @@ func (sde *ScanDataExport) Validate(params job.Parameters) error {
// params map[string]interface{} : parameters with key-pair style for the job execution.
//
// Returns:
// error if failed to run. NOTES: If job is stopped or cancelled, a specified error should be returned
//
// error if failed to run. NOTES: If job is stopped or cancelled, a specified error should be returned
func (sde *ScanDataExport) Run(ctx job.Context, params job.Parameters) error {
if _, ok := params[export.JobModeKey]; !ok {
return errors.Errorf("no mode specified for scan data export execution")

View File

@ -22,7 +22,7 @@ var singletons sync.Map
// GetLogger gets an unified logger entry for logging per the passed settings.
// The logger may built based on the multiple registered logger backends.
//
// loggerOptions ...Option : logger options
// loggerOptions ...Option : logger options
//
// If failed, a nil logger and a non-nil error will be returned.
// Otherwise, a non nil logger is returned with nil error.
@ -125,11 +125,13 @@ func GetSweeper(context context.Context, sweeperOptions ...Option) (sweeper.Inte
// GetLogDataGetter return the 1st matched log data getter interface
//
// loggerOptions ...Option : logger options
// loggerOptions ...Option : logger options
//
// If failed,
// configured but initialize failed: a nil log data getter and a non-nil error will be returned.
// no getter configured: a nil log data getter with a nil error are returned
//
// configured but initialize failed: a nil log data getter and a non-nil error will be returned.
// no getter configured: a nil log data getter with a nil error are returned
//
// Otherwise, a non nil log data getter is returned with nil error.
func GetLogDataGetter(loggerOptions ...Option) (getter.Interface, error) {
if len(loggerOptions) == 0 {

View File

@ -148,10 +148,11 @@ func parseModel(model interface{}) *metadata {
// parseFilterable parses whether the field is filterable according to the field annotation
// For the following struct definition, "Field1" isn't filterable and "Field2" is filterable
// type Model struct {
// Field1 string `filter:"false"`
// Field2 string
// }
//
// type Model struct {
// Field1 string `filter:"false"`
// Field2 string
// }
func parseFilterable(field reflect.StructField) bool {
return field.Tag.Get("filter") != "false"
}
@ -159,13 +160,14 @@ func parseFilterable(field reflect.StructField) bool {
// parseSortable parses whether the field is sortable according to the field annotation
// If the field is sortable and is also specified as the default sort, return a q.Sort model as well
// For the following struct definition, "Field1" isn't sortable and "Field2", "Field2", "Field4", "Field5" are all sortable
// type Model struct {
// Field1 string `sort:"false"`
// Field2 string `sort:"true;default"`
// Field3 string `sort:"true;default:desc"`
// Field4 string `sort:"default"`
// Field5 string
// }
//
// type Model struct {
// Field1 string `sort:"false"`
// Field2 string `sort:"true;default"`
// Field3 string `sort:"true;default:desc"`
// Field4 string `sort:"default"`
// Field5 string
// }
func parseSortable(field reflect.StructField) (*q.Sort, bool) {
var defaultSort *q.Sort
for _, item := range strings.Split(field.Tag.Get("sort"), ";") {
@ -188,10 +190,12 @@ func parseSortable(field reflect.StructField) (*q.Sort, bool) {
}
// parseColumn parses the column name according to the field annotation
// type Model struct {
// Field1 string `orm:"column(customized_field1)"`
// Field2 string
// }
//
// type Model struct {
// Field1 string `orm:"column(customized_field1)"`
// Field2 string
// }
//
// It returns "customized_field1" for "Field1" and returns "field2" for "Field2"
func parseColumn(field reflect.StructField) string {
column := ""

View File

@ -270,8 +270,8 @@ func ParamPlaceholderForIn(n int) string {
// to DDL and other statements that do not accept parameters) to be used as part
// of an SQL statement. For example:
//
// exp_date := pq.QuoteLiteral("2023-01-05 15:00:00Z")
// err := db.Exec(fmt.Sprintf("CREATE ROLE my_user VALID UNTIL %s", exp_date))
// exp_date := pq.QuoteLiteral("2023-01-05 15:00:00Z")
// err := db.Exec(fmt.Sprintf("CREATE ROLE my_user VALID UNTIL %s", exp_date))
//
// Any single quotes in name will be escaped. Any backslashes (i.e. "\") will be
// replaced by two backslashes (i.e. "\\") and the C-style escape identifier

View File

@ -27,37 +27,43 @@ import (
// QuerySetter generates the query setter according to the provided model and query.
// e.g.
// type Foo struct{
// Field1 string `orm:"-"` // can not filter/sort
// Field2 string `orm:"column(customized_field2)"` // support filter by "Field2", "customized_field2"
// Field3 string `sort:"false"` // cannot be sorted
// Field4 string `sort:"default:desc"` // the default field/order(asc/desc) to sort if no sorting specified in query.
// Field5 string `filter:"false"` // cannot be filtered
// }
//
// type Foo struct{
// Field1 string `orm:"-"` // can not filter/sort
// Field2 string `orm:"column(customized_field2)"` // support filter by "Field2", "customized_field2"
// Field3 string `sort:"false"` // cannot be sorted
// Field4 string `sort:"default:desc"` // the default field/order(asc/desc) to sort if no sorting specified in query.
// Field5 string `filter:"false"` // cannot be filtered
// }
//
// // support filter by "Field6", "field6"
// func (f *Foo) FilterByField6(ctx context.Context, qs orm.QuerySetter, key string, value interface{}) orm.QuerySetter {
// ...
// return qs
// }
//
// func (f *Foo) FilterByField6(ctx context.Context, qs orm.QuerySetter, key string, value interface{}) orm.QuerySetter {
// ...
// return qs
// }
//
// Defining the method "GetDefaultSorts() []*q.Sort" for the model whose default sorting contains more than one fields
// type Bar struct{
// Field1 string
// Field2 string
// }
//
// type Bar struct{
// Field1 string
// Field2 string
// }
//
// // Sort by "Field1" desc, "Field2"
// func (b *Bar) GetDefaultSorts() []*q.Sort {
// return []*q.Sort{
// {
// Key: "Field1",
// DESC: true,
// },
// {
// Key: "Field2",
// DESC: false,
// },
// }
// }
//
// func (b *Bar) GetDefaultSorts() []*q.Sort {
// return []*q.Sort{
// {
// Key: "Field1",
// DESC: true,
// },
// {
// Key: "Field2",
// DESC: false,
// },
// }
// }
func QuerySetter(ctx context.Context, model interface{}, query *q.Query) (orm.QuerySeter, error) {
t := reflect.TypeOf(model)
if t.Kind() != reflect.Ptr {

View File

@ -44,10 +44,12 @@ Soft reference: The accessory is not tied to the subject manifest.
Hard reference: The accessory is tied to the subject manifest.
Deletion
1. Soft Reference: If the linkage is Soft Reference, when the subject artifact is removed, the linkage will be removed as well, the accessory artifact becomes an individual artifact.
2. Hard Reference: If the linkage is Hard Reference, the accessory artifact will be removed together with the subject artifact.
Garbage Collection
1. Soft Reference: If the linkage is Soft Reference, Harbor treats the accessory as normal artifact and will not set it as the GC candidate.
2. Hard Reference: If the linkage is Hard Reference, Harbor treats the accessory as an extra stuff of the subject artifact. It means, it being tied to the subject artifact and will be GCed whenever the subject artifact is marked and deleted.
*/

View File

@ -91,7 +91,7 @@ func (bm *BaseManager) CacheClient(ctx context.Context) cache.Cache {
return bm.cacheClient
}
// ResourceType returns the resource type.
// ResourceType returns the resource type.
func (bm *BaseManager) ResourceType(ctx context.Context) string {
return bm.resourceType
}

View File

@ -18,9 +18,10 @@ const (
// Driver defines the capabilities one distribution provider should have.
// Includes:
// Self descriptor
// Health checking
// Preheat related : Preheat means transfer the preheating image to the network of distribution provider in advance.
//
// Self descriptor
// Health checking
// Preheat related : Preheat means transfer the preheating image to the network of distribution provider in advance.
type Driver interface {
// Self returns the metadata of the driver.
// The metadata includes: name, icon(optional), maintainers(optional), version and source repo.

View File

@ -141,21 +141,21 @@ func (a adapter) HealthCheck() (string, error) {
}
/*
{
"child": [],
"manifest": {
"sha256:400ee2ed939df769d4681023810d2e4fb9479b8401d97003c710d0e20f7c49c6": {
"imageSizeBytes": "763789",
"layerId": "",
"mediaType": "application/vnd.docker.distribution.manifest.v2+json",
"tag": ["another", "latest"],
"timeCreatedMs": "1595895577054",
"timeUploadedMs": "1597767277119"
}
},
"name": "eminent-nation-87317/testgcr/busybox",
"tags": ["another", "latest"]
}
{
"child": [],
"manifest": {
"sha256:400ee2ed939df769d4681023810d2e4fb9479b8401d97003c710d0e20f7c49c6": {
"imageSizeBytes": "763789",
"layerId": "",
"mediaType": "application/vnd.docker.distribution.manifest.v2+json",
"tag": ["another", "latest"],
"timeCreatedMs": "1595895577054",
"timeUploadedMs": "1597767277119"
}
},
"name": "eminent-nation-87317/testgcr/busybox",
"tags": ["another", "latest"]
}
*/
func (a adapter) listGcrTagsByRef(repository, reference string) ([]string, string, error) {
u := buildTagListURL(a.registry.URL, repository)

View File

@ -37,12 +37,12 @@ type Scanner struct {
// report MIME types. For example, a scanner capable of analyzing Docker images and producing
// a vulnerabilities report recognizable by Harbor web console might be represented with the
// following capability:
// - consumes MIME types:
// -- application/vnd.oci.image.manifest.v1+json
// -- application/vnd.docker.distribution.manifest.v2+json
// - produces MIME types
// -- application/vnd.scanner.adapter.vuln.report.harbor+json; version=1.0
// -- application/vnd.scanner.adapter.vuln.report.raw
// - consumes MIME types:
// -- application/vnd.oci.image.manifest.v1+json
// -- application/vnd.docker.distribution.manifest.v2+json
// - produces MIME types
// -- application/vnd.scanner.adapter.vuln.report.harbor+json; version=1.0
// -- application/vnd.scanner.adapter.vuln.report.raw
type ScannerCapability struct {
// The set of MIME types of the artifacts supported by the scanner to produce the reports
// specified in the "produces_mime_types". A given mime type should only be present in one

View File

@ -42,13 +42,13 @@ type tagHandler struct {
// Content-Type: application/json
// Link: <<url>?n=<n from the request>&last=<last tag value from previous response>>; rel="next"
//
// {
// "name": "<name>",
// "tags": [
// "<tag>",
// ...
// ]
// }
// {
// "name": "<name>",
// "tags": [
// "<tag>",
// ...
// ]
// }
func (t *tagHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
n, _, err := util.ParseNAndLastParameters(req)
if err != nil {

View File

@ -16,7 +16,6 @@ import (
"github.com/goharbor/harbor/src/pkg/audit"
"github.com/goharbor/harbor/src/server/v2.0/models"
"github.com/goharbor/harbor/src/server/v2.0/restapi/operations/auditlog"
operation "github.com/goharbor/harbor/src/server/v2.0/restapi/operations/auditlog"
)
func newAuditLogAPI() *auditlogAPI {
@ -92,7 +91,7 @@ func (a *auditlogAPI) ListAuditLogs(ctx context.Context, params auditlog.ListAud
OpTime: strfmt.DateTime(log.OpTime),
})
}
return operation.NewListAuditLogsOK().
return auditlog.NewListAuditLogsOK().
WithXTotalCount(total).
WithLink(a.Links(ctx, params.HTTPRequest.URL, total, query.PageNumber, query.PageSize).String()).
WithPayload(auditLogs)

View File

@ -6,6 +6,8 @@ import (
"time"
"github.com/go-openapi/strfmt"
"golang.org/x/text/cases"
"golang.org/x/text/language"
"github.com/goharbor/harbor/src/common/utils"
"github.com/goharbor/harbor/src/lib/log"
@ -47,7 +49,7 @@ func (h *GCHistory) ToSwagger() *models.GCHistory {
Schedule: &models.ScheduleObj{
// covert MANUAL to Manual because the type of the ScheduleObj
// must be 'Hourly', 'Daily', 'Weekly', 'Custom', 'Manual' and 'None'
Type: strings.Title(strings.ToLower(h.Schedule.Type)),
Type: cases.Title(language.English).String(strings.ToLower(h.Schedule.Type)),
Cron: h.Schedule.Cron,
NextScheduledTime: strfmt.DateTime(utils.NextSchedule(h.Schedule.Cron, time.Now())),
},

View File

@ -15,7 +15,6 @@ import (
"github.com/goharbor/harbor/src/server/v2.0/handler/model"
"github.com/goharbor/harbor/src/server/v2.0/models"
"github.com/goharbor/harbor/src/server/v2.0/restapi/operations/webhookjob"
operation "github.com/goharbor/harbor/src/server/v2.0/restapi/operations/webhookjob"
)
func newNotificationJobAPI() *notificationJobAPI {
@ -72,7 +71,7 @@ func (n *notificationJobAPI) ListWebhookJobs(ctx context.Context, params webhook
results = append(results, model.NewNotificationJob(j).ToSwagger())
}
return operation.NewListWebhookJobsOK().
return webhookjob.NewListWebhookJobsOK().
WithXTotalCount(total).
WithLink(n.Links(ctx, params.HTTPRequest.URL, total, query.PageNumber, query.PageSize).String()).
WithPayload(results)

View File

@ -36,7 +36,6 @@ import (
"github.com/goharbor/harbor/src/server/v2.0/handler/model"
"github.com/goharbor/harbor/src/server/v2.0/models"
"github.com/goharbor/harbor/src/server/v2.0/restapi/operations/webhook"
operation "github.com/goharbor/harbor/src/server/v2.0/restapi/operations/webhook"
)
func newNotificationPolicyAPI() *notificationPolicyAPI {
@ -102,7 +101,7 @@ func (n *notificationPolicyAPI) ListWebhookPoliciesOfProject(ctx context.Context
results = append(results, model.NewNotifiactionPolicy(p).ToSwagger())
}
return operation.NewListWebhookPoliciesOfProjectOK().
return webhook.NewListWebhookPoliciesOfProjectOK().
WithXTotalCount(total).
WithLink(n.Links(ctx, params.HTTPRequest.URL, total, query.PageNumber, query.PageSize).String()).
WithPayload(results)
@ -137,7 +136,7 @@ func (n *notificationPolicyAPI) CreateWebhookPolicyOfProject(ctx context.Context
}
location := fmt.Sprintf("%s/%d", strings.TrimSuffix(params.HTTPRequest.URL.Path, "/"), id)
return operation.NewCreateWebhookPolicyOfProjectCreated().WithLocation(location)
return webhook.NewCreateWebhookPolicyOfProjectCreated().WithLocation(location)
}
func (n *notificationPolicyAPI) UpdateWebhookPolicyOfProject(ctx context.Context, params webhook.UpdateWebhookPolicyOfProjectParams) middleware.Responder {
@ -171,7 +170,7 @@ func (n *notificationPolicyAPI) UpdateWebhookPolicyOfProject(ctx context.Context
return n.SendError(ctx, err)
}
return operation.NewUpdateWebhookPolicyOfProjectOK()
return webhook.NewUpdateWebhookPolicyOfProjectOK()
}
func (n *notificationPolicyAPI) DeleteWebhookPolicyOfProject(ctx context.Context, params webhook.DeleteWebhookPolicyOfProjectParams) middleware.Responder {
@ -185,7 +184,7 @@ func (n *notificationPolicyAPI) DeleteWebhookPolicyOfProject(ctx context.Context
if err := n.webhookPolicyMgr.Delete(ctx, params.WebhookPolicyID); err != nil {
return n.SendError(ctx, err)
}
return operation.NewDeleteWebhookPolicyOfProjectOK()
return webhook.NewDeleteWebhookPolicyOfProjectOK()
}
func (n *notificationPolicyAPI) GetWebhookPolicyOfProject(ctx context.Context, params webhook.GetWebhookPolicyOfProjectParams) middleware.Responder {
@ -206,7 +205,7 @@ func (n *notificationPolicyAPI) GetWebhookPolicyOfProject(ctx context.Context, p
return n.SendError(ctx, err)
}
return operation.NewGetWebhookPolicyOfProjectOK().WithPayload(model.NewNotifiactionPolicy(policy).ToSwagger())
return webhook.NewGetWebhookPolicyOfProjectOK().WithPayload(model.NewNotifiactionPolicy(policy).ToSwagger())
}
func (n *notificationPolicyAPI) LastTrigger(ctx context.Context, params webhook.LastTriggerParams) middleware.Responder {
@ -234,7 +233,7 @@ func (n *notificationPolicyAPI) LastTrigger(ctx context.Context, params webhook.
return n.SendError(ctx, err)
}
return operation.NewLastTriggerOK().WithPayload(triggers)
return webhook.NewLastTriggerOK().WithPayload(triggers)
}
func (n *notificationPolicyAPI) GetSupportedEventTypes(ctx context.Context, params webhook.GetSupportedEventTypesParams) middleware.Responder {
@ -252,7 +251,7 @@ func (n *notificationPolicyAPI) GetSupportedEventTypes(ctx context.Context, para
notificationTypes.EventType = append(notificationTypes.EventType, models.EventType(key))
}
return operation.NewGetSupportedEventTypesOK().WithPayload(notificationTypes)
return webhook.NewGetSupportedEventTypesOK().WithPayload(notificationTypes)
}
func (n *notificationPolicyAPI) getLastTriggerTimeGroupByEventType(ctx context.Context, eventType string, policyID int64) (time.Time, error) {

View File

@ -31,7 +31,6 @@ import (
taskCtl "github.com/goharbor/harbor/src/controller/task"
"github.com/goharbor/harbor/src/jobservice/job"
"github.com/goharbor/harbor/src/lib/errors"
liberrors "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/lib/q"
"github.com/goharbor/harbor/src/pkg/p2p/preheat/models/policy"
instanceModel "github.com/goharbor/harbor/src/pkg/p2p/preheat/models/provider"
@ -343,7 +342,7 @@ func (api *preheatAPI) DeletePolicy(ctx context.Context, params operation.Delete
// Detecting running tasks under the policy
if err = detectRunningExecutions(executions); err != nil {
return api.SendError(ctx, liberrors.New(err).WithCode(liberrors.PreconditionCode))
return api.SendError(ctx, errors.New(err).WithCode(errors.PreconditionCode))
}
err = api.preheatCtl.DeletePolicy(ctx, policy.ID)
@ -442,7 +441,7 @@ func (api *preheatAPI) PingInstances(ctx context.Context, params operation.PingI
if params.Instance.ID > 0 {
// by ID
instance, err = api.preheatCtl.GetInstance(ctx, params.Instance.ID)
if liberrors.IsNotFoundErr(err) {
if errors.IsNotFoundErr(err) {
return operation.NewPingInstancesNotFound()
}
if err != nil {

View File

@ -36,7 +36,6 @@ import (
"github.com/goharbor/harbor/src/server/v2.0/handler/model"
"github.com/goharbor/harbor/src/server/v2.0/models"
"github.com/goharbor/harbor/src/server/v2.0/restapi/operations/purge"
operation "github.com/goharbor/harbor/src/server/v2.0/restapi/operations/purge"
)
type purgeAPI struct {
@ -189,7 +188,7 @@ func (p *purgeAPI) GetPurgeHistory(ctx context.Context, params purge.GetPurgeHis
results = append(results, h.ToSwagger())
}
return operation.NewGetPurgeHistoryOK().
return purge.NewGetPurgeHistoryOK().
WithXTotalCount(total).
WithLink(p.Links(ctx, params.HTTPRequest.URL, total, query.PageNumber, query.PageSize).String()).
WithPayload(results)
@ -226,7 +225,7 @@ func (p *purgeAPI) GetPurgeJob(ctx context.Context, params purge.GetPurgeJobPara
UpdateTime: exec.UpdateTime,
}
return operation.NewGetPurgeJobOK().WithPayload(res.ToSwagger())
return purge.NewGetPurgeJobOK().WithPayload(res.ToSwagger())
}
func (p *purgeAPI) GetPurgeJobLog(ctx context.Context, params purge.GetPurgeJobLogParams) middleware.Responder {
@ -249,7 +248,7 @@ func (p *purgeAPI) GetPurgeJobLog(ctx context.Context, params purge.GetPurgeJobL
if err != nil {
return p.SendError(ctx, err)
}
return operation.NewGetPurgeJobLogOK().WithPayload(string(taskLog))
return purge.NewGetPurgeJobLogOK().WithPayload(string(taskLog))
}
func (p *purgeAPI) GetPurgeSchedule(ctx context.Context, params purge.GetPurgeScheduleParams) middleware.Responder {
@ -258,7 +257,7 @@ func (p *purgeAPI) GetPurgeSchedule(ctx context.Context, params purge.GetPurgeSc
}
sch, err := p.schedulerCtl.Get(ctx, pg.VendorType)
if errors.IsNotFoundErr(err) {
return operation.NewGetPurgeScheduleOK()
return purge.NewGetPurgeScheduleOK()
}
if err != nil {
return p.SendError(ctx, err)
@ -278,7 +277,7 @@ func (p *purgeAPI) GetPurgeSchedule(ctx context.Context, params purge.GetPurgeSc
CreationTime: strfmt.DateTime(sch.CreationTime),
UpdateTime: strfmt.DateTime(sch.UpdateTime),
}
return operation.NewGetPurgeScheduleOK().WithPayload(execHistory)
return purge.NewGetPurgeScheduleOK().WithPayload(execHistory)
}
func (p *purgeAPI) UpdatePurgeSchedule(ctx context.Context, params purge.UpdatePurgeScheduleParams) middleware.Responder {
@ -292,10 +291,10 @@ func (p *purgeAPI) UpdatePurgeSchedule(ctx context.Context, params purge.UpdateP
if err != nil {
return p.SendError(ctx, err)
}
return operation.NewUpdatePurgeScheduleOK()
return purge.NewUpdatePurgeScheduleOK()
}
func verifyUpdateRequest(params operation.UpdatePurgeScheduleParams) error {
func verifyUpdateRequest(params purge.UpdatePurgeScheduleParams) error {
if params.Schedule == nil || params.Schedule.Schedule == nil {
return errors.BadRequestError(fmt.Errorf("schedule cann't be empty"))
}
@ -326,12 +325,12 @@ func (p *purgeAPI) createSchedule(ctx context.Context, vendorType string, cronTy
return nil
}
func (p *purgeAPI) StopPurge(ctx context.Context, params operation.StopPurgeParams) middleware.Responder {
func (p *purgeAPI) StopPurge(ctx context.Context, params purge.StopPurgeParams) middleware.Responder {
if err := p.RequireSystemAccess(ctx, rbac.ActionStop, rbac.ResourcePurgeAuditLog); err != nil {
return p.SendError(ctx, err)
}
if err := p.purgeCtr.Stop(ctx, params.PurgeID); err != nil {
return p.SendError(ctx, err)
}
return operation.NewStopPurgeOK()
return purge.NewStopPurgeOK()
}

View File

@ -20,6 +20,8 @@ import (
"strings"
"github.com/go-openapi/runtime/middleware"
"golang.org/x/text/cases"
"golang.org/x/text/language"
"github.com/goharbor/harbor/src/common/rbac"
"github.com/goharbor/harbor/src/controller/scan"
@ -256,7 +258,7 @@ func (s *scanAllAPI) getMetrics(ctx context.Context, trigger ...string) (*models
}
sts.Ongoing = !job.Status(execution.Status).Final() || sts.Total != sts.Completed
sts.Trigger = strings.Title(strings.ToLower(execution.Trigger))
sts.Trigger = cases.Title(language.English).String(strings.ToLower(execution.Trigger))
}
return sts, nil

View File

@ -309,11 +309,11 @@ func (se *scanDataExportAPI) requireProjectsAccess(ctx context.Context, pids []i
// validateScanExportParams validates scan data export request parameters by
// following policies.
// rules:
// 1. check the scan data type
// 2. the criteria should not be empty
// 3. currently only the export of single project is open
// 4. check the existence of project
// 5. do not allow to input space in the repo/tag/cve_id (space will lead to misjudge for doublestar filter)
// 1. check the scan data type
// 2. the criteria should not be empty
// 3. currently only the export of single project is open
// 4. check the existence of project
// 5. do not allow to input space in the repo/tag/cve_id (space will lead to misjudge for doublestar filter)
func (se *scanDataExportAPI) validateScanExportParams(ctx context.Context, params operation.ExportScanDataParams) error {
// check if the MIME type for the export is the Generic vulnerability data
if params.XScanDataType != v1.MimeTypeGenericVulnerabilityReport {

View File

@ -16,7 +16,7 @@ go get github.com/mattn/goveralls
go get -u github.com/client9/misspell/cmd/misspell
# binary will be $(go env GOPATH)/bin/golangci-lint
# go install/go get installation aren't guaranteed to work. We recommend using binary installation.
curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.45.2
curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.50.1
sudo service postgresql stop || echo no postgresql need to be stopped
sleep 2