diff --git a/.golangci.yml b/.golangci.yml index 9350ed9005b..9c8e4708f30 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,38 +1,50 @@ -run: - timeout: 10m - +version: "2" linters: + default: none enable: - - unused - - gosimple - - gofmt - - govet - - staticcheck - - unparam - - unconvert + - bodyclose - errcheck + - errorlint + - govet - ineffassign - misspell - - bodyclose - - errorlint - disable-all: true - -linters-settings: - errorlint: - errorf: true - errorf-multi: false - asserts: false - comparison: false - misspell: - ignore-words: - - creater - -issues: - exclude-rules: - - linters: - - unparam - text: \(\*leaseStep\)\.Provides\$1 - result 1 \(error\) is always nil - - linters: - staticcheck - # Code has a "Deprecated:" comment - text: "SA1019:" + - unconvert + - unparam + - unused + settings: + errorlint: + errorf: true + errorf-multi: false + asserts: false + comparison: false + misspell: + ignore-rules: + - creater + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + rules: + - linters: + - unparam + text: \(\*leaseStep\)\.Provides\$1 - result 1 \(error\) is always nil + - linters: + - staticcheck + text: 'SA1019:' + paths: + - third_party$ + - builtin$ + - examples$ +formatters: + enable: + - gofmt + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ diff --git a/cmd/applyconfig/applyconfig.go b/cmd/applyconfig/applyconfig.go index 84da256209a..a1fbe780683 100644 --- a/cmd/applyconfig/applyconfig.go +++ b/cmd/applyconfig/applyconfig.go @@ -188,10 +188,10 @@ func makeOcApply(kubeConfig, context, path, user string, dry dryRunMethod, apply cmd.Args = append(cmd.Args, "--dry-run=server", "--validate=true") case dryClient: cmd.Args = append(cmd.Args, "--dry-run=client") - default: - panic(fmt.Sprintf("BUG: Unknown dry run method '%s' received, this should never happen", string(dry))) case dryNone: // No additional args needed + default: + panic(fmt.Sprintf("BUG: Unknown dry run method '%s' received, this should never happen", string(dry))) } fileName := filepath.Base(path) diff --git a/cmd/autoconfigbrancher/main.go b/cmd/autoconfigbrancher/main.go index 069c1ebe8a5..9502a4eb6f9 100644 --- a/cmd/autoconfigbrancher/main.go +++ b/cmd/autoconfigbrancher/main.go @@ -51,7 +51,7 @@ type options struct { func parseOptions() options { var o options fs := flag.NewFlagSet(os.Args[0], flag.ExitOnError) - o.FutureOptions.Bind(fs) + o.Bind(fs) fs.StringVar(&o.githubLogin, "github-login", githubLogin, "The GitHub username to use.") fs.StringVar(&o.gitName, "git-name", "", "The name to use on the git commit. Requires --git-email. If not specified, uses the system default.") fs.StringVar(&o.gitEmail, "git-email", "", "The email to use on the git commit. Requires --git-name. If not specified, uses the system default.") @@ -135,11 +135,11 @@ func main() { logrus.WithError(fmt.Errorf("version %s split by dot doesn't have two elements", o.CurrentRelease)).Fatal("Failed to parse the current version") } - if err := secret.Add(o.GitHubOptions.TokenPath); err != nil { + if err := secret.Add(o.TokenPath); err != nil { logrus.WithError(err).Fatal("Failed to start secrets agent") } - gc, err := o.GitHubOptions.GitHubClient(!o.Confirm) + gc, err := o.GitHubClient(!o.Confirm) if err != nil { logrus.WithError(err).Fatal("error getting GitHub client") } @@ -292,7 +292,7 @@ func main() { func runSteps(steps []step, author string, stdout, stderr io.Writer) (needsPushing bool, err error) { startCommitOut, err := exec.Command("git", "rev-parse", "HEAD").CombinedOutput() if err != nil { - return false, fmt.Errorf("failed to execute `git rev-parse HEAD`: %w\noutput:%s\n", err, string(startCommitOut)) + return false, fmt.Errorf("failed to execute `git rev-parse HEAD`: %w\noutput:%s", err, string(startCommitOut)) } startCommitSHA := strings.TrimSpace(string(startCommitOut)) @@ -313,7 +313,7 @@ func runSteps(steps []step, author string, stdout, stderr io.Writer) (needsPushi overallDiff, err := exec.Command("git", "diff", startCommitSHA).CombinedOutput() if err != nil { - return false, fmt.Errorf("failed to check the overall diff: %w, out:\n%s\n", err, string(overallDiff)) + return false, fmt.Errorf("failed to check the overall diff: %w, out:\n%s", err, string(overallDiff)) } if strings.TrimSpace(string(overallDiff)) == "" { logrus.Info("Empty overall diff") diff --git a/cmd/autoperibolossync/main.go b/cmd/autoperibolossync/main.go index 6f964aff23b..a5471946dfd 100644 --- a/cmd/autoperibolossync/main.go +++ b/cmd/autoperibolossync/main.go @@ -91,7 +91,7 @@ func validateOptions(o options) error { if o.peribolosConfig == "" { return errors.New("--peribolos-config is not specified") } - return o.GitHubOptions.Validate(o.dryRun) + return o.Validate(o.dryRun) } func main() { @@ -100,11 +100,11 @@ func main() { logrus.WithError(err).Fatal("Invalid arguments.") } - if err := secret.Add(o.GitHubOptions.TokenPath); err != nil { + if err := secret.Add(o.TokenPath); err != nil { logrus.WithError(err).Fatal("Failed to start secrets agent") } - gc, err := o.GitHubOptions.GitHubClient(o.dryRun) + gc, err := o.GitHubClient(o.dryRun) if err != nil { logrus.WithError(err).Fatal("error getting GitHub client") } @@ -150,7 +150,7 @@ func main() { } title := fmt.Sprintf("%s %s", matchTitle, time.Now().Format(time.RFC1123)) - if err := bumper.GitCommitAndPush(fmt.Sprintf("https://%s:%s@github.com/%s/%s.git", o.githubLogin, string(secret.GetTokenGenerator(o.GitHubOptions.TokenPath)()), o.githubLogin, githubRepo), remoteBranch, o.gitName, o.gitEmail, title, stdout, stderr, o.dryRun); err != nil { + if err := bumper.GitCommitAndPush(fmt.Sprintf("https://%s:%s@github.com/%s/%s.git", o.githubLogin, string(secret.GetTokenGenerator(o.TokenPath)()), o.githubLogin, githubRepo), remoteBranch, o.gitName, o.gitEmail, title, stdout, stderr, o.dryRun); err != nil { logrus.WithError(err).Fatal("Failed to push changes.") } diff --git a/cmd/autopublicizeconfig/main.go b/cmd/autopublicizeconfig/main.go index c3ec068663e..458d4d1e32e 100644 --- a/cmd/autopublicizeconfig/main.go +++ b/cmd/autopublicizeconfig/main.go @@ -60,7 +60,7 @@ func parseOptions() options { fs.StringVar(&o.releaseRepoPath, "release-repo-path", "", "Path to a openshift/release repository directory") o.AddFlags(fs) - o.WhitelistOptions.Bind(fs) + o.Bind(fs) if err := fs.Parse(os.Args[1:]); err != nil { logrus.WithError(err).Errorf("cannot parse args: '%s'", os.Args[1:]) @@ -97,17 +97,17 @@ func main() { logrus.WithError(err).Fatal("Invalid arguments.") } - if err := secret.Add(o.GitHubOptions.TokenPath); err != nil { + if err := secret.Add(o.TokenPath); err != nil { logrus.WithError(err).Fatal("Failed to start secrets agent") } - gc, err := o.GitHubOptions.GitHubClient(o.dryRun) + gc, err := o.GitHubClient(o.dryRun) if err != nil { logrus.WithError(err).Fatal("error getting GitHub client") } logrus.Info("Getting repositories that exists in the whitelist or promote official images") - orgRepos, err := getReposForPrivateOrg(o.releaseRepoPath, o.WhitelistOptions.WhitelistConfig.Whitelist) + orgRepos, err := getReposForPrivateOrg(o.releaseRepoPath, o.WhitelistConfig.Whitelist) if err != nil { logrus.WithError(err).Fatal("couldn't get the list of org/repos that promote official images") } @@ -157,7 +157,7 @@ func main() { logrus.Info("Preparing pull request") title := fmt.Sprintf("%s %s", matchTitle, time.Now().Format(time.RFC1123)) - if err := bumper.GitCommitAndPush(fmt.Sprintf("https://%s:%s@github.com/%s/%s.git", o.githubLogin, string(secret.GetTokenGenerator(o.GitHubOptions.TokenPath)()), o.githubLogin, githubRepo), remoteBranch, o.gitName, o.gitEmail, title, stdout, stderr, o.dryRun); err != nil { + if err := bumper.GitCommitAndPush(fmt.Sprintf("https://%s:%s@github.com/%s/%s.git", o.githubLogin, string(secret.GetTokenGenerator(o.TokenPath)()), o.githubLogin, githubRepo), remoteBranch, o.gitName, o.gitEmail, title, stdout, stderr, o.dryRun); err != nil { logrus.WithError(err).Fatal("Failed to push changes.") } diff --git a/cmd/autotestgridgenerator/main.go b/cmd/autotestgridgenerator/main.go index 1eb6c61310b..d67d47c9c83 100644 --- a/cmd/autotestgridgenerator/main.go +++ b/cmd/autotestgridgenerator/main.go @@ -52,7 +52,7 @@ func parseOptions() options { fs.StringVar(&o.upstreamBranch, "upstream-branch", upstreamBranch, "The repository branch name where the PR will be created.") o.GitAuthorOptions.AddFlags(fs) - o.PRCreationOptions.GitHubOptions.AddFlags(fs) + o.GitHubOptions.AddFlags(fs) if err := fs.Parse(os.Args[1:]); err != nil { logrus.WithError(err).Errorf("cannot parse args: '%s'", os.Args[1:]) } @@ -60,7 +60,7 @@ func parseOptions() options { } func validateOptions(o options) error { - if err := o.GitAuthorOptions.Validate(); err != nil { + if err := o.Validate(); err != nil { return err } return o.GitHubOptions.Validate(false) @@ -71,7 +71,7 @@ func main() { if err := validateOptions(o); err != nil { logrus.WithError(err).Fatal("Invalid arguments.") } - if err := o.PRCreationOptions.Finalize(); err != nil { + if err := o.Finalize(); err != nil { logrus.WithError(err).Fatal("failed to finalize PR creation options") } @@ -96,7 +96,7 @@ func main() { logrus.WithError(err).Fatalf("failed to run %s", fullCommand) } title := fmt.Sprintf("%s at %s", matchTitle, time.Now().Format(time.RFC1123)) - err = o.PRCreationOptions.UpsertPR(o.workingDir, o.githubOrg, githubRepo, o.upstreamBranch, title, prcreation.PrAssignee(o.assign), prcreation.MatchTitle(matchTitle)) + err = o.UpsertPR(o.workingDir, o.githubOrg, githubRepo, o.upstreamBranch, title, prcreation.PrAssignee(o.assign), prcreation.MatchTitle(matchTitle)) if err != nil { logrus.WithError(err).Fatalf("failed to upsert PR") } diff --git a/cmd/blocking-issue-creator/main.go b/cmd/blocking-issue-creator/main.go index 1003c34eb6a..3fcfc9915fc 100644 --- a/cmd/blocking-issue-creator/main.go +++ b/cmd/blocking-issue-creator/main.go @@ -50,7 +50,7 @@ func gatherOptions() options { fs.BoolVar(&o.dryRun, "dry-run", true, "Dry run for testing. Uses API tokens but does not mutate.") o.github.AddFlags(fs) - o.FutureOptions.Bind(fs) + o.Bind(fs) if err := fs.Parse(os.Args[1:]); err != nil { logrus.WithError(err).Fatal("could not parse input") diff --git a/cmd/blocking-issue-creator/main_test.go b/cmd/blocking-issue-creator/main_test.go index 25c566baa57..38a87f244a9 100644 --- a/cmd/blocking-issue-creator/main_test.go +++ b/cmd/blocking-issue-creator/main_test.go @@ -21,7 +21,7 @@ type fakeGithubClient struct { func (f fakeGithubClient) FindIssues(query, sortVerb string, asc bool) ([]github.Issue, error) { var issues []github.Issue - for _, issue := range f.FakeClient.Issues { + for _, issue := range f.Issues { issues = append(issues, *issue) } sort.Slice(issues, func(i, j int) bool { return issues[i].ID < issues[j].ID }) @@ -222,7 +222,7 @@ func TestManageIssues(t *testing.T) { fgh := fakeGithubClient{ FakeClient: fakegithub.NewFakeClient(), } - fgh.FakeClient.Issues = tc.issues + fgh.Issues = tc.issues if err := manageIssues(fgh, "", tc.repoInfo, tc.branches, logrus.WithField("id", tc.id)); err != nil { t.Fatal(err) diff --git a/cmd/branchingconfigmanagers/frequency-reducer/main.go b/cmd/branchingconfigmanagers/frequency-reducer/main.go index 8cbca358818..04b6339d2b2 100644 --- a/cmd/branchingconfigmanagers/frequency-reducer/main.go +++ b/cmd/branchingconfigmanagers/frequency-reducer/main.go @@ -25,7 +25,7 @@ type options struct { func (o options) validate() error { var errs []error - if err := o.ConfirmableOptions.Validate(); err != nil { + if err := o.Validate(); err != nil { errs = append(errs, err) } @@ -53,7 +53,7 @@ func main() { logrus.Fatalf("Not valid --current-release: %v", err) } - if err := o.ConfirmableOptions.Complete(); err != nil { + if err := o.Complete(); err != nil { logrus.Fatalf("Couldn't complete the config options: %v", err) } @@ -75,11 +75,11 @@ func updateIntervalFieldsForMatchedSteps( configuration *config.DataWithInfo, version ocplifecycle.MajorMinor, ) { - testVersion, err := ocplifecycle.ParseMajorMinor(extractVersion(configuration.Info.Metadata.Branch)) + testVersion, err := ocplifecycle.ParseMajorMinor(extractVersion(configuration.Info.Branch)) if err != nil { return } - if configuration.Info.Metadata.Org == "openshift" || configuration.Info.Metadata.Org == "openshift-priv" { + if configuration.Info.Org == "openshift" || configuration.Info.Org == "openshift-priv" { for _, test := range configuration.Configuration.Tests { if !strings.Contains(test.As, "mirror-nightly-image") && !strings.Contains(test.As, "promote-") { if test.Cron != nil { diff --git a/cmd/branchingconfigmanagers/tide-config-manager/main.go b/cmd/branchingconfigmanagers/tide-config-manager/main.go index 7e7ac595061..334f1a6b64d 100644 --- a/cmd/branchingconfigmanagers/tide-config-manager/main.go +++ b/cmd/branchingconfigmanagers/tide-config-manager/main.go @@ -334,7 +334,7 @@ func (gae *generalAvailabilityEvent) ensureStaffEngApprovedLabel(q *prowconfig.T branches.Insert(gae.openshiftFuture) } - if !(branches.Equal(sets.New[string](gae.releaseFuture)) || branches.Equal(sets.New[string](gae.openshiftFuture)) || branches.Equal(gae.openshiftReleaseBranchesPlus1)) { + if !branches.Equal(sets.New[string](gae.releaseFuture)) && !branches.Equal(sets.New[string](gae.openshiftFuture)) && !branches.Equal(gae.openshiftReleaseBranchesPlus1) { fmt.Printf("Suspicious staff-eng-approved query: %s\n", q.Repos) } } diff --git a/cmd/bugzilla-backporter/main.go b/cmd/bugzilla-backporter/main.go index 1b7aaf10e03..00259f79858 100644 --- a/cmd/bugzilla-backporter/main.go +++ b/cmd/bugzilla-backporter/main.go @@ -12,7 +12,6 @@ import ( "k8s.io/apimachinery/pkg/util/sets" prowConfig "sigs.k8s.io/prow/pkg/config" "sigs.k8s.io/prow/pkg/config/secret" - "sigs.k8s.io/prow/pkg/flagutil" prowflagutil "sigs.k8s.io/prow/pkg/flagutil" "sigs.k8s.io/prow/pkg/interrupts" "sigs.k8s.io/prow/pkg/metrics" @@ -45,7 +44,7 @@ func gatherOptions() (options, error) { fs.DurationVar(&o.gracePeriod, "gracePeriod", time.Second*10, "Grace period for server shutdown") fs.StringVar(&o.pluginConfig, "plugin-config", "/etc/plugins/plugins.yaml", "Path to plugin config file.") - for _, group := range []flagutil.OptionGroup{&o.bugzilla} { + for _, group := range []prowflagutil.OptionGroup{&o.bugzilla} { group.AddFlags(fs) } err := fs.Parse(os.Args[1:]) diff --git a/cmd/check-gh-automation/main.go b/cmd/check-gh-automation/main.go index 2237d00be51..8a4987522c4 100644 --- a/cmd/check-gh-automation/main.go +++ b/cmd/check-gh-automation/main.go @@ -234,7 +234,7 @@ func checkRepos(repos []string, bots []string, appName string, ignore sets.Set[s orgConfig := prowAgent.Config().BranchProtection.GetOrg(org) branchProtectionEnabled := true // By default, it is turned on in absence of configuration stating otherwise if orgConfig != nil { - unmanagedOrgLevel := orgConfig.Policy.Unmanaged + unmanagedOrgLevel := orgConfig.Unmanaged branchProtectionEnabled = unmanagedOrgLevel == nil || !*unmanagedOrgLevel repoLevel, exists := orgConfig.Repos[repo] diff --git a/cmd/ci-images-mirror/main.go b/cmd/ci-images-mirror/main.go index dc2d6574ae5..f6a14bd6b8f 100644 --- a/cmd/ci-images-mirror/main.go +++ b/cmd/ci-images-mirror/main.go @@ -163,7 +163,7 @@ func (s *supplementalCIImagesServiceWithMirrorStore) Mirror(m map[string]quayioc for k, v := range m { source := v.Image if source == "" { - source = fmt.Sprintf("%s/%s", api.ServiceDomainAPPCIRegistry, v.ImageStreamTagReference.ISTagName()) + source = fmt.Sprintf("%s/%s", api.ServiceDomainAPPCIRegistry, v.ISTagName()) } if err := s.mirrorStore.Put(quayiociimagesdistributor.MirrorTask{ Source: source, diff --git a/cmd/ci-operator-checkconfig/main.go b/cmd/ci-operator-checkconfig/main.go index 11c5874cecb..288decd257c 100644 --- a/cmd/ci-operator-checkconfig/main.go +++ b/cmd/ci-operator-checkconfig/main.go @@ -46,7 +46,7 @@ func (o *options) parse() error { fs.StringVar(®istryDir, "registry", "", "Path to the step registry directory") fs.StringVar(&profilesConfigPath, "cluster-profiles-config", "", "Path to the cluster profile config file") fs.StringVar(&clusterClaimConfigPath, "cluster-claim-owners-config", "", "Path to the cluster claim owners config file") - o.Options.Bind(fs) + o.Bind(fs) if err := fs.Parse(os.Args[1:]); err != nil { return fmt.Errorf("failed to parse flags: %w", err) @@ -74,10 +74,10 @@ func (o *options) parse() error { } o.ciOPConfigAgent = ciOPConfigAgent - if err := o.Options.Validate(); err != nil { + if err := o.Validate(); err != nil { return fmt.Errorf("failed to validate config options: %w", err) } - if err := o.Options.Complete(); err != nil { + if err := o.Complete(); err != nil { return fmt.Errorf("failed to complete config options: %w", err) } return nil diff --git a/cmd/ci-operator-prowgen/main.go b/cmd/ci-operator-prowgen/main.go index eea7e38fe91..c1e1a305f4c 100644 --- a/cmd/ci-operator-prowgen/main.go +++ b/cmd/ci-operator-prowgen/main.go @@ -54,7 +54,7 @@ func bindOptions(flag *flag.FlagSet) *options { flag.Var(&opt.knownInfraJobFiles, "known-infra-file", "Name of a known infra-file that will not be acted on. Can be passed multiple times.") - opt.Options.Bind(flag) + opt.Bind(flag) return opt } diff --git a/cmd/ci-operator-yaml-creator/main.go b/cmd/ci-operator-yaml-creator/main.go index d7630c6d53e..a0bc018a6db 100644 --- a/cmd/ci-operator-yaml-creator/main.go +++ b/cmd/ci-operator-yaml-creator/main.go @@ -151,7 +151,7 @@ func process( if !filter(metadata) { return nil } - if cfg.BuildRootImage == nil || cfg.BuildRootImage.FromRepository || metadata.Variant != "" || (metadata.Metadata.Branch != "master" && metadata.Metadata.Branch != "main") { + if cfg.BuildRootImage == nil || cfg.BuildRootImage.FromRepository || metadata.Variant != "" || (metadata.Branch != "master" && metadata.Branch != "main") { return nil } diff --git a/cmd/ci-operator/main.go b/cmd/ci-operator/main.go index de0b70f3d65..d376c4475cb 100644 --- a/cmd/ci-operator/main.go +++ b/cmd/ci-operator/main.go @@ -1230,7 +1230,7 @@ func (o *options) resolveInputs(steps []api.Step) error { if len(o.namespace) == 0 { o.namespace = "ci-op-{id}" } - o.namespace = strings.Replace(o.namespace, "{id}", o.inputHash, -1) + o.namespace = strings.ReplaceAll(o.namespace, "{id}", o.inputHash) // TODO: instead of mutating this here, we should pass the parts of graph execution that are resolved // after the graph is created but before it is run down into the run step. o.jobSpec.SetNamespace(o.namespace) @@ -1368,7 +1368,7 @@ func (o *options) initializeNamespace() error { continue } } - ns.ObjectMeta.Annotations[key] = value + ns.Annotations[key] = value } updateErr := client.Update(ctx, ns) @@ -2094,9 +2094,9 @@ func validateSteps(nodes api.OrderedStepList) []error { for _, n := range nodes { if err := n.Step.Validate(); err != nil { errs = append(errs, fmt.Errorf("step %q failed validation: %w", n.Step.Name(), err)) - if errors.Is(err, steps.NoLeaseClientErr) { + if errors.Is(err, steps.ErrNoLeaseClient) { errs = append(errs, errors.New("a lease client was required but none was provided, add the --lease-... arguments")) - } else if errors.Is(err, steps.NoHiveClientErr) { + } else if errors.Is(err, steps.ErrNoHiveClient) { errs = append(errs, errors.New("a Hive client was required but none was provided, add the --hive-kubeconfig argument")) } } @@ -2163,13 +2163,14 @@ func getCloneSecretFromPath(cloneAuthType steps.CloneAuthType, secretPath string hash := getHashFromBytes(data) data = bytes.TrimSpace(data) - if cloneAuthType == steps.CloneAuthTypeSSH { + switch cloneAuthType { + case steps.CloneAuthTypeSSH: secret.Name = fmt.Sprintf("ssh-%s", hash) secret.Type = coreapi.SecretTypeSSHAuth // Secret.Data["ssh-privatekey"] is required on SecretTypeSSHAuth type. // https://github.com/kubernetes/api/blob/master/core/v1/types.go#L5466-L5470 secret.Data[coreapi.SSHAuthPrivateKey] = data - } else if cloneAuthType == steps.CloneAuthTypeOAuth { + case steps.CloneAuthTypeOAuth: secret.Type = coreapi.SecretTypeBasicAuth secret.Name = fmt.Sprintf("oauth-%s", hash) secret.Data[steps.OauthSecretKey] = data diff --git a/cmd/ci-secret-bootstrap/main.go b/cmd/ci-secret-bootstrap/main.go index cf4177ad0b4..d9f62c09f34 100644 --- a/cmd/ci-secret-bootstrap/main.go +++ b/cmd/ci-secret-bootstrap/main.go @@ -224,7 +224,7 @@ func (o *options) validateCompletedOptions() error { } if itemContext.Item != "" && len(itemContext.DockerConfigJSONData) > 0 { - return fmt.Errorf("config[%d].from[%s]: both bitwarden dockerconfigJSON items are not allowed.", i, key) + return fmt.Errorf("config[%d].from[%s]: both bitwarden dockerconfigJSON items are not allowed", i, key) } if len(itemContext.DockerConfigJSONData) > 0 { diff --git a/cmd/cluster-init/cmd/onboard/config/generate.go b/cmd/cluster-init/cmd/onboard/config/generate.go index bac23cd41b8..9739a488639 100644 --- a/cmd/cluster-init/cmd/onboard/config/generate.go +++ b/cmd/cluster-init/cmd/onboard/config/generate.go @@ -45,7 +45,7 @@ func generateConfig(ctx context.Context, log *logrus.Entry, opts generateConfigO log = log.WithField("stage", "onboard config") clusterInstall, err := clusterinstall.Load(opts.ClusterInstall, clusterinstall.FinalizeOption(clusterinstall.FinalizeOptions{ - InstallBase: opts.Options.InstallBase, + InstallBase: opts.InstallBase, ReleaseRepo: opts.releaseRepo, })) if err != nil { diff --git a/cmd/cluster-init/cmd/onboard/config/update.go b/cmd/cluster-init/cmd/onboard/config/update.go index 7fc9d036f39..ad8e2bd277d 100644 --- a/cmd/cluster-init/cmd/onboard/config/update.go +++ b/cmd/cluster-init/cmd/onboard/config/update.go @@ -44,8 +44,8 @@ func newUpdateCmd(log *logrus.Entry) (*cobra.Command, error) { } stdFs := flag.NewFlagSet(os.Args[0], flag.ExitOnError) - opts.KubernetesOptions.NOInClusterConfigDefault = true - opts.KubernetesOptions.AddFlags(stdFs) + opts.NOInClusterConfigDefault = true + opts.AddFlags(stdFs) pf := cmd.PersistentFlags() pf.StringVar(&opts.releaseRepo, "release-repo", "", "Path to openshift/release.") if err := cmd.MarkPersistentFlagRequired("release-repo"); err != nil { @@ -58,7 +58,7 @@ func newUpdateCmd(log *logrus.Entry) (*cobra.Command, error) { } func updateConfig(ctx context.Context, log *logrus.Entry, opts *updateConfigOptions) error { - kubeconfigs, err := opts.KubernetesOptions.LoadClusterConfigs() + kubeconfigs, err := opts.LoadClusterConfigs() if err != nil { return fmt.Errorf("load kubeconfigs: %w", err) } diff --git a/cmd/clusterimageset-updater/main.go b/cmd/clusterimageset-updater/main.go index b653473819a..34f3e4a29da 100644 --- a/cmd/clusterimageset-updater/main.go +++ b/cmd/clusterimageset-updater/main.go @@ -113,7 +113,7 @@ func main() { } bounds, err := labelsToBounds(pool.Labels) if err != nil { - return fmt.Errorf("Pool %s: %w", pool.Name, err) + return fmt.Errorf("pool %s: %w", pool.Name, err) } if bounds != nil { poolFilesByBounds[*bounds] = append(poolFilesByBounds[*bounds], path) @@ -158,7 +158,7 @@ func main() { } bounds, err := labelsToBounds(imageset.Annotations) if err != nil { - return fmt.Errorf("Failed to parse version labels for clusterimageset %s: %w", imageset.Name, err) + return fmt.Errorf("failed to parse version labels for clusterimageset %s: %w", imageset.Name, err) } if bounds != nil { isCurrent := false @@ -201,22 +201,22 @@ func main() { }, } if bounds.Stream != "" { - clusterimageset.ObjectMeta.Annotations[versionStreamLabel] = bounds.Stream + clusterimageset.Annotations[versionStreamLabel] = bounds.Stream } raw, err := yaml.Marshal(clusterimageset) if err != nil { - errs = append(errs, fmt.Errorf("Could not marshal yaml for clusterimageset %s: %w", name, err)) + errs = append(errs, fmt.Errorf("could not marshal yaml for clusterimageset %s: %w", name, err)) continue } if err := os.WriteFile(filepath.Join(o.outputDir, fmt.Sprintf("%s_clusterimageset.yaml", name)), raw, 0644); err != nil { - errs = append(errs, fmt.Errorf("Failed to write file for clusterimageset %s: %w", name, err)) + errs = append(errs, fmt.Errorf("failed to write file for clusterimageset %s: %w", name, err)) } } // delete old clusterimagesets for _, path := range toDelete { if err := os.Remove(path); err != nil && !os.IsNotExist(err) { - errs = append(errs, fmt.Errorf("Failed to delete file %s: %w", path, err)) + errs = append(errs, fmt.Errorf("failed to delete file %s: %w", path, err)) } } @@ -226,22 +226,22 @@ func main() { for _, path := range files { raw, err := os.ReadFile(path) if err != nil { - errs = append(errs, fmt.Errorf("Failed to read file %s: %w", path, err)) + errs = append(errs, fmt.Errorf("failed to read file %s: %w", path, err)) continue } var newClusterPool hivev1.ClusterPool if err := yaml.Unmarshal(raw, &newClusterPool); err != nil { - errs = append(errs, fmt.Errorf("Failed to unmarshal clusterpool %s: %w", path, err)) + errs = append(errs, fmt.Errorf("failed to unmarshal clusterpool %s: %w", path, err)) continue } newClusterPool.Spec.ImageSetRef.Name = imagesetName newRaw, err := yaml.Marshal(newClusterPool) if err != nil { - errs = append(errs, fmt.Errorf("Failed to remarshal clusterpool %s: %w", path, err)) + errs = append(errs, fmt.Errorf("failed to remarshal clusterpool %s: %w", path, err)) continue } if err := os.WriteFile(path, newRaw, 0644); err != nil { - errs = append(errs, fmt.Errorf("Failed to write updated file %s: %w", path, err)) + errs = append(errs, fmt.Errorf("failed to write updated file %s: %w", path, err)) } } } diff --git a/cmd/config-brancher/main.go b/cmd/config-brancher/main.go index 7c4e4bcb55a..a2af3cfafda 100644 --- a/cmd/config-brancher/main.go +++ b/cmd/config-brancher/main.go @@ -144,7 +144,7 @@ func generateBranchedConfigs(currentRelease, bumpRelease string, futureReleases futureConfig.Metadata.Branch = futureBranch logrus.Info(currentRelease) if skipPeriodics && - !(futureConfig.Metadata.Branch == fmt.Sprintf("openshift-%s", currentRelease) || futureConfig.Metadata.Branch == fmt.Sprintf("release-%s", currentRelease)) { + futureConfig.Metadata.Branch != fmt.Sprintf("openshift-%s", currentRelease) && futureConfig.Metadata.Branch != fmt.Sprintf("release-%s", currentRelease) { removePeriodics(&futureConfig.Tests) } @@ -226,20 +226,20 @@ func updateRelease(config *api.ReleaseBuildConfiguration, currentRelease, future // updateImages updates the release that is used for input images // if it matches the release we are updating from func updateImages(config *api.ReleaseBuildConfiguration, currentRelease, futureRelease string) { - for name := range config.InputConfiguration.BaseImages { - image := config.InputConfiguration.BaseImages[name] + for name := range config.BaseImages { + image := config.BaseImages[name] if api.RefersToOfficialImage(image.Namespace, api.WithOKD) && strings.Contains(image.Name, currentRelease) { bumpCurrentToFuture(&image.Name, currentRelease, futureRelease) } - config.InputConfiguration.BaseImages[name] = image + config.BaseImages[name] = image } - for i := range config.InputConfiguration.BaseRPMImages { - image := config.InputConfiguration.BaseRPMImages[i] + for i := range config.BaseRPMImages { + image := config.BaseRPMImages[i] if api.RefersToOfficialImage(image.Namespace, api.WithOKD) && strings.Contains(image.Name, currentRelease) { bumpCurrentToFuture(&image.Name, currentRelease, futureRelease) } - config.InputConfiguration.BaseRPMImages[i] = image + config.BaseRPMImages[i] = image } if config.InputConfiguration.BuildRootImage != nil { diff --git a/cmd/cvp-trigger/main_test.go b/cmd/cvp-trigger/main_test.go index fa40a687b80..1229d587a77 100644 --- a/cmd/cvp-trigger/main_test.go +++ b/cmd/cvp-trigger/main_test.go @@ -15,7 +15,6 @@ import ( k8sv1 "k8s.io/api/core/v1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" pjapi "sigs.k8s.io/prow/pkg/apis/prowjobs/v1" - "sigs.k8s.io/prow/pkg/config" prowconfig "sigs.k8s.io/prow/pkg/config" configflagutil "sigs.k8s.io/prow/pkg/flagutil/config" ) @@ -54,7 +53,7 @@ func Test_getProwjob(t *testing.T) { args: args{ jobName: "foo", config: &prowconfig.Config{ - JobConfig: config.JobConfig{ + JobConfig: prowconfig.JobConfig{ Presets: nil, PresubmitsStatic: nil, PostsubmitsStatic: nil, @@ -82,7 +81,7 @@ func Test_getProwjob(t *testing.T) { args: args{ jobName: "foo", config: &prowconfig.Config{ - JobConfig: config.JobConfig{ + JobConfig: prowconfig.JobConfig{ Presets: nil, PresubmitsStatic: nil, PostsubmitsStatic: nil, @@ -110,7 +109,7 @@ func Test_getProwjob(t *testing.T) { args: args{ jobName: "bar", config: &prowconfig.Config{ - JobConfig: config.JobConfig{ + JobConfig: prowconfig.JobConfig{ Presets: nil, PresubmitsStatic: nil, PostsubmitsStatic: nil, @@ -616,7 +615,7 @@ func Test_getJobArtifactsURL(t *testing.T) { prowConfig := &prowconfig.Config{ JobConfig: prowconfig.JobConfig{}, ProwConfig: prowconfig.ProwConfig{ - Plank: config.Plank{ + Plank: prowconfig.Plank{ Controller: prowconfig.Controller{}, DefaultDecorationConfigsMap: map[string]*pjapi.DecorationConfig{ fmt.Sprintf("%s/%s", org, repo): {GCSConfiguration: &pjapi.GCSConfiguration{Bucket: bucket}}, @@ -627,7 +626,7 @@ func Test_getJobArtifactsURL(t *testing.T) { }, }, } - if err := prowConfig.ProwConfig.Plank.FinalizeDefaultDecorationConfigs(); err != nil { + if err := prowConfig.Plank.FinalizeDefaultDecorationConfigs(); err != nil { t.Fatalf("could not finalize config: %v", err) } type args struct { diff --git a/cmd/determinize-ci-operator/main.go b/cmd/determinize-ci-operator/main.go index aff67e8e6cc..69321b96868 100644 --- a/cmd/determinize-ci-operator/main.go +++ b/cmd/determinize-ci-operator/main.go @@ -35,7 +35,7 @@ type options struct { func (o options) validate() error { var errs []error - if err := o.ConfirmableOptions.Validate(); err != nil { + if err := o.Validate(); err != nil { errs = append(errs, err) } if diff := sets.New[string](o.enabledTemplateMigrations.Strings()...).Difference(validTemplateMigrations); len(diff) != 0 { @@ -64,7 +64,7 @@ func main() { logrus.Fatalf("Invalid options: %v", err) } - if err := o.ConfirmableOptions.Complete(); err != nil { + if err := o.Complete(); err != nil { logrus.Fatalf("Couldn't complete the config options: %v", err) } diff --git a/cmd/generate-registry-metadata/main.go b/cmd/generate-registry-metadata/main.go index 38638ae7be5..6d793e5bc0f 100644 --- a/cmd/generate-registry-metadata/main.go +++ b/cmd/generate-registry-metadata/main.go @@ -82,7 +82,7 @@ func generateMetadata(registryPath string) (api.RegistryMetadata, error) { return nil }) if err := utilerrors.NewAggregate(append(errs, err)); err != nil { - return api.RegistryMetadata{}, fmt.Errorf("Failed to update registry metadata: %w", err) + return api.RegistryMetadata{}, fmt.Errorf("failed to update registry metadata: %w", err) } return metadata, nil } @@ -92,10 +92,10 @@ func writeMetadata(registryPath string, metadata api.RegistryMetadata) error { metadataPath := filepath.Join(registryPath, filepath.Dir(data.Path), fmt.Sprintf("%s%s", strings.TrimSuffix(filename, ".yaml"), load.MetadataSuffix)) output, err := json.MarshalIndent(data, "", "\t") if err != nil { - return fmt.Errorf("Failed to marshal metadata file `%s`: %w", metadataPath, err) + return fmt.Errorf("failed to marshal metadata file `%s`: %w", metadataPath, err) } if err := os.WriteFile(metadataPath, output, 0644); err != nil { - return fmt.Errorf("Failed to write metadata file `%s`: %w", metadataPath, err) + return fmt.Errorf("failed to write metadata file `%s`: %w", metadataPath, err) } } return nil diff --git a/cmd/job-trigger-controller-manager/main.go b/cmd/job-trigger-controller-manager/main.go index d091accf3b5..b0117e18bfa 100644 --- a/cmd/job-trigger-controller-manager/main.go +++ b/cmd/job-trigger-controller-manager/main.go @@ -41,7 +41,7 @@ func gatherOptions() (*options, error) { o := &options{} fs := flag.NewFlagSet(os.Args[0], flag.ExitOnError) - o.ConfigOptions.AddFlags(fs) + o.AddFlags(fs) fs.BoolVar(&o.dryRun, "dry-run", true, "Whether to run the controller-manager with dry-run") fs.StringVar(&o.namespace, "namespace", "ci", "In which namespace the operation will take place") fs.Int64Var(&o.jobTriggerWaitInSeconds, "job-trigger-wait-seconds", 20, "Amount of seconds to wait for job to trigger in order to update status") @@ -72,7 +72,7 @@ func main() { logrus.WithError(err).Fatal("Invalid options") } - agent, err := o.ConfigOptions.ConfigAgent() + agent, err := o.ConfigAgent() if err != nil { logrus.WithError(err).Fatal("could not load Prow configuration") } diff --git a/cmd/lensserver/main.go b/cmd/lensserver/main.go index 57b63130274..e5da52aa459 100644 --- a/cmd/lensserver/main.go +++ b/cmd/lensserver/main.go @@ -10,7 +10,6 @@ import ( ctrlruntimeclient "sigs.k8s.io/controller-runtime/pkg/client" prowapi "sigs.k8s.io/prow/pkg/apis/prowjobs/v1" "sigs.k8s.io/prow/pkg/deck/jobs" - "sigs.k8s.io/prow/pkg/flagutil" prowflagutil "sigs.k8s.io/prow/pkg/flagutil" configflagutil "sigs.k8s.io/prow/pkg/flagutil/config" "sigs.k8s.io/prow/pkg/interrupts" @@ -32,7 +31,7 @@ func gatherOptions() options { o := options{} fs := flag.CommandLine - for _, group := range []flagutil.OptionGroup{&o.storage, &o.config} { + for _, group := range []prowflagutil.OptionGroup{&o.storage, &o.config} { group.AddFlags(fs) } flag.Parse() diff --git a/cmd/multi-pr-prow-plugin/main.go b/cmd/multi-pr-prow-plugin/main.go index 7b79ca05f4f..88abcb79bc4 100644 --- a/cmd/multi-pr-prow-plugin/main.go +++ b/cmd/multi-pr-prow-plugin/main.go @@ -50,7 +50,7 @@ func gatherOptions() options { fs.StringVar(&o.logLevel, "log-level", "info", "Level at which to log output.") fs.StringVar(&o.webhookSecretFile, "hmac-secret-file", "/etc/webhook/hmac", "Path to the file containing the GitHub HMAC secret.") - o.ConfigOptions.AddFlags(fs) + o.AddFlags(fs) o.github.AddFlags(fs) o.githubEventServerOptions.Bind(fs) o.kubernetesOptions.AddFlags(fs) @@ -129,7 +129,7 @@ func main() { logger.WithError(err).Fatal("Error getting kube client.") } - agent, err := o.ConfigOptions.ConfigAgent() + agent, err := o.ConfigAgent() if err != nil { logrus.WithError(err).Fatal("could not load Prow configuration") } diff --git a/cmd/multi-pr-prow-plugin/report.go b/cmd/multi-pr-prow-plugin/report.go index 204a357a614..b95dec07dad 100644 --- a/cmd/multi-pr-prow-plugin/report.go +++ b/cmd/multi-pr-prow-plugin/report.go @@ -73,7 +73,7 @@ type CheckRunDetails struct { } func (r *reporter) reportNewProwJob(prowJob *prowv1.ProwJob, jr jobRun, logger *logrus.Entry) error { - key := ctrlruntimeclient.ObjectKey{Namespace: r.namespace, Name: prowJob.ObjectMeta.Name} + key := ctrlruntimeclient.ObjectKey{Namespace: r.namespace, Name: prowJob.Name} created := &prowv1.ProwJob{} if err := wait.PollUntilContextTimeout(context.Background(), time.Second*5, time.Second*60, true, func(ctx context.Context) (bool, error) { if err := r.kubeClient.Get(context.Background(), key, created); err != nil { @@ -178,12 +178,12 @@ func (r *reporter) sync(logger *logrus.Entry) error { checkRun := github.CheckRun{ Conclusion: stateToConclusion[prowJob.Status.State], Output: github.CheckRunOutput{ - Title: job.CheckRunDetails.Title, + Title: job.Title, Summary: "Job Finished", - Text: job.CheckRunDetails.Text, + Text: job.Text, }, } - if err := r.ghc.UpdateCheckRun(job.Org, job.Repo, job.CheckRunDetails.ID, checkRun); err != nil { + if err := r.ghc.UpdateCheckRun(job.Org, job.Repo, job.ID, checkRun); err != nil { jobLogger.WithError(err).Error("could not update check run") errs = append(errs, err) } diff --git a/cmd/multi-pr-prow-plugin/server.go b/cmd/multi-pr-prow-plugin/server.go index 9d62c12ac4a..e4595ef6149 100644 --- a/cmd/multi-pr-prow-plugin/server.go +++ b/cmd/multi-pr-prow-plugin/server.go @@ -210,7 +210,7 @@ func (s *server) handle(l *logrus.Entry, ic github.IssueCommentEvent) ([]*prowv1 s.reportFailure("could not generate prow job", err, org, repo, user, number, l) continue } - logrus.Infof("submitting prowjob: %s", prowJob.ObjectMeta.Name) + logrus.Infof("submitting prowjob: %s", prowJob.Name) if err = s.kubeClient.Create(context.Background(), prowJob); err != nil { l.WithError(err).Error("could not create prow job") s.reportFailure("could not submit prow job", nil, org, repo, user, number, l) @@ -376,7 +376,7 @@ func (s *server) generateProwJob(jr jobRun) (*prowv1.ProwJob, error) { } } if primaryRef == nil { - return nil, fmt.Errorf("No ref for requested test included in command. The org, repo, and branch containing the requested test need to be targeted by at least one of the included PRs.") + return nil, fmt.Errorf("no ref for requested test included in command. The org, repo, and branch containing the requested test need to be targeted by at least one of the included PRs") } if err := s.prowConfigGetter.Defaulter().DefaultPeriodic(periodic); err != nil { @@ -395,8 +395,8 @@ func (s *server) generateProwJob(jr jobRun) (*prowv1.ProwJob, error) { } func (s *server) clusterForJob(jobName string) (string, error) { - if time.Now().Add(time.Minute * -15).After(s.jobClusterCache.lastCleared) { - s.jobClusterCache.lastCleared = time.Now() + if time.Now().Add(time.Minute * -15).After(s.lastCleared) { + s.lastCleared = time.Now() s.jobClusterCache.clusterForJob = make(map[string]string) } if cluster, ok := s.jobClusterCache.clusterForJob[jobName]; ok { diff --git a/cmd/ocp-build-data-enforcer/main.go b/cmd/ocp-build-data-enforcer/main.go index d67c9dd50b3..482319b963e 100644 --- a/cmd/ocp-build-data-enforcer/main.go +++ b/cmd/ocp-build-data-enforcer/main.go @@ -278,7 +278,7 @@ func (dp *diffProcessor) process() error { dp.maxPRs-- gitClient, err := dp.gitClient.ClientFor(d.org, d.repo) if err != nil { - return fmt.Errorf("Failed to get git client: %w", err) + return fmt.Errorf("failed to get git client: %w", err) } defer func() { if err := gitClient.Clean(); err != nil { diff --git a/cmd/payload-testing-prow-plugin/server.go b/cmd/payload-testing-prow-plugin/server.go index d54f595fdf0..49503616c56 100644 --- a/cmd/payload-testing-prow-plugin/server.go +++ b/cmd/payload-testing-prow-plugin/server.go @@ -443,9 +443,9 @@ func (s *server) handle(l *logrus.Entry, ic github.IssueCommentEvent) (string, [ jobNames = append(jobNames, job.Name) releaseJobSpecs = append(releaseJobSpecs, prpqv1.ReleaseJobSpec{ CIOperatorConfig: prpqv1.CIOperatorMetadata{ - Org: job.Metadata.Org, - Repo: job.Metadata.Repo, - Branch: job.Metadata.Branch, + Org: job.Org, + Repo: job.Repo, + Branch: job.Branch, Variant: job.Metadata.Variant, }, Test: job.Test, diff --git a/cmd/payload-testing-ui/server.go b/cmd/payload-testing-ui/server.go index 5689e3620de..d0a23b7a34f 100644 --- a/cmd/payload-testing-ui/server.go +++ b/cmd/payload-testing-ui/server.go @@ -284,7 +284,7 @@ func (s *server) runDetails(w http.ResponseWriter, r *http.Request) { } return } - title := fmt.Sprintf(runTitle, run.ObjectMeta.Name) + title := fmt.Sprintf(runTitle, run.Name) status := make([]*prpqv1.PullRequestPayloadJobStatus, 0, len(run.Spec.Jobs.Jobs)) for _, j := range run.Spec.Jobs.Jobs { name := j.JobName(jobconfig.PeriodicPrefix) diff --git a/cmd/pipeline-controller/config_data_provider_test.go b/cmd/pipeline-controller/config_data_provider_test.go index 40407ceb55f..eac2e236918 100644 --- a/cmd/pipeline-controller/config_data_provider_test.go +++ b/cmd/pipeline-controller/config_data_provider_test.go @@ -42,7 +42,7 @@ func composeBPConfig() config.ProwConfig { func decorateWithOrgPolicy(cfg config.ProwConfig) config.ProwConfig { if org, ok := cfg.BranchProtection.Orgs["org"]; ok { - org.Policy.RequireManuallyTriggeredJobs = yes() + org.RequireManuallyTriggeredJobs = yes() cfg.BranchProtection.Orgs["org"] = org } @@ -52,7 +52,7 @@ func decorateWithOrgPolicy(cfg config.ProwConfig) config.ProwConfig { func decorateWithRepoPolicy(cfg config.ProwConfig) config.ProwConfig { if org, ok := cfg.BranchProtection.Orgs["org"]; ok { if repo, ok := org.Repos["repo"]; ok { - repo.Policy.RequireManuallyTriggeredJobs = yes() + repo.RequireManuallyTriggeredJobs = yes() cfg.BranchProtection.Orgs["org"].Repos["repo"] = repo } } diff --git a/cmd/pipeline-controller/reconciler.go b/cmd/pipeline-controller/reconciler.go index 072620eeeec..c20d0407a69 100644 --- a/cmd/pipeline-controller/reconciler.go +++ b/cmd/pipeline-controller/reconciler.go @@ -188,7 +188,7 @@ func (r *reconciler) reportSuccessOnPR(ctx context.Context, pj *v1.ProwJob, pres } selector := map[string]string{} for _, l := range []string{kube.OrgLabel, kube.RepoLabel, kube.PullLabel, kube.BaseRefLabel} { - selector[l] = pj.ObjectMeta.Labels[l] + selector[l] = pj.Labels[l] } var pjs v1.ProwJobList if err := r.lister.List(ctx, &pjs, ctrlruntimeclient.MatchingLabels(selector)); err != nil { diff --git a/cmd/pj-rehearse/server.go b/cmd/pj-rehearse/server.go index 10a2e4940c4..3a0b5f48d99 100644 --- a/cmd/pj-rehearse/server.go +++ b/cmd/pj-rehearse/server.go @@ -404,9 +404,10 @@ func (s *server) handlePotentialCommands(pullRequest *github.PullRequest, commen allowedLabel := false approved := false for _, label := range pullRequest.Labels { - if label.Name == rehearse.NetworkAccessRehearsalsOkLabel { + switch label.Name { + case rehearse.NetworkAccessRehearsalsOkLabel: allowedLabel = true - } else if label.Name == labels.Approved { + case labels.Approved: approved = true } } @@ -435,11 +436,12 @@ func (s *server) handlePotentialCommands(pullRequest *github.PullRequest, commen } if len(presubmits) > 0 || len(periodics) > 0 { limit := math.MaxInt - if command == rehearseNormal || command == rehearseAutoAck { + switch command { + case rehearseNormal, rehearseAutoAck: limit = rc.NormalLimit - } else if command == rehearseMore { + case rehearseMore: limit = rc.MoreLimit - } else if command == rehearseMax { + case rehearseMax: limit = rc.MaxLimit } diff --git a/cmd/pod-scaler/frontend.go b/cmd/pod-scaler/frontend.go index 977bedceffb..90650014603 100644 --- a/cmd/pod-scaler/frontend.go +++ b/cmd/pod-scaler/frontend.go @@ -3,7 +3,6 @@ package main import ( "crypto/sha256" "embed" - _ "embed" "encoding/base32" "encoding/json" "fmt" diff --git a/cmd/pod-scaler/main.go b/cmd/pod-scaler/main.go index 03f7758a5d8..e3b2e8e0f73 100644 --- a/cmd/pod-scaler/main.go +++ b/cmd/pod-scaler/main.go @@ -73,7 +73,7 @@ func bindOptions(fs *flag.FlagSet) *options { o := options{producerOptions: producerOptions{kubernetesOptions: prowflagutil.KubernetesOptions{NOInClusterConfigDefault: true}}} o.instrumentationOptions.AddFlags(fs) fs.StringVar(&o.mode, "mode", "", "Which mode to run in.") - o.producerOptions.kubernetesOptions.AddFlags(fs) + o.kubernetesOptions.AddFlags(fs) fs.DurationVar(&o.ignoreLatest, "ignore-latest", 0, "Duration of latest time series to ignore when querying Prometheus. For instance, 1h will ignore the latest hour of data.") fs.BoolVar(&o.once, "produce-once", false, "Query Prometheus and refresh cached data only once before exiting.") fs.IntVar(&o.port, "port", 0, "Port to serve admission webhooks on.") diff --git a/cmd/pod-scaler/producer.go b/cmd/pod-scaler/producer.go index 786ce43972e..256a3b6bff7 100644 --- a/cmd/pod-scaler/producer.go +++ b/cmd/pod-scaler/producer.go @@ -261,10 +261,7 @@ func divideRange(uncovered []podscaler.TimeRange, step time.Duration, numSteps i // so we take each uncovered range and split it into chunks we can ask for. start := uncoveredRange.Start stop := uncoveredRange.End - for { - if start.After(uncoveredRange.End) { - break - } + for !start.After(uncoveredRange.End) { steps := int64(stop.Sub(start) / step) if steps <= 1 { // this range is likely too small to contain novel data and asking for this in a query leads diff --git a/cmd/pr-reminder/main.go b/cmd/pr-reminder/main.go index bbeaf910c5a..b0c3494492d 100644 --- a/cmd/pr-reminder/main.go +++ b/cmd/pr-reminder/main.go @@ -434,7 +434,7 @@ func findPRs(users map[string]user, channels map[string][]repoChannel, ghClient org, repo := split[0], split[1] for _, pr := range repoToPRs[cfg.orgRepo] { - if isUnreviewed(org, repo, pr, ghClient) && !hasUnactionableLabels(pr.Labels) && !(cfg.omitBots && pr.User.Type == github.UserTypeBot) { + if isUnreviewed(org, repo, pr, ghClient) && !hasUnactionableLabels(pr.Labels) && (!cfg.omitBots || pr.User.Type != github.UserTypeBot) { if _, recorded := channelToPRs[channel]; !recorded { channelToPRs[channel] = []prRequest{} } diff --git a/cmd/prcreator/main.go b/cmd/prcreator/main.go index 07feaef4bd2..92759d70d37 100644 --- a/cmd/prcreator/main.go +++ b/cmd/prcreator/main.go @@ -24,7 +24,7 @@ type options struct { func gatherOptions() (*options, error) { opts := options{} - opts.PRCreationOptions.AddFlags(flag.CommandLine) + opts.AddFlags(flag.CommandLine) flag.StringVar(&opts.prTitle, "pr-title", "", "The title of the PR to create") flag.StringVar(&opts.prMessage, "pr-message", "", "The message of the PR to create") flag.StringVar(&opts.gitCommitMessage, "git-message", "", "The git commit message of the PR to create. If not set, then its value will be composed of other flags") @@ -48,7 +48,7 @@ func gatherOptions() (*options, error) { errs = append(errs, errors.New("--branch is mandatory")) } - if err := opts.PRCreationOptions.Finalize(); err != nil { + if err := opts.Finalize(); err != nil { errs = append(errs, err) } @@ -61,7 +61,7 @@ func main() { logrus.WithError(err).Fatal("failed to gather options") } - if err := opts.PRCreationOptions.UpsertPR(".", + if err := opts.UpsertPR(".", opts.organization, opts.repo, opts.branch, diff --git a/cmd/private-org-peribolos-sync/main.go b/cmd/private-org-peribolos-sync/main.go index b3b26969120..693c4758639 100644 --- a/cmd/private-org-peribolos-sync/main.go +++ b/cmd/private-org-peribolos-sync/main.go @@ -71,7 +71,7 @@ func gatherOptions() (options, error) { fs.Var(&o.flattenOrgs, "flatten-org", "Organizations whose repos should not have org prefix (can be specified multiple times)") o.github.AddFlags(fs) - o.WhitelistOptions.Bind(fs) + o.Bind(fs) if err := fs.Parse(os.Args[1:]); err != nil { return o, fmt.Errorf("faild to parse flags: %w", err) } @@ -133,7 +133,7 @@ func main() { logger.WithError(err).Fatal("Error getting GitHub client.") } - orgRepos, err := getReposForPrivateOrg(o.releaseRepoPath, o.WhitelistOptions.WhitelistConfig, o.onlyOrg) + orgRepos, err := getReposForPrivateOrg(o.releaseRepoPath, o.WhitelistConfig, o.onlyOrg) if err != nil { logger.WithError(err).Fatal("couldn't get the list of org/repos that promote official images") } diff --git a/cmd/private-org-sync/main.go b/cmd/private-org-sync/main.go index b9e2e7506c5..de7da18253a 100644 --- a/cmd/private-org-sync/main.go +++ b/cmd/private-org-sync/main.go @@ -619,7 +619,7 @@ func main() { var errs []error - locations, whitelistErrors := getWhitelistedLocations(o.WhitelistOptions.WhitelistConfig.Whitelist, syncer.git, o.prefix, token) + locations, whitelistErrors := getWhitelistedLocations(o.WhitelistConfig.Whitelist, syncer.git, o.prefix, token) errs = append(errs, whitelistErrors...) callback := func(_ *api.ReleaseBuildConfiguration, repoInfo *config.Info) error { diff --git a/cmd/private-prow-configs-mirror/main_test.go b/cmd/private-prow-configs-mirror/main_test.go index c01d3deff5f..901cd034ef5 100644 --- a/cmd/private-prow-configs-mirror/main_test.go +++ b/cmd/private-prow-configs-mirror/main_test.go @@ -11,7 +11,6 @@ import ( prowapi "sigs.k8s.io/prow/pkg/apis/prowjobs/v1" prowconfig "sigs.k8s.io/prow/pkg/config" "sigs.k8s.io/prow/pkg/git/types" - "sigs.k8s.io/prow/pkg/plugins" prowplugins "sigs.k8s.io/prow/pkg/plugins" ) @@ -404,12 +403,12 @@ func TestInjectPrivateJobURLPrefixConfig(t *testing.T) { func TestInjectPrivateApprovePlugin(t *testing.T) { testCases := []struct { id string - approves []plugins.Approve - expected []plugins.Approve + approves []prowplugins.Approve + expected []prowplugins.Approve }{ { id: "no changes expected", - approves: []plugins.Approve{ + approves: []prowplugins.Approve{ { IgnoreReviewState: pBool(false), LgtmActsAsApprove: true, @@ -421,7 +420,7 @@ func TestInjectPrivateApprovePlugin(t *testing.T) { Repos: []string{"openshift/anotherRepo3", "testshift/anotherRepo4"}, }, }, - expected: []plugins.Approve{ + expected: []prowplugins.Approve{ { IgnoreReviewState: pBool(false), LgtmActsAsApprove: true, @@ -436,7 +435,7 @@ func TestInjectPrivateApprovePlugin(t *testing.T) { }, { id: "changes expected", - approves: []plugins.Approve{ + approves: []prowplugins.Approve{ { IgnoreReviewState: pBool(false), LgtmActsAsApprove: true, @@ -448,7 +447,7 @@ func TestInjectPrivateApprovePlugin(t *testing.T) { Repos: []string{"openshift/anotherRepo3", "testshift/testRepo3"}, }, }, - expected: []plugins.Approve{ + expected: []prowplugins.Approve{ { IgnoreReviewState: pBool(false), LgtmActsAsApprove: true, @@ -476,12 +475,12 @@ func TestInjectPrivateApprovePlugin(t *testing.T) { func TestInjectPrivateLGTMPlugin(t *testing.T) { testCases := []struct { id string - lgtms []plugins.Lgtm - expected []plugins.Lgtm + lgtms []prowplugins.Lgtm + expected []prowplugins.Lgtm }{ { id: "no changes expected", - lgtms: []plugins.Lgtm{ + lgtms: []prowplugins.Lgtm{ { ReviewActsAsLgtm: true, Repos: []string{"openshift/anotherRepo1", "testshift/anotherRepo2"}, @@ -491,7 +490,7 @@ func TestInjectPrivateLGTMPlugin(t *testing.T) { Repos: []string{"openshift/anotherRepo3", "testshift/anotherRepo4"}, }, }, - expected: []plugins.Lgtm{ + expected: []prowplugins.Lgtm{ { ReviewActsAsLgtm: true, Repos: []string{"openshift/anotherRepo1", "testshift/anotherRepo2"}, @@ -504,7 +503,7 @@ func TestInjectPrivateLGTMPlugin(t *testing.T) { }, { id: "changes expected", - lgtms: []plugins.Lgtm{ + lgtms: []prowplugins.Lgtm{ { ReviewActsAsLgtm: true, Repos: []string{"openshift/testRepo1", "testshift/anotherRepo2"}, @@ -514,7 +513,7 @@ func TestInjectPrivateLGTMPlugin(t *testing.T) { Repos: []string{"openshift/anotherRepo3", "testshift/testRepo3"}, }, }, - expected: []plugins.Lgtm{ + expected: []prowplugins.Lgtm{ { ReviewActsAsLgtm: true, Repos: []string{"openshift-priv/testRepo1", "openshift/testRepo1", "testshift/anotherRepo2"}, @@ -540,48 +539,48 @@ func TestInjectPrivateLGTMPlugin(t *testing.T) { func TestInjectPrivateBugzillaPlugin(t *testing.T) { testCases := []struct { id string - bugzilla plugins.Bugzilla - expected plugins.Bugzilla + bugzilla prowplugins.Bugzilla + expected prowplugins.Bugzilla }{ { id: "no changes expected", - bugzilla: plugins.Bugzilla{ - Orgs: map[string]plugins.BugzillaOrgOptions{ - "openshift": {Repos: map[string]plugins.BugzillaRepoOptions{ - "anotherRepo1": {Branches: map[string]plugins.BugzillaBranchOptions{"master": {ExcludeDefaults: pBool(true)}}}}}, - "testshift": {Repos: map[string]plugins.BugzillaRepoOptions{ - "anotherRepo2": {Branches: map[string]plugins.BugzillaBranchOptions{"master": {ExcludeDefaults: pBool(true)}}}}}, + bugzilla: prowplugins.Bugzilla{ + Orgs: map[string]prowplugins.BugzillaOrgOptions{ + "openshift": {Repos: map[string]prowplugins.BugzillaRepoOptions{ + "anotherRepo1": {Branches: map[string]prowplugins.BugzillaBranchOptions{"master": {ExcludeDefaults: pBool(true)}}}}}, + "testshift": {Repos: map[string]prowplugins.BugzillaRepoOptions{ + "anotherRepo2": {Branches: map[string]prowplugins.BugzillaBranchOptions{"master": {ExcludeDefaults: pBool(true)}}}}}, }, }, - expected: plugins.Bugzilla{ - Orgs: map[string]plugins.BugzillaOrgOptions{ - "openshift": {Repos: map[string]plugins.BugzillaRepoOptions{ - "anotherRepo1": {Branches: map[string]plugins.BugzillaBranchOptions{"master": {ExcludeDefaults: pBool(true)}}}}}, - "testshift": {Repos: map[string]plugins.BugzillaRepoOptions{ - "anotherRepo2": {Branches: map[string]plugins.BugzillaBranchOptions{"master": {ExcludeDefaults: pBool(true)}}}}}, + expected: prowplugins.Bugzilla{ + Orgs: map[string]prowplugins.BugzillaOrgOptions{ + "openshift": {Repos: map[string]prowplugins.BugzillaRepoOptions{ + "anotherRepo1": {Branches: map[string]prowplugins.BugzillaBranchOptions{"master": {ExcludeDefaults: pBool(true)}}}}}, + "testshift": {Repos: map[string]prowplugins.BugzillaRepoOptions{ + "anotherRepo2": {Branches: map[string]prowplugins.BugzillaBranchOptions{"master": {ExcludeDefaults: pBool(true)}}}}}, }, }, }, { id: "changes expected", - bugzilla: plugins.Bugzilla{ - Orgs: map[string]plugins.BugzillaOrgOptions{ - "openshift": {Repos: map[string]plugins.BugzillaRepoOptions{ - "testRepo1": {Branches: map[string]plugins.BugzillaBranchOptions{"master": {ExcludeDefaults: pBool(true)}}}}}, - "testshift": {Repos: map[string]plugins.BugzillaRepoOptions{ - "testRepo3": {Branches: map[string]plugins.BugzillaBranchOptions{"master": {ExcludeDefaults: pBool(true)}}}}}, - }, - }, - expected: plugins.Bugzilla{ - Orgs: map[string]plugins.BugzillaOrgOptions{ - "openshift": {Repos: map[string]plugins.BugzillaRepoOptions{ - "testRepo1": {Branches: map[string]plugins.BugzillaBranchOptions{"master": {ExcludeDefaults: pBool(true)}}}}}, - "testshift": {Repos: map[string]plugins.BugzillaRepoOptions{ - "testRepo3": {Branches: map[string]plugins.BugzillaBranchOptions{"master": {ExcludeDefaults: pBool(true)}}}}}, - "openshift-priv": {Repos: map[string]plugins.BugzillaRepoOptions{ - "testRepo1": {Branches: map[string]plugins.BugzillaBranchOptions{"master": {ExcludeDefaults: pBool(true)}}}, - "testRepo3": {Branches: map[string]plugins.BugzillaBranchOptions{"master": {ExcludeDefaults: pBool(true)}}}}, + bugzilla: prowplugins.Bugzilla{ + Orgs: map[string]prowplugins.BugzillaOrgOptions{ + "openshift": {Repos: map[string]prowplugins.BugzillaRepoOptions{ + "testRepo1": {Branches: map[string]prowplugins.BugzillaBranchOptions{"master": {ExcludeDefaults: pBool(true)}}}}}, + "testshift": {Repos: map[string]prowplugins.BugzillaRepoOptions{ + "testRepo3": {Branches: map[string]prowplugins.BugzillaBranchOptions{"master": {ExcludeDefaults: pBool(true)}}}}}, + }, + }, + expected: prowplugins.Bugzilla{ + Orgs: map[string]prowplugins.BugzillaOrgOptions{ + "openshift": {Repos: map[string]prowplugins.BugzillaRepoOptions{ + "testRepo1": {Branches: map[string]prowplugins.BugzillaBranchOptions{"master": {ExcludeDefaults: pBool(true)}}}}}, + "testshift": {Repos: map[string]prowplugins.BugzillaRepoOptions{ + "testRepo3": {Branches: map[string]prowplugins.BugzillaBranchOptions{"master": {ExcludeDefaults: pBool(true)}}}}}, + "openshift-priv": {Repos: map[string]prowplugins.BugzillaRepoOptions{ + "testRepo1": {Branches: map[string]prowplugins.BugzillaBranchOptions{"master": {ExcludeDefaults: pBool(true)}}}, + "testRepo3": {Branches: map[string]prowplugins.BugzillaBranchOptions{"master": {ExcludeDefaults: pBool(true)}}}}, }, }, }, diff --git a/cmd/prow-job-dispatcher/main.go b/cmd/prow-job-dispatcher/main.go index c30f14f0344..b312b6143b1 100644 --- a/cmd/prow-job-dispatcher/main.go +++ b/cmd/prow-job-dispatcher/main.go @@ -666,14 +666,14 @@ func main() { } } - if o.PrometheusOptions.PrometheusPasswordPath != "" { - if err := secret.Add(o.PrometheusOptions.PrometheusPasswordPath); err != nil { + if o.PrometheusPasswordPath != "" { + if err := secret.Add(o.PrometheusPasswordPath); err != nil { logrus.WithError(err).Fatal("Failed to start secrets agent") } } - if o.PrometheusOptions.PrometheusBearerTokenPath != "" { - if err := secret.Add(o.PrometheusOptions.PrometheusBearerTokenPath); err != nil { + if o.PrometheusBearerTokenPath != "" { + if err := secret.Add(o.PrometheusBearerTokenPath); err != nil { logrus.WithError(err).Fatal("Failed to start secrets agent") } } diff --git a/cmd/publicize/main.go b/cmd/publicize/main.go index 773e19d386d..8272c9b9f61 100644 --- a/cmd/publicize/main.go +++ b/cmd/publicize/main.go @@ -98,11 +98,11 @@ func (o *options) Validate() error { bytes, err := gzip.ReadFileMaybeGZIP(o.configPath) if err != nil { - return fmt.Errorf("Couldn't read publicize configuration file: %v", o.configPath) + return fmt.Errorf("couldn't read publicize configuration file: %v", o.configPath) } if err := yaml.Unmarshal(bytes, &o.config); err != nil { - return fmt.Errorf("Couldn't unmarshal publicize configuration: %w", err) + return fmt.Errorf("couldn't unmarshal publicize configuration: %w", err) } if err := o.config.validate(); err != nil { @@ -127,12 +127,12 @@ func (o *options) getConfigWatchAndUpdate() (func(ctx context.Context), error) { eventFunc := func() error { bytes, err := gzip.ReadFileMaybeGZIP(o.configPath) if err != nil { - return fmt.Errorf("Couldn't read publicize configuration file %s: %w", o.configPath, err) + return fmt.Errorf("couldn't read publicize configuration file %s: %w", o.configPath, err) } var c *Config if err := yaml.Unmarshal(bytes, &c); err != nil { - return fmt.Errorf("Couldn't unmarshal publicize configuration: %w", err) + return fmt.Errorf("couldn't unmarshal publicize configuration: %w", err) } if err := c.validate(); err != nil { diff --git a/cmd/publicize/server.go b/cmd/publicize/server.go index 959aa56b77d..332d58ba95d 100644 --- a/cmd/publicize/server.go +++ b/cmd/publicize/server.go @@ -108,7 +108,7 @@ func (s *server) handleIssueComment(l *logrus.Entry, ic github.IssueCommentEvent func (s *server) checkPrerequisites(logger *logrus.Entry, pr *github.PullRequest, ic github.IssueCommentEvent) error { if !ic.Issue.IsPullRequest() { - return errors.New("Publicize plugin can only be used in pull requests") + return errors.New("publicize plugin can only be used in pull requests") } org := ic.Repo.Owner.Login @@ -175,7 +175,7 @@ func (s *server) mergeAndPushToRemote(sourceOrg, sourceRepo, destOrg, destRepo s } if !merged { - return "", fmt.Errorf("couldn't merge %s/%s, due to merge conflict. You will need to create a new PR in %s/%s which merges/resolves from %s/%s. Once this PR merges, you can then use /publicize there to merge all changes into the the public repository.", destOrg, destRepo, sourceOrg, sourceRepo, destOrg, destRepo) + return "", fmt.Errorf("couldn't merge %s/%s, due to merge conflict. You will need to create a new PR in %s/%s which merges/resolves from %s/%s. Once this PR merges, you can then use /publicize there to merge all changes into the the public repository", destOrg, destRepo, sourceOrg, sourceRepo, destOrg, destRepo) } if !dry { diff --git a/cmd/rebalancer/main.go b/cmd/rebalancer/main.go index ab1650827b0..8533577e6dc 100644 --- a/cmd/rebalancer/main.go +++ b/cmd/rebalancer/main.go @@ -43,19 +43,19 @@ func main() { fs.Var(&o.profiles, "profiles", "Comma-separated list of profiles; may be repeated") fs.IntVar(&o.prometheusDaysBefore, "prometheus-days-before", 14, "Number [1,15] of days before. Time 00-00-00 of that day will be used as time to query Prometheus. E.g., 1 means 00-00-00 of yesterday.") - o.PrometheusOptions.AddFlags(fs) + o.AddFlags(fs) if err := fs.Parse(os.Args[1:]); err != nil { logrus.WithError(err).Fatalf("cannot parse args: '%s'", os.Args[1:]) } - if o.PrometheusOptions.PrometheusPasswordPath != "" { - if err := secret.Add(o.PrometheusOptions.PrometheusPasswordPath); err != nil { + if o.PrometheusPasswordPath != "" { + if err := secret.Add(o.PrometheusPasswordPath); err != nil { logrus.WithError(err).Fatal("Failed to start secrets agent") } } - if o.PrometheusOptions.PrometheusBearerTokenPath != "" { - if err := secret.Add(o.PrometheusOptions.PrometheusBearerTokenPath); err != nil { + if o.PrometheusBearerTokenPath != "" { + if err := secret.Add(o.PrometheusBearerTokenPath); err != nil { logrus.WithError(err).Fatal("Failed to start secrets agent") } } diff --git a/cmd/repo-brancher/main.go b/cmd/repo-brancher/main.go index d66d94c4e76..fd94f1e4776 100644 --- a/cmd/repo-brancher/main.go +++ b/cmd/repo-brancher/main.go @@ -53,7 +53,7 @@ func (o *options) bind(fs *flag.FlagSet) { fs.StringVar(&o.tokenPath, "token-path", "", "Path to token to use when pushing to GitHub.") fs.BoolVar(&o.fastForward, "fast-forward", false, "Attempt to fast-forward future branches if they already exist.") fs.Var(&o.ignore, "ignore", "Ignore a repo or entire org. Format: org or org/repo. Can be passed multiple times.") - o.FutureOptions.Bind(fs) + o.Bind(fs) } func gatherOptions() options { @@ -75,7 +75,7 @@ func (f *censoringFormatter) Format(entry *logrus.Entry) ([]byte, error) { for key, value := range entry.Data { if valueString, ok := value.(string); ok { if strings.Contains(valueString, f.secret) { - entry.Data[key] = strings.Replace(valueString, f.secret, "xxx", -1) + entry.Data[key] = strings.ReplaceAll(valueString, f.secret, "xxx") } } } diff --git a/cmd/repo-init/frontend.go b/cmd/repo-init/frontend.go index aae68a523eb..cd9ecc1783e 100644 --- a/cmd/repo-init/frontend.go +++ b/cmd/repo-init/frontend.go @@ -2,7 +2,6 @@ package main import ( "embed" - _ "embed" "io" "io/fs" "net/http" diff --git a/cmd/result-aggregator/main.go b/cmd/result-aggregator/main.go index db1a0933d61..06732832624 100644 --- a/cmd/result-aggregator/main.go +++ b/cmd/result-aggregator/main.go @@ -12,7 +12,6 @@ import ( "time" "github.com/prometheus/client_golang/prometheus" - "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus" prowConfig "sigs.k8s.io/prow/pkg/config" @@ -215,7 +214,7 @@ func handlePodScalerResult() http.HandlerFunc { func main() { o, err := gatherOptions() if err != nil { - logrus.WithError(err).Fatal("failed to gather options") + log.WithError(err).Fatal("failed to gather options") } if err := validateOptions(o); err != nil { log.Fatalf("invalid options: %v", err) diff --git a/cmd/retester/main.go b/cmd/retester/main.go index cf4491fa1bf..06814a65fa3 100644 --- a/cmd/retester/main.go +++ b/cmd/retester/main.go @@ -12,7 +12,6 @@ import ( "github.com/sirupsen/logrus" prowConfig "sigs.k8s.io/prow/pkg/config" - "sigs.k8s.io/prow/pkg/flagutil" prowflagutil "sigs.k8s.io/prow/pkg/flagutil" configflagutil "sigs.k8s.io/prow/pkg/flagutil/config" "sigs.k8s.io/prow/pkg/interrupts" @@ -41,7 +40,7 @@ type options struct { } func (o *options) Validate() error { - for _, group := range []flagutil.OptionGroup{&o.github, &o.config} { + for _, group := range []prowflagutil.OptionGroup{&o.github, &o.config} { if err := group.Validate(o.dryRun); err != nil { return err } @@ -80,7 +79,7 @@ func gatherOptions() options { fs.StringVar(&o.cacheRecordAgeRaw, "cache-record-age", "168h", "Parseable duration string that specifies how long a cache record lives in cache after the last time it was considered") fs.StringVar(&o.configFile, "config-file", "", "Path to the configure file of the retest.") - for _, group := range []flagutil.OptionGroup{&o.github, &o.config} { + for _, group := range []prowflagutil.OptionGroup{&o.github, &o.config} { group.AddFlags(fs) } diff --git a/cmd/slack-bot/main.go b/cmd/slack-bot/main.go index 8ea9f568df1..f405c81492c 100644 --- a/cmd/slack-bot/main.go +++ b/cmd/slack-bot/main.go @@ -22,7 +22,6 @@ import ( ctrlruntimeclient "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/prow/pkg/config" "sigs.k8s.io/prow/pkg/config/secret" - "sigs.k8s.io/prow/pkg/flagutil" prowflagutil "sigs.k8s.io/prow/pkg/flagutil" configflagutil "sigs.k8s.io/prow/pkg/flagutil/config" "sigs.k8s.io/prow/pkg/interrupts" @@ -78,7 +77,7 @@ func (o *options) Validate() error { return fmt.Errorf("--slack-signing-secret-path is required") } - for _, group := range []flagutil.OptionGroup{&o.instrumentationOptions, &o.jiraOptions, &o.prowconfig} { + for _, group := range []prowflagutil.OptionGroup{&o.instrumentationOptions, &o.jiraOptions, &o.prowconfig} { if err := group.Validate(false); err != nil { return err } @@ -96,7 +95,7 @@ func gatherOptions(fs *flag.FlagSet, args ...string) options { o.prowconfig.ConfigPathFlagName = "prow-config-path" o.prowconfig.JobConfigPathFlagName = "prow-job-config-path" - for _, group := range []flagutil.OptionGroup{&o.instrumentationOptions, &o.jiraOptions, &o.prowconfig} { + for _, group := range []prowflagutil.OptionGroup{&o.instrumentationOptions, &o.jiraOptions, &o.prowconfig} { group.AddFlags(fs) } diff --git a/cmd/sprint-automation/main.go b/cmd/sprint-automation/main.go index 2160aeed86d..ca32f353bd4 100644 --- a/cmd/sprint-automation/main.go +++ b/cmd/sprint-automation/main.go @@ -19,7 +19,6 @@ import ( "k8s.io/client-go/kubernetes/scheme" ctrlruntimeclient "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/prow/pkg/config/secret" - "sigs.k8s.io/prow/pkg/flagutil" prowflagutil "sigs.k8s.io/prow/pkg/flagutil" jirautil "sigs.k8s.io/prow/pkg/jira" "sigs.k8s.io/prow/pkg/logrusutil" @@ -54,7 +53,7 @@ func (o *options) Validate() error { return fmt.Errorf("--slack-token-path is required") } - for _, group := range []flagutil.OptionGroup{&o.jiraOptions, &o.pagerDutyOptions, &o.kubernetesOptions} { + for _, group := range []prowflagutil.OptionGroup{&o.jiraOptions, &o.pagerDutyOptions, &o.kubernetesOptions} { if err := group.Validate(false); err != nil { return err } @@ -67,7 +66,7 @@ func gatherOptions(fs *flag.FlagSet, args ...string) options { o := options{kubernetesOptions: prowflagutil.KubernetesOptions{NOInClusterConfigDefault: true}} fs.StringVar(&o.logLevel, "log-level", "info", "Level at which to log output.") - for _, group := range []flagutil.OptionGroup{&o.jiraOptions, &o.pagerDutyOptions, &o.kubernetesOptions} { + for _, group := range []prowflagutil.OptionGroup{&o.jiraOptions, &o.pagerDutyOptions, &o.kubernetesOptions} { group.AddFlags(fs) } diff --git a/cmd/testgrid-config-generator/main.go b/cmd/testgrid-config-generator/main.go index a488a1cf0d2..cf9494f73c5 100644 --- a/cmd/testgrid-config-generator/main.go +++ b/cmd/testgrid-config-generator/main.go @@ -162,7 +162,7 @@ func (d *dashboard) add(bucket, name string, description string, daysOfResults i return } d.existing.Insert(name) - d.Dashboard.DashboardTab = append(d.Dashboard.DashboardTab, dashboardTabFor(name, description)) + d.DashboardTab = append(d.DashboardTab, dashboardTabFor(name, description)) d.testGroups = append(d.testGroups, testGroupFor(bucket, name, daysOfResults)) } diff --git a/cmd/vault-secret-collection-manager/main.go b/cmd/vault-secret-collection-manager/main.go index aba5e646844..38fec7eb6cb 100644 --- a/cmd/vault-secret-collection-manager/main.go +++ b/cmd/vault-secret-collection-manager/main.go @@ -49,14 +49,14 @@ func parseOptions() (*option, error) { flag.StringVar(&o.vaultToken, "vault-token", "", "The privileged token to use when communicating with vault, must be able to CRUD policies") flag.StringVar(&o.vaultRole, "vault-role", "", "The vault role to use, must be able to CRUD policies. Will be used for kubernetes service account auth.") flag.StringVar(&o.authBackendType, "auth-backend-type", "oidc", "The backend type used for user authentication.") - o.InstrumentationOptions.AddFlags(flag.CommandLine) + o.AddFlags(flag.CommandLine) flag.Parse() var errs []error if o.vaultToken == "" && o.vaultRole == "" { errs = append(errs, errors.New("--vault-token or --vault-role is required")) } - if err := o.InstrumentationOptions.Validate(false); err != nil { + if err := o.Validate(false); err != nil { errs = append(errs, err) } return o, utilerrors.NewAggregate(errs) @@ -90,7 +90,7 @@ func main() { fmt.Fprintf(w, "OK") }) healthServer := &http.Server{ - Addr: ":" + strconv.Itoa(o.InstrumentationOptions.HealthPort), + Addr: ":" + strconv.Itoa(o.HealthPort), Handler: healthMux, } interrupts.ListenAndServe(healthServer, 0) diff --git a/hack/lint.sh b/hack/lint.sh index 6bc04b86cf0..5a209bed84f 100755 --- a/hack/lint.sh +++ b/hack/lint.sh @@ -29,6 +29,6 @@ else $DOCKER run --rm \ --volume "${PWD}:/go/src/github.com/openshift/ci-tools:z" \ --workdir /go/src/github.com/openshift/ci-tools \ - docker.io/golangci/golangci-lint:v1.63.4 \ + quay-proxy.ci.openshift.org/openshift/ci-public:ci_golangci-lint_latest \ golangci-lint run "$GOLANGCI_LINT_ARGS" fi diff --git a/pkg/api/graph.go b/pkg/api/graph.go index 1200558eb05..6ccb22e64d6 100644 --- a/pkg/api/graph.go +++ b/pkg/api/graph.go @@ -173,11 +173,11 @@ func AllStepsLink() StepLink { type allStepsLink struct{} -func (_ allStepsLink) SatisfiedBy(_ StepLink) bool { +func (allStepsLink) SatisfiedBy(StepLink) bool { return true } -func (_ allStepsLink) UnsatisfiableError() string { +func (allStepsLink) UnsatisfiableError() string { return "" } diff --git a/pkg/api/types.go b/pkg/api/types.go index 0d76bd0bceb..779a72df7cf 100644 --- a/pkg/api/types.go +++ b/pkg/api/types.go @@ -395,7 +395,7 @@ func (b *VersionBounds) Query() string { func BoundsFromQuery(query string) (*VersionBounds, error) { splitParts := strings.Split(query, " ") if len(splitParts) != 2 || !strings.HasPrefix(splitParts[0], ">") || !strings.HasPrefix(splitParts[1], "<") { - return nil, fmt.Errorf("Invalid version range `%s`. Must be in form `>4.x.y <4.a.b-c`", query) + return nil, fmt.Errorf("invalid version range `%s`. Must be in form `>4.x.y <4.a.b-c`", query) } return &VersionBounds{ diff --git a/pkg/backporter/backporter.go b/pkg/backporter/backporter.go index 4351317c45f..eb6b095c3bb 100644 --- a/pkg/backporter/backporter.go +++ b/pkg/backporter/backporter.go @@ -404,7 +404,7 @@ func GetBugHandler(client bugzilla.Client, m *metrics.Metrics) http.HandlerFunc if err != nil { http.Error(w, fmt.Sprintf("Bug#%d not found", bugID), http.StatusNotFound) metrics.RecordError("BugID not found", m.ErrorRate) - logrus.WithFields(logFieldsFor(endpoint, bugID)).WithError(fmt.Errorf("Bug#%d not found: %w", bugID, err)) + logrus.WithFields(logFieldsFor(endpoint, bugID)).WithError(fmt.Errorf("bug#%d not found: %w", bugID, err)) return } @@ -521,7 +521,7 @@ func buildDependenceTree(root *bugzilla.Bug, client bugzilla.Client) (*dependenc func getClonesTemplateData(bugID int, client bugzilla.Client, allTargetVersions []string) (*ClonesTemplateData, int, error) { bug, err := client.GetBug(bugID) if err != nil { - return nil, http.StatusNotFound, fmt.Errorf("Bug#%d not found: %w", bugID, err) + return nil, http.StatusNotFound, fmt.Errorf("bug#%d not found: %w", bugID, err) } clones, err := client.GetAllClones(bug) if err != nil { @@ -558,7 +558,7 @@ func getClonesTemplateData(bugID int, client bugzilla.Client, allTargetVersions g.Go(func() error { clonePRs, err := client.GetExternalBugPRsOnBug(clone.ID) if err != nil { - return fmt.Errorf("Bug#%d - error occurred while retreiving list of PRs : %w", clone.ID, err) + return fmt.Errorf("bug#%d - error occurred while retreiving list of PRs : %w", clone.ID, err) } clone.PRs = clonePRs return nil diff --git a/pkg/branchcuts/bumper/gen-release-jobs-bumper.go b/pkg/branchcuts/bumper/gen-release-jobs-bumper.go index eef7104837d..021a0e8bd11 100644 --- a/pkg/branchcuts/bumper/gen-release-jobs-bumper.go +++ b/pkg/branchcuts/bumper/gen-release-jobs-bumper.go @@ -213,7 +213,7 @@ func bumpTestSteps(tests []cioperatorapi.TestStep, major int) error { } func bumpTestStepEnvVars(multistageTest cioperatorapi.TestStep, major int) error { - if multistageTest.LiteralTestStep == nil || multistageTest.LiteralTestStep.Environment == nil { + if multistageTest.LiteralTestStep == nil || multistageTest.Environment == nil { return nil } for i := 0; i < len(multistageTest.Environment); i++ { diff --git a/pkg/clusterinit/clusterinstall/clusterinstall.go b/pkg/clusterinit/clusterinstall/clusterinstall.go index c060005334a..c4e5ca12978 100644 --- a/pkg/clusterinit/clusterinstall/clusterinstall.go +++ b/pkg/clusterinit/clusterinstall/clusterinstall.go @@ -43,7 +43,7 @@ type ClusterInstall struct { } func (ci *ClusterInstall) IsOCP() bool { - return !(*ci.Onboard.Hosted || *ci.Onboard.OSD || *ci.Onboard.Unmanaged) + return !*ci.Onboard.Hosted && !*ci.Onboard.OSD && !*ci.Onboard.Unmanaged } type Provision struct { diff --git a/pkg/clusterinit/onboard/certificate.go b/pkg/clusterinit/onboard/certificate.go index 237fa385dd3..e5898800038 100644 --- a/pkg/clusterinit/onboard/certificate.go +++ b/pkg/clusterinit/onboard/certificate.go @@ -156,7 +156,7 @@ func (s *certificateGenerator) generateCertificateManifests(baseDomain, imageReg }, } - if !(*s.clusterInstall.Onboard.OSD || *s.clusterInstall.Onboard.Hosted || *s.clusterInstall.Onboard.Unmanaged) { + if !*s.clusterInstall.Onboard.OSD && !*s.clusterInstall.Onboard.Hosted && !*s.clusterInstall.Onboard.Unmanaged { manifests = append(manifests, apiServerCert, appsCert) } manifests = append(manifests, imageRegistryCert) diff --git a/pkg/clusterinit/onboard/cisecretbootstrap.go b/pkg/clusterinit/onboard/cisecretbootstrap.go index f352e7318d6..fd54ec3721b 100644 --- a/pkg/clusterinit/onboard/cisecretbootstrap.go +++ b/pkg/clusterinit/onboard/cisecretbootstrap.go @@ -407,7 +407,7 @@ func (s *ciSecretBootstrapStep) updateDexIdAndSecret(c *secretbootstrap.Config) }, } - if !(*s.clusterInstall.Onboard.Hosted || *s.clusterInstall.Onboard.OSD) { + if !*s.clusterInstall.Onboard.Hosted && !*s.clusterInstall.Onboard.OSD { s.log.Info("Cluster is neither hosted nor osd, syncing dex OIDC secret") secret.To = append(secret.To, secretbootstrap.SecretContext{ Cluster: string(api.ClusterAPPCI), diff --git a/pkg/config/options_test.go b/pkg/config/options_test.go index 4bebe4bb344..6b301c02375 100644 --- a/pkg/config/options_test.go +++ b/pkg/config/options_test.go @@ -13,7 +13,6 @@ import ( "k8s.io/apimachinery/pkg/util/sets" - "github.com/openshift/ci-tools/pkg/api" cioperatorapi "github.com/openshift/ci-tools/pkg/api" jc "github.com/openshift/ci-tools/pkg/jobconfig" "github.com/openshift/ci-tools/pkg/testhelper" @@ -157,13 +156,13 @@ func TestOptions_Matches(t *testing.T) { var testCases = []struct { name string input Options - metadata api.Metadata + metadata cioperatorapi.Metadata expected bool }{ { name: "nothing set matches everything", input: Options{}, - metadata: api.Metadata{ + metadata: cioperatorapi.Metadata{ Org: "org", Repo: "repo", }, @@ -174,7 +173,7 @@ func TestOptions_Matches(t *testing.T) { input: Options{ Org: "org", }, - metadata: api.Metadata{ + metadata: cioperatorapi.Metadata{ Org: "org", Repo: "repo", }, @@ -185,7 +184,7 @@ func TestOptions_Matches(t *testing.T) { input: Options{ Org: "org", }, - metadata: api.Metadata{ + metadata: cioperatorapi.Metadata{ Org: "arg", Repo: "repo", }, @@ -196,7 +195,7 @@ func TestOptions_Matches(t *testing.T) { input: Options{ Repo: "repo", }, - metadata: api.Metadata{ + metadata: cioperatorapi.Metadata{ Org: "anything", Repo: "repo", }, @@ -207,7 +206,7 @@ func TestOptions_Matches(t *testing.T) { input: Options{ Repo: "repo", }, - metadata: api.Metadata{ + metadata: cioperatorapi.Metadata{ Org: "anything", Repo: "ripo", }, @@ -219,7 +218,7 @@ func TestOptions_Matches(t *testing.T) { Org: "org", Repo: "repo", }, - metadata: api.Metadata{ + metadata: cioperatorapi.Metadata{ Org: "org", Repo: "repo", }, @@ -231,7 +230,7 @@ func TestOptions_Matches(t *testing.T) { Org: "org", Repo: "repo", }, - metadata: api.Metadata{ + metadata: cioperatorapi.Metadata{ Org: "org", Repo: "ripo", }, @@ -243,7 +242,7 @@ func TestOptions_Matches(t *testing.T) { Org: "org", Repo: "repo", }, - metadata: api.Metadata{ + metadata: cioperatorapi.Metadata{ Org: "arg", Repo: "repo", }, diff --git a/pkg/config/whitelist.go b/pkg/config/whitelist.go index 6706e80948a..c5083efc70c 100644 --- a/pkg/config/whitelist.go +++ b/pkg/config/whitelist.go @@ -38,19 +38,19 @@ func (o *WhitelistOptions) Validate() error { if o.whitelistFile != "" { info, err := os.Stat(o.whitelistFile) if os.IsNotExist(err) { - return fmt.Errorf("The file that specified in --whitelist-file does not exist: %v", o.whitelistFile) + return fmt.Errorf("the file that specified in --whitelist-file does not exist: %v", o.whitelistFile) } if info.IsDir() { - return fmt.Errorf("The file that specified in --whitelist-file is a directory: %v", o.whitelistFile) + return fmt.Errorf("the file that specified in --whitelist-file is a directory: %v", o.whitelistFile) } bytes, err := gzip.ReadFileMaybeGZIP(o.whitelistFile) if err != nil { - return fmt.Errorf("Couldn't read whitelist configuration file: %v", o.whitelistFile) + return fmt.Errorf("couldn't read whitelist configuration file: %v", o.whitelistFile) } if err := yaml.Unmarshal(bytes, &o.WhitelistConfig); err != nil { - return errors.New("Couldn't unmarshal whitelist configuration") + return errors.New("couldn't unmarshal whitelist configuration") } } diff --git a/pkg/controller/multiarchbuildconfig/multiarchbuildconfig_test.go b/pkg/controller/multiarchbuildconfig/multiarchbuildconfig_test.go index 592eddf44ae..e0fb91c0f31 100644 --- a/pkg/controller/multiarchbuildconfig/multiarchbuildconfig_test.go +++ b/pkg/controller/multiarchbuildconfig/multiarchbuildconfig_test.go @@ -18,7 +18,6 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" "k8s.io/utils/pointer" - "sigs.k8s.io/controller-runtime/pkg/client" ctrlruntimeclient "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" "sigs.k8s.io/controller-runtime/pkg/client/interceptor" @@ -296,8 +295,8 @@ func TestReconcile(t *testing.T) { return client.Create(ctx, obj, opts...) } } - updateInterceptor := func(failOnMABCUpdate bool) func(ctx context.Context, client client.WithWatch, obj client.Object, opts ...client.UpdateOption) error { - return func(ctx context.Context, client client.WithWatch, obj client.Object, opts ...client.UpdateOption) error { + updateInterceptor := func(failOnMABCUpdate bool) func(ctx context.Context, client ctrlruntimeclient.WithWatch, obj ctrlruntimeclient.Object, opts ...ctrlruntimeclient.UpdateOption) error { + return func(ctx context.Context, client ctrlruntimeclient.WithWatch, obj ctrlruntimeclient.Object, opts ...ctrlruntimeclient.UpdateOption) error { if _, ok := obj.(*v1.MultiArchBuildConfig); ok && failOnMABCUpdate { return errors.New("planned failure") } diff --git a/pkg/controller/promotionreconciler/prowjobreconciler/prowjobreconciler.go b/pkg/controller/promotionreconciler/prowjobreconciler/prowjobreconciler.go index cb20ed898f1..76fb6565607 100644 --- a/pkg/controller/promotionreconciler/prowjobreconciler/prowjobreconciler.go +++ b/pkg/controller/promotionreconciler/prowjobreconciler/prowjobreconciler.go @@ -96,7 +96,7 @@ func orcbToEvent(orbc OrgRepoBranchCommit) event.TypedGenericEvent[*prowv1.ProwJ func nameToORBC(name string) (*OrgRepoBranchCommit, error) { split := strings.Split(name, "|") if n := len(split); n != 4 { - return nil, fmt.Errorf("splitting string by '|' did not return four but %d results. This is a bug.", n) + return nil, fmt.Errorf("splitting string by '|' did not return four but %d results. This is a bug", n) } return &OrgRepoBranchCommit{ Org: split[0], diff --git a/pkg/controller/prpqr_reconciler/prpqr_reconciler.go b/pkg/controller/prpqr_reconciler/prpqr_reconciler.go index b3530d3de59..29b40f7acb0 100644 --- a/pkg/controller/prpqr_reconciler/prpqr_reconciler.go +++ b/pkg/controller/prpqr_reconciler/prpqr_reconciler.go @@ -32,7 +32,6 @@ import ( prowconfig "sigs.k8s.io/prow/pkg/config" "sigs.k8s.io/prow/pkg/pjutil" - "github.com/openshift/ci-tools/pkg/api" cioperatorapi "github.com/openshift/ci-tools/pkg/api" v1 "github.com/openshift/ci-tools/pkg/api/pullrequestpayloadqualification/v1" "github.com/openshift/ci-tools/pkg/controller/prpqr_reconciler/pjstatussyncer" @@ -56,7 +55,7 @@ const ( ) type injectingResolverClient interface { - ConfigWithTest(base *api.Metadata, testSource *api.MetadataWithTest) (*api.ReleaseBuildConfiguration, error) + ConfigWithTest(base *cioperatorapi.Metadata, testSource *cioperatorapi.MetadataWithTest) (*cioperatorapi.ReleaseBuildConfiguration, error) } type prowConfigGetter interface { @@ -261,8 +260,8 @@ func (r *reconciler) triggerJobs(ctx context.Context, continue } - inject := &api.MetadataWithTest{ - Metadata: api.Metadata{ + inject := &cioperatorapi.MetadataWithTest{ + Metadata: cioperatorapi.Metadata{ Org: jobSpec.CIOperatorConfig.Org, Repo: jobSpec.CIOperatorConfig.Repo, Branch: jobSpec.CIOperatorConfig.Branch, @@ -561,7 +560,7 @@ func jobNameHash(name string) string { return hex.EncodeToString(hasher.Sum(nil)) } -func resolveCiopConfig(rc injectingResolverClient, baseCiop *api.Metadata, inject *api.MetadataWithTest) (*api.ReleaseBuildConfiguration, error) { +func resolveCiopConfig(rc injectingResolverClient, baseCiop *cioperatorapi.Metadata, inject *cioperatorapi.MetadataWithTest) (*cioperatorapi.ReleaseBuildConfiguration, error) { ciopConfig, err := rc.ConfigWithTest(baseCiop, inject) if err != nil { return nil, fmt.Errorf("failed to get config from resolver: %w", err) @@ -576,12 +575,12 @@ type aggregatedOptions struct { releaseJobName string } -func (r *reconciler) generateProwjob(ciopConfig *api.ReleaseBuildConfiguration, - baseCiop *api.Metadata, +func (r *reconciler) generateProwjob(ciopConfig *cioperatorapi.ReleaseBuildConfiguration, + baseCiop *cioperatorapi.Metadata, prpqrName, prpqrNamespace string, prs []v1.PullRequestUnderTest, mimickedJob string, - inject *api.MetadataWithTest, + inject *cioperatorapi.MetadataWithTest, aggregatedOptions *aggregatedOptions, initialPayloadPullspec, latestPayloadPullspec string, imageTagOverrides []v1.ImageTagOverride, @@ -761,21 +760,21 @@ func (r *reconciler) clusterForJob(jobName string) (string, error) { return cluster, nil } -func metadataFromPullRequestsUnderTest(prs []v1.PullRequestUnderTest) *api.Metadata { +func metadataFromPullRequestsUnderTest(prs []v1.PullRequestUnderTest) *cioperatorapi.Metadata { var orgs, repos, branches []string for _, pr := range prs { orgs = append(orgs, pr.Org) repos = append(repos, pr.Repo) branches = append(branches, pr.BaseRef) } - return &api.Metadata{ + return &cioperatorapi.Metadata{ Org: strings.Join(orgs, ","), Repo: strings.Join(repos, ","), Branch: strings.Join(branches, ","), } } -func (r *reconciler) generateAggregatedProwjobs(uid string, ciopConfig *api.ReleaseBuildConfiguration, baseCiop *api.Metadata, prpqrName, prpqrNamespace string, spec *v1.ReleaseJobSpec, prs []v1.PullRequestUnderTest, inject *api.MetadataWithTest, shardCount, shardIndex int) ([]*prowv1.ProwJob, error) { +func (r *reconciler) generateAggregatedProwjobs(uid string, ciopConfig *cioperatorapi.ReleaseBuildConfiguration, baseCiop *cioperatorapi.Metadata, prpqrName, prpqrNamespace string, spec *v1.ReleaseJobSpec, prs []v1.PullRequestUnderTest, inject *cioperatorapi.MetadataWithTest, shardCount, shardIndex int) ([]*prowv1.ProwJob, error) { var ret []*prowv1.ProwJob for i := 0; i < spec.AggregatedCount; i++ { @@ -797,13 +796,13 @@ func (r *reconciler) generateAggregatedProwjobs(uid string, ciopConfig *api.Rele return ret, nil } -func generateAggregatorJob(baseCiop *api.Metadata, uid, aggregatorJobName, jobName, prpqrName, prpqrNamespace string, getCfg prowConfigGetter, startTime time.Time, submitted string, aggregatedJobTimeout time.Duration) (*prowv1.ProwJob, error) { - ciopConfig := &api.ReleaseBuildConfiguration{ +func generateAggregatorJob(baseCiop *cioperatorapi.Metadata, uid, aggregatorJobName, jobName, prpqrName, prpqrNamespace string, getCfg prowConfigGetter, startTime time.Time, submitted string, aggregatedJobTimeout time.Duration) (*prowv1.ProwJob, error) { + ciopConfig := &cioperatorapi.ReleaseBuildConfiguration{ Metadata: *baseCiop, - Tests: []api.TestStepConfiguration{ + Tests: []cioperatorapi.TestStepConfiguration{ { As: "release-analysis-prpqr-aggregator", - MultiStageTestConfiguration: &api.MultiStageTestConfiguration{ + MultiStageTestConfiguration: &cioperatorapi.MultiStageTestConfiguration{ Environment: map[string]string{ "GOOGLE_SA_CREDENTIAL_FILE": "/var/run/secrets/google-serviceaccount-credentials.json", "VERIFICATION_JOB_NAME": jobName, @@ -812,7 +811,7 @@ func generateAggregatorJob(baseCiop *api.Metadata, uid, aggregatorJobName, jobNa "WORKING_DIR": "$(ARTIFACT_DIR)/release-analysis-aggregator", "EXPLICIT_GCS_PREFIX": fmt.Sprintf("logs/%s", submitted), }, - Test: []api.TestStep{ + Test: []cioperatorapi.TestStep{ { Reference: &[]string{"openshift-release-analysis-prpqr-aggregator"}[0], }, @@ -820,7 +819,7 @@ func generateAggregatorJob(baseCiop *api.Metadata, uid, aggregatorJobName, jobNa }, }, }, - Resources: map[string]api.ResourceRequirements{ + Resources: map[string]cioperatorapi.ResourceRequirements{ "*": { Requests: map[string]string{"cpu": "100m", "memory": "200Mi"}, Limits: map[string]string{"memory": "6Gi"}, @@ -862,7 +861,7 @@ func generateAggregatorJob(baseCiop *api.Metadata, uid, aggregatorJobName, jobNa return &pj, nil } -func generateJobNameToSubmit(inject *api.MetadataWithTest, prs []v1.PullRequestUnderTest, shardCount, shardIndex int) string { +func generateJobNameToSubmit(inject *cioperatorapi.MetadataWithTest, prs []v1.PullRequestUnderTest, shardCount, shardIndex int) string { var refs string for i, pr := range prs { if i > 0 { diff --git a/pkg/defaults/defaults.go b/pkg/defaults/defaults.go index 16afa2aabab..2c323bade36 100644 --- a/pkg/defaults/defaults.go +++ b/pkg/defaults/defaults.go @@ -154,7 +154,7 @@ func fromConfig( } params.Add("JOB_NAME", func() (string, error) { return jobSpec.Job, nil }) params.Add("JOB_NAME_HASH", func() (string, error) { return jobSpec.JobNameHash(), nil }) - params.Add("JOB_NAME_SAFE", func() (string, error) { return strings.Replace(jobSpec.Job, "_", "-", -1), nil }) + params.Add("JOB_NAME_SAFE", func() (string, error) { return strings.ReplaceAll(jobSpec.Job, "_", "-"), nil }) params.Add("UNIQUE_HASH", func() (string, error) { return jobSpec.UniqueHash(), nil }) params.Add("NAMESPACE", func() (string, error) { return jobSpec.Namespace(), nil }) inputImages := make(inputImageSet) diff --git a/pkg/diffs/diffs.go b/pkg/diffs/diffs.go index b9c0ffb38a0..b4f80631df1 100644 --- a/pkg/diffs/diffs.go +++ b/pkg/diffs/diffs.go @@ -14,7 +14,6 @@ import ( pjapi "sigs.k8s.io/prow/pkg/apis/prowjobs/v1" prowconfig "sigs.k8s.io/prow/pkg/config" - "github.com/openshift/ci-tools/pkg/api" cioperatorapi "github.com/openshift/ci-tools/pkg/api" "github.com/openshift/ci-tools/pkg/config" "github.com/openshift/ci-tools/pkg/jobconfig" @@ -58,7 +57,7 @@ func GetChangedCiopConfigs(masterConfig, prConfig config.DataByFilename, logger return out } - if diff := cmp.Diff(withoutTests(oldConfig.Configuration), withoutTests(newConfig.Configuration), cmpopts.IgnoreUnexported(api.ProjectDirectoryImageBuildStepConfiguration{})); diff != "" { + if diff := cmp.Diff(withoutTests(oldConfig.Configuration), withoutTests(newConfig.Configuration), cmpopts.IgnoreUnexported(cioperatorapi.ProjectDirectoryImageBuildStepConfiguration{})); diff != "" { logger.WithField(logCiopConfig, filename).Info(changedCiopConfigMsg) configs[filename] = newConfig continue diff --git a/pkg/dispatcher/config_test.go b/pkg/dispatcher/config_test.go index ae384380faa..67a607c423c 100644 --- a/pkg/dispatcher/config_test.go +++ b/pkg/dispatcher/config_test.go @@ -14,7 +14,6 @@ import ( v1 "k8s.io/api/core/v1" utilerrors "k8s.io/apimachinery/pkg/util/errors" "k8s.io/apimachinery/pkg/util/sets" - "sigs.k8s.io/prow/pkg/config" prowconfig "sigs.k8s.io/prow/pkg/config" "github.com/openshift/ci-tools/pkg/api" @@ -276,27 +275,27 @@ func TestGetClusterForJob(t *testing.T) { { name: "some job", config: &c, - jobBase: config.JobBase{Agent: "kubernetes", Name: "some-job"}, + jobBase: prowconfig.JobBase{Agent: "kubernetes", Name: "some-job"}, path: "org/repo/some-postsubmits.yaml", expected: "api.ci", }, { name: "job must on build01", config: &c, - jobBase: config.JobBase{Agent: "kubernetes", Name: "periodic-build01-upgrade"}, + jobBase: prowconfig.JobBase{Agent: "kubernetes", Name: "periodic-build01-upgrade"}, expected: "ci/api-build01-ci-devcluster-openshift-com:6443", }, { name: "some periodic job in release repo", config: &c, - jobBase: config.JobBase{Agent: "kubernetes", Name: "promote-release-openshift-machine-os-content-e2e-aws-4.1"}, + jobBase: prowconfig.JobBase{Agent: "kubernetes", Name: "promote-release-openshift-machine-os-content-e2e-aws-4.1"}, path: "ci-operator/jobs/openshift/release/openshift-release-release-4.1-periodics.yaml", expected: "api.ci", }, { name: "some jenkins job", config: &c, - jobBase: config.JobBase{Agent: "jenkins", Name: "test_branch_wildfly_images"}, + jobBase: prowconfig.JobBase{Agent: "jenkins", Name: "test_branch_wildfly_images"}, path: "ci-operator/jobs/openshift-s2i/s2i-wildfly/openshift-s2i-s2i-wildfly-master-postsubmits.yaml", }, { @@ -317,7 +316,7 @@ func TestGetClusterForJob(t *testing.T) { }, }, }, - jobBase: config.JobBase{Agent: "kubernetes", Name: "some-job"}, + jobBase: prowconfig.JobBase{Agent: "kubernetes", Name: "some-job"}, path: "ci-operator/jobs/openshift/openshift-azure/openshift-openshift-azure-infra-periodics.yaml", expectedErr: fmt.Errorf("path ci-operator/jobs/openshift/openshift-azure/openshift-openshift-azure-infra-periodics.yaml matches more than 1 regex: [.*/openshift-openshift-azure-infra-periodics.yaml$ .*infra-periodics.yaml$]"), }, @@ -335,7 +334,7 @@ func TestGetClusterForJob(t *testing.T) { }, }, }, - jobBase: config.JobBase{Agent: "kubernetes", Name: "some-job"}, + jobBase: prowconfig.JobBase{Agent: "kubernetes", Name: "some-job"}, path: "ci-operator/jobs/kubevirt/kubevirt-ssp-operator/kubevirt-kubevirt-ssp-operator-master-presubmits.yaml", expectedErr: fmt.Errorf("path ci-operator/jobs/kubevirt/kubevirt-ssp-operator/kubevirt-kubevirt-ssp-operator-master-presubmits.yaml matches more than 1 regex: [.*kubevirt-kubevirt-ssp-operator-master-presubmits.yaml$ .*kubevirt-ssp-operator-master-presubmits.yaml$]"), }, @@ -353,7 +352,7 @@ func TestGetClusterForJob(t *testing.T) { }, }, }, - jobBase: config.JobBase{Agent: "kubernetes", Name: "some-job"}, + jobBase: prowconfig.JobBase{Agent: "kubernetes", Name: "some-job"}, path: "ci-operator/jobs/kubevirt/kubevirt-ssp-operator/kubevirt-kubevirt-ssp-operator-master-presubmits.yaml", expected: api.ClusterBuild02, }, @@ -385,41 +384,41 @@ func TestDetermineClusterForJob(t *testing.T) { { name: "some job", config: &configWithBuildFarmWithJobs, - jobBase: config.JobBase{Agent: "kubernetes", Name: "some-job"}, + jobBase: prowconfig.JobBase{Agent: "kubernetes", Name: "some-job"}, path: "org/repo/some-postsubmits.yaml", expected: "api.ci", }, { name: "job must on build01", config: &configWithBuildFarmWithJobs, - jobBase: config.JobBase{Agent: "kubernetes", Name: "periodic-build01-upgrade"}, + jobBase: prowconfig.JobBase{Agent: "kubernetes", Name: "periodic-build01-upgrade"}, expected: "build01", }, { name: "some periodic job in release repo", config: &configWithBuildFarmWithJobs, - jobBase: config.JobBase{Agent: "kubernetes", Name: "promote-release-openshift-machine-os-content-e2e-aws-4.1"}, + jobBase: prowconfig.JobBase{Agent: "kubernetes", Name: "promote-release-openshift-machine-os-content-e2e-aws-4.1"}, path: "ci-operator/jobs/openshift/release/openshift-release-release-4.1-periodics.yaml", expected: "api.ci", }, { name: "some jenkins job", config: &configWithBuildFarmWithJobs, - jobBase: config.JobBase{Agent: "jenkins", Name: "test_branch_wildfly_images"}, + jobBase: prowconfig.JobBase{Agent: "jenkins", Name: "test_branch_wildfly_images"}, path: "ci-operator/jobs/openshift-s2i/s2i-wildfly/openshift-s2i-s2i-wildfly-master-postsubmits.yaml", expected: "", }, { name: "some job without agent", config: &configWithBuildFarmWithJobs, - jobBase: config.JobBase{Name: "no-agent-job"}, + jobBase: prowconfig.JobBase{Name: "no-agent-job"}, path: "ci-operator/jobs/openshift-s2i/s2i-wildfly/openshift-s2i-s2i-wildfly-master-postsubmits.yaml", expected: "api.ci", }, { name: "some job in build farm", config: &configWithBuildFarmWithJobs, - jobBase: config.JobBase{Agent: "kubernetes", Name: "some-build-farm-job"}, + jobBase: prowconfig.JobBase{Agent: "kubernetes", Name: "some-build-farm-job"}, path: "org/repo/some-build-farm-presubmits.yaml", expected: "build01", expectedCanBeRelocated: true, @@ -427,13 +426,13 @@ func TestDetermineClusterForJob(t *testing.T) { { name: "Vsphere job on vsphere02", config: &configWithBuildFarmWithJobs, - jobBase: config.JobBase{Agent: "kubernetes", Name: "yalayala-vsphere"}, + jobBase: prowconfig.JobBase{Agent: "kubernetes", Name: "yalayala-vsphere"}, expected: "vsphere02", }, { name: "Vsphere job on vsphere02 with profile", config: &configWithBuildFarmWithJobs, - jobBase: config.JobBase{Agent: "kubernetes", Name: "yalayala-vsphere", Labels: map[string]string{ + jobBase: prowconfig.JobBase{Agent: "kubernetes", Name: "yalayala-vsphere", Labels: map[string]string{ api.CloudClusterProfileLabel: string(api.ClusterProfileVSphereElastic), }}, expected: "vsphere02", @@ -441,7 +440,7 @@ func TestDetermineClusterForJob(t *testing.T) { { name: "Vsphere job not on vsphere02 with profile", config: &configWithBuildFarmWithJobs, - jobBase: config.JobBase{Agent: "kubernetes", Name: "yalayala-vsphere", Labels: map[string]string{ + jobBase: prowconfig.JobBase{Agent: "kubernetes", Name: "yalayala-vsphere", Labels: map[string]string{ api.CloudClusterProfileLabel: string(api.ClusterProfileVSphereElasticPoc), }}, expected: "api.ci", @@ -450,7 +449,7 @@ func TestDetermineClusterForJob(t *testing.T) { { name: "applyconfig job for vsphere", config: &configWithBuildFarmWithJobs, - jobBase: config.JobBase{Agent: "kubernetes", Name: "pull-ci-openshift-release-master-vsphere-dry", Spec: &v1.PodSpec{ + jobBase: prowconfig.JobBase{Agent: "kubernetes", Name: "pull-ci-openshift-release-master-vsphere-dry", Spec: &v1.PodSpec{ Containers: []v1.Container{ {Image: "registry.svc.ci.openshift.org/ci/applyconfig:latest"}, }, @@ -462,7 +461,7 @@ func TestDetermineClusterForJob(t *testing.T) { { name: "pull-ci-openshift-os-master-unit", config: &configWithBuildFarmWithJobs, - jobBase: config.JobBase{Agent: "kubernetes", Name: "pull-ci-openshift-os-master-unit", + jobBase: prowconfig.JobBase{Agent: "kubernetes", Name: "pull-ci-openshift-os-master-unit", Labels: map[string]string{"devices.kubevirt.io/kvm": "1"}, }, expected: "build02", @@ -471,7 +470,7 @@ func TestDetermineClusterForJob(t *testing.T) { { name: "a job with cluster label", config: &configWithBuildFarmWithJobs, - jobBase: config.JobBase{Agent: "kubernetes", Name: "pull-ci-openshift-os-master-unit", + jobBase: prowconfig.JobBase{Agent: "kubernetes", Name: "pull-ci-openshift-os-master-unit", Labels: map[string]string{"ci-operator.openshift.io/cluster": "b01"}, }, expected: "b01", @@ -480,7 +479,7 @@ func TestDetermineClusterForJob(t *testing.T) { { name: "a job with noBuilds label", config: &configWithBuildFarmWithJobs, - jobBase: config.JobBase{Agent: "kubernetes", Name: "pull-ci-openshift-os-master-unit", + jobBase: prowconfig.JobBase{Agent: "kubernetes", Name: "pull-ci-openshift-os-master-unit", Labels: map[string]string{"ci.openshift.io/no-builds": "true"}, }, expected: "build03", @@ -489,7 +488,7 @@ func TestDetermineClusterForJob(t *testing.T) { { name: "a job with cluster label and noBuilds label: cluster label wins", config: &configWithBuildFarmWithJobs, - jobBase: config.JobBase{Agent: "kubernetes", Name: "pull-ci-openshift-os-master-unit", + jobBase: prowconfig.JobBase{Agent: "kubernetes", Name: "pull-ci-openshift-os-master-unit", Labels: map[string]string{"ci-operator.openshift.io/cluster": "b01", "ci.openshift.io/no-builds": "true"}, }, expected: "b01", @@ -498,7 +497,7 @@ func TestDetermineClusterForJob(t *testing.T) { { name: "DetermineE2EByJob: cloud label has no effect if DetermineE2EByJob=false", config: &configWithBuildFarmWithJobs, - jobBase: config.JobBase{Agent: "kubernetes", Name: "some-e2e-job", + jobBase: prowconfig.JobBase{Agent: "kubernetes", Name: "some-e2e-job", Labels: map[string]string{"ci-operator.openshift.io/cloud": "aws"}, }, expected: "api.ci", @@ -507,7 +506,7 @@ func TestDetermineClusterForJob(t *testing.T) { { name: "DetermineE2EByJob: cloud label", config: &configWithBuildFarmWithJobsAndDetermineE2EByJob, - jobBase: config.JobBase{Agent: "kubernetes", Name: "some-e2e-job", + jobBase: prowconfig.JobBase{Agent: "kubernetes", Name: "some-e2e-job", Labels: map[string]string{"ci-operator.openshift.io/cloud": "aws"}, }, expected: "build01", @@ -516,7 +515,7 @@ func TestDetermineClusterForJob(t *testing.T) { { name: "DetermineE2EByJob: env var", config: &configWithBuildFarmWithJobsAndDetermineE2EByJob, - jobBase: config.JobBase{Agent: "kubernetes", Name: "some-e2e-job", + jobBase: prowconfig.JobBase{Agent: "kubernetes", Name: "some-e2e-job", Spec: &v1.PodSpec{ Containers: []v1.Container{ { @@ -533,7 +532,7 @@ func TestDetermineClusterForJob(t *testing.T) { { name: "capabilities with enabled DetermineE2EByJob, cloud provider type is respected", config: &configWithBuildFarmWithJobsAndDetermineE2EByJob, - jobBase: config.JobBase{Agent: "kubernetes", Name: "some-e2e-job", + jobBase: prowconfig.JobBase{Agent: "kubernetes", Name: "some-e2e-job", Labels: map[string]string{ "capability/intranet": "intranet", "capability/arm64": "arm64", @@ -549,7 +548,7 @@ func TestDetermineClusterForJob(t *testing.T) { { name: "no cluster with all desired capabilities will return error", config: &configWithBuildFarmWithJobsAndDetermineE2EByJob, - jobBase: config.JobBase{Agent: "kubernetes", Name: "some-e2e-job", + jobBase: prowconfig.JobBase{Agent: "kubernetes", Name: "some-e2e-job", Labels: map[string]string{ "capability/intranet": "intranet", "capability/arm64": "arm64", @@ -566,7 +565,7 @@ func TestDetermineClusterForJob(t *testing.T) { { name: "cluster label has priority over capabilities", config: &configWithBuildFarmWithJobsAndDetermineE2EByJob, - jobBase: config.JobBase{Agent: "kubernetes", Name: "some-e2e-job", + jobBase: prowconfig.JobBase{Agent: "kubernetes", Name: "some-e2e-job", Labels: map[string]string{ "capability/intranet": "intranet", "ci-operator.openshift.io/cluster": "build10"}, @@ -579,7 +578,7 @@ func TestDetermineClusterForJob(t *testing.T) { { name: "capabilities have priority over kvm label", config: &configWithBuildFarmWithJobsAndDetermineE2EByJob, - jobBase: config.JobBase{Agent: "kubernetes", Name: "some-e2e-job", + jobBase: prowconfig.JobBase{Agent: "kubernetes", Name: "some-e2e-job", Labels: map[string]string{ "capability/kvm": "kvm"}}, cm: ClusterMap{"build03": ClusterInfo{Provider: "aws", Capacity: 100, Capabilities: []string{"kvm"}}, diff --git a/pkg/github/prcreation/prcreation.go b/pkg/github/prcreation/prcreation.go index 1bcb60e07b4..b43831cccb3 100644 --- a/pkg/github/prcreation/prcreation.go +++ b/pkg/github/prcreation/prcreation.go @@ -24,11 +24,11 @@ type PRCreationOptions struct { func (o *PRCreationOptions) AddFlags(fs *flag.FlagSet) { fs.BoolVar(&o.SelfApprove, "self-approve", false, "If the created PR should be self-approved by adding the lgtm+approved labels") - o.GitHubOptions.AddFlags(fs) + o.AddFlags(fs) } func (o *PRCreationOptions) Finalize() error { - if err := o.GitHubOptions.Validate(false); err != nil { + if err := o.Validate(false); err != nil { return err } if err := secret.Add(o.TokenPath); err != nil { diff --git a/pkg/gsm-secrets/iam.go b/pkg/gsm-secrets/iam.go index 239b8fd734d..65a5cd08112 100644 --- a/pkg/gsm-secrets/iam.go +++ b/pkg/gsm-secrets/iam.go @@ -60,7 +60,7 @@ func GetSecretsUpdaterConditionDescription(collection string) string { func IsManagedBinding(b *iampb.Binding) bool { isSecretAccessorRole := strings.Contains(b.Role, "/roles/openshift_ci_secrets_viewer") isSecretUpdaterRole := strings.Contains(b.Role, "/roles/openshift_ci_secrets_updater") - if !(isSecretAccessorRole || isSecretUpdaterRole) { + if !isSecretAccessorRole && !isSecretUpdaterRole { return false } if b.Condition == nil { diff --git a/pkg/jobrunaggregator/jobrunaggregatoranalyzer/analyzer.go b/pkg/jobrunaggregator/jobrunaggregatoranalyzer/analyzer.go index 49cab56ae30..11277452869 100644 --- a/pkg/jobrunaggregator/jobrunaggregatoranalyzer/analyzer.go +++ b/pkg/jobrunaggregator/jobrunaggregatoranalyzer/analyzer.go @@ -157,7 +157,7 @@ func (o *JobRunAggregatorAnalyzerOptions) Run(ctx context.Context) error { } // if more than three jobruns timed out, just fail the entire aggregation if len(unfinishedJobNames) > 3 { - return fmt.Errorf("%s for %s: found %d unfinished related jobRuns: %v\n", o.jobName, o.payloadTag, len(unfinishedJobNames), strings.Join(unfinishedJobNames, ", ")) + return fmt.Errorf("%s for %s: found %d unfinished related jobRuns: %v", o.jobName, o.payloadTag, len(unfinishedJobNames), strings.Join(unfinishedJobNames, ", ")) } alog.Infof("aggregating %d related jobRuns: %v", len(finishedJobsToAggregate), strings.Join(finishedJobRunNames, ", ")) @@ -301,13 +301,13 @@ func (o *JobRunAggregatorAnalyzerOptions) Run(ctx context.Context) error { if hasFailedTestCase(syntheticSuite) { // we already indicated failure messages above - return fmt.Errorf("Some tests failed aggregation. See above for details.") + return fmt.Errorf("some tests failed aggregation. See above for details") } // catch edge case where *all* aggregated jobs failed before they could run any real tests. // if *any* of them ran real tests, the other failures would normally fail aggregation anyway. but if all setup fell over early, we get nothing to aggregate. if !anyRealTestsRan(syntheticSuite) { - return fmt.Errorf("None of the jobs aggregated ran an expected test suite. This usually means they failed very early.") + return fmt.Errorf("none of the jobs aggregated ran an expected test suite. This usually means they failed very early") } return nil diff --git a/pkg/jobrunaggregator/jobrunaggregatoranalyzer/pass_fail.go b/pkg/jobrunaggregator/jobrunaggregatoranalyzer/pass_fail.go index 50c3370d316..b9d5b2873a9 100644 --- a/pkg/jobrunaggregator/jobrunaggregatoranalyzer/pass_fail.go +++ b/pkg/jobrunaggregator/jobrunaggregatoranalyzer/pass_fail.go @@ -230,8 +230,8 @@ func getMinor(in string) (int, error) { } func normalizeJobName(jobName, fromRelease, toRelease string) string { - newJobName := strings.Replace(jobName, toRelease, "", -1) - return strings.Replace(newJobName, fromRelease, "", -1) + newJobName := strings.ReplaceAll(jobName, toRelease, "") + return strings.ReplaceAll(newJobName, fromRelease, "") } func (a *weeklyAverageFromTenDays) getNormalizedFallBackJobName(ctx context.Context, jobName string) (string, error) { diff --git a/pkg/jobrunaggregator/jobrunaggregatorlib/big_query.go b/pkg/jobrunaggregator/jobrunaggregatorlib/big_query.go index 7e4874cc274..5f8a96420e3 100644 --- a/pkg/jobrunaggregator/jobrunaggregatorlib/big_query.go +++ b/pkg/jobrunaggregator/jobrunaggregatorlib/big_query.go @@ -53,11 +53,10 @@ func (f *BigQueryDataCoordinates) Validate() error { } func (f *BigQueryDataCoordinates) SubstituteDataSetLocation(query string) string { - return strings.Replace( + return strings.ReplaceAll( query, "DATA_SET_LOCATION", - f.ProjectID+"."+f.DataSetID, - -1) + f.ProjectID+"."+f.DataSetID) } type BigQueryInserter interface { diff --git a/pkg/jobrunaggregator/jobrunaggregatorlib/ci_data_client.go b/pkg/jobrunaggregator/jobrunaggregatorlib/ci_data_client.go index 992bdce5b1b..00a42c1cc6e 100644 --- a/pkg/jobrunaggregator/jobrunaggregatorlib/ci_data_client.go +++ b/pkg/jobrunaggregator/jobrunaggregatorlib/ci_data_client.go @@ -1020,12 +1020,12 @@ func (c *ciDataClient) ListAggregatedTestRunsForJob(ctx context.Context, frequen if err != nil { return nil, err } - queryString := strings.Replace( + queryString := strings.ReplaceAll( `SELECT * FROM DATA_SET_LOCATION.TABLE_NAME WHERE TABLE_NAME.JobName = @JobName `, - "TABLE_NAME", frequencyTable, -1) + "TABLE_NAME", frequencyTable) queryString = c.dataCoordinates.SubstituteDataSetLocation(queryString) diff --git a/pkg/load/load_test.go b/pkg/load/load_test.go index b550fa94ccc..c07411119f2 100644 --- a/pkg/load/load_test.go +++ b/pkg/load/load_test.go @@ -277,19 +277,20 @@ func TestClusterProfilesConfig(t *testing.T) { profilesWithOwners := make(api.ClusterProfilesMap) for _, profileName := range api.ClusterProfiles() { - if profileName == "aws" { + switch profileName { + case "aws": profilesWithOwners[profileName] = api.ClusterProfileDetails{ Profile: profileName, Owners: []api.ClusterProfileOwners{{Org: "org1"}}, Secret: api.GetDefaultClusterProfileSecretName(profileName), } - } else if profileName == "aws-2" { + case "aws-2": profilesWithOwners[profileName] = api.ClusterProfileDetails{ Profile: profileName, Owners: []api.ClusterProfileOwners{{Org: "org2", Repos: []string{"repo1", "repo2"}}}, Secret: api.GetDefaultClusterProfileSecretName(profileName), } - } else { + default: profilesWithOwners[profileName] = api.ClusterProfileDetails{ Profile: profileName, Secret: api.GetDefaultClusterProfileSecretName(profileName), @@ -299,18 +300,19 @@ func TestClusterProfilesConfig(t *testing.T) { profilesWithSecrets := make(api.ClusterProfilesMap) for _, profileName := range api.ClusterProfiles() { - if profileName == "aws-2" { + switch profileName { + case "aws-2": profilesWithSecrets[profileName] = api.ClusterProfileDetails{ Profile: profileName, Owners: []api.ClusterProfileOwners{{Org: "org2", Repos: []string{"repo1", "repo2"}}}, Secret: "non-default-secret-name-aws", } - } else if profileName == "vsphere-connected-2" { + case "vsphere-connected-2": profilesWithSecrets[profileName] = api.ClusterProfileDetails{ Profile: profileName, Secret: "non-default-secret-name-vsphere", } - } else { + default: profilesWithSecrets[profileName] = api.ClusterProfileDetails{ Profile: profileName, Secret: api.GetDefaultClusterProfileSecretName(profileName), diff --git a/pkg/promotion/promotion.go b/pkg/promotion/promotion.go index 796bce6522c..276a6b79b9a 100644 --- a/pkg/promotion/promotion.go +++ b/pkg/promotion/promotion.go @@ -8,7 +8,6 @@ import ( "k8s.io/apimachinery/pkg/util/sets" "sigs.k8s.io/prow/pkg/flagutil" - "github.com/openshift/ci-tools/pkg/api" cioperatorapi "github.com/openshift/ci-tools/pkg/api" "github.com/openshift/ci-tools/pkg/config" ) @@ -41,12 +40,12 @@ func AllPromotionImageStreamTags(configSpec *cioperatorapi.ReleaseBuildConfigura } disabled := sets.New(target.ExcludedImages...) - if !disabled.Has(api.PromotionExcludeImageWildcard) { + if !disabled.Has(cioperatorapi.PromotionExcludeImageWildcard) { for _, image := range configSpec.Images { result.Insert(fmt.Sprintf("%s/%s:%s", target.Namespace, target.Name, image.To)) } } - for _, image := range disabled.Delete(api.PromotionExcludeImageWildcard).UnsortedList() { + for _, image := range disabled.Delete(cioperatorapi.PromotionExcludeImageWildcard).UnsortedList() { delete(result, image) } @@ -140,7 +139,7 @@ func (o *Options) matches(configuration *cioperatorapi.ReleaseBuildConfiguration // OperateOnCIOperatorConfigDir filters the full set of configurations // down to those that were selected by the user with promotion options func (o *Options) OperateOnCIOperatorConfigDir(configDir string, includeOKD cioperatorapi.OKDInclusion, callback func(*cioperatorapi.ReleaseBuildConfiguration, *config.Info) error) error { - return o.Options.OperateOnCIOperatorConfigDir(configDir, func(configuration *cioperatorapi.ReleaseBuildConfiguration, info *config.Info) error { + return o.ConfirmableOptions.OperateOnCIOperatorConfigDir(configDir, func(configuration *cioperatorapi.ReleaseBuildConfiguration, info *config.Info) error { if !o.matches(configuration, includeOKD) { return nil } diff --git a/pkg/prowgen/jobbase_test.go b/pkg/prowgen/jobbase_test.go index cb473d250c2..296e4dc9160 100644 --- a/pkg/prowgen/jobbase_test.go +++ b/pkg/prowgen/jobbase_test.go @@ -6,7 +6,6 @@ import ( "k8s.io/utils/pointer" prowv1 "sigs.k8s.io/prow/pkg/apis/prowjobs/v1" - v1 "sigs.k8s.io/prow/pkg/apis/prowjobs/v1" ciop "github.com/openshift/ci-tools/pkg/api" "github.com/openshift/ci-tools/pkg/config" @@ -278,7 +277,7 @@ func TestNewProwJobBaseBuilderForTest(t *testing.T) { As: "simple", Commands: "make", ContainerTestConfiguration: &ciop.ContainerTestConfiguration{From: "src"}, - Timeout: &v1.Duration{Duration: time.Second}, + Timeout: &prowv1.Duration{Duration: time.Second}, }, info: defaultInfo, }, @@ -295,7 +294,7 @@ func TestNewProwJobBaseBuilderForTest(t *testing.T) { As: "simple", Commands: "make", ContainerTestConfiguration: &ciop.ContainerTestConfiguration{From: "src"}, - Timeout: &v1.Duration{Duration: time.Second}, + Timeout: &prowv1.Duration{Duration: time.Second}, }, info: defaultInfo, }, diff --git a/pkg/prowgen/podspec.go b/pkg/prowgen/podspec.go index 44f67993ba3..1d7679ed1a8 100644 --- a/pkg/prowgen/podspec.go +++ b/pkg/prowgen/podspec.go @@ -417,7 +417,7 @@ func Template(template, command, fromImage, target string, profile cioperatorapi addUniqueParameter(container, fmt.Sprintf("--template=%s", templatePath)) defaultEnvVars := []corev1.EnvVar{ - {Name: envSafeJobName, Value: strings.Replace(target, "_", "-", -1)}, + {Name: envSafeJobName, Value: strings.ReplaceAll(target, "_", "-")}, {Name: envTestCommand, Value: command}, {Name: envClusterType, Value: profile.ClusterType()}, } diff --git a/pkg/prowgen/prowgen_test.go b/pkg/prowgen/prowgen_test.go index 1412c8a7e50..b6192b06a9a 100644 --- a/pkg/prowgen/prowgen_test.go +++ b/pkg/prowgen/prowgen_test.go @@ -10,7 +10,6 @@ import ( prowv1 "sigs.k8s.io/prow/pkg/apis/prowjobs/v1" prowconfig "sigs.k8s.io/prow/pkg/config" - "github.com/openshift/ci-tools/pkg/api" ciop "github.com/openshift/ci-tools/pkg/api" "github.com/openshift/ci-tools/pkg/config" "github.com/openshift/ci-tools/pkg/testhelper" @@ -442,7 +441,7 @@ func TestGenerateJobs(t *testing.T) { config: &ciop.ReleaseBuildConfiguration{ Tests: []ciop.TestStepConfiguration{}, Images: []ciop.ProjectDirectoryImageBuildStepConfiguration{{}}, - PromotionConfiguration: &ciop.PromotionConfiguration{Targets: []api.PromotionTarget{{Namespace: "ci"}}}, + PromotionConfiguration: &ciop.PromotionConfiguration{Targets: []ciop.PromotionTarget{{Namespace: "ci"}}}, }, repoInfo: &ProwgenInfo{Metadata: ciop.Metadata{ Org: "organization", @@ -459,7 +458,7 @@ func TestGenerateJobs(t *testing.T) { {To: "out-2", From: "base"}, }, PromotionConfiguration: &ciop.PromotionConfiguration{ - Targets: []api.PromotionTarget{{ + Targets: []ciop.PromotionTarget{{ Namespace: "ci", AdditionalImages: map[string]string{ "out": "out-1", diff --git a/pkg/registry/graph.go b/pkg/registry/graph.go index 5cc6c7fc764..4f5933075bb 100644 --- a/pkg/registry/graph.go +++ b/pkg/registry/graph.go @@ -265,7 +265,7 @@ func hasCycles(node *chainNode, ancestors sets.Set[string], traversedPath []stri ancestors = sets.New[string]() } if ancestors.Has(node.name) { - return fmt.Errorf("Cycle detected: %s is an ancestor of itself; traversedPath: %v", node.name, append(traversedPath, node.name)) + return fmt.Errorf("cycle detected: %s is an ancestor of itself; traversedPath: %v", node.name, append(traversedPath, node.name)) } ancestors.Insert(node.name) for child := range node.chainChildren { @@ -322,7 +322,7 @@ func NewGraph(stepsByName ReferenceByName, chainsByName ChainByName, workflowsBy for _, step := range chain.Steps { if step.Reference != nil { if _, exists := referenceNodes[*step.Reference]; !exists { - return nodesByName, fmt.Errorf("Chain %s contains non-existent reference %s", name, *step.Reference) + return nodesByName, fmt.Errorf("chain %s contains non-existent reference %s", name, *step.Reference) } node.addReferenceChild(referenceNodes[*step.Reference]) } @@ -334,7 +334,7 @@ func NewGraph(stepsByName ReferenceByName, chainsByName ChainByName, workflowsBy for parent, children := range parentChildChain { for _, child := range children { if _, exists := chainNodes[child]; !exists { - return nodesByName, fmt.Errorf("Chain %s contains non-existent chain %s", parent.Name(), child) + return nodesByName, fmt.Errorf("chain %s contains non-existent chain %s", parent.Name(), child) } parent.addChainChild(chainNodes[child]) } @@ -356,7 +356,7 @@ func NewGraph(stepsByName ReferenceByName, chainsByName ChainByName, workflowsBy if workflow.Observers != nil { for _, observer := range workflow.Observers.Enable { if child, exists := nodesByName.Observers[observer]; !exists { - return nodesByName, fmt.Errorf("Workflow %s contains non-existent observer %s", name, observer) + return nodesByName, fmt.Errorf("workflow %s contains non-existent observer %s", name, observer) } else { if node.observerChildren == nil { node.observerChildren = make(observerNodeSet) @@ -373,13 +373,13 @@ func NewGraph(stepsByName ReferenceByName, chainsByName ChainByName, workflowsBy for _, step := range steps { if step.Reference != nil { if _, exists := referenceNodes[*step.Reference]; !exists { - return nodesByName, fmt.Errorf("Workflow %s contains non-existent reference %s", name, *step.Reference) + return nodesByName, fmt.Errorf("workflow %s contains non-existent reference %s", name, *step.Reference) } node.addReferenceChild(referenceNodes[*step.Reference]) } if step.Chain != nil { if _, exists := chainNodes[*step.Chain]; !exists { - return nodesByName, fmt.Errorf("Workflow %s contains non-existent chain %s", name, *step.Chain) + return nodesByName, fmt.Errorf("workflow %s contains non-existent chain %s", name, *step.Chain) } node.addChainChild(chainNodes[*step.Chain]) } diff --git a/pkg/registry/resolver.go b/pkg/registry/resolver.go index 5d89b4d2d8f..dfa02378990 100644 --- a/pkg/registry/resolver.go +++ b/pkg/registry/resolver.go @@ -410,7 +410,7 @@ func ResolveConfig(resolver Resolver, config api.ReleaseBuildConfiguration) (api resolvedConfig, err := resolver.Resolve(step.As, *step.MultiStageTestConfiguration) if err != nil { - return api.ReleaseBuildConfiguration{}, fmt.Errorf("Failed resolve MultiStageTestConfiguration: %w", err) + return api.ReleaseBuildConfiguration{}, fmt.Errorf("failed resolve MultiStageTestConfiguration: %w", err) } step.MultiStageTestConfigurationLiteral = &resolvedConfig // remove old multi stage config diff --git a/pkg/secrets/flags.go b/pkg/secrets/flags.go index 6f6a5738305..91e726fc9d3 100644 --- a/pkg/secrets/flags.go +++ b/pkg/secrets/flags.go @@ -59,7 +59,7 @@ func (o *CLIOptions) NewClient(censor *DynamicCensor) (Client, error) { c, err = vaultclient.New(o.VaultAddr, o.VaultToken) } if err != nil { - return nil, fmt.Errorf("Failed to construct vault client: %w", err) + return nil, fmt.Errorf("failed to construct vault client: %w", err) } return NewVaultClient(c, o.VaultPrefix, censor), nil } diff --git a/pkg/steps/artifacts.go b/pkg/steps/artifacts.go index fb354b2f255..b465b983932 100644 --- a/pkg/steps/artifacts.go +++ b/pkg/steps/artifacts.go @@ -16,7 +16,6 @@ import ( "github.com/sirupsen/logrus" - coreapi "k8s.io/api/core/v1" corev1 "k8s.io/api/core/v1" kerrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime" @@ -67,7 +66,7 @@ func NewTestCaseNotifier(nested util.ContainerNotifier) *TestCaseNotifier { return &TestCaseNotifier{nested: nested} } -func (n *TestCaseNotifier) Notify(pod *coreapi.Pod, containerName string) { +func (n *TestCaseNotifier) Notify(pod *corev1.Pod, containerName string) { n.nested.Notify(pod, containerName) n.lastPod = pod } @@ -91,7 +90,7 @@ func (n *TestCaseNotifier) SubTests(prefix string) []*junit.TestCase { if len(names) == 0 { return nil } - statuses := make([]coreapi.ContainerStatus, len(pod.Status.ContainerStatuses)) + statuses := make([]corev1.ContainerStatus, len(pod.Status.ContainerStatuses)) copy(statuses, pod.Status.ContainerStatuses) sort.Slice(statuses, func(i, j int) bool { aT, bT := statuses[i].State.Terminated, statuses[j].State.Terminated @@ -171,7 +170,7 @@ func copyArtifacts(podClient kubernetes.PodClient, into, ns, name, containerName args = append(args, "-C", s, ".") } - e, err := podClient.Exec(ns, name, &coreapi.PodExecOptions{ + e, err := podClient.Exec(ns, name, &corev1.PodExecOptions{ Container: containerName, Stdout: true, Stderr: true, @@ -251,7 +250,7 @@ func copyArtifacts(podClient kubernetes.PodClient, into, ns, name, containerName } func removeFile(podClient kubernetes.PodClient, ns, name, containerName string, paths []string) error { - e, err := podClient.Exec(ns, name, &coreapi.PodExecOptions{ + e, err := podClient.Exec(ns, name, &corev1.PodExecOptions{ Container: containerName, Stdout: true, Stderr: true, @@ -272,11 +271,11 @@ func removeFile(podClient kubernetes.PodClient, ns, name, containerName string, } func addPodUtils( - pod *coreapi.Pod, + pod *corev1.Pod, artifactDir string, decorationConfig *prowv1.DecorationConfig, rawJobSpec string, - secretsToCensor []coreapi.VolumeMount, + secretsToCensor []corev1.VolumeMount, generatePodOptions *GeneratePodOptions, jobSpec *api.JobSpec, ) error { @@ -292,7 +291,7 @@ func addPodUtils( if err != nil { return fmt.Errorf("could not inject entrypoint: %w", err) } - pod.Spec.Containers[0].Env = append(pod.Spec.Containers[0].Env, coreapi.EnvVar{Name: artifactEnv, Value: logMount.MountPath + "/artifacts"}) + pod.Spec.Containers[0].Env = append(pod.Spec.Containers[0].Env, corev1.EnvVar{Name: artifactEnv, Value: logMount.MountPath + "/artifacts"}) sidecar, err := decorate.Sidecar(decorationConfig, blobStorageOptions, blobStorageMounts, logMount, nil, rawJobSpec, !decorate.RequirePassingEntries, true, secretsToCensor, *wrapperOptions) if err != nil { @@ -333,11 +332,11 @@ func addPodUtils( return nil } -func artifactsContainer() coreapi.Container { - return coreapi.Container{ +func artifactsContainer() corev1.Container { + return corev1.Container{ Name: "artifacts", Image: "quay.io/prometheus/busybox:latest", - VolumeMounts: []coreapi.VolumeMount{ + VolumeMounts: []corev1.VolumeMount{ {Name: "artifacts", MountPath: "/tmp/artifacts"}, }, Command: []string{ @@ -519,8 +518,8 @@ func (w *ArtifactWorker) Complete(podName string) { } } -func hasFailedContainers(pod *coreapi.Pod) bool { - for _, status := range append(append([]coreapi.ContainerStatus(nil), pod.Status.ContainerStatuses...), pod.Status.InitContainerStatuses...) { +func hasFailedContainers(pod *corev1.Pod) bool { + for _, status := range append(append([]corev1.ContainerStatus(nil), pod.Status.ContainerStatuses...), pod.Status.InitContainerStatuses...) { if status.State.Terminated != nil && status.State.Terminated.ExitCode != 0 { return true } @@ -528,7 +527,7 @@ func hasFailedContainers(pod *coreapi.Pod) bool { return false } -func (w *ArtifactWorker) Notify(pod *coreapi.Pod, containerName string) { +func (w *ArtifactWorker) Notify(pod *corev1.Pod, containerName string) { w.lock.Lock() defer w.lock.Unlock() @@ -565,9 +564,9 @@ func (w *ArtifactWorker) Done(podName string) <-chan struct{} { return w.remaining[podName].done } -func addArtifactContainersFromPod(pod *coreapi.Pod, worker *ArtifactWorker) { +func addArtifactContainersFromPod(pod *corev1.Pod, worker *ArtifactWorker) { var containers []string - for _, container := range append(append([]coreapi.Container{}, pod.Spec.InitContainers...), pod.Spec.Containers...) { + for _, container := range append(append([]corev1.Container{}, pod.Spec.InitContainers...), pod.Spec.Containers...) { if !containerHasVolumeName(container, "artifacts") { continue } @@ -580,7 +579,7 @@ func addArtifactContainersFromPod(pod *coreapi.Pod, worker *ArtifactWorker) { worker.CollectFromPod(pod.Name, containers, waitForContainers) } -func containerHasVolumeName(container coreapi.Container, name string) bool { +func containerHasVolumeName(container corev1.Container, name string) bool { for _, v := range container.VolumeMounts { if v.Name == name { return true @@ -589,13 +588,13 @@ func containerHasVolumeName(container coreapi.Container, name string) bool { return false } -func addArtifactsToPod(pod *coreapi.Pod) { +func addArtifactsToPod(pod *corev1.Pod) { if hasArtifactsVolume(pod) && hasMountsArtifactsVolume(pod) { pod.Spec.Containers = append(pod.Spec.Containers, artifactsContainer()) } } -func hasArtifactsVolume(pod *coreapi.Pod) bool { +func hasArtifactsVolume(pod *corev1.Pod) bool { for _, volume := range pod.Spec.Volumes { if volume.Name == "artifacts" { return true @@ -604,7 +603,7 @@ func hasArtifactsVolume(pod *coreapi.Pod) bool { return false } -func hasMountsArtifactsVolume(pod *coreapi.Pod) bool { +func hasMountsArtifactsVolume(pod *corev1.Pod) bool { for _, initContainer := range pod.Spec.InitContainers { for _, volumeMount := range initContainer.VolumeMounts { if volumeMount.Name == "artifacts" { @@ -628,7 +627,7 @@ func gatherContainerLogsOutput(podClient kubernetes.PodClient, artifactDir, name logger := logrus.WithFields(logrus.Fields{"pod": podName, "namespace": namespace, "artifactDir": artifactDir}) logger.Trace("Gathering container logs.") var validationErrors []error - pod := &coreapi.Pod{} + pod := &corev1.Pod{} if err := podClient.Get(context.TODO(), ctrlruntimeclient.ObjectKey{Namespace: namespace, Name: podName}, pod); err != nil { if kerrors.IsNotFound(err) { return nil @@ -661,7 +660,7 @@ func gatherContainerLogsOutput(podClient kubernetes.PodClient, artifactDir, name w := gzip.NewWriter(file) logger.Trace("Fetching container logs.") - if s, err := podClient.GetLogs(namespace, podName, &coreapi.PodLogOptions{Container: status.Name}).Stream(context.TODO()); err == nil { + if s, err := podClient.GetLogs(namespace, podName, &corev1.PodLogOptions{Container: status.Name}).Stream(context.TODO()); err == nil { if _, err := io.Copy(w, s); err != nil { validationErrors = append(validationErrors, fmt.Errorf("error: Unable to copy log output from pod container %s: %w", status.Name, err)) } @@ -708,8 +707,8 @@ func gatherSuccessfulBuildLog(buildClient BuildClient, namespace, buildName stri return nil } -func getContainerStatuses(pod *coreapi.Pod) []coreapi.ContainerStatus { - var statuses []coreapi.ContainerStatus +func getContainerStatuses(pod *corev1.Pod) []corev1.ContainerStatus { + var statuses []corev1.ContainerStatus statuses = append(statuses, pod.Status.InitContainerStatuses...) statuses = append(statuses, pod.Status.ContainerStatuses...) return statuses diff --git a/pkg/steps/cluster_claim.go b/pkg/steps/cluster_claim.go index d099300c1eb..1611b0cbc1e 100644 --- a/pkg/steps/cluster_claim.go +++ b/pkg/steps/cluster_claim.go @@ -46,11 +46,11 @@ func (s clusterClaimStep) Inputs() (api.InputDefinition, error) { return s.wrapped.Inputs() } -var NoHiveClientErr = errors.New("step claims a cluster without providing a Hive client") +var ErrNoHiveClient = errors.New("step claims a cluster without providing a Hive client") func (s *clusterClaimStep) Validate() error { if s.hiveClient == nil { - return NoHiveClientErr + return ErrNoHiveClient } return nil } @@ -190,11 +190,12 @@ func NamePerTest(name, testName string) string { func getHiveSecret(src *corev1.Secret, name, namespace, testName string) (*corev1.Secret, error) { var key string - if name == api.HiveAdminKubeconfigSecret { + switch name { + case api.HiveAdminKubeconfigSecret: key = api.HiveAdminKubeconfigSecretKey - } else if name == api.HiveAdminPasswordSecret { + case api.HiveAdminPasswordSecret: key = api.HiveAdminPasswordSecretKey - } else { + default: return nil, fmt.Errorf("cannot mutate secret %s in namespace %s", src.Name, src.Namespace) } _, ok := src.Data[key] diff --git a/pkg/steps/ip_pool.go b/pkg/steps/ip_pool.go index 2a3209a3c01..c8c5eefd30a 100644 --- a/pkg/steps/ip_pool.go +++ b/pkg/steps/ip_pool.go @@ -21,7 +21,7 @@ import ( "github.com/openshift/ci-tools/pkg/results" ) -var NoLeaseClientForIPErr = errors.New("step needs access to an IP pool, but no lease client provided") +var ErrNoLeaseClientForIP = errors.New("step needs access to an IP pool, but no lease client provided") // ipPoolStep wraps another step and acquires/releases chunks of IPs. type ipPoolStep struct { @@ -54,7 +54,7 @@ func (s *ipPoolStep) Inputs() (api.InputDefinition, error) { func (s *ipPoolStep) Validate() error { if s.client == nil { - return NoLeaseClientForIPErr + return ErrNoLeaseClientForIP } return nil } diff --git a/pkg/steps/lease.go b/pkg/steps/lease.go index bb092da916f..849a5e8697a 100644 --- a/pkg/steps/lease.go +++ b/pkg/steps/lease.go @@ -20,7 +20,7 @@ import ( "github.com/openshift/ci-tools/pkg/results" ) -var NoLeaseClientErr = errors.New("step needs a lease but no lease client provided") +var ErrNoLeaseClient = errors.New("step needs a lease but no lease client provided") type stepLease struct { api.StepLease @@ -57,7 +57,7 @@ func (s *leaseStep) Inputs() (api.InputDefinition, error) { func (s *leaseStep) Validate() error { if s.client == nil { - return NoLeaseClientErr + return ErrNoLeaseClient } return nil } diff --git a/pkg/steps/pod.go b/pkg/steps/pod.go index 6fcf7762963..44672b58d4e 100644 --- a/pkg/steps/pod.go +++ b/pkg/steps/pod.go @@ -25,7 +25,6 @@ import ( "github.com/openshift/ci-tools/pkg/kubernetes" "github.com/openshift/ci-tools/pkg/results" "github.com/openshift/ci-tools/pkg/util" - podsutils "github.com/openshift/ci-tools/pkg/util" ) const ( @@ -109,7 +108,7 @@ func (s *podStep) run(ctx context.Context) error { } if s.config.NestedPodman { - podsutils.ConfigurePodForNestedPodman(pod, s.name, s.config.As) + util.ConfigurePodForNestedPodman(pod, s.name, s.config.As) if err := s.setupNestedPodmanRBACs(ctx); err != nil { return fmt.Errorf("setup rbac for nested-podman: %w", err) } diff --git a/pkg/steps/release/import_release.go b/pkg/steps/release/import_release.go index 8f2974a7290..303be5ecbef 100644 --- a/pkg/steps/release/import_release.go +++ b/pkg/steps/release/import_release.go @@ -12,7 +12,6 @@ import ( coreapi "k8s.io/api/core/v1" kerrors "k8s.io/apimachinery/pkg/api/errors" - meta "k8s.io/apimachinery/pkg/apis/meta/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/apimachinery/pkg/util/wait" @@ -92,7 +91,7 @@ func (s *importReleaseStep) run(ctx context.Context) error { // create the stable image stream with lookup policy so we have a place to put our imported images newIS := &imagev1.ImageStream{ - ObjectMeta: meta.ObjectMeta{ + ObjectMeta: metav1.ObjectMeta{ Namespace: s.jobSpec.Namespace(), Name: streamName, }, @@ -379,7 +378,7 @@ func (s *importReleaseStep) getCLIImage(ctx context.Context, target, streamName referencePolicy = s.referencePolicy } streamTag := &imagev1.ImageStreamTag{ - ObjectMeta: meta.ObjectMeta{ + ObjectMeta: metav1.ObjectMeta{ Namespace: s.jobSpec.Namespace(), Name: overrideCLIStreamName + ":latest", }, @@ -412,7 +411,7 @@ func (s *importReleaseStep) getCLIImage(ctx context.Context, target, streamName targetCLI := fmt.Sprintf("%s-cli", target) if _, err := steps.RunPod(ctx, s.client, &coreapi.Pod{ - ObjectMeta: meta.ObjectMeta{ + ObjectMeta: metav1.ObjectMeta{ Name: targetCLI, Namespace: s.jobSpec.Namespace(), Labels: map[string]string{Label: s.name}, @@ -450,7 +449,7 @@ func (s *importReleaseStep) getCLIImage(ctx context.Context, target, streamName referencePolicy = s.referencePolicy } streamTag := &imagev1.ImageStreamTag{ - ObjectMeta: meta.ObjectMeta{ + ObjectMeta: metav1.ObjectMeta{ Namespace: s.jobSpec.Namespace(), Name: fmt.Sprintf("%s:cli", streamName), }, diff --git a/pkg/steps/release/release_images.go b/pkg/steps/release/release_images.go index 6b1b8226354..03c3e0c0815 100644 --- a/pkg/steps/release/release_images.go +++ b/pkg/steps/release/release_images.go @@ -105,7 +105,7 @@ func (s *releaseImagesTagStep) Inputs() (api.InputDefinition, error) { func (s *releaseImagesTagStep) Validate() error { if s.integratedStream == nil { - return NilIntegratedStreamError + return ErrNilIntegratedStream } return nil } diff --git a/pkg/steps/release/snapshot.go b/pkg/steps/release/snapshot.go index 0789c546993..77ec4914b89 100644 --- a/pkg/steps/release/snapshot.go +++ b/pkg/steps/release/snapshot.go @@ -35,11 +35,11 @@ func (r *releaseSnapshotStep) Inputs() (api.InputDefinition, error) { return nil, nil } -var NilIntegratedStreamError = errors.New("step snapshot an integrated stream without resolving required information") +var ErrNilIntegratedStream = errors.New("step snapshot an integrated stream without resolving required information") func (r *releaseSnapshotStep) Validate() error { if r.integratedStream == nil { - return NilIntegratedStreamError + return ErrNilIntegratedStream } return nil } diff --git a/pkg/steps/rpm_server.go b/pkg/steps/rpm_server.go index 1ab8d2c2751..ed150fb9675 100644 --- a/pkg/steps/rpm_server.go +++ b/pkg/steps/rpm_server.go @@ -394,7 +394,7 @@ func (s *rpmServerStep) Provides() api.ParameterMap { } ret := make(api.ParameterMap) for _, ref := range refs { - rpmByOrgAndRepo := strings.Replace(fmt.Sprintf("RPM_REPO_%s_%s", strings.ToUpper(ref.Org), strings.ToUpper(ref.Repo)), "-", "_", -1) + rpmByOrgAndRepo := strings.ReplaceAll(fmt.Sprintf("RPM_REPO_%s_%s", strings.ToUpper(ref.Org), strings.ToUpper(ref.Repo)), "-", "_") ret[rpmByOrgAndRepo] = s.rpmRepoURL } return ret diff --git a/pkg/steps/source.go b/pkg/steps/source.go index 94da223f41f..c698a1eef76 100644 --- a/pkg/steps/source.go +++ b/pkg/steps/source.go @@ -303,7 +303,7 @@ func buildFromSource(jobSpec *api.JobSpec, fromTag, toTag api.PipelineImageStrea buildName := string(toTag) // Build names cannot contain '_', but repository names can. When building from a multi-pr config, there could be '_' present in the toTag if strings.Contains(buildName, "_") { - buildName = strings.Replace(buildName, "_", "-", -1) + buildName = strings.ReplaceAll(buildName, "_", "-") logrus.Infof("replacing '_' chars in build name; new name: %s", buildName) } buildResources, err := ResourcesFor(resources.RequirementsForStep(string(toTag))) @@ -430,7 +430,7 @@ func handleFailedBuild(ctx context.Context, client BuildClient, ns, name string, return err } - if !(isInfraReason(b.Status.Reason) || hintsAtInfraReason(b.Status.LogSnippet)) { + if !isInfraReason(b.Status.Reason) && !hintsAtInfraReason(b.Status.LogSnippet) { logrus.Debugf("Build %q (created at %v) classified as legitimate failure, will not be retried", name, b.CreationTimestamp) return err } diff --git a/pkg/steps/template.go b/pkg/steps/template.go index 5de5892272f..100adb6e120 100644 --- a/pkg/steps/template.go +++ b/pkg/steps/template.go @@ -102,7 +102,7 @@ func (s *templateExecutionStep) run(ctx context.Context) error { if err != nil { return fmt.Errorf("could not resolve image format: %w", err) } - s.template.Parameters[i].Value = strings.Replace(format, api.ComponentFormatReplacement, component, -1) + s.template.Parameters[i].Value = strings.ReplaceAll(format, api.ComponentFormatReplacement, component) } } diff --git a/pkg/steps/utils/clusterpool_test.go b/pkg/steps/utils/clusterpool_test.go index dba3970b8c4..94aac66ff53 100644 --- a/pkg/steps/utils/clusterpool_test.go +++ b/pkg/steps/utils/clusterpool_test.go @@ -11,7 +11,6 @@ import ( v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes/scheme" "k8s.io/utils/pointer" - "sigs.k8s.io/controller-runtime/pkg/client" ctrlruntimeclient "sigs.k8s.io/controller-runtime/pkg/client" fakectrlruntimeclient "sigs.k8s.io/controller-runtime/pkg/client/fake" @@ -25,11 +24,11 @@ type fakePoolClient struct { returns []hivev1.ClusterPool } -func (f fakePoolClient) Get(_ context.Context, _ client.ObjectKey, _ client.Object, opts ...client.GetOption) error { +func (f fakePoolClient) Get(_ context.Context, _ ctrlruntimeclient.ObjectKey, _ ctrlruntimeclient.Object, opts ...ctrlruntimeclient.GetOption) error { panic("implement me") } -func (f fakePoolClient) List(_ context.Context, list client.ObjectList, _ ...client.ListOption) error { +func (f fakePoolClient) List(_ context.Context, list ctrlruntimeclient.ObjectList, _ ...ctrlruntimeclient.ListOption) error { l := list.(*hivev1.ClusterPoolList) l.Items = f.returns return nil diff --git a/pkg/steps/write_params.go b/pkg/steps/write_params.go index cb829607a99..9677d86bb09 100644 --- a/pkg/steps/write_params.go +++ b/pkg/steps/write_params.go @@ -46,7 +46,7 @@ func (s *writeParametersStep) run() error { params = append(params, fmt.Sprintf("%s=%s", k, v)) continue } - params = append(params, fmt.Sprintf("%s='%s'", k, strings.Replace(strings.Replace(v, "\\", "\\\\", -1), "'", "\\'", -1))) + params = append(params, fmt.Sprintf("%s='%s'", k, strings.ReplaceAll(strings.ReplaceAll(v, "\\", "\\\\"), "'", "\\'"))) } sort.Strings(params) diff --git a/pkg/testhelper/kubernetes/pod.go b/pkg/testhelper/kubernetes/pod.go index 0ec10ec40cd..900c0f90535 100644 --- a/pkg/testhelper/kubernetes/pod.go +++ b/pkg/testhelper/kubernetes/pod.go @@ -56,7 +56,7 @@ func (f *FakePodExecutor) Get(ctx context.Context, n ctrlruntimeclient.ObjectKey } func (f *FakePodExecutor) Watch(ctx context.Context, list ctrlruntimeclient.ObjectList, opts ...ctrlruntimeclient.ListOption) (watch.Interface, error) { - if err := f.LoggingClient.List(ctx, list, opts...); err != nil { + if err := f.List(ctx, list, opts...); err != nil { return nil, err } filter(list, opts...) diff --git a/pkg/util/imagestreamtagwrapper/imagestreamtagwrapper.go b/pkg/util/imagestreamtagwrapper/imagestreamtagwrapper.go index c369cdf1470..f97b80fa726 100644 --- a/pkg/util/imagestreamtagwrapper/imagestreamtagwrapper.go +++ b/pkg/util/imagestreamtagwrapper/imagestreamtagwrapper.go @@ -15,7 +15,6 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/sets" cache "sigs.k8s.io/controller-runtime/pkg/cache" - "sigs.k8s.io/controller-runtime/pkg/client" ctrlruntimeclient "sigs.k8s.io/controller-runtime/pkg/client" imagegroup "github.com/openshift/api/image" @@ -54,7 +53,7 @@ type imagestreamtagwrapper struct { ctrlruntimeclient.Client } -func (istw *imagestreamtagwrapper) Get(ctx context.Context, key ctrlruntimeclient.ObjectKey, obj ctrlruntimeclient.Object, opts ...client.GetOption) error { +func (istw *imagestreamtagwrapper) Get(ctx context.Context, key ctrlruntimeclient.ObjectKey, obj ctrlruntimeclient.Object, opts ...ctrlruntimeclient.GetOption) error { if imageStreamTag, isImageStreamTag := obj.(*imagev1.ImageStreamTag); isImageStreamTag { return istw.assembleImageStreamTag(ctx, key, imageStreamTag) } diff --git a/pkg/util/rbacs_test.go b/pkg/util/rbacs_test.go index 7adad2c6caf..f97cd2a605b 100644 --- a/pkg/util/rbacs_test.go +++ b/pkg/util/rbacs_test.go @@ -7,7 +7,6 @@ import ( "testing" "time" - coreapi "k8s.io/api/core/v1" v1 "k8s.io/api/core/v1" rbacapi "k8s.io/api/rbac/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" @@ -20,14 +19,14 @@ import ( func TestCreateRBACs(t *testing.T) { testCases := []struct { id string - sa *coreapi.ServiceAccount + sa *v1.ServiceAccount role *rbacapi.Role roleBinding *rbacapi.RoleBinding expectedError string }{ { id: "happy", - sa: &coreapi.ServiceAccount{ObjectMeta: metav1.ObjectMeta{Name: "ci-operator", Namespace: "test-namespace"}}, + sa: &v1.ServiceAccount{ObjectMeta: metav1.ObjectMeta{Name: "ci-operator", Namespace: "test-namespace"}}, role: &rbacapi.Role{ ObjectMeta: metav1.ObjectMeta{Name: "ci-operator-image", Namespace: "test-namespace"}, Rules: []rbacapi.PolicyRule{ @@ -52,7 +51,7 @@ func TestCreateRBACs(t *testing.T) { }, { id: "sad", - sa: &coreapi.ServiceAccount{ObjectMeta: metav1.ObjectMeta{Name: "ci-operator", Namespace: "test-namespace"}}, + sa: &v1.ServiceAccount{ObjectMeta: metav1.ObjectMeta{Name: "ci-operator", Namespace: "test-namespace"}}, role: &rbacapi.Role{ ObjectMeta: metav1.ObjectMeta{Name: "ci-operator-image", Namespace: "test-namespace"}, Rules: []rbacapi.PolicyRule{ @@ -85,7 +84,7 @@ func TestCreateRBACs(t *testing.T) { if tc.expectedError == "" { go func() { if err := wait.Poll(10*time.Millisecond, 100*time.Millisecond, func() (bool, error) { - newSA := &coreapi.ServiceAccount{} + newSA := &v1.ServiceAccount{} if err := client.Get(context.Background(), ctrlruntimeclient.ObjectKey{ Namespace: "test-namespace", Name: "ci-operator", diff --git a/pkg/validation/config.go b/pkg/validation/config.go index 3d5f19de52d..86df3bb051e 100644 --- a/pkg/validation/config.go +++ b/pkg/validation/config.go @@ -206,7 +206,7 @@ func (v *Validator) validateConfiguration(ctx *configContext, config *api.Releas case 1: return fmt.Errorf("invalid configuration: %s", lines[0]) default: - return fmt.Errorf("configuration has %d errors:\n\n * %s\n", len(lines), strings.Join(lines, "\n * ")) + return fmt.Errorf("configuration has %d errors:\n\n * %s", len(lines), strings.Join(lines, "\n * ")) } } diff --git a/pkg/validation/test.go b/pkg/validation/test.go index fa9fe873c2f..f701e45e323 100644 --- a/pkg/validation/test.go +++ b/pkg/validation/test.go @@ -305,7 +305,7 @@ func validateTestStepDependencies(config *api.ReleaseBuildConfiguration) []error if claimRelease != nil { explicitlyConfigured = explicitlyConfigured || releaseName == claimRelease.ReleaseName } - if !(implicitlyConfigured || explicitlyConfigured) { + if !implicitlyConfigured && !explicitlyConfigured { errs = append(errs, validationError(fmt.Sprintf("this dependency requires a %q release, which is not configured", releaseName))) } } @@ -873,7 +873,7 @@ func validateDependencies(fieldRoot string, dependencies []api.StepDependency) [ for i, dependency := range dependencies { if dependency.Name == "" { errs = append(errs, fmt.Errorf("%s.dependencies[%d].name must be set", fieldRoot, i)) - } else if numColons := strings.Count(dependency.Name, ":"); !(numColons == 0 || numColons == 1) { + } else if numColons := strings.Count(dependency.Name, ":"); numColons != 0 && numColons != 1 { errs = append(errs, fmt.Errorf("%s.dependencies[%d].name must take the `tag` or `stream:tag` form, not %q", fieldRoot, i, dependency.Name)) } if dependency.Env == "" { diff --git a/pkg/webreg/graphviz.go b/pkg/webreg/graphviz.go index 0520df7bfcc..1043695ed2e 100644 --- a/pkg/webreg/graphviz.go +++ b/pkg/webreg/graphviz.go @@ -231,7 +231,7 @@ func renderDotFile(dot string) ([]byte, error) { cmd.Stderr = buf out, err := cmd.Output() if execErr, ok := err.(*exec.Error); ok && execErr.Err == exec.ErrNotFound { - return []byte{}, errors.New("The 'dot' binary is not installed") + return []byte{}, errors.New("the 'dot' binary is not installed") } else if err != nil { return out, errors.New(buf.String()) } diff --git a/pkg/webreg/webreg.go b/pkg/webreg/webreg.go index e04f6ca333f..cbafda230c1 100644 --- a/pkg/webreg/webreg.go +++ b/pkg/webreg/webreg.go @@ -1083,7 +1083,7 @@ func WebRegHandler(regAgent agents.RegistryAgent, confAgent agents.ConfigAgent) case "ci-operator-reference": ciOpConfigRefHandler(w) default: - writeErrorPage(w, errors.New("Invalid path"), http.StatusNotImplemented) + writeErrorPage(w, errors.New("invalid path"), http.StatusNotImplemented) } return } else if len(splitURI) == 2 { @@ -1098,11 +1098,11 @@ func WebRegHandler(regAgent agents.RegistryAgent, confAgent agents.ConfigAgent) workflowHandler(regAgent, w, req) return default: - writeErrorPage(w, fmt.Errorf("Component type %s not found", splitURI[0]), http.StatusNotFound) + writeErrorPage(w, fmt.Errorf("component type %s not found", splitURI[0]), http.StatusNotFound) return } } - writeErrorPage(w, errors.New("Invalid path"), http.StatusNotImplemented) + writeErrorPage(w, errors.New("invalid path"), http.StatusNotImplemented) } } @@ -1265,7 +1265,7 @@ func referenceHandler(agent agents.RegistryAgent, w http.ResponseWriter, req *ht name := path.Base(req.URL.Path) page, err := baseTemplate.Clone() if err != nil { - writeErrorPage(w, fmt.Errorf("Failed to render page: %w", err), http.StatusInternalServerError) + writeErrorPage(w, fmt.Errorf("failed to render page: %w", err), http.StatusInternalServerError) return } page, err = page.Funcs( @@ -1285,17 +1285,17 @@ func referenceHandler(agent agents.RegistryAgent, w http.ResponseWriter, req *ht }, ).Parse(referencePage) if err != nil { - writeErrorPage(w, fmt.Errorf("Failed to render page: %w", err), http.StatusInternalServerError) + writeErrorPage(w, fmt.Errorf("failed to render page: %w", err), http.StatusInternalServerError) return } refs, _, _, docs, metadata := agent.GetRegistryComponents() if _, ok := refs[name]; !ok { - writeErrorPage(w, fmt.Errorf("Could not find reference `%s`. If you reached this page via a link provided in the logs of a failed test, the failed step may be a literal defined step, which does not exist in the step registry. Please look at the job info page for the failed test instead.", name), http.StatusNotFound) + writeErrorPage(w, fmt.Errorf("could not find reference `%s`. If you reached this page via a link provided in the logs of a failed test, the failed step may be a literal defined step, which does not exist in the step registry. Please look at the job info page for the failed test instead", name), http.StatusNotFound) return } refMetadataName := fmt.Sprint(name, load.RefSuffix) if _, ok := metadata[refMetadataName]; !ok { - writeErrorPage(w, fmt.Errorf("Could not find metadata for file `%s`. Please contact the Developer Productivity Test Platform.", refMetadataName), http.StatusInternalServerError) + writeErrorPage(w, fmt.Errorf("could not find metadata for file `%s`. Please contact the Developer Productivity Test Platform", refMetadataName), http.StatusInternalServerError) return } ref := struct { @@ -1334,7 +1334,7 @@ func chainHandler(agent agents.RegistryAgent, w http.ResponseWriter, req *http.R refs, chains, _, docs, metadata := agent.GetRegistryComponents() page, err := baseTemplate.Clone() if err != nil { - writeErrorPage(w, fmt.Errorf("Failed to render page: %w", err), http.StatusInternalServerError) + writeErrorPage(w, fmt.Errorf("failed to render page: %w", err), http.StatusInternalServerError) return } page = setDocs(page, docs) @@ -1342,16 +1342,16 @@ func chainHandler(agent agents.RegistryAgent, w http.ResponseWriter, req *http.R page = setChainDependencies(page, refs, chains) page = setChainEnvironment(page, refs, chains) if page, err = page.Parse(chainPage); err != nil { - writeErrorPage(w, fmt.Errorf("Failed to render page: %w", err), http.StatusInternalServerError) + writeErrorPage(w, fmt.Errorf("failed to render page: %w", err), http.StatusInternalServerError) return } if _, ok := chains[name]; !ok { - writeErrorPage(w, fmt.Errorf("Could not find chain %s", name), http.StatusNotFound) + writeErrorPage(w, fmt.Errorf("could not find chain %s", name), http.StatusNotFound) return } chainMetadataName := fmt.Sprint(name, load.ChainSuffix) if _, ok := metadata[chainMetadataName]; !ok { - writeErrorPage(w, fmt.Errorf("Could not find metadata for file `%s`. Please contact the Developer Productivity Test Platform.", chainMetadataName), http.StatusInternalServerError) + writeErrorPage(w, fmt.Errorf("could not find metadata for file `%s`. Please contact the Developer Productivity Test Platform", chainMetadataName), http.StatusInternalServerError) return } chain := struct { @@ -1377,7 +1377,7 @@ func workflowHandler(agent agents.RegistryAgent, w http.ResponseWriter, req *htt refs, chains, workflows, docs, metadata := agent.GetRegistryComponents() page, err := baseTemplate.Clone() if err != nil { - writeErrorPage(w, fmt.Errorf("Failed to render page: %w", err), http.StatusInternalServerError) + writeErrorPage(w, fmt.Errorf("failed to render page: %w", err), http.StatusInternalServerError) return } @@ -1388,16 +1388,16 @@ func workflowHandler(agent agents.RegistryAgent, w http.ResponseWriter, req *htt page = setWorkflowEnvironment(page, refs, chains, workflows) if page, err = page.Parse(workflowJobPage); err != nil { - writeErrorPage(w, fmt.Errorf("Failed to render page: %w", err), http.StatusInternalServerError) + writeErrorPage(w, fmt.Errorf("failed to render page: %w", err), http.StatusInternalServerError) return } if _, ok := workflows[name]; !ok { - writeErrorPage(w, fmt.Errorf("Could not find workflow %s", name), http.StatusNotFound) + writeErrorPage(w, fmt.Errorf("could not find workflow %s", name), http.StatusNotFound) return } workflowMetadataName := fmt.Sprint(name, load.WorkflowSuffix) if _, ok := metadata[workflowMetadataName]; !ok { - writeErrorPage(w, fmt.Errorf("Could not find metadata for file `%s`. Please contact the Developer Productivity Test Platform.", workflowMetadataName), http.StatusInternalServerError) + writeErrorPage(w, fmt.Errorf("could not find metadata for file `%s`. Please contact the Developer Productivity Test Platform", workflowMetadataName), http.StatusInternalServerError) return } workflow := struct { @@ -1422,10 +1422,10 @@ func findConfigForJob(testName string, config api.ReleaseBuildConfiguration) (ap if test.MultiStageTestConfiguration != nil { return *test.MultiStageTestConfiguration, nil } - return api.MultiStageTestConfiguration{}, fmt.Errorf("Provided job %s is not a multi stage type test", testName) + return api.MultiStageTestConfiguration{}, fmt.Errorf("provided job %s is not a multi stage type test", testName) } } - return api.MultiStageTestConfiguration{}, fmt.Errorf("Could not find job %s. Job either does not exist or is not a multi stage test", testName) + return api.MultiStageTestConfiguration{}, fmt.Errorf("could not find job %s. Job either does not exist or is not a multi stage test", testName) } func jobHandler(regAgent agents.RegistryAgent, confAgent agents.ConfigAgent, w http.ResponseWriter, r *http.Request) { @@ -1463,7 +1463,7 @@ func jobHandler(regAgent agents.RegistryAgent, confAgent agents.ConfigAgent, w h page, err := baseTemplate.Clone() if err != nil { - writeErrorPage(w, fmt.Errorf("Failed to render page: %w", err), http.StatusInternalServerError) + writeErrorPage(w, fmt.Errorf("failed to render page: %w", err), http.StatusInternalServerError) return } page = setDocs(page, docs) @@ -1471,7 +1471,7 @@ func jobHandler(regAgent agents.RegistryAgent, confAgent agents.ConfigAgent, w h page = setChainGraph(page, chains) if page, err = page.Parse(workflowJobPage); err != nil { - writeErrorPage(w, fmt.Errorf("Failed to render page: %w", err), http.StatusInternalServerError) + writeErrorPage(w, fmt.Errorf("failed to render page: %w", err), http.StatusInternalServerError) return } workflow := struct { @@ -1610,12 +1610,12 @@ func searchHandler(confAgent agents.ConfigAgent, w http.ResponseWriter, req *htt } page, err := baseTemplate.Clone() if err != nil { - writeErrorPage(w, fmt.Errorf("Failed to render page: %w", err), http.StatusInternalServerError) + writeErrorPage(w, fmt.Errorf("failed to render page: %w", err), http.StatusInternalServerError) return } if page, err = page.Parse(jobSearchPage); err != nil { - writeErrorPage(w, fmt.Errorf("Failed to render page: %w", err), http.StatusInternalServerError) + writeErrorPage(w, fmt.Errorf("failed to render page: %w", err), http.StatusInternalServerError) return } writePage(w, "Job Search Page", page, matches) diff --git a/test/e2e/framework/framework.go b/test/e2e/framework/framework.go index 68901ce3a44..e2a2df727be 100644 --- a/test/e2e/framework/framework.go +++ b/test/e2e/framework/framework.go @@ -141,7 +141,7 @@ func KubernetesClientEnv(t *T) []string { port, portSet := os.LookupEnv("KUBERNETES_SERVICE_PORT") kubeconfig, kubeconfigSet := os.LookupEnv("KUBECONFIG") - if !((hostSet && portSet) || kubeconfigSet) { + if (!hostSet || !portSet) && !kubeconfigSet { t.Fatal("either KUBERNETES_SERVICE_{HOST,PORT} or KUBECONFIG must be set for this test") } diff --git a/test/e2e/pod-scaler/prometheus/prometheus.go b/test/e2e/pod-scaler/prometheus/prometheus.go index db23a15a64f..3a0d5bfa197 100644 --- a/test/e2e/pod-scaler/prometheus/prometheus.go +++ b/test/e2e/pod-scaler/prometheus/prometheus.go @@ -61,7 +61,7 @@ func Initialize(t testhelper.TestingTInterface, tmpDir string, r *rand.Rand, str // restart Prometheus to reload TSDB, by default this can take minutes without a restart prometheusCancel() if err := prometheusInit.Wait(); err != nil { - if exitErr, ok := err.(*exec.ExitError); ok && exitErr.ProcessState.String() == "signal: killed" { + if exitErr, ok := err.(*exec.ExitError); ok && exitErr.String() == "signal: killed" { // this was us killing the process, ignore } else { logrus.WithError(err).Fatalf("Failed to initialize Prometheus: %v: %v", err, prometheusInitOutput.String()) diff --git a/test/e2e/pod-scaler/run/consumer.go b/test/e2e/pod-scaler/run/consumer.go index b6d74fca8cf..14fdb396951 100644 --- a/test/e2e/pod-scaler/run/consumer.go +++ b/test/e2e/pod-scaler/run/consumer.go @@ -47,7 +47,7 @@ func Admission(t testhelper.TestingTInterface, dataDir, kubeconfig string, paren // create mock report credentials credFile := path.Join(t.TempDir(), "credentials") - var content string = ":" + content := ":" err = os.WriteFile(credFile, []byte(content), 0400) if err != nil { t.Fatalf("Failed to create a mock file for report-credentials: %v", err) diff --git a/test/integration/repo-init/expected/core-services/prow/02_config/_config.yaml b/test/integration/repo-init/expected/core-services/prow/02_config/_config.yaml index 3d096d50fdb..129a0ea0aa8 100644 --- a/test/integration/repo-init/expected/core-services/prow/02_config/_config.yaml +++ b/test/integration/repo-init/expected/core-services/prow/02_config/_config.yaml @@ -27,8 +27,11 @@ log_level: info managed_webhooks: auto_accept_invitation: false respect_legacy_global_token: false +moonraker: + client_timeout: 10m0s plank: max_goroutines: 20 + max_revivals: 3 pod_pending_timeout: 10m0s pod_running_timeout: 48h0m0s pod_unscheduled_timeout: 5m0s diff --git a/test/integration/repo-init/input/core-services/prow/02_config/_config.yaml b/test/integration/repo-init/input/core-services/prow/02_config/_config.yaml index 3d096d50fdb..129a0ea0aa8 100644 --- a/test/integration/repo-init/input/core-services/prow/02_config/_config.yaml +++ b/test/integration/repo-init/input/core-services/prow/02_config/_config.yaml @@ -27,8 +27,11 @@ log_level: info managed_webhooks: auto_accept_invitation: false respect_legacy_global_token: false +moonraker: + client_timeout: 10m0s plank: max_goroutines: 20 + max_revivals: 3 pod_pending_timeout: 10m0s pod_running_timeout: 48h0m0s pod_unscheduled_timeout: 5m0s