diff --git a/.golangci.yml b/.golangci.yml index 8aa43e158..9d29ee1a9 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -155,6 +155,13 @@ issues: linters: - gocritic + # Gosmopolitan complains of internationalization issues on the file that actually defines + # the translation. + - path: i18n\.go + text: "Han" + linters: + - gosmopolitan + # These are performance optimisations rather than style issues per se. # They warn when function arguments or range values copy a lot of memory # rather than using a pointer. diff --git a/pkg/addon/addon.go b/pkg/addon/addon.go index 71468b4ae..7c4973c46 100644 --- a/pkg/addon/addon.go +++ b/pkg/addon/addon.go @@ -124,6 +124,9 @@ const ( // InstallerRuntimeOption inject install runtime info into addon options InstallerRuntimeOption string = "installerRuntimeOption" + + // CUEExtension with the expected extension for CUE files + CUEExtension = ".cue" ) // ParameterFileName is the addon resources/parameter.cue file name @@ -396,7 +399,7 @@ func readResFile(a *InstallPackage, reader AsyncReader, readPath string) error { } file := ElementFile{Data: b, Name: filepath.Base(readPath)} switch filepath.Ext(filename) { - case ".cue": + case CUEExtension: a.CUETemplates = append(a.CUETemplates, file) case ".yaml", ".yml": a.YAMLTemplates = append(a.YAMLTemplates, file) @@ -425,7 +428,7 @@ func readDefFile(a *UIData, reader AsyncReader, readPath string) error { filename := path.Base(readPath) file := ElementFile{Data: b, Name: filepath.Base(readPath)} switch filepath.Ext(filename) { - case ".cue": + case CUEExtension: a.CUEDefinitions = append(a.CUEDefinitions, file) case ".yaml", ".yml": a.Definitions = append(a.Definitions, file) @@ -442,7 +445,7 @@ func readConfigTemplateFile(a *UIData, reader AsyncReader, readPath string) erro return err } filename := path.Base(readPath) - if filepath.Ext(filename) != ".cue" { + if filepath.Ext(filename) != CUEExtension { return nil } file := ElementFile{Data: b, Name: filepath.Base(readPath)} @@ -458,7 +461,7 @@ func readViewFile(a *InstallPackage, reader AsyncReader, readPath string) error } filename := path.Base(readPath) switch filepath.Ext(filename) { - case ".cue": + case CUEExtension: a.CUEViews = append(a.CUEViews, ElementFile{Data: b, Name: filepath.Base(readPath)}) case ".yaml", ".yml": a.YAMLViews = append(a.YAMLViews, ElementFile{Data: b, Name: filepath.Base(readPath)}) @@ -582,7 +585,7 @@ func unmarshalToContent(content []byte) (fileContent *github.RepositoryContent, if directoryUnmarshalError == nil { return nil, directoryContent, nil } - return nil, nil, fmt.Errorf("unmarshalling failed for both file and directory content: %s and %w", fileUnmarshalError, directoryUnmarshalError) + return nil, nil, fmt.Errorf("unmarshalling failed for both file and directory content: %s and %w", fileUnmarshalError.Error(), directoryUnmarshalError) } func genAddonAPISchema(addonRes *UIData) error { diff --git a/pkg/addon/push.go b/pkg/addon/push.go index dab368df1..4c227d461 100644 --- a/pkg/addon/push.go +++ b/pkg/addon/push.go @@ -167,7 +167,9 @@ func (p *PushCmd) Push(ctx context.Context) error { if err != nil { return err } - + defer func() { + _ = resp.Body.Close() + }() return handlePushResponse(resp) } diff --git a/pkg/appfile/appfile.go b/pkg/appfile/appfile.go index 2a77a8db8..8c14ae446 100644 --- a/pkg/appfile/appfile.go +++ b/pkg/appfile/appfile.go @@ -203,7 +203,7 @@ type Appfile struct { // GeneratePolicyManifests generates policy manifests from an appFile // internal policies like apply-once, topology, will not render manifests -func (af *Appfile) GeneratePolicyManifests(ctx context.Context) ([]*unstructured.Unstructured, error) { +func (af *Appfile) GeneratePolicyManifests(_ context.Context) ([]*unstructured.Unstructured, error) { var manifests []*unstructured.Unstructured for _, policy := range af.ParsedPolicies { un, err := af.generatePolicyUnstructured(policy) diff --git a/pkg/appfile/dryrun/dryrun.go b/pkg/appfile/dryrun/dryrun.go index 6d2a7eb96..5593a0d7b 100644 --- a/pkg/appfile/dryrun/dryrun.go +++ b/pkg/appfile/dryrun/dryrun.go @@ -189,7 +189,7 @@ func (d *Option) PrintDryRun(buff *bytes.Buffer, appName string, comps []*types. case traitType == definition.AuxiliaryWorkload: buff.WriteString("## From the auxiliary workload \n") case traitType != "": - buff.WriteString(fmt.Sprintf("## From the trait %s \n", traitType)) + fmt.Fprintf(buff, "## From the trait %s \n", traitType) } result, err := yaml.Marshal(t) if err != nil { diff --git a/pkg/cmd/utils.go b/pkg/cmd/utils.go index ed48f15e4..8b6baccea 100644 --- a/pkg/cmd/utils.go +++ b/pkg/cmd/utils.go @@ -25,7 +25,7 @@ import ( ) // GetNamespace get namespace from command flags and env -func GetNamespace(f Factory, cmd *cobra.Command) string { +func GetNamespace(_ Factory, cmd *cobra.Command) string { namespace, err := cmd.Flags().GetString(flagNamespace) cmdutil.CheckErr(err) if namespace != "" { diff --git a/pkg/config/factory.go b/pkg/config/factory.go index 6afb1b726..a2149a7b4 100644 --- a/pkg/config/factory.go +++ b/pkg/config/factory.go @@ -197,8 +197,8 @@ type Distribution struct { // CreateDistributionSpec the spec of the distribution type CreateDistributionSpec struct { - Configs []*NamespacedName - Targets []*ClusterTarget + Configs []*NamespacedName `json:"configs"` + Targets []*ClusterTarget `json:"targets"` } // Validation the response of the validation @@ -612,7 +612,7 @@ func (k *kubeConfigFactory) GetConfig(ctx context.Context, namespace, name strin // CreateOrUpdateConfig create or update the config. // Write the expand config to the target server. -func (k *kubeConfigFactory) CreateOrUpdateConfig(ctx context.Context, i *Config, ns string) error { +func (k *kubeConfigFactory) CreateOrUpdateConfig(ctx context.Context, i *Config, _ string) error { var secret v1.Secret if err := k.cli.Get(ctx, pkgtypes.NamespacedName{Namespace: i.Namespace, Name: i.Name}, &secret); err == nil { if secret.Labels[types.LabelConfigType] != i.Template.Name { diff --git a/pkg/config/provider/provider.go b/pkg/config/provider/provider.go index dd194c7d9..edd3b6317 100644 --- a/pkg/config/provider/provider.go +++ b/pkg/config/provider/provider.go @@ -56,7 +56,7 @@ type Response struct { Message string `json:"message"` } -func (p *provider) Create(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act types.Action) error { +func (p *provider) Create(ctx monitorContext.Context, _ wfContext.Context, v *value.Value, _ types.Action) error { var ccp CreateConfigProperties if err := v.UnmarshalTo(&ccp); err != nil { return ErrRequestInvalid @@ -84,7 +84,7 @@ func (p *provider) Create(ctx monitorContext.Context, wfCtx wfContext.Context, v return p.factory.CreateOrUpdateConfig(ctx.GetContext(), configItem, ccp.Namespace) } -func (p *provider) Read(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act types.Action) error { +func (p *provider) Read(ctx monitorContext.Context, _ wfContext.Context, v *value.Value, _ types.Action) error { var nn config.NamespacedName if err := v.UnmarshalTo(&nn); err != nil { return ErrRequestInvalid @@ -96,7 +96,7 @@ func (p *provider) Read(ctx monitorContext.Context, wfCtx wfContext.Context, v * return v.FillObject(content, "config") } -func (p *provider) List(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act types.Action) error { +func (p *provider) List(ctx monitorContext.Context, _ wfContext.Context, v *value.Value, _ types.Action) error { template, err := v.GetString("template") if err != nil { return ErrRequestInvalid @@ -125,7 +125,7 @@ func (p *provider) List(ctx monitorContext.Context, wfCtx wfContext.Context, v * return v.FillObject(contents, "configs") } -func (p *provider) Delete(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act types.Action) error { +func (p *provider) Delete(ctx monitorContext.Context, _ wfContext.Context, v *value.Value, _ types.Action) error { var nn config.NamespacedName if err := v.UnmarshalTo(&nn); err != nil { return errors.New("the request is in valid") diff --git a/pkg/controller/core.oam.dev/v1beta1/application/application_controller.go b/pkg/controller/core.oam.dev/v1beta1/application/application_controller.go index cb7a7772c..a4a625e1a 100644 --- a/pkg/controller/core.oam.dev/v1beta1/application/application_controller.go +++ b/pkg/controller/core.oam.dev/v1beta1/application/application_controller.go @@ -539,49 +539,49 @@ func (r *Reconciler) SetupWithManager(mgr ctrl.Manager) error { // filter the changes in workflow status // let workflow handle its reconcile UpdateFunc: func(e ctrlEvent.UpdateEvent) bool { - new, isNewApp := e.ObjectNew.DeepCopyObject().(*v1beta1.Application) + newApp, isNewApp := e.ObjectNew.DeepCopyObject().(*v1beta1.Application) old, isOldApp := e.ObjectOld.DeepCopyObject().(*v1beta1.Application) if !isNewApp || !isOldApp { return filterManagedFieldChangesUpdate(e) } // We think this event is triggered by resync - if reflect.DeepEqual(old, new) { + if reflect.DeepEqual(old, newApp) { return true } // filter managedFields changes old.ManagedFields = nil - new.ManagedFields = nil + newApp.ManagedFields = nil // if the generation is changed, return true to let the controller handle it - if old.Generation != new.Generation { + if old.Generation != newApp.Generation { return true } // filter the events triggered by initial application status - if new.Status.Phase == common.ApplicationRendering || (old.Status.Phase == common.ApplicationRendering && new.Status.Phase == common.ApplicationRunningWorkflow) { + if newApp.Status.Phase == common.ApplicationRendering || (old.Status.Phase == common.ApplicationRendering && newApp.Status.Phase == common.ApplicationRunningWorkflow) { return false } // ignore the changes in workflow status - if old.Status.Workflow != nil && new.Status.Workflow != nil { + if old.Status.Workflow != nil && newApp.Status.Workflow != nil { // only workflow execution will change the status.workflow // let workflow backoff to requeue the event - new.Status.Workflow.Steps = old.Status.Workflow.Steps - new.Status.Workflow.ContextBackend = old.Status.Workflow.ContextBackend - new.Status.Workflow.Message = old.Status.Workflow.Message - new.Status.Workflow.EndTime = old.Status.Workflow.EndTime + newApp.Status.Workflow.Steps = old.Status.Workflow.Steps + newApp.Status.Workflow.ContextBackend = old.Status.Workflow.ContextBackend + newApp.Status.Workflow.Message = old.Status.Workflow.Message + newApp.Status.Workflow.EndTime = old.Status.Workflow.EndTime } // appliedResources and Services will be changed during the execution of workflow // once the resources is added, the managed fields will also be changed - new.Status.AppliedResources = old.Status.AppliedResources - new.Status.Services = old.Status.Services + newApp.Status.AppliedResources = old.Status.AppliedResources + newApp.Status.Services = old.Status.Services // the resource version will be changed if the object is changed // ignore this change and let reflect.DeepEqual to compare the rest of the object - new.ResourceVersion = old.ResourceVersion - return !reflect.DeepEqual(old, new) + newApp.ResourceVersion = old.ResourceVersion + return !reflect.DeepEqual(old, newApp) }, CreateFunc: func(e ctrlEvent.CreateEvent) bool { return true @@ -616,14 +616,14 @@ func updateObservedGeneration(app *v1beta1.Application) { // For old k8s version like 1.18.5, the managedField could always update and cause infinite loop // this function helps filter those events and prevent infinite loop func filterManagedFieldChangesUpdate(e ctrlEvent.UpdateEvent) bool { - new, isNewRT := e.ObjectNew.DeepCopyObject().(*v1beta1.ResourceTracker) + newTracker, isNewRT := e.ObjectNew.DeepCopyObject().(*v1beta1.ResourceTracker) old, isOldRT := e.ObjectOld.DeepCopyObject().(*v1beta1.ResourceTracker) if !isNewRT || !isOldRT { return true } - new.ManagedFields = old.ManagedFields - new.ResourceVersion = old.ResourceVersion - return !reflect.DeepEqual(new, old) + newTracker.ManagedFields = old.ManagedFields + newTracker.ResourceVersion = old.ResourceVersion + return !reflect.DeepEqual(newTracker, old) } func findObjectForResourceTracker(rt client.Object) []reconcile.Request { diff --git a/pkg/controller/core.oam.dev/v1beta1/application/revision.go b/pkg/controller/core.oam.dev/v1beta1/application/revision.go index 78e2bc405..2ab5e7b26 100644 --- a/pkg/controller/core.oam.dev/v1beta1/application/revision.go +++ b/pkg/controller/core.oam.dev/v1beta1/application/revision.go @@ -250,7 +250,8 @@ func ComputeAppRevisionHash(appRevision *v1beta1.ApplicationRevision) (string, e return "", err } for key, wd := range appRevision.Spec.WorkloadDefinitions { - hash, err := utils.ComputeSpecHash(&wd.Spec) + wdCopy := wd + hash, err := utils.ComputeSpecHash(&wdCopy.Spec) if err != nil { return "", err } @@ -271,7 +272,8 @@ func ComputeAppRevisionHash(appRevision *v1beta1.ApplicationRevision) (string, e revHash.TraitDefinitionHash[key] = hash } for key, pd := range appRevision.Spec.PolicyDefinitions { - hash, err := utils.ComputeSpecHash(&pd.Spec) + pdCopy := pd + hash, err := utils.ComputeSpecHash(&pdCopy.Spec) if err != nil { return "", err } diff --git a/pkg/definition/gen_sdk/gen_sdk.go b/pkg/definition/gen_sdk/gen_sdk.go index 566c3043c..8f507451c 100644 --- a/pkg/definition/gen_sdk/gen_sdk.go +++ b/pkg/definition/gen_sdk/gen_sdk.go @@ -463,6 +463,9 @@ func (g *Generator) completeOpenAPISchema(doc *openapi3.T) { // GenerateCode will call openapi-generator to generate code and modify it func (g *Generator) GenerateCode() (err error) { tmpFile, err := os.CreateTemp("", g.meta.name+"-*.json") + if err != nil { + return err + } _, err = tmpFile.Write(g.openapiSchema) if err != nil { return errors.Wrap(err, "write openapi schema to temporary file") diff --git a/pkg/oam/mock/mocks.go b/pkg/oam/mock/mocks.go index 76b32848a..4ac55469c 100644 --- a/pkg/oam/mock/mocks.go +++ b/pkg/oam/mock/mocks.go @@ -44,7 +44,9 @@ func (m *Conditioned) GetCondition(ct condition.ConditionType) condition.Conditi } // ManagedResourceReferencer is a mock that implements ManagedResourceReferencer interface. -type ManagedResourceReferencer struct{ Ref *corev1.ObjectReference } +type ManagedResourceReferencer struct { + Ref *corev1.ObjectReference `json:"ref"` +} // SetResourceReference sets the ResourceReference. func (m *ManagedResourceReferencer) SetResourceReference(r *corev1.ObjectReference) { m.Ref = r } @@ -53,7 +55,9 @@ func (m *ManagedResourceReferencer) SetResourceReference(r *corev1.ObjectReferen func (m *ManagedResourceReferencer) GetResourceReference() *corev1.ObjectReference { return m.Ref } // A WorkloadReferencer references an OAM Workload type. -type WorkloadReferencer struct{ Ref corev1.ObjectReference } +type WorkloadReferencer struct { + Ref corev1.ObjectReference `json:"ref"` +} // GetWorkloadReference gets the WorkloadReference. func (w *WorkloadReferencer) GetWorkloadReference() corev1.ObjectReference { @@ -201,7 +205,7 @@ type LocalSecretReference struct { // LocalConnectionSecretWriterTo is a mock that implements LocalConnectionSecretWriterTo interface. type LocalConnectionSecretWriterTo struct { - Ref *LocalSecretReference + Ref *LocalSecretReference `json:"local_secret_ref"` } // SetWriteConnectionSecretToReference sets the WriteConnectionSecretToReference. diff --git a/pkg/policy/override.go b/pkg/policy/override.go index 9fa77d4f5..e17acb368 100644 --- a/pkg/policy/override.go +++ b/pkg/policy/override.go @@ -31,7 +31,7 @@ import ( ) // ParseOverridePolicyRelatedDefinitions get definitions inside override policy -func ParseOverridePolicyRelatedDefinitions(ctx context.Context, cli client.Client, app *v1beta1.Application, policy v1beta1.AppPolicy) (compDefs []*v1beta1.ComponentDefinition, traitDefs []*v1beta1.TraitDefinition, err error) { +func ParseOverridePolicyRelatedDefinitions(ctx context.Context, cli client.Client, _ *v1beta1.Application, policy v1beta1.AppPolicy) (compDefs []*v1beta1.ComponentDefinition, traitDefs []*v1beta1.TraitDefinition, err error) { if policy.Properties == nil { return compDefs, traitDefs, fmt.Errorf("override policy %s must not have empty properties", policy.Name) } diff --git a/pkg/resourcekeeper/admission.go b/pkg/resourcekeeper/admission.go index 2448837ff..10f34702a 100644 --- a/pkg/resourcekeeper/admission.go +++ b/pkg/resourcekeeper/admission.go @@ -58,7 +58,7 @@ type NamespaceAdmissionHandler struct { } // Validate check if cross namespace is available -func (h *NamespaceAdmissionHandler) Validate(ctx context.Context, manifests []*unstructured.Unstructured) error { +func (h *NamespaceAdmissionHandler) Validate(_ context.Context, manifests []*unstructured.Unstructured) error { if !AllowCrossNamespaceResource { for _, manifest := range manifests { if manifest.GetNamespace() != h.app.GetNamespace() { @@ -77,7 +77,7 @@ type ResourceTypeAdmissionHandler struct { } // Validate check if resource type is valid -func (h *ResourceTypeAdmissionHandler) Validate(ctx context.Context, manifests []*unstructured.Unstructured) error { +func (h *ResourceTypeAdmissionHandler) Validate(_ context.Context, manifests []*unstructured.Unstructured) error { if AllowResourceTypes != "" { if !h.initialized { h.initialized = true diff --git a/pkg/utils/helm/repo_index.go b/pkg/utils/helm/repo_index.go index 21e743883..135bd8bfb 100644 --- a/pkg/utils/helm/repo_index.go +++ b/pkg/utils/helm/repo_index.go @@ -33,7 +33,7 @@ import ( const IndexYaml = "index.yaml" // LoadRepoIndex load helm repo index -func LoadRepoIndex(ctx context.Context, u string, cred *RepoCredential) (*helmrepo.IndexFile, error) { +func LoadRepoIndex(_ context.Context, u string, cred *RepoCredential) (*helmrepo.IndexFile, error) { if !strings.HasSuffix(u, "/") { u = fmt.Sprintf("%s/%s", u, IndexYaml) diff --git a/pkg/utils/k8s.go b/pkg/utils/k8s.go index 1bf25acda..98c154135 100644 --- a/pkg/utils/k8s.go +++ b/pkg/utils/k8s.go @@ -399,9 +399,8 @@ func contains(object *runtime.Object, fieldSelector fields.Selector) bool { if (negative && fmt.Sprintf("%v", result.String()) != value) || (!negative && fmt.Sprintf("%v", result.String()) == value) { continue - } else { - return false } + return false } return true } diff --git a/pkg/utils/parse.go b/pkg/utils/parse.go index 2735e1d09..7cfe91855 100644 --- a/pkg/utils/parse.go +++ b/pkg/utils/parse.go @@ -42,6 +42,9 @@ const TypeGitlab = "gitlab" // TypeUnknown represents parse failed const TypeUnknown = "unknown" +// errInvalidFormatMsg with the message to be returned in case of a format error. +const errInvalidFormatMsg = "invalid format " + // Content contains different type of content needed when building Registry type Content struct { OssContent @@ -103,12 +106,12 @@ func Parse(addr string) (string, *Content, error) { // 1. https://github.com///tree// // 2. https://github.com/// if len(l) < 3 { - return "", nil, errors.New("invalid format " + addr) + return "", nil, errors.New(errInvalidFormatMsg + addr) } if l[2] == "tree" { // https://github.com///tree// if len(l) < 5 { - return "", nil, errors.New("invalid format " + addr) + return "", nil, errors.New(errInvalidFormatMsg + addr) } return TypeGithub, &Content{ GithubContent: GithubContent{ @@ -131,7 +134,7 @@ func Parse(addr string) (string, *Content, error) { nil case "api.github.com": if len(l) != 5 { - return "", nil, errors.New("invalid format " + addr) + return "", nil, errors.New(errInvalidFormatMsg + addr) } //https://api.github.com/repos///contents/ return TypeGithub, &Content{ @@ -148,13 +151,13 @@ func Parse(addr string) (string, *Content, error) { // 1. https://gitee.com///tree// // 2. https://gitee.com/// if len(l) < 3 { - return "", nil, errors.New("invalid format " + addr) + return "", nil, errors.New(errInvalidFormatMsg + addr) } switch l[2] { case "tree": // https://gitee.com///tree// if len(l) < 5 { - return "", nil, errors.New("invalid format " + addr) + return "", nil, errors.New(errInvalidFormatMsg + addr) } return TypeGitee, &Content{ GiteeContent: GiteeContent{ diff --git a/pkg/velaql/context.go b/pkg/velaql/context.go index ba807ae43..4f32df91a 100644 --- a/pkg/velaql/context.go +++ b/pkg/velaql/context.go @@ -60,34 +60,34 @@ func (c ViewContext) GetStore() *corev1.ConfigMap { } // GetMutableValue get mutable data from workflow context. -func (c ViewContext) GetMutableValue(paths ...string) string { +func (c ViewContext) GetMutableValue(_ ...string) string { return "" } // SetMutableValue set mutable data in workflow context config map. -func (c ViewContext) SetMutableValue(data string, paths ...string) { +func (c ViewContext) SetMutableValue(_ string, _ ...string) { } // IncreaseCountValueInMemory increase count in workflow context memory store. -func (c ViewContext) IncreaseCountValueInMemory(paths ...string) int { +func (c ViewContext) IncreaseCountValueInMemory(_ ...string) int { return 0 } // SetValueInMemory set data in workflow context memory store. -func (c ViewContext) SetValueInMemory(data interface{}, paths ...string) { +func (c ViewContext) SetValueInMemory(_ interface{}, _ ...string) { } // GetValueInMemory get data in workflow context memory store. -func (c ViewContext) GetValueInMemory(paths ...string) (interface{}, bool) { +func (c ViewContext) GetValueInMemory(_ ...string) (interface{}, bool) { return "", true } // DeleteValueInMemory delete data in workflow context memory store. -func (c ViewContext) DeleteValueInMemory(paths ...string) { +func (c ViewContext) DeleteValueInMemory(_ ...string) { } // DeleteMutableValue delete mutable data in workflow context. -func (c ViewContext) DeleteMutableValue(paths ...string) { +func (c ViewContext) DeleteMutableValue(_ ...string) { } // Commit the workflow context and persist it's content. diff --git a/pkg/velaql/providers/query/endpoint.go b/pkg/velaql/providers/query/endpoint.go index 1edeab278..183b4e4f9 100644 --- a/pkg/velaql/providers/query/endpoint.go +++ b/pkg/velaql/providers/query/endpoint.go @@ -48,7 +48,7 @@ import ( // CollectServiceEndpoints generator service endpoints is available for common component type, // such as webservice or helm // it can not support the cloud service component currently -func (h *provider) CollectServiceEndpoints(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act types.Action) error { +func (h *provider) CollectServiceEndpoints(ctx monitorContext.Context, _ wfContext.Context, v *value.Value, _ types.Action) error { val, err := v.LookupValue("app") if err != nil { return err diff --git a/pkg/velaql/providers/query/handler.go b/pkg/velaql/providers/query/handler.go index 061d60db5..7ee251827 100644 --- a/pkg/velaql/providers/query/handler.go +++ b/pkg/velaql/providers/query/handler.go @@ -92,7 +92,7 @@ type FilterOption struct { } // ListResourcesInApp lists CRs created by Application, this provider queries the object data. -func (h *provider) ListResourcesInApp(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act types.Action) error { +func (h *provider) ListResourcesInApp(ctx monitorContext.Context, _ wfContext.Context, v *value.Value, _ types.Action) error { val, err := v.LookupValue("app") if err != nil { return err @@ -113,7 +113,7 @@ func (h *provider) ListResourcesInApp(ctx monitorContext.Context, wfCtx wfContex } // ListAppliedResources list applied resource from tracker, this provider only queries the metadata. -func (h *provider) ListAppliedResources(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act types.Action) error { +func (h *provider) ListAppliedResources(ctx monitorContext.Context, _ wfContext.Context, v *value.Value, _ types.Action) error { val, err := v.LookupValue("app") if err != nil { return err @@ -138,7 +138,7 @@ func (h *provider) ListAppliedResources(ctx monitorContext.Context, wfCtx wfCont return fillQueryResult(v, appResList, "list") } -func (h *provider) CollectResources(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act types.Action) error { +func (h *provider) CollectResources(ctx monitorContext.Context, _ wfContext.Context, v *value.Value, _ types.Action) error { val, err := v.LookupValue("app") if err != nil { return err @@ -180,7 +180,7 @@ func (h *provider) CollectResources(ctx monitorContext.Context, wfCtx wfContext. return fillQueryResult(v, resources, "list") } -func (h *provider) SearchEvents(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act types.Action) error { +func (h *provider) SearchEvents(ctx monitorContext.Context, _ wfContext.Context, v *value.Value, _ types.Action) error { val, err := v.LookupValue("value") if err != nil { return err @@ -209,7 +209,7 @@ func (h *provider) SearchEvents(ctx monitorContext.Context, wfCtx wfContext.Cont return fillQueryResult(v, eventList.Items, "list") } -func (h *provider) CollectLogsInPod(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act types.Action) error { +func (h *provider) CollectLogsInPod(ctx monitorContext.Context, _ wfContext.Context, v *value.Value, _ types.Action) error { cluster, err := v.GetString("cluster") if err != nil { return errors.Wrapf(err, "invalid cluster") diff --git a/pkg/velaql/view.go b/pkg/velaql/view.go index 06567c0d3..ec711d263 100644 --- a/pkg/velaql/view.go +++ b/pkg/velaql/view.go @@ -159,7 +159,7 @@ func (handler *ViewHandler) QueryView(ctx context.Context, qv QueryView) (*value return viewCtx.GetVar(qv.Export) } -func (handler *ViewHandler) dispatch(ctx context.Context, cluster string, owner string, manifests ...*unstructured.Unstructured) error { +func (handler *ViewHandler) dispatch(ctx context.Context, cluster string, _ string, manifests ...*unstructured.Unstructured) error { ctx = multicluster.ContextWithClusterName(ctx, cluster) applicator := apply.NewAPIApplicator(handler.cli) for _, manifest := range manifests { @@ -170,7 +170,7 @@ func (handler *ViewHandler) dispatch(ctx context.Context, cluster string, owner return nil } -func (handler *ViewHandler) delete(ctx context.Context, cluster string, owner string, manifest *unstructured.Unstructured) error { +func (handler *ViewHandler) delete(ctx context.Context, _ string, _ string, manifest *unstructured.Unstructured) error { return handler.cli.Delete(ctx, manifest) } diff --git a/pkg/webhook/core.oam.dev/v1beta1/application/mutating_handler.go b/pkg/webhook/core.oam.dev/v1beta1/application/mutating_handler.go index bf900f2ca..8bb5a5e87 100644 --- a/pkg/webhook/core.oam.dev/v1beta1/application/mutating_handler.go +++ b/pkg/webhook/core.oam.dev/v1beta1/application/mutating_handler.go @@ -49,7 +49,7 @@ var _ admission.Handler = &MutatingHandler{} type appMutator func(ctx context.Context, req admission.Request, oldApp *v1beta1.Application, newApp *v1beta1.Application) (bool, error) -func (h *MutatingHandler) handleIdentity(ctx context.Context, req admission.Request, _ *v1beta1.Application, app *v1beta1.Application) (bool, error) { +func (h *MutatingHandler) handleIdentity(_ context.Context, req admission.Request, _ *v1beta1.Application, app *v1beta1.Application) (bool, error) { if !utilfeature.DefaultMutableFeatureGate.Enabled(features.AuthenticateApplication) { return false, nil } @@ -66,7 +66,7 @@ func (h *MutatingHandler) handleIdentity(ctx context.Context, req admission.Requ return true, nil } -func (h *MutatingHandler) handleWorkflow(ctx context.Context, req admission.Request, _ *v1beta1.Application, app *v1beta1.Application) (modified bool, err error) { +func (h *MutatingHandler) handleWorkflow(_ context.Context, _ admission.Request, _ *v1beta1.Application, app *v1beta1.Application) (modified bool, err error) { if app.Spec.Workflow != nil { for i, step := range app.Spec.Workflow.Steps { if step.Name == "" { @@ -84,7 +84,7 @@ func (h *MutatingHandler) handleWorkflow(ctx context.Context, req admission.Requ return modified, nil } -func (h *MutatingHandler) handleSharding(ctx context.Context, req admission.Request, oldApp *v1beta1.Application, newApp *v1beta1.Application) (bool, error) { +func (h *MutatingHandler) handleSharding(_ context.Context, _ admission.Request, oldApp *v1beta1.Application, newApp *v1beta1.Application) (bool, error) { if sharding.EnableSharding && !utilfeature.DefaultMutableFeatureGate.Enabled(features.DisableWebhookAutoSchedule) { oid, scheduled := sharding.GetScheduledShardID(oldApp) _, newScheduled := sharding.GetScheduledShardID(newApp) diff --git a/pkg/webhook/core.oam.dev/v1beta1/application/validation.go b/pkg/webhook/core.oam.dev/v1beta1/application/validation.go index 6472fb501..bb191b7d0 100644 --- a/pkg/webhook/core.oam.dev/v1beta1/application/validation.go +++ b/pkg/webhook/core.oam.dev/v1beta1/application/validation.go @@ -33,7 +33,7 @@ import ( ) // ValidateWorkflow validates the Application workflow -func (h *ValidatingHandler) ValidateWorkflow(ctx context.Context, app *v1beta1.Application) field.ErrorList { +func (h *ValidatingHandler) ValidateWorkflow(_ context.Context, app *v1beta1.Application) field.ErrorList { var errs field.ErrorList if app.Spec.Workflow != nil { stepName := make(map[string]interface{}) @@ -117,7 +117,7 @@ func (h *ValidatingHandler) ValidateCreate(ctx context.Context, app *v1beta1.App } // ValidateUpdate validates the Application on update -func (h *ValidatingHandler) ValidateUpdate(ctx context.Context, newApp, oldApp *v1beta1.Application) field.ErrorList { +func (h *ValidatingHandler) ValidateUpdate(ctx context.Context, newApp, _ *v1beta1.Application) field.ErrorList { // check if the newApp is valid errs := h.ValidateCreate(ctx, newApp) // TODO: add more validating diff --git a/pkg/webhook/core.oam.dev/v1beta1/componentdefinition/mutating_handler.go b/pkg/webhook/core.oam.dev/v1beta1/componentdefinition/mutating_handler.go index e300bfee7..6a1918366 100644 --- a/pkg/webhook/core.oam.dev/v1beta1/componentdefinition/mutating_handler.go +++ b/pkg/webhook/core.oam.dev/v1beta1/componentdefinition/mutating_handler.go @@ -49,7 +49,7 @@ type MutatingHandler struct { var _ admission.Handler = &MutatingHandler{} // Handle handles admission requests. -func (h *MutatingHandler) Handle(ctx context.Context, req admission.Request) admission.Response { +func (h *MutatingHandler) Handle(_ context.Context, req admission.Request) admission.Response { obj := &v1beta1.ComponentDefinition{} err := h.Decoder.Decode(req, obj) diff --git a/pkg/webhook/core.oam.dev/v1beta1/traitdefinition/validating_handler.go b/pkg/webhook/core.oam.dev/v1beta1/traitdefinition/validating_handler.go index a42bb8ce1..5cbbee464 100644 --- a/pkg/webhook/core.oam.dev/v1beta1/traitdefinition/validating_handler.go +++ b/pkg/webhook/core.oam.dev/v1beta1/traitdefinition/validating_handler.go @@ -128,7 +128,7 @@ func (h *ValidatingHandler) InjectDecoder(d *admission.Decoder) error { } // RegisterValidatingHandler will register TraitDefinition validation to webhook -func RegisterValidatingHandler(mgr manager.Manager, args controller.Args) { +func RegisterValidatingHandler(mgr manager.Manager, _ controller.Args) { server := mgr.GetWebhookServer() server.Register("/validating-core-oam-dev-v1alpha2-traitdefinitions", &webhook.Admission{Handler: &ValidatingHandler{ Validators: []TraitDefValidator{ @@ -150,11 +150,11 @@ func ValidateDefinitionReference(_ context.Context, td v1beta1.TraitDefinition) if len(td.Spec.Reference.Name) > 0 { return nil } - cap, err := appfile.ConvertTemplateJSON2Object(td.Name, td.Spec.Extension, td.Spec.Schematic) + capability, err := appfile.ConvertTemplateJSON2Object(td.Name, td.Spec.Extension, td.Spec.Schematic) if err != nil { return errors.WithMessage(err, errValidateDefRef) } - if cap.CueTemplate == "" { + if capability.CueTemplate == "" { return errors.New(failInfoDefRefOmitted) } diff --git a/pkg/workflow/providers/multicluster/multicluster.go b/pkg/workflow/providers/multicluster/multicluster.go index aefee0594..f4ff7c3d8 100644 --- a/pkg/workflow/providers/multicluster/multicluster.go +++ b/pkg/workflow/providers/multicluster/multicluster.go @@ -50,7 +50,7 @@ type provider struct { // MakePlacementDecisions // Deprecated -func (p *provider) MakePlacementDecisions(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act wfTypes.Action) error { +func (p *provider) MakePlacementDecisions(ctx monitorContext.Context, _ wfContext.Context, v *value.Value, _ wfTypes.Action) error { policy, err := v.GetString("inputs", "policyName") if err != nil { return err @@ -108,7 +108,7 @@ func (p *provider) MakePlacementDecisions(ctx monitorContext.Context, wfCtx wfCo // PatchApplication // Deprecated -func (p *provider) PatchApplication(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act wfTypes.Action) error { +func (p *provider) PatchApplication(_ monitorContext.Context, _ wfContext.Context, v *value.Value, _ wfTypes.Action) error { env, err := v.GetString("inputs", "envName") if err != nil { return err @@ -138,7 +138,7 @@ func (p *provider) PatchApplication(ctx monitorContext.Context, wfCtx wfContext. return v.FillObject(newApp, "outputs") } -func (p *provider) ListClusters(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act wfTypes.Action) error { +func (p *provider) ListClusters(ctx monitorContext.Context, _ wfContext.Context, v *value.Value, _ wfTypes.Action) error { secrets, err := multicluster.ListExistingClusterSecrets(ctx, p.Client) if err != nil { return err @@ -169,7 +169,7 @@ func (p *provider) Deploy(ctx monitorContext.Context, _ wfContext.Context, v *va return nil } -func (p *provider) GetPlacementsFromTopologyPolicies(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act wfTypes.Action) error { +func (p *provider) GetPlacementsFromTopologyPolicies(ctx monitorContext.Context, _ wfContext.Context, v *value.Value, _ wfTypes.Action) error { policyNames, err := v.GetStringSlice("policies") if err != nil { return err diff --git a/pkg/workflow/providers/oam/apply.go b/pkg/workflow/providers/oam/apply.go index 69e47cf1f..34e8bacbd 100644 --- a/pkg/workflow/providers/oam/apply.go +++ b/pkg/workflow/providers/oam/apply.go @@ -64,7 +64,7 @@ type provider struct { } // RenderComponent render component -func (p *provider) RenderComponent(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act wfTypes.Action) error { +func (p *provider) RenderComponent(ctx monitorContext.Context, _ wfContext.Context, v *value.Value, _ wfTypes.Action) error { comp, patcher, clusterName, overrideNamespace, err := lookUpCompInfo(v) if err != nil { return err @@ -93,7 +93,7 @@ func (p *provider) RenderComponent(ctx monitorContext.Context, wfCtx wfContext.C } // ApplyComponent apply component. -func (p *provider) ApplyComponent(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act wfTypes.Action) error { +func (p *provider) ApplyComponent(ctx monitorContext.Context, _ wfContext.Context, v *value.Value, act wfTypes.Action) error { comp, patcher, clusterName, overrideNamespace, err := lookUpCompInfo(v) if err != nil { return err @@ -155,7 +155,7 @@ func lookUpCompInfo(v *value.Value) (*common.ApplicationComponent, *value.Value, } // LoadComponent load component describe info in application. -func (p *provider) LoadComponent(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act wfTypes.Action) error { +func (p *provider) LoadComponent(ctx monitorContext.Context, _ wfContext.Context, v *value.Value, _ wfTypes.Action) error { app := &v1beta1.Application{} // if specify `app`, use specified application otherwise use default application from provider appSettings, err := v.LookupValue("app") @@ -200,7 +200,7 @@ func (p *provider) LoadComponent(ctx monitorContext.Context, wfCtx wfContext.Con } // LoadComponentInOrder load component describe info in application output will be a list with order defined in application. -func (p *provider) LoadComponentInOrder(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act wfTypes.Action) error { +func (p *provider) LoadComponentInOrder(ctx monitorContext.Context, _ wfContext.Context, v *value.Value, _ wfTypes.Action) error { app := &v1beta1.Application{} // if specify `app`, use specified application otherwise use default application from provider appSettings, err := v.LookupValue("app") @@ -232,7 +232,7 @@ func (p *provider) LoadComponentInOrder(ctx monitorContext.Context, wfCtx wfCont } // LoadPolicies load policy describe info in application. -func (p *provider) LoadPolicies(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act wfTypes.Action) error { +func (p *provider) LoadPolicies(_ monitorContext.Context, _ wfContext.Context, v *value.Value, _ wfTypes.Action) error { for _, po := range p.app.Spec.Policies { if err := v.FillObject(po, "value", po.Name); err != nil { return err diff --git a/pkg/workflow/providers/terraform/terraform.go b/pkg/workflow/providers/terraform/terraform.go index 9c7e03a2f..8b897e13f 100644 --- a/pkg/workflow/providers/terraform/terraform.go +++ b/pkg/workflow/providers/terraform/terraform.go @@ -40,7 +40,7 @@ type provider struct { renderer oamProvider.WorkloadRenderer } -func (p *provider) LoadTerraformComponents(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act wfTypes.Action) error { +func (p *provider) LoadTerraformComponents(ctx monitorContext.Context, _ wfContext.Context, v *value.Value, _ wfTypes.Action) error { var components []common.ApplicationComponent for _, comp := range p.app.Spec.Components { wl, err := p.renderer(ctx, comp) @@ -55,7 +55,7 @@ func (p *provider) LoadTerraformComponents(ctx monitorContext.Context, wfCtx wfC return v.FillObject(components, "outputs", "components") } -func (p *provider) GetConnectionStatus(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act wfTypes.Action) error { +func (p *provider) GetConnectionStatus(_ monitorContext.Context, _ wfContext.Context, v *value.Value, _ wfTypes.Action) error { componentName, err := v.GetString("inputs", "componentName") if err != nil { return errors.Wrapf(err, "failed to get component name") diff --git a/pkg/workflow/providers/time/date.go b/pkg/workflow/providers/time/date.go index 52fcb9fe0..a26379195 100644 --- a/pkg/workflow/providers/time/date.go +++ b/pkg/workflow/providers/time/date.go @@ -33,7 +33,7 @@ const ( type provider struct { } -func (h *provider) Timestamp(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act types.Action) error { +func (h *provider) Timestamp(_ monitorContext.Context, _ wfContext.Context, v *value.Value, _ types.Action) error { date, err := v.GetString("date") if err != nil { return err @@ -52,7 +52,7 @@ func (h *provider) Timestamp(ctx monitorContext.Context, wfCtx wfContext.Context return v.FillObject(t.Unix(), "timestamp") } -func (h *provider) Date(ctx monitorContext.Context, wfCtx wfContext.Context, v *value.Value, act types.Action) error { +func (h *provider) Date(_ monitorContext.Context, _ wfContext.Context, v *value.Value, _ types.Action) error { timestamp, err := v.GetInt64("timestamp") if err != nil { return err diff --git a/references/cli/addon-registry.go b/references/cli/addon-registry.go index 22e046815..ecf7890ad 100644 --- a/references/cli/addon-registry.go +++ b/references/cli/addon-registry.go @@ -66,7 +66,7 @@ func NewAddonRegistryCommand(c common.Args, ioStreams cmdutil.IOStreams) *cobra. } // NewAddAddonRegistryCommand return an addon registry create command -func NewAddAddonRegistryCommand(c common.Args, ioStreams cmdutil.IOStreams) *cobra.Command { +func NewAddAddonRegistryCommand(c common.Args, _ cmdutil.IOStreams) *cobra.Command { cmd := &cobra.Command{ Use: "add", Short: "Add an addon registry.", @@ -103,7 +103,7 @@ add a specified gitlab registry: vela addon registry add my-repo --type gitlab - } // NewGetAddonRegistryCommand return an addon registry get command -func NewGetAddonRegistryCommand(c common.Args, ioStreams cmdutil.IOStreams) *cobra.Command { +func NewGetAddonRegistryCommand(c common.Args, _ cmdutil.IOStreams) *cobra.Command { return &cobra.Command{ Use: "get", Short: "Get an addon registry.", @@ -124,7 +124,7 @@ func NewGetAddonRegistryCommand(c common.Args, ioStreams cmdutil.IOStreams) *cob } // NewListAddonRegistryCommand return an addon registry list command -func NewListAddonRegistryCommand(c common.Args, ioStreams cmdutil.IOStreams) *cobra.Command { +func NewListAddonRegistryCommand(c common.Args, _ cmdutil.IOStreams) *cobra.Command { return &cobra.Command{ Use: "list", Short: "List addon registries.", @@ -140,7 +140,7 @@ func NewListAddonRegistryCommand(c common.Args, ioStreams cmdutil.IOStreams) *co } // NewUpdateAddonRegistryCommand return an addon registry update command -func NewUpdateAddonRegistryCommand(c common.Args, ioStreams cmdutil.IOStreams) *cobra.Command { +func NewUpdateAddonRegistryCommand(c common.Args, _ cmdutil.IOStreams) *cobra.Command { cmd := &cobra.Command{ Use: "update", Short: "Update an addon registry.", @@ -162,7 +162,7 @@ func NewUpdateAddonRegistryCommand(c common.Args, ioStreams cmdutil.IOStreams) * } // NewDeleteAddonRegistryCommand return an addon registry delete command -func NewDeleteAddonRegistryCommand(c common.Args, ioStreams cmdutil.IOStreams) *cobra.Command { +func NewDeleteAddonRegistryCommand(c common.Args, _ cmdutil.IOStreams) *cobra.Command { return &cobra.Command{ Use: "delete", Short: "Delete an addon registry", diff --git a/references/cli/addon.go b/references/cli/addon.go index af08ce846..30f1ce949 100644 --- a/references/cli/addon.go +++ b/references/cli/addon.go @@ -232,7 +232,7 @@ func NewAddonEnableCommand(c common.Args, ioStream cmdutil.IOStreams) *cobra.Com } // AdditionalEndpointPrinter will print endpoints -func AdditionalEndpointPrinter(ctx context.Context, c common.Args, k8sClient client.Client, name, info string, isUpgrade bool) { +func AdditionalEndpointPrinter(ctx context.Context, c common.Args, _ client.Client, name, info string, _ bool) { err := printAppEndpoints(ctx, addonutil.Addon2AppName(name), types.DefaultKubeVelaNS, Filter{}, c, true) if err != nil { fmt.Println("Get application endpoints error:", err) @@ -361,7 +361,7 @@ func parseAddonArgsToMap(args []string) (map[string]interface{}, error) { } // NewAddonDisableCommand create addon disable command -func NewAddonDisableCommand(c common.Args, ioStream cmdutil.IOStreams) *cobra.Command { +func NewAddonDisableCommand(c common.Args, _ cmdutil.IOStreams) *cobra.Command { cmd := &cobra.Command{ Use: "disable", Aliases: []string{"uninstall"}, @@ -1180,7 +1180,7 @@ func transClusters(cstr string) []interface{} { } // NewAddonPackageCommand create addon package command -func NewAddonPackageCommand(c common.Args) *cobra.Command { +func NewAddonPackageCommand(_ common.Args) *cobra.Command { cmd := &cobra.Command{ Use: "package", Short: "package an addon directory", diff --git a/references/cli/common.go b/references/cli/common.go index 92fbc69f4..16adc8b60 100644 --- a/references/cli/common.go +++ b/references/cli/common.go @@ -53,6 +53,12 @@ const ( FlagNamespace = "namespace" // FlagInteractive command flag to specify the use of interactive process FlagInteractive = "interactive" + // CUEExtension with the expected extension for a CUE file. + CUEExtension = ".cue" + // YAMLExtension with the expected extension for a YAML file. + YAMLExtension = ".yaml" + // YMLExtension with an alternative extension for a YAML file as .yml. + YMLExtension = ".yml" ) func addNamespaceAndEnvArg(cmd *cobra.Command) { diff --git a/references/cli/def.go b/references/cli/def.go index 93dd7e97e..01a932053 100644 --- a/references/cli/def.go +++ b/references/cli/def.go @@ -166,7 +166,7 @@ func buildTemplateFromYAML(templateYAML string, def *pkgdef.Definition) error { } // NewDefinitionInitCommand create the `vela def init` command to help user initialize a definition locally -func NewDefinitionInitCommand(c common.Args) *cobra.Command { +func NewDefinitionInitCommand(_ common.Args) *cobra.Command { cmd := &cobra.Command{ Use: "init DEF_NAME", Short: "Init a new definition", @@ -688,7 +688,7 @@ func NewDefinitionEditCommand(c common.Args) *cobra.Command { } } filename := fmt.Sprintf("vela-def-%d", time.Now().UnixNano()) - tempFilePath := filepath.Join(os.TempDir(), filename+".cue") + tempFilePath := filepath.Join(os.TempDir(), filename+CUEExtension) if err := os.WriteFile(tempFilePath, []byte(cueString), 0600); err != nil { return errors.Wrapf(err, "failed to write temporary file") } @@ -821,12 +821,12 @@ func NewDefinitionRenderCommand(c common.Args) *cobra.Command { err := filepath.Walk(args[0], func(path string, info os.FileInfo, err error) error { filename := filepath.Base(path) fileSuffix := filepath.Ext(path) - if fileSuffix != ".cue" { + if fileSuffix != CUEExtension { return nil } inputFilenames = append(inputFilenames, path) if output != "" { - outputFilenames = append(outputFilenames, filepath.Join(output, strings.ReplaceAll(filename, ".cue", ".yaml"))) + outputFilenames = append(outputFilenames, filepath.Join(output, strings.ReplaceAll(filename, CUEExtension, YAMLExtension))) } else { outputFilenames = append(outputFilenames, "") } @@ -920,7 +920,7 @@ func defApplyOne(ctx context.Context, c common.Args, namespace, defpath string, def := pkgdef.Definition{Unstructured: unstructured.Unstructured{}} switch { - case strings.HasSuffix(defpath, ".yaml") || strings.HasSuffix(defpath, ".yml"): + case strings.HasSuffix(defpath, YAMLExtension) || strings.HasSuffix(defpath, YMLExtension): // In this case, it's not in cue format, it's a yaml if err = def.FromYAML(defBytes); err != nil { return "", errors.Wrapf(err, "failed to parse YAML to definition") @@ -1218,7 +1218,7 @@ func NewDefinitionGenDocCommand(_ common.Args, streams util.IOStreams) *cobra.Co readers := make([]io.Reader, 0, len(args)) for _, arg := range args { - if !strings.HasSuffix(arg, ".cue") { + if !strings.HasSuffix(arg, CUEExtension) { return fmt.Errorf("invalid file %s, must be a cue file", arg) } diff --git a/references/cli/dryrun.go b/references/cli/dryrun.go index 9f943dd73..c3d66268c 100644 --- a/references/cli/dryrun.go +++ b/references/cli/dryrun.go @@ -189,7 +189,7 @@ func DryRunApplication(cmdOption *DryRunCmdOptions, c common.Args, namespace str func readObj(path string) (*unstructured.Unstructured, error) { switch { - case strings.HasSuffix(path, ".cue"): + case strings.HasSuffix(path, CUEExtension): def := pkgdef.Definition{Unstructured: unstructured.Unstructured{}} defBytes, err := os.ReadFile(filepath.Clean(path)) if err != nil { @@ -238,7 +238,7 @@ func ReadDefinitionsFromFile(path string, io cmdutil.IOStreams) ([]*unstructured return nil } fileType := filepath.Ext(e.Name()) - if fileType != ".yaml" && fileType != ".yml" && fileType != ".cue" { + if fileType != YAMLExtension && fileType != YMLExtension && fileType != CUEExtension { return nil } obj, err := readObj(path) @@ -262,7 +262,7 @@ func readApplicationFromFile(filename string) (*corev1beta1.Application, error) fileType := filepath.Ext(filename) switch fileType { - case ".yaml", ".yml": + case YAMLExtension, YMLExtension: fileContent, err = yaml.YAMLToJSON(fileContent) if err != nil { return nil, err @@ -288,7 +288,7 @@ func readApplicationFromFiles(cmdOption *DryRunCmdOptions, buff *bytes.Buffer) ( fileType := filepath.Ext(filename) switch fileType { - case ".yaml", ".yml": + case YAMLExtension, YMLExtension: // only support one object in one yaml file fileContent, err = yaml.YAMLToJSON(fileContent) if err != nil { @@ -344,7 +344,7 @@ func readApplicationFromFiles(cmdOption *DryRunCmdOptions, buff *bytes.Buffer) ( if !cmdOption.MergeStandaloneFiles { if wf != nil && ((app.Spec.Workflow != nil && app.Spec.Workflow.Ref != wf.Name) || app.Spec.Workflow == nil) { - buff.WriteString(fmt.Sprintf("WARNING: workflow %s not referenced by application\n\n", wf.Name)) + fmt.Fprintf(buff, "WARNING: workflow %s not referenced by application\n\n", wf.Name) } } else { if wf != nil { @@ -362,7 +362,7 @@ func readApplicationFromFiles(cmdOption *DryRunCmdOptions, buff *bytes.Buffer) ( for _, policy := range policies { // check standalone policies if _, exist := policyNameMap[policy.Name]; !exist && !cmdOption.MergeStandaloneFiles { - buff.WriteString(fmt.Sprintf("WARNING: policy %s not referenced by application\n\n", policy.Name)) + fmt.Fprintf(buff, "WARNING: policy %s not referenced by application\n\n", policy.Name) continue } app.Spec.Policies = append(app.Spec.Policies, corev1beta1.AppPolicy{ diff --git a/references/cli/kube.go b/references/cli/kube.go index 6ecfe7862..dcb22e2ae 100644 --- a/references/cli/kube.go +++ b/references/cli/kube.go @@ -126,7 +126,7 @@ func (opt *KubeApplyOptions) Validate() error { for _, fileData := range opt.filesData { switch { - case strings.HasSuffix(fileData.Path, ".yaml"), strings.HasSuffix(fileData.Path, ".yml"): + case strings.HasSuffix(fileData.Path, YAMLExtension), strings.HasSuffix(fileData.Path, YMLExtension): decoder := yaml.NewDecoder(bytes.NewReader(fileData.Data)) for { obj := &unstructured.Unstructured{Object: map[string]interface{}{}} diff --git a/references/cli/show.go b/references/cli/show.go index 26cb95622..58e34990a 100644 --- a/references/cli/show.go +++ b/references/cli/show.go @@ -285,7 +285,7 @@ func generateSideBar(capabilities []types.Capability, docsPath string) error { } for _, c := range components { - if _, err := f.WriteString(fmt.Sprintf(" - [%s](%s/%s.md)\n", c, types.TypeComponentDefinition, c)); err != nil { + if _, err := fmt.Fprintf(f, " - [%s](%s/%s.md)\n", c, types.TypeComponentDefinition, c); err != nil { return err } } @@ -293,7 +293,7 @@ func generateSideBar(capabilities []types.Capability, docsPath string) error { return err } for _, t := range traits { - if _, err := f.WriteString(fmt.Sprintf(" - [%s](%s/%s.md)\n", t, types.TypeTrait, t)); err != nil { + if _, err := fmt.Fprintf(f, " - [%s](%s/%s.md)\n", t, types.TypeTrait, t); err != nil { return err } } @@ -301,7 +301,7 @@ func generateSideBar(capabilities []types.Capability, docsPath string) error { return err } for _, t := range workflowSteps { - if _, err := f.WriteString(fmt.Sprintf(" - [%s](%s/%s.md)\n", t, types.TypeWorkflowStep, t)); err != nil { + if _, err := fmt.Fprintf(f, " - [%s](%s/%s.md)\n", t, types.TypeWorkflowStep, t); err != nil { return err } } @@ -310,7 +310,7 @@ func generateSideBar(capabilities []types.Capability, docsPath string) error { return err } for _, t := range policies { - if _, err := f.WriteString(fmt.Sprintf(" - [%s](%s/%s.md)\n", t, types.TypePolicy, t)); err != nil { + if _, err := fmt.Fprintf(f, " - [%s](%s/%s.md)\n", t, types.TypePolicy, t); err != nil { return err } } @@ -392,7 +392,7 @@ func generateREADME(capabilities []types.Capability, docsPath string) error { } for _, w := range workloads { - if _, err := f.WriteString(fmt.Sprintf(" - [%s](%s/%s.md)\n", w, types.TypeComponentDefinition, w)); err != nil { + if _, err := fmt.Fprintf(f, " - [%s](%s/%s.md)\n", w, types.TypeComponentDefinition, w); err != nil { return err } } @@ -401,7 +401,7 @@ func generateREADME(capabilities []types.Capability, docsPath string) error { } for _, t := range traits { - if _, err := f.WriteString(fmt.Sprintf(" - [%s](%s/%s.md)\n", t, types.TypeTrait, t)); err != nil { + if _, err := fmt.Fprintf(f, " - [%s](%s/%s.md)\n", t, types.TypeTrait, t); err != nil { return err } } @@ -410,7 +410,7 @@ func generateREADME(capabilities []types.Capability, docsPath string) error { return err } for _, t := range workflowSteps { - if _, err := f.WriteString(fmt.Sprintf(" - [%s](%s/%s.md)\n", t, types.TypeWorkflowStep, t)); err != nil { + if _, err := fmt.Fprintf(f, " - [%s](%s/%s.md)\n", t, types.TypeWorkflowStep, t); err != nil { return err } } @@ -419,7 +419,7 @@ func generateREADME(capabilities []types.Capability, docsPath string) error { return err } for _, t := range policies { - if _, err := f.WriteString(fmt.Sprintf(" - [%s](%s/%s.md)\n", t, types.TypePolicy, t)); err != nil { + if _, err := fmt.Fprintf(f, " - [%s](%s/%s.md)\n", t, types.TypePolicy, t); err != nil { return err } } diff --git a/references/cli/top.go b/references/cli/top.go index 848223b40..ff33fa8f3 100644 --- a/references/cli/top.go +++ b/references/cli/top.go @@ -32,7 +32,7 @@ import ( ) // NewTopCommand will create command `top` for displaying the platform overview -func NewTopCommand(c common.Args, order string, ioStreams cmdutil.IOStreams) *cobra.Command { +func NewTopCommand(c common.Args, order string, _ cmdutil.IOStreams) *cobra.Command { cmd := &cobra.Command{ Use: "top", Short: "Launch UI to display the platform overview.", diff --git a/references/cli/top/component/app_test.go b/references/cli/top/component/app_test.go index 62642f63a..169ef53d7 100644 --- a/references/cli/top/component/app_test.go +++ b/references/cli/top/component/app_test.go @@ -28,44 +28,44 @@ import ( var themeConfig = config.ThemeConfig{ Info: struct { - Title config.Color - Text config.Color + Title config.Color `yaml:"title"` + Text config.Color `yaml:"text"` }{ Title: "royalblue", Text: "lightgray", }, Menu: struct { - Description config.Color - Key config.Color + Description config.Color `yaml:"description"` + Key config.Color `yaml:"key"` }{ Description: "gray", Key: "royalblue", }, Logo: struct { - Text config.Color + Text config.Color `yaml:"text"` }{ Text: "royalblue", }, Crumbs: struct { - Foreground config.Color - Background config.Color + Foreground config.Color `yaml:"foreground"` + Background config.Color `yaml:"background"` }{ Foreground: "white", Background: "royalblue", }, Border: struct { - App config.Color - Table config.Color + App config.Color `yaml:"app"` + Table config.Color `yaml:"table"` }{ App: "black", Table: "lightgray", }, Table: struct { - Title config.Color - Header config.Color - Body config.Color - CursorBg config.Color - CursorFg config.Color + Title config.Color `yaml:"title"` + Header config.Color `yaml:"header"` + Body config.Color `yaml:"body"` + CursorBg config.Color `yaml:"cursorbg"` + CursorFg config.Color `yaml:"cursorfg"` }{ Title: "royalblue", Header: "white", @@ -74,13 +74,13 @@ var themeConfig = config.ThemeConfig{ CursorFg: "black", }, Status: struct { - Starting config.Color - Healthy config.Color - UnHealthy config.Color - Waiting config.Color - Succeeded config.Color - Failed config.Color - Unknown config.Color + Starting config.Color `yaml:"starting"` + Healthy config.Color `yaml:"healthy"` + UnHealthy config.Color `yaml:"unhealthy"` + Waiting config.Color `yaml:"waiting"` + Succeeded config.Color `yaml:"succeeded"` + Failed config.Color `yaml:"failed"` + Unknown config.Color `yaml:"unknown"` }{ Starting: "blue", Healthy: "green", @@ -91,22 +91,22 @@ var themeConfig = config.ThemeConfig{ Unknown: "gray", }, Yaml: struct { - Key config.Color - Colon config.Color - Value config.Color + Key config.Color `yaml:"key"` + Colon config.Color `yaml:"colon"` + Value config.Color `yaml:"value"` }{ Key: "#d33582", Colon: "lightgray", Value: "#839495", }, Topology: struct { - Line config.Color - App config.Color - Workflow config.Color - Component config.Color - Policy config.Color - Trait config.Color - Kind config.Color + Line config.Color `yaml:"line"` + App config.Color `yaml:"app"` + Workflow config.Color `yaml:"workflow"` + Component config.Color `yaml:"component"` + Policy config.Color `yaml:"policy"` + Trait config.Color `yaml:"trait"` + Kind config.Color `yaml:"kind"` }{ Line: "cadetblue", App: "red", diff --git a/references/cli/top/config/color.go b/references/cli/top/config/color.go index a80a347ad..9f0a59aec 100644 --- a/references/cli/top/config/color.go +++ b/references/cli/top/config/color.go @@ -33,54 +33,54 @@ type Color string // ThemeConfig is the theme config. type ThemeConfig struct { Info struct { - Title Color - Text Color - } + Title Color `yaml:"title"` + Text Color `yaml:"text"` + } `yaml:"info"` Menu struct { - Description Color - Key Color - } + Description Color `yaml:"description"` + Key Color `yaml:"key"` + } `yaml:"menu"` Logo struct { - Text Color - } + Text Color `yaml:"text"` + } `yaml:"logo"` Crumbs struct { - Foreground Color - Background Color - } + Foreground Color `yaml:"foreground"` + Background Color `yaml:"background"` + } `yaml:"crumbs"` Border struct { - App Color - Table Color - } + App Color `yaml:"app"` + Table Color `yaml:"table"` + } `yaml:"border"` Table struct { - Title Color - Header Color - Body Color - CursorBg Color - CursorFg Color - } + Title Color `yaml:"title"` + Header Color `yaml:"header"` + Body Color `yaml:"body"` + CursorBg Color `yaml:"cursorbg"` + CursorFg Color `yaml:"cursorfg"` + } `yaml:"table"` Status struct { - Starting Color - Healthy Color - UnHealthy Color - Waiting Color - Succeeded Color - Failed Color - Unknown Color - } + Starting Color `yaml:"starting"` + Healthy Color `yaml:"healthy"` + UnHealthy Color `yaml:"unhealthy"` + Waiting Color `yaml:"waiting"` + Succeeded Color `yaml:"succeeded"` + Failed Color `yaml:"failed"` + Unknown Color `yaml:"unknown"` + } `yaml:"status"` Yaml struct { - Key Color - Colon Color - Value Color - } + Key Color `yaml:"key"` + Colon Color `yaml:"colon"` + Value Color `yaml:"value"` + } `yaml:"yaml"` Topology struct { - Line Color - App Color - Workflow Color - Component Color - Policy Color - Trait Color - Kind Color - } + Line Color `yaml:"line"` + App Color `yaml:"app"` + Workflow Color `yaml:"workflow"` + Component Color `yaml:"component"` + Policy Color `yaml:"policy"` + Trait Color `yaml:"trait"` + Kind Color `yaml:"kind"` + } `yaml:"topology"` } var ( @@ -188,44 +188,44 @@ func LoadThemeConfig() *ThemeConfig { func defaultTheme() *ThemeConfig { return &ThemeConfig{ Info: struct { - Title Color - Text Color + Title Color `yaml:"title"` + Text Color `yaml:"text"` }{ Title: "royalblue", Text: "lightgray", }, Menu: struct { - Description Color - Key Color + Description Color `yaml:"description"` + Key Color `yaml:"key"` }{ Description: "gray", Key: "royalblue", }, Logo: struct { - Text Color + Text Color `yaml:"text"` }{ Text: "royalblue", }, Crumbs: struct { - Foreground Color - Background Color + Foreground Color `yaml:"foreground"` + Background Color `yaml:"background"` }{ Foreground: "white", Background: "royalblue", }, Border: struct { - App Color - Table Color + App Color `yaml:"app"` + Table Color `yaml:"table"` }{ App: "black", Table: "lightgray", }, Table: struct { - Title Color - Header Color - Body Color - CursorBg Color - CursorFg Color + Title Color `yaml:"title"` + Header Color `yaml:"header"` + Body Color `yaml:"body"` + CursorBg Color `yaml:"cursorbg"` + CursorFg Color `yaml:"cursorfg"` }{ Title: "royalblue", Header: "white", @@ -234,22 +234,22 @@ func defaultTheme() *ThemeConfig { CursorFg: "black", }, Yaml: struct { - Key Color - Colon Color - Value Color + Key Color `yaml:"key"` + Colon Color `yaml:"colon"` + Value Color `yaml:"value"` }{ Key: "#d33582", Colon: "lightgray", Value: "#839495", }, Status: struct { - Starting Color - Healthy Color - UnHealthy Color - Waiting Color - Succeeded Color - Failed Color - Unknown Color + Starting Color `yaml:"starting"` + Healthy Color `yaml:"healthy"` + UnHealthy Color `yaml:"unhealthy"` + Waiting Color `yaml:"waiting"` + Succeeded Color `yaml:"succeeded"` + Failed Color `yaml:"failed"` + Unknown Color `yaml:"unknown"` }{ Starting: "blue", Healthy: "green", @@ -260,13 +260,13 @@ func defaultTheme() *ThemeConfig { Unknown: "gray", }, Topology: struct { - Line Color - App Color - Workflow Color - Component Color - Policy Color - Trait Color - Kind Color + Line Color `yaml:"line"` + App Color `yaml:"app"` + Workflow Color `yaml:"workflow"` + Component Color `yaml:"component"` + Policy Color `yaml:"policy"` + Trait Color `yaml:"trait"` + Kind Color `yaml:"kind"` }{ Line: "cadetblue", App: "red", diff --git a/references/cli/top/model/cluster.go b/references/cli/top/model/cluster.go index ad70d596c..b849aa5b0 100644 --- a/references/cli/top/model/cluster.go +++ b/references/cli/top/model/cluster.go @@ -65,18 +65,18 @@ func ListClusters(ctx context.Context, c client.Client) (ClusterList, error) { cluster, err := multicluster.NewClusterClient(c).Get(context.Background(), key) if err != nil { continue - } else { - clusterInfo.alias = cluster.Spec.Alias - clusterInfo.clusterType = string(cluster.Spec.CredentialType) - clusterInfo.endpoint = cluster.Spec.Endpoint - var labels []string - for k, v := range cluster.Labels { - if !strings.HasPrefix(k, config.MetaApiGroupName) { - labels = append(labels, "[blue::]"+k+"="+"[green::]"+v) - } - } - clusterInfo.labels = strings.Join(labels, ",") } + clusterInfo.alias = cluster.Spec.Alias + clusterInfo.clusterType = string(cluster.Spec.CredentialType) + clusterInfo.endpoint = cluster.Spec.Endpoint + var labels []string + for k, v := range cluster.Labels { + if !strings.HasPrefix(k, config.MetaApiGroupName) { + labels = append(labels, "[blue::]"+k+"="+"[green::]"+v) + } + } + clusterInfo.labels = strings.Join(labels, ",") + list = append(list, clusterInfo) } return list, nil diff --git a/references/cli/top/model/resource.go b/references/cli/top/model/resource.go index b3f187835..a411f5a2c 100644 --- a/references/cli/top/model/resource.go +++ b/references/cli/top/model/resource.go @@ -68,7 +68,7 @@ func collectResource(ctx context.Context, c client.Client, opt query.Option) ([] var resources = make([]unstructured.Unstructured, 0) for _, res := range appResList { if res.ResourceTree != nil { - resources = append(resources, sonLeafResource(*res, res.ResourceTree, opt.Filter.Kind, opt.Filter.APIVersion)...) + resources = append(resources, sonLeafResource(res.ResourceTree, opt.Filter.Kind, opt.Filter.APIVersion)...) } if (opt.Filter.Kind == "" && opt.Filter.APIVersion == "") || (res.Kind == opt.Filter.Kind && res.APIVersion == opt.Filter.APIVersion) { var object unstructured.Unstructured @@ -82,11 +82,11 @@ func collectResource(ctx context.Context, c client.Client, opt query.Option) ([] return resources, nil } -func sonLeafResource(res querytypes.AppliedResource, node *querytypes.ResourceTreeNode, kind string, apiVersion string) []unstructured.Unstructured { +func sonLeafResource(node *querytypes.ResourceTreeNode, kind string, apiVersion string) []unstructured.Unstructured { objects := make([]unstructured.Unstructured, 0) if node.LeafNodes != nil { for i := 0; i < len(node.LeafNodes); i++ { - objects = append(objects, sonLeafResource(res, node.LeafNodes[i], kind, apiVersion)...) + objects = append(objects, sonLeafResource(node.LeafNodes[i], kind, apiVersion)...) } } if (kind == "" && apiVersion == "") || (node.Kind == kind && node.APIVersion == apiVersion) { diff --git a/references/cli/top/model/resource_test.go b/references/cli/top/model/resource_test.go index 058201bea..080d886d8 100644 --- a/references/cli/top/model/resource_test.go +++ b/references/cli/top/model/resource_test.go @@ -77,7 +77,6 @@ var _ = Describe("test resource", func() { }) func TestSonLeafResource(t *testing.T) { - res := querytypes.AppliedResource{} node := &querytypes.ResourceTreeNode{ LeafNodes: []*querytypes.ResourceTreeNode{ { @@ -85,6 +84,6 @@ func TestSonLeafResource(t *testing.T) { }, }, } - objs := sonLeafResource(res, node, "", "") + objs := sonLeafResource(node, "", "") assert.Equal(t, len(objs), 2) } diff --git a/references/cli/workflow.go b/references/cli/workflow.go index e870d7a3a..1dd7a3f3e 100644 --- a/references/cli/workflow.go +++ b/references/cli/workflow.go @@ -72,7 +72,7 @@ func NewWorkflowCommand(c common.Args, order string, ioStreams cmdutil.IOStreams } // NewWorkflowSuspendCommand create workflow suspend command -func NewWorkflowSuspendCommand(c common.Args, ioStream cmdutil.IOStreams, wargs *WorkflowArgs) *cobra.Command { +func NewWorkflowSuspendCommand(_ common.Args, _ cmdutil.IOStreams, wargs *WorkflowArgs) *cobra.Command { cmd := &cobra.Command{ Use: "suspend", Short: "Suspend a workflow.", @@ -97,7 +97,7 @@ func NewWorkflowSuspendCommand(c common.Args, ioStream cmdutil.IOStreams, wargs } // NewWorkflowResumeCommand create workflow resume command -func NewWorkflowResumeCommand(c common.Args, ioStream cmdutil.IOStreams, wargs *WorkflowArgs) *cobra.Command { +func NewWorkflowResumeCommand(_ common.Args, _ cmdutil.IOStreams, wargs *WorkflowArgs) *cobra.Command { cmd := &cobra.Command{ Use: "resume", Short: "Resume a suspend workflow.", @@ -122,7 +122,7 @@ func NewWorkflowResumeCommand(c common.Args, ioStream cmdutil.IOStreams, wargs * } // NewWorkflowTerminateCommand create workflow terminate command -func NewWorkflowTerminateCommand(c common.Args, ioStream cmdutil.IOStreams, wargs *WorkflowArgs) *cobra.Command { +func NewWorkflowTerminateCommand(_ common.Args, _ cmdutil.IOStreams, wargs *WorkflowArgs) *cobra.Command { cmd := &cobra.Command{ Use: "terminate", Short: "Terminate a workflow.", @@ -143,7 +143,7 @@ func NewWorkflowTerminateCommand(c common.Args, ioStream cmdutil.IOStreams, warg } // NewWorkflowRestartCommand create workflow restart command -func NewWorkflowRestartCommand(c common.Args, ioStream cmdutil.IOStreams, wargs *WorkflowArgs) *cobra.Command { +func NewWorkflowRestartCommand(_ common.Args, _ cmdutil.IOStreams, wargs *WorkflowArgs) *cobra.Command { cmd := &cobra.Command{ Use: "restart", Short: "Restart a workflow.", @@ -167,7 +167,7 @@ func NewWorkflowRestartCommand(c common.Args, ioStream cmdutil.IOStreams, wargs } // NewWorkflowRollbackCommand create workflow rollback command -func NewWorkflowRollbackCommand(c common.Args, ioStream cmdutil.IOStreams, wargs *WorkflowArgs) *cobra.Command { +func NewWorkflowRollbackCommand(_ common.Args, _ cmdutil.IOStreams, wargs *WorkflowArgs) *cobra.Command { cmd := &cobra.Command{ Use: "rollback", Short: "Rollback an application workflow to the latest revision.", @@ -249,7 +249,7 @@ func NewWorkflowDebugCommand(c common.Args, ioStream cmdutil.IOStreams, wargs *W } // NewWorkflowListCommand create workflow list command -func NewWorkflowListCommand(c common.Args, ioStream cmdutil.IOStreams, wargs *WorkflowArgs) *cobra.Command { +func NewWorkflowListCommand(c common.Args, ioStream cmdutil.IOStreams, _ *WorkflowArgs) *cobra.Command { cmd := &cobra.Command{ Use: "list", Short: "List running workflows", diff --git a/references/common/application.go b/references/common/application.go index c133ffe52..6c2e1f30e 100644 --- a/references/common/application.go +++ b/references/common/application.go @@ -284,7 +284,7 @@ func CollectApplicationResource(ctx context.Context, c client.Client, opt query. var resources = make([]unstructured.Unstructured, 0) for _, res := range appResList { if res.ResourceTree != nil { - resources = append(resources, sonLeafResource(*res, res.ResourceTree, opt.Filter.Kind, opt.Filter.APIVersion)...) + resources = append(resources, sonLeafResource(res.ResourceTree, opt.Filter.Kind, opt.Filter.APIVersion)...) } if (opt.Filter.Kind == "" && opt.Filter.APIVersion == "") || (res.Kind == opt.Filter.Kind && res.APIVersion == opt.Filter.APIVersion) { var object unstructured.Unstructured @@ -298,11 +298,11 @@ func CollectApplicationResource(ctx context.Context, c client.Client, opt query. return resources, nil } -func sonLeafResource(res querytypes.AppliedResource, node *querytypes.ResourceTreeNode, kind string, apiVersion string) []unstructured.Unstructured { +func sonLeafResource(node *querytypes.ResourceTreeNode, kind string, apiVersion string) []unstructured.Unstructured { objects := make([]unstructured.Unstructured, 0) if node.LeafNodes != nil { for i := 0; i < len(node.LeafNodes); i++ { - objects = append(objects, sonLeafResource(res, node.LeafNodes[i], kind, apiVersion)...) + objects = append(objects, sonLeafResource(node.LeafNodes[i], kind, apiVersion)...) } } if (kind == "" && apiVersion == "") || (node.Kind == kind && node.APIVersion == apiVersion) { diff --git a/references/cuegen/convert.go b/references/cuegen/convert.go index 07d8730d0..57c18c096 100644 --- a/references/cuegen/convert.go +++ b/references/cuegen/convert.go @@ -31,7 +31,7 @@ import ( func (g *Generator) convertDecls(x *goast.GenDecl) (decls []Decl, _ error) { // TODO(iyear): currently only support 'type' if x.Tok != gotoken.TYPE { - return + return decls, nil } for _, spec := range x.Specs { diff --git a/references/docgen/console.go b/references/docgen/console.go index e764bb94c..441a7a9d6 100644 --- a/references/docgen/console.go +++ b/references/docgen/console.go @@ -125,7 +125,7 @@ func (ref *ConsoleReference) GenerateTerraformCapabilityProperties(capability ty } // Show will show capability reference in console -func (ref *ConsoleReference) Show(ctx context.Context, c common.Args, ioStreams cmdutil.IOStreams, capabilityName string, ns string, rev int64) error { +func (ref *ConsoleReference) Show(ctx context.Context, c common.Args, ioStreams cmdutil.IOStreams, capabilityName string, ns string, _ int64) error { caps, err := ref.getCapabilities(ctx, c) if err != nil { return err diff --git a/references/docgen/markdown.go b/references/docgen/markdown.go index c5db39dc7..d6bca9a9e 100644 --- a/references/docgen/markdown.go +++ b/references/docgen/markdown.go @@ -139,7 +139,7 @@ func (ref *MarkdownReference) CreateMarkdown(ctx context.Context, caps []types.C // GenerateMarkdownForCap will generate markdown for one capability // nolint:gocyclo -func (ref *MarkdownReference) GenerateMarkdownForCap(ctx context.Context, c types.Capability, pd *packages.PackageDiscover, containSuffix bool) (string, error) { +func (ref *MarkdownReference) GenerateMarkdownForCap(_ context.Context, c types.Capability, pd *packages.PackageDiscover, containSuffix bool) (string, error) { var ( description string base string diff --git a/references/docgen/provider.go b/references/docgen/provider.go index 56c41b355..16815b879 100644 --- a/references/docgen/provider.go +++ b/references/docgen/provider.go @@ -100,7 +100,7 @@ func GenerateProviderMarkdown(provider io.Reader, w io.Writer) error { } // header - docs.WriteString(fmt.Sprintf("## %s\n", iter.Label())) + fmt.Fprintf(docs, "## %s\n", iter.Label()) doc, _, err := ref.parseParameters("", item.LookupPath(cue.ParsePath(paramsKey)), "*Params*", 0, true) if err != nil { @@ -116,7 +116,7 @@ func GenerateProviderMarkdown(provider io.Reader, w io.Writer) error { } doc := bytes.NewBuffer(nil) - doc.WriteString(fmt.Sprintf("# %s\n\n", pkg)) // package name header + fmt.Fprintf(doc, "# %s\n\n", pkg) // package name header doc.Write(docs.Bytes()) doc.WriteString("------\n\n") // footer