diff --git a/.golangci.yaml b/.golangci.yaml index c952308576..2f7c742c1c 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -154,7 +154,7 @@ linters-settings: disabled: false # Functions or methods with unused parameters can be a symptom of an unfinished refactoring or a bug. - name: unused-parameter - disabled: true + disabled: false # Since Go 1.18, interface{} has an alias: any. This rule proposes to replace instances of interface{} with any. - name: use-any disabled: false diff --git a/applicationset/controllers/applicationset_controller_test.go b/applicationset/controllers/applicationset_controller_test.go index 480222b8dd..efa17b2217 100644 --- a/applicationset/controllers/applicationset_controller_test.go +++ b/applicationset/controllers/applicationset_controller_test.go @@ -1055,7 +1055,7 @@ func TestCreateOrUpdateInCluster(t *testing.T) { } client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(initObjs...).WithIndex(&v1alpha1.Application{}, ".metadata.controller", appControllerIndexer).Build() - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() r := ApplicationSetReconciler{ Client: client, @@ -1163,7 +1163,7 @@ func TestRemoveFinalizerOnInvalidDestination_FinalizerTypes(t *testing.T) { objects := append([]runtime.Object{}, secret) kubeclientset := kubefake.NewSimpleClientset(objects...) - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() argodb := db.NewDB("argocd", settings.NewSettingsManager(context.TODO(), kubeclientset, "argocd"), kubeclientset) @@ -1322,7 +1322,7 @@ func TestRemoveFinalizerOnInvalidDestination_DestinationTypes(t *testing.T) { objects := append([]runtime.Object{}, secret) kubeclientset := kubefake.NewSimpleClientset(objects...) - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() argodb := db.NewDB("argocd", settings.NewSettingsManager(context.TODO(), kubeclientset, "argocd"), kubeclientset) @@ -1409,7 +1409,7 @@ func TestRemoveOwnerReferencesOnDeleteAppSet(t *testing.T) { initObjs := []crtclient.Object{&app, &appSet} client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(initObjs...).WithIndex(&v1alpha1.Application{}, ".metadata.controller", appControllerIndexer).Build() - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() r := ApplicationSetReconciler{ Client: client, @@ -1608,7 +1608,7 @@ func TestCreateApplications(t *testing.T) { } client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(initObjs...).WithIndex(&v1alpha1.Application{}, ".metadata.controller", appControllerIndexer).Build() - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() r := ApplicationSetReconciler{ Client: client, @@ -1750,7 +1750,7 @@ func TestDeleteInCluster(t *testing.T) { } client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(initObjs...).WithIndex(&v1alpha1.Application{}, ".metadata.controller", appControllerIndexer).Build() - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() r := ApplicationSetReconciler{ Client: client, @@ -1796,7 +1796,7 @@ func TestGetMinRequeueAfter(t *testing.T) { require.NoError(t, err) client := fake.NewClientBuilder().WithScheme(scheme).Build() - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() generator := v1alpha1.ApplicationSetGenerator{ List: &v1alpha1.ListGenerator{}, @@ -1867,7 +1867,7 @@ func TestRequeueGeneratorFails(t *testing.T) { generatorMock.On("GenerateParams", &generator, mock.AnythingOfType("*v1alpha1.ApplicationSet"), mock.Anything). Return([]map[string]any{}, errors.New("Simulated error generating params that could be related to an external service/API call")) - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() r := ApplicationSetReconciler{ Client: client, @@ -1919,7 +1919,7 @@ func TestValidateGeneratedApplications(t *testing.T) { } client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(myProject).Build() - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() // Test a subset of the validations that 'validateGeneratedApplications' performs for _, cc := range []struct { @@ -2123,7 +2123,7 @@ func TestReconcilerValidationProjectErrorBehaviour(t *testing.T) { kubeclientset := kubefake.NewSimpleClientset() client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&appSet, &project).WithStatusSubresource(&appSet).WithIndex(&v1alpha1.Application{}, ".metadata.controller", appControllerIndexer).Build() - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() argodb := db.NewDB("argocd", settings.NewSettingsManager(context.TODO(), kubeclientset, "argocd"), kubeclientset) @@ -2322,7 +2322,7 @@ func TestSetApplicationSetStatusCondition(t *testing.T) { for _, testCase := range testCases { client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&testCase.appset).WithIndex(&v1alpha1.Application{}, ".metadata.controller", appControllerIndexer).WithStatusSubresource(&testCase.appset).Build() - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() argodb := db.NewDB("argocd", settings.NewSettingsManager(context.TODO(), kubeclientset, "argocd"), kubeclientset) @@ -2411,7 +2411,7 @@ func applicationsUpdateSyncPolicyTest(t *testing.T, applicationsSyncPolicy v1alp kubeclientset := kubefake.NewSimpleClientset(objects...) client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&appSet, &defaultProject).WithStatusSubresource(&appSet).WithIndex(&v1alpha1.Application{}, ".metadata.controller", appControllerIndexer).Build() - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() argodb := db.NewDB("argocd", settings.NewSettingsManager(context.TODO(), kubeclientset, "argocd"), kubeclientset) @@ -2587,7 +2587,7 @@ func applicationsDeleteSyncPolicyTest(t *testing.T, applicationsSyncPolicy v1alp kubeclientset := kubefake.NewSimpleClientset(objects...) client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&appSet, &defaultProject).WithStatusSubresource(&appSet).WithIndex(&v1alpha1.Application{}, ".metadata.controller", appControllerIndexer).Build() - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() argodb := db.NewDB("argocd", settings.NewSettingsManager(context.TODO(), kubeclientset, "argocd"), kubeclientset) @@ -2776,7 +2776,7 @@ func TestPolicies(t *testing.T) { } client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&appSet, &defaultProject).WithStatusSubresource(&appSet).WithIndex(&v1alpha1.Application{}, ".metadata.controller", appControllerIndexer).Build() - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() argodb := db.NewDB("argocd", settings.NewSettingsManager(context.TODO(), kubeclientset, "argocd"), kubeclientset) @@ -2935,7 +2935,7 @@ func TestSetApplicationSetApplicationStatus(t *testing.T) { } { t.Run(cc.name, func(t *testing.T) { client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&cc.appSet).WithStatusSubresource(&cc.appSet).Build() - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() argodb := db.NewDB("argocd", settings.NewSettingsManager(context.TODO(), kubeclientset, "argocd"), kubeclientset) @@ -2966,7 +2966,7 @@ func TestBuildAppDependencyList(t *testing.T) { require.NoError(t, err) client := fake.NewClientBuilder().WithScheme(scheme).Build() - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() for _, cc := range []struct { name string @@ -3722,7 +3722,7 @@ func TestBuildAppSyncMap(t *testing.T) { require.NoError(t, err) client := fake.NewClientBuilder().WithScheme(scheme).Build() - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() for _, cc := range []struct { name string @@ -5312,7 +5312,7 @@ func TestUpdateApplicationSetApplicationStatus(t *testing.T) { kubeclientset := kubefake.NewSimpleClientset([]runtime.Object{}...) client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&cc.appSet).WithStatusSubresource(&cc.appSet).Build() - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() argodb := db.NewDB("argocd", settings.NewSettingsManager(context.TODO(), kubeclientset, "argocd"), kubeclientset) @@ -6062,7 +6062,7 @@ func TestUpdateApplicationSetApplicationStatusProgress(t *testing.T) { kubeclientset := kubefake.NewSimpleClientset([]runtime.Object{}...) client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&cc.appSet).WithStatusSubresource(&cc.appSet).Build() - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() argodb := db.NewDB("argocd", settings.NewSettingsManager(context.TODO(), kubeclientset, "argocd"), kubeclientset) @@ -6274,7 +6274,7 @@ func TestUpdateResourceStatus(t *testing.T) { kubeclientset := kubefake.NewSimpleClientset([]runtime.Object{}...) client := fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(&cc.appSet).WithObjects(&cc.appSet).Build() - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() argodb := db.NewDB("argocd", settings.NewSettingsManager(context.TODO(), kubeclientset, "argocd"), kubeclientset) @@ -6365,7 +6365,7 @@ func TestResourceStatusAreOrdered(t *testing.T) { kubeclientset := kubefake.NewSimpleClientset([]runtime.Object{}...) client := fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(&cc.appSet).WithObjects(&cc.appSet).Build() - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() argodb := db.NewDB("argocd", settings.NewSettingsManager(context.TODO(), kubeclientset, "argocd"), kubeclientset) diff --git a/applicationset/controllers/requeue_after_test.go b/applicationset/controllers/requeue_after_test.go index 39b3f580ae..6d7b4ef925 100644 --- a/applicationset/controllers/requeue_after_test.go +++ b/applicationset/controllers/requeue_after_test.go @@ -90,7 +90,7 @@ func TestRequeueAfter(t *testing.T) { } client := fake.NewClientBuilder().WithScheme(scheme).Build() - metrics := appsetmetrics.NewFakeAppsetMetrics(client) + metrics := appsetmetrics.NewFakeAppsetMetrics() r := ApplicationSetReconciler{ Client: client, Scheme: scheme, diff --git a/applicationset/generators/list.go b/applicationset/generators/list.go index 7ef4c73ce2..b3cb0ffae3 100644 --- a/applicationset/generators/list.go +++ b/applicationset/generators/list.go @@ -21,7 +21,7 @@ func NewListGenerator() Generator { return g } -func (g *ListGenerator) GetRequeueAfter(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator) time.Duration { +func (g *ListGenerator) GetRequeueAfter(_ *argoprojiov1alpha1.ApplicationSetGenerator) time.Duration { return NoRequeueAfter } diff --git a/applicationset/generators/plugin.go b/applicationset/generators/plugin.go index 8525474ebb..bdf66f76ea 100644 --- a/applicationset/generators/plugin.go +++ b/applicationset/generators/plugin.go @@ -106,7 +106,7 @@ func (g *PluginGenerator) getPluginFromGenerator(ctx context.Context, appSetName } } - pluginClient, err := plugin.NewPluginService(ctx, appSetName, cm["baseUrl"], token, requestTimeout) + pluginClient, err := plugin.NewPluginService(appSetName, cm["baseUrl"], token, requestTimeout) if err != nil { return nil, fmt.Errorf("error initializing plugin client: %w", err) } diff --git a/applicationset/generators/pull_request.go b/applicationset/generators/pull_request.go index fb9c46ee0f..ffc0b7ddf6 100644 --- a/applicationset/generators/pull_request.go +++ b/applicationset/generators/pull_request.go @@ -144,7 +144,7 @@ func (g *PullRequestGenerator) selectServiceProvider(ctx context.Context, genera if err != nil { return nil, fmt.Errorf("error fetching Secret token: %w", err) } - return pullrequest.NewGitLabService(ctx, token, providerConfig.API, providerConfig.Project, providerConfig.Labels, providerConfig.PullRequestState, g.scmRootCAPath, providerConfig.Insecure, caCerts) + return pullrequest.NewGitLabService(token, providerConfig.API, providerConfig.Project, providerConfig.Labels, providerConfig.PullRequestState, g.scmRootCAPath, providerConfig.Insecure, caCerts) } if generatorConfig.Gitea != nil { providerConfig := generatorConfig.Gitea @@ -152,7 +152,7 @@ func (g *PullRequestGenerator) selectServiceProvider(ctx context.Context, genera if err != nil { return nil, fmt.Errorf("error fetching Secret token: %w", err) } - return pullrequest.NewGiteaService(ctx, token, providerConfig.API, providerConfig.Owner, providerConfig.Repo, providerConfig.Insecure) + return pullrequest.NewGiteaService(token, providerConfig.API, providerConfig.Owner, providerConfig.Repo, providerConfig.Insecure) } if generatorConfig.BitbucketServer != nil { providerConfig := generatorConfig.BitbucketServer @@ -204,7 +204,7 @@ func (g *PullRequestGenerator) selectServiceProvider(ctx context.Context, genera if err != nil { return nil, fmt.Errorf("error fetching Secret token: %w", err) } - return pullrequest.NewAzureDevOpsService(ctx, token, providerConfig.API, providerConfig.Organization, providerConfig.Project, providerConfig.Repo, providerConfig.Labels) + return pullrequest.NewAzureDevOpsService(token, providerConfig.API, providerConfig.Organization, providerConfig.Project, providerConfig.Repo, providerConfig.Labels) } return nil, errors.New("no Pull Request provider implementation configured") } diff --git a/applicationset/generators/scm_provider.go b/applicationset/generators/scm_provider.go index 3bbc8664c7..15663eae30 100644 --- a/applicationset/generators/scm_provider.go +++ b/applicationset/generators/scm_provider.go @@ -160,7 +160,7 @@ func (g *SCMProviderGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha if err != nil { return nil, fmt.Errorf("error fetching Gitlab token: %w", err) } - provider, err = scm_provider.NewGitlabProvider(ctx, providerConfig.Group, token, providerConfig.API, providerConfig.AllBranches, providerConfig.IncludeSubgroups, providerConfig.WillIncludeSharedProjects(), providerConfig.Insecure, g.scmRootCAPath, providerConfig.Topic, caCerts) + provider, err = scm_provider.NewGitlabProvider(providerConfig.Group, token, providerConfig.API, providerConfig.AllBranches, providerConfig.IncludeSubgroups, providerConfig.WillIncludeSharedProjects(), providerConfig.Insecure, g.scmRootCAPath, providerConfig.Topic, caCerts) if err != nil { return nil, fmt.Errorf("error initializing Gitlab service: %w", err) } @@ -169,7 +169,7 @@ func (g *SCMProviderGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha if err != nil { return nil, fmt.Errorf("error fetching Gitea token: %w", err) } - provider, err = scm_provider.NewGiteaProvider(ctx, providerConfig.Gitea.Owner, token, providerConfig.Gitea.API, providerConfig.Gitea.AllBranches, providerConfig.Gitea.Insecure) + provider, err = scm_provider.NewGiteaProvider(providerConfig.Gitea.Owner, token, providerConfig.Gitea.API, providerConfig.Gitea.AllBranches, providerConfig.Gitea.Insecure) if err != nil { return nil, fmt.Errorf("error initializing Gitea service: %w", err) } @@ -206,7 +206,7 @@ func (g *SCMProviderGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha if err != nil { return nil, fmt.Errorf("error fetching Azure Devops access token: %w", err) } - provider, err = scm_provider.NewAzureDevOpsProvider(ctx, token, providerConfig.AzureDevOps.Organization, providerConfig.AzureDevOps.API, providerConfig.AzureDevOps.TeamProject, providerConfig.AzureDevOps.AllBranches) + provider, err = scm_provider.NewAzureDevOpsProvider(token, providerConfig.AzureDevOps.Organization, providerConfig.AzureDevOps.API, providerConfig.AzureDevOps.TeamProject, providerConfig.AzureDevOps.AllBranches) if err != nil { return nil, fmt.Errorf("error initializing Azure Devops service: %w", err) } @@ -215,7 +215,7 @@ func (g *SCMProviderGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha if err != nil { return nil, fmt.Errorf("error fetching Bitbucket cloud appPassword: %w", err) } - provider, err = scm_provider.NewBitBucketCloudProvider(ctx, providerConfig.Bitbucket.Owner, providerConfig.Bitbucket.User, appPassword, providerConfig.Bitbucket.AllBranches) + provider, err = scm_provider.NewBitBucketCloudProvider(providerConfig.Bitbucket.Owner, providerConfig.Bitbucket.User, appPassword, providerConfig.Bitbucket.AllBranches) if err != nil { return nil, fmt.Errorf("error initializing Bitbucket cloud service: %w", err) } diff --git a/applicationset/metrics/fake.go b/applicationset/metrics/fake.go index 9c1d55d2f2..aebddde651 100644 --- a/applicationset/metrics/fake.go +++ b/applicationset/metrics/fake.go @@ -2,11 +2,10 @@ package metrics import ( "github.com/prometheus/client_golang/prometheus" - ctrlclient "sigs.k8s.io/controller-runtime/pkg/client" ) // Fake implementation for testing -func NewFakeAppsetMetrics(client ctrlclient.WithWatch) *ApplicationsetMetrics { +func NewFakeAppsetMetrics() *ApplicationsetMetrics { reconcileHistogram := prometheus.NewHistogramVec( prometheus.HistogramOpts{ Name: "argocd_appset_reconcile", diff --git a/applicationset/services/internal/http/client.go b/applicationset/services/internal/http/client.go index 07e3565eeb..b16bd873e6 100644 --- a/applicationset/services/internal/http/client.go +++ b/applicationset/services/internal/http/client.go @@ -65,7 +65,7 @@ func newClient(baseURL string, options ...ClientOptionFunc) (*Client, error) { return c, nil } -func (c *Client) NewRequest(method, path string, body any, options []ClientOptionFunc) (*http.Request, error) { +func (c *Client) NewRequestWithContext(ctx context.Context, method, path string, body any) (*http.Request, error) { // Make sure the given URL end with a slash if !strings.HasSuffix(c.baseURL, "/") { c.baseURL += "/" @@ -82,7 +82,7 @@ func (c *Client) NewRequest(method, path string, body any, options []ClientOptio } } - req, err := http.NewRequest(method, c.baseURL+path, buf) + req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, buf) if err != nil { return nil, err } @@ -102,7 +102,7 @@ func (c *Client) NewRequest(method, path string, body any, options []ClientOptio return req, nil } -func (c *Client) Do(ctx context.Context, req *http.Request, v any) (*http.Response, error) { +func (c *Client) Do(req *http.Request, v any) (*http.Response, error) { resp, err := c.client.Do(req) if err != nil { return nil, err diff --git a/applicationset/services/internal/http/client_test.go b/applicationset/services/internal/http/client_test.go index 2799b99668..3385f22642 100644 --- a/applicationset/services/internal/http/client_test.go +++ b/applicationset/services/internal/http/client_test.go @@ -15,7 +15,7 @@ import ( ) func TestClient(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) _, err := w.Write([]byte("Hello, World!")) if err != nil { @@ -30,8 +30,6 @@ func TestClient(t *testing.T) { } func TestClientDo(t *testing.T) { - ctx := context.Background() - for _, c := range []struct { name string params map[string]string @@ -48,7 +46,7 @@ func TestClientDo(t *testing.T) { "pkey1": "val1", "pkey2": "val2", }, - fakeServer: httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fakeServer: httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) _, err := w.Write([]byte(`[{ "key1": "val1", @@ -120,12 +118,12 @@ func TestClientDo(t *testing.T) { client, err := NewClient(cc.fakeServer.URL, cc.clientOptionFns...) require.NoError(t, err, "NewClient returned unexpected error") - req, err := client.NewRequest("POST", "", cc.params, nil) + req, err := client.NewRequestWithContext(context.Background(), http.MethodPost, "", cc.params) require.NoError(t, err, "NewRequest returned unexpected error") var data []map[string]any - resp, err := client.Do(ctx, req, &data) + resp, err := client.Do(req, &data) if cc.expectedError != nil { assert.EqualError(t, err, cc.expectedError.Error()) diff --git a/applicationset/services/plugin/plugin_service.go b/applicationset/services/plugin/plugin_service.go index 4064718c94..233f1db401 100644 --- a/applicationset/services/plugin/plugin_service.go +++ b/applicationset/services/plugin/plugin_service.go @@ -34,7 +34,7 @@ type Service struct { appSetName string } -func NewPluginService(ctx context.Context, appSetName string, baseURL string, token string, requestTimeout int) (*Service, error) { +func NewPluginService(appSetName string, baseURL string, token string, requestTimeout int) (*Service, error) { var clientOptionFns []internalhttp.ClientOptionFunc clientOptionFns = append(clientOptionFns, internalhttp.WithToken(token)) @@ -55,14 +55,14 @@ func NewPluginService(ctx context.Context, appSetName string, baseURL string, to } func (p *Service) List(ctx context.Context, parameters v1alpha1.PluginParameters) (*ServiceResponse, error) { - req, err := p.client.NewRequest(http.MethodPost, "api/v1/getparams.execute", ServiceRequest{ApplicationSetName: p.appSetName, Input: v1alpha1.PluginInput{Parameters: parameters}}, nil) + req, err := p.client.NewRequestWithContext(ctx, http.MethodPost, "api/v1/getparams.execute", ServiceRequest{ApplicationSetName: p.appSetName, Input: v1alpha1.PluginInput{Parameters: parameters}}) if err != nil { return nil, fmt.Errorf("NewRequest returned unexpected error: %w", err) } var data ServiceResponse - _, err = p.client.Do(ctx, req, &data) + _, err = p.client.Do(req, &data) if err != nil { return nil, fmt.Errorf("error get api '%s': %w", p.appSetName, err) } diff --git a/applicationset/services/plugin/plugin_service_test.go b/applicationset/services/plugin/plugin_service_test.go index c6e795c403..b5643619e0 100644 --- a/applicationset/services/plugin/plugin_service_test.go +++ b/applicationset/services/plugin/plugin_service_test.go @@ -31,7 +31,7 @@ func TestPlugin(t *testing.T) { ts := httptest.NewServer(handler) defer ts.Close() - client, err := NewPluginService(context.Background(), "plugin-test", ts.URL, token, 0) + client, err := NewPluginService("plugin-test", ts.URL, token, 0) require.NoError(t, err) data, err := client.List(context.Background(), nil) diff --git a/applicationset/services/pull_request/azure_devops.go b/applicationset/services/pull_request/azure_devops.go index 78cf29f01a..ed46d029b6 100644 --- a/applicationset/services/pull_request/azure_devops.go +++ b/applicationset/services/pull_request/azure_devops.go @@ -41,7 +41,7 @@ var ( _ AzureDevOpsClientFactory = &devopsFactoryImpl{} ) -func NewAzureDevOpsService(ctx context.Context, token, url, organization, project, repo string, labels []string) (PullRequestService, error) { +func NewAzureDevOpsService(token, url, organization, project, repo string, labels []string) (PullRequestService, error) { organizationUrl := buildURL(url, organization) var connection *azuredevops.Connection diff --git a/applicationset/services/pull_request/bitbucket_cloud_test.go b/applicationset/services/pull_request/bitbucket_cloud_test.go index 411f6148c8..740734de6c 100644 --- a/applicationset/services/pull_request/bitbucket_cloud_test.go +++ b/applicationset/services/pull_request/bitbucket_cloud_test.go @@ -241,7 +241,7 @@ func TestListPullRequestPaginationCloud(t *testing.T) { } func TestListResponseErrorCloud(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusInternalServerError) })) defer ts.Close() diff --git a/applicationset/services/pull_request/bitbucket_server_test.go b/applicationset/services/pull_request/bitbucket_server_test.go index b9da370830..1ee0c2c214 100644 --- a/applicationset/services/pull_request/bitbucket_server_test.go +++ b/applicationset/services/pull_request/bitbucket_server_test.go @@ -303,7 +303,7 @@ func TestListPullRequestTLS(t *testing.T) { } func TestListResponseError(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusInternalServerError) })) defer ts.Close() diff --git a/applicationset/services/pull_request/fake.go b/applicationset/services/pull_request/fake.go index 845df70d66..50d4969e84 100644 --- a/applicationset/services/pull_request/fake.go +++ b/applicationset/services/pull_request/fake.go @@ -18,6 +18,6 @@ func NewFakeService(_ context.Context, listPullReuests []*PullRequest, listError }, nil } -func (g *FakeService) List(ctx context.Context) ([]*PullRequest, error) { +func (g *FakeService) List(_ context.Context) ([]*PullRequest, error) { return g.listPullReuests, g.listError } diff --git a/applicationset/services/pull_request/gitea.go b/applicationset/services/pull_request/gitea.go index 5f32e4dc30..b86574fbcc 100644 --- a/applicationset/services/pull_request/gitea.go +++ b/applicationset/services/pull_request/gitea.go @@ -18,7 +18,7 @@ type GiteaService struct { var _ PullRequestService = (*GiteaService)(nil) -func NewGiteaService(ctx context.Context, token, url, owner, repo string, insecure bool) (PullRequestService, error) { +func NewGiteaService(token, url, owner, repo string, insecure bool) (PullRequestService, error) { if token == "" { token = os.Getenv("GITEA_TOKEN") } @@ -49,6 +49,7 @@ func (g *GiteaService) List(ctx context.Context) ([]*PullRequest, error) { opts := gitea.ListPullRequestsOptions{ State: gitea.StateOpen, } + g.client.SetContext(ctx) prs, _, err := g.client.ListRepoPullRequests(g.owner, g.repo, opts) if err != nil { return nil, err diff --git a/applicationset/services/pull_request/gitea_test.go b/applicationset/services/pull_request/gitea_test.go index ab58a049e5..6b2bca7d13 100644 --- a/applicationset/services/pull_request/gitea_test.go +++ b/applicationset/services/pull_request/gitea_test.go @@ -251,7 +251,7 @@ func TestGiteaList(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { giteaMockHandler(t)(w, r) })) - host, err := NewGiteaService(context.Background(), "", ts.URL, "test-argocd", "pr-test", false) + host, err := NewGiteaService("", ts.URL, "test-argocd", "pr-test", false) require.NoError(t, err) prs, err := host.List(context.Background()) require.NoError(t, err) diff --git a/applicationset/services/pull_request/gitlab.go b/applicationset/services/pull_request/gitlab.go index 8443847fce..aaa31a8c87 100644 --- a/applicationset/services/pull_request/gitlab.go +++ b/applicationset/services/pull_request/gitlab.go @@ -21,7 +21,7 @@ type GitLabService struct { var _ PullRequestService = (*GitLabService)(nil) -func NewGitLabService(ctx context.Context, token, url, project string, labels []string, pullRequestState string, scmRootCAPath string, insecure bool, caCerts []byte) (PullRequestService, error) { +func NewGitLabService(token, url, project string, labels []string, pullRequestState string, scmRootCAPath string, insecure bool, caCerts []byte) (PullRequestService, error) { var clientOptionFns []gitlab.ClientOptionFunc // Set a custom Gitlab base URL if one is provided @@ -74,7 +74,7 @@ func (g *GitLabService) List(ctx context.Context) ([]*PullRequest, error) { pullRequests := []*PullRequest{} for { - mrs, resp, err := g.client.MergeRequests.ListProjectMergeRequests(g.project, opts) + mrs, resp, err := g.client.MergeRequests.ListProjectMergeRequests(g.project, opts, gitlab.WithContext(ctx)) if err != nil { return nil, fmt.Errorf("error listing merge requests for project '%s': %w", g.project, err) } diff --git a/applicationset/services/pull_request/gitlab_test.go b/applicationset/services/pull_request/gitlab_test.go index 18467fe088..f46982823e 100644 --- a/applicationset/services/pull_request/gitlab_test.go +++ b/applicationset/services/pull_request/gitlab_test.go @@ -35,7 +35,7 @@ func TestGitLabServiceCustomBaseURL(t *testing.T) { writeMRListResponse(t, w) }) - svc, err := NewGitLabService(context.Background(), "", server.URL, "278964", nil, "", "", false, nil) + svc, err := NewGitLabService("", server.URL, "278964", nil, "", "", false, nil) require.NoError(t, err) _, err = svc.List(context.Background()) @@ -54,7 +54,7 @@ func TestGitLabServiceToken(t *testing.T) { writeMRListResponse(t, w) }) - svc, err := NewGitLabService(context.Background(), "token-123", server.URL, "278964", nil, "", "", false, nil) + svc, err := NewGitLabService("token-123", server.URL, "278964", nil, "", "", false, nil) require.NoError(t, err) _, err = svc.List(context.Background()) @@ -73,7 +73,7 @@ func TestList(t *testing.T) { writeMRListResponse(t, w) }) - svc, err := NewGitLabService(context.Background(), "", server.URL, "278964", []string{}, "", "", false, nil) + svc, err := NewGitLabService("", server.URL, "278964", []string{}, "", "", false, nil) require.NoError(t, err) prs, err := svc.List(context.Background()) @@ -99,7 +99,7 @@ func TestListWithLabels(t *testing.T) { writeMRListResponse(t, w) }) - svc, err := NewGitLabService(context.Background(), "", server.URL, "278964", []string{"feature", "ready"}, "", "", false, nil) + svc, err := NewGitLabService("", server.URL, "278964", []string{"feature", "ready"}, "", "", false, nil) require.NoError(t, err) _, err = svc.List(context.Background()) @@ -118,7 +118,7 @@ func TestListWithState(t *testing.T) { writeMRListResponse(t, w) }) - svc, err := NewGitLabService(context.Background(), "", server.URL, "278964", []string{}, "opened", "", false, nil) + svc, err := NewGitLabService("", server.URL, "278964", []string{}, "opened", "", false, nil) require.NoError(t, err) _, err = svc.List(context.Background()) @@ -161,7 +161,7 @@ func TestListWithStateTLS(t *testing.T) { for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { - ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { writeMRListResponse(t, w) })) defer ts.Close() @@ -180,7 +180,7 @@ func TestListWithStateTLS(t *testing.T) { } } - svc, err := NewGitLabService(context.Background(), "", ts.URL, "278964", []string{}, "opened", "", test.tlsInsecure, certs) + svc, err := NewGitLabService("", ts.URL, "278964", []string{}, "opened", "", test.tlsInsecure, certs) require.NoError(t, err) _, err = svc.List(context.Background()) diff --git a/applicationset/services/repo_service_test.go b/applicationset/services/repo_service_test.go index 249d758a79..e9d97cc012 100644 --- a/applicationset/services/repo_service_test.go +++ b/applicationset/services/repo_service_test.go @@ -39,12 +39,12 @@ func TestGetDirectories(t *testing.T) { wantErr assert.ErrorAssertionFunc }{ {name: "ErrorGettingRepos", fields: fields{ - getRepository: func(ctx context.Context, url, project string) (*v1alpha1.Repository, error) { + getRepository: func(_ context.Context, _, _ string) (*v1alpha1.Repository, error) { return nil, errors.New("unable to get repos") }, }, args: args{}, want: nil, wantErr: assert.Error}, {name: "ErrorGettingDirs", fields: fields{ - getRepository: func(ctx context.Context, url, project string) (*v1alpha1.Repository, error) { + getRepository: func(_ context.Context, _, _ string) (*v1alpha1.Repository, error) { return &v1alpha1.Repository{}, nil }, repoServerClientFuncs: []func(*repo_mocks.RepoServerServiceClient){ @@ -54,7 +54,7 @@ func TestGetDirectories(t *testing.T) { }, }, args: args{}, want: nil, wantErr: assert.Error}, {name: "HappyCase", fields: fields{ - getRepository: func(ctx context.Context, url, project string) (*v1alpha1.Repository, error) { + getRepository: func(_ context.Context, _, _ string) (*v1alpha1.Repository, error) { return &v1alpha1.Repository{}, nil }, repoServerClientFuncs: []func(*repo_mocks.RepoServerServiceClient){ @@ -66,7 +66,7 @@ func TestGetDirectories(t *testing.T) { }, }, args: args{}, want: []string{"foo", "foo/bar", "bar/foo"}, wantErr: assert.NoError}, {name: "ErrorVerifyingCommit", fields: fields{ - getRepository: func(ctx context.Context, url, project string) (*v1alpha1.Repository, error) { + getRepository: func(_ context.Context, _, _ string) (*v1alpha1.Repository, error) { return &v1alpha1.Repository{}, nil }, repoServerClientFuncs: []func(*repo_mocks.RepoServerServiceClient){ @@ -122,12 +122,12 @@ func TestGetFiles(t *testing.T) { wantErr assert.ErrorAssertionFunc }{ {name: "ErrorGettingRepos", fields: fields{ - getRepository: func(ctx context.Context, url, project string) (*v1alpha1.Repository, error) { + getRepository: func(_ context.Context, _, _ string) (*v1alpha1.Repository, error) { return nil, errors.New("unable to get repos") }, }, args: args{}, want: nil, wantErr: assert.Error}, {name: "ErrorGettingFiles", fields: fields{ - getRepository: func(ctx context.Context, url, project string) (*v1alpha1.Repository, error) { + getRepository: func(_ context.Context, _, _ string) (*v1alpha1.Repository, error) { return &v1alpha1.Repository{}, nil }, repoServerClientFuncs: []func(*repo_mocks.RepoServerServiceClient){ @@ -137,7 +137,7 @@ func TestGetFiles(t *testing.T) { }, }, args: args{}, want: nil, wantErr: assert.Error}, {name: "HappyCase", fields: fields{ - getRepository: func(ctx context.Context, url, project string) (*v1alpha1.Repository, error) { + getRepository: func(_ context.Context, _, _ string) (*v1alpha1.Repository, error) { return &v1alpha1.Repository{}, nil }, repoServerClientFuncs: []func(*repo_mocks.RepoServerServiceClient){ @@ -155,7 +155,7 @@ func TestGetFiles(t *testing.T) { "bar.yaml": []byte("yay: appsets"), }, wantErr: assert.NoError}, {name: "ErrorVerifyingCommit", fields: fields{ - getRepository: func(ctx context.Context, url, project string) (*v1alpha1.Repository, error) { + getRepository: func(_ context.Context, _, _ string) (*v1alpha1.Repository, error) { return &v1alpha1.Repository{}, nil }, repoServerClientFuncs: []func(*repo_mocks.RepoServerServiceClient){ @@ -189,7 +189,7 @@ func TestGetFiles(t *testing.T) { } func TestNewArgoCDService(t *testing.T) { - service, err := NewArgoCDService(func(ctx context.Context, url, project string) (*v1alpha1.Repository, error) { + service, err := NewArgoCDService(func(_ context.Context, _, _ string) (*v1alpha1.Repository, error) { return &v1alpha1.Repository{}, nil }, false, &repo_mocks.Clientset{}, false) require.NoError(t, err) diff --git a/applicationset/services/scm_provider/azure_devops.go b/applicationset/services/scm_provider/azure_devops.go index b43f57b969..4c198e10cf 100644 --- a/applicationset/services/scm_provider/azure_devops.go +++ b/applicationset/services/scm_provider/azure_devops.go @@ -57,7 +57,7 @@ var ( _ AzureDevOpsClientFactory = &devopsFactoryImpl{} ) -func NewAzureDevOpsProvider(ctx context.Context, accessToken string, org string, url string, project string, allBranches bool) (*AzureDevOpsProvider, error) { +func NewAzureDevOpsProvider(accessToken string, org string, url string, project string, allBranches bool) (*AzureDevOpsProvider, error) { if accessToken == "" { return nil, errors.New("no access token provided") } @@ -72,7 +72,7 @@ func NewAzureDevOpsProvider(ctx context.Context, accessToken string, org string, return &AzureDevOpsProvider{organization: org, teamProject: project, accessToken: accessToken, clientFactory: &devopsFactoryImpl{connection: connection}, allBranches: allBranches}, nil } -func (g *AzureDevOpsProvider) ListRepos(ctx context.Context, cloneProtocol string) ([]*Repository, error) { +func (g *AzureDevOpsProvider) ListRepos(ctx context.Context, _ string) ([]*Repository, error) { gitClient, err := g.clientFactory.GetClient(ctx) if err != nil { return nil, fmt.Errorf("failed to get Azure DevOps client: %w", err) diff --git a/applicationset/services/scm_provider/bitbucket_cloud.go b/applicationset/services/scm_provider/bitbucket_cloud.go index 7b40d99e8c..a91ed1dbf0 100644 --- a/applicationset/services/scm_provider/bitbucket_cloud.go +++ b/applicationset/services/scm_provider/bitbucket_cloud.go @@ -52,7 +52,7 @@ func (c *ExtendedClient) GetContents(repo *Repository, path string) (bool, error var _ SCMProviderService = &BitBucketCloudProvider{} -func NewBitBucketCloudProvider(ctx context.Context, owner string, user string, password string, allBranches bool) (*BitBucketCloudProvider, error) { +func NewBitBucketCloudProvider(owner string, user string, password string, allBranches bool) (*BitBucketCloudProvider, error) { client := &ExtendedClient{ bitbucket.NewBasicAuth(user, password), user, @@ -62,7 +62,7 @@ func NewBitBucketCloudProvider(ctx context.Context, owner string, user string, p return &BitBucketCloudProvider{client: client, owner: owner, allBranches: allBranches}, nil } -func (g *BitBucketCloudProvider) GetBranches(ctx context.Context, repo *Repository) ([]*Repository, error) { +func (g *BitBucketCloudProvider) GetBranches(_ context.Context, repo *Repository) ([]*Repository, error) { repos := []*Repository{} branches, err := g.listBranches(repo) if err != nil { @@ -87,7 +87,7 @@ func (g *BitBucketCloudProvider) GetBranches(ctx context.Context, repo *Reposito return repos, nil } -func (g *BitBucketCloudProvider) ListRepos(ctx context.Context, cloneProtocol string) ([]*Repository, error) { +func (g *BitBucketCloudProvider) ListRepos(_ context.Context, cloneProtocol string) ([]*Repository, error) { if cloneProtocol == "" { cloneProtocol = "ssh" } @@ -117,7 +117,7 @@ func (g *BitBucketCloudProvider) ListRepos(ctx context.Context, cloneProtocol st return repos, nil } -func (g *BitBucketCloudProvider) RepoHasPath(ctx context.Context, repo *Repository, path string) (bool, error) { +func (g *BitBucketCloudProvider) RepoHasPath(_ context.Context, repo *Repository, path string) (bool, error) { contents, err := g.client.GetContents(repo, path) if err != nil { return false, err diff --git a/applicationset/services/scm_provider/bitbucket_cloud_test.go b/applicationset/services/scm_provider/bitbucket_cloud_test.go index d4127dbbf4..8633d4b7e7 100644 --- a/applicationset/services/scm_provider/bitbucket_cloud_test.go +++ b/applicationset/services/scm_provider/bitbucket_cloud_test.go @@ -87,7 +87,7 @@ func TestBitbucketHasRepo(t *testing.T) { for _, c := range cases { t.Run(c.name, func(t *testing.T) { - provider, _ := NewBitBucketCloudProvider(context.Background(), c.owner, "user", "password", false) + provider, _ := NewBitBucketCloudProvider(c.owner, "user", "password", false) repo := &Repository{ Organization: c.owner, Repository: c.repo, @@ -487,7 +487,7 @@ func TestBitbucketListRepos(t *testing.T) { for _, c := range cases { t.Run(c.name, func(t *testing.T) { - provider, _ := NewBitBucketCloudProvider(context.Background(), c.owner, "user", "password", c.allBranches) + provider, _ := NewBitBucketCloudProvider(c.owner, "user", "password", c.allBranches) rawRepos, err := ListRepos(context.Background(), provider, c.filters, c.proto) if c.hasError { require.Error(t, err) diff --git a/applicationset/services/scm_provider/bitbucket_server_test.go b/applicationset/services/scm_provider/bitbucket_server_test.go index 211d86cafd..753e8f75f7 100644 --- a/applicationset/services/scm_provider/bitbucket_server_test.go +++ b/applicationset/services/scm_provider/bitbucket_server_test.go @@ -369,7 +369,7 @@ func TestGetBranchesMissingDefault(t *testing.T) { } func TestGetBranchesEmptyRepo(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ts := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { assert.Empty(t, r.Header.Get("Authorization")) if r.RequestURI == "/rest/api/1.0/projects/PROJECT/repos/REPO/branches/default" { return diff --git a/applicationset/services/scm_provider/gitea.go b/applicationset/services/scm_provider/gitea.go index 9f0650f2d6..b633d0c5ef 100644 --- a/applicationset/services/scm_provider/gitea.go +++ b/applicationset/services/scm_provider/gitea.go @@ -19,7 +19,7 @@ type GiteaProvider struct { var _ SCMProviderService = &GiteaProvider{} -func NewGiteaProvider(ctx context.Context, owner, token, url string, allBranches, insecure bool) (*GiteaProvider, error) { +func NewGiteaProvider(owner, token, url string, allBranches, insecure bool) (*GiteaProvider, error) { if token == "" { token = os.Getenv("GITEA_TOKEN") } @@ -46,7 +46,7 @@ func NewGiteaProvider(ctx context.Context, owner, token, url string, allBranches }, nil } -func (g *GiteaProvider) GetBranches(ctx context.Context, repo *Repository) ([]*Repository, error) { +func (g *GiteaProvider) GetBranches(_ context.Context, repo *Repository) ([]*Repository, error) { if !g.allBranches { branch, status, err := g.client.GetRepoBranch(g.owner, repo.Repository, repo.Branch) if status.StatusCode == http.StatusNotFound { @@ -87,7 +87,7 @@ func (g *GiteaProvider) GetBranches(ctx context.Context, repo *Repository) ([]*R return repos, nil } -func (g *GiteaProvider) ListRepos(ctx context.Context, cloneProtocol string) ([]*Repository, error) { +func (g *GiteaProvider) ListRepos(_ context.Context, cloneProtocol string) ([]*Repository, error) { repos := []*Repository{} repoOpts := gitea.ListOrgReposOptions{} giteaRepos, _, err := g.client.ListOrgRepos(g.owner, repoOpts) @@ -126,7 +126,7 @@ func (g *GiteaProvider) ListRepos(ctx context.Context, cloneProtocol string) ([] return repos, nil } -func (g *GiteaProvider) RepoHasPath(ctx context.Context, repo *Repository, path string) (bool, error) { +func (g *GiteaProvider) RepoHasPath(_ context.Context, repo *Repository, path string) (bool, error) { _, resp, err := g.client.GetContents(repo.Organization, repo.Repository, repo.Branch, path) if resp != nil && resp.StatusCode == http.StatusNotFound { return false, nil diff --git a/applicationset/services/scm_provider/gitea_test.go b/applicationset/services/scm_provider/gitea_test.go index 1253d30c9a..6ca88c8be4 100644 --- a/applicationset/services/scm_provider/gitea_test.go +++ b/applicationset/services/scm_provider/gitea_test.go @@ -304,7 +304,7 @@ func TestGiteaListRepos(t *testing.T) { defer ts.Close() for _, c := range cases { t.Run(c.name, func(t *testing.T) { - provider, _ := NewGiteaProvider(context.Background(), "test-argocd", "", ts.URL, c.allBranches, false) + provider, _ := NewGiteaProvider("test-argocd", "", ts.URL, c.allBranches, false) rawRepos, err := ListRepos(context.Background(), provider, c.filters, c.proto) if c.hasError { require.Error(t, err) @@ -334,7 +334,7 @@ func TestGiteaHasPath(t *testing.T) { giteaMockHandler(t)(w, r) })) defer ts.Close() - host, _ := NewGiteaProvider(context.Background(), "gitea", "", ts.URL, false, false) + host, _ := NewGiteaProvider("gitea", "", ts.URL, false, false) repo := &Repository{ Organization: "gitea", Repository: "go-sdk", diff --git a/applicationset/services/scm_provider/gitlab.go b/applicationset/services/scm_provider/gitlab.go index c1f9016abf..fb1fc58040 100644 --- a/applicationset/services/scm_provider/gitlab.go +++ b/applicationset/services/scm_provider/gitlab.go @@ -24,7 +24,7 @@ type GitlabProvider struct { var _ SCMProviderService = &GitlabProvider{} -func NewGitlabProvider(ctx context.Context, organization string, token string, url string, allBranches, includeSubgroups, includeSharedProjects, insecure bool, scmRootCAPath, topic string, caCerts []byte) (*GitlabProvider, error) { +func NewGitlabProvider(organization string, token string, url string, allBranches, includeSubgroups, includeSharedProjects, insecure bool, scmRootCAPath, topic string, caCerts []byte) (*GitlabProvider, error) { // Undocumented environment variable to set a default token, to be used in testing to dodge anonymous rate limits. if token == "" { token = os.Getenv("GITLAB_TOKEN") @@ -75,7 +75,7 @@ func (g *GitlabProvider) GetBranches(ctx context.Context, repo *Repository) ([]* return repos, nil } -func (g *GitlabProvider) ListRepos(ctx context.Context, cloneProtocol string) ([]*Repository, error) { +func (g *GitlabProvider) ListRepos(_ context.Context, cloneProtocol string) ([]*Repository, error) { opt := &gitlab.ListGroupProjectsOptions{ ListOptions: gitlab.ListOptions{PerPage: 100}, IncludeSubGroups: &g.includeSubgroups, diff --git a/applicationset/services/scm_provider/gitlab_test.go b/applicationset/services/scm_provider/gitlab_test.go index 4443086333..dca058aaca 100644 --- a/applicationset/services/scm_provider/gitlab_test.go +++ b/applicationset/services/scm_provider/gitlab_test.go @@ -1124,7 +1124,7 @@ func TestGitlabListRepos(t *testing.T) { })) for _, c := range cases { t.Run(c.name, func(t *testing.T) { - provider, _ := NewGitlabProvider(context.Background(), "test-argocd-proton", "", ts.URL, c.allBranches, c.includeSubgroups, c.includeSharedProjects, c.insecure, "", c.topic, nil) + provider, _ := NewGitlabProvider("test-argocd-proton", "", ts.URL, c.allBranches, c.includeSubgroups, c.includeSharedProjects, c.insecure, "", c.topic, nil) rawRepos, err := ListRepos(context.Background(), provider, c.filters, c.proto) if c.hasError { require.Error(t, err) @@ -1163,7 +1163,7 @@ func TestGitlabHasPath(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { gitlabMockHandler(t)(w, r) })) - host, _ := NewGitlabProvider(context.Background(), "test-argocd-proton", "", ts.URL, false, true, true, false, "", "", nil) + host, _ := NewGitlabProvider("test-argocd-proton", "", ts.URL, false, true, true, false, "", "", nil) repo := &Repository{ Organization: "test-argocd-proton", Repository: "argocd", @@ -1209,7 +1209,7 @@ func TestGitlabGetBranches(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { gitlabMockHandler(t)(w, r) })) - host, _ := NewGitlabProvider(context.Background(), "test-argocd-proton", "", ts.URL, false, true, true, false, "", "", nil) + host, _ := NewGitlabProvider("test-argocd-proton", "", ts.URL, false, true, true, false, "", "", nil) repo := &Repository{ RepositoryId: 27084533, @@ -1286,7 +1286,7 @@ func TestGetBranchesTLS(t *testing.T) { } } - host, err := NewGitlabProvider(context.Background(), "test-argocd-proton", "", ts.URL, false, true, true, test.tlsInsecure, "", "", certs) + host, err := NewGitlabProvider("test-argocd-proton", "", ts.URL, false, true, true, test.tlsInsecure, "", "", certs) require.NoError(t, err) repo := &Repository{ RepositoryId: 27084533, diff --git a/applicationset/utils/applicationset_lister.go b/applicationset/utils/applicationset_lister.go index 5e9d659363..c9a5ecf944 100644 --- a/applicationset/utils/applicationset_lister.go +++ b/applicationset/utils/applicationset_lister.go @@ -19,7 +19,7 @@ func NewAppsetLister(client ctrlclient.Client) ApplicationSetLister { return &AppsetLister{Client: client} } -func (l *AppsetLister) List(selector labels.Selector) (ret []*ApplicationSet, err error) { +func (l *AppsetLister) List(_ labels.Selector) (ret []*ApplicationSet, err error) { return clientListAppsets(l.Client, ctrlclient.ListOptions{}) } @@ -37,11 +37,11 @@ type appsetNamespaceLister struct { Namespace string } -func (n *appsetNamespaceLister) List(selector labels.Selector) (ret []*ApplicationSet, err error) { +func (n *appsetNamespaceLister) List(_ labels.Selector) (ret []*ApplicationSet, err error) { return clientListAppsets(n.Client, ctrlclient.ListOptions{Namespace: n.Namespace}) } -func (n *appsetNamespaceLister) Get(name string) (*ApplicationSet, error) { +func (n *appsetNamespaceLister) Get(_ string) (*ApplicationSet, error) { appset := ApplicationSet{} err := n.Client.Get(context.TODO(), ctrlclient.ObjectKeyFromObject(&appset), &appset) return &appset, err diff --git a/applicationset/utils/selector.go b/applicationset/utils/selector.go index 556b186b58..eae0324236 100644 --- a/applicationset/utils/selector.go +++ b/applicationset/utils/selector.go @@ -69,11 +69,11 @@ func (s internalSelector) Add(reqs ...Requirement) Selector { type nothingSelector struct{} -func (n nothingSelector) Matches(l labels.Labels) bool { +func (n nothingSelector) Matches(_ labels.Labels) bool { return false } -func (n nothingSelector) Add(r ...Requirement) Selector { +func (n nothingSelector) Add(_ ...Requirement) Selector { return n } diff --git a/applicationset/utils/utils_test.go b/applicationset/utils/utils_test.go index 6c66186649..b64b0735fc 100644 --- a/applicationset/utils/utils_test.go +++ b/applicationset/utils/utils_test.go @@ -565,7 +565,7 @@ func TestRenderTemplateParamsGoTemplate(t *testing.T) { expectedVal: " foo:\n bar:\n bool: true\n number: 2\n str: Hello world", errorMessage: "failed to execute go template {{ toYaml . | indent 2 }}: template: :1:3: executing \"\" at : error calling toYaml: error marshaling into JSON: json: unsupported type: func(*string)", params: map[string]any{ - "foo": func(test *string) { + "foo": func(_ *string) { }, }, }, diff --git a/applicationset/webhook/webhook_test.go b/applicationset/webhook/webhook_test.go index 1d5ba90d0d..07e8539548 100644 --- a/applicationset/webhook/webhook_test.go +++ b/applicationset/webhook/webhook_test.go @@ -35,15 +35,15 @@ type generatorMock struct { mock.Mock } -func (g *generatorMock) GetTemplate(appSetGenerator *v1alpha1.ApplicationSetGenerator) *v1alpha1.ApplicationSetTemplate { +func (g *generatorMock) GetTemplate(_ *v1alpha1.ApplicationSetGenerator) *v1alpha1.ApplicationSetTemplate { return &v1alpha1.ApplicationSetTemplate{} } -func (g *generatorMock) GenerateParams(appSetGenerator *v1alpha1.ApplicationSetGenerator, _ *v1alpha1.ApplicationSet, client client.Client) ([]map[string]any, error) { +func (g *generatorMock) GenerateParams(_ *v1alpha1.ApplicationSetGenerator, _ *v1alpha1.ApplicationSet, _ client.Client) ([]map[string]any, error) { return []map[string]any{}, nil } -func (g *generatorMock) GetRequeueAfter(appSetGenerator *v1alpha1.ApplicationSetGenerator) time.Duration { +func (g *generatorMock) GetRequeueAfter(_ *v1alpha1.ApplicationSetGenerator) time.Duration { d, _ := time.ParseDuration("10s") return d } diff --git a/cmd/argocd-application-controller/commands/argocd_application_controller.go b/cmd/argocd-application-controller/commands/argocd_application_controller.go index ec364baf5b..80b7abe296 100644 --- a/cmd/argocd-application-controller/commands/argocd_application_controller.go +++ b/cmd/argocd-application-controller/commands/argocd_application_controller.go @@ -97,7 +97,7 @@ func NewCommand() *cobra.Command { Short: "Run ArgoCD Application Controller", Long: "ArgoCD application controller is a Kubernetes controller that continuously monitors running applications and compares the current, live state against the desired target state (as specified in the repo). This command runs Application Controller in the foreground. It can be configured by following options.", DisableAutoGenTag: true, - RunE: func(c *cobra.Command, args []string) error { + RunE: func(c *cobra.Command, _ []string) error { ctx, cancel := context.WithCancel(c.Context()) defer cancel() diff --git a/cmd/argocd-applicationset-controller/commands/applicationset_controller.go b/cmd/argocd-applicationset-controller/commands/applicationset_controller.go index ffd925a8c0..1ff5329574 100644 --- a/cmd/argocd-applicationset-controller/commands/applicationset_controller.go +++ b/cmd/argocd-applicationset-controller/commands/applicationset_controller.go @@ -81,7 +81,7 @@ func NewCommand() *cobra.Command { command := cobra.Command{ Use: "controller", Short: "Starts Argo CD ApplicationSet controller", - RunE: func(c *cobra.Command, args []string) error { + RunE: func(c *cobra.Command, _ []string) error { ctx := c.Context() vers := common.GetVersion() diff --git a/cmd/argocd-cmp-server/commands/argocd_cmp_server.go b/cmd/argocd-cmp-server/commands/argocd_cmp_server.go index 9d1894695f..4c917e7679 100644 --- a/cmd/argocd-cmp-server/commands/argocd_cmp_server.go +++ b/cmd/argocd-cmp-server/commands/argocd_cmp_server.go @@ -36,7 +36,7 @@ func NewCommand() *cobra.Command { Short: "Run ArgoCD ConfigManagementPlugin Server", Long: "ArgoCD ConfigManagementPlugin Server is an internal service which runs as sidecar container in reposerver deployment. The following configuration options are available:", DisableAutoGenTag: true, - RunE: func(c *cobra.Command, args []string) error { + RunE: func(c *cobra.Command, _ []string) error { ctx := c.Context() vers := common.GetVersion() diff --git a/cmd/argocd-commit-server/commands/argocd_commit_server.go b/cmd/argocd-commit-server/commands/argocd_commit_server.go index 5c07bc0c14..eee928b008 100644 --- a/cmd/argocd-commit-server/commands/argocd_commit_server.go +++ b/cmd/argocd-commit-server/commands/argocd_commit_server.go @@ -38,7 +38,7 @@ func NewCommand() *cobra.Command { Use: "argocd-commit-server", Short: "Run Argo CD Commit Server", Long: "Argo CD Commit Server is an internal service which commits and pushes hydrated manifests to git. This command runs Commit Server in the foreground.", - RunE: func(cmd *cobra.Command, args []string) error { + RunE: func(_ *cobra.Command, _ []string) error { vers := common.GetVersion() vers.LogStartupInfo( "Argo CD Commit Server", diff --git a/cmd/argocd-dex/commands/argocd_dex.go b/cmd/argocd-dex/commands/argocd_dex.go index 332e79b6af..62a7854604 100644 --- a/cmd/argocd-dex/commands/argocd_dex.go +++ b/cmd/argocd-dex/commands/argocd_dex.go @@ -52,7 +52,7 @@ func NewRunDexCommand() *cobra.Command { command := cobra.Command{ Use: "rundex", Short: "Runs dex generating a config using settings from the Argo CD configmap and secret", - RunE: func(c *cobra.Command, args []string) error { + RunE: func(c *cobra.Command, _ []string) error { ctx := c.Context() vers := common.GetVersion() @@ -159,7 +159,7 @@ func NewGenDexConfigCommand() *cobra.Command { command := cobra.Command{ Use: "gendexcfg", Short: "Generates a dex config from Argo CD settings", - RunE: func(c *cobra.Command, args []string) error { + RunE: func(c *cobra.Command, _ []string) error { ctx := c.Context() cli.SetLogFormat(cmdutil.LogFormat) diff --git a/cmd/argocd-git-ask-pass/commands/argocd_git_ask_pass.go b/cmd/argocd-git-ask-pass/commands/argocd_git_ask_pass.go index 73673e977b..b815f1c7a1 100644 --- a/cmd/argocd-git-ask-pass/commands/argocd_git_ask_pass.go +++ b/cmd/argocd-git-ask-pass/commands/argocd_git_ask_pass.go @@ -25,7 +25,7 @@ func NewCommand() *cobra.Command { Use: cliName, Short: "Argo CD git credential helper", DisableAutoGenTag: true, - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { ctx := c.Context() if len(os.Args) != 2 { diff --git a/cmd/argocd-k8s-auth/commands/aws.go b/cmd/argocd-k8s-auth/commands/aws.go index 1794a5bf57..a8e4a2f757 100644 --- a/cmd/argocd-k8s-auth/commands/aws.go +++ b/cmd/argocd-k8s-auth/commands/aws.go @@ -41,7 +41,7 @@ func newAWSCommand() *cobra.Command { ) command := &cobra.Command{ Use: "aws", - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { ctx := c.Context() presignedURLString, err := getSignedRequestWithRetry(ctx, time.Minute, 5*time.Second, clusterName, roleARN, profile, getSignedRequest) diff --git a/cmd/argocd-k8s-auth/commands/aws_test.go b/cmd/argocd-k8s-auth/commands/aws_test.go index 37d9e9ea04..bacfab0f57 100644 --- a/cmd/argocd-k8s-auth/commands/aws_test.go +++ b/cmd/argocd-k8s-auth/commands/aws_test.go @@ -17,7 +17,7 @@ func TestGetSignedRequestWithRetry(t *testing.T) { // given t.Parallel() mock := &signedRequestMock{ - returnFunc: func(m *signedRequestMock) (string, error) { + returnFunc: func(_ *signedRequestMock) (string, error) { return "token", nil }, } @@ -52,7 +52,7 @@ func TestGetSignedRequestWithRetry(t *testing.T) { // given t.Parallel() mock := &signedRequestMock{ - returnFunc: func(m *signedRequestMock) (string, error) { + returnFunc: func(_ *signedRequestMock) (string, error) { return "", errors.New("some error") }, } @@ -71,7 +71,7 @@ type signedRequestMock struct { returnFunc func(m *signedRequestMock) (string, error) } -func (m *signedRequestMock) getSignedRequestMock(clusterName, roleARN string, profile string) (string, error) { +func (m *signedRequestMock) getSignedRequestMock(_, _ string, _ string) (string, error) { m.getSignedRequestCalls++ return m.returnFunc(m) } diff --git a/cmd/argocd-k8s-auth/commands/azure.go b/cmd/argocd-k8s-auth/commands/azure.go index 287b8d457a..f04b1e3c04 100644 --- a/cmd/argocd-k8s-auth/commands/azure.go +++ b/cmd/argocd-k8s-auth/commands/azure.go @@ -22,7 +22,7 @@ const ( func newAzureCommand() *cobra.Command { command := &cobra.Command{ Use: "azure", - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { o := token.OptionsWithEnv() if o.LoginMethod == "" { // no environment variable overrides // we'll use default of WorkloadIdentityLogin for the login flow diff --git a/cmd/argocd-k8s-auth/commands/gcp.go b/cmd/argocd-k8s-auth/commands/gcp.go index 388d274072..5d6eda5567 100644 --- a/cmd/argocd-k8s-auth/commands/gcp.go +++ b/cmd/argocd-k8s-auth/commands/gcp.go @@ -24,7 +24,7 @@ var defaultGCPScopes = []string{ func newGCPCommand() *cobra.Command { command := &cobra.Command{ Use: "gcp", - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { ctx := c.Context() // Preferred way to retrieve GCP credentials diff --git a/cmd/argocd-notification/commands/controller.go b/cmd/argocd-notification/commands/controller.go index 152dab6a07..bdbb152b17 100644 --- a/cmd/argocd-notification/commands/controller.go +++ b/cmd/argocd-notification/commands/controller.go @@ -66,7 +66,7 @@ func NewCommand() *cobra.Command { command := cobra.Command{ Use: "controller", Short: "Starts Argo CD Notifications controller", - RunE: func(c *cobra.Command, args []string) error { + RunE: func(_ *cobra.Command, _ []string) error { ctx, cancel := context.WithCancel(context.Background()) defer cancel() diff --git a/cmd/argocd-repo-server/commands/argocd_repo_server.go b/cmd/argocd-repo-server/commands/argocd_repo_server.go index 19d9a2a1e4..86a345c000 100644 --- a/cmd/argocd-repo-server/commands/argocd_repo_server.go +++ b/cmd/argocd-repo-server/commands/argocd_repo_server.go @@ -83,7 +83,7 @@ func NewCommand() *cobra.Command { Short: "Run ArgoCD Repository Server", Long: "ArgoCD Repository Server is an internal service which maintains a local cache of the Git repository holding the application manifests, and is responsible for generating and returning the Kubernetes manifests. This command runs Repository Server in the foreground. It can be configured by following options.", DisableAutoGenTag: true, - RunE: func(c *cobra.Command, args []string) error { + RunE: func(c *cobra.Command, _ []string) error { ctx := c.Context() vers := common.GetVersion() diff --git a/cmd/argocd-server/commands/argocd_server.go b/cmd/argocd-server/commands/argocd_server.go index 403cfdae16..75845f9fd9 100644 --- a/cmd/argocd-server/commands/argocd_server.go +++ b/cmd/argocd-server/commands/argocd_server.go @@ -103,7 +103,7 @@ func NewCommand() *cobra.Command { Short: "Run the ArgoCD API server", Long: "The API server is a gRPC/REST server which exposes the API consumed by the Web UI, CLI, and CI/CD systems. This command runs API server in the foreground. It can be configured by following options.", DisableAutoGenTag: true, - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { ctx := c.Context() vers := common.GetVersion() diff --git a/cmd/argocd/commands/account.go b/cmd/argocd/commands/account.go index 4307990f81..733a26803e 100644 --- a/cmd/argocd/commands/account.go +++ b/cmd/argocd/commands/account.go @@ -262,7 +262,7 @@ func NewAccountListCommand(clientOpts *argocdclient.ClientOptions) *cobra.Comman Use: "list", Short: "List accounts", Example: "argocd account list", - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { ctx := c.Context() conn, client := headless.NewClientOrDie(clientOpts, c).NewAccountClientOrDie() @@ -309,7 +309,7 @@ argocd account get # Get details for an account by name argocd account get --account `, - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { ctx := c.Context() clientset := headless.NewClientOrDie(clientOpts, c) @@ -382,7 +382,7 @@ argocd account generate-token # Generate token for the account with the specified name argocd account generate-token --account `, - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { ctx := c.Context() clientset := headless.NewClientOrDie(clientOpts, c) diff --git a/cmd/argocd/commands/admin/app.go b/cmd/argocd/commands/admin/app.go index c60484c6ff..f106aa1b96 100644 --- a/cmd/argocd/commands/admin/app.go +++ b/cmd/argocd/commands/admin/app.go @@ -371,7 +371,7 @@ func reconcileApplications( appClientset, 1*time.Hour, appinformers.WithNamespace(namespace), - appinformers.WithTweakListOptions(func(options *metav1.ListOptions) {}), + appinformers.WithTweakListOptions(func(_ *metav1.ListOptions) {}), ) appInformer := appInformerFactory.Argoproj().V1alpha1().Applications().Informer() @@ -384,9 +384,9 @@ func reconcileApplications( appLister := appInformerFactory.Argoproj().V1alpha1().Applications().Lister() projLister := appInformerFactory.Argoproj().V1alpha1().AppProjects().Lister() - server, err := metrics.NewMetricsServer("", appLister, func(obj any) bool { + server, err := metrics.NewMetricsServer("", appLister, func(_ any) bool { return true - }, func(r *http.Request) error { + }, func(_ *http.Request) error { return nil }, []string{}, []string{}) if err != nil { @@ -453,5 +453,5 @@ func reconcileApplications( } func newLiveStateCache(argoDB db.ArgoDB, appInformer kubecache.SharedIndexInformer, settingsMgr *settings.SettingsManager, server *metrics.MetricsServer) cache.LiveStateCache { - return cache.NewLiveStateCache(argoDB, appInformer, settingsMgr, kubeutil.NewKubectl(), server, func(managedByApp map[string]bool, ref corev1.ObjectReference) {}, &sharding.ClusterSharding{}, argo.NewResourceTracking()) + return cache.NewLiveStateCache(argoDB, appInformer, settingsMgr, kubeutil.NewKubectl(), server, func(_ map[string]bool, _ corev1.ObjectReference) {}, &sharding.ClusterSharding{}, argo.NewResourceTracking()) } diff --git a/cmd/argocd/commands/admin/app_test.go b/cmd/argocd/commands/admin/app_test.go index 964d23ccab..a851575c01 100644 --- a/cmd/argocd/commands/admin/app_test.go +++ b/cmd/argocd/commands/admin/app_test.go @@ -110,7 +110,7 @@ func TestGetReconcileResults_Refresh(t *testing.T) { liveStateCache.On("IsNamespaced", mock.Anything, mock.Anything).Return(true, nil) result, err := reconcileApplications(ctx, kubeClientset, appClientset, "default", &repoServerClientset, "", - func(argoDB db.ArgoDB, appInformer cache.SharedIndexInformer, settingsMgr *settings.SettingsManager, server *metrics.MetricsServer) statecache.LiveStateCache { + func(_ db.ArgoDB, _ cache.SharedIndexInformer, _ *settings.SettingsManager, _ *metrics.MetricsServer) statecache.LiveStateCache { return &liveStateCache }, false, diff --git a/cmd/argocd/commands/admin/backup.go b/cmd/argocd/commands/admin/backup.go index 7725ed1d9e..8245409cd8 100644 --- a/cmd/argocd/commands/admin/backup.go +++ b/cmd/argocd/commands/admin/backup.go @@ -36,7 +36,7 @@ func NewExportCommand() *cobra.Command { command := cobra.Command{ Use: "export", Short: "Export all Argo CD data to stdout (default) or a file", - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { ctx := c.Context() config, err := clientConfig.ClientConfig() diff --git a/cmd/argocd/commands/admin/cluster.go b/cmd/argocd/commands/admin/cluster.go index 2f90687d38..124a75f67a 100644 --- a/cmd/argocd/commands/admin/cluster.go +++ b/cmd/argocd/commands/admin/cluster.go @@ -194,7 +194,7 @@ func NewClusterShardsCommand(clientOpts *argocdclient.ClientOptions) *cobra.Comm command := cobra.Command{ Use: "shards", Short: "Print information about each controller shard and the estimated portion of Kubernetes resources it is responsible for.", - Run: func(cmd *cobra.Command, args []string) { + Run: func(cmd *cobra.Command, _ []string) { ctx := cmd.Context() log.SetLevel(log.WarnLevel) @@ -321,12 +321,12 @@ func NewClusterNamespacesCommand() *cobra.Command { command := cobra.Command{ Use: "namespaces", Short: "Print information namespaces which Argo CD manages in each cluster.", - Run: func(cmd *cobra.Command, args []string) { + Run: func(cmd *cobra.Command, _ []string) { ctx := cmd.Context() log.SetLevel(log.WarnLevel) - err := runClusterNamespacesCommand(ctx, clientConfig, func(appClient *versioned.Clientset, _ db.ArgoDB, clusters map[string][]string) error { + err := runClusterNamespacesCommand(ctx, clientConfig, func(_ *versioned.Clientset, _ db.ArgoDB, clusters map[string][]string) error { w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0) _, _ = fmt.Fprintf(w, "CLUSTER\tNAMESPACES\n") @@ -486,7 +486,7 @@ argocd admin cluster stats --shard=1 #In a multi-cluster environment to print stats for a specific cluster say(target-cluster) argocd admin cluster stats target-cluster`, - Run: func(cmd *cobra.Command, args []string) { + Run: func(cmd *cobra.Command, _ []string) { ctx := cmd.Context() log.SetLevel(log.WarnLevel) diff --git a/cmd/argocd/commands/admin/dashboard.go b/cmd/argocd/commands/admin/dashboard.go index 41abce130e..3a416e81a2 100644 --- a/cmd/argocd/commands/admin/dashboard.go +++ b/cmd/argocd/commands/admin/dashboard.go @@ -27,7 +27,7 @@ func NewDashboardCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command cmd := &cobra.Command{ Use: "dashboard", Short: "Starts Argo CD Web UI locally", - Run: func(cmd *cobra.Command, args []string) { + Run: func(cmd *cobra.Command, _ []string) { ctx := cmd.Context() compression, err := cache.CompressionTypeFromString(compressionStr) diff --git a/cmd/argocd/commands/admin/initial_password.go b/cmd/argocd/commands/admin/initial_password.go index fa1352b007..97bf490949 100644 --- a/cmd/argocd/commands/admin/initial_password.go +++ b/cmd/argocd/commands/admin/initial_password.go @@ -21,7 +21,7 @@ func NewInitialPasswordCommand() *cobra.Command { command := cobra.Command{ Use: "initial-password", Short: "Prints initial password to log in to Argo CD for the first time", - Run: func(c *cobra.Command, args []string) { + Run: func(_ *cobra.Command, _ []string) { config, err := clientConfig.ClientConfig() errors.CheckError(err) namespace, _, err := clientConfig.Namespace() diff --git a/cmd/argocd/commands/admin/project.go b/cmd/argocd/commands/admin/project.go index e943c99f31..480d3f283a 100644 --- a/cmd/argocd/commands/admin/project.go +++ b/cmd/argocd/commands/admin/project.go @@ -106,7 +106,7 @@ func getModification(modification string, resource string, scope string, permiss return fmt.Sprintf("%s, %s, %s/%s, %s", resource, action, proj, scope, permission) }, nil case "remove": - return func(proj string, action string) string { + return func(_ string, _ string) string { return "" }, nil } diff --git a/cmd/argocd/commands/admin/redis_initial_password.go b/cmd/argocd/commands/admin/redis_initial_password.go index 82085f9ec6..b527b33589 100644 --- a/cmd/argocd/commands/admin/redis_initial_password.go +++ b/cmd/argocd/commands/admin/redis_initial_password.go @@ -40,7 +40,7 @@ func NewRedisInitialPasswordCommand() *cobra.Command { command := cobra.Command{ Use: "redis-initial-password", Short: "Ensure the Redis password exists, creating a new one if necessary.", - Run: func(c *cobra.Command, args []string) { + Run: func(_ *cobra.Command, _ []string) { namespace, _, err := clientConfig.Namespace() errors.CheckError(err) diff --git a/cmd/argocd/commands/admin/settings.go b/cmd/argocd/commands/admin/settings.go index 3dda4b3652..2e576cc7da 100644 --- a/cmd/argocd/commands/admin/settings.go +++ b/cmd/argocd/commands/admin/settings.go @@ -295,7 +295,7 @@ argocd admin settings validate --argocd-cm-path ./argocd-cm.yaml #Validates accounts and plugins settings in Kubernetes cluster of current kubeconfig context argocd admin settings validate --group accounts --group plugins --load-cluster-settings`, - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { ctx := c.Context() settingsManager, err := cmdCtx.createSettingsManager(ctx) @@ -511,7 +511,7 @@ argocd admin settings resource-overrides health ./deploy.yaml --argocd-cm-path . os.Exit(1) } - executeResourceOverrideCommand(ctx, cmdCtx, args, func(res unstructured.Unstructured, override v1alpha1.ResourceOverride, overrides map[string]v1alpha1.ResourceOverride) { + executeResourceOverrideCommand(ctx, cmdCtx, args, func(res unstructured.Unstructured, _ v1alpha1.ResourceOverride, overrides map[string]v1alpha1.ResourceOverride) { gvk := res.GroupVersionKind() resHealth, err := healthutil.GetResourceHealth(&res, lua.ResourceHealthOverrides(overrides)) diff --git a/cmd/argocd/commands/app.go b/cmd/argocd/commands/app.go index 2a9eca19f6..37b0e45a47 100644 --- a/cmd/argocd/commands/app.go +++ b/cmd/argocd/commands/app.go @@ -1664,7 +1664,7 @@ func NewApplicationListCommand(clientOpts *argocdclient.ClientOptions) *cobra.Co argocd app list -l app.kubernetes.io/instance argocd app list -l '!app.kubernetes.io/instance' argocd app list -l 'app.kubernetes.io/instance notin (my-app,other-app)'`, - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { ctx := c.Context() conn, appIf := headless.NewClientOrDie(clientOpts, c).NewApplicationClientOrDie() diff --git a/cmd/argocd/commands/app_test.go b/cmd/argocd/commands/app_test.go index c3536bc3c5..3e413dfa53 100644 --- a/cmd/argocd/commands/app_test.go +++ b/cmd/argocd/commands/app_test.go @@ -1029,7 +1029,7 @@ func TestTargetObjects_invalid(t *testing.T) { assert.Error(t, err) } -func TestCheckForDeleteEvent(t *testing.T) { +func TestCheckForDeleteEvent(_ *testing.T) { ctx := context.Background() fakeClient := new(fakeAcdClient) @@ -1942,7 +1942,7 @@ type customAcdClient struct { *fakeAcdClient } -func (c *customAcdClient) WatchApplicationWithRetry(ctx context.Context, appName string, revision string) chan *v1alpha1.ApplicationWatchEvent { +func (c *customAcdClient) WatchApplicationWithRetry(ctx context.Context, _ string, _ string) chan *v1alpha1.ApplicationWatchEvent { appEventsCh := make(chan *v1alpha1.ApplicationWatchEvent) _, appClient := c.NewApplicationClientOrDie() app, _ := appClient.Get(ctx, &applicationpkg.ApplicationQuery{}) @@ -1982,19 +1982,19 @@ func (c *fakeConnection) Close() error { type fakeSettingsServiceClient struct{} -func (f fakeSettingsServiceClient) Get(ctx context.Context, in *settingspkg.SettingsQuery, opts ...grpc.CallOption) (*settingspkg.Settings, error) { +func (f fakeSettingsServiceClient) Get(_ context.Context, _ *settingspkg.SettingsQuery, _ ...grpc.CallOption) (*settingspkg.Settings, error) { return &settingspkg.Settings{ URL: "http://localhost:8080", }, nil } -func (f fakeSettingsServiceClient) GetPlugins(ctx context.Context, in *settingspkg.SettingsQuery, opts ...grpc.CallOption) (*settingspkg.SettingsPluginsResponse, error) { +func (f fakeSettingsServiceClient) GetPlugins(_ context.Context, _ *settingspkg.SettingsQuery, _ ...grpc.CallOption) (*settingspkg.SettingsPluginsResponse, error) { return nil, nil } type fakeAppServiceClient struct{} -func (c *fakeAppServiceClient) Get(ctx context.Context, in *applicationpkg.ApplicationQuery, opts ...grpc.CallOption) (*v1alpha1.Application, error) { +func (c *fakeAppServiceClient) Get(_ context.Context, _ *applicationpkg.ApplicationQuery, _ ...grpc.CallOption) (*v1alpha1.Application, error) { time := metav1.Date(2020, time.November, 10, 23, 0, 0, 0, time.UTC) return &v1alpha1.Application{ ObjectMeta: metav1.ObjectMeta{ @@ -2062,111 +2062,111 @@ func (c *fakeAppServiceClient) Get(ctx context.Context, in *applicationpkg.Appli }, nil } -func (c *fakeAppServiceClient) List(ctx context.Context, in *applicationpkg.ApplicationQuery, opts ...grpc.CallOption) (*v1alpha1.ApplicationList, error) { +func (c *fakeAppServiceClient) List(_ context.Context, _ *applicationpkg.ApplicationQuery, _ ...grpc.CallOption) (*v1alpha1.ApplicationList, error) { return nil, nil } -func (c *fakeAppServiceClient) ListResourceEvents(ctx context.Context, in *applicationpkg.ApplicationResourceEventsQuery, opts ...grpc.CallOption) (*corev1.EventList, error) { +func (c *fakeAppServiceClient) ListResourceEvents(_ context.Context, _ *applicationpkg.ApplicationResourceEventsQuery, _ ...grpc.CallOption) (*corev1.EventList, error) { return nil, nil } -func (c *fakeAppServiceClient) Watch(ctx context.Context, in *applicationpkg.ApplicationQuery, opts ...grpc.CallOption) (applicationpkg.ApplicationService_WatchClient, error) { +func (c *fakeAppServiceClient) Watch(_ context.Context, _ *applicationpkg.ApplicationQuery, _ ...grpc.CallOption) (applicationpkg.ApplicationService_WatchClient, error) { return nil, nil } -func (c *fakeAppServiceClient) Create(ctx context.Context, in *applicationpkg.ApplicationCreateRequest, opts ...grpc.CallOption) (*v1alpha1.Application, error) { +func (c *fakeAppServiceClient) Create(_ context.Context, _ *applicationpkg.ApplicationCreateRequest, _ ...grpc.CallOption) (*v1alpha1.Application, error) { return nil, nil } -func (c *fakeAppServiceClient) GetApplicationSyncWindows(ctx context.Context, in *applicationpkg.ApplicationSyncWindowsQuery, opts ...grpc.CallOption) (*applicationpkg.ApplicationSyncWindowsResponse, error) { +func (c *fakeAppServiceClient) GetApplicationSyncWindows(_ context.Context, _ *applicationpkg.ApplicationSyncWindowsQuery, _ ...grpc.CallOption) (*applicationpkg.ApplicationSyncWindowsResponse, error) { return nil, nil } -func (c *fakeAppServiceClient) RevisionMetadata(ctx context.Context, in *applicationpkg.RevisionMetadataQuery, opts ...grpc.CallOption) (*v1alpha1.RevisionMetadata, error) { +func (c *fakeAppServiceClient) RevisionMetadata(_ context.Context, _ *applicationpkg.RevisionMetadataQuery, _ ...grpc.CallOption) (*v1alpha1.RevisionMetadata, error) { return nil, nil } -func (c *fakeAppServiceClient) RevisionChartDetails(ctx context.Context, in *applicationpkg.RevisionMetadataQuery, opts ...grpc.CallOption) (*v1alpha1.ChartDetails, error) { +func (c *fakeAppServiceClient) RevisionChartDetails(_ context.Context, _ *applicationpkg.RevisionMetadataQuery, _ ...grpc.CallOption) (*v1alpha1.ChartDetails, error) { return nil, nil } -func (c *fakeAppServiceClient) GetManifests(ctx context.Context, in *applicationpkg.ApplicationManifestQuery, opts ...grpc.CallOption) (*apiclient.ManifestResponse, error) { +func (c *fakeAppServiceClient) GetManifests(_ context.Context, _ *applicationpkg.ApplicationManifestQuery, _ ...grpc.CallOption) (*apiclient.ManifestResponse, error) { return nil, nil } -func (c *fakeAppServiceClient) GetManifestsWithFiles(ctx context.Context, opts ...grpc.CallOption) (applicationpkg.ApplicationService_GetManifestsWithFilesClient, error) { +func (c *fakeAppServiceClient) GetManifestsWithFiles(_ context.Context, _ ...grpc.CallOption) (applicationpkg.ApplicationService_GetManifestsWithFilesClient, error) { return nil, nil } -func (c *fakeAppServiceClient) Update(ctx context.Context, in *applicationpkg.ApplicationUpdateRequest, opts ...grpc.CallOption) (*v1alpha1.Application, error) { +func (c *fakeAppServiceClient) Update(_ context.Context, _ *applicationpkg.ApplicationUpdateRequest, _ ...grpc.CallOption) (*v1alpha1.Application, error) { return nil, nil } -func (c *fakeAppServiceClient) UpdateSpec(ctx context.Context, in *applicationpkg.ApplicationUpdateSpecRequest, opts ...grpc.CallOption) (*v1alpha1.ApplicationSpec, error) { +func (c *fakeAppServiceClient) UpdateSpec(_ context.Context, _ *applicationpkg.ApplicationUpdateSpecRequest, _ ...grpc.CallOption) (*v1alpha1.ApplicationSpec, error) { return nil, nil } -func (c *fakeAppServiceClient) Patch(ctx context.Context, in *applicationpkg.ApplicationPatchRequest, opts ...grpc.CallOption) (*v1alpha1.Application, error) { +func (c *fakeAppServiceClient) Patch(_ context.Context, _ *applicationpkg.ApplicationPatchRequest, _ ...grpc.CallOption) (*v1alpha1.Application, error) { return nil, nil } -func (c *fakeAppServiceClient) Delete(ctx context.Context, in *applicationpkg.ApplicationDeleteRequest, opts ...grpc.CallOption) (*applicationpkg.ApplicationResponse, error) { +func (c *fakeAppServiceClient) Delete(_ context.Context, _ *applicationpkg.ApplicationDeleteRequest, _ ...grpc.CallOption) (*applicationpkg.ApplicationResponse, error) { return nil, nil } -func (c *fakeAppServiceClient) Sync(ctx context.Context, in *applicationpkg.ApplicationSyncRequest, opts ...grpc.CallOption) (*v1alpha1.Application, error) { +func (c *fakeAppServiceClient) Sync(_ context.Context, _ *applicationpkg.ApplicationSyncRequest, _ ...grpc.CallOption) (*v1alpha1.Application, error) { return nil, nil } -func (c *fakeAppServiceClient) ManagedResources(ctx context.Context, in *applicationpkg.ResourcesQuery, opts ...grpc.CallOption) (*applicationpkg.ManagedResourcesResponse, error) { +func (c *fakeAppServiceClient) ManagedResources(_ context.Context, _ *applicationpkg.ResourcesQuery, _ ...grpc.CallOption) (*applicationpkg.ManagedResourcesResponse, error) { return nil, nil } -func (c *fakeAppServiceClient) ResourceTree(ctx context.Context, in *applicationpkg.ResourcesQuery, opts ...grpc.CallOption) (*v1alpha1.ApplicationTree, error) { +func (c *fakeAppServiceClient) ResourceTree(_ context.Context, _ *applicationpkg.ResourcesQuery, _ ...grpc.CallOption) (*v1alpha1.ApplicationTree, error) { return nil, nil } -func (c *fakeAppServiceClient) WatchResourceTree(ctx context.Context, in *applicationpkg.ResourcesQuery, opts ...grpc.CallOption) (applicationpkg.ApplicationService_WatchResourceTreeClient, error) { +func (c *fakeAppServiceClient) WatchResourceTree(_ context.Context, _ *applicationpkg.ResourcesQuery, _ ...grpc.CallOption) (applicationpkg.ApplicationService_WatchResourceTreeClient, error) { return nil, nil } -func (c *fakeAppServiceClient) Rollback(ctx context.Context, in *applicationpkg.ApplicationRollbackRequest, opts ...grpc.CallOption) (*v1alpha1.Application, error) { +func (c *fakeAppServiceClient) Rollback(_ context.Context, _ *applicationpkg.ApplicationRollbackRequest, _ ...grpc.CallOption) (*v1alpha1.Application, error) { return nil, nil } -func (c *fakeAppServiceClient) TerminateOperation(ctx context.Context, in *applicationpkg.OperationTerminateRequest, opts ...grpc.CallOption) (*applicationpkg.OperationTerminateResponse, error) { +func (c *fakeAppServiceClient) TerminateOperation(_ context.Context, _ *applicationpkg.OperationTerminateRequest, _ ...grpc.CallOption) (*applicationpkg.OperationTerminateResponse, error) { return nil, nil } -func (c *fakeAppServiceClient) GetResource(ctx context.Context, in *applicationpkg.ApplicationResourceRequest, opts ...grpc.CallOption) (*applicationpkg.ApplicationResourceResponse, error) { +func (c *fakeAppServiceClient) GetResource(_ context.Context, _ *applicationpkg.ApplicationResourceRequest, _ ...grpc.CallOption) (*applicationpkg.ApplicationResourceResponse, error) { return nil, nil } -func (c *fakeAppServiceClient) PatchResource(ctx context.Context, in *applicationpkg.ApplicationResourcePatchRequest, opts ...grpc.CallOption) (*applicationpkg.ApplicationResourceResponse, error) { +func (c *fakeAppServiceClient) PatchResource(_ context.Context, _ *applicationpkg.ApplicationResourcePatchRequest, _ ...grpc.CallOption) (*applicationpkg.ApplicationResourceResponse, error) { return nil, nil } -func (c *fakeAppServiceClient) ListResourceActions(ctx context.Context, in *applicationpkg.ApplicationResourceRequest, opts ...grpc.CallOption) (*applicationpkg.ResourceActionsListResponse, error) { +func (c *fakeAppServiceClient) ListResourceActions(_ context.Context, _ *applicationpkg.ApplicationResourceRequest, _ ...grpc.CallOption) (*applicationpkg.ResourceActionsListResponse, error) { return nil, nil } -func (c *fakeAppServiceClient) RunResourceAction(ctx context.Context, in *applicationpkg.ResourceActionRunRequest, opts ...grpc.CallOption) (*applicationpkg.ApplicationResponse, error) { +func (c *fakeAppServiceClient) RunResourceAction(_ context.Context, _ *applicationpkg.ResourceActionRunRequest, _ ...grpc.CallOption) (*applicationpkg.ApplicationResponse, error) { return nil, nil } -func (c *fakeAppServiceClient) DeleteResource(ctx context.Context, in *applicationpkg.ApplicationResourceDeleteRequest, opts ...grpc.CallOption) (*applicationpkg.ApplicationResponse, error) { +func (c *fakeAppServiceClient) DeleteResource(_ context.Context, _ *applicationpkg.ApplicationResourceDeleteRequest, _ ...grpc.CallOption) (*applicationpkg.ApplicationResponse, error) { return nil, nil } -func (c *fakeAppServiceClient) PodLogs(ctx context.Context, in *applicationpkg.ApplicationPodLogsQuery, opts ...grpc.CallOption) (applicationpkg.ApplicationService_PodLogsClient, error) { +func (c *fakeAppServiceClient) PodLogs(_ context.Context, _ *applicationpkg.ApplicationPodLogsQuery, _ ...grpc.CallOption) (applicationpkg.ApplicationService_PodLogsClient, error) { return nil, nil } -func (c *fakeAppServiceClient) ListLinks(ctx context.Context, in *applicationpkg.ListAppLinksRequest, opts ...grpc.CallOption) (*applicationpkg.LinksResponse, error) { +func (c *fakeAppServiceClient) ListLinks(_ context.Context, _ *applicationpkg.ListAppLinksRequest, _ ...grpc.CallOption) (*applicationpkg.LinksResponse, error) { return nil, nil } -func (c *fakeAppServiceClient) ListResourceLinks(ctx context.Context, in *applicationpkg.ApplicationResourceRequest, opts ...grpc.CallOption) (*applicationpkg.LinksResponse, error) { +func (c *fakeAppServiceClient) ListResourceLinks(_ context.Context, _ *applicationpkg.ApplicationResourceRequest, _ ...grpc.CallOption) (*applicationpkg.LinksResponse, error) { return nil, nil } @@ -2284,7 +2284,7 @@ func (c *fakeAcdClient) NewAccountClientOrDie() (io.Closer, accountpkg.AccountSe return nil, nil } -func (c *fakeAcdClient) WatchApplicationWithRetry(ctx context.Context, appName string, revision string) chan *v1alpha1.ApplicationWatchEvent { +func (c *fakeAcdClient) WatchApplicationWithRetry(_ context.Context, _ string, _ string) chan *v1alpha1.ApplicationWatchEvent { appEventsCh := make(chan *v1alpha1.ApplicationWatchEvent) go func() { diff --git a/cmd/argocd/commands/applicationset.go b/cmd/argocd/commands/applicationset.go index 64ed8d3b45..55364876ee 100644 --- a/cmd/argocd/commands/applicationset.go +++ b/cmd/argocd/commands/applicationset.go @@ -293,7 +293,7 @@ func NewApplicationSetListCommand(clientOpts *argocdclient.ClientOptions) *cobra # List all ApplicationSets argocd appset list `), - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { ctx := c.Context() conn, appIf := headless.NewClientOrDie(clientOpts, c).NewApplicationSetClientOrDie() diff --git a/cmd/argocd/commands/bcrypt.go b/cmd/argocd/commands/bcrypt.go index d2557ef411..7b0b1a75af 100644 --- a/cmd/argocd/commands/bcrypt.go +++ b/cmd/argocd/commands/bcrypt.go @@ -16,7 +16,7 @@ func NewBcryptCmd() *cobra.Command { Short: "Generate bcrypt hash for any password", Example: `# Generate bcrypt hash for any password argocd account bcrypt --password YOUR_PASSWORD`, - Run: func(cmd *cobra.Command, args []string) { + Run: func(cmd *cobra.Command, _ []string) { bytePassword := []byte(password) // Hashing the password hash, err := bcrypt.GenerateFromPassword(bytePassword, bcrypt.DefaultCost) diff --git a/cmd/argocd/commands/cert.go b/cmd/argocd/commands/cert.go index 45c78a0483..6580b192f3 100644 --- a/cmd/argocd/commands/cert.go +++ b/cmd/argocd/commands/cert.go @@ -148,7 +148,7 @@ func NewCertAddSSHCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command command := &cobra.Command{ Use: "add-ssh --batch", Short: "Add SSH known host entries for repository servers", - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { ctx := c.Context() conn, certIf := headless.NewClientOrDie(clientOpts, c).NewCertClientOrDie() @@ -276,7 +276,7 @@ func NewCertListCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command { command := &cobra.Command{ Use: "list", Short: "List configured certificates", - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { ctx := c.Context() if certType != "" { diff --git a/cmd/argocd/commands/cluster.go b/cmd/argocd/commands/cluster.go index 165b162356..38435fba4a 100644 --- a/cmd/argocd/commands/cluster.go +++ b/cmd/argocd/commands/cluster.go @@ -496,7 +496,7 @@ func NewClusterListCommand(clientOpts *argocdclient.ClientOptions) *cobra.Comman command := &cobra.Command{ Use: "list", Short: "List configured clusters", - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { ctx := c.Context() conn, clusterIf := headless.NewClientOrDie(clientOpts, c).NewClusterClientOrDie() diff --git a/cmd/argocd/commands/cluster_test.go b/cmd/argocd/commands/cluster_test.go index 311713a30f..53086c1f95 100644 --- a/cmd/argocd/commands/cluster_test.go +++ b/cmd/argocd/commands/cluster_test.go @@ -26,7 +26,7 @@ func Test_getQueryBySelector(t *testing.T) { assert.Equal(t, "https://my-server", query.Server) } -func Test_printClusterTable(t *testing.T) { +func Test_printClusterTable(_ *testing.T) { printClusterTable([]v1alpha1.Cluster{ { Server: "my-server", diff --git a/cmd/argocd/commands/configure.go b/cmd/argocd/commands/configure.go index 15c4bef41e..d61bbe2d45 100644 --- a/cmd/argocd/commands/configure.go +++ b/cmd/argocd/commands/configure.go @@ -24,7 +24,7 @@ argocd configure --prompts-enabled=true # Disable optional interactive prompts argocd configure --prompts-enabled=false`, - Run: func(c *cobra.Command, args []string) { + Run: func(_ *cobra.Command, _ []string) { localCfg, err := localconfig.ReadLocalConfig(globalClientOpts.ConfigPath) errors.CheckError(err) diff --git a/cmd/argocd/commands/gpg.go b/cmd/argocd/commands/gpg.go index 02cd7adea1..1390306b76 100644 --- a/cmd/argocd/commands/gpg.go +++ b/cmd/argocd/commands/gpg.go @@ -54,7 +54,7 @@ func NewGPGListCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command { argocd gpg list -o yaml `), - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { ctx := c.Context() conn, gpgIf := headless.NewClientOrDie(clientOpts, c).NewGPGKeyClientOrDie() @@ -133,7 +133,7 @@ func NewGPGAddCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command { argocd gpg add --from /path/to/keyfile `), - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { ctx := c.Context() if fromFile == "" { diff --git a/cmd/argocd/commands/project.go b/cmd/argocd/commands/project.go index 50ae57354a..9332b44747 100644 --- a/cmd/argocd/commands/project.go +++ b/cmd/argocd/commands/project.go @@ -828,7 +828,7 @@ func NewProjectListCommand(clientOpts *argocdclient.ClientOptions) *cobra.Comman # List all available projects in yaml format argocd proj list -o yaml `), - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { ctx := c.Context() conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie() diff --git a/cmd/argocd/commands/repo.go b/cmd/argocd/commands/repo.go index 33a39fbb67..3202a7442c 100644 --- a/cmd/argocd/commands/repo.go +++ b/cmd/argocd/commands/repo.go @@ -307,7 +307,7 @@ func NewRepoListCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command { command := &cobra.Command{ Use: "list", Short: "List configured repositories", - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { ctx := c.Context() conn, repoIf := headless.NewClientOrDie(clientOpts, c).NewRepoClientOrDie() diff --git a/cmd/argocd/commands/repocreds.go b/cmd/argocd/commands/repocreds.go index 1cc99bf872..c0de970a5f 100644 --- a/cmd/argocd/commands/repocreds.go +++ b/cmd/argocd/commands/repocreds.go @@ -268,7 +268,7 @@ func NewRepoCredsListCommand(clientOpts *argocdclient.ClientOptions) *cobra.Comm # List all repo urls in url format argocd repocreds list -o url `), - Run: func(c *cobra.Command, args []string) { + Run: func(c *cobra.Command, _ []string) { ctx := c.Context() conn, repoIf := headless.NewClientOrDie(clientOpts, c).NewRepoCredsClientOrDie() diff --git a/cmd/argocd/commands/version.go b/cmd/argocd/commands/version.go index ee7385d06d..293fd50bee 100644 --- a/cmd/argocd/commands/version.go +++ b/cmd/argocd/commands/version.go @@ -39,7 +39,7 @@ func NewVersionCmd(clientOpts *argocdclient.ClientOptions, serverVersion *versio # Print only client and server core version strings in YAML format argocd version --short -o yaml `, - Run: func(cmd *cobra.Command, args []string) { + Run: func(cmd *cobra.Command, _ []string) { ctx := cmd.Context() cv := common.GetVersion() diff --git a/cmpserver/plugin/plugin.go b/cmpserver/plugin/plugin.go index ba149c39d1..9e87e2d74e 100644 --- a/cmpserver/plugin/plugin.go +++ b/cmpserver/plugin/plugin.go @@ -425,7 +425,7 @@ func getParametersAnnouncement(ctx context.Context, appDir string, announcements return repoResponse, nil } -func (s *Service) CheckPluginConfiguration(ctx context.Context, _ *empty.Empty) (*apiclient.CheckPluginConfigurationResponse, error) { +func (s *Service) CheckPluginConfiguration(_ context.Context, _ *empty.Empty) (*apiclient.CheckPluginConfigurationResponse, error) { isDiscoveryConfigured := s.isDiscoveryConfigured() response := &apiclient.CheckPluginConfigurationResponse{IsDiscoveryConfigured: isDiscoveryConfigured, ProvideGitCreds: s.initConstants.PluginConfig.Spec.ProvideGitCreds} diff --git a/commitserver/commit/commit.go b/commitserver/commit/commit.go index 52e7548b36..f351388f20 100644 --- a/commitserver/commit/commit.go +++ b/commitserver/commit/commit.go @@ -34,7 +34,7 @@ func NewService(gitCredsStore git.CredsStore, metricsServer *metrics.Server) *Se // CommitHydratedManifests handles a commit request. It clones the repository, checks out the sync branch, checks out // the target branch, clears the repository contents, writes the manifests to the repository, commits the changes, and // pushes the changes. It returns the hydrated revision SHA and an error if one occurred. -func (s *Service) CommitHydratedManifests(ctx context.Context, r *apiclient.CommitHydratedManifestsRequest) (*apiclient.CommitHydratedManifestsResponse, error) { +func (s *Service) CommitHydratedManifests(_ context.Context, r *apiclient.CommitHydratedManifestsRequest) (*apiclient.CommitHydratedManifestsResponse, error) { // This method is intentionally short. It's a wrapper around handleCommitRequest that adds metrics and logging. // Keep logic here minimal and put most of the logic in handleCommitRequest. startTime := time.Now() diff --git a/controller/appcontroller.go b/controller/appcontroller.go index e4d5eda967..ebb52582be 100644 --- a/controller/appcontroller.go +++ b/controller/appcontroller.go @@ -239,7 +239,7 @@ func NewApplicationController( } } }, - UpdateFunc: func(old, new any) { + UpdateFunc: func(_, new any) { if key, err := cache.MetaNamespaceKeyFunc(new); err == nil { ctrl.projectRefreshQueue.AddRateLimited(key) if projMeta, ok := new.(metav1.Object); ok { @@ -270,7 +270,7 @@ func NewApplicationController( deploymentInformer = factory.Apps().V1().Deployments() } - readinessHealthCheck := func(r *http.Request) error { + readinessHealthCheck := func(_ *http.Request) error { if dynamicClusterDistributionEnabled { applicationControllerName := env.StringFromEnv(common.EnvAppControllerName, common.DefaultApplicationControllerName) appControllerDeployment, err := deploymentInformer.Lister().Deployments(settingsMgr.GetNamespace()).Get(applicationControllerName) @@ -587,7 +587,7 @@ func (ctrl *ApplicationController) getResourceTree(a *appv1.Application, managed managedResourcesKeys = append(managedResourcesKeys, kube.GetResourceKey(live)) } } - err = ctrl.stateCache.IterateHierarchyV2(a.Spec.Destination.Server, managedResourcesKeys, func(child appv1.ResourceNode, appName string) bool { + err = ctrl.stateCache.IterateHierarchyV2(a.Spec.Destination.Server, managedResourcesKeys, func(child appv1.ResourceNode, _ string) bool { permitted, _ := proj.IsResourcePermitted(schema.GroupKind{Group: child.ResourceRef.Group, Kind: child.ResourceRef.Kind}, child.Namespace, a.Spec.Destination, func(project string) ([]*appv1.Cluster, error) { clusters, err := ctrl.db.GetProjectClusters(context.TODO(), project) if err != nil { diff --git a/controller/appcontroller_test.go b/controller/appcontroller_test.go index 350fa959c3..2a5b15a646 100644 --- a/controller/appcontroller_test.go +++ b/controller/appcontroller_test.go @@ -880,11 +880,11 @@ func TestFinalizeAppDeletion(t *testing.T) { fakeAppCs.AddReactor("get", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { return defaultReactor.React(action) }) - fakeAppCs.AddReactor("patch", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { + fakeAppCs.AddReactor("patch", "*", func(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) { patched = true return true, &v1alpha1.Application{}, nil }) - err := ctrl.finalizeApplicationDeletion(app, func(project string) ([]*v1alpha1.Cluster, error) { + err := ctrl.finalizeApplicationDeletion(app, func(_ string) ([]*v1alpha1.Cluster, error) { return []*v1alpha1.Cluster{}, nil }) require.NoError(t, err) @@ -932,11 +932,11 @@ func TestFinalizeAppDeletion(t *testing.T) { fakeAppCs.AddReactor("get", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { return defaultReactor.React(action) }) - fakeAppCs.AddReactor("patch", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { + fakeAppCs.AddReactor("patch", "*", func(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) { patched = true return true, &v1alpha1.Application{}, nil }) - err := ctrl.finalizeApplicationDeletion(app, func(project string) ([]*v1alpha1.Cluster, error) { + err := ctrl.finalizeApplicationDeletion(app, func(_ string) ([]*v1alpha1.Cluster, error) { return []*v1alpha1.Cluster{}, nil }) require.NoError(t, err) @@ -966,11 +966,11 @@ func TestFinalizeAppDeletion(t *testing.T) { fakeAppCs.AddReactor("get", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { return defaultReactor.React(action) }) - fakeAppCs.AddReactor("patch", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { + fakeAppCs.AddReactor("patch", "*", func(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) { patched = true return true, &v1alpha1.Application{}, nil }) - err := ctrl.finalizeApplicationDeletion(app, func(project string) ([]*v1alpha1.Cluster, error) { + err := ctrl.finalizeApplicationDeletion(app, func(_ string) ([]*v1alpha1.Cluster, error) { return []*v1alpha1.Cluster{}, nil }) require.NoError(t, err) @@ -994,7 +994,7 @@ func TestFinalizeAppDeletion(t *testing.T) { fakeAppCs.AddReactor("get", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { return defaultReactor.React(action) }) - err := ctrl.finalizeApplicationDeletion(app, func(project string) ([]*v1alpha1.Cluster, error) { + err := ctrl.finalizeApplicationDeletion(app, func(_ string) ([]*v1alpha1.Cluster, error) { return []*v1alpha1.Cluster{}, nil }) require.NoError(t, err) @@ -1033,11 +1033,11 @@ func TestFinalizeAppDeletion(t *testing.T) { fakeAppCs.AddReactor("get", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { return defaultReactor.React(action) }) - fakeAppCs.AddReactor("patch", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { + fakeAppCs.AddReactor("patch", "*", func(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) { patched = true return true, &v1alpha1.Application{}, nil }) - err := ctrl.finalizeApplicationDeletion(app, func(project string) ([]*v1alpha1.Cluster, error) { + err := ctrl.finalizeApplicationDeletion(app, func(_ string) ([]*v1alpha1.Cluster, error) { return []*v1alpha1.Cluster{}, nil }) require.NoError(t, err) @@ -1077,11 +1077,11 @@ func TestFinalizeAppDeletion(t *testing.T) { fakeAppCs.AddReactor("get", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { return defaultReactor.React(action) }) - fakeAppCs.AddReactor("patch", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { + fakeAppCs.AddReactor("patch", "*", func(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) { patched = true return true, &v1alpha1.Application{}, nil }) - err := ctrl.finalizeApplicationDeletion(app, func(project string) ([]*v1alpha1.Cluster, error) { + err := ctrl.finalizeApplicationDeletion(app, func(_ string) ([]*v1alpha1.Cluster, error) { return []*v1alpha1.Cluster{}, nil }) require.NoError(t, err) @@ -1124,11 +1124,11 @@ func TestFinalizeAppDeletion(t *testing.T) { fakeAppCs.AddReactor("get", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { return defaultReactor.React(action) }) - fakeAppCs.AddReactor("patch", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { + fakeAppCs.AddReactor("patch", "*", func(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) { patched = true return true, &v1alpha1.Application{}, nil }) - err := ctrl.finalizeApplicationDeletion(app, func(project string) ([]*v1alpha1.Cluster, error) { + err := ctrl.finalizeApplicationDeletion(app, func(_ string) ([]*v1alpha1.Cluster, error) { return []*v1alpha1.Cluster{}, nil }) require.NoError(t, err) @@ -1307,7 +1307,7 @@ func TestSetOperationStateOnDeletedApp(t *testing.T) { fakeAppCs := ctrl.applicationClientset.(*appclientset.Clientset) fakeAppCs.ReactionChain = nil patched := false - fakeAppCs.AddReactor("patch", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { + fakeAppCs.AddReactor("patch", "*", func(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) { patched = true return true, &v1alpha1.Application{}, apierrors.NewNotFound(schema.GroupResource{}, "my-app") }) @@ -1338,7 +1338,7 @@ func TestSetOperationStateLogRetries(t *testing.T) { fakeAppCs := ctrl.applicationClientset.(*appclientset.Clientset) fakeAppCs.ReactionChain = nil patched := false - fakeAppCs.AddReactor("patch", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { + fakeAppCs.AddReactor("patch", "*", func(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) { if !patched { patched = true return true, &v1alpha1.Application{}, errors.New("fake error") @@ -1935,7 +1935,7 @@ func TestFinalizeProjectDeletion_HasApplications(t *testing.T) { fakeAppCs := ctrl.applicationClientset.(*appclientset.Clientset) patched := false - fakeAppCs.PrependReactor("patch", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { + fakeAppCs.PrependReactor("patch", "*", func(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) { patched = true return true, &v1alpha1.Application{}, nil }) diff --git a/controller/cache/cache.go b/controller/cache/cache.go index b649b02d3c..f3c86f409b 100644 --- a/controller/cache/cache.go +++ b/controller/cache/cache.go @@ -618,7 +618,7 @@ func (c *liveStateCache) getCluster(server string) (clustercache.ClusterCache, e c.onObjectUpdated(toNotify, ref) }) - _ = clusterCache.OnEvent(func(event watch.EventType, un *unstructured.Unstructured) { + _ = clusterCache.OnEvent(func(_ watch.EventType, un *unstructured.Unstructured) { gvk := un.GroupVersionKind() c.metricsServer.IncClusterEventsCount(cluster.Server, gvk.Group, gvk.Kind) }) diff --git a/controller/cache/cache_test.go b/controller/cache/cache_test.go index 076633444e..c02a8fb2c6 100644 --- a/controller/cache/cache_test.go +++ b/controller/cache/cache_test.go @@ -40,7 +40,7 @@ func (n netError) Error() string { return string(n) } func (n netError) Timeout() bool { return false } func (n netError) Temporary() bool { return false } -func TestHandleModEvent_HasChanges(t *testing.T) { +func TestHandleModEvent_HasChanges(_ *testing.T) { clusterCache := &mocks.ClusterCache{} clusterCache.On("Invalidate", mock.Anything, mock.Anything).Return(nil).Once() clusterCache.On("EnsureSynced").Return(nil).Once() @@ -72,7 +72,7 @@ func TestHandleModEvent_ClusterExcluded(t *testing.T) { clustersCache := liveStateCache{ db: nil, appInformer: nil, - onObjectUpdated: func(managedByApp map[string]bool, ref corev1.ObjectReference) { + onObjectUpdated: func(_ map[string]bool, _ corev1.ObjectReference) { }, kubectl: nil, settingsMgr: &argosettings.SettingsManager{}, @@ -97,7 +97,7 @@ func TestHandleModEvent_ClusterExcluded(t *testing.T) { assert.Len(t, clustersCache.clusters, 1) } -func TestHandleModEvent_NoChanges(t *testing.T) { +func TestHandleModEvent_NoChanges(_ *testing.T) { clusterCache := &mocks.ClusterCache{} clusterCache.On("Invalidate", mock.Anything).Panic("should not invalidate") clusterCache.On("EnsureSynced").Return(nil).Panic("should not re-sync") @@ -174,7 +174,7 @@ func TestHandleDeleteEvent_CacheDeadlock(t *testing.T) { handleDeleteWasCalled.Lock() engineHoldsEngineLock.Lock() - gitopsEngineClusterCache.On("EnsureSynced").Run(func(args mock.Arguments) { + gitopsEngineClusterCache.On("EnsureSynced").Run(func(_ mock.Arguments) { gitopsEngineClusterCacheLock.Lock() t.Log("EnsureSynced: Engine has engine lock") engineHoldsEngineLock.Unlock() @@ -188,7 +188,7 @@ func TestHandleDeleteEvent_CacheDeadlock(t *testing.T) { ensureSyncedCompleted.Unlock() }).Return(nil).Once() - gitopsEngineClusterCache.On("Invalidate").Run(func(args mock.Arguments) { + gitopsEngineClusterCache.On("Invalidate").Run(func(_ mock.Arguments) { // Allow EnsureSynced to continue now that we're in the deadlock condition handleDeleteWasCalled.Unlock() // Wait until gitops engine holds the gitops lock diff --git a/controller/clusterinfoupdater_test.go b/controller/clusterinfoupdater_test.go index 4467f44b3c..b6ae81dc27 100644 --- a/controller/clusterinfoupdater_test.go +++ b/controller/clusterinfoupdater_test.go @@ -102,7 +102,7 @@ func TestClusterSecretUpdater(t *testing.T) { } func TestUpdateClusterLabels(t *testing.T) { - shouldNotBeInvoked := func(ctx context.Context, cluster *v1alpha1.Cluster) (*v1alpha1.Cluster, error) { + shouldNotBeInvoked := func(_ context.Context, _ *v1alpha1.Cluster) (*v1alpha1.Cluster, error) { shouldNotHappen := errors.New("if an error happens here, something's wrong") require.NoError(t, shouldNotHappen) return nil, shouldNotHappen @@ -160,7 +160,7 @@ func TestUpdateClusterLabels(t *testing.T) { Server: "kubernetes.svc.local", Labels: map[string]string{"argocd.argoproj.io/kubernetes-version": "1.27", "argocd.argoproj.io/auto-label-cluster-info": "true"}, }, - func(ctx context.Context, cluster *v1alpha1.Cluster) (*v1alpha1.Cluster, error) { + func(_ context.Context, cluster *v1alpha1.Cluster) (*v1alpha1.Cluster, error) { assert.Equal(t, "1.28", cluster.Labels["argocd.argoproj.io/kubernetes-version"]) return nil, nil }, @@ -176,7 +176,7 @@ func TestUpdateClusterLabels(t *testing.T) { Server: "kubernetes.svc.local", Labels: map[string]string{"argocd.argoproj.io/kubernetes-version": "1.27", "argocd.argoproj.io/auto-label-cluster-info": "true"}, }, - func(ctx context.Context, cluster *v1alpha1.Cluster) (*v1alpha1.Cluster, error) { + func(_ context.Context, cluster *v1alpha1.Cluster) (*v1alpha1.Cluster, error) { assert.Equal(t, "1.28", cluster.Labels["argocd.argoproj.io/kubernetes-version"]) return nil, errors.New("some error happened while saving") }, diff --git a/controller/metrics/metrics_test.go b/controller/metrics/metrics_test.go index 5410e274e3..d50b51a534 100644 --- a/controller/metrics/metrics_test.go +++ b/controller/metrics/metrics_test.go @@ -171,11 +171,11 @@ status: status: Healthy ` -var noOpHealthCheck = func(r *http.Request) error { +var noOpHealthCheck = func(_ *http.Request) error { return nil } -var appFilter = func(obj any) bool { +var appFilter = func(_ any) bool { return true } @@ -203,7 +203,7 @@ func newFakeLister(fakeAppYAMLs ...string) (context.CancelFunc, applister.Applic fakeApps = append(fakeApps, a) } appClientset := appclientset.NewSimpleClientset(fakeApps...) - factory := appinformer.NewSharedInformerFactoryWithOptions(appClientset, 0, appinformer.WithNamespace("argocd"), appinformer.WithTweakListOptions(func(options *metav1.ListOptions) {})) + factory := appinformer.NewSharedInformerFactoryWithOptions(appClientset, 0, appinformer.WithNamespace("argocd"), appinformer.WithTweakListOptions(func(_ *metav1.ListOptions) {})) appInformer := factory.Argoproj().V1alpha1().Applications().Informer() go appInformer.Run(ctx.Done()) if !cache.WaitForCacheSync(ctx.Done(), appInformer.HasSynced) { diff --git a/controller/sharding/sharding.go b/controller/sharding/sharding.go index 1ae2052efd..4c087cd169 100644 --- a/controller/sharding/sharding.go +++ b/controller/sharding/sharding.go @@ -63,7 +63,7 @@ type shardApplicationControllerMapping struct { // and returns whether or not the cluster should be processed by a given shard. It calls the distributionFunction // to determine which shard will process the cluster, and if the given shard is equal to the calculated shard // the function will return true. -func GetClusterFilter(db db.ArgoDB, distributionFunction DistributionFunction, replicas, shard int) ClusterFilterFunction { +func GetClusterFilter(_ db.ArgoDB, distributionFunction DistributionFunction, replicas, shard int) ClusterFilterFunction { return func(c *v1alpha1.Cluster) bool { clusterShard := 0 if c != nil && c.Shard != nil { @@ -255,7 +255,7 @@ func getAppDistribution(getCluster clusterAccessor, getApps appAccessor) map[str // NoShardingDistributionFunction returns a DistributionFunction that will process all cluster by shard 0 // the function is created for API compatibility purposes and is not supposed to be activated. func NoShardingDistributionFunction() DistributionFunction { - return func(c *v1alpha1.Cluster) int { return 0 } + return func(_ *v1alpha1.Cluster) int { return 0 } } // InferShard extracts the shard index based on its hostname. diff --git a/controller/state.go b/controller/state.go index c981bb1cc0..d4c822ce66 100644 --- a/controller/state.go +++ b/controller/state.go @@ -780,7 +780,7 @@ func (m *appStateManager) CompareAppState(app *v1alpha1.Application, project *v1 } gvk := obj.GroupVersionKind() - isSelfReferencedObj := m.isSelfReferencedObj(liveObj, targetObj, app.GetName(), appLabelKey, trackingMethod, installationID) + isSelfReferencedObj := m.isSelfReferencedObj(liveObj, targetObj, app.GetName(), trackingMethod, installationID) resState := v1alpha1.ResourceStatus{ Namespace: obj.GetNamespace(), @@ -1108,7 +1108,7 @@ func NewAppStateManager( // group and kind) match the properties of the live object, or if the tracking method // used does not provide the required properties for matching. // Reference: https://github.com/argoproj/argo-cd/issues/8683 -func (m *appStateManager) isSelfReferencedObj(live, config *unstructured.Unstructured, appName, appLabelKey string, trackingMethod v1alpha1.TrackingMethod, installationID string) bool { +func (m *appStateManager) isSelfReferencedObj(live, config *unstructured.Unstructured, appName string, trackingMethod v1alpha1.TrackingMethod, installationID string) bool { if live == nil { return true } @@ -1141,7 +1141,7 @@ func (m *appStateManager) isSelfReferencedObj(live, config *unstructured.Unstruc // to match the properties from the live object. Cluster scoped objects // carry the app's destination namespace in the tracking annotation, // but are unique in GVK + name combination. - appInstance := m.resourceTracking.GetAppInstance(live, appLabelKey, trackingMethod, installationID) + appInstance := m.resourceTracking.GetAppInstance(live, trackingMethod, installationID) if appInstance != nil { return isSelfReferencedObj(live, *appInstance) } diff --git a/controller/state_test.go b/controller/state_test.go index 6c5f74c18d..2cb1bbd231 100644 --- a/controller/state_test.go +++ b/controller/state_test.go @@ -1410,8 +1410,8 @@ func TestIsLiveResourceManaged(t *testing.T) { configObj := managedObj.DeepCopy() // then - assert.True(t, manager.isSelfReferencedObj(managedObj, configObj, appName, common.AnnotationKeyAppInstance, argo.TrackingMethodLabel, "")) - assert.True(t, manager.isSelfReferencedObj(managedObj, configObj, appName, common.AnnotationKeyAppInstance, argo.TrackingMethodAnnotation, "")) + assert.True(t, manager.isSelfReferencedObj(managedObj, configObj, appName, argo.TrackingMethodLabel, "")) + assert.True(t, manager.isSelfReferencedObj(managedObj, configObj, appName, argo.TrackingMethodAnnotation, "")) }) t.Run("will return true if tracked with label", func(t *testing.T) { // given @@ -1419,43 +1419,43 @@ func TestIsLiveResourceManaged(t *testing.T) { configObj := managedObjWithLabel.DeepCopy() // then - assert.True(t, manager.isSelfReferencedObj(managedObjWithLabel, configObj, appName, common.AnnotationKeyAppInstance, argo.TrackingMethodLabel, "")) + assert.True(t, manager.isSelfReferencedObj(managedObjWithLabel, configObj, appName, argo.TrackingMethodLabel, "")) }) t.Run("will handle if trackingId has wrong resource name and config is nil", func(t *testing.T) { // given t.Parallel() // then - assert.True(t, manager.isSelfReferencedObj(unmanagedObjWrongName, nil, appName, common.AnnotationKeyAppInstance, argo.TrackingMethodLabel, "")) - assert.False(t, manager.isSelfReferencedObj(unmanagedObjWrongName, nil, appName, common.AnnotationKeyAppInstance, argo.TrackingMethodAnnotation, "")) + assert.True(t, manager.isSelfReferencedObj(unmanagedObjWrongName, nil, appName, argo.TrackingMethodLabel, "")) + assert.False(t, manager.isSelfReferencedObj(unmanagedObjWrongName, nil, appName, argo.TrackingMethodAnnotation, "")) }) t.Run("will handle if trackingId has wrong resource group and config is nil", func(t *testing.T) { // given t.Parallel() // then - assert.True(t, manager.isSelfReferencedObj(unmanagedObjWrongGroup, nil, appName, common.AnnotationKeyAppInstance, argo.TrackingMethodLabel, "")) - assert.False(t, manager.isSelfReferencedObj(unmanagedObjWrongGroup, nil, appName, common.AnnotationKeyAppInstance, argo.TrackingMethodAnnotation, "")) + assert.True(t, manager.isSelfReferencedObj(unmanagedObjWrongGroup, nil, appName, argo.TrackingMethodLabel, "")) + assert.False(t, manager.isSelfReferencedObj(unmanagedObjWrongGroup, nil, appName, argo.TrackingMethodAnnotation, "")) }) t.Run("will handle if trackingId has wrong kind and config is nil", func(t *testing.T) { // given t.Parallel() // then - assert.True(t, manager.isSelfReferencedObj(unmanagedObjWrongKind, nil, appName, common.AnnotationKeyAppInstance, argo.TrackingMethodLabel, "")) - assert.False(t, manager.isSelfReferencedObj(unmanagedObjWrongKind, nil, appName, common.AnnotationKeyAppInstance, argo.TrackingMethodAnnotation, "")) + assert.True(t, manager.isSelfReferencedObj(unmanagedObjWrongKind, nil, appName, argo.TrackingMethodLabel, "")) + assert.False(t, manager.isSelfReferencedObj(unmanagedObjWrongKind, nil, appName, argo.TrackingMethodAnnotation, "")) }) t.Run("will handle if trackingId has wrong namespace and config is nil", func(t *testing.T) { // given t.Parallel() // then - assert.True(t, manager.isSelfReferencedObj(unmanagedObjWrongNamespace, nil, appName, common.AnnotationKeyAppInstance, argo.TrackingMethodLabel, "")) - assert.False(t, manager.isSelfReferencedObj(unmanagedObjWrongNamespace, nil, appName, common.AnnotationKeyAppInstance, argo.TrackingMethodAnnotationAndLabel, "")) + assert.True(t, manager.isSelfReferencedObj(unmanagedObjWrongNamespace, nil, appName, argo.TrackingMethodLabel, "")) + assert.False(t, manager.isSelfReferencedObj(unmanagedObjWrongNamespace, nil, appName, argo.TrackingMethodAnnotationAndLabel, "")) }) t.Run("will return true if live is nil", func(t *testing.T) { t.Parallel() - assert.True(t, manager.isSelfReferencedObj(nil, nil, appName, common.AnnotationKeyAppInstance, argo.TrackingMethodAnnotation, "")) + assert.True(t, manager.isSelfReferencedObj(nil, nil, appName, argo.TrackingMethodAnnotation, "")) }) t.Run("will handle upgrade in desired state APIGroup", func(t *testing.T) { @@ -1465,7 +1465,7 @@ func TestIsLiveResourceManaged(t *testing.T) { delete(config.GetAnnotations(), common.AnnotationKeyAppInstance) // then - assert.True(t, manager.isSelfReferencedObj(managedWrongAPIGroup, config, appName, common.AnnotationKeyAppInstance, argo.TrackingMethodAnnotation, "")) + assert.True(t, manager.isSelfReferencedObj(managedWrongAPIGroup, config, appName, argo.TrackingMethodAnnotation, "")) }) } diff --git a/controller/sync.go b/controller/sync.go index bb39bfdaef..a54d0b4d9b 100644 --- a/controller/sync.go +++ b/controller/sync.go @@ -307,11 +307,6 @@ func (m *appStateManager) SyncAppState(app *v1alpha1.Application, state *v1alpha reconciliationResult.Target = patchedTargets } - appLabelKey, err := m.settingsMgr.GetAppInstanceLabelKey() - if err != nil { - log.Errorf("Could not get appInstanceLabelKey: %v", err) - return - } installationID, err := m.settingsMgr.GetInstallationID() if err != nil { log.Errorf("Could not get installation ID: %v", err) @@ -368,7 +363,7 @@ func (m *appStateManager) SyncAppState(app *v1alpha1.Application, state *v1alpha return (len(syncOp.Resources) == 0 || isPostDeleteHook(target) || argo.ContainsSyncResource(key.Name, key.Namespace, schema.GroupVersionKind{Kind: key.Kind, Group: key.Group}, syncOp.Resources)) && - m.isSelfReferencedObj(live, target, app.GetName(), appLabelKey, trackingMethod, installationID) + m.isSelfReferencedObj(live, target, app.GetName(), trackingMethod, installationID) }), sync.WithManifestValidation(!syncOp.SyncOptions.HasOption(common.SyncOptionsDisableValidation)), sync.WithSyncWaveHook(delayBetweenSyncWaves), @@ -572,7 +567,7 @@ func hasSharedResourceCondition(app *v1alpha1.Application) (bool, string) { // Note, this is not foolproof, since a proper fix would require the CRD record // status.observedGeneration coupled with a health.lua that verifies // status.observedGeneration == metadata.generation -func delayBetweenSyncWaves(phase common.SyncPhase, wave int, finalWave bool) error { +func delayBetweenSyncWaves(_ common.SyncPhase, _ int, finalWave bool) error { if !finalWave { delaySec := 2 if delaySecStr := os.Getenv(EnvVarSyncWaveDelay); delaySecStr != "" { diff --git a/hack/dev-mounter/main.go b/hack/dev-mounter/main.go index 59f5fbb918..a50904dd07 100644 --- a/hack/dev-mounter/main.go +++ b/hack/dev-mounter/main.go @@ -34,7 +34,7 @@ func newCommand() *cobra.Command { configMaps []string ) command := cobra.Command{ - Run: func(cmd *cobra.Command, args []string) { + Run: func(_ *cobra.Command, _ []string) { config, err := clientConfig.ClientConfig() errors.CheckError(err) ns, _, err := clientConfig.Namespace() @@ -99,7 +99,7 @@ func newCommand() *cobra.Command { informer := factory.Core().V1().ConfigMaps().Informer() _, err = informer.AddEventHandler(cache.ResourceEventHandlerFuncs{ AddFunc: handledConfigMap, - UpdateFunc: func(oldObj, newObj any) { + UpdateFunc: func(_, newObj any) { handledConfigMap(newObj) }, }) diff --git a/hack/gen-catalog/main.go b/hack/gen-catalog/main.go index decc4a39ed..2c16b72aea 100644 --- a/hack/gen-catalog/main.go +++ b/hack/gen-catalog/main.go @@ -42,7 +42,7 @@ func main() { func newCatalogCommand() *cobra.Command { return &cobra.Command{ Use: "catalog", - Run: func(c *cobra.Command, args []string) { + Run: func(_ *cobra.Command, _ []string) { cm := corev1.ConfigMap{ TypeMeta: metav1.TypeMeta{ Kind: "ConfigMap", @@ -89,7 +89,7 @@ func newCatalogCommand() *cobra.Command { func newDocsCommand() *cobra.Command { return &cobra.Command{ Use: "docs", - Run: func(c *cobra.Command, args []string) { + Run: func(_ *cobra.Command, _ []string) { var builtItDocsData bytes.Buffer wd, err := os.Getwd() dieOnError(err, "Failed to get current working directory") diff --git a/hack/gen-resources/cmd/commands/cmd.go b/hack/gen-resources/cmd/commands/cmd.go index 5804e4cda8..9124e7fc07 100644 --- a/hack/gen-resources/cmd/commands/cmd.go +++ b/hack/gen-resources/cmd/commands/cmd.go @@ -53,7 +53,7 @@ func NewGenerateCommand(opts *util.GenerateOpts) *cobra.Command { Use: "generate [-f file]", Short: "Generate entities", Long: "Generate entities", - Run: func(c *cobra.Command, args []string) { + Run: func(_ *cobra.Command, _ []string) { log.Printf("Retrieve configuration from %s", file) err := util.Parse(opts, file) if err != nil { @@ -97,7 +97,7 @@ func NewCleanCommand(opts *util.GenerateOpts) *cobra.Command { Use: "clean", Short: "Clean entities", Long: "Clean entities", - Run: func(c *cobra.Command, args []string) { + Run: func(_ *cobra.Command, _ []string) { argoClientSet := util.ConnectToK8sArgoClientSet() clientSet := util.ConnectToK8sClientSet() settingsMgr := settings.NewSettingsManager(context.TODO(), clientSet, opts.Namespace) diff --git a/hack/known_types/main.go b/hack/known_types/main.go index ca2cf23a38..b6c914fd19 100644 --- a/hack/known_types/main.go +++ b/hack/known_types/main.go @@ -27,7 +27,7 @@ func newCommand() *cobra.Command { command := &cobra.Command{ Use: "go run github.com/argoproj/argo-cd/hack/known_types ALIAS PACKAGE_PATH OUTPUT_PATH", Example: "go run github.com/argoproj/argo-cd/hack/known_types corev1 k8s.io/api/core/v1 corev1_known_types.go", - RunE: func(c *cobra.Command, args []string) error { + RunE: func(_ *cobra.Command, args []string) error { if len(args) < 3 { return errors.New("alias and package are not specified") } diff --git a/pkg/apiclient/grpcproxy.go b/pkg/apiclient/grpcproxy.go index 70fcafb805..97a8be3449 100644 --- a/pkg/apiclient/grpcproxy.go +++ b/pkg/apiclient/grpcproxy.go @@ -118,7 +118,7 @@ func (c *client) startGRPCProxy() (*grpc.Server, net.Listener, error) { MinTime: common.GetGRPCKeepAliveEnforcementMinimum(), }, ), - grpc.UnknownServiceHandler(func(srv any, stream grpc.ServerStream) error { + grpc.UnknownServiceHandler(func(_ any, stream grpc.ServerStream) error { fullMethodName, ok := grpc.MethodFromServerStream(stream) if !ok { return errors.New("Unable to get method name from stream context.") diff --git a/pkg/apis/application/v1alpha1/applicationset_types.go b/pkg/apis/application/v1alpha1/applicationset_types.go index 16f9eeecd5..1497dd54f4 100644 --- a/pkg/apis/application/v1alpha1/applicationset_types.go +++ b/pkg/apis/application/v1alpha1/applicationset_types.go @@ -908,7 +908,7 @@ func (a *ApplicationSet) RefreshRequired() bool { // If the applicationset has a pre-existing condition of a type that is not in the evaluated list, // it will be preserved. If the applicationset has a pre-existing condition of a type, status, reason that // is in the evaluated list, but not in the incoming conditions list, it will be removed. -func (status *ApplicationSetStatus) SetConditions(conditions []ApplicationSetCondition, evaluatedTypes map[ApplicationSetConditionType]bool) { +func (status *ApplicationSetStatus) SetConditions(conditions []ApplicationSetCondition, _ map[ApplicationSetConditionType]bool) { applicationSetConditions := make([]ApplicationSetCondition, 0) now := metav1.Now() for i := range conditions { diff --git a/pkg/apis/application/v1alpha1/types_test.go b/pkg/apis/application/v1alpha1/types_test.go index 754ff50bec..27e14da50c 100644 --- a/pkg/apis/application/v1alpha1/types_test.go +++ b/pkg/apis/application/v1alpha1/types_test.go @@ -235,7 +235,7 @@ func TestAppProject_IsDestinationPermitted(t *testing.T) { Destinations: data.projDest, }, } - permitted, _ := proj.IsDestinationPermitted(data.appDest, func(project string) ([]*Cluster, error) { + permitted, _ := proj.IsDestinationPermitted(data.appDest, func(_ string) ([]*Cluster, error) { return []*Cluster{}, nil }) assert.Equal(t, data.isPermitted, permitted) @@ -402,7 +402,7 @@ func TestAppProject_IsNegatedDestinationPermitted(t *testing.T) { Destinations: data.projDest, }, } - permitted, _ := proj.IsDestinationPermitted(data.appDest, func(project string) ([]*Cluster, error) { + permitted, _ := proj.IsDestinationPermitted(data.appDest, func(_ string) ([]*Cluster, error) { return []*Cluster{}, nil }) assert.Equalf(t, data.isPermitted, permitted, "appDest mismatch for %+v with project destinations %+v", data.appDest, data.projDest) diff --git a/reposerver/cache/cache_test.go b/reposerver/cache/cache_test.go index 18ead8aa9e..5f32d87066 100644 --- a/reposerver/cache/cache_test.go +++ b/reposerver/cache/cache_test.go @@ -503,7 +503,7 @@ func TestGetOrLockGitReferences(t *testing.T) { t.Cleanup(fixtures.mockCache.StopRedisCallback) cache := fixtures.cache fixtures.mockCache.RedisClient.On("Get", mock.Anything, mock.Anything).Unset() - fixtures.mockCache.RedisClient.On("Get", mock.Anything, mock.Anything).Return(cacheutil.ErrCacheMiss).Once().Run(func(args mock.Arguments) { + fixtures.mockCache.RedisClient.On("Get", mock.Anything, mock.Anything).Return(cacheutil.ErrCacheMiss).Once().Run(func(_ mock.Arguments) { err := cache.SetGitReferences("test-repo", *GitRefCacheItemToReferences([][2]string{{"test-repo", "ref: test"}})) require.NoError(t, err) }).On("Get", mock.Anything, mock.Anything).Return(nil) diff --git a/reposerver/repository/repository.go b/reposerver/repository/repository.go index 2c408151bf..f5a036fac6 100644 --- a/reposerver/repository/repository.go +++ b/reposerver/repository/repository.go @@ -182,7 +182,7 @@ func (s *Service) Init() error { } // ListRefs List a subset of the refs (currently, branches and tags) of a git repo -func (s *Service) ListRefs(ctx context.Context, q *apiclient.ListRefsRequest) (*apiclient.Refs, error) { +func (s *Service) ListRefs(_ context.Context, q *apiclient.ListRefsRequest) (*apiclient.Refs, error) { gitClient, err := s.newClient(q.Repo) if err != nil { return nil, fmt.Errorf("error creating git client: %w", err) @@ -239,7 +239,7 @@ func (s *Service) ListApps(ctx context.Context, q *apiclient.ListAppsRequest) (* } // ListPlugins lists the contents of a GitHub repo -func (s *Service) ListPlugins(ctx context.Context, _ *empty.Empty) (*apiclient.PluginList, error) { +func (s *Service) ListPlugins(_ context.Context, _ *empty.Empty) (*apiclient.PluginList, error) { pluginSockFilePath := common.GetPluginSockFilePath() sockFiles, err := os.ReadDir(pluginSockFilePath) @@ -2288,7 +2288,7 @@ func populatePluginAppDetails(ctx context.Context, res *apiclient.RepoAppDetails return nil } -func (s *Service) GetRevisionMetadata(ctx context.Context, q *apiclient.RepoServerRevisionMetadataRequest) (*v1alpha1.RevisionMetadata, error) { +func (s *Service) GetRevisionMetadata(_ context.Context, q *apiclient.RepoServerRevisionMetadataRequest) (*v1alpha1.RevisionMetadata, error) { if !(git.IsCommitSHA(q.Revision) || git.IsTruncatedCommitSHA(q.Revision)) { return nil, fmt.Errorf("revision %s must be resolved", q.Revision) } @@ -2365,7 +2365,7 @@ func (s *Service) GetRevisionMetadata(ctx context.Context, q *apiclient.RepoServ } // GetRevisionChartDetails returns the helm chart details of a given version -func (s *Service) GetRevisionChartDetails(ctx context.Context, q *apiclient.RepoServerRevisionChartDetailsRequest) (*v1alpha1.ChartDetails, error) { +func (s *Service) GetRevisionChartDetails(_ context.Context, q *apiclient.RepoServerRevisionChartDetailsRequest) (*v1alpha1.ChartDetails, error) { details, err := s.cache.GetRevisionChartDetails(q.Repo.Repo, q.Name, q.Revision) if err == nil { log.Infof("revision chart details cache hit: %s/%s/%s", q.Repo.Repo, q.Name, q.Revision) @@ -2552,7 +2552,7 @@ func checkoutRevision(gitClient git.Client, revision string, submoduleEnabled bo return err } -func (s *Service) GetHelmCharts(ctx context.Context, q *apiclient.HelmChartsRequest) (*apiclient.HelmChartsResponse, error) { +func (s *Service) GetHelmCharts(_ context.Context, q *apiclient.HelmChartsRequest) (*apiclient.HelmChartsResponse, error) { index, err := s.newHelmClient(q.Repo.Repo, q.Repo.GetHelmCreds(), q.Repo.EnableOCI, q.Repo.Proxy, q.Repo.NoProxy, helm.WithIndexCache(s.cache), helm.WithChartPaths(s.chartPaths)).GetIndex(true, s.initConstants.HelmRegistryMaxIndexSize) if err != nil { return nil, err @@ -2570,7 +2570,7 @@ func (s *Service) GetHelmCharts(ctx context.Context, q *apiclient.HelmChartsRequ return &res, nil } -func (s *Service) TestRepository(ctx context.Context, q *apiclient.TestRepositoryRequest) (*apiclient.TestRepositoryResponse, error) { +func (s *Service) TestRepository(_ context.Context, q *apiclient.TestRepositoryRequest) (*apiclient.TestRepositoryResponse, error) { repo := q.Repo // per Type doc, "git" should be assumed if empty or absent if repo.Type == "" { @@ -2603,7 +2603,7 @@ func (s *Service) TestRepository(ctx context.Context, q *apiclient.TestRepositor } // ResolveRevision resolves the revision/ambiguousRevision specified in the ResolveRevisionRequest request into a concrete revision. -func (s *Service) ResolveRevision(ctx context.Context, q *apiclient.ResolveRevisionRequest) (*apiclient.ResolveRevisionResponse, error) { +func (s *Service) ResolveRevision(_ context.Context, q *apiclient.ResolveRevisionRequest) (*apiclient.ResolveRevisionResponse, error) { repo := q.Repo app := q.App ambiguousRevision := q.AmbiguousRevision diff --git a/reposerver/repository/repository_test.go b/reposerver/repository/repository_test.go index 38196a1fdb..d733f12277 100644 --- a/reposerver/repository/repository_test.go +++ b/reposerver/repository/repository_test.go @@ -149,13 +149,13 @@ func newServiceWithOpt(t *testing.T, cf clientFunc, root string) (*Service, *git t.Cleanup(cacheMocks.mockCache.StopRedisCallback) service := NewService(metrics.NewMetricsServer(), cacheMocks.cache, RepoServerInitConstants{ParallelismLimit: 1}, argo.NewResourceTracking(), &git.NoopCredsStore{}, root) - service.newGitClient = func(rawRepoURL string, root string, creds git.Creds, insecure bool, enableLfs bool, proxy string, noProxy string, opts ...git.ClientOpts) (client git.Client, e error) { + service.newGitClient = func(_ string, _ string, _ git.Creds, _ bool, _ bool, _ string, _ string, _ ...git.ClientOpts) (client git.Client, e error) { return gitClient, nil } - service.newHelmClient = func(repoURL string, creds helm.Creds, enableOci bool, proxy string, noProxy string, opts ...helm.ClientOpts) helm.Client { + service.newHelmClient = func(_ string, _ helm.Creds, _ bool, _ string, _ string, _ ...helm.ClientOpts) helm.Client { return helmClient } - service.gitRepoInitializer = func(rootPath string) goio.Closer { + service.gitRepoInitializer = func(_ string) goio.Closer { return io.NopCloser } service.gitRepoPaths = paths @@ -183,7 +183,7 @@ func newServiceWithCommitSHA(t *testing.T, root, revision string) *Service { revisionErr = errors.New("not a commit SHA") } - service, gitClient, _ := newServiceWithOpt(t, func(gitClient *gitmocks.Client, helmClient *helmmocks.Client, paths *iomocks.TempPaths) { + service, gitClient, _ := newServiceWithOpt(t, func(gitClient *gitmocks.Client, _ *helmmocks.Client, paths *iomocks.TempPaths) { gitClient.On("Init").Return(nil) gitClient.On("IsRevisionPresent", mock.Anything).Return(false) gitClient.On("Fetch", mock.Anything).Return(nil) @@ -195,7 +195,7 @@ func newServiceWithCommitSHA(t *testing.T, root, revision string) *Service { paths.On("GetPathIfExists", mock.Anything).Return(root, nil) }, root) - service.newGitClient = func(rawRepoURL string, root string, creds git.Creds, insecure bool, enableLfs bool, proxy string, noProxy string, opts ...git.ClientOpts) (client git.Client, e error) { + service.newGitClient = func(_ string, _ string, _ git.Creds, _ bool, _ bool, _ string, _ string, _ ...git.ClientOpts) (client git.Client, e error) { return gitClient, nil } @@ -370,12 +370,12 @@ func TestGenerateManifest_RefOnlyShortCircuit(t *testing.T) { service.newGitClient = func(rawRepoURL string, root string, creds git.Creds, insecure bool, enableLfs bool, proxy string, noProxy string, opts ...git.ClientOpts) (client git.Client, e error) { opts = append(opts, git.WithEventHandlers(git.EventHandlers{ // Primary check, we want to make sure ls-remote is not called when the item is in cache - OnLsRemote: func(repo string) func() { + OnLsRemote: func(_ string) func() { return func() { lsremoteCalled = true } }, - OnFetch: func(repo string) func() { + OnFetch: func(_ string) func() { return func() { assert.Fail(t, "Fetch should not be called from GenerateManifest when the source is ref only") } @@ -422,7 +422,7 @@ func TestGenerateManifestsHelmWithRefs_CachedNoLsRemote(t *testing.T) { t.Cleanup(func() { cacheMocks.mockCache.StopRedisCallback() err := filepath.WalkDir(dir, - func(path string, di fs.DirEntry, err error) error { + func(path string, _ fs.DirEntry, err error) error { if err == nil { return os.Chmod(path, 0o777) } @@ -436,7 +436,7 @@ func TestGenerateManifestsHelmWithRefs_CachedNoLsRemote(t *testing.T) { service.newGitClient = func(rawRepoURL string, root string, creds git.Creds, insecure bool, enableLfs bool, proxy string, noProxy string, opts ...git.ClientOpts) (client git.Client, e error) { opts = append(opts, git.WithEventHandlers(git.EventHandlers{ // Primary check, we want to make sure ls-remote is not called when the item is in cache - OnLsRemote: func(repo string) func() { + OnLsRemote: func(_ string) func() { return func() { assert.Fail(t, "LsRemote should not be called when the item is in cache") } @@ -518,7 +518,7 @@ func TestHelmChartReferencingExternalValues(t *testing.T) { {Ref: "ref", RepoURL: "https://git.example.com/test/repo"}, }, } - refSources, err := argo.GetRefSources(context.Background(), spec.Sources, spec.Project, func(ctx context.Context, url string, project string) (*v1alpha1.Repository, error) { + refSources, err := argo.GetRefSources(context.Background(), spec.Sources, spec.Project, func(_ context.Context, _ string, _ string) (*v1alpha1.Repository, error) { return &v1alpha1.Repository{ Repo: "https://git.example.com/test/repo", }, nil @@ -554,7 +554,7 @@ func TestHelmChartReferencingExternalValues_InvalidRefs(t *testing.T) { // Empty refsource service := newService(t, ".") - getRepository := func(ctx context.Context, url string, project string) (*v1alpha1.Repository, error) { + getRepository := func(_ context.Context, _ string, _ string) (*v1alpha1.Repository, error) { return &v1alpha1.Repository{ Repo: "https://git.example.com/test/repo", }, nil @@ -627,7 +627,7 @@ func TestHelmChartReferencingExternalValues_OutOfBounds_Symlink(t *testing.T) { {Ref: "ref", RepoURL: "https://git.example.com/test/repo"}, }, } - refSources, err := argo.GetRefSources(context.Background(), spec.Sources, spec.Project, func(ctx context.Context, url string, project string) (*v1alpha1.Repository, error) { + refSources, err := argo.GetRefSources(context.Background(), spec.Sources, spec.Project, func(_ context.Context, _ string, _ string) (*v1alpha1.Repository, error) { return &v1alpha1.Repository{ Repo: "https://git.example.com/test/repo", }, nil @@ -2052,7 +2052,7 @@ func TestGenerateManifestsWithAppParameterFile(t *testing.T) { t.Run("Multi-source with source as ref only does not generate manifests", func(t *testing.T) { service := newService(t, ".") - runWithTempTestdata(t, "single-app-only", func(t *testing.T, path string) { + runWithTempTestdata(t, "single-app-only", func(t *testing.T, _ string) { t.Helper() manifests, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{ Repo: &v1alpha1.Repository{}, @@ -3396,7 +3396,7 @@ func TestErrorGetGitDirectories(t *testing.T) { }, }, want: nil, wantErr: assert.Error}, {name: "InvalidResolveRevision", fields: fields{service: func() *Service { - s, _, _ := newServiceWithOpt(t, func(gitClient *gitmocks.Client, helmClient *helmmocks.Client, paths *iomocks.TempPaths) { + s, _, _ := newServiceWithOpt(t, func(gitClient *gitmocks.Client, _ *helmmocks.Client, paths *iomocks.TempPaths) { gitClient.On("Checkout", mock.Anything, mock.Anything).Return("", nil) gitClient.On("LsRemote", mock.Anything).Return("", errors.New("ah error")) gitClient.On("Root").Return(root) @@ -3413,7 +3413,7 @@ func TestErrorGetGitDirectories(t *testing.T) { }, }, want: nil, wantErr: assert.Error}, {name: "ErrorVerifyCommit", fields: fields{service: func() *Service { - s, _, _ := newServiceWithOpt(t, func(gitClient *gitmocks.Client, helmClient *helmmocks.Client, paths *iomocks.TempPaths) { + s, _, _ := newServiceWithOpt(t, func(gitClient *gitmocks.Client, _ *helmmocks.Client, paths *iomocks.TempPaths) { gitClient.On("Checkout", mock.Anything, mock.Anything).Return("", nil) gitClient.On("LsRemote", mock.Anything).Return("", errors.New("ah error")) gitClient.On("VerifyCommitSignature", mock.Anything).Return("", fmt.Errorf("revision %s is not signed", "sadfsadf")) @@ -3447,7 +3447,7 @@ func TestErrorGetGitDirectories(t *testing.T) { func TestGetGitDirectories(t *testing.T) { // test not using the cache root := "./testdata/git-files-dirs" - s, _, cacheMocks := newServiceWithOpt(t, func(gitClient *gitmocks.Client, helmClient *helmmocks.Client, paths *iomocks.TempPaths) { + s, _, cacheMocks := newServiceWithOpt(t, func(gitClient *gitmocks.Client, _ *helmmocks.Client, paths *iomocks.TempPaths) { gitClient.On("Init").Return(nil) gitClient.On("IsRevisionPresent", mock.Anything).Return(false) gitClient.On("Fetch", mock.Anything).Return(nil) @@ -3480,7 +3480,7 @@ func TestGetGitDirectories(t *testing.T) { func TestGetGitDirectoriesWithHiddenDirSupported(t *testing.T) { // test not using the cache root := "./testdata/git-files-dirs" - s, _, cacheMocks := newServiceWithOpt(t, func(gitClient *gitmocks.Client, helmClient *helmmocks.Client, paths *iomocks.TempPaths) { + s, _, cacheMocks := newServiceWithOpt(t, func(gitClient *gitmocks.Client, _ *helmmocks.Client, paths *iomocks.TempPaths) { gitClient.On("Init").Return(nil) gitClient.On("IsRevisionPresent", mock.Anything).Return(false) gitClient.On("Fetch", mock.Anything).Return(nil) @@ -3538,7 +3538,7 @@ func TestErrorGetGitFiles(t *testing.T) { }, }, want: nil, wantErr: assert.Error}, {name: "InvalidResolveRevision", fields: fields{service: func() *Service { - s, _, _ := newServiceWithOpt(t, func(gitClient *gitmocks.Client, helmClient *helmmocks.Client, paths *iomocks.TempPaths) { + s, _, _ := newServiceWithOpt(t, func(gitClient *gitmocks.Client, _ *helmmocks.Client, paths *iomocks.TempPaths) { gitClient.On("Checkout", mock.Anything, mock.Anything).Return("", nil) gitClient.On("LsRemote", mock.Anything).Return("", errors.New("ah error")) gitClient.On("Root").Return(root) @@ -3574,7 +3574,7 @@ func TestGetGitFiles(t *testing.T) { "./testdata/git-files-dirs/config.yaml", "./testdata/git-files-dirs/config.yaml", "./testdata/git-files-dirs/app/foo/bar/config.yaml", } root := "" - s, _, cacheMocks := newServiceWithOpt(t, func(gitClient *gitmocks.Client, helmClient *helmmocks.Client, paths *iomocks.TempPaths) { + s, _, cacheMocks := newServiceWithOpt(t, func(gitClient *gitmocks.Client, _ *helmmocks.Client, paths *iomocks.TempPaths) { gitClient.On("Init").Return(nil) gitClient.On("IsRevisionPresent", mock.Anything).Return(false) gitClient.On("Fetch", mock.Anything).Return(nil) @@ -3641,7 +3641,7 @@ func TestErrorUpdateRevisionForPaths(t *testing.T) { }, }, want: nil, wantErr: assert.Error}, {name: "InvalidResolveRevision", fields: fields{service: func() *Service { - s, _, _ := newServiceWithOpt(t, func(gitClient *gitmocks.Client, helmClient *helmmocks.Client, paths *iomocks.TempPaths) { + s, _, _ := newServiceWithOpt(t, func(gitClient *gitmocks.Client, _ *helmmocks.Client, paths *iomocks.TempPaths) { gitClient.On("Checkout", mock.Anything, mock.Anything).Return("", nil) gitClient.On("LsRemote", mock.Anything).Return("", errors.New("ah error")) gitClient.On("Root").Return(root) @@ -3659,7 +3659,7 @@ func TestErrorUpdateRevisionForPaths(t *testing.T) { }, }, want: nil, wantErr: assert.Error}, {name: "InvalidResolveSyncedRevision", fields: fields{service: func() *Service { - s, _, _ := newServiceWithOpt(t, func(gitClient *gitmocks.Client, helmClient *helmmocks.Client, paths *iomocks.TempPaths) { + s, _, _ := newServiceWithOpt(t, func(gitClient *gitmocks.Client, _ *helmmocks.Client, paths *iomocks.TempPaths) { gitClient.On("Checkout", mock.Anything, mock.Anything).Return("", nil) gitClient.On("LsRemote", "HEAD").Once().Return("632039659e542ed7de0c170a4fcc1c571b288fc0", nil) gitClient.On("LsRemote", mock.Anything).Return("", errors.New("ah error")) @@ -3712,7 +3712,7 @@ func TestUpdateRevisionForPaths(t *testing.T) { cacheHit *cacheHit }{ {name: "NoPathAbort", fields: func() fields { - s, _, c := newServiceWithOpt(t, func(gitClient *gitmocks.Client, helmClient *helmmocks.Client, paths *iomocks.TempPaths) { + s, _, c := newServiceWithOpt(t, func(gitClient *gitmocks.Client, _ *helmmocks.Client, _ *iomocks.TempPaths) { gitClient.On("Checkout", mock.Anything, mock.Anything).Return("", nil) }, ".") return fields{ @@ -3727,7 +3727,7 @@ func TestUpdateRevisionForPaths(t *testing.T) { }, }, want: &apiclient.UpdateRevisionForPathsResponse{}, wantErr: assert.NoError}, {name: "SameResolvedRevisionAbort", fields: func() fields { - s, _, c := newServiceWithOpt(t, func(gitClient *gitmocks.Client, helmClient *helmmocks.Client, paths *iomocks.TempPaths) { + s, _, c := newServiceWithOpt(t, func(gitClient *gitmocks.Client, _ *helmmocks.Client, paths *iomocks.TempPaths) { gitClient.On("Checkout", mock.Anything, mock.Anything).Return("", nil) gitClient.On("LsRemote", "HEAD").Once().Return("632039659e542ed7de0c170a4fcc1c571b288fc0", nil) gitClient.On("LsRemote", "SYNCEDHEAD").Once().Return("632039659e542ed7de0c170a4fcc1c571b288fc0", nil) @@ -3750,7 +3750,7 @@ func TestUpdateRevisionForPaths(t *testing.T) { Revision: "632039659e542ed7de0c170a4fcc1c571b288fc0", }, wantErr: assert.NoError}, {name: "ChangedFilesDoNothing", fields: func() fields { - s, _, c := newServiceWithOpt(t, func(gitClient *gitmocks.Client, helmClient *helmmocks.Client, paths *iomocks.TempPaths) { + s, _, c := newServiceWithOpt(t, func(gitClient *gitmocks.Client, _ *helmmocks.Client, paths *iomocks.TempPaths) { gitClient.On("Init").Return(nil) gitClient.On("IsRevisionPresent", mock.Anything).Return(false) gitClient.On("Fetch", mock.Anything).Return(nil) @@ -3779,7 +3779,7 @@ func TestUpdateRevisionForPaths(t *testing.T) { Changes: true, }, wantErr: assert.NoError}, {name: "NoChangesUpdateCache", fields: func() fields { - s, _, c := newServiceWithOpt(t, func(gitClient *gitmocks.Client, helmClient *helmmocks.Client, paths *iomocks.TempPaths) { + s, _, c := newServiceWithOpt(t, func(gitClient *gitmocks.Client, _ *helmmocks.Client, paths *iomocks.TempPaths) { gitClient.On("Init").Return(nil) gitClient.On("IsRevisionPresent", mock.Anything).Return(false) gitClient.On("Fetch", mock.Anything).Return(nil) @@ -3817,7 +3817,7 @@ func TestUpdateRevisionForPaths(t *testing.T) { revision: "632039659e542ed7de0c170a4fcc1c571b288fc0", }}, {name: "NoChangesHelmMultiSourceUpdateCache", fields: func() fields { - s, _, c := newServiceWithOpt(t, func(gitClient *gitmocks.Client, helmClient *helmmocks.Client, paths *iomocks.TempPaths) { + s, _, c := newServiceWithOpt(t, func(gitClient *gitmocks.Client, _ *helmmocks.Client, paths *iomocks.TempPaths) { gitClient.On("Init").Return(nil) gitClient.On("IsRevisionPresent", mock.Anything).Return(false) gitClient.On("Fetch", mock.Anything).Return(nil) diff --git a/server/account/account.go b/server/account/account.go index 541401a731..405966f137 100644 --- a/server/account/account.go +++ b/server/account/account.go @@ -180,7 +180,7 @@ func (s *Server) ensureHasAccountPermission(ctx context.Context, action string, } // ListAccounts returns the list of accounts -func (s *Server) ListAccounts(ctx context.Context, r *account.ListAccountRequest) (*account.AccountsList, error) { +func (s *Server) ListAccounts(ctx context.Context, _ *account.ListAccountRequest) (*account.AccountsList, error) { resp := account.AccountsList{} accounts, err := s.settingsMgr.GetAccounts() if err != nil { diff --git a/server/account/account_test.go b/server/account/account_test.go index 3028171cd3..272a0297c9 100644 --- a/server/account/account_test.go +++ b/server/account/account_test.go @@ -32,7 +32,7 @@ const ( // return an AccountServer which returns fake data func newTestAccountServer(ctx context.Context, opts ...func(cm *corev1.ConfigMap, secret *corev1.Secret)) (*Server, *session.Server) { - return newTestAccountServerExt(ctx, func(claims jwt.Claims, rvals ...any) bool { + return newTestAccountServerExt(ctx, func(_ jwt.Claims, _ ...any) bool { return true }, opts...) } @@ -140,7 +140,7 @@ func TestUpdatePassword(t *testing.T) { } func TestUpdatePassword_AdminUpdatesAnotherUser(t *testing.T) { - accountServer, sessionServer := newTestAccountServer(context.Background(), func(cm *corev1.ConfigMap, secret *corev1.Secret) { + accountServer, sessionServer := newTestAccountServer(context.Background(), func(cm *corev1.ConfigMap, _ *corev1.Secret) { cm.Data["accounts.anotherUser"] = "login" }) ctx := adminContext(context.Background()) @@ -153,12 +153,12 @@ func TestUpdatePassword_AdminUpdatesAnotherUser(t *testing.T) { } func TestUpdatePassword_DoesNotHavePermissions(t *testing.T) { - enforcer := func(claims jwt.Claims, rvals ...any) bool { + enforcer := func(_ jwt.Claims, _ ...any) bool { return false } t.Run("LocalAccountUpdatesAnotherAccount", func(t *testing.T) { - accountServer, _ := newTestAccountServerExt(context.Background(), enforcer, func(cm *corev1.ConfigMap, secret *corev1.Secret) { + accountServer, _ := newTestAccountServerExt(context.Background(), enforcer, func(cm *corev1.ConfigMap, _ *corev1.Secret) { cm.Data["accounts.anotherUser"] = "login" }) ctx := adminContext(context.Background()) @@ -175,7 +175,7 @@ func TestUpdatePassword_DoesNotHavePermissions(t *testing.T) { } func TestUpdatePassword_ProjectToken(t *testing.T) { - accountServer, _ := newTestAccountServer(context.Background(), func(cm *corev1.ConfigMap, secret *corev1.Secret) { + accountServer, _ := newTestAccountServer(context.Background(), func(cm *corev1.ConfigMap, _ *corev1.Secret) { cm.Data["accounts.anotherUser"] = "login" }) ctx := projTokenContext(context.Background()) @@ -184,7 +184,7 @@ func TestUpdatePassword_ProjectToken(t *testing.T) { } func TestUpdatePassword_OldSSOToken(t *testing.T) { - accountServer, _ := newTestAccountServer(context.Background(), func(cm *corev1.ConfigMap, secret *corev1.Secret) { + accountServer, _ := newTestAccountServer(context.Background(), func(cm *corev1.ConfigMap, _ *corev1.Secret) { cm.Data["accounts.anotherUser"] = "login" }) ctx := ssoAdminContext(context.Background(), time.Now().Add(-2*common.ChangePasswordSSOTokenMaxAge)) @@ -194,7 +194,7 @@ func TestUpdatePassword_OldSSOToken(t *testing.T) { } func TestUpdatePassword_SSOUserUpdatesAnotherUser(t *testing.T) { - accountServer, sessionServer := newTestAccountServer(context.Background(), func(cm *corev1.ConfigMap, secret *corev1.Secret) { + accountServer, sessionServer := newTestAccountServer(context.Background(), func(cm *corev1.ConfigMap, _ *corev1.Secret) { cm.Data["accounts.anotherUser"] = "login" }) ctx := ssoAdminContext(context.Background(), time.Now()) @@ -217,7 +217,7 @@ func TestListAccounts_NoAccountsConfigured(t *testing.T) { func TestListAccounts_AccountsAreConfigured(t *testing.T) { ctx := adminContext(context.Background()) - accountServer, _ := newTestAccountServer(ctx, func(cm *corev1.ConfigMap, secret *corev1.Secret) { + accountServer, _ := newTestAccountServer(ctx, func(cm *corev1.ConfigMap, _ *corev1.Secret) { cm.Data["accounts.account1"] = "apiKey" cm.Data["accounts.account2"] = "login, apiKey" cm.Data["accounts.account2.enabled"] = "false" @@ -235,7 +235,7 @@ func TestListAccounts_AccountsAreConfigured(t *testing.T) { func TestGetAccount(t *testing.T) { ctx := adminContext(context.Background()) - accountServer, _ := newTestAccountServer(ctx, func(cm *corev1.ConfigMap, secret *corev1.Secret) { + accountServer, _ := newTestAccountServer(ctx, func(cm *corev1.ConfigMap, _ *corev1.Secret) { cm.Data["accounts.account1"] = "apiKey" }) @@ -255,7 +255,7 @@ func TestGetAccount(t *testing.T) { func TestCreateToken_SuccessfullyCreated(t *testing.T) { ctx := adminContext(context.Background()) - accountServer, _ := newTestAccountServer(ctx, func(cm *corev1.ConfigMap, secret *corev1.Secret) { + accountServer, _ := newTestAccountServer(ctx, func(cm *corev1.ConfigMap, _ *corev1.Secret) { cm.Data["accounts.account1"] = "apiKey" }) @@ -270,7 +270,7 @@ func TestCreateToken_SuccessfullyCreated(t *testing.T) { func TestCreateToken_DoesNotHaveCapability(t *testing.T) { ctx := adminContext(context.Background()) - accountServer, _ := newTestAccountServer(ctx, func(cm *corev1.ConfigMap, secret *corev1.Secret) { + accountServer, _ := newTestAccountServer(ctx, func(cm *corev1.ConfigMap, _ *corev1.Secret) { cm.Data["accounts.account1"] = "login" }) @@ -280,7 +280,7 @@ func TestCreateToken_DoesNotHaveCapability(t *testing.T) { func TestCreateToken_UserSpecifiedID(t *testing.T) { ctx := adminContext(context.Background()) - accountServer, _ := newTestAccountServer(ctx, func(cm *corev1.ConfigMap, secret *corev1.Secret) { + accountServer, _ := newTestAccountServer(ctx, func(cm *corev1.ConfigMap, _ *corev1.Secret) { cm.Data["accounts.account1"] = "apiKey" }) @@ -309,7 +309,7 @@ func TestDeleteToken_SuccessfullyRemoved(t *testing.T) { } func TestCanI_GetLogsAllowNoSwitch(t *testing.T) { - accountServer, _ := newTestAccountServer(context.Background(), func(cm *corev1.ConfigMap, secret *corev1.Secret) { + accountServer, _ := newTestAccountServer(context.Background(), func(_ *corev1.ConfigMap, _ *corev1.Secret) { }) ctx := projTokenContext(context.Background()) @@ -319,11 +319,11 @@ func TestCanI_GetLogsAllowNoSwitch(t *testing.T) { } func TestCanI_GetLogsDenySwitchOn(t *testing.T) { - enforcer := func(claims jwt.Claims, rvals ...any) bool { + enforcer := func(_ jwt.Claims, _ ...any) bool { return false } - accountServer, _ := newTestAccountServerExt(context.Background(), enforcer, func(cm *corev1.ConfigMap, secret *corev1.Secret) { + accountServer, _ := newTestAccountServerExt(context.Background(), enforcer, func(cm *corev1.ConfigMap, _ *corev1.Secret) { cm.Data["server.rbac.log.enforce.enable"] = "true" }) @@ -334,7 +334,7 @@ func TestCanI_GetLogsDenySwitchOn(t *testing.T) { } func TestCanI_GetLogsAllowSwitchOn(t *testing.T) { - accountServer, _ := newTestAccountServer(context.Background(), func(cm *corev1.ConfigMap, secret *corev1.Secret) { + accountServer, _ := newTestAccountServer(context.Background(), func(cm *corev1.ConfigMap, _ *corev1.Secret) { cm.Data["server.rbac.log.enforce.enable"] = "true" }) @@ -345,7 +345,7 @@ func TestCanI_GetLogsAllowSwitchOn(t *testing.T) { } func TestCanI_GetLogsAllowSwitchOff(t *testing.T) { - accountServer, _ := newTestAccountServer(context.Background(), func(cm *corev1.ConfigMap, secret *corev1.Secret) { + accountServer, _ := newTestAccountServer(context.Background(), func(cm *corev1.ConfigMap, _ *corev1.Secret) { cm.Data["server.rbac.log.enforce.enable"] = "false" }) diff --git a/server/application/application_test.go b/server/application/application_test.go index 51074a86ce..55776c1f29 100644 --- a/server/application/application_test.go +++ b/server/application/application_test.go @@ -71,7 +71,7 @@ type broadcasterMock struct { objects []runtime.Object } -func (b broadcasterMock) Subscribe(ch chan *v1alpha1.ApplicationWatchEvent, filters ...func(event *v1alpha1.ApplicationWatchEvent) bool) func() { +func (b broadcasterMock) Subscribe(ch chan *v1alpha1.ApplicationWatchEvent, _ ...func(event *v1alpha1.ApplicationWatchEvent) bool) func() { // Simulate the broadcaster notifying the subscriber of an application update. // The second parameter to Subscribe is filters. For the purposes of tests, we ignore the filters. Future tests // might require implementing those. @@ -228,7 +228,7 @@ func newTestAppServerWithEnforcerConfigure(t *testing.T, f func(*rbac.Enforcer), objects = append(objects, defaultProj, myProj, projWithSyncWindows) fakeAppsClientset := apps.NewSimpleClientset(objects...) - factory := appinformer.NewSharedInformerFactoryWithOptions(fakeAppsClientset, 0, appinformer.WithNamespace(""), appinformer.WithTweakListOptions(func(options *metav1.ListOptions) {})) + factory := appinformer.NewSharedInformerFactoryWithOptions(fakeAppsClientset, 0, appinformer.WithNamespace(""), appinformer.WithTweakListOptions(func(_ *metav1.ListOptions) {})) fakeProjLister := factory.Argoproj().V1alpha1().AppProjects().Lister().AppProjects(testNamespace) enforcer := rbac.NewEnforcer(kubeclientset, testNamespace, common.ArgoCDRBACConfigMapName, nil) @@ -391,7 +391,7 @@ func newTestAppServerWithEnforcerConfigureWithBenchmark(b *testing.B, f func(*rb objects = append(objects, defaultProj, myProj, projWithSyncWindows) fakeAppsClientset := apps.NewSimpleClientset(objects...) - factory := appinformer.NewSharedInformerFactoryWithOptions(fakeAppsClientset, 0, appinformer.WithNamespace(""), appinformer.WithTweakListOptions(func(options *metav1.ListOptions) {})) + factory := appinformer.NewSharedInformerFactoryWithOptions(fakeAppsClientset, 0, appinformer.WithNamespace(""), appinformer.WithTweakListOptions(func(_ *metav1.ListOptions) {})) fakeProjLister := factory.Argoproj().V1alpha1().AppProjects().Lister().AppProjects(testNamespace) enforcer := rbac.NewEnforcer(kubeclientset, testNamespace, common.ArgoCDRBACConfigMapName, nil) @@ -582,15 +582,15 @@ func (t *TestServerStream) Context() context.Context { return t.ctx } -func (t *TestServerStream) SendMsg(m any) error { +func (t *TestServerStream) SendMsg(_ any) error { return nil } -func (t *TestServerStream) RecvMsg(m any) error { +func (t *TestServerStream) RecvMsg(_ any) error { return nil } -func (t *TestServerStream) SendAndClose(r *apiclient.ManifestResponse) error { +func (t *TestServerStream) SendAndClose(_ *apiclient.ManifestResponse) error { return nil } @@ -616,7 +616,7 @@ type TestResourceTreeServer struct { ctx context.Context } -func (t *TestResourceTreeServer) Send(tree *v1alpha1.ApplicationTree) error { +func (t *TestResourceTreeServer) Send(_ *v1alpha1.ApplicationTree) error { return nil } @@ -634,11 +634,11 @@ func (t *TestResourceTreeServer) Context() context.Context { return t.ctx } -func (t *TestResourceTreeServer) SendMsg(m any) error { +func (t *TestResourceTreeServer) SendMsg(_ any) error { return nil } -func (t *TestResourceTreeServer) RecvMsg(m any) error { +func (t *TestResourceTreeServer) RecvMsg(_ any) error { return nil } @@ -646,7 +646,7 @@ type TestPodLogsServer struct { ctx context.Context } -func (t *TestPodLogsServer) Send(log *application.LogEntry) error { +func (t *TestPodLogsServer) Send(_ *application.LogEntry) error { return nil } @@ -664,11 +664,11 @@ func (t *TestPodLogsServer) Context() context.Context { return t.ctx } -func (t *TestPodLogsServer) SendMsg(m any) error { +func (t *TestPodLogsServer) SendMsg(_ any) error { return nil } -func (t *TestPodLogsServer) RecvMsg(m any) error { +func (t *TestPodLogsServer) RecvMsg(_ any) error { return nil } @@ -1556,15 +1556,15 @@ func TestDeleteApp(t *testing.T) { fakeAppCs.ReactionChain = nil patched := false deleted := false - fakeAppCs.AddReactor("patch", "applications", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { + fakeAppCs.AddReactor("patch", "applications", func(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) { patched = true return true, nil, nil }) - fakeAppCs.AddReactor("delete", "applications", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { + fakeAppCs.AddReactor("delete", "applications", func(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) { deleted = true return true, nil, nil }) - fakeAppCs.AddReactor("get", "applications", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { + fakeAppCs.AddReactor("get", "applications", func(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) { return true, &v1alpha1.Application{Spec: v1alpha1.ApplicationSpec{Source: &v1alpha1.ApplicationSource{}}}, nil }) appServer.appclientset = fakeAppCs @@ -2014,7 +2014,7 @@ func TestGetCachedAppState(t *testing.T) { } appServer := newTestAppServer(t, testApp, testProj) fakeClientSet := appServer.appclientset.(*apps.Clientset) - fakeClientSet.AddReactor("get", "applications", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { + fakeClientSet.AddReactor("get", "applications", func(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) { return true, &v1alpha1.Application{Spec: v1alpha1.ApplicationSpec{Source: &v1alpha1.ApplicationSource{}}}, nil }) t.Run("NoError", func(t *testing.T) { @@ -2033,18 +2033,18 @@ func TestGetCachedAppState(t *testing.T) { fakeClientSet.Lock() fakeClientSet.ReactionChain = nil fakeClientSet.WatchReactionChain = nil - fakeClientSet.AddReactor("patch", "applications", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { + fakeClientSet.AddReactor("patch", "applications", func(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) { patched = true updated := testApp.DeepCopy() updated.ResourceVersion = "2" appServer.appBroadcaster.OnUpdate(testApp, updated) return true, testApp, nil }) - fakeClientSet.AddReactor("get", "applications", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { + fakeClientSet.AddReactor("get", "applications", func(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) { return true, &v1alpha1.Application{Spec: v1alpha1.ApplicationSpec{Source: &v1alpha1.ApplicationSource{}}}, nil }) fakeClientSet.Unlock() - fakeClientSet.AddWatchReactor("applications", func(action kubetesting.Action) (handled bool, ret watch.Interface, err error) { + fakeClientSet.AddWatchReactor("applications", func(_ kubetesting.Action) (handled bool, ret watch.Interface, err error) { return true, watcher, nil }) } diff --git a/server/application/logs_test.go b/server/application/logs_test.go index 7a565e37ef..fad125b33a 100644 --- a/server/application/logs_test.go +++ b/server/application/logs_test.go @@ -76,7 +76,7 @@ func TestMergeLogStreams(t *testing.T) { assert.Equal(t, []string{"1", "2", "3", "4"}, lines) } -func TestMergeLogStreams_RaceCondition(t *testing.T) { +func TestMergeLogStreams_RaceCondition(_ *testing.T) { // Test for regression of this issue: https://github.com/argoproj/argo-cd/issues/7006 for i := 0; i < 5000; i++ { first := make(chan logEntry) diff --git a/server/application/websocket.go b/server/application/websocket.go index 1bf5c8a2d9..8228726ee9 100644 --- a/server/application/websocket.go +++ b/server/application/websocket.go @@ -26,7 +26,7 @@ const ( var upgrader = func() websocket.Upgrader { upgrader := websocket.Upgrader{} upgrader.HandshakeTimeout = time.Second * 2 - upgrader.CheckOrigin = func(r *http.Request) bool { + upgrader.CheckOrigin = func(_ *http.Request) bool { return true } return upgrader diff --git a/server/application/websocket_test.go b/server/application/websocket_test.go index ab5011569b..b3b52fd14f 100644 --- a/server/application/websocket_test.go +++ b/server/application/websocket_test.go @@ -130,7 +130,7 @@ func TestValidateWithAdminPermissions(t *testing.T) { enf := newEnforcer() _ = enf.SetBuiltinPolicy(assets.BuiltinPolicyCSV) enf.SetDefaultRole("role:admin") - enf.SetClaimsEnforcerFunc(func(claims jwt.Claims, rvals ...any) bool { + enf.SetClaimsEnforcerFunc(func(_ jwt.Claims, _ ...any) bool { return true }) ts := newTestTerminalSession(w, r) @@ -150,7 +150,7 @@ func TestValidateWithoutPermissions(t *testing.T) { enf := newEnforcer() _ = enf.SetBuiltinPolicy(assets.BuiltinPolicyCSV) enf.SetDefaultRole("role:test") - enf.SetClaimsEnforcerFunc(func(claims jwt.Claims, rvals ...any) bool { + enf.SetClaimsEnforcerFunc(func(_ jwt.Claims, _ ...any) bool { return false }) ts := newTestTerminalSession(w, r) diff --git a/server/applicationset/applicationset_test.go b/server/applicationset/applicationset_test.go index 10ec15c00c..51934ff8c6 100644 --- a/server/applicationset/applicationset_test.go +++ b/server/applicationset/applicationset_test.go @@ -115,7 +115,7 @@ func newTestAppSetServerWithEnforcerConfigure(f func(*rbac.Enforcer), namespace objects = append(objects, defaultProj, myProj) fakeAppsClientset := apps.NewSimpleClientset(objects...) - factory := appinformer.NewSharedInformerFactoryWithOptions(fakeAppsClientset, 0, appinformer.WithNamespace(namespace), appinformer.WithTweakListOptions(func(options *metav1.ListOptions) {})) + factory := appinformer.NewSharedInformerFactoryWithOptions(fakeAppsClientset, 0, appinformer.WithNamespace(namespace), appinformer.WithTweakListOptions(func(_ *metav1.ListOptions) {})) fakeProjLister := factory.Argoproj().V1alpha1().AppProjects().Lister().AppProjects(testNamespace) enforcer := rbac.NewEnforcer(kubeclientset, testNamespace, common.ArgoCDRBACConfigMapName, nil) diff --git a/server/cluster/cluster_test.go b/server/cluster/cluster_test.go index 33aad37bc4..bae72906f2 100644 --- a/server/cluster/cluster_test.go +++ b/server/cluster/cluster_test.go @@ -126,7 +126,7 @@ func newEnforcer() *rbac.Enforcer { enforcer := rbac.NewEnforcer(fake.NewClientset(test.NewFakeConfigMap()), test.FakeArgoCDNamespace, common.ArgoCDRBACConfigMapName, nil) _ = enforcer.SetBuiltinPolicy(assets.BuiltinPolicyCSV) enforcer.SetDefaultRole("role:test") - enforcer.SetClaimsEnforcerFunc(func(claims jwt.Claims, rvals ...any) bool { + enforcer.SetClaimsEnforcerFunc(func(_ jwt.Claims, _ ...any) bool { return true }) return enforcer @@ -179,18 +179,18 @@ func TestUpdateCluster_RejectInvalidParams(t *testing.T) { } db.On("ListClusters", mock.Anything).Return( - func(ctx context.Context) *v1alpha1.ClusterList { + func(_ context.Context) *v1alpha1.ClusterList { return &v1alpha1.ClusterList{ ListMeta: metav1.ListMeta{}, Items: clusters, } }, - func(ctx context.Context) error { + func(_ context.Context) error { return nil }, ) db.On("UpdateCluster", mock.Anything, mock.Anything).Return( - func(ctx context.Context, c *v1alpha1.Cluster) *v1alpha1.Cluster { + func(_ context.Context, c *v1alpha1.Cluster) *v1alpha1.Cluster { for _, cluster := range clusters { if c.Server == cluster.Server { return c @@ -198,7 +198,7 @@ func TestUpdateCluster_RejectInvalidParams(t *testing.T) { } return nil }, - func(ctx context.Context, c *v1alpha1.Cluster) error { + func(_ context.Context, c *v1alpha1.Cluster) error { for _, cluster := range clusters { if c.Server == cluster.Server { return nil @@ -208,7 +208,7 @@ func TestUpdateCluster_RejectInvalidParams(t *testing.T) { }, ) db.On("GetCluster", mock.Anything, mock.Anything).Return( - func(ctx context.Context, server string) *v1alpha1.Cluster { + func(_ context.Context, server string) *v1alpha1.Cluster { for _, cluster := range clusters { if server == cluster.Server { return &cluster @@ -216,7 +216,7 @@ func TestUpdateCluster_RejectInvalidParams(t *testing.T) { } return nil }, - func(ctx context.Context, server string) error { + func(_ context.Context, server string) error { for _, cluster := range clusters { if server == cluster.Server { return nil diff --git a/server/extension/extension_test.go b/server/extension/extension_test.go index 7d870ea5d7..0063eec757 100644 --- a/server/extension/extension_test.go +++ b/server/extension/extension_test.go @@ -415,12 +415,12 @@ func TestCallExtension(t *testing.T) { wg.Add(2) f.metricsMock. On("IncExtensionRequestCounter", mock.Anything, mock.Anything). - Run(func(args mock.Arguments) { + Run(func(_ mock.Arguments) { wg.Done() }) f.metricsMock. On("ObserveExtensionRequestDuration", mock.Anything, mock.Anything). - Run(func(args mock.Arguments) { + Run(func(_ mock.Arguments) { wg.Done() }) diff --git a/server/gpgkey/gpgkey.go b/server/gpgkey/gpgkey.go index 2332b6052f..d967d4dd3c 100644 --- a/server/gpgkey/gpgkey.go +++ b/server/gpgkey/gpgkey.go @@ -36,7 +36,7 @@ func NewServer( } // ListGnuPGPublicKeys returns a list of GnuPG public keys in the configuration -func (s *Server) List(ctx context.Context, q *gpgkeypkg.GnuPGPublicKeyQuery) (*appsv1.GnuPGPublicKeyList, error) { +func (s *Server) List(ctx context.Context, _ *gpgkeypkg.GnuPGPublicKeyQuery) (*appsv1.GnuPGPublicKeyList, error) { if err := s.enf.EnforceErr(ctx.Value("claims"), rbacpolicy.ResourceGPGKeys, rbacpolicy.ActionGet, ""); err != nil { return nil, err } diff --git a/server/notification/notification.go b/server/notification/notification.go index e34520e975..1cc8ef7237 100644 --- a/server/notification/notification.go +++ b/server/notification/notification.go @@ -22,7 +22,7 @@ func NewServer(apiFactory api.Factory) notification.NotificationServiceServer { } // List returns list of notification triggers -func (s *Server) ListTriggers(ctx context.Context, q *notification.TriggersListRequest) (*notification.TriggerList, error) { +func (s *Server) ListTriggers(_ context.Context, _ *notification.TriggersListRequest) (*notification.TriggerList, error) { api, err := s.apiFactory.GetAPI() if err != nil { if apierrors.IsNotFound(err) { @@ -37,7 +37,7 @@ func (s *Server) ListTriggers(ctx context.Context, q *notification.TriggersListR } // List returns list of notification services -func (s *Server) ListServices(ctx context.Context, q *notification.ServicesListRequest) (*notification.ServiceList, error) { +func (s *Server) ListServices(_ context.Context, _ *notification.ServicesListRequest) (*notification.ServiceList, error) { api, err := s.apiFactory.GetAPI() if err != nil { if apierrors.IsNotFound(err) { @@ -53,7 +53,7 @@ func (s *Server) ListServices(ctx context.Context, q *notification.ServicesListR } // List returns list of notification templates -func (s *Server) ListTemplates(ctx context.Context, q *notification.TemplatesListRequest) (*notification.TemplateList, error) { +func (s *Server) ListTemplates(_ context.Context, _ *notification.TemplatesListRequest) (*notification.TemplateList, error) { api, err := s.apiFactory.GetAPI() if err != nil { if apierrors.IsNotFound(err) { diff --git a/server/project/project.go b/server/project/project.go index 47db95122f..0fe0ae2a20 100644 --- a/server/project/project.go +++ b/server/project/project.go @@ -285,7 +285,7 @@ func (s *Server) Create(ctx context.Context, q *project.ProjectCreateRequest) (* } // List returns list of projects -func (s *Server) List(ctx context.Context, q *project.ProjectQuery) (*v1alpha1.AppProjectList, error) { +func (s *Server) List(ctx context.Context, _ *project.ProjectQuery) (*v1alpha1.AppProjectList, error) { list, err := s.appclientset.ArgoprojV1alpha1().AppProjects(s.ns).List(ctx, metav1.ListOptions{}) if list != nil { newItems := make([]v1alpha1.AppProject, 0) diff --git a/server/project/project_test.go b/server/project/project_test.go index 097e55624b..dd8253510a 100644 --- a/server/project/project_test.go +++ b/server/project/project_test.go @@ -79,7 +79,7 @@ func TestProjectServer(t *testing.T) { ctx := context.Background() fakeAppsClientset := apps.NewSimpleClientset() - factory := informer.NewSharedInformerFactoryWithOptions(fakeAppsClientset, 0, informer.WithNamespace(""), informer.WithTweakListOptions(func(options *metav1.ListOptions) {})) + factory := informer.NewSharedInformerFactoryWithOptions(fakeAppsClientset, 0, informer.WithNamespace(""), informer.WithTweakListOptions(func(_ *metav1.ListOptions) {})) projInformer := factory.Argoproj().V1alpha1().AppProjects().Informer() go projInformer.Run(ctx.Done()) if !k8scache.WaitForCacheSync(ctx.Done(), projInformer.HasSynced) { @@ -713,7 +713,7 @@ func newEnforcer(kubeclientset *fake.Clientset) *rbac.Enforcer { enforcer := rbac.NewEnforcer(kubeclientset, testNamespace, common.ArgoCDRBACConfigMapName, nil) _ = enforcer.SetBuiltinPolicy(assets.BuiltinPolicyCSV) enforcer.SetDefaultRole("role:admin") - enforcer.SetClaimsEnforcerFunc(func(claims jwt.Claims, rvals ...any) bool { + enforcer.SetClaimsEnforcerFunc(func(_ jwt.Claims, _ ...any) bool { return true }) return enforcer diff --git a/server/repocreds/repocreds.go b/server/repocreds/repocreds.go index 4c3c2d1253..97bf346545 100644 --- a/server/repocreds/repocreds.go +++ b/server/repocreds/repocreds.go @@ -42,7 +42,7 @@ func NewServer( } // ListRepositoryCredentials returns a list of all configured repository credential sets -func (s *Server) ListRepositoryCredentials(ctx context.Context, q *repocredspkg.RepoCredsQuery) (*appsv1.RepoCredsList, error) { +func (s *Server) ListRepositoryCredentials(ctx context.Context, _ *repocredspkg.RepoCredsQuery) (*appsv1.RepoCredsList, error) { urls, err := s.db.ListRepositoryCredentials(ctx) if err != nil { return nil, err @@ -66,7 +66,7 @@ func (s *Server) ListRepositoryCredentials(ctx context.Context, q *repocredspkg. } // ListWriteRepositoryCredentials returns a list of all configured repository credential sets -func (s *Server) ListWriteRepositoryCredentials(ctx context.Context, q *repocredspkg.RepoCredsQuery) (*appsv1.RepoCredsList, error) { +func (s *Server) ListWriteRepositoryCredentials(ctx context.Context, _ *repocredspkg.RepoCredsQuery) (*appsv1.RepoCredsList, error) { urls, err := s.db.ListRepositoryCredentials(ctx) if err != nil { return nil, err diff --git a/server/repository/repository_test.go b/server/repository/repository_test.go index fd3b560409..d6a45e9c6c 100644 --- a/server/repository/repository_test.go +++ b/server/repository/repository_test.go @@ -232,7 +232,7 @@ var ( func newAppAndProjLister(objects ...runtime.Object) (applisters.ApplicationLister, k8scache.SharedIndexInformer) { fakeAppsClientset := fakeapps.NewSimpleClientset(objects...) - factory := appinformer.NewSharedInformerFactoryWithOptions(fakeAppsClientset, 0, appinformer.WithNamespace(""), appinformer.WithTweakListOptions(func(options *metav1.ListOptions) {})) + factory := appinformer.NewSharedInformerFactoryWithOptions(fakeAppsClientset, 0, appinformer.WithNamespace(""), appinformer.WithTweakListOptions(func(_ *metav1.ListOptions) {})) projInformer := factory.Argoproj().V1alpha1().AppProjects() appsInformer := factory.Argoproj().V1alpha1().Applications() for _, obj := range objects { @@ -540,7 +540,7 @@ func TestRepositoryServerListApps(t *testing.T) { url := "https://test" db := &dbmocks.ArgoDB{} db.On("GetRepository", context.TODO(), url, "default").Return(&appsv1.Repository{Repo: url}, nil) - db.On("GetProjectRepositories", context.TODO(), "default").Return(nil, nil) + db.On("GetProjectRepositories", "default").Return(nil, nil) db.On("GetProjectClusters", context.TODO(), "default").Return(nil, nil) repoServerClient.On("ListApps", context.TODO(), mock.Anything).Return(&apiclient.AppList{ Apps: map[string]string{ @@ -571,7 +571,7 @@ func TestRepositoryServerListApps(t *testing.T) { url := "https://test" db := &dbmocks.ArgoDB{} db.On("GetRepository", context.TODO(), url, "default").Return(&appsv1.Repository{Repo: url}, nil) - db.On("GetProjectRepositories", context.TODO(), "default").Return(nil, nil) + db.On("GetProjectRepositories", "default").Return(nil, nil) db.On("GetProjectClusters", context.TODO(), "default").Return(nil, nil) repoServerClient.On("ListApps", context.TODO(), mock.Anything).Return(&apiclient.AppList{ Apps: map[string]string{ @@ -671,7 +671,7 @@ func TestRepositoryServerGetAppDetails(t *testing.T) { db := &dbmocks.ArgoDB{} db.On("ListHelmRepositories", context.TODO(), mock.Anything).Return(nil, nil) db.On("GetRepository", context.TODO(), url, "default").Return(&appsv1.Repository{Repo: url}, nil) - db.On("GetProjectRepositories", context.TODO(), "default").Return(nil, nil) + db.On("GetProjectRepositories", "default").Return(nil, nil) db.On("GetProjectClusters", context.TODO(), "default").Return(nil, nil) expectedResp := apiclient.RepoAppDetailsResponse{Type: "Directory"} repoServerClient.On("GetAppDetails", context.TODO(), mock.Anything).Return(&expectedResp, nil) @@ -696,7 +696,7 @@ func TestRepositoryServerGetAppDetails(t *testing.T) { url := "https://test" db := &dbmocks.ArgoDB{} db.On("GetRepository", context.TODO(), url, "default").Return(&appsv1.Repository{Repo: url}, nil) - db.On("GetProjectRepositories", context.TODO(), "default").Return(nil, nil) + db.On("GetProjectRepositories", "default").Return(nil, nil) db.On("GetProjectClusters", context.TODO(), "default").Return(nil, nil) expectedResp := apiclient.RepoAppDetailsResponse{Type: "Directory"} repoServerClient.On("GetAppDetails", context.TODO(), mock.Anything).Return(&expectedResp, nil) @@ -722,7 +722,7 @@ func TestRepositoryServerGetAppDetails(t *testing.T) { db := &dbmocks.ArgoDB{} db.On("ListHelmRepositories", context.TODO(), mock.Anything).Return(nil, nil) db.On("GetRepository", context.TODO(), url, "default").Return(&appsv1.Repository{Repo: url}, nil) - db.On("GetProjectRepositories", context.TODO(), "default").Return(nil, nil) + db.On("GetProjectRepositories", "default").Return(nil, nil) db.On("GetProjectClusters", context.TODO(), "default").Return(nil, nil) expectedResp := apiclient.RepoAppDetailsResponse{Type: "Directory"} repoServerClient.On("GetAppDetails", context.TODO(), mock.Anything).Return(&expectedResp, nil) @@ -747,7 +747,7 @@ func TestRepositoryServerGetAppDetails(t *testing.T) { db := &dbmocks.ArgoDB{} db.On("ListHelmRepositories", context.TODO(), mock.Anything).Return(helmRepos, nil) db.On("GetRepository", context.TODO(), url, "default").Return(&appsv1.Repository{Repo: url}, nil) - db.On("GetProjectRepositories", context.TODO(), "default").Return(nil, nil) + db.On("GetProjectRepositories", "default").Return(nil, nil) db.On("GetProjectClusters", context.TODO(), "default").Return(nil, nil) expectedResp := apiclient.RepoAppDetailsResponse{Type: "Helm"} repoServerClient.On("GetAppDetails", context.TODO(), mock.Anything).Return(&expectedResp, nil) @@ -786,7 +786,7 @@ func TestRepositoryServerGetAppDetails(t *testing.T) { db.On("ListHelmRepositories", context.TODO(), mock.Anything).Return(helmRepos, nil) db.On("GetRepository", context.TODO(), url0, "default").Return(&appsv1.Repository{Repo: url0}, nil) db.On("GetRepository", context.TODO(), url1, "default").Return(&appsv1.Repository{Repo: url1}, nil) - db.On("GetProjectRepositories", context.TODO(), "default").Return(nil, nil) + db.On("GetProjectRepositories", "default").Return(nil, nil) db.On("GetProjectClusters", context.TODO(), "default").Return(nil, nil) expectedResp0 := apiclient.RepoAppDetailsResponse{Type: "Plugin"} expectedResp1 := apiclient.RepoAppDetailsResponse{Type: "Helm"} @@ -865,7 +865,7 @@ func TestRepositoryServerGetAppDetails(t *testing.T) { db := &dbmocks.ArgoDB{} db.On("GetRepository", context.TODO(), url, "default").Return(&appsv1.Repository{Repo: url}, nil) db.On("ListHelmRepositories", context.TODO(), mock.Anything).Return(nil, nil) - db.On("GetProjectRepositories", context.TODO(), "default").Return(nil, nil) + db.On("GetProjectRepositories", "default").Return(nil, nil) db.On("GetProjectClusters", context.TODO(), "default").Return(nil, nil) expectedResp := apiclient.RepoAppDetailsResponse{Type: "Directory"} repoServerClient.On("GetAppDetails", context.TODO(), mock.Anything).Return(&expectedResp, nil) @@ -893,7 +893,7 @@ func TestRepositoryServerGetAppDetails(t *testing.T) { db := &dbmocks.ArgoDB{} db.On("ListHelmRepositories", context.TODO(), mock.Anything).Return(helmRepos, nil) db.On("GetRepository", context.TODO(), url, "default").Return(&appsv1.Repository{Repo: url}, nil) - db.On("GetProjectRepositories", context.TODO(), "default").Return(nil, nil) + db.On("GetProjectRepositories", "default").Return(nil, nil) db.On("GetProjectClusters", context.TODO(), "default").Return(nil, nil) expectedResp := apiclient.RepoAppDetailsResponse{Type: "Helm"} repoServerClient.On("GetAppDetails", context.TODO(), mock.Anything).Return(&expectedResp, nil) @@ -922,7 +922,7 @@ func TestRepositoryServerGetAppDetails(t *testing.T) { db := &dbmocks.ArgoDB{} db.On("GetRepository", context.TODO(), url, "default").Return(&appsv1.Repository{Repo: url}, nil) db.On("ListHelmRepositories", context.TODO(), mock.Anything).Return(nil, nil) - db.On("GetProjectRepositories", context.TODO(), "default").Return(nil, nil) + db.On("GetProjectRepositories", "default").Return(nil, nil) db.On("GetProjectClusters", context.TODO(), "default").Return(nil, nil) expectedResp := apiclient.RepoAppDetailsResponse{Type: "Directory"} repoServerClient.On("GetAppDetails", context.TODO(), mock.Anything).Return(&expectedResp, nil) @@ -963,7 +963,7 @@ func newEnforcer(kubeclientset *fake.Clientset) *rbac.Enforcer { enforcer := rbac.NewEnforcer(kubeclientset, testNamespace, common.ArgoCDRBACConfigMapName, nil) _ = enforcer.SetBuiltinPolicy(assets.BuiltinPolicyCSV) enforcer.SetDefaultRole("role:admin") - enforcer.SetClaimsEnforcerFunc(func(claims jwt.Claims, rvals ...any) bool { + enforcer.SetClaimsEnforcerFunc(func(_ jwt.Claims, _ ...any) bool { return true }) return enforcer @@ -985,7 +985,7 @@ func TestGetRepository(t *testing.T) { name: "empty project and no repos", args: args{ ctx: context.TODO(), - listRepositories: func(ctx context.Context, query *repository.RepoQuery) (*appsv1.RepositoryList, error) { + listRepositories: func(_ context.Context, _ *repository.RepoQuery) (*appsv1.RepositoryList, error) { return &appsv1.RepositoryList{ Items: []*appsv1.Repository{ {Repo: "something-else"}, @@ -1001,7 +1001,7 @@ func TestGetRepository(t *testing.T) { name: "empty project and no matching repos", args: args{ ctx: context.TODO(), - listRepositories: func(ctx context.Context, query *repository.RepoQuery) (*appsv1.RepositoryList, error) { + listRepositories: func(_ context.Context, _ *repository.RepoQuery) (*appsv1.RepositoryList, error) { return &appsv1.RepositoryList{}, nil }, q: &repository.RepoQuery{ @@ -1015,7 +1015,7 @@ func TestGetRepository(t *testing.T) { name: "empty project + matching repo with an empty project", args: args{ ctx: context.TODO(), - listRepositories: func(ctx context.Context, query *repository.RepoQuery) (*appsv1.RepositoryList, error) { + listRepositories: func(_ context.Context, _ *repository.RepoQuery) (*appsv1.RepositoryList, error) { return &appsv1.RepositoryList{ Items: []*appsv1.Repository{ {Repo: "foobar", Project: ""}, @@ -1037,7 +1037,7 @@ func TestGetRepository(t *testing.T) { name: "empty project + matching repo with a non-empty project", args: args{ ctx: context.TODO(), - listRepositories: func(ctx context.Context, query *repository.RepoQuery) (*appsv1.RepositoryList, error) { + listRepositories: func(_ context.Context, _ *repository.RepoQuery) (*appsv1.RepositoryList, error) { return &appsv1.RepositoryList{ Items: []*appsv1.Repository{ {Repo: "foobar", Project: "foobar"}, @@ -1059,7 +1059,7 @@ func TestGetRepository(t *testing.T) { name: "non-empty project + matching repo with an empty project", args: args{ ctx: context.TODO(), - listRepositories: func(ctx context.Context, query *repository.RepoQuery) (*appsv1.RepositoryList, error) { + listRepositories: func(_ context.Context, _ *repository.RepoQuery) (*appsv1.RepositoryList, error) { return &appsv1.RepositoryList{ Items: []*appsv1.Repository{ {Repo: "foobar", Project: ""}, @@ -1078,7 +1078,7 @@ func TestGetRepository(t *testing.T) { name: "non-empty project + matching repo with a matching project", args: args{ ctx: context.TODO(), - listRepositories: func(ctx context.Context, query *repository.RepoQuery) (*appsv1.RepositoryList, error) { + listRepositories: func(_ context.Context, _ *repository.RepoQuery) (*appsv1.RepositoryList, error) { return &appsv1.RepositoryList{ Items: []*appsv1.Repository{ {Repo: "foobar", Project: "foobar"}, @@ -1100,7 +1100,7 @@ func TestGetRepository(t *testing.T) { name: "non-empty project + matching repo with a non-matching project", args: args{ ctx: context.TODO(), - listRepositories: func(ctx context.Context, query *repository.RepoQuery) (*appsv1.RepositoryList, error) { + listRepositories: func(_ context.Context, _ *repository.RepoQuery) (*appsv1.RepositoryList, error) { return &appsv1.RepositoryList{ Items: []*appsv1.Repository{ {Repo: "foobar", Project: "something-else"}, diff --git a/server/server.go b/server/server.go index 412a482972..035142a6cf 100644 --- a/server/server.go +++ b/server/server.go @@ -304,8 +304,8 @@ func NewServer(ctx context.Context, opts ArgoCDServerOpts, appsetOpts Applicatio if len(opts.ApplicationNamespaces) > 0 { appInformerNs = "" } - projFactory := appinformer.NewSharedInformerFactoryWithOptions(opts.AppClientset, 0, appinformer.WithNamespace(opts.Namespace), appinformer.WithTweakListOptions(func(options *metav1.ListOptions) {})) - appFactory := appinformer.NewSharedInformerFactoryWithOptions(opts.AppClientset, 0, appinformer.WithNamespace(appInformerNs), appinformer.WithTweakListOptions(func(options *metav1.ListOptions) {})) + projFactory := appinformer.NewSharedInformerFactoryWithOptions(opts.AppClientset, 0, appinformer.WithNamespace(opts.Namespace), appinformer.WithTweakListOptions(func(_ *metav1.ListOptions) {})) + appFactory := appinformer.NewSharedInformerFactoryWithOptions(opts.AppClientset, 0, appinformer.WithNamespace(appInformerNs), appinformer.WithTweakListOptions(func(_ *metav1.ListOptions) {})) projInformer := projFactory.Argoproj().V1alpha1().AppProjects().Informer() projLister := projFactory.Argoproj().V1alpha1().AppProjects().Lister().AppProjects(opts.Namespace) @@ -606,7 +606,7 @@ func (server *ArgoCDServer) Run(ctx context.Context, listeners *Listeners) { // gRPC clients know we support http2 for their communication. NextProtos: []string{"http/1.1", "h2"}, } - tlsConfig.GetCertificate = func(info *tls.ClientHelloInfo) (*tls.Certificate, error) { + tlsConfig.GetCertificate = func(_ *tls.ClientHelloInfo) (*tls.Certificate, error) { return server.settings.Certificate, nil } if server.TLSConfigCustomizer != nil { @@ -933,7 +933,7 @@ func (server *ArgoCDServer) newGRPCServer() (*grpc.Server, application.AppResour grpc_prometheus.StreamServerInterceptor, grpc_auth.StreamServerInterceptor(server.Authenticate), grpc_util.UserAgentStreamServerInterceptor(common.ArgoCDUserAgentName, clientConstraint), - grpc_util.PayloadStreamServerInterceptor(server.log, true, func(ctx context.Context, fullMethodName string, servingObject any) bool { + grpc_util.PayloadStreamServerInterceptor(server.log, true, func(_ context.Context, fullMethodName string, _ any) bool { return !sensitiveMethods[fullMethodName] }), grpc_util.ErrorCodeK8sStreamServerInterceptor(), @@ -947,7 +947,7 @@ func (server *ArgoCDServer) newGRPCServer() (*grpc.Server, application.AppResour grpc_prometheus.UnaryServerInterceptor, grpc_auth.UnaryServerInterceptor(server.Authenticate), grpc_util.UserAgentUnaryServerInterceptor(common.ArgoCDUserAgentName, clientConstraint), - grpc_util.PayloadUnaryServerInterceptor(server.log, true, func(ctx context.Context, fullMethodName string, servingObject any) bool { + grpc_util.PayloadUnaryServerInterceptor(server.log, true, func(_ context.Context, fullMethodName string, _ any) bool { return !sensitiveMethods[fullMethodName] }), grpc_util.ErrorCodeK8sUnaryServerInterceptor(), diff --git a/server/server_test.go b/server/server_test.go index 45426b2c6e..7906c1f899 100644 --- a/server/server_test.go +++ b/server/server_test.go @@ -616,7 +616,7 @@ func getTestServer(t *testing.T, anonymousEnabled bool, withFakeSSO bool, useDex if anonymousEnabled { cm.Data["users.anonymous.enabled"] = "true" } - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ts := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) { // Start with a placeholder. We need the server URL before setting up the real handler. })) ts.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -1603,7 +1603,7 @@ func TestReplaceBaseHRef(t *testing.T) { func Test_enforceContentTypes(t *testing.T) { getBaseHandler := func(t *testing.T, allow bool) http.Handler { t.Helper() - return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + return http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) { assert.True(t, allow, "http handler was hit when it should have been blocked by content type enforcement") writer.WriteHeader(http.StatusOK) }) diff --git a/server/session/session.go b/server/session/session.go index 780d66c123..d515ae50bd 100644 --- a/server/session/session.go +++ b/server/session/session.go @@ -74,7 +74,7 @@ func (s *Server) Create(_ context.Context, q *session.SessionCreateRequest) (*se } // Delete an authentication cookie from the client. This makes sense only for the Web client. -func (s *Server) Delete(ctx context.Context, q *session.SessionDeleteRequest) (*session.SessionResponse, error) { +func (s *Server) Delete(_ context.Context, _ *session.SessionDeleteRequest) (*session.SessionResponse, error) { return &session.SessionResponse{Token: ""}, nil } @@ -82,13 +82,13 @@ func (s *Server) Delete(ctx context.Context, q *session.SessionDeleteRequest) (* // Without this function here, ArgoCDServer.authenticate would be invoked and credentials checked. // Since this service is generally invoked when the user has _no_ credentials, that would create a // chicken-and-egg situation if we didn't place this here to allow traffic to pass through. -func (s *Server) AuthFuncOverride(ctx context.Context, fullMethodName string) (context.Context, error) { +func (s *Server) AuthFuncOverride(ctx context.Context, _ string) (context.Context, error) { // this authenticates the user, but ignores any error, so that we have claims populated ctx, _ = s.authenticator.Authenticate(ctx) return ctx, nil } -func (s *Server) GetUserInfo(ctx context.Context, q *session.GetUserInfoRequest) (*session.GetUserInfoResponse, error) { +func (s *Server) GetUserInfo(ctx context.Context, _ *session.GetUserInfoRequest) (*session.GetUserInfoResponse, error) { return &session.GetUserInfoResponse{ LoggedIn: sessionmgr.LoggedIn(ctx), Username: sessionmgr.Username(ctx), diff --git a/server/settings/settings.go b/server/settings/settings.go index 919ca89cc3..8455553cd9 100644 --- a/server/settings/settings.go +++ b/server/settings/settings.go @@ -37,7 +37,7 @@ func NewServer(mgr *settings.SettingsManager, repoClient apiclient.Clientset, au } // Get returns Argo CD settings -func (s *Server) Get(ctx context.Context, q *settingspkg.SettingsQuery) (*settingspkg.Settings, error) { +func (s *Server) Get(ctx context.Context, _ *settingspkg.SettingsQuery) (*settingspkg.Settings, error) { resourceOverrides, err := s.mgr.GetResourceOverrides() if err != nil { return nil, err @@ -152,7 +152,7 @@ func (s *Server) Get(ctx context.Context, q *settingspkg.SettingsQuery) (*settin } // GetPlugins returns a list of plugins -func (s *Server) GetPlugins(ctx context.Context, q *settingspkg.SettingsQuery) (*settingspkg.SettingsPluginsResponse, error) { +func (s *Server) GetPlugins(ctx context.Context, _ *settingspkg.SettingsQuery) (*settingspkg.SettingsPluginsResponse, error) { plugins, err := s.plugins(ctx) if err != nil { return nil, err diff --git a/server/version/version.go b/server/version/version.go index cc4eeb2415..66f84f0ae8 100644 --- a/server/version/version.go +++ b/server/version/version.go @@ -73,7 +73,7 @@ func (s *Server) Version(ctx context.Context, _ *empty.Empty) (*version.VersionM } // AuthFuncOverride allows the version to be returned without auth -func (s *Server) AuthFuncOverride(ctx context.Context, fullMethodName string) (context.Context, error) { +func (s *Server) AuthFuncOverride(ctx context.Context, _ string) (context.Context, error) { if s.authenticator != nil { // this authenticates the user, but ignores any error, so that we have claims populated ctx, _ = s.authenticator.Authenticate(ctx) diff --git a/test/e2e/accounts_test.go b/test/e2e/accounts_test.go index dd56837dac..967abeec83 100644 --- a/test/e2e/accounts_test.go +++ b/test/e2e/accounts_test.go @@ -26,14 +26,14 @@ func TestCreateAndUseAccount(t *testing.T) { When(). Create(). Then(). - And(func(account *account.Account, err error) { + And(func(account *account.Account, _ error) { assert.Equal(t, account.Name, ctx.GetName()) assert.Equal(t, []string{"login"}, account.Capabilities) }). When(). Login(). Then(). - CurrentUser(func(user *session.GetUserInfoResponse, err error) { + CurrentUser(func(user *session.GetUserInfoResponse, _ error) { assert.True(t, user.LoggedIn) assert.Equal(t, user.Username, ctx.GetName()) }) @@ -48,7 +48,7 @@ func TestCanIGetLogsAllowNoSwitch(t *testing.T) { Login(). CanIGetLogs(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(output string, _ error) { assert.Contains(t, output, "yes") }) } @@ -63,7 +63,7 @@ func TestCanIGetLogsDenySwitchOn(t *testing.T) { SetParamInSettingConfigMap("server.rbac.log.enforce.enable", "true"). CanIGetLogs(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(output string, _ error) { assert.Contains(t, output, "no") }) } @@ -91,7 +91,7 @@ func TestCanIGetLogsAllowSwitchOn(t *testing.T) { SetParamInSettingConfigMap("server.rbac.log.enforce.enable", "true"). CanIGetLogs(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(output string, _ error) { assert.Contains(t, output, "yes") }) } @@ -106,7 +106,7 @@ func TestCanIGetLogsAllowSwitchOff(t *testing.T) { SetParamInSettingConfigMap("server.rbac.log.enforce.enable", "false"). CanIGetLogs(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(output string, _ error) { assert.Contains(t, output, "yes") }) } diff --git a/test/e2e/admin_test.go b/test/e2e/admin_test.go index 326e70debc..d68dc45a24 100644 --- a/test/e2e/admin_test.go +++ b/test/e2e/admin_test.go @@ -69,7 +69,7 @@ func TestBackupExportImport(t *testing.T) { When(). RunImport(exportRawOutput). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(_ string, err error) { require.NoError(t, err, "import finished with error") _, err = fixture.AppClientset.ArgoprojV1alpha1().Applications(fixture.TestNamespace()).Get(context.Background(), "exported-app1", metav1.GetOptions{}) require.NoError(t, err, "failed getting test namespace application after import") diff --git a/test/e2e/app_deletion_test.go b/test/e2e/app_deletion_test.go index c0332eb017..58d63e2da9 100644 --- a/test/e2e/app_deletion_test.go +++ b/test/e2e/app_deletion_test.go @@ -58,7 +58,7 @@ func TestDeletingAppByLabel(t *testing.T) { Then(). // delete is unsuccessful since no selector match AndCLIOutput( - func(output string, err error) { + func(_ string, err error) { assert.ErrorContains(t, err, "no apps match selector foo=baz") }, ). diff --git a/test/e2e/app_management_ns_test.go b/test/e2e/app_management_ns_test.go index 2423ba5462..023b733b80 100644 --- a/test/e2e/app_management_ns_test.go +++ b/test/e2e/app_management_ns_test.go @@ -43,7 +43,7 @@ import ( ) // This empty test is here only for clarity, to conform to logs rbac tests structure in account. This exact usecase is covered in the TestAppLogs test -func TestNamespacedGetLogsAllowNoSwitch(t *testing.T) { +func TestNamespacedGetLogsAllowNoSwitch(_ *testing.T) { } func TestNamespacedGetLogsDenySwitchOn(t *testing.T) { @@ -88,7 +88,7 @@ func TestNamespacedGetLogsDenySwitchOn(t *testing.T) { SetParamInSettingConfigMap("server.rbac.log.enforce.enable", "true"). Then(). Expect(HealthIs(health.HealthStatusHealthy)). - And(func(app *Application) { + And(func(_ *Application) { _, err := fixture.RunCliWithRetry(5, "app", "logs", ctx.AppQualifiedName(), "--kind", "Deployment", "--group", "", "--name", "guestbook-ui") assert.ErrorContains(t, err, "permission denied") }) @@ -141,17 +141,17 @@ func TestNamespacedGetLogsAllowSwitchOnNS(t *testing.T) { SetParamInSettingConfigMap("server.rbac.log.enforce.enable", "true"). Then(). Expect(HealthIs(health.HealthStatusHealthy)). - And(func(app *Application) { + And(func(_ *Application) { out, err := fixture.RunCliWithRetry(5, "app", "logs", ctx.AppQualifiedName(), "--kind", "Deployment", "--group", "", "--name", "guestbook-ui") require.NoError(t, err) assert.Contains(t, out, "Hi") }). - And(func(app *Application) { + And(func(_ *Application) { out, err := fixture.RunCliWithRetry(5, "app", "logs", ctx.AppQualifiedName(), "--kind", "Pod") require.NoError(t, err) assert.Contains(t, out, "Hi") }). - And(func(app *Application) { + And(func(_ *Application) { out, err := fixture.RunCliWithRetry(5, "app", "logs", ctx.AppQualifiedName(), "--kind", "Service") require.NoError(t, err) assert.NotContains(t, out, "Hi") @@ -199,17 +199,17 @@ func TestNamespacedGetLogsAllowSwitchOff(t *testing.T) { SetParamInSettingConfigMap("server.rbac.log.enforce.enable", "false"). Then(). Expect(HealthIs(health.HealthStatusHealthy)). - And(func(app *Application) { + And(func(_ *Application) { out, err := fixture.RunCliWithRetry(5, "app", "logs", ctx.AppQualifiedName(), "--kind", "Deployment", "--group", "", "--name", "guestbook-ui") require.NoError(t, err) assert.Contains(t, out, "Hi") }). - And(func(app *Application) { + And(func(_ *Application) { out, err := fixture.RunCliWithRetry(5, "app", "logs", ctx.AppQualifiedName(), "--kind", "Pod") require.NoError(t, err) assert.Contains(t, out, "Hi") }). - And(func(app *Application) { + And(func(_ *Application) { out, err := fixture.RunCliWithRetry(5, "app", "logs", ctx.AppQualifiedName(), "--kind", "Service") require.NoError(t, err) assert.NotContains(t, out, "Hi") @@ -289,7 +289,7 @@ func TestNamespacedAppCreation(t *testing.T) { assert.Equal(t, KubernetesInternalAPIServerAddr, app.Spec.Destination.Server) }). Expect(NamespacedEvent(fixture.AppNamespace(), EventReasonResourceCreated, "create")). - And(func(app *Application) { + And(func(_ *Application) { // app should be listed output, err := fixture.RunCli("app", "list") require.NoError(t, err) @@ -462,7 +462,7 @@ func TestNamespacedAppLabels(t *testing.T) { When(). CreateApp("-l", "foo=bar"). Then(). - And(func(app *Application) { + And(func(_ *Application) { assert.Contains(t, FailOnErr(fixture.RunCli("app", "list")), ctx.AppQualifiedName()) assert.Contains(t, FailOnErr(fixture.RunCli("app", "list", "-l", "foo=bar")), ctx.AppQualifiedName()) assert.NotContains(t, FailOnErr(fixture.RunCli("app", "list", "-l", "foo=rubbish")), ctx.AppQualifiedName()) @@ -701,7 +701,7 @@ func TestNamespacedAppWithSecrets(t *testing.T) { Then(). Expect(OperationPhaseIs(OperationSucceeded)). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { diffOutput := FailOnErr(fixture.RunCli("app", "diff", ctx.AppQualifiedName())).(string) assert.Empty(t, diffOutput) }). @@ -715,7 +715,7 @@ metadata: stringData: username: test-username`). Then(). - And(func(app *Application) { + And(func(_ *Application) { diffOutput := FailOnErr(fixture.RunCli("app", "diff", ctx.AppQualifiedName(), "--local", "testdata/secrets")).(string) assert.Empty(t, diffOutput) }) @@ -732,7 +732,7 @@ func TestNamespacedResourceDiffing(t *testing.T) { Sync(). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { // Patch deployment _, err := fixture.KubeClientset.AppsV1().Deployments(fixture.DeploymentNamespace()).Patch(context.Background(), "guestbook-ui", types.JSONPatchType, []byte(`[{ "op": "replace", "path": "/spec/template/spec/containers/0/image", "value": "test" }]`), metav1.PatchOptions{}) @@ -742,7 +742,7 @@ func TestNamespacedResourceDiffing(t *testing.T) { Refresh(RefreshTypeNormal). Then(). Expect(SyncStatusIs(SyncStatusCodeOutOfSync)). - And(func(app *Application) { + And(func(_ *Application) { diffOutput, err := fixture.RunCli("app", "diff", ctx.AppQualifiedName(), "--local-repo-root", ".", "--local", "testdata/guestbook") require.Error(t, err) assert.Contains(t, diffOutput, fmt.Sprintf("===== apps/Deployment %s/guestbook-ui ======", fixture.DeploymentNamespace())) @@ -755,7 +755,7 @@ func TestNamespacedResourceDiffing(t *testing.T) { Refresh(RefreshTypeNormal). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { diffOutput, err := fixture.RunCli("app", "diff", ctx.AppQualifiedName(), "--local-repo-root", ".", "--local", "testdata/guestbook") require.NoError(t, err) assert.Empty(t, diffOutput) @@ -814,13 +814,13 @@ func TestNamespacedResourceDiffing(t *testing.T) { When().Refresh(RefreshTypeNormal). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { deployment, err := fixture.KubeClientset.AppsV1().Deployments(fixture.DeploymentNamespace()).Get(context.Background(), "guestbook-ui", metav1.GetOptions{}) require.NoError(t, err) assert.Equal(t, int32(1), *deployment.Spec.RevisionHistoryLimit) }). When().Sync().Then().Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { deployment, err := fixture.KubeClientset.AppsV1().Deployments(fixture.DeploymentNamespace()).Get(context.Background(), "guestbook-ui", metav1.GetOptions{}) require.NoError(t, err) assert.Equal(t, int32(1), *deployment.Spec.RevisionHistoryLimit) @@ -892,7 +892,7 @@ func testNSEdgeCasesApplicationResources(t *testing.T, appPath string, statusCod } expect. Expect(HealthIs(statusCode)). - And(func(app *Application) { + And(func(_ *Application) { diffOutput, err := fixture.RunCli("app", "diff", ctx.AppQualifiedName(), "--local-repo-root", ".", "--local", path.Join("testdata", appPath)) assert.Empty(t, diffOutput) require.NoError(t, err) @@ -969,7 +969,7 @@ func TestNamespacedSyncResourceByLabel(t *testing.T) { _, _ = fixture.RunCli("app", "sync", ctx.AppQualifiedName(), "--label", "app.kubernetes.io/instance="+app.Name) }). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { _, err := fixture.RunCli("app", "sync", ctx.AppQualifiedName(), "--label", "this-label=does-not-exist") assert.ErrorContains(t, err, "level=fatal") }) @@ -985,7 +985,7 @@ func TestNamespacedLocalManifestSync(t *testing.T) { CreateApp(). Sync(). Then(). - And(func(app *Application) { + And(func(_ *Application) { res, _ := fixture.RunCli("app", "manifests", ctx.AppQualifiedName()) assert.Contains(t, res, "containerPort: 80") assert.Contains(t, res, "image: quay.io/argoprojlabs/argocd-e2e-container:0.2") @@ -996,7 +996,7 @@ func TestNamespacedLocalManifestSync(t *testing.T) { Sync("--local-repo-root", "."). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { res, _ := fixture.RunCli("app", "manifests", ctx.AppQualifiedName()) assert.Contains(t, res, "containerPort: 81") assert.Contains(t, res, "image: quay.io/argoprojlabs/argocd-e2e-container:0.3") @@ -1007,7 +1007,7 @@ func TestNamespacedLocalManifestSync(t *testing.T) { Sync(). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { res, _ := fixture.RunCli("app", "manifests", ctx.AppQualifiedName()) assert.Contains(t, res, "containerPort: 80") assert.Contains(t, res, "image: quay.io/argoprojlabs/argocd-e2e-container:0.2") @@ -1852,7 +1852,7 @@ func TestNamespacedNamespaceAutoCreation(t *testing.T) { Delete(true). Then(). Expect(Success("")). - And(func(app *Application) { + And(func(_ *Application) { // Verify delete app does not delete the namespace auto created output, err := fixture.Run("", "kubectl", "get", "namespace", updatedNamespace) require.NoError(t, err) @@ -1991,7 +1991,7 @@ func TestNamespacedNamespaceAutoCreationWithMetadataAndNsManifest(t *testing.T) Sync(). Then(). Expect(Success("")). - Expect(Namespace(namespace, func(app *Application, ns *corev1.Namespace) { + Expect(Namespace(namespace, func(_ *Application, ns *corev1.Namespace) { delete(ns.Labels, "kubernetes.io/metadata.name") delete(ns.Labels, "argocd.argoproj.io/tracking-id") delete(ns.Labels, "kubectl.kubernetes.io/last-applied-configuration") @@ -2443,7 +2443,7 @@ func TestNamespacedDisableManifestGeneration(t *testing.T) { }). Refresh(RefreshTypeHard). Then(). - And(func(app *Application) { + And(func(_ *Application) { // Wait for refresh to complete time.Sleep(1 * time.Second) }). diff --git a/test/e2e/app_management_test.go b/test/e2e/app_management_test.go index 65d725fa0d..d1a4e3dbe0 100644 --- a/test/e2e/app_management_test.go +++ b/test/e2e/app_management_test.go @@ -53,7 +53,7 @@ const ( ) // This empty test is here only for clarity, to conform to logs rbac tests structure in account. This exact usecase is covered in the TestAppLogs test -func TestGetLogsAllowNoSwitch(t *testing.T) { +func TestGetLogsAllowNoSwitch(_ *testing.T) { } func TestGetLogsDenySwitchOn(t *testing.T) { @@ -608,7 +608,7 @@ func TestAppLabels(t *testing.T) { When(). CreateApp("-l", "foo=bar"). Then(). - And(func(app *Application) { + And(func(_ *Application) { assert.Contains(t, FailOnErr(fixture.RunCli("app", "list")), fixture.Name()) assert.Contains(t, FailOnErr(fixture.RunCli("app", "list", "-l", "foo=bar")), fixture.Name()) assert.NotContains(t, FailOnErr(fixture.RunCli("app", "list", "-l", "foo=rubbish")), fixture.Name()) @@ -880,7 +880,7 @@ func TestResourceDiffing(t *testing.T) { Sync(). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { // Patch deployment _, err := fixture.KubeClientset.AppsV1().Deployments(fixture.DeploymentNamespace()).Patch(context.Background(), "guestbook-ui", types.JSONPatchType, []byte(`[{ "op": "replace", "path": "/spec/template/spec/containers/0/image", "value": "test" }]`), metav1.PatchOptions{}) @@ -962,13 +962,13 @@ func TestResourceDiffing(t *testing.T) { When().Refresh(RefreshTypeNormal). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { deployment, err := fixture.KubeClientset.AppsV1().Deployments(fixture.DeploymentNamespace()).Get(context.Background(), "guestbook-ui", metav1.GetOptions{}) require.NoError(t, err) assert.Equal(t, int32(1), *deployment.Spec.RevisionHistoryLimit) }). When().Sync().Then().Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { deployment, err := fixture.KubeClientset.AppsV1().Deployments(fixture.DeploymentNamespace()).Get(context.Background(), "guestbook-ui", metav1.GetOptions{}) require.NoError(t, err) assert.Equal(t, int32(1), *deployment.Spec.RevisionHistoryLimit) @@ -1585,7 +1585,7 @@ func TestPermissions(t *testing.T) { Refresh(RefreshTypeNormal). Then(). // make sure application resource actiions are failing - And(func(app *Application) { + And(func(_ *Application) { assertResourceActions(t, "test-permissions", false) }) } @@ -2238,7 +2238,7 @@ func TestNamespaceAutoCreation(t *testing.T) { When(). CreateApp("--sync-option", "CreateNamespace=true"). Then(). - And(func(app *Application) { + And(func(_ *Application) { // Make sure the namespace we are about to update to does not exist _, err := fixture.Run("", "kubectl", "get", "namespace", updatedNamespace) assert.ErrorContains(t, err, "not found") @@ -2256,7 +2256,7 @@ func TestNamespaceAutoCreation(t *testing.T) { Delete(true). Then(). Expect(Success("")). - And(func(app *Application) { + And(func(_ *Application) { // Verify delete app does not delete the namespace auto created output, err := fixture.Run("", "kubectl", "get", "namespace", updatedNamespace) require.NoError(t, err) @@ -2558,7 +2558,7 @@ func TestDisableManifestGeneration(t *testing.T) { }). Refresh(RefreshTypeHard). Then(). - And(func(app *Application) { + And(func(_ *Application) { // Wait for refresh to complete time.Sleep(1 * time.Second) }). diff --git a/test/e2e/app_multiple_sources_test.go b/test/e2e/app_multiple_sources_test.go index e3118244e1..ba49527696 100644 --- a/test/e2e/app_multiple_sources_test.go +++ b/test/e2e/app_multiple_sources_test.go @@ -195,7 +195,7 @@ func TestMultiSourceAppWithSourceName(t *testing.T) { assert.Equal(t, KubernetesInternalAPIServerAddr, app.Spec.Destination.Server) }). Expect(Event(EventReasonResourceCreated, "create")). - And(func(app *Application) { + And(func(_ *Application) { // we remove the first source output, err := RunCli("app", "remove-source", Name(), "--source-name", sources[0].Name) require.NoError(t, err) @@ -257,7 +257,7 @@ func TestMultiSourceAppSetWithSourceName(t *testing.T) { assert.Equal(t, KubernetesInternalAPIServerAddr, app.Spec.Destination.Server) }). Expect(Event(EventReasonResourceCreated, "create")). - And(func(app *Application) { + And(func(_ *Application) { _, err := RunCli("app", "set", Name(), "--source-name", sources[1].Name, "--path", "deployment") require.NoError(t, err) }). @@ -284,12 +284,12 @@ func TestMultiSourceApptErrorWhenSourceNameAndSourcePosition(t *testing.T) { CreateMultiSourceAppFromFile(). Then(). Expect(Event(EventReasonResourceCreated, "create")). - And(func(app *Application) { + And(func(_ *Application) { _, err := RunCli("app", "get", Name(), "--source-name", sources[1].Name, "--source-position", "1") require.Error(t, err) assert.Contains(t, err.Error(), "Only one of source-position and source-name can be specified.") }). - And(func(app *Application) { + And(func(_ *Application) { _, err := RunCli("app", "manifests", Name(), "--revisions", "0.0.2", "--source-names", sources[0].Name, "--revisions", "0.0.2", "--source-positions", "1") require.Error(t, err) assert.Contains(t, err.Error(), "Only one of source-positions and source-names can be specified.") diff --git a/test/e2e/app_sync_options_test.go b/test/e2e/app_sync_options_test.go index 96dde8804e..96456cfd36 100644 --- a/test/e2e/app_sync_options_test.go +++ b/test/e2e/app_sync_options_test.go @@ -48,7 +48,7 @@ func TestNamespaceCreationWithSSA(t *testing.T) { Sync(). Then(). Expect(Success("")). - Expect(Namespace(namespace, func(app *Application, ns *corev1.Namespace) { + Expect(Namespace(namespace, func(_ *Application, ns *corev1.Namespace) { assert.NotContains(t, ns.Annotations, "kubectl.kubernetes.io/last-applied-configuration") })). Expect(SyncStatusIs(SyncStatusCodeSynced)). diff --git a/test/e2e/cluster_test.go b/test/e2e/cluster_test.go index d65bd1c464..8fef8a41ba 100644 --- a/test/e2e/cluster_test.go +++ b/test/e2e/cluster_test.go @@ -42,7 +42,7 @@ https://kubernetes.default.svc in-cluster %v Successful `, fixtu When(). List(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(output string, _ error) { last = output }) if expected == last { @@ -65,7 +65,7 @@ func TestClusterAdd(t *testing.T) { Create(). List(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(output string, _ error) { assert.Equal(t, fmt.Sprintf(`SERVER NAME VERSION STATUS MESSAGE PROJECT https://kubernetes.default.svc test-cluster-add %v Successful %s`, fixture.GetVersions().ServerVersion, fixture.ProjectName), output) }) @@ -88,7 +88,7 @@ func TestClusterAddPermissionDenied(t *testing.T) { IgnoreErrors(). Create(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(_ string, err error) { assert.ErrorContains(t, err, "PermissionDenied desc = permission denied") }) } @@ -121,7 +121,7 @@ func TestClusterAddAllowed(t *testing.T) { Create(). List(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(output string, _ error) { assert.Equal(t, fmt.Sprintf(`SERVER NAME VERSION STATUS MESSAGE PROJECT https://kubernetes.default.svc test-cluster-add-allowed %v Successful argo-project`, fixture.GetVersions().ServerVersion), output) }) @@ -150,7 +150,7 @@ func TestClusterListDenied(t *testing.T) { Create(). List(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(output string, _ error) { assert.Equal(t, "SERVER NAME VERSION STATUS MESSAGE PROJECT", output) }) } @@ -168,7 +168,7 @@ func TestClusterSet(t *testing.T) { SetNamespaces(). GetByName("in-cluster"). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(output string, _ error) { assert.Contains(t, output, "namespace-edit-1") assert.Contains(t, output, "namespace-edit-2") }) @@ -253,7 +253,7 @@ func TestClusterDeleteDenied(t *testing.T) { Create(). DeleteByName(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(_ string, err error) { assert.ErrorContains(t, err, "PermissionDenied desc = permission denied") }) @@ -267,7 +267,7 @@ func TestClusterDeleteDenied(t *testing.T) { Create(). DeleteByServer(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(_ string, err error) { assert.ErrorContains(t, err, "PermissionDenied desc = permission denied") }) } @@ -317,7 +317,7 @@ func TestClusterDelete(t *testing.T) { clstAction.DeleteByName(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(output string, _ error) { assert.Equal(t, "Cluster 'default' removed", output) }) diff --git a/test/e2e/custom_tool_test.go b/test/e2e/custom_tool_test.go index 41ab74e942..fb7b22d765 100644 --- a/test/e2e/custom_tool_test.go +++ b/test/e2e/custom_tool_test.go @@ -40,7 +40,7 @@ func TestCustomToolWithGitCreds(t *testing.T) { Expect(OperationPhaseIs(OperationSucceeded)). Expect(SyncStatusIs(SyncStatusCodeSynced)). Expect(HealthIs(health.HealthStatusHealthy)). - And(func(app *Application) { + And(func(_ *Application) { output, err := fixture.Run("", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.GitAskpass}") require.NoError(t, err) assert.Equal(t, "argocd", output) @@ -70,17 +70,17 @@ func TestCustomToolWithGitCredsTemplate(t *testing.T) { Expect(OperationPhaseIs(OperationSucceeded)). Expect(SyncStatusIs(SyncStatusCodeSynced)). Expect(HealthIs(health.HealthStatusHealthy)). - And(func(app *Application) { + And(func(_ *Application) { output, err := fixture.Run("", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.GitAskpass}") require.NoError(t, err) assert.Equal(t, "argocd", output) }). - And(func(app *Application) { + And(func(_ *Application) { output, err := fixture.Run("", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.GitUsername}") require.NoError(t, err) assert.Empty(t, output) }). - And(func(app *Application) { + And(func(_ *Application) { output, err := fixture.Run("", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.GitPassword}") require.NoError(t, err) assert.Empty(t, output) @@ -110,12 +110,12 @@ func TestCustomToolWithSSHGitCreds(t *testing.T) { Expect(OperationPhaseIs(OperationSucceeded)). Expect(SyncStatusIs(SyncStatusCodeSynced)). Expect(HealthIs(health.HealthStatusHealthy)). - And(func(app *Application) { + And(func(_ *Application) { output, err := fixture.Run("", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", fixture.Name(), "-o", "jsonpath={.metadata.annotations.GitSSHCommand}") require.NoError(t, err) assert.Regexp(t, `-i [^ ]+`, output, "test plugin expects $GIT_SSH_COMMAND to contain the option '-i '") }). - And(func(app *Application) { + And(func(_ *Application) { output, err := fixture.Run("", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", fixture.Name(), "-o", "jsonpath={.metadata.annotations.GitSSHCredsFileSHA}") require.NoError(t, err) assert.Regexp(t, `\w+\s+[\/\w]+`, output, "git ssh credentials file should be able to be read, hashing the contents") @@ -171,23 +171,23 @@ func TestCustomToolWithEnv(t *testing.T) { Expect(OperationPhaseIs(OperationSucceeded)). Expect(SyncStatusIs(SyncStatusCodeSynced)). Expect(HealthIs(health.HealthStatusHealthy)). - And(func(app *Application) { + And(func(_ *Application) { output, err := fixture.Run("", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.Bar}") require.NoError(t, err) assert.Equal(t, "baz", output) }). - And(func(app *Application) { + And(func(_ *Application) { output, err := fixture.Run("", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.Foo}") require.NoError(t, err) assert.Equal(t, "bar", output) }). - And(func(app *Application) { + And(func(_ *Application) { expectedKubeVersion := fixture.GetVersions().ServerVersion.Format("%s.%s") output, err := fixture.Run("", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.KubeVersion}") require.NoError(t, err) assert.Equal(t, expectedKubeVersion, output) }). - And(func(app *Application) { + And(func(_ *Application) { expectedApiVersion := fixture.GetApiResources() expectedApiVersionSlice := strings.Split(expectedApiVersion, ",") sort.Strings(expectedApiVersionSlice) @@ -222,10 +222,10 @@ func TestCustomToolSyncAndDiffLocal(t *testing.T) { Expect(OperationPhaseIs(OperationSucceeded)). Expect(SyncStatusIs(SyncStatusCodeSynced)). Expect(HealthIs(health.HealthStatusHealthy)). - And(func(app *Application) { + And(func(_ *Application) { FailOnErr(fixture.RunCli("app", "sync", ctx.AppName(), "--local", appPath, "--local-repo-root", testdataPath)) }). - And(func(app *Application) { + And(func(_ *Application) { FailOnErr(fixture.RunCli("app", "diff", ctx.AppName(), "--local", appPath, "--local-repo-root", testdataPath)) }) } @@ -320,18 +320,18 @@ func TestCMPDiscoverWithFindCommandWithEnv(t *testing.T) { Expect(OperationPhaseIs(OperationSucceeded)). Expect(SyncStatusIs(SyncStatusCodeSynced)). Expect(HealthIs(health.HealthStatusHealthy)). - And(func(app *Application) { + And(func(_ *Application) { output, err := fixture.Run("", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.Bar}") require.NoError(t, err) assert.Equal(t, "baz", output) }). - And(func(app *Application) { + And(func(_ *Application) { expectedKubeVersion := fixture.GetVersions().ServerVersion.Format("%s.%s") output, err := fixture.Run("", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", ctx.AppName(), "-o", "jsonpath={.metadata.annotations.KubeVersion}") require.NoError(t, err) assert.Equal(t, expectedKubeVersion, output) }). - And(func(app *Application) { + And(func(_ *Application) { expectedApiVersion := fixture.GetApiResources() expectedApiVersionSlice := strings.Split(expectedApiVersion, ",") sort.Strings(expectedApiVersionSlice) diff --git a/test/e2e/deployment_test.go b/test/e2e/deployment_test.go index 1e83a4494e..27b2c65142 100644 --- a/test/e2e/deployment_test.go +++ b/test/e2e/deployment_test.go @@ -67,7 +67,7 @@ func TestDeploymentWithAnnotationTrackingMode(t *testing.T) { Expect(HealthIs(health.HealthStatusHealthy)). When(). Then(). - And(func(app *Application) { + And(func(_ *Application) { out, err := RunCli("app", "manifests", ctx.AppName()) require.NoError(t, err) assert.Contains(t, out, fmt.Sprintf(`annotations: @@ -90,7 +90,7 @@ func TestDeploymentWithLabelTrackingMode(t *testing.T) { Expect(HealthIs(health.HealthStatusHealthy)). When(). Then(). - And(func(app *Application) { + And(func(_ *Application) { out, err := RunCli("app", "manifests", ctx.AppName()) require.NoError(t, err) assert.Contains(t, out, fmt.Sprintf(`labels: @@ -113,7 +113,7 @@ func TestDeploymentWithoutTrackingMode(t *testing.T) { Expect(HealthIs(health.HealthStatusHealthy)). When(). Then(). - And(func(app *Application) { + And(func(_ *Application) { out, err := RunCli("app", "manifests", ctx.AppName()) require.NoError(t, err) assert.Contains(t, out, fmt.Sprintf(`labels: diff --git a/test/e2e/fixture/app/expectation.go b/test/e2e/fixture/app/expectation.go index 02365ba696..7615fdc31c 100644 --- a/test/e2e/fixture/app/expectation.go +++ b/test/e2e/fixture/app/expectation.go @@ -246,7 +246,7 @@ func DoesNotExistNow() Expectation { } func Pod(predicate func(p corev1.Pod) bool) Expectation { - return func(c *Consequences) (state, string) { + return func(_ *Consequences) (state, string) { pods, err := pods() if err != nil { return failed, err.Error() @@ -261,7 +261,7 @@ func Pod(predicate func(p corev1.Pod) bool) Expectation { } func NotPod(predicate func(p corev1.Pod) bool) Expectation { - return func(c *Consequences) (state, string) { + return func(_ *Consequences) (state, string) { pods, err := pods() if err != nil { return failed, err.Error() @@ -282,7 +282,7 @@ func pods() (*corev1.PodList, error) { } func NoNamespace(name string) Expectation { - return func(c *Consequences) (state, string) { + return func(_ *Consequences) (state, string) { _, err := namespace(name) if err != nil { return succeeded, "namespace not found" diff --git a/test/e2e/fixture/applicationsets/expectation.go b/test/e2e/fixture/applicationsets/expectation.go index fc8de495fe..a693320315 100644 --- a/test/e2e/fixture/applicationsets/expectation.go +++ b/test/e2e/fixture/applicationsets/expectation.go @@ -116,7 +116,7 @@ func ApplicationsDoNotExist(expectedApps []v1alpha1.Application) Expectation { // Pod checks whether a specified condition is true for any of the pods in the namespace func Pod(predicate func(p corev1.Pod) bool) Expectation { - return func(c *Consequences) (state, string) { + return func(_ *Consequences) (state, string) { pods, err := pods(utils.ApplicationsResourcesNamespace) if err != nil { return failed, err.Error() diff --git a/test/e2e/fixture/cluster/actions.go b/test/e2e/fixture/cluster/actions.go index ac114bad0c..2e662825dc 100644 --- a/test/e2e/fixture/cluster/actions.go +++ b/test/e2e/fixture/cluster/actions.go @@ -38,7 +38,7 @@ func (a *Actions) DoNotIgnoreErrors() *Actions { return a } -func (a *Actions) Create(args ...string) *Actions { +func (a *Actions) Create() *Actions { _, clusterClient, _ := fixture.ArgoCDClientset.NewClusterClient() _, err := clusterClient.Create(context.Background(), &clusterpkg.ClusterCreateRequest{ @@ -67,7 +67,7 @@ func (a *Actions) Create(args ...string) *Actions { return a } -func (a *Actions) CreateWithRBAC(args ...string) *Actions { +func (a *Actions) CreateWithRBAC() *Actions { pathOpts := clientcmd.NewDefaultPathOptions() config, err := pathOpts.GetStartingConfig() if err != nil { diff --git a/test/e2e/git_submodule_test.go b/test/e2e/git_submodule_test.go index 73329d1223..95008f5527 100644 --- a/test/e2e/git_submodule_test.go +++ b/test/e2e/git_submodule_test.go @@ -18,7 +18,7 @@ func TestGitSubmoduleSSHSupport(t *testing.T) { CustomSSHKnownHostsAdded(). SubmoduleSSHRepoURLAdded(true). When(). - CreateFromFile(func(app *Application) {}). + CreateFromFile(func(_ *Application) {}). Sync(). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). @@ -33,7 +33,7 @@ func TestGitSubmoduleHTTPSSupport(t *testing.T) { CustomCACertAdded(). SubmoduleHTTPSRepoURLAdded(true). When(). - CreateFromFile(func(app *Application) {}). + CreateFromFile(func(_ *Application) {}). Sync(). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). @@ -48,7 +48,7 @@ func TestGitSubmoduleRemovalSupport(t *testing.T) { CustomSSHKnownHostsAdded(). SubmoduleSSHRepoURLAdded(true). When(). - CreateFromFile(func(app *Application) {}). + CreateFromFile(func(_ *Application) {}). Sync(). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). diff --git a/test/e2e/helm_test.go b/test/e2e/helm_test.go index 0ecb03e730..a30e880dca 100644 --- a/test/e2e/helm_test.go +++ b/test/e2e/helm_test.go @@ -222,7 +222,7 @@ func TestHelmValuesLiteralFileRemote(t *testing.T) { // send back the address so that it can be used c <- listener.Addr().String() - http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + http.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) { // return the sentinel text at root URL fmt.Fprint(w, sentinel) }) @@ -326,7 +326,7 @@ func TestHelmSetEnv(t *testing.T) { Then(). Expect(OperationPhaseIs(OperationSucceeded)). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { assert.Equal(t, fixture.Name(), FailOnErr(fixture.Run(".", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.foo}")).(string)) }) } @@ -341,7 +341,7 @@ func TestHelmSetStringEnv(t *testing.T) { Then(). Expect(OperationPhaseIs(OperationSucceeded)). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { assert.Equal(t, fixture.Name(), FailOnErr(fixture.Run(".", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.foo}")).(string)) }) } @@ -356,7 +356,7 @@ func TestKubeVersion(t *testing.T) { Sync(). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { kubeVersion := FailOnErr(fixture.Run(".", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.kubeVersion}")).(string) // Capabilities.KubeVersion defaults to 1.9.0, we assume here you are running a later version @@ -368,7 +368,7 @@ func TestKubeVersion(t *testing.T) { Sync(). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { assert.Equal(t, "v999.999.999", FailOnErr(fixture.Run(".", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.kubeVersion}")).(string)) }) @@ -384,7 +384,7 @@ func TestApiVersions(t *testing.T) { Sync(). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { apiVersions := FailOnErr(fixture.Run(".", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.apiVersions}")).(string) // The v1 API shouldn't be going anywhere. @@ -396,7 +396,7 @@ func TestApiVersions(t *testing.T) { Sync(). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { apiVersions := FailOnErr(fixture.Run(".", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.apiVersions}")).(string) assert.Contains(t, apiVersions, "v1/MyTestResource") diff --git a/test/e2e/jsonnet_test.go b/test/e2e/jsonnet_test.go index 3f1113b420..c582ea4f8a 100644 --- a/test/e2e/jsonnet_test.go +++ b/test/e2e/jsonnet_test.go @@ -83,7 +83,7 @@ func TestJsonnetTlaEnv(t *testing.T) { Then(). Expect(OperationPhaseIs(OperationSucceeded)). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { assert.Equal(t, Name(), FailOnErr(Run(".", "kubectl", "-n", DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.foo}")).(string)) assert.Equal(t, Name(), FailOnErr(Run(".", "kubectl", "-n", DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.bar}")).(string)) }) @@ -98,7 +98,7 @@ func TestJsonnetExtVarEnv(t *testing.T) { Then(). Expect(OperationPhaseIs(OperationSucceeded)). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { assert.Equal(t, Name(), FailOnErr(Run(".", "kubectl", "-n", DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.foo}")).(string)) assert.Equal(t, Name(), FailOnErr(Run(".", "kubectl", "-n", DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.bar}")).(string)) }) diff --git a/test/e2e/kustomize_test.go b/test/e2e/kustomize_test.go index a49c26b1e1..22d7519c6c 100644 --- a/test/e2e/kustomize_test.go +++ b/test/e2e/kustomize_test.go @@ -17,7 +17,7 @@ import ( func TestKustomize2AppSource(t *testing.T) { patchLabelMatchesFor := func(kind string) func(app *Application) { - return func(app *Application) { + return func(_ *Application) { name := "k2-patched-guestbook-ui-deploy1" labelValue, err := fixture.Run( "", "kubectl", "-n="+fixture.DeploymentNamespace(), @@ -184,7 +184,7 @@ func TestKustomizeReplicas2AppSource(t *testing.T) { deploymentName := "guestbook-ui" deploymentReplicas := 2 checkReplicasFor := func(kind string) func(app *Application) { - return func(app *Application) { + return func(_ *Application) { name := deploymentName replicas, err := fixture.Run( "", "kubectl", "-n="+fixture.DeploymentNamespace(), @@ -301,7 +301,7 @@ func TestKustomizeKubeVersion(t *testing.T) { Sync(). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { kubeVersion := errors.FailOnErr(fixture.Run(".", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.kubeVersion}")).(string) // Capabilities.KubeVersion defaults to 1.9.0, we assume here you are running a later version @@ -313,7 +313,7 @@ func TestKustomizeKubeVersion(t *testing.T) { Sync(). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { assert.Equal(t, "v999.999.999", errors.FailOnErr(fixture.Run(".", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.kubeVersion}")).(string)) }) @@ -333,7 +333,7 @@ func TestKustomizeApiVersions(t *testing.T) { Sync(). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { apiVersions := errors.FailOnErr(fixture.Run(".", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.apiVersions}")).(string) // The v1 API shouldn't be going anywhere. @@ -345,7 +345,7 @@ func TestKustomizeApiVersions(t *testing.T) { Sync(). Then(). Expect(SyncStatusIs(SyncStatusCodeSynced)). - And(func(app *Application) { + And(func(_ *Application) { apiVersions := errors.FailOnErr(fixture.Run(".", "kubectl", "-n", fixture.DeploymentNamespace(), "get", "cm", "my-map", "-o", "jsonpath={.data.apiVersions}")).(string) assert.Contains(t, apiVersions, "v1/MyTestResource") diff --git a/test/e2e/scoped_repository_test.go b/test/e2e/scoped_repository_test.go index 0075b6bd1b..08ecb4ad27 100644 --- a/test/e2e/scoped_repository_test.go +++ b/test/e2e/scoped_repository_test.go @@ -29,11 +29,11 @@ func TestCreateRepositoryWithProject(t *testing.T) { Project("argo-project"). Create(). Then(). - And(func(r *Repository, err error) { + And(func(r *Repository, _ error) { assert.Equal(t, r.Repo, path) assert.Equal(t, "argo-project", r.Project) - prjConsequence.And(func(projectResponse *project.DetailedProjectsResponse, err error) { + prjConsequence.And(func(projectResponse *project.DetailedProjectsResponse, _ error) { assert.Len(t, projectResponse.Repositories, 1) assert.Equal(t, projectResponse.Repositories[0].Repo, path) }) @@ -55,7 +55,7 @@ func TestCreateRepositoryNonAdminUserPermissionDenied(t *testing.T) { IgnoreErrors(). Create(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(_ string, err error) { assert.ErrorContains(t, err, "PermissionDenied desc = permission denied: repositories, create") }) } @@ -82,7 +82,7 @@ func TestCreateRepositoryNonAdminUserWithWrongProject(t *testing.T) { IgnoreErrors(). Create(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(_ string, err error) { assert.ErrorContains(t, err, "PermissionDenied desc = permission denied: repositories, create") }) } @@ -118,14 +118,14 @@ func TestDeleteRepositoryRbacAllowed(t *testing.T) { Project("argo-project"). Create(). Then(). - And(func(r *Repository, err error) { + And(func(r *Repository, _ error) { assert.Equal(t, r.Repo, path) assert.Equal(t, "argo-project", r.Project) }). When(). Delete(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(output string, _ error) { assert.Contains(t, output, "Repository 'https://github.com/argoproj/argo-cd.git' removed") }) } @@ -161,7 +161,7 @@ func TestDeleteRepositoryRbacDenied(t *testing.T) { Project("argo-project"). Create(). Then(). - And(func(r *Repository, err error) { + And(func(r *Repository, _ error) { assert.Equal(t, r.Repo, path) assert.Equal(t, "argo-project", r.Project) }). @@ -169,7 +169,7 @@ func TestDeleteRepositoryRbacDenied(t *testing.T) { IgnoreErrors(). Delete(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(_ string, err error) { assert.ErrorContains(t, err, "PermissionDenied desc = permission denied: repositories, delete") }) } @@ -182,13 +182,13 @@ func TestDeleteRepository(t *testing.T) { Project("argo-project"). Create(). Then(). - And(func(r *Repository, err error) { + And(func(r *Repository, _ error) { assert.Equal(t, r.Repo, path) }). When(). Delete(). Then(). - And(func(r *Repository, err error) { + And(func(_ *Repository, err error) { assert.Equal(t, "repo not found", err.Error()) }) } @@ -201,13 +201,13 @@ func TestListRepoCLIOutput(t *testing.T) { Project("argo-project"). Create(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(output string, _ error) { assert.Equal(t, `Repository 'https://github.com/argoproj/argo-cd.git' added`, output) }). When(). List(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(output string, _ error) { assert.Equal(t, `TYPE NAME REPO INSECURE OCI LFS CREDS STATUS MESSAGE PROJECT git https://github.com/argoproj/argo-cd.git false false false false Successful argo-project`, output) }) @@ -221,13 +221,13 @@ func TestGetRepoCLIOutput(t *testing.T) { Project("argo-project"). Create(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(output string, _ error) { assert.Equal(t, `Repository 'https://github.com/argoproj/argo-cd.git' added`, output) }). When(). Get(). Then(). - AndCLIOutput(func(output string, err error) { + AndCLIOutput(func(output string, _ error) { assert.Equal(t, `TYPE NAME REPO INSECURE OCI LFS CREDS STATUS MESSAGE PROJECT git https://github.com/argoproj/argo-cd.git false false false false Successful argo-project`, output) }) diff --git a/test/manifests_test.go b/test/manifests_test.go index 9c30714041..8d6807dffc 100644 --- a/test/manifests_test.go +++ b/test/manifests_test.go @@ -22,7 +22,7 @@ func TestKustomizeVersion(t *testing.T) { // TestBuildManifests makes sure we are consistent in naming, and all kustomization.yamls are buildable func TestBuildManifests(t *testing.T) { - err := filepath.Walk("../manifests", func(path string, f os.FileInfo, err error) error { + err := filepath.Walk("../manifests", func(path string, _ os.FileInfo, err error) error { if err != nil { return err } diff --git a/test/testdata.go b/test/testdata.go index a9b1cfa72a..8e10050f5c 100644 --- a/test/testdata.go +++ b/test/testdata.go @@ -119,7 +119,7 @@ func NewFakeConfigMap() *corev1.ConfigMap { return &cm } -func NewFakeSecret(policy ...string) *corev1.Secret { +func NewFakeSecret() *corev1.Secret { secret := corev1.Secret{ TypeMeta: metav1.TypeMeta{ Kind: "Secret", @@ -163,7 +163,7 @@ func NewFakeProjListerFromInterface(appProjects appclient.AppProjectInterface) a func NewFakeProjLister(objects ...runtime.Object) applister.AppProjectNamespaceLister { fakeAppClientset := apps.NewSimpleClientset(objects...) - factory := appinformer.NewSharedInformerFactoryWithOptions(fakeAppClientset, 0, appinformer.WithNamespace(""), appinformer.WithTweakListOptions(func(options *metav1.ListOptions) {})) + factory := appinformer.NewSharedInformerFactoryWithOptions(fakeAppClientset, 0, appinformer.WithNamespace(""), appinformer.WithTweakListOptions(func(_ *metav1.ListOptions) {})) projInformer := factory.Argoproj().V1alpha1().AppProjects().Informer() cancel := StartInformer(projInformer) defer cancel() diff --git a/util/argo/argo.go b/util/argo/argo.go index 810b9a5dec..6faa2d9975 100644 --- a/util/argo/argo.go +++ b/util/argo/argo.go @@ -707,7 +707,7 @@ func GetAppProjectWithScopedResources(ctx context.Context, name string, projList if err != nil { return nil, nil, nil, fmt.Errorf("error getting project clusters: %w", err) } - repos, err := db.GetProjectRepositories(ctx, name) + repos, err := db.GetProjectRepositories(name) if err != nil { return nil, nil, nil, fmt.Errorf("error getting project repos: %w", err) } @@ -721,7 +721,7 @@ func GetAppProjectByName(ctx context.Context, name string, projLister applicatio return nil, fmt.Errorf("error getting app project %q: %w", name, err) } project := projOrig.DeepCopy() - repos, err := db.GetProjectRepositories(ctx, name) + repos, err := db.GetProjectRepositories(name) if err != nil { return nil, fmt.Errorf("error getting project repositories: %w", err) } diff --git a/util/argo/argo_test.go b/util/argo/argo_test.go index c45cab489c..328b013f9f 100644 --- a/util/argo/argo_test.go +++ b/util/argo/argo_test.go @@ -1302,7 +1302,7 @@ func Test_GetRefSources(t *testing.T) { {RepoURL: "file://" + repoPath}, }) - refSources, err := GetRefSources(context.Background(), argoSpec.Sources, argoSpec.Project, func(ctx context.Context, url string, project string) (*argoappv1.Repository, error) { + refSources, err := GetRefSources(context.Background(), argoSpec.Sources, argoSpec.Project, func(_ context.Context, _ string, _ string) (*argoappv1.Repository, error) { return repo, nil }, []string{}, false) @@ -1322,7 +1322,7 @@ func Test_GetRefSources(t *testing.T) { {RepoURL: "file://" + repoPath}, }) - refSources, err := GetRefSources(context.Background(), argoSpec.Sources, argoSpec.Project, func(ctx context.Context, url string, project string) (*argoappv1.Repository, error) { + refSources, err := GetRefSources(context.Background(), argoSpec.Sources, argoSpec.Project, func(_ context.Context, _ string, _ string) (*argoappv1.Repository, error) { return nil, errors.New("repo does not exist") }, []string{}, false) @@ -1336,7 +1336,7 @@ func Test_GetRefSources(t *testing.T) { {RepoURL: "file://" + repoPath}, }) - refSources, err := GetRefSources(context.TODO(), argoSpec.Sources, argoSpec.Project, func(ctx context.Context, url string, project string) (*argoappv1.Repository, error) { + refSources, err := GetRefSources(context.TODO(), argoSpec.Sources, argoSpec.Project, func(_ context.Context, _ string, _ string) (*argoappv1.Repository, error) { return nil, err }, []string{}, false) @@ -1350,7 +1350,7 @@ func Test_GetRefSources(t *testing.T) { {RepoURL: "file://does-not-exist", Ref: "source1"}, }) - refSources, err := GetRefSources(context.TODO(), argoSpec.Sources, argoSpec.Project, func(ctx context.Context, url string, project string) (*argoappv1.Repository, error) { + refSources, err := GetRefSources(context.TODO(), argoSpec.Sources, argoSpec.Project, func(_ context.Context, _ string, _ string) (*argoappv1.Repository, error) { return nil, err }, []string{}, false) diff --git a/util/argo/resource_tracking.go b/util/argo/resource_tracking.go index 3366d15208..546aaa68e1 100644 --- a/util/argo/resource_tracking.go +++ b/util/argo/resource_tracking.go @@ -29,7 +29,7 @@ var ( // ResourceTracking defines methods which allow setup and retrieve tracking information to resource type ResourceTracking interface { GetAppName(un *unstructured.Unstructured, key string, trackingMethod v1alpha1.TrackingMethod, installationID string) string - GetAppInstance(un *unstructured.Unstructured, key string, trackingMethod v1alpha1.TrackingMethod, installationID string) *AppInstanceValue + GetAppInstance(un *unstructured.Unstructured, trackingMethod v1alpha1.TrackingMethod, installationID string) *AppInstanceValue SetAppInstance(un *unstructured.Unstructured, key, val, namespace string, trackingMethod v1alpha1.TrackingMethod, instanceID string) error BuildAppInstanceValue(value AppInstanceValue) string ParseAppInstanceValue(value string) (*AppInstanceValue, error) @@ -111,7 +111,7 @@ func (rt *resourceTracking) GetAppName(un *unstructured.Unstructured, key string // GetAppInstance returns the representation of the app instance annotation. // If the tracking method does not support metadata, or the annotation could // not be parsed, it returns nil. -func (rt *resourceTracking) GetAppInstance(un *unstructured.Unstructured, key string, trackingMethod v1alpha1.TrackingMethod, instanceID string) *AppInstanceValue { +func (rt *resourceTracking) GetAppInstance(un *unstructured.Unstructured, trackingMethod v1alpha1.TrackingMethod, instanceID string) *AppInstanceValue { switch trackingMethod { case TrackingMethodAnnotation, TrackingMethodAnnotationAndLabel: return rt.getAppInstanceValue(un, instanceID) diff --git a/util/cache/inmemory.go b/util/cache/inmemory.go index 5f1544c20f..f42a6bf537 100644 --- a/util/cache/inmemory.go +++ b/util/cache/inmemory.go @@ -89,11 +89,11 @@ func (i *InMemoryCache) Flush() { i.memCache.Flush() } -func (i *InMemoryCache) OnUpdated(ctx context.Context, key string, callback func() error) error { +func (i *InMemoryCache) OnUpdated(_ context.Context, _ string, _ func() error) error { return nil } -func (i *InMemoryCache) NotifyUpdated(key string) error { +func (i *InMemoryCache) NotifyUpdated(_ string) error { return nil } diff --git a/util/cache/redis.go b/util/cache/redis.go index 5f0de926f7..cdc98138bf 100644 --- a/util/cache/redis.go +++ b/util/cache/redis.go @@ -196,7 +196,7 @@ func (rh *redisHook) ProcessHook(next redis.ProcessHook) redis.ProcessHook { } } -func (redisHook) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook { +func (redisHook) ProcessPipelineHook(_ redis.ProcessPipelineHook) redis.ProcessPipelineHook { return nil } diff --git a/util/cache/redis_hook.go b/util/cache/redis_hook.go index e7cc3f4bcc..5d30337e2d 100644 --- a/util/cache/redis_hook.go +++ b/util/cache/redis_hook.go @@ -36,6 +36,6 @@ func (hook *argoRedisHooks) ProcessHook(next redis.ProcessHook) redis.ProcessHoo } } -func (hook *argoRedisHooks) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook { +func (hook *argoRedisHooks) ProcessPipelineHook(_ redis.ProcessPipelineHook) redis.ProcessPipelineHook { return nil } diff --git a/util/cli/cli.go b/util/cli/cli.go index d1e8492ec4..4ffbda988c 100644 --- a/util/cli/cli.go +++ b/util/cli/cli.go @@ -38,7 +38,7 @@ func NewVersionCmd(cliName string) *cobra.Command { versionCmd := cobra.Command{ Use: "version", Short: "Print version information", - Run: func(cmd *cobra.Command, args []string) { + Run: func(_ *cobra.Command, _ []string) { version := common.GetVersion() fmt.Printf("%s: %s\n", cliName, version) if short { diff --git a/util/clusterauth/clusterauth_test.go b/util/clusterauth/clusterauth_test.go index 748519697b..4ce14e36a0 100644 --- a/util/clusterauth/clusterauth_test.go +++ b/util/clusterauth/clusterauth_test.go @@ -191,7 +191,7 @@ func TestGenerateNewClusterManagerSecret(t *testing.T) { "token": []byte("fake-token"), } - kubeclientset.AddReactor("*", "secrets", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { + kubeclientset.AddReactor("*", "secrets", func(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) { return true, generatedSecret, nil }) diff --git a/util/config/reader_test.go b/util/config/reader_test.go index 7265aefb68..052e9c090b 100644 --- a/util/config/reader_test.go +++ b/util/config/reader_test.go @@ -84,7 +84,7 @@ func TestUnmarshalRemoteFile(t *testing.T) { // send back the address so that it can be used c <- listener.Addr().String() - http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + http.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) { // return the sentinel text at root URL fmt.Fprint(w, sentinel) }) diff --git a/util/db/certificate.go b/util/db/certificate.go index 978c29f964..1b45d68657 100644 --- a/util/db/certificate.go +++ b/util/db/certificate.go @@ -56,7 +56,7 @@ type CertificateListSelector struct { // - For SSH keys, the SHA256 fingerprint of the key as string, prepended by // the string "SHA256:" // - For TLS certs, the Subject of the X509 cert as a string in DN notation -func (db *db) ListRepoCertificates(ctx context.Context, selector *CertificateListSelector) (*appsv1.RepositoryCertificateList, error) { +func (db *db) ListRepoCertificates(_ context.Context, selector *CertificateListSelector) (*appsv1.RepositoryCertificateList, error) { // selector may be given as nil, but we need at least an empty data structure // so we create it if necessary. if selector == nil { @@ -123,7 +123,7 @@ func (db *db) ListRepoCertificates(ctx context.Context, selector *CertificateLis } // Get a single certificate from the datastore -func (db *db) GetRepoCertificate(ctx context.Context, serverType string, serverName string) (*appsv1.RepositoryCertificate, error) { +func (db *db) GetRepoCertificate(_ context.Context, serverType string, serverName string) (*appsv1.RepositoryCertificate, error) { if serverType == "ssh" { sshKnownHostsList, err := db.getSSHKnownHostsData() if err != nil { diff --git a/util/db/cluster.go b/util/db/cluster.go index a17f72d284..c09bc7e91b 100644 --- a/util/db/cluster.go +++ b/util/db/cluster.go @@ -57,7 +57,7 @@ func (db *db) getLocalCluster() *appv1.Cluster { } // ListClusters returns list of clusters -func (db *db) ListClusters(ctx context.Context) (*appv1.ClusterList, error) { +func (db *db) ListClusters(_ context.Context) (*appv1.ClusterList, error) { clusterSecrets, err := db.listSecretsByType(common.LabelValueSecretTypeCluster) if err != nil { return nil, err @@ -233,7 +233,7 @@ func (db *db) GetCluster(_ context.Context, server string) (*appv1.Cluster, erro } // GetProjectClusters return project scoped clusters by given project name -func (db *db) GetProjectClusters(ctx context.Context, project string) ([]*appv1.Cluster, error) { +func (db *db) GetProjectClusters(_ context.Context, project string) ([]*appv1.Cluster, error) { informer, err := db.settingsMgr.GetSecretsInformer() if err != nil { return nil, fmt.Errorf("failed to get secrets informer: %w", err) @@ -253,7 +253,7 @@ func (db *db) GetProjectClusters(ctx context.Context, project string) ([]*appv1. return res, nil } -func (db *db) GetClusterServersByName(ctx context.Context, name string) ([]string, error) { +func (db *db) GetClusterServersByName(_ context.Context, name string) ([]string, error) { informer, err := db.settingsMgr.GetSecretsInformer() if err != nil { return nil, err diff --git a/util/db/cluster_norace_test.go b/util/db/cluster_norace_test.go index 23b5beecef..179463e9f6 100644 --- a/util/db/cluster_norace_test.go +++ b/util/db/cluster_norace_test.go @@ -122,7 +122,7 @@ func TestWatchClusters_LocalClusterModifications(t *testing.T) { assert.NoError(t, db.DeleteCluster(context.Background(), v1alpha1.KubernetesInternalAPIServerAddr)) }, - func(old *v1alpha1.Cluster, new *v1alpha1.Cluster) { + func(_ *v1alpha1.Cluster, new *v1alpha1.Cluster) { assert.Equal(t, v1alpha1.KubernetesInternalAPIServerAddr, new.Server) assert.Equal(t, "in-cluster", new.Name) }, diff --git a/util/db/cluster_test.go b/util/db/cluster_test.go index 345dd6107e..e68ca3a1ca 100644 --- a/util/db/cluster_test.go +++ b/util/db/cluster_test.go @@ -424,7 +424,7 @@ func TestListClusters(t *testing.T) { // TestClusterRaceConditionClusterSecrets reproduces a race condition // on the cluster secrets. The test isn't asserting anything because // before the fix it would cause a panic from concurrent map iteration and map write -func TestClusterRaceConditionClusterSecrets(t *testing.T) { +func TestClusterRaceConditionClusterSecrets(_ *testing.T) { clusterSecret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "mycluster", diff --git a/util/db/db.go b/util/db/db.go index 4114450631..708354d119 100644 --- a/util/db/db.go +++ b/util/db/db.go @@ -55,7 +55,7 @@ type ArgoDB interface { // GetRepository returns a repository by URL GetRepository(ctx context.Context, url, project string) (*appv1.Repository, error) // GetProjectRepositories returns project scoped repositories by given project name - GetProjectRepositories(ctx context.Context, project string) ([]*appv1.Repository, error) + GetProjectRepositories(project string) ([]*appv1.Repository, error) // RepositoryExists returns whether a repository is configured for the given URL RepositoryExists(ctx context.Context, repoURL, project string) (bool, error) // UpdateRepository updates a repository @@ -68,7 +68,7 @@ type ArgoDB interface { // GetWriteRepository returns a repository by URL with write credentials GetWriteRepository(ctx context.Context, url, project string) (*appv1.Repository, error) // GetProjectWriteRepositories returns project scoped repositories from write credentials by given project name - GetProjectWriteRepositories(ctx context.Context, project string) ([]*appv1.Repository, error) + GetProjectWriteRepositories(project string) ([]*appv1.Repository, error) // WriteRepositoryExists returns whether a repository is configured for the given URL with write credentials WriteRepositoryExists(ctx context.Context, repoURL, project string) (bool, error) // UpdateWriteRepository updates a repository with write credentials diff --git a/util/db/gpgkeys.go b/util/db/gpgkeys.go index add5b4f422..28b6934668 100644 --- a/util/db/gpgkeys.go +++ b/util/db/gpgkeys.go @@ -57,7 +57,7 @@ func validatePGPKey(keyData string) (*appsv1.GnuPGPublicKey, error) { } // ListConfiguredGPGPublicKeys returns a list of all configured GPG public keys from the ConfigMap -func (db *db) ListConfiguredGPGPublicKeys(ctx context.Context) (map[string]*appsv1.GnuPGPublicKey, error) { +func (db *db) ListConfiguredGPGPublicKeys(_ context.Context) (map[string]*appsv1.GnuPGPublicKey, error) { log.Debugf("Loading PGP public keys from config map") result := make(map[string]*appsv1.GnuPGPublicKey) keysCM, err := db.settingsMgr.GetConfigMapByName(common.ArgoCDGPGKeysConfigMapName) diff --git a/util/db/mocks/ArgoDB.go b/util/db/mocks/ArgoDB.go index 837f939a6f..173c7e5be0 100644 --- a/util/db/mocks/ArgoDB.go +++ b/util/db/mocks/ArgoDB.go @@ -481,9 +481,9 @@ func (_m *ArgoDB) GetProjectClusters(ctx context.Context, project string) ([]*v1 return r0, r1 } -// GetProjectRepositories provides a mock function with given fields: ctx, project -func (_m *ArgoDB) GetProjectRepositories(ctx context.Context, project string) ([]*v1alpha1.Repository, error) { - ret := _m.Called(ctx, project) +// GetProjectRepositories provides a mock function with given fields: project +func (_m *ArgoDB) GetProjectRepositories(project string) ([]*v1alpha1.Repository, error) { + ret := _m.Called(project) if len(ret) == 0 { panic("no return value specified for GetProjectRepositories") @@ -491,19 +491,19 @@ func (_m *ArgoDB) GetProjectRepositories(ctx context.Context, project string) ([ var r0 []*v1alpha1.Repository var r1 error - if rf, ok := ret.Get(0).(func(context.Context, string) ([]*v1alpha1.Repository, error)); ok { - return rf(ctx, project) + if rf, ok := ret.Get(0).(func(string) ([]*v1alpha1.Repository, error)); ok { + return rf(project) } - if rf, ok := ret.Get(0).(func(context.Context, string) []*v1alpha1.Repository); ok { - r0 = rf(ctx, project) + if rf, ok := ret.Get(0).(func(string) []*v1alpha1.Repository); ok { + r0 = rf(project) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]*v1alpha1.Repository) } } - if rf, ok := ret.Get(1).(func(context.Context, string) error); ok { - r1 = rf(ctx, project) + if rf, ok := ret.Get(1).(func(string) error); ok { + r1 = rf(project) } else { r1 = ret.Error(1) } @@ -511,9 +511,9 @@ func (_m *ArgoDB) GetProjectRepositories(ctx context.Context, project string) ([ return r0, r1 } -// GetProjectWriteRepositories provides a mock function with given fields: ctx, project -func (_m *ArgoDB) GetProjectWriteRepositories(ctx context.Context, project string) ([]*v1alpha1.Repository, error) { - ret := _m.Called(ctx, project) +// GetProjectWriteRepositories provides a mock function with given fields: project +func (_m *ArgoDB) GetProjectWriteRepositories(project string) ([]*v1alpha1.Repository, error) { + ret := _m.Called(project) if len(ret) == 0 { panic("no return value specified for GetProjectWriteRepositories") @@ -521,19 +521,19 @@ func (_m *ArgoDB) GetProjectWriteRepositories(ctx context.Context, project strin var r0 []*v1alpha1.Repository var r1 error - if rf, ok := ret.Get(0).(func(context.Context, string) ([]*v1alpha1.Repository, error)); ok { - return rf(ctx, project) + if rf, ok := ret.Get(0).(func(string) ([]*v1alpha1.Repository, error)); ok { + return rf(project) } - if rf, ok := ret.Get(0).(func(context.Context, string) []*v1alpha1.Repository); ok { - r0 = rf(ctx, project) + if rf, ok := ret.Get(0).(func(string) []*v1alpha1.Repository); ok { + r0 = rf(project) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]*v1alpha1.Repository) } } - if rf, ok := ret.Get(1).(func(context.Context, string) error); ok { - r1 = rf(ctx, project) + if rf, ok := ret.Get(1).(func(string) error); ok { + r1 = rf(project) } else { r1 = ret.Error(1) } diff --git a/util/db/repository.go b/util/db/repository.go index fd2d5e6a68..f7d59cbd4a 100644 --- a/util/db/repository.go +++ b/util/db/repository.go @@ -118,11 +118,11 @@ func (db *db) GetWriteRepository(ctx context.Context, repoURL, project string) ( return repository, err } -func (db *db) GetProjectRepositories(ctx context.Context, project string) ([]*v1alpha1.Repository, error) { +func (db *db) GetProjectRepositories(project string) ([]*v1alpha1.Repository, error) { return db.getRepositories(settings.ByProjectRepoIndexer, project) } -func (db *db) GetProjectWriteRepositories(ctx context.Context, project string) ([]*v1alpha1.Repository, error) { +func (db *db) GetProjectWriteRepositories(project string) ([]*v1alpha1.Repository, error) { return db.getRepositories(settings.ByProjectRepoWriteIndexer, project) } diff --git a/util/db/repository_legacy.go b/util/db/repository_legacy.go index d0bfaf4321..f84333ba5a 100644 --- a/util/db/repository_legacy.go +++ b/util/db/repository_legacy.go @@ -27,13 +27,13 @@ type legacyRepositoryBackend struct { db *db } -func (l *legacyRepositoryBackend) CreateRepository(ctx context.Context, r *appsv1.Repository) (*appsv1.Repository, error) { +func (l *legacyRepositoryBackend) CreateRepository(_ context.Context, _ *appsv1.Repository) (*appsv1.Repository, error) { // This strategy only kept to preserve backward compatibility, but is deprecated. // Therefore, no new repositories can be added with this backend. panic("creating new repositories is not supported for the legacy repository backend") } -func (l *legacyRepositoryBackend) GetRepository(ctx context.Context, repoURL, project string) (*appsv1.Repository, error) { +func (l *legacyRepositoryBackend) GetRepository(_ context.Context, repoURL, _ string) (*appsv1.Repository, error) { repository, err := l.tryGetRepository(repoURL) if err != nil { return nil, fmt.Errorf("unable to get repository: %w", err) @@ -41,7 +41,7 @@ func (l *legacyRepositoryBackend) GetRepository(ctx context.Context, repoURL, pr return repository, nil } -func (l *legacyRepositoryBackend) ListRepositories(ctx context.Context, repoType *string) ([]*appsv1.Repository, error) { +func (l *legacyRepositoryBackend) ListRepositories(_ context.Context, repoType *string) ([]*appsv1.Repository, error) { inRepos, err := l.db.settingsMgr.GetRepositories() if err != nil { return nil, err @@ -71,7 +71,7 @@ func (l *legacyRepositoryBackend) ListRepositories(ctx context.Context, repoType return repos, nil } -func (l *legacyRepositoryBackend) UpdateRepository(ctx context.Context, r *appsv1.Repository) (*appsv1.Repository, error) { +func (l *legacyRepositoryBackend) UpdateRepository(_ context.Context, r *appsv1.Repository) (*appsv1.Repository, error) { repos, err := l.db.settingsMgr.GetRepositories() if err != nil { return nil, err @@ -102,7 +102,7 @@ func (l *legacyRepositoryBackend) UpdateRepository(ctx context.Context, r *appsv return r, nil } -func (l *legacyRepositoryBackend) DeleteRepository(ctx context.Context, repoURL, project string) error { +func (l *legacyRepositoryBackend) DeleteRepository(_ context.Context, repoURL, _ string) error { repos, err := l.db.settingsMgr.GetRepositories() if err != nil { return err @@ -127,7 +127,7 @@ func (l *legacyRepositoryBackend) DeleteRepository(ctx context.Context, repoURL, return l.db.settingsMgr.SaveRepositories(repos) } -func (l *legacyRepositoryBackend) RepositoryExists(ctx context.Context, repoURL, project string, allowFallback bool) (bool, error) { +func (l *legacyRepositoryBackend) RepositoryExists(_ context.Context, repoURL, _ string, _ bool) (bool, error) { repos, err := l.db.settingsMgr.GetRepositories() if err != nil { return false, fmt.Errorf("unable to get repositories: %w", err) @@ -137,13 +137,13 @@ func (l *legacyRepositoryBackend) RepositoryExists(ctx context.Context, repoURL, return index >= 0, nil } -func (l *legacyRepositoryBackend) CreateRepoCreds(ctx context.Context, r *appsv1.RepoCreds) (*appsv1.RepoCreds, error) { +func (l *legacyRepositoryBackend) CreateRepoCreds(_ context.Context, _ *appsv1.RepoCreds) (*appsv1.RepoCreds, error) { // This strategy only kept to preserve backward compatibility, but is deprecated. // Therefore, no new repositories can be added with this backend. panic("creating new repository credentials is not supported for the legacy repository backend") } -func (l *legacyRepositoryBackend) GetRepoCreds(ctx context.Context, repoURL string) (*appsv1.RepoCreds, error) { +func (l *legacyRepositoryBackend) GetRepoCreds(_ context.Context, repoURL string) (*appsv1.RepoCreds, error) { var credential *appsv1.RepoCreds repoCredentials, err := l.db.settingsMgr.GetRepositoryCredentials() @@ -161,7 +161,7 @@ func (l *legacyRepositoryBackend) GetRepoCreds(ctx context.Context, repoURL stri return credential, err } -func (l *legacyRepositoryBackend) ListRepoCreds(ctx context.Context) ([]string, error) { +func (l *legacyRepositoryBackend) ListRepoCreds(_ context.Context) ([]string, error) { repos, err := l.db.settingsMgr.GetRepositoryCredentials() if err != nil { return nil, err @@ -175,7 +175,7 @@ func (l *legacyRepositoryBackend) ListRepoCreds(ctx context.Context) ([]string, return urls, nil } -func (l *legacyRepositoryBackend) UpdateRepoCreds(ctx context.Context, r *appsv1.RepoCreds) (*appsv1.RepoCreds, error) { +func (l *legacyRepositoryBackend) UpdateRepoCreds(_ context.Context, r *appsv1.RepoCreds) (*appsv1.RepoCreds, error) { repos, err := l.db.settingsMgr.GetRepositoryCredentials() if err != nil { return nil, err @@ -200,7 +200,7 @@ func (l *legacyRepositoryBackend) UpdateRepoCreds(ctx context.Context, r *appsv1 return r, nil } -func (l *legacyRepositoryBackend) DeleteRepoCreds(ctx context.Context, name string) error { +func (l *legacyRepositoryBackend) DeleteRepoCreds(_ context.Context, name string) error { repos, err := l.db.settingsMgr.GetRepositoryCredentials() if err != nil { return err @@ -225,7 +225,7 @@ func (l *legacyRepositoryBackend) DeleteRepoCreds(ctx context.Context, name stri return l.db.settingsMgr.SaveRepositoryCredentials(repos) } -func (l *legacyRepositoryBackend) RepoCredsExists(ctx context.Context, repoURL string) (bool, error) { +func (l *legacyRepositoryBackend) RepoCredsExists(_ context.Context, repoURL string) (bool, error) { creds, err := l.db.settingsMgr.GetRepositoryCredentials() if err != nil { return false, err @@ -235,7 +235,7 @@ func (l *legacyRepositoryBackend) RepoCredsExists(ctx context.Context, repoURL s return index >= 0, nil } -func (l *legacyRepositoryBackend) GetAllHelmRepoCreds(ctx context.Context) ([]*appsv1.RepoCreds, error) { +func (l *legacyRepositoryBackend) GetAllHelmRepoCreds(_ context.Context) ([]*appsv1.RepoCreds, error) { var allCredentials []*appsv1.RepoCreds repoCredentials, err := l.db.settingsMgr.GetRepositoryCredentials() if err != nil { diff --git a/util/db/repository_secrets.go b/util/db/repository_secrets.go index 6d5d0ad3a2..fbe44d1fd1 100644 --- a/util/db/repository_secrets.go +++ b/util/db/repository_secrets.go @@ -83,7 +83,7 @@ func (s *secretsRepositoryBackend) GetRepoCredsBySecretName(_ context.Context, n return s.secretToRepoCred(secret) } -func (s *secretsRepositoryBackend) GetRepository(ctx context.Context, repoURL, project string) (*appsv1.Repository, error) { +func (s *secretsRepositoryBackend) GetRepository(_ context.Context, repoURL, project string) (*appsv1.Repository, error) { secret, err := s.getRepositorySecret(repoURL, project, true) if err != nil { if status.Code(err) == codes.NotFound { @@ -101,7 +101,7 @@ func (s *secretsRepositoryBackend) GetRepository(ctx context.Context, repoURL, p return repository, err } -func (s *secretsRepositoryBackend) ListRepositories(ctx context.Context, repoType *string) ([]*appsv1.Repository, error) { +func (s *secretsRepositoryBackend) ListRepositories(_ context.Context, repoType *string) ([]*appsv1.Repository, error) { var repos []*appsv1.Repository secrets, err := s.db.listSecretsByType(s.getSecretType()) @@ -166,7 +166,7 @@ func (s *secretsRepositoryBackend) DeleteRepository(ctx context.Context, repoURL return s.db.settingsMgr.ResyncInformers() } -func (s *secretsRepositoryBackend) RepositoryExists(ctx context.Context, repoURL, project string, allowFallback bool) (bool, error) { +func (s *secretsRepositoryBackend) RepositoryExists(_ context.Context, repoURL, project string, allowFallback bool) (bool, error) { secret, err := s.getRepositorySecret(repoURL, project, allowFallback) if err != nil { if status.Code(err) == codes.NotFound { @@ -201,7 +201,7 @@ func (s *secretsRepositoryBackend) CreateRepoCreds(ctx context.Context, repoCred return repoCreds, s.db.settingsMgr.ResyncInformers() } -func (s *secretsRepositoryBackend) GetRepoCreds(ctx context.Context, repoURL string) (*appsv1.RepoCreds, error) { +func (s *secretsRepositoryBackend) GetRepoCreds(_ context.Context, repoURL string) (*appsv1.RepoCreds, error) { secret, err := s.getRepoCredsSecret(repoURL) if err != nil { if status.Code(err) == codes.NotFound { @@ -214,7 +214,7 @@ func (s *secretsRepositoryBackend) GetRepoCreds(ctx context.Context, repoURL str return s.secretToRepoCred(secret) } -func (s *secretsRepositoryBackend) ListRepoCreds(ctx context.Context) ([]string, error) { +func (s *secretsRepositoryBackend) ListRepoCreds(_ context.Context) ([]string, error) { var repoURLs []string secrets, err := s.db.listSecretsByType(common.LabelValueSecretTypeRepoCreds) @@ -266,7 +266,7 @@ func (s *secretsRepositoryBackend) DeleteRepoCreds(ctx context.Context, name str return s.db.settingsMgr.ResyncInformers() } -func (s *secretsRepositoryBackend) RepoCredsExists(ctx context.Context, repoURL string) (bool, error) { +func (s *secretsRepositoryBackend) RepoCredsExists(_ context.Context, repoURL string) (bool, error) { _, err := s.getRepoCredsSecret(repoURL) if err != nil { if status.Code(err) == codes.NotFound { @@ -279,7 +279,7 @@ func (s *secretsRepositoryBackend) RepoCredsExists(ctx context.Context, repoURL return true, nil } -func (s *secretsRepositoryBackend) GetAllHelmRepoCreds(ctx context.Context) ([]*appsv1.RepoCreds, error) { +func (s *secretsRepositoryBackend) GetAllHelmRepoCreds(_ context.Context) ([]*appsv1.RepoCreds, error) { var helmRepoCreds []*appsv1.RepoCreds secrets, err := s.db.listSecretsByType(common.LabelValueSecretTypeRepoCreds) diff --git a/util/db/repository_secrets_test.go b/util/db/repository_secrets_test.go index 1d91dd3293..4905eb6ad1 100644 --- a/util/db/repository_secrets_test.go +++ b/util/db/repository_secrets_test.go @@ -88,7 +88,7 @@ func TestSecretsRepositoryBackend_CreateRepository(t *testing.T) { delete(secret.Labels, common.LabelKeySecretType) f := setupWithK8sObjects(secret) f.clientSet.ReactionChain = nil - f.clientSet.AddReactor("create", "secrets", func(action k8stesting.Action) (handled bool, ret runtime.Object, err error) { + f.clientSet.AddReactor("create", "secrets", func(_ k8stesting.Action) (handled bool, ret runtime.Object, err error) { gr := schema.GroupResource{ Group: "v1", Resource: "secrets", @@ -125,7 +125,7 @@ func TestSecretsRepositoryBackend_CreateRepository(t *testing.T) { f := setupWithK8sObjects(secret) f.clientSet.ReactionChain = nil f.clientSet.WatchReactionChain = nil - f.clientSet.AddReactor("create", "secrets", func(action k8stesting.Action) (handled bool, ret runtime.Object, err error) { + f.clientSet.AddReactor("create", "secrets", func(_ k8stesting.Action) (handled bool, ret runtime.Object, err error) { gr := schema.GroupResource{ Group: "v1", Resource: "secrets", @@ -134,7 +134,7 @@ func TestSecretsRepositoryBackend_CreateRepository(t *testing.T) { }) watcher := watch.NewFakeWithChanSize(1, true) watcher.Add(secret) - f.clientSet.AddWatchReactor("secrets", func(action k8stesting.Action) (handled bool, ret watch.Interface, err error) { + f.clientSet.AddWatchReactor("secrets", func(_ k8stesting.Action) (handled bool, ret watch.Interface, err error) { return true, watcher, nil }) diff --git a/util/db/repository_test.go b/util/db/repository_test.go index a0601815e9..4f7d40ec35 100644 --- a/util/db/repository_test.go +++ b/util/db/repository_test.go @@ -357,7 +357,7 @@ func Test_GetProjectRepositories(t *testing.T) { clientset := getClientset(map[string]string{}, repoSecretWithProject, repoSecretWithoutProject) argoDB := NewDB(testNamespace, settings.NewSettingsManager(context.TODO(), clientset, testNamespace), clientset) - repos, err := argoDB.GetProjectRepositories(context.TODO(), "some-project") + repos, err := argoDB.GetProjectRepositories("some-project") require.NoError(t, err) assert.Len(t, repos, 1) assert.Equal(t, "git@github.com:argoproj/argo-cd", repos[0].Repo) diff --git a/util/dex/dex.go b/util/dex/dex.go index a24d2d18f5..b91f0f4d8b 100644 --- a/util/dex/dex.go +++ b/util/dex/dex.go @@ -45,7 +45,7 @@ func TLSConfig(tlsConfig *DexTLSConfig) *tls.Config { return &tls.Config{ InsecureSkipVerify: false, RootCAs: tlsConfig.RootCAs, - VerifyPeerCertificate: func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error { + VerifyPeerCertificate: func(rawCerts [][]byte, _ [][]*x509.Certificate) error { if !bytes.Equal(rawCerts[0], tlsConfig.Certificate) { return stderrors.New("dex server certificate does not match") } diff --git a/util/dex/dex_test.go b/util/dex/dex_test.go index 3bca3134bd..8151d46014 100644 --- a/util/dex/dex_test.go +++ b/util/dex/dex_test.go @@ -481,7 +481,7 @@ func Test_DexReverseProxy(t *testing.T) { }) t.Run("Bad case", func(t *testing.T) { - fakeDex := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + fakeDex := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { rw.WriteHeader(http.StatusInternalServerError) })) defer fakeDex.Close() @@ -490,7 +490,7 @@ func Test_DexReverseProxy(t *testing.T) { fmt.Printf("Fake API Server listening on %s\n", server.URL) defer server.Close() client := &http.Client{ - CheckRedirect: func(req *http.Request, via []*http.Request) error { + CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }, } @@ -511,7 +511,7 @@ func Test_DexReverseProxy(t *testing.T) { }) t.Run("Round Tripper", func(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + server := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, req *http.Request) { assert.Equal(t, "/", req.URL.String()) })) defer server.Close() diff --git a/util/git/client.go b/util/git/client.go index 300646e22c..3625edbbda 100644 --- a/util/git/client.go +++ b/util/git/client.go @@ -211,7 +211,7 @@ func GetRepoHTTPClient(repoURL string, insecure bool, creds Creds, proxyURL stri // 15 second timeout by default Timeout: gitClientTimeout, // don't follow redirect - CheckRedirect: func(req *http.Request, via []*http.Request) error { + CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }, } @@ -220,7 +220,7 @@ func GetRepoHTTPClient(repoURL string, insecure bool, creds Creds, proxyURL stri // Callback function to return any configured client certificate // We never return err, but an empty cert instead. - clientCertFunc := func(req *tls.CertificateRequestInfo) (*tls.Certificate, error) { + clientCertFunc := func(_ *tls.CertificateRequestInfo) (*tls.Certificate, error) { var err error cert := tls.Certificate{} diff --git a/util/git/creds.go b/util/git/creds.go index de84fc42dc..6cdf40c50a 100644 --- a/util/git/creds.go +++ b/util/git/creds.go @@ -61,14 +61,14 @@ func init() { type NoopCredsStore struct{} -func (d NoopCredsStore) Add(username string, password string) string { +func (d NoopCredsStore) Add(_ string, _ string) string { return "" } -func (d NoopCredsStore) Remove(id string) { +func (d NoopCredsStore) Remove(_ string) { } -func (d NoopCredsStore) Environ(id string) []string { +func (d NoopCredsStore) Environ(_ string) []string { return []string{} } @@ -101,7 +101,7 @@ func (c NopCreds) Environ() (io.Closer, []string, error) { } // GetUserInfo returns empty strings for user info -func (c NopCreds) GetUserInfo(ctx context.Context) (name string, email string, err error) { +func (c NopCreds) GetUserInfo(_ context.Context) (name string, email string, err error) { return "", "", nil } @@ -156,7 +156,7 @@ func NewHTTPSCreds(username string, password string, clientCertData string, clie } // GetUserInfo returns the username and email address for the credentials, if they're available. -func (creds HTTPSCreds) GetUserInfo(ctx context.Context) (string, string, error) { +func (creds HTTPSCreds) GetUserInfo(_ context.Context) (string, string, error) { // Email not implemented for HTTPS creds. return creds.username, "", nil } @@ -269,7 +269,7 @@ func NewSSHCreds(sshPrivateKey string, caPath string, insecureIgnoreHostKey bool // GetUserInfo returns empty strings for user info. // TODO: Implement this method to return the username and email address for the credentials, if they're available. -func (c SSHCreds) GetUserInfo(ctx context.Context) (string, string, error) { +func (c SSHCreds) GetUserInfo(_ context.Context) (string, string, error) { // User info not implemented for SSH creds. return "", "", nil } @@ -586,7 +586,7 @@ func NewGoogleCloudCreds(jsonData string, store CredsStore) GoogleCloudCreds { // GetUserInfo returns the username and email address for the credentials, if they're available. // TODO: implement getting email instead of just username. -func (c GoogleCloudCreds) GetUserInfo(ctx context.Context) (string, string, error) { +func (c GoogleCloudCreds) GetUserInfo(_ context.Context) (string, string, error) { username, err := c.getUsername() if err != nil { return "", "", fmt.Errorf("failed to get username from creds: %w", err) diff --git a/util/git/creds_test.go b/util/git/creds_test.go index 303ac2f8f4..322a79cd04 100644 --- a/util/git/creds_test.go +++ b/util/git/creds_test.go @@ -43,7 +43,7 @@ func (s *memoryCredsStore) Remove(id string) { delete(s.creds, id) } -func (s *memoryCredsStore) Environ(id string) []string { +func (s *memoryCredsStore) Environ(_ string) []string { return nil } diff --git a/util/gpg/gpg.go b/util/gpg/gpg.go index 6b8cefbeea..b3cf979b60 100644 --- a/util/gpg/gpg.go +++ b/util/gpg/gpg.go @@ -704,7 +704,7 @@ func SyncKeyRingFromDirectory(basePath string) ([]string, []string, error) { } // Collect configuration, i.e. files in basePath - err = filepath.Walk(basePath, func(path string, fi os.FileInfo, err error) error { + err = filepath.Walk(basePath, func(_ string, fi os.FileInfo, err error) error { if err != nil { return err } diff --git a/util/grpc/errors.go b/util/grpc/errors.go index 4af5238521..141c76e7b1 100644 --- a/util/grpc/errors.go +++ b/util/grpc/errors.go @@ -103,7 +103,7 @@ func kubeErrToGRPC(err error) error { // ErrorCodeGitUnaryServerInterceptor replaces Kubernetes errors with relevant gRPC equivalents, if any. func ErrorCodeGitUnaryServerInterceptor() grpc.UnaryServerInterceptor { - return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) { + return func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) { resp, err = handler(ctx, req) return resp, gitErrToGRPC(err) } @@ -111,7 +111,7 @@ func ErrorCodeGitUnaryServerInterceptor() grpc.UnaryServerInterceptor { // ErrorCodeGitStreamServerInterceptor replaces Kubernetes errors with relevant gRPC equivalents, if any. func ErrorCodeGitStreamServerInterceptor() grpc.StreamServerInterceptor { - return func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + return func(srv any, ss grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error { err := handler(srv, ss) return gitErrToGRPC(err) } @@ -119,7 +119,7 @@ func ErrorCodeGitStreamServerInterceptor() grpc.StreamServerInterceptor { // ErrorCodeK8sUnaryServerInterceptor replaces Kubernetes errors with relevant gRPC equivalents, if any. func ErrorCodeK8sUnaryServerInterceptor() grpc.UnaryServerInterceptor { - return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) { + return func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) { resp, err = handler(ctx, req) return resp, kubeErrToGRPC(err) } @@ -127,7 +127,7 @@ func ErrorCodeK8sUnaryServerInterceptor() grpc.UnaryServerInterceptor { // ErrorCodeK8sStreamServerInterceptor replaces Kubernetes errors with relevant gRPC equivalents, if any. func ErrorCodeK8sStreamServerInterceptor() grpc.StreamServerInterceptor { - return func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + return func(srv any, ss grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error { err := handler(srv, ss) return kubeErrToGRPC(err) } diff --git a/util/grpc/grpc.go b/util/grpc/grpc.go index bc6526a6f4..7216f3c9b5 100644 --- a/util/grpc/grpc.go +++ b/util/grpc/grpc.go @@ -23,7 +23,7 @@ import ( // PanicLoggerUnaryServerInterceptor returns a new unary server interceptor for recovering from panics and returning error func PanicLoggerUnaryServerInterceptor(log *logrus.Entry) grpc.UnaryServerInterceptor { - return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (_ any, err error) { + return func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (_ any, err error) { defer func() { if r := recover(); r != nil { log.Errorf("Recovered from panic: %+v\n%s", r, debug.Stack()) @@ -36,7 +36,7 @@ func PanicLoggerUnaryServerInterceptor(log *logrus.Entry) grpc.UnaryServerInterc // PanicLoggerStreamServerInterceptor returns a new streaming server interceptor for recovering from panics and returning error func PanicLoggerStreamServerInterceptor(log *logrus.Entry) grpc.StreamServerInterceptor { - return func(srv any, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) { + return func(srv any, stream grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) { defer func() { if r := recover(); r != nil { log.Errorf("Recovered from panic: %+v\n%s", r, debug.Stack()) diff --git a/util/grpc/logging_test.go b/util/grpc/logging_test.go index b7d30b0c62..cd9c05aae4 100644 --- a/util/grpc/logging_test.go +++ b/util/grpc/logging_test.go @@ -26,10 +26,10 @@ func Test_JSONLogging(t *testing.T) { req := new(account.CreateTokenRequest) req.Name = "create-token-name" info := &grpc.UnaryServerInfo{} - handler := func(ctx context.Context, req any) (any, error) { + handler := func(_ context.Context, _ any) (any, error) { return nil, nil } - decider := func(ctx context.Context, fullMethodName string, servingObject any) bool { + decider := func(_ context.Context, _ string, _ any) bool { return true } interceptor := PayloadUnaryServerInterceptor(entry, false, decider) @@ -47,10 +47,10 @@ func Test_logRequest(t *testing.T) { req := new(account.CreateTokenRequest) req.Name = "create-token-name" info := &grpc.UnaryServerInfo{} - handler := func(ctx context.Context, req any) (any, error) { + handler := func(_ context.Context, _ any) (any, error) { return nil, nil } - decider := func(ctx context.Context, fullMethodName string, servingObject any) bool { + decider := func(_ context.Context, _ string, _ any) bool { return true } diff --git a/util/grpc/sanitizer.go b/util/grpc/sanitizer.go index 45bd8f82ac..1afae682fb 100644 --- a/util/grpc/sanitizer.go +++ b/util/grpc/sanitizer.go @@ -19,7 +19,7 @@ const ( // ErrorSanitizerUnaryServerInterceptor returns a new unary server interceptor that sanitizes error messages // and provides Sanitizer to define replacements. func ErrorSanitizerUnaryServerInterceptor() grpc.UnaryServerInterceptor { - return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) { + return func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) { sanitizer := NewSanitizer() resp, err = handler(ContextWithSanitizer(ctx, sanitizer), req) if err == nil { diff --git a/util/grpc/sanitizer_test.go b/util/grpc/sanitizer_test.go index ba016a1cd3..9f7ac92f4a 100644 --- a/util/grpc/sanitizer_test.go +++ b/util/grpc/sanitizer_test.go @@ -40,7 +40,7 @@ func TestSanitizer_RegexReplacement(t *testing.T) { func TestErrorSanitizerUnaryServerInterceptor(t *testing.T) { interceptor := ErrorSanitizerUnaryServerInterceptor() - _, err := interceptor(context.Background(), nil, nil, func(ctx context.Context, req any) (any, error) { + _, err := interceptor(context.Background(), nil, nil, func(ctx context.Context, _ any) (any, error) { sanitizer, ok := SanitizerFromContext(ctx) require.True(t, ok) sanitizer.AddReplacement("/my-random/path", ".") diff --git a/util/grpc/useragent.go b/util/grpc/useragent.go index a05d51c669..54ecdde769 100644 --- a/util/grpc/useragent.go +++ b/util/grpc/useragent.go @@ -18,7 +18,7 @@ func UserAgentUnaryServerInterceptor(clientName, constraintStr string) grpc.Unar if err != nil { panic(err) } - return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { + return func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { if err := userAgentEnforcer(ctx, clientName, constraintStr, semVerConstraint); err != nil { return nil, err } @@ -33,7 +33,7 @@ func UserAgentStreamServerInterceptor(clientName, constraintStr string) grpc.Str if err != nil { panic(err) } - return func(srv any, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + return func(srv any, stream grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error { if err := userAgentEnforcer(stream.Context(), clientName, constraintStr, semVerConstraint); err != nil { return err } diff --git a/util/healthz/healthz_test.go b/util/healthz/healthz_test.go index d2724686dd..c76a284c67 100644 --- a/util/healthz/healthz_test.go +++ b/util/healthz/healthz_test.go @@ -23,7 +23,7 @@ func TestHealthCheck(t *testing.T) { c <- listener.Addr().String() mux := http.NewServeMux() - ServeHealthCheck(mux, func(r *http.Request) error { + ServeHealthCheck(mux, func(_ *http.Request) error { if sentinel { return errors.New("This is a dummy error") } diff --git a/util/helm/cmd.go b/util/helm/cmd.go index 28b458fa51..0f5abca86f 100644 --- a/util/helm/cmd.go +++ b/util/helm/cmd.go @@ -120,7 +120,7 @@ func (c *Cmd) RegistryLogin(repo string, creds Creds) (string, error) { return out, nil } -func (c *Cmd) RegistryLogout(repo string, creds Creds) (string, error) { +func (c *Cmd) RegistryLogout(repo string, _ Creds) (string, error) { args := []string{"registry", "logout"} args = append(args, repo) out, _, err := c.run(args...) diff --git a/util/kube/failureretrywrapper.go b/util/kube/failureretrywrapper.go index f9d66e8910..9cacc6d0c7 100644 --- a/util/kube/failureretrywrapper.go +++ b/util/kube/failureretrywrapper.go @@ -17,7 +17,7 @@ type failureRetryRoundTripper struct { } // nolint:unparam -func shouldRetry(counter int, r *http.Request, response *http.Response, err error) bool { +func shouldRetry(counter int, _ *http.Request, response *http.Response, err error) bool { if counter <= 0 { return false } diff --git a/util/kube/util.go b/util/kube/util.go index b5e4c2498f..684e5a1e02 100644 --- a/util/kube/util.go +++ b/util/kube/util.go @@ -70,7 +70,7 @@ func (ku *kubeUtil) CreateOrUpdateSecret(ns string, name string, update updateFn // CreateOrUpdateSecretField creates or updates a secret name in namespace ns, with given value for given field func (ku *kubeUtil) CreateOrUpdateSecretField(ns string, name string, field string, value string) error { - err := ku.CreateOrUpdateSecret(ns, name, func(s *corev1.Secret, new bool) error { + err := ku.CreateOrUpdateSecret(ns, name, func(s *corev1.Secret, _ bool) error { s.Data[field] = []byte(value) return nil }) diff --git a/util/lua/custom_actions_test.go b/util/lua/custom_actions_test.go index dc8662bc5e..8df7c78975 100644 --- a/util/lua/custom_actions_test.go +++ b/util/lua/custom_actions_test.go @@ -103,7 +103,7 @@ type IndividualActionTest struct { } func TestLuaResourceActionsScript(t *testing.T) { - err := filepath.Walk("../../resource_customizations", func(path string, f os.FileInfo, err error) error { + err := filepath.Walk("../../resource_customizations", func(path string, _ os.FileInfo, err error) error { if !strings.Contains(path, "action_test.yaml") { return nil } diff --git a/util/lua/health_test.go b/util/lua/health_test.go index c2e4e67663..caf28e84ff 100644 --- a/util/lua/health_test.go +++ b/util/lua/health_test.go @@ -34,7 +34,7 @@ func getObj(path string) *unstructured.Unstructured { } func TestLuaHealthScript(t *testing.T) { - err := filepath.Walk("../../resource_customizations", func(path string, f os.FileInfo, err error) error { + err := filepath.Walk("../../resource_customizations", func(path string, _ os.FileInfo, err error) error { if !strings.Contains(path, "health.lua") { return nil } diff --git a/util/notification/expression/strings/strings_test.go b/util/notification/expression/strings/strings_test.go index 76cb57606b..c84ba4f374 100644 --- a/util/notification/expression/strings/strings_test.go +++ b/util/notification/expression/strings/strings_test.go @@ -49,7 +49,7 @@ func TestUpperAndLower(t *testing.T) { exprs := NewExprs() for _, testCase := range testCases { - t.Run("With success case: Func: "+testCase.fn, func(tc *testing.T) { + t.Run("With success case: Func: "+testCase.fn, func(t *testing.T) { toUpperFn, ok := exprs[testCase.fn].(func(s string) string) assert.True(t, ok) diff --git a/util/oidc/oidc_test.go b/util/oidc/oidc_test.go index 2b35cef926..b31bb407af 100644 --- a/util/oidc/oidc_test.go +++ b/util/oidc/oidc_test.go @@ -644,7 +644,7 @@ func TestGetUserInfo(t *testing.T) { }, }, idpClaims: jwt.MapClaims{"sub": "randomUser", "exp": float64(time.Now().Add(5 * time.Minute).Unix())}, - idpHandler: func(w http.ResponseWriter, r *http.Request) { + idpHandler: func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNotFound) }, cache: cache.NewInMemoryCache(24 * time.Hour), @@ -678,7 +678,7 @@ func TestGetUserInfo(t *testing.T) { }, }, idpClaims: jwt.MapClaims{"sub": "randomUser", "exp": float64(time.Now().Add(5 * time.Minute).Unix())}, - idpHandler: func(w http.ResponseWriter, r *http.Request) { + idpHandler: func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusUnauthorized) }, cache: cache.NewInMemoryCache(24 * time.Hour), @@ -712,7 +712,7 @@ func TestGetUserInfo(t *testing.T) { }, }, idpClaims: jwt.MapClaims{"sub": "randomUser", "exp": float64(time.Now().Add(5 * time.Minute).Unix())}, - idpHandler: func(w http.ResponseWriter, r *http.Request) { + idpHandler: func(w http.ResponseWriter, _ *http.Request) { userInfoBytes := ` notevenJsongarbage ` @@ -754,7 +754,7 @@ func TestGetUserInfo(t *testing.T) { }, }, idpClaims: jwt.MapClaims{"sub": "randomUser", "exp": float64(time.Now().Add(5 * time.Minute).Unix())}, - idpHandler: func(w http.ResponseWriter, r *http.Request) { + idpHandler: func(w http.ResponseWriter, _ *http.Request) { userInfoBytes := ` { "groups":["githubOrg:engineers"] @@ -789,7 +789,7 @@ func TestGetUserInfo(t *testing.T) { }, }, idpClaims: jwt.MapClaims{"sub": "randomUser", "exp": float64(time.Now().Add(5 * time.Minute).Unix())}, - idpHandler: func(w http.ResponseWriter, r *http.Request) { + idpHandler: func(w http.ResponseWriter, _ *http.Request) { userInfoBytes := ` { "groups":["githubOrg:engineers"] diff --git a/util/rbac/rbac.go b/util/rbac/rbac.go index 77a8a4cbbd..300de8c92f 100644 --- a/util/rbac/rbac.go +++ b/util/rbac/rbac.go @@ -519,18 +519,18 @@ func loadPolicyLine(line string, model model.Model) error { return nil } -func (a *argocdAdapter) SavePolicy(model model.Model) error { +func (a *argocdAdapter) SavePolicy(_ model.Model) error { return errors.New("not implemented") } -func (a *argocdAdapter) AddPolicy(sec string, ptype string, rule []string) error { +func (a *argocdAdapter) AddPolicy(_ string, _ string, _ []string) error { return errors.New("not implemented") } -func (a *argocdAdapter) RemovePolicy(sec string, ptype string, rule []string) error { +func (a *argocdAdapter) RemovePolicy(_ string, _ string, _ []string) error { return errors.New("not implemented") } -func (a *argocdAdapter) RemoveFilteredPolicy(sec string, ptype string, fieldIndex int, fieldValues ...string) error { +func (a *argocdAdapter) RemoveFilteredPolicy(_ string, _ string, _ int, _ ...string) error { return errors.New("not implemented") } diff --git a/util/rbac/rbac_norace_test.go b/util/rbac/rbac_norace_test.go index a35d29ceba..97735a2ef6 100644 --- a/util/rbac/rbac_norace_test.go +++ b/util/rbac/rbac_norace_test.go @@ -32,7 +32,7 @@ func TestPolicyInformer(t *testing.T) { ctx := context.Background() ctx, cancel := context.WithCancel(ctx) defer cancel() - go enf.runInformer(ctx, func(cm *corev1.ConfigMap) error { + go enf.runInformer(ctx, func(_ *corev1.ConfigMap) error { return nil }) diff --git a/util/rbac/rbac_test.go b/util/rbac/rbac_test.go index 8e8b54f44c..4b4cce17d9 100644 --- a/util/rbac/rbac_test.go +++ b/util/rbac/rbac_test.go @@ -22,7 +22,7 @@ const ( fakeNamespace = "fake-ns" ) -var noOpUpdate = func(cm *corev1.ConfigMap) error { +var noOpUpdate = func(_ *corev1.ConfigMap) error { return nil } @@ -215,7 +215,7 @@ p, alice, *, get, foo/obj, allow p, mike, *, get, foo/obj, deny ` _ = enf.SetUserPolicy(policy) - enf.SetClaimsEnforcerFunc(func(claims jwt.Claims, rvals ...any) bool { + enf.SetClaimsEnforcerFunc(func(_ jwt.Claims, _ ...any) bool { return false }) @@ -279,7 +279,7 @@ func TestClaimsEnforcerFunc(t *testing.T) { Subject: "foo", } assert.False(t, enf.Enforce(&claims, "applications", "get", "foo/bar")) - enf.SetClaimsEnforcerFunc(func(claims jwt.Claims, rvals ...any) bool { + enf.SetClaimsEnforcerFunc(func(_ jwt.Claims, _ ...any) bool { return true }) assert.True(t, enf.Enforce(&claims, "applications", "get", "foo/bar")) @@ -308,7 +308,7 @@ func TestClaimsEnforcerFuncWithRuntimePolicy(t *testing.T) { Subject: "foo", } assert.False(t, enf.EnforceRuntimePolicy("", runtimePolicy, claims, "applications", "get", "foo/bar")) - enf.SetClaimsEnforcerFunc(func(claims jwt.Claims, rvals ...any) bool { + enf.SetClaimsEnforcerFunc(func(_ jwt.Claims, _ ...any) bool { return true }) assert.True(t, enf.EnforceRuntimePolicy("", runtimePolicy, claims, "applications", "get", "foo/bar")) diff --git a/util/session/sessionmanager_test.go b/util/session/sessionmanager_test.go index 82d3472f3f..1fe50fb74a 100644 --- a/util/session/sessionmanager_test.go +++ b/util/session/sessionmanager_test.go @@ -225,7 +225,7 @@ type tokenVerifierMock struct { err error } -func (tm *tokenVerifierMock) VerifyToken(token string) (jwt.Claims, string, error) { +func (tm *tokenVerifierMock) VerifyToken(_ string) (jwt.Claims, string, error) { if tm.claims == nil { return nil, "", tm.err } @@ -238,7 +238,7 @@ func strPointer(str string) *string { func TestSessionManager_WithAuthMiddleware(t *testing.T) { handlerFunc := func() func(http.ResponseWriter, *http.Request) { - return func(w http.ResponseWriter, r *http.Request) { + return func(w http.ResponseWriter, _ *http.Request) { t.Helper() w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", "application/text") diff --git a/util/settings/settings.go b/util/settings/settings.go index 0fec981957..47893e4185 100644 --- a/util/settings/settings.go +++ b/util/settings/settings.go @@ -1388,14 +1388,14 @@ func (mgr *SettingsManager) initialize(ctx context.Context) error { } eventHandler := cache.ResourceEventHandlerFuncs{ - UpdateFunc: func(oldObj, newObj any) { + UpdateFunc: func(_, _ any) { mgr.invalidateCache() mgr.onRepoOrClusterChanged() }, - AddFunc: func(obj any) { + AddFunc: func(_ any) { mgr.onRepoOrClusterChanged() }, - DeleteFunc: func(obj any) { + DeleteFunc: func(_ any) { mgr.onRepoOrClusterChanged() }, } diff --git a/util/swagger/swagger.go b/util/swagger/swagger.go index 44cf8b0a52..0509939129 100644 --- a/util/swagger/swagger.go +++ b/util/swagger/swagger.go @@ -15,7 +15,7 @@ const redocScriptName = "redoc.standalone.js" func ServeSwaggerUI(mux *http.ServeMux, swaggerJSON string, uiPath string, rootPath string) { prefix := path.Dir(uiPath) swaggerPath := path.Join(prefix, "swagger.json") - mux.HandleFunc(swaggerPath, func(w http.ResponseWriter, r *http.Request) { + mux.HandleFunc(swaggerPath, func(w http.ResponseWriter, _ *http.Request) { _, _ = fmt.Fprint(w, swaggerJSON) }) diff --git a/util/test/testutil.go b/util/test/testutil.go index 61fa0e7461..0da029fdae 100644 --- a/util/test/testutil.go +++ b/util/test/testutil.go @@ -139,7 +139,7 @@ func dexMockHandler(t *testing.T, url string) func(http.ResponseWriter, *http.Re func GetDexTestServer(t *testing.T) *httptest.Server { t.Helper() - ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ts := httptest.NewTLSServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) { // Start with a placeholder. We need the server URL before setting up the real handler. })) ts.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -204,7 +204,7 @@ func oidcMockHandler(t *testing.T, url string) func(http.ResponseWriter, *http.R func GetOIDCTestServer(t *testing.T) *httptest.Server { t.Helper() - ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ts := httptest.NewTLSServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) { // Start with a placeholder. We need the server URL before setting up the real handler. })) ts.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {