diff --git a/.golangci.yml b/.golangci.yml index a7820476..d03fb085 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,9 +1,15 @@ linters: - enabled: + enable: - revive - unparam disable: [] +linters-settings: + revive: + rules: + - name: empty-block + disabled: true + issues: exclude-rules: - path: cli/update.go diff --git a/analytics/state_checker.go b/analytics/state_checker.go index 19e4b155..48be22dd 100644 --- a/analytics/state_checker.go +++ b/analytics/state_checker.go @@ -5,19 +5,13 @@ import ( ) const ( - // DisabledEnvKey controls both the old (analytics plugin) and new (v2) implementations DisabledEnvKey = "BITRISE_ANALYTICS_DISABLED" - // V2DisabledEnvKey controls only the new (v2) implementation - V2DisabledEnvKey = "BITRISE_ANALYTICS_V2_DISABLED" - // V2AsyncDisabledEnvKey can be used to disable the default async queries - V2AsyncDisabledEnvKey = "BITRISE_ANALYTICS_V2_ASYNC_DISABLED" trueEnv = "true" ) type StateChecker interface { Enabled() bool - UseAsync() bool } type stateChecker struct { @@ -29,13 +23,5 @@ func NewStateChecker(repository env.Repository) StateChecker { } func (s stateChecker) Enabled() bool { - if s.envRepository.Get(V2DisabledEnvKey) == trueEnv { - return false - } - return s.envRepository.Get(DisabledEnvKey) != trueEnv } - -func (s stateChecker) UseAsync() bool { - return s.envRepository.Get(V2AsyncDisabledEnvKey) != trueEnv -} diff --git a/analytics/tracker.go b/analytics/tracker.go index c1540757..86667399 100644 --- a/analytics/tracker.go +++ b/analytics/tracker.go @@ -57,7 +57,7 @@ const ( timeoutProperty = "timeout" runTimeProperty = "runtime" osProperty = "os" - stackRevIdProperty = "stack_rev_id" + stackRevIDProperty = "stack_rev_id" snapshotProperty = "snapshot" toolVersionsProperty = "tool_versions" @@ -72,8 +72,8 @@ const ( buildSlugEnvKey = "BITRISE_BUILD_SLUG" appSlugEnvKey = "BITRISE_APP_SLUG" StepExecutionIDEnvKey = "BITRISE_STEP_EXECUTION_ID" - stackRevIdKey = "BITRISE_STACK_REV_ID" - macStackRevIdKey = "BITRISE_OSX_STACK_REV_ID" + stackRevIDKey = "BITRISE_STACK_REV_ID" + macStackRevIDKey = "BITRISE_OSX_STACK_REV_ID" bitriseVersionKey = "bitrise" envmanVersionKey = "envman" @@ -108,6 +108,7 @@ type Tracker interface { SendStepFinishedEvent(properties analytics.Properties, result StepResult) SendCLIWarning(message string) SendToolVersionSnapshot(toolVersions, snapshotType string) + IsTracking() bool Wait() } @@ -128,9 +129,6 @@ func NewDefaultTracker() Tracker { logger := log.NewUtilsLogAdapter() tracker := analytics.NewDefaultTracker(&logger) - if stateChecker.UseAsync() { - tracker = analytics.NewDefaultTracker(&logger) - } return NewTracker(tracker, envRepository, stateChecker, &logger) } @@ -210,16 +208,16 @@ func (t tracker) SendToolVersionSnapshot(toolVersions, snapshotType string) { return } - stackRevId := t.envRepository.Get(stackRevIdKey) - if stackRevId == "" { + stackRevID := t.envRepository.Get(stackRevIDKey) + if stackRevID == "" { // Legacy - stackRevId = t.envRepository.Get(macStackRevIdKey) + stackRevID = t.envRepository.Get(macStackRevIDKey) } properties := analytics.Properties{ ciModeProperty: t.envRepository.Get(configs.CIModeEnvKey) == "true", osProperty: runtime.GOOS, - stackRevIdProperty: stackRevId, + stackRevIDProperty: stackRevID, snapshotProperty: snapshotType, toolVersionsProperty: toolVersions, } @@ -278,6 +276,10 @@ func (t tracker) Wait() { t.tracker.Wait() } +func (t tracker) IsTracking() bool { + return t.stateChecker.Enabled() +} + func prepareStartProperties(info StepInfo) analytics.Properties { properties := analytics.Properties{} properties.AppendIfNotEmpty(stepIDProperty, info.StepID) diff --git a/bitrise/setup.go b/bitrise/setup.go index 282cd333..c59f5ae4 100644 --- a/bitrise/setup.go +++ b/bitrise/setup.go @@ -38,10 +38,6 @@ var PluginDependencyMap = map[string]PluginDependency{ Source: "https://github.com/bitrise-io/bitrise-workflow-editor.git", MinVersion: "1.3.305", }, - "analytics": { - Source: "https://github.com/bitrise-io/bitrise-plugins-analytics.git", - MinVersion: "0.13.2", - }, } // RunSetupIfNeeded ... diff --git a/bitrise/util.go b/bitrise/util.go index ecbc2894..5ad03635 100644 --- a/bitrise/util.go +++ b/bitrise/util.go @@ -11,10 +11,8 @@ import ( "github.com/bitrise-io/bitrise/configs" "github.com/bitrise-io/bitrise/log" "github.com/bitrise-io/bitrise/models" - "github.com/bitrise-io/bitrise/tools" envmanModels "github.com/bitrise-io/envman/models" "github.com/bitrise-io/go-utils/command" - "github.com/bitrise-io/go-utils/command/git" "github.com/bitrise-io/go-utils/fileutil" "github.com/bitrise-io/go-utils/pathutil" "github.com/bitrise-io/go-utils/pointers" @@ -212,23 +210,6 @@ func SetBuildFailedEnv(failed bool) error { return os.Setenv("BITRISE_BUILD_STATUS", statusStr) } -// SaveConfigToFile ... -func SaveConfigToFile(pth string, bitriseConf models.BitriseDataModel) error { - contBytes, err := generateYAML(bitriseConf) - if err != nil { - return err - } - return fileutil.WriteBytesToFile(pth, contBytes) -} - -func generateYAML(v interface{}) ([]byte, error) { - bytes, err := yaml.Marshal(v) - if err != nil { - return []byte{}, err - } - return bytes, nil -} - func normalizeValidateFillMissingDefaults(bitriseData *models.BitriseDataModel) ([]string, error) { if err := bitriseData.Normalize(); err != nil { return []string{}, err @@ -328,357 +309,3 @@ func ReadSpecStep(pth string) (stepmanModels.StepModel, error) { return stepModel, nil } - -func getInputByKey(inputs []envmanModels.EnvironmentItemModel, key string) (envmanModels.EnvironmentItemModel, error) { - for _, input := range inputs { - aKey, _, err := input.GetKeyValuePair() - if err != nil { - return envmanModels.EnvironmentItemModel{}, err - } - if aKey == key { - return input, nil - } - } - return envmanModels.EnvironmentItemModel{}, fmt.Errorf("No Environmnet found for key (%s)", key) -} - -func isStringSliceWithSameElements(s1, s2 []string) bool { - if len(s1) != len(s2) { - return false - } - - m := make(map[string]bool, len(s1)) - for _, s := range s1 { - m[s] = true - } - - for _, s := range s2 { - v, found := m[s] - if !found || !v { - return false - } - delete(m, s) - } - return len(m) == 0 -} - -func isDependecyEqual(d1, d2 stepmanModels.DependencyModel) bool { - return (d1.Manager == d2.Manager && d1.Name == d2.Name) -} - -func containsDependecy(m map[stepmanModels.DependencyModel]bool, d1 stepmanModels.DependencyModel) bool { - for d2 := range m { - if isDependecyEqual(d1, d2) { - return true - } - } - return false -} - -func isDependencySliceWithSameElements(s1, s2 []stepmanModels.DependencyModel) bool { - if len(s1) != len(s2) { - return false - } - - m := make(map[stepmanModels.DependencyModel]bool, len(s1)) - for _, s := range s1 { - m[s] = true - } - - for _, d := range s2 { - if containsDependecy(m, d) == false { - return false - } - delete(m, d) - } - return len(m) == 0 -} - -func removeStepDefaultsAndFillStepOutputs(stepListItem *models.StepListItemModel, defaultStepLibSource string) error { - // Create stepIDData - compositeStepIDStr, workflowStep, err := models.GetStepIDStepDataPair(*stepListItem) - if err != nil { - return err - } - stepIDData, err := models.CreateStepIDDataFromString(compositeStepIDStr, defaultStepLibSource) - if err != nil { - return err - } - - // Activate step - get step.yml - tempStepCloneDirPath, err := pathutil.NormalizedOSTempDirPath("step_clone") - if err != nil { - return err - } - tempStepYMLDirPath, err := pathutil.NormalizedOSTempDirPath("step_yml") - if err != nil { - return err - } - tempStepYMLFilePath := filepath.Join(tempStepYMLDirPath, "step.yml") - - if stepIDData.SteplibSource == "path" { - stepAbsLocalPth, err := pathutil.AbsPath(stepIDData.IDorURI) - if err != nil { - return err - } - if err := command.CopyFile(filepath.Join(stepAbsLocalPth, "step.yml"), tempStepYMLFilePath); err != nil { - return err - } - } else if stepIDData.SteplibSource == "git" { - repo, err := git.New(tempStepCloneDirPath) - if err != nil { - return err - } - - var cloneCmd *command.Model - if stepIDData.Version == "" { - cloneCmd = repo.Clone(stepIDData.IDorURI, "--depth=1") - } else { - cloneCmd = repo.CloneTagOrBranch(stepIDData.IDorURI, stepIDData.Version, "--depth=1") - } - if err := cloneCmd.Run(); err != nil { - return err - } - - if err := command.CopyFile(filepath.Join(tempStepCloneDirPath, "step.yml"), tempStepYMLFilePath); err != nil { - return err - } - } else if stepIDData.SteplibSource == "_" { - // Steplib independent steps are completly defined in workflow - tempStepYMLFilePath = "" - } else if stepIDData.SteplibSource != "" { - if err := tools.StepmanSetup(stepIDData.SteplibSource); err != nil { - return err - } - if err := tools.StepmanActivate(stepIDData.SteplibSource, stepIDData.IDorURI, stepIDData.Version, tempStepCloneDirPath, tempStepYMLFilePath); err != nil { - return err - } - } else { - return errors.New("Failed to fill step ouputs: unknown SteplibSource") - } - - // Fill outputs - if tempStepYMLFilePath != "" { - specStep, err := ReadSpecStep(tempStepYMLFilePath) - if err != nil { - return err - } - - if workflowStep.Title != nil && specStep.Title != nil && *workflowStep.Title == *specStep.Title { - workflowStep.Title = nil - } - if workflowStep.Description != nil && specStep.Description != nil && *workflowStep.Description == *specStep.Description { - workflowStep.Description = nil - } - if workflowStep.Summary != nil && specStep.Summary != nil && *workflowStep.Summary == *specStep.Summary { - workflowStep.Summary = nil - } - if workflowStep.Website != nil && specStep.Website != nil && *workflowStep.Website == *specStep.Website { - workflowStep.Website = nil - } - if workflowStep.SourceCodeURL != nil && specStep.SourceCodeURL != nil && *workflowStep.SourceCodeURL == *specStep.SourceCodeURL { - workflowStep.SourceCodeURL = nil - } - if workflowStep.SupportURL != nil && specStep.SupportURL != nil && *workflowStep.SupportURL == *specStep.SupportURL { - workflowStep.SupportURL = nil - } - workflowStep.PublishedAt = nil - if workflowStep.Source != nil && specStep.Source != nil { - if workflowStep.Source.Git == specStep.Source.Git { - workflowStep.Source.Git = "" - } - if workflowStep.Source.Commit == specStep.Source.Commit { - workflowStep.Source.Commit = "" - } - } - if isStringSliceWithSameElements(workflowStep.HostOsTags, specStep.HostOsTags) { - workflowStep.HostOsTags = []string{} - } - if isStringSliceWithSameElements(workflowStep.ProjectTypeTags, specStep.ProjectTypeTags) { - workflowStep.ProjectTypeTags = []string{} - } - if isStringSliceWithSameElements(workflowStep.TypeTags, specStep.TypeTags) { - workflowStep.TypeTags = []string{} - } - if isDependencySliceWithSameElements(workflowStep.Dependencies, specStep.Dependencies) { - workflowStep.Dependencies = []stepmanModels.DependencyModel{} - } - if workflowStep.IsRequiresAdminUser != nil && specStep.IsRequiresAdminUser != nil && *workflowStep.IsRequiresAdminUser == *specStep.IsRequiresAdminUser { - workflowStep.IsRequiresAdminUser = nil - } - if workflowStep.IsAlwaysRun != nil && specStep.IsAlwaysRun != nil && *workflowStep.IsAlwaysRun == *specStep.IsAlwaysRun { - workflowStep.IsAlwaysRun = nil - } - if workflowStep.IsSkippable != nil && specStep.IsSkippable != nil && *workflowStep.IsSkippable == *specStep.IsSkippable { - workflowStep.IsSkippable = nil - } - if workflowStep.RunIf != nil && specStep.RunIf != nil && *workflowStep.RunIf == *specStep.RunIf { - workflowStep.RunIf = nil - } - - inputs := []envmanModels.EnvironmentItemModel{} - for _, input := range workflowStep.Inputs { - sameValue := false - - wfKey, wfValue, err := input.GetKeyValuePair() - if err != nil { - return err - } - - wfOptions, err := input.GetOptions() - if err != nil { - return err - } - - sInput, err := getInputByKey(specStep.Inputs, wfKey) - if err != nil { - return err - } - - _, sValue, err := sInput.GetKeyValuePair() - if err != nil { - return err - } - - if wfValue == sValue { - sameValue = true - } - - sOptions, err := sInput.GetOptions() - if err != nil { - return err - } - - hasOptions := false - - if wfOptions.IsSensitive != nil && sOptions.IsSensitive != nil && *wfOptions.IsSensitive == *sOptions.IsSensitive { - wfOptions.IsSensitive = nil - } else { - hasOptions = true - } - - if wfOptions.IsExpand != nil && sOptions.IsExpand != nil && *wfOptions.IsExpand == *sOptions.IsExpand { - wfOptions.IsExpand = nil - } else { - hasOptions = true - } - - if wfOptions.SkipIfEmpty != nil && sOptions.SkipIfEmpty != nil && *wfOptions.SkipIfEmpty == *sOptions.SkipIfEmpty { - wfOptions.SkipIfEmpty = nil - } else { - hasOptions = true - } - - if wfOptions.Title != nil && sOptions.Title != nil && *wfOptions.Title == *sOptions.Title { - wfOptions.Title = nil - } else { - hasOptions = true - } - - if wfOptions.Description != nil && sOptions.Description != nil && *wfOptions.Description == *sOptions.Description { - wfOptions.Description = nil - } else { - hasOptions = true - } - - if wfOptions.Summary != nil && sOptions.Summary != nil && *wfOptions.Summary == *sOptions.Summary { - wfOptions.Summary = nil - } else { - hasOptions = true - } - - if wfOptions.Category != nil && sOptions.Category != nil && *wfOptions.Category == *sOptions.Category { - wfOptions.Category = nil - } else { - hasOptions = true - } - - if isStringSliceWithSameElements(wfOptions.ValueOptions, sOptions.ValueOptions) { - wfOptions.ValueOptions = []string{} - } else { - hasOptions = true - } - - if wfOptions.IsRequired != nil && sOptions.IsRequired != nil && *wfOptions.IsRequired == *sOptions.IsRequired { - wfOptions.IsRequired = nil - } else { - hasOptions = true - } - - if wfOptions.IsDontChangeValue != nil && sOptions.IsDontChangeValue != nil && *wfOptions.IsDontChangeValue == *sOptions.IsDontChangeValue { - wfOptions.IsDontChangeValue = nil - } else { - hasOptions = true - } - - if wfOptions.IsTemplate != nil && sOptions.IsTemplate != nil && *wfOptions.IsTemplate == *sOptions.IsTemplate { - wfOptions.IsTemplate = nil - } else { - hasOptions = true - } - - if !hasOptions && sameValue { - // default env - } else { - if hasOptions { - input[envmanModels.OptionsKey] = wfOptions - } else { - delete(input, envmanModels.OptionsKey) - } - - inputs = append(inputs, input) - } - } - - workflowStep.Inputs = inputs - - // We need only key-value and title from spec outputs - outputs := []envmanModels.EnvironmentItemModel{} - for _, output := range specStep.Outputs { - sKey, sValue, err := output.GetKeyValuePair() - if err != nil { - return err - } - - sOptions, err := output.GetOptions() - if err != nil { - return err - } - - newOutput := envmanModels.EnvironmentItemModel{ - sKey: sValue, - envmanModels.OptionsKey: envmanModels.EnvironmentItemOptionsModel{ - Title: sOptions.Title, - }, - } - - outputs = append(outputs, newOutput) - } - - workflowStep.Outputs = outputs - - (*stepListItem)[compositeStepIDStr] = workflowStep - } - - // Cleanup - if err := command.RemoveDir(tempStepCloneDirPath); err != nil { - return errors.New(fmt.Sprint("Failed to remove step clone dir: ", err)) - } - if err := command.RemoveDir(tempStepYMLDirPath); err != nil { - return errors.New(fmt.Sprint("Failed to remove step clone dir: ", err)) - } - - return nil -} - -// RemoveConfigRedundantFieldsAndFillStepOutputs ... -func RemoveConfigRedundantFieldsAndFillStepOutputs(config *models.BitriseDataModel) error { - for _, workflow := range config.Workflows { - for _, stepListItem := range workflow.Steps { - if err := removeStepDefaultsAndFillStepOutputs(&stepListItem, config.DefaultStepLibSource); err != nil { - return err - } - } - } - return config.RemoveRedundantFields() -} diff --git a/bitrise/util_test.go b/bitrise/util_test.go index 4e2d333b..ae46e872 100644 --- a/bitrise/util_test.go +++ b/bitrise/util_test.go @@ -4,9 +4,7 @@ import ( "encoding/json" "testing" - "github.com/bitrise-io/bitrise/configs" envmanModels "github.com/bitrise-io/envman/models" - stepmanModels "github.com/bitrise-io/stepman/models" "github.com/stretchr/testify/require" ) @@ -73,149 +71,6 @@ func TestApplyOutputAliases(t *testing.T) { } } -func TestRemoveConfigRedundantFieldsAndFillStepOutputs(t *testing.T) { - // setup - require.NoError(t, configs.InitPaths()) - - configStr := ` - format_version: 1.3.0 - default_step_lib_source: "https://github.com/bitrise-io/bitrise-steplib.git" - - workflows: - remove_test: - steps: - - script: - inputs: - - content: | - #!/bin/bash - set -v - exit 2 - opts: - is_expand: true - - timestamp: - title: Generate timestamps - ` - - config, warnings, err := ConfigModelFromYAMLBytes([]byte(configStr)) - require.Equal(t, nil, err) - require.Equal(t, 0, len(warnings)) - - require.Equal(t, nil, RemoveConfigRedundantFieldsAndFillStepOutputs(&config)) - - for workflowID, workflow := range config.Workflows { - if workflowID == "remove_test" { - for _, stepListItem := range workflow.Steps { - for stepID, step := range stepListItem { - if stepID == "script" { - for _, input := range step.Inputs { - key, _, err := input.GetKeyValuePair() - require.Equal(t, nil, err) - - if key == "content" { - opts, err := input.GetOptions() - require.Equal(t, nil, err) - - // script content should keep is_expand: true, because it's different from spec default - require.Equal(t, true, *opts.IsExpand) - } - } - } else if stepID == "timestamp" { - // timestamp title should be nil, because it's the same as spec value - require.Equal(t, (*string)(nil), step.Title) - - for _, output := range step.Outputs { - key, _, err := output.GetKeyValuePair() - require.Equal(t, nil, err) - - if key == "UNIX_TIMESTAMP" { - // timestamp outputs should filled with key-value & opts.Title - opts, err := output.GetOptions() - require.Equal(t, nil, err) - - require.Equal(t, "unix style", *opts.Title) - require.Equal(t, (*bool)(nil), opts.IsExpand) - require.Equal(t, (*bool)(nil), opts.IsDontChangeValue) - require.Equal(t, (*bool)(nil), opts.IsRequired) - } - } - } - } - } - } - } - - // timestamp outputs should filled with key-value & opts.Title - -} - -func TestSsStringSliceWithSameElements(t *testing.T) { - s1 := []string{} - s2 := []string{} - require.Equal(t, true, isStringSliceWithSameElements(s1, s2)) - - s1 = []string{"1", "2", "3"} - s2 = []string{"2", "1"} - require.Equal(t, false, isStringSliceWithSameElements(s1, s2)) - - s2 = append(s2, "3") - require.Equal(t, true, isStringSliceWithSameElements(s1, s2)) - - s2 = []string{"1,", "1,", "1"} - require.Equal(t, false, isStringSliceWithSameElements(s1, s2)) -} - -func TestIsDependecyEqual(t *testing.T) { - d1 := stepmanModels.DependencyModel{Manager: "manager", Name: "dep"} - d2 := stepmanModels.DependencyModel{Manager: "manager", Name: "dep"} - - require.Equal(t, true, isDependecyEqual(d1, d2)) - - d1 = stepmanModels.DependencyModel{Manager: "manager", Name: "dep1"} - d2 = stepmanModels.DependencyModel{Manager: "manager", Name: "dep"} - - require.Equal(t, false, isDependecyEqual(d1, d2)) - - d1 = stepmanModels.DependencyModel{Manager: "manager", Name: "dep"} - d2 = stepmanModels.DependencyModel{Manager: "manager1", Name: "dep"} - - require.Equal(t, false, isDependecyEqual(d1, d2)) -} - -func TestContainsDependecy(t *testing.T) { - d1 := stepmanModels.DependencyModel{Manager: "manager", Name: "dep1"} - d2 := stepmanModels.DependencyModel{Manager: "manager", Name: "dep2"} - d3 := stepmanModels.DependencyModel{Manager: "manager1", Name: "dep3"} - - m := map[stepmanModels.DependencyModel]bool{ - d1: false, - d2: true, - } - - require.Equal(t, true, containsDependecy(m, d1)) - - require.Equal(t, false, containsDependecy(m, d3)) -} - -func TestIsDependencySliceWithSameElements(t *testing.T) { - s1 := []stepmanModels.DependencyModel{} - s2 := []stepmanModels.DependencyModel{} - require.Equal(t, true, isDependencySliceWithSameElements(s1, s2)) - - d1 := stepmanModels.DependencyModel{Manager: "manager", Name: "dep1"} - d2 := stepmanModels.DependencyModel{Manager: "manager", Name: "dep2"} - d3 := stepmanModels.DependencyModel{Manager: "manager1", Name: "dep3"} - - s1 = []stepmanModels.DependencyModel{d1, d2, d3} - s2 = []stepmanModels.DependencyModel{d2, d1} - require.Equal(t, false, isDependencySliceWithSameElements(s1, s2)) - - s2 = append(s2, d3) - require.Equal(t, true, isDependencySliceWithSameElements(s1, s2)) - - s2 = []stepmanModels.DependencyModel{d1, d1, d1} - require.Equal(t, false, isDependencySliceWithSameElements(s1, s2)) -} - func TestConfigModelFromYAMLBytes(t *testing.T) { configStr := ` format_version: 1.3.0 diff --git a/cli/agent.go b/cli/agent.go index c256a653..2a4ba1a3 100644 --- a/cli/agent.go +++ b/cli/agent.go @@ -34,7 +34,7 @@ func registerAgentOverrides(dirs configs.BitriseDirs) error { envKey: configs.BitriseTestDeployDirEnvKey, }, { - dir: dirs.HtmlReportDir, + dir: dirs.HTMLReportDir, envKey: configs.BitriseHtmlReportDirEnvKey, }, } diff --git a/cli/agent_test.go b/cli/agent_test.go index 6b228470..e550698e 100644 --- a/cli/agent_test.go +++ b/cli/agent_test.go @@ -3,7 +3,7 @@ package cli import ( "errors" "io/fs" - "io/ioutil" + "os" "path/filepath" "testing" @@ -22,7 +22,7 @@ func TestCleanupDirs(t *testing.T) { name: "Clean existing file", dirs: []string{filepath.Join(tmpDir, "file")}, prepareFn: func() { - err := ioutil.WriteFile(filepath.Join(tmpDir, "file"), []byte("file"), 0644) + err := os.WriteFile(filepath.Join(tmpDir, "file"), []byte("file"), 0644) require.NoError(t, err) }, wantErr: false, @@ -31,9 +31,9 @@ func TestCleanupDirs(t *testing.T) { name: "Clean existing directory", dirs: []string{filepath.Join(tmpDir, "dir")}, prepareFn: func() { - err := ioutil.WriteFile(filepath.Join(tmpDir, "dir", "file1"), []byte("file1"), 0644) + err := os.WriteFile(filepath.Join(tmpDir, "dir", "file1"), []byte("file1"), 0644) require.NoError(t, err) - err = ioutil.WriteFile(filepath.Join(tmpDir, "dir", "file2"), []byte("file2"), 0644) + err = os.WriteFile(filepath.Join(tmpDir, "dir", "file2"), []byte("file2"), 0644) require.NoError(t, err) }, wantErr: false, @@ -63,9 +63,9 @@ func TestCleanupDirs(t *testing.T) { t.Setenv("BITRISE_TEST_DEPLOY_DIR", dir1) t.Setenv("BITRISE_DEPLOY_DIR", dir2) - err := ioutil.WriteFile(filepath.Join(dir1, "file1"), []byte("file1"), 0644) + err := os.WriteFile(filepath.Join(dir1, "file1"), []byte("file1"), 0644) require.NoError(t, err) - err = ioutil.WriteFile(filepath.Join(dir2, "file1"), []byte("file2"), 0644) + err = os.WriteFile(filepath.Join(dir2, "file1"), []byte("file2"), 0644) require.NoError(t, err) }, wantErr: false, @@ -81,7 +81,7 @@ func TestCleanupDirs(t *testing.T) { } for _, dir := range tc.dirs { - _, err := ioutil.ReadDir(dir) + _, err := os.ReadDir(dir) if err != nil && !errors.Is(err, fs.ErrNotExist) { t.Errorf("Unexpected error: %v", err) } diff --git a/cli/build_run_result_collector.go b/cli/build_run_result_collector.go index 841701cd..0ca36ae9 100644 --- a/cli/build_run_result_collector.go +++ b/cli/build_run_result_collector.go @@ -134,12 +134,12 @@ func (r buildRunResultCollector) registerStepRunResults( logStepFinished(stepResults, stepExecutionId, isLastStep) } -func logStepFinished(stepResults models.StepRunResultsModel, stepExecutionId string, isLastStep bool) { - params := stepFinishedParamsFromResults(stepResults, stepExecutionId, isLastStep) +func logStepFinished(stepResults models.StepRunResultsModel, stepExecutionID string, isLastStep bool) { + params := stepFinishedParamsFromResults(stepResults, stepExecutionID, isLastStep) log.PrintStepFinishedEvent(params) } -func stepFinishedParamsFromResults(results models.StepRunResultsModel, stepExecutionId string, isLastStep bool) log.StepFinishedParams { +func stepFinishedParamsFromResults(results models.StepRunResultsModel, stepExecutionID string, isLastStep bool) log.StepFinishedParams { title := "" if results.StepInfo.Step.Title != nil { title = *results.StepInfo.Step.Title @@ -175,7 +175,7 @@ func stepFinishedParamsFromResults(results models.StepRunResultsModel, stepExecu } params := log.StepFinishedParams{ - ExecutionId: stepExecutionId, + ExecutionID: stepExecutionID, Status: results.Status.String(), Title: title, RunTime: results.RunTime.Milliseconds(), diff --git a/cli/commands.go b/cli/commands.go index 8c8213cf..f21f651a 100644 --- a/cli/commands.go +++ b/cli/commands.go @@ -75,49 +75,6 @@ var ( }, }, triggerCommand, - { - Name: "export", - Usage: "Export the bitrise configuration.", - Action: export, - Flags: []cli.Flag{ - flConfig, - flConfigBase64, - flFormat, - flOutputPath, - flPretty, - }, - }, - { - Name: "normalize", - Usage: "Normalize the bitrise configuration.", - Action: normalize, - Flags: []cli.Flag{ - flConfig, - flConfigBase64, - }, - }, - { - Name: "step-list", - Usage: "List of available steps.", - Action: stepList, - Flags: []cli.Flag{ - flCollection, - flFormat, - }, - }, - { - Name: "step-info", - Aliases: []string{"i"}, - Usage: "Provides information (step ID, last version, given version) about specified step.", - Action: stepInfo, - Flags: []cli.Flag{ - flCollection, - flVersion, - flFormat, - flShort, - flStepYML, - }, - }, workflowListCommand, { Name: "share", diff --git a/cli/docker/container_manager.go b/cli/docker/container_manager.go index 8474ffb8..d61872bc 100644 --- a/cli/docker/container_manager.go +++ b/cli/docker/container_manager.go @@ -56,7 +56,7 @@ func (rc *RunningContainer) ExecuteCommandArgs(envs []string) []string { const bitriseNetwork = "bitrise" type ContainerManager struct { - logger DockerLogger + logger Logger workflowContainers map[string]*RunningContainer serviceContainers map[string][]*RunningContainer client *client.Client @@ -65,30 +65,30 @@ type ContainerManager struct { released bool } -type DockerLogger struct { +type Logger struct { logger log.Logger secrets []string } -func (dl *DockerLogger) Infof(format string, args ...interface{}) { +func (dl *Logger) Infof(format string, args ...interface{}) { log := fmt.Sprintf(format, args...) redacted, _ := dl.Redact(log) dl.logger.Info(redacted) } -func (dl *DockerLogger) Errorf(format string, args ...interface{}) { +func (dl *Logger) Errorf(format string, args ...interface{}) { log := fmt.Sprintf(format, args...) redacted, _ := dl.Redact(log) dl.logger.Error(redacted) } -func (dl *DockerLogger) Warnf(format string, args ...interface{}) { +func (dl *Logger) Warnf(format string, args ...interface{}) { log := fmt.Sprintf(format, args...) redacted, _ := dl.Redact(log) dl.logger.Warn(redacted) } -func (dl *DockerLogger) Redact(s string) (string, error) { +func (dl *Logger) Redact(s string) (string, error) { src := bytes.NewReader([]byte(s)) dstBuf := new(bytes.Buffer) logger := log.NewUtilsLogAdapter() @@ -112,7 +112,7 @@ func NewContainerManager(logger log.Logger, secrets []string) *ContainerManager } return &ContainerManager{ - logger: DockerLogger{ + logger: Logger{ logger: logger, secrets: secrets, }, diff --git a/cli/docker/environment_source.go b/cli/docker/environment_source.go index d2d3d46b..5438ea4d 100644 --- a/cli/docker/environment_source.go +++ b/cli/docker/environment_source.go @@ -8,7 +8,7 @@ import ( ) // implementing env.EnvironmentSource -type DockerEnvironmentSource struct { +type EnvironmentSource struct { Logger log.Logger } @@ -20,7 +20,7 @@ type DockerEnvironmentSource struct { // containers (for instance Java). // Instead, we have our own implementation, filtering for envs that are whitelisted, and that are the envs // starting with BITRISE_, and additionally the PATH, PR, CI and ENVMAN_ENVSTORE_PATH envs. -func (des *DockerEnvironmentSource) GetEnvironment() map[string]string { +func (des *EnvironmentSource) GetEnvironment() map[string]string { passthroughEnvsList := strings.Split(os.Getenv("BITRISE_DOCKER_PASSTHROUGH_ENVS"), ",") passthroughEnvsList = append(passthroughEnvsList, "PATH", "PR", "CI", "ENVMAN_ENVSTORE_PATH") dockerPassthroughEnvsMap := make(map[string]bool) @@ -50,7 +50,7 @@ func (des *DockerEnvironmentSource) GetEnvironment() map[string]string { } // SplitEnv splits an env returned by os.Environ -func (des *DockerEnvironmentSource) splitEnv(env string) (key string, value string) { +func (des *EnvironmentSource) splitEnv(env string) (key string, value string) { const sep = "=" split := strings.SplitAfterN(env, sep, 2) if split == nil { diff --git a/cli/export.go b/cli/export.go deleted file mode 100644 index 157e2c90..00000000 --- a/cli/export.go +++ /dev/null @@ -1,72 +0,0 @@ -package cli - -import ( - "encoding/json" - - "github.com/bitrise-io/bitrise/log" - "github.com/bitrise-io/bitrise/output" - "github.com/bitrise-io/go-utils/fileutil" - "github.com/urfave/cli" - "gopkg.in/yaml.v2" -) - -func export(c *cli.Context) error { - // Expand cli.Context - bitriseConfigBase64Data := c.String(ConfigBase64Key) - - bitriseConfigPath := c.String(ConfigKey) - - outfilePth := c.String(OuputPathKey) - outFormat := c.String(OuputFormatKey) - prettyFormat := c.Bool(PrettyFormatKey) - // - - if outfilePth == "" { - showSubcommandHelp(c) - failf("No output file path specified!") - } - - if outFormat == "" { - showSubcommandHelp(c) - failf("No output format format specified!") - } - - // Config validation - bitriseConfig, warnings, err := CreateBitriseConfigFromCLIParams(bitriseConfigBase64Data, bitriseConfigPath) - for _, warning := range warnings { - log.Warnf("warning: %s", warning) - } - if err != nil { - showSubcommandHelp(c) - failf("Failed to create bitrise config, error: %s", err) - } - - // serialize - configBytes := []byte{} - if outFormat == output.FormatJSON { - if prettyFormat { - configBytes, err = json.MarshalIndent(bitriseConfig, "", "\t") - } else { - configBytes, err = json.Marshal(bitriseConfig) - } - if err != nil { - failf("Failed to generate config JSON, error: %s", err) - } - } else if outFormat == output.FormatYML { - configBytes, err = yaml.Marshal(bitriseConfig) - if err != nil { - failf("Failed to generate config YML, error: %s", err) - } - } else { - failf("Invalid output format: %s", outFormat) - } - - // write to file - if err := fileutil.WriteBytesToFile(outfilePth, configBytes); err != nil { - failf("Failed to write file (%s), error: %s", outfilePth, err) - } - - log.Infof("Done, saved to path: %s", outfilePth) - - return nil -} diff --git a/cli/normalize.go b/cli/normalize.go deleted file mode 100644 index 897ac166..00000000 --- a/cli/normalize.go +++ /dev/null @@ -1,45 +0,0 @@ -package cli - -import ( - "github.com/bitrise-io/bitrise/bitrise" - "github.com/bitrise-io/bitrise/log" - "github.com/urfave/cli" -) - -func normalize(c *cli.Context) error { - // Expand cli.Context - bitriseConfigBase64Data := c.String(ConfigBase64Key) - - bitriseConfigPath := c.String(ConfigKey) - // - - // Input validation - bitriseConfigPath, err := GetBitriseConfigFilePath(bitriseConfigPath) - if err != nil { - failf("Failed to get bitrise config path, error: %s", err) - } - if bitriseConfigPath == "" { - failf("No bitrise config path defined!") - } - - // Config validation - bitriseConfig, warnings, err := CreateBitriseConfigFromCLIParams(bitriseConfigBase64Data, bitriseConfigPath) - for _, warning := range warnings { - log.Warnf("warning: %s", warning) - } - if err != nil { - failf("Failed to create bitrise config, error: %s", err) - } - - // Normalize - if err := bitrise.RemoveConfigRedundantFieldsAndFillStepOutputs(&bitriseConfig); err != nil { - failf("Failed to remove redundant fields, error: %s", err) - } - if err := bitrise.SaveConfigToFile(bitriseConfigPath, bitriseConfig); err != nil { - failf("Failed to save config to file, error: %s", err) - } - - log.Info("Redundant fields removed") - - return nil -} diff --git a/cli/run.go b/cli/run.go index 7557111d..61febf28 100644 --- a/cli/run.go +++ b/cli/run.go @@ -40,9 +40,9 @@ const ( secretFilteringFlag = "secret-filtering" ) -var workflowNotSpecifiedErr = errors.New("workflow not specified") -var utilityWorkflowSpecifiedErr = errors.New("utility workflow specified") -var workflowRunFailedErr = errors.New("workflow run failed") +var errWorkflowNotSpecified = errors.New("workflow not specified") +var errUtilityWorkflowSpecified = errors.New("utility workflow specified") +var errWorkflowRunFailed = errors.New("workflow run failed") type RunConfig struct { Modes models.WorkflowRunModes @@ -84,12 +84,12 @@ func run(c *cli.Context) error { config, err := processArgs(c) if err != nil { - if err == workflowNotSpecifiedErr { + if err == errWorkflowNotSpecified { if config != nil { printAvailableWorkflows(config.Config) } failf("No workflow specified") - } else if err == utilityWorkflowSpecifiedErr { + } else if err == errUtilityWorkflowSpecified { printAboutUtilityWorkflowsText() failf("Utility workflows can't be triggered directly") } @@ -124,7 +124,7 @@ func run(c *cli.Context) error { if shouldWaitForCleanup { <-cleanupSynchronCtx.Done() } - if err == workflowRunFailedErr { + if err == errWorkflowRunFailed { msg := createWorkflowRunStatusMessage(exitCode) printWorkflowRunStatusMessage(msg) analytics.LogMessage("info", "bitrise-cli", "exit", map[string]interface{}{"build_slug": os.Getenv("BITRISE_BUILD_SLUG")}, msg) @@ -187,7 +187,7 @@ func NewWorkflowRunner(config RunConfig, agentConfig *configs.AgentConfig) Workf func (r WorkflowRunner) RunWorkflowsWithSetupAndCheckForUpdate() (int, error) { if r.config.Workflow == "" { - return 1, workflowNotSpecifiedErr + return 1, errWorkflowNotSpecified } _, exist := r.config.Config.Workflows[r.config.Workflow] if !exist { @@ -223,7 +223,7 @@ func (r WorkflowRunner) RunWorkflowsWithSetupAndCheckForUpdate() (int, error) { if buildRunResults, err := r.runWorkflows(tracker); err != nil { return 1, fmt.Errorf("failed to run workflow: %s", err) } else if buildRunResults.IsBuildFailed() { - return buildRunResults.ExitCode(), workflowRunFailedErr + return buildRunResults.ExitCode(), errWorkflowRunFailed } if err := checkUpdate(); err != nil { @@ -312,6 +312,14 @@ func (r WorkflowRunner) runWorkflows(tracker analytics.Tracker) (models.BuildRun log.PrintBitriseStartedEvent(plan) + if tracker.IsTracking() { + log.Print() + log.Print("Bitrise collects anonymous usage stats to improve the product, detect and respond to Step error conditions.") + env := fmt.Sprintf("%s=%s", analytics.DisabledEnvKey, "true") + log.Printf("If you want to opt out, define the env var %s", colorstring.Cyan(env)) + log.Print() + } + // Run workflows for i, workflowRunPlan := range plan.ExecutionPlan { isLastWorkflow := i == len(plan.ExecutionPlan)-1 @@ -385,10 +393,10 @@ func processArgs(c *cli.Context) (*RunConfig, error) { } if runParams.WorkflowToRunID == "" { - return nil, workflowNotSpecifiedErr + return nil, errWorkflowNotSpecified } if strings.HasPrefix(runParams.WorkflowToRunID, "_") { - return nil, utilityWorkflowSpecifiedErr + return nil, errUtilityWorkflowSpecified } inventoryEnvironments, err := CreateInventoryFromCLIParams(runParams.InventoryBase64Data, runParams.InventoryPath) diff --git a/cli/run_test.go b/cli/run_test.go index aa4cf498..b132dd84 100644 --- a/cli/run_test.go +++ b/cli/run_test.go @@ -1732,3 +1732,4 @@ func (n noOpTracker) SendWorkflowStarted(analytics.Properties, string, string) func (n noOpTracker) SendWorkflowFinished(analytics.Properties, bool) {} func (n noOpTracker) SendToolVersionSnapshot(string, string) {} func (n noOpTracker) Wait() {} +func (n noOpTracker) IsTracking() bool { return false } diff --git a/cli/run_trigger_params_test.go b/cli/run_trigger_params_test.go index 77b06437..91e3fd8e 100644 --- a/cli/run_trigger_params_test.go +++ b/cli/run_trigger_params_test.go @@ -9,7 +9,7 @@ import ( "github.com/stretchr/testify/require" ) -func toBase64(t *testing.T, str string) string { +func toBase64(str string) string { bytes := base64.StdEncoding.EncodeToString([]byte(str)) return string(bytes) } @@ -36,10 +36,10 @@ func TestParseRunAndTriggerJSONParams(t *testing.T) { OuputFormatKey: "json", ConfigKey: "bitrise.yml", - ConfigBase64Key: toBase64(t, "bitrise.yml"), + ConfigBase64Key: toBase64("bitrise.yml"), InventoryKey: ".secrets.bitrise.yml", - InventoryBase64Key: toBase64(t, ".secrets.bitrise.yml"), + InventoryBase64Key: toBase64(".secrets.bitrise.yml"), } params, err := parseRunAndTriggerJSONParams(toJSON(t, paramsMap)) require.NoError(t, err) @@ -56,10 +56,10 @@ func TestParseRunAndTriggerJSONParams(t *testing.T) { require.Equal(t, "json", params.Format) require.Equal(t, "bitrise.yml", params.BitriseConfigPath) - require.Equal(t, toBase64(t, "bitrise.yml"), params.BitriseConfigBase64Data) + require.Equal(t, toBase64("bitrise.yml"), params.BitriseConfigBase64Data) require.Equal(t, ".secrets.bitrise.yml", params.InventoryPath) - require.Equal(t, toBase64(t, ".secrets.bitrise.yml"), params.InventoryBase64Data) + require.Equal(t, toBase64(".secrets.bitrise.yml"), params.InventoryBase64Data) } t.Log("it fails for invalid json") @@ -99,10 +99,10 @@ func TestParseRunAndTriggerParams(t *testing.T) { format := "json" bitriseConfigPath := "bitrise.yml" - bitriseConfigBase64Data := toBase64(t, "bitrise.yml") + bitriseConfigBase64Data := toBase64("bitrise.yml") inventoryPath := ".secrets.bitrise.yml" - inventoryBase64Data := toBase64(t, ".secrets.bitrise.yml") + inventoryBase64Data := toBase64(".secrets.bitrise.yml") jsonParams := "" base64JSONParams := "" @@ -149,10 +149,10 @@ func TestParseRunAndTriggerParams(t *testing.T) { format := "json" bitriseConfigPath := "bitrise.yml" - bitriseConfigBase64Data := toBase64(t, "bitrise.yml") + bitriseConfigBase64Data := toBase64("bitrise.yml") inventoryPath := ".secrets.bitrise.yml" - inventoryBase64Data := toBase64(t, ".secrets.bitrise.yml") + inventoryBase64Data := toBase64(".secrets.bitrise.yml") paramsMap := map[string]interface{}{ WorkflowKey: workflow, @@ -209,10 +209,10 @@ func TestParseRunAndTriggerParams(t *testing.T) { format := "json" bitriseConfigPath := "bitrise.yml" - bitriseConfigBase64Data := toBase64(t, "bitrise.yml") + bitriseConfigBase64Data := toBase64("bitrise.yml") inventoryPath := ".secrets.bitrise.yml" - inventoryBase64Data := toBase64(t, ".secrets.bitrise.yml") + inventoryBase64Data := toBase64(".secrets.bitrise.yml") paramsMap := map[string]interface{}{ WorkflowKey: workflow, @@ -233,7 +233,7 @@ func TestParseRunAndTriggerParams(t *testing.T) { } jsonParams := "" - base64JSONParams := toBase64(t, toJSON(t, paramsMap)) + base64JSONParams := toBase64(toJSON(t, paramsMap)) params, err := parseRunAndTriggerParams("", "", "", "", "", "", "", "", "", "", "", "", jsonParams, base64JSONParams) require.NoError(t, err) @@ -269,10 +269,10 @@ func TestParseRunAndTriggerParams(t *testing.T) { format := "json" bitriseConfigPath := "bitrise.yml" - bitriseConfigBase64Data := toBase64(t, "bitrise.yml") + bitriseConfigBase64Data := toBase64("bitrise.yml") inventoryPath := ".secrets.bitrise.yml" - inventoryBase64Data := toBase64(t, ".secrets.bitrise.yml") + inventoryBase64Data := toBase64(".secrets.bitrise.yml") paramsMap := map[string]interface{}{ WorkflowKey: workflow, @@ -293,7 +293,7 @@ func TestParseRunAndTriggerParams(t *testing.T) { } jsonParams := `{"workflow":"test","pr-ready-state":"draft"}` - base64JSONParams := toBase64(t, toJSON(t, paramsMap)) + base64JSONParams := toBase64(toJSON(t, paramsMap)) params, err := parseRunAndTriggerParams("", "", "", "", "", "", "", "", "", "", "", "", jsonParams, base64JSONParams) require.NoError(t, err) @@ -329,10 +329,10 @@ func TestParseRunAndTriggerParams(t *testing.T) { format := "json" bitriseConfigPath := "bitrise.yml" - bitriseConfigBase64Data := toBase64(t, "bitrise.yml") + bitriseConfigBase64Data := toBase64("bitrise.yml") inventoryPath := ".secrets.bitrise.yml" - inventoryBase64Data := toBase64(t, ".secrets.bitrise.yml") + inventoryBase64Data := toBase64(".secrets.bitrise.yml") jsonParams := `{"workflow":"test","pattern":"feature/","config":"test.bitrise.yml","inventory":".test.secrets.bitrise.yml"}` base64JSONParams := "" @@ -373,10 +373,10 @@ func TestParseRunParams(t *testing.T) { workflow := "primary" bitriseConfigPath := "bitrise.yml" - bitriseConfigBase64Data := toBase64(t, "bitrise.yml") + bitriseConfigBase64Data := toBase64("bitrise.yml") inventoryPath := ".secrets.bitrise.yml" - inventoryBase64Data := toBase64(t, ".secrets.bitrise.yml") + inventoryBase64Data := toBase64(".secrets.bitrise.yml") jsonParams := "" base64JSONParams := "" @@ -419,10 +419,10 @@ func TestParseTriggerParams(t *testing.T) { tag := "0.9.0" bitriseConfigPath := "bitrise.yml" - bitriseConfigBase64Data := toBase64(t, "bitrise.yml") + bitriseConfigBase64Data := toBase64("bitrise.yml") inventoryPath := ".secrets.bitrise.yml" - inventoryBase64Data := toBase64(t, ".secrets.bitrise.yml") + inventoryBase64Data := toBase64(".secrets.bitrise.yml") jsonParams := "" base64JSONParams := "" @@ -467,10 +467,10 @@ func TestParseTriggerCheckParams(t *testing.T) { format := "json" bitriseConfigPath := "bitrise.yml" - bitriseConfigBase64Data := toBase64(t, "bitrise.yml") + bitriseConfigBase64Data := toBase64("bitrise.yml") inventoryPath := ".secrets.bitrise.yml" - inventoryBase64Data := toBase64(t, ".secrets.bitrise.yml") + inventoryBase64Data := toBase64(".secrets.bitrise.yml") jsonParams := "" base64JSONParams := "" diff --git a/cli/run_util.go b/cli/run_util.go index e014c3cc..2ea8bd20 100644 --- a/cli/run_util.go +++ b/cli/run_util.go @@ -5,7 +5,6 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" "os" "path/filepath" "runtime" @@ -161,7 +160,7 @@ func registerSecretEnvsFiltering(filtering bool) error { } func isDirEmpty(path string) (bool, error) { - entries, err := ioutil.ReadDir(path) + entries, err := os.ReadDir(path) if err != nil { return false, err } @@ -435,7 +434,7 @@ func (r WorkflowRunner) executeStep( var envs []string if workflow.Container.Image != "" { - envs, err = envman.ReadAndEvaluateEnvs(configs.InputEnvstorePath, &docker.DockerEnvironmentSource{ + envs, err = envman.ReadAndEvaluateEnvs(configs.InputEnvstorePath, &docker.EnvironmentSource{ Logger: logger, }) if err != nil { @@ -847,6 +846,7 @@ func (r WorkflowRunner) activateAndRunSteps( } } stepTestDir, err := os.MkdirTemp(testDeployDir, "step_test_result") + if err != nil { log.Errorf("Failed to create per-step test result dir: %s", err) } @@ -942,17 +942,17 @@ func (r WorkflowRunner) activateAndRunSteps( return buildRunResults } -func logStepStarted(stepInfo stepmanModels.StepInfoModel, step stepmanModels.StepModel, idx int, stepExcutionId string, stepStartTime time.Time) { +func logStepStarted(stepInfo stepmanModels.StepInfoModel, step stepmanModels.StepModel, idx int, stepExcutionID string, stepStartTime time.Time) { title := "" if stepInfo.Step.Title != nil && *stepInfo.Step.Title != "" { title = *stepInfo.Step.Title } params := log.StepStartedParams{ - ExecutionId: stepExcutionId, + ExecutionID: stepExcutionID, Position: idx, Title: title, - Id: stepInfo.ID, + ID: stepInfo.ID, Version: stepInfo.Version, Collection: stepInfo.Library, Toolkit: toolkits.ToolkitForStep(step).ToolkitName(), diff --git a/cli/share_audit.go b/cli/share_audit.go index 2c28836e..45d475ee 100644 --- a/cli/share_audit.go +++ b/cli/share_audit.go @@ -5,7 +5,7 @@ import ( "github.com/urfave/cli" ) -func shareAudit(c *cli.Context) error { +func shareAudit(_ *cli.Context) error { if err := tools.StepmanShareAudit(); err != nil { failf("Bitrise share audit failed, error: %s", err) } diff --git a/cli/share_finish.go b/cli/share_finish.go index 650516f7..39e36442 100644 --- a/cli/share_finish.go +++ b/cli/share_finish.go @@ -5,7 +5,7 @@ import ( "github.com/urfave/cli" ) -func finish(c *cli.Context) error { +func finish(_ *cli.Context) error { if err := tools.StepmanShareFinish(); err != nil { failf("Bitrise share finish failed, error: %s", err) } diff --git a/cli/step_info.go b/cli/step_info.go deleted file mode 100644 index d7df05ea..00000000 --- a/cli/step_info.go +++ /dev/null @@ -1,88 +0,0 @@ -package cli - -import ( - "fmt" - - "github.com/bitrise-io/bitrise/log" - "github.com/bitrise-io/bitrise/output" - "github.com/bitrise-io/bitrise/tools" - "github.com/urfave/cli" -) - -func printStep(collectionURI, id, version, format string) error { - stepInfo, err := tools.StepmanStepInfo(collectionURI, id, version) - - switch format { - case output.FormatRaw: - if err != nil { - return err - } - log.Print("Step info:") - log.Print(stepInfo.String()) - case output.FormatJSON: - if err != nil { - return fmt.Errorf("StepmanJSONStepLibStepInfo failed, err: %s", err) - } - log.Print(stepInfo.JSON()) - default: - return fmt.Errorf("Invalid format: %s", format) - } - return nil -} - -func stepInfo(c *cli.Context) error { - warnings := []string{} - - // Expand cli.Context - bitriseConfigBase64Data := c.String(ConfigBase64Key) - - bitriseConfigPath := c.String(ConfigKey) - - format := c.String(OuputFormatKey) - - YMLPath := c.String(StepYMLKey) - collectionURI := c.String(CollectionKey) - - id := "" - if len(c.Args()) < 1 { - registerFatal("No step specified!", warnings, format) - } else { - id = c.Args()[0] - } - - version := c.String(VersionKey) - // - - if format == "" { - format = output.FormatRaw - } else if !(format == output.FormatRaw || format == output.FormatJSON) { - registerFatal(fmt.Sprintf("Invalid format: %s", format), warnings, output.FormatJSON) - } - - if YMLPath != "" { - collectionURI = "path" - id = YMLPath - version = "" - } else { - // Steplib step info - if collectionURI == "" { - bitriseConfig, warns, err := CreateBitriseConfigFromCLIParams(bitriseConfigBase64Data, bitriseConfigPath) - warnings = append(warnings, warns...) - if err != nil { - registerFatal(fmt.Sprintf("No collection defined and failed to read bitrise config, err: %s", err), warnings, format) - } - - if bitriseConfig.DefaultStepLibSource == "" { - registerFatal("No collection defined and no default collection found in bitrise config", warnings, format) - } - - collectionURI = bitriseConfig.DefaultStepLibSource - } - } - - if err := printStep(collectionURI, id, version, format); err != nil { - registerFatal(fmt.Sprintf("Failed to print step info, err: %s", err), warnings, format) - } - - return nil -} diff --git a/cli/step_list.go b/cli/step_list.go deleted file mode 100644 index f6fb4f5f..00000000 --- a/cli/step_list.go +++ /dev/null @@ -1,67 +0,0 @@ -package cli - -import ( - "fmt" - - "github.com/bitrise-io/bitrise/log" - "github.com/bitrise-io/bitrise/output" - "github.com/bitrise-io/bitrise/tools" - "github.com/urfave/cli" -) - -func stepList(c *cli.Context) error { - warnings := []string{} - - // Expand cli.Context - bitriseConfigBase64Data := c.String(ConfigBase64Key) - - bitriseConfigPath := c.String(ConfigKey) - - format := c.String(OuputFormatKey) - - collectionURI := c.String(CollectionKey) - // - - // Input validation - if format == "" { - format = output.FormatRaw - } else if !(format == output.FormatRaw || format == output.FormatJSON) { - registerFatal(fmt.Sprintf("Invalid format: %s", format), warnings, output.FormatJSON) - } - - if collectionURI == "" { - bitriseConfig, warns, err := CreateBitriseConfigFromCLIParams(bitriseConfigBase64Data, bitriseConfigPath) - warnings = append(warnings, warns...) - if err != nil { - registerFatal(fmt.Sprintf("No collection defined and failed to read bitrise config, err: %s", err), warnings, format) - } - - if bitriseConfig.DefaultStepLibSource == "" { - registerFatal("No collection defined and no default collection found in bitrise config", warnings, format) - } - - collectionURI = bitriseConfig.DefaultStepLibSource - } - - switch format { - case output.FormatRaw: - out, err := tools.StepmanRawStepList(collectionURI) - if out != "" { - log.Print("Step list:") - log.Printf("%s", out) - } - if err != nil { - registerFatal(fmt.Sprintf("Failed to print step info, err: %s", err), warnings, format) - } - case output.FormatJSON: - outStr, err := tools.StepmanJSONStepList(collectionURI) - if err != nil { - registerFatal(fmt.Sprintf("Failed to print step info, err: %s", err), warnings, format) - } - log.Print(outStr) - default: - registerFatal(fmt.Sprintf("Invalid format: %s", format), warnings, output.FormatJSON) - } - - return nil -} diff --git a/cli/trigger.go b/cli/trigger.go index 5d70609a..6e0efe70 100644 --- a/cli/trigger.go +++ b/cli/trigger.go @@ -198,7 +198,7 @@ func trigger(c *cli.Context) error { runner := NewWorkflowRunner(runConfig, agentConfig) exitCode, err := runner.RunWorkflowsWithSetupAndCheckForUpdate() if err != nil { - if err == workflowRunFailedErr { + if err == errWorkflowRunFailed { msg := createWorkflowRunStatusMessage(exitCode) printWorkflowRunStatusMessage(msg) analytics.LogMessage("info", "bitrise-cli", "exit", map[string]interface{}{"build_slug": os.Getenv("BITRISE_BUILD_SLUG")}, msg) diff --git a/cli/update.go b/cli/update.go index 9a234e13..6d643c9c 100644 --- a/cli/update.go +++ b/cli/update.go @@ -6,7 +6,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net/http" "os" "os/exec" @@ -180,7 +179,7 @@ func download(version string) error { } url := fmt.Sprintf(downloadURL, version, strings.Title(runtime.GOOS)) - tmpfile, err := ioutil.TempFile("", "bitrise") + tmpfile, err := os.CreateTemp("", "bitrise") if err != nil { return fmt.Errorf("can't create temporary file: %s", err) } diff --git a/configs/agent_config.go b/configs/agent_config.go index bc831201..b43fc509 100644 --- a/configs/agent_config.go +++ b/configs/agent_config.go @@ -35,9 +35,9 @@ type BitriseDirs struct { // It might be outside of BitriseDataHomeDir if the user has configured it so TestDeployDir string `yaml:"BITRISE_TEST_DEPLOY_DIR"` - // HtmlReportDir is for deployable html reports. + // HTMLReportDir is for deployable html reports. // It might be outside of BitriseDataHomeDir if the user has configured it so - HtmlReportDir string `yaml:"BITRISE_HTML_REPORT_DIR"` + HTMLReportDir string `yaml:"BITRISE_HTML_REPORT_DIR"` } // AgentHooks are various hooks that are executed before and after the CLI runs a build. diff --git a/configs/agent_config_test.go b/configs/agent_config_test.go index b4e9f643..29f6fd38 100644 --- a/configs/agent_config_test.go +++ b/configs/agent_config_test.go @@ -1,7 +1,7 @@ package configs import ( - "io/ioutil" + "os" "path/filepath" "testing" @@ -13,7 +13,7 @@ func TestReadAgentConfig(t *testing.T) { t.Setenv("BITRISE_BUILD_SLUG", "80b66786-d011-430f-9c68-00e9416a7325") tempDir := t.TempDir() t.Setenv("HOOKS_DIR", tempDir) - err := ioutil.WriteFile(filepath.Join(tempDir, "cleanup.sh"), []byte("echo cleanup.sh"), 0644) + err := os.WriteFile(filepath.Join(tempDir, "cleanup.sh"), []byte("echo cleanup.sh"), 0644) require.NoError(t, err) testCases := []struct { diff --git a/go.mod b/go.mod index c0ee6bc9..7348a9e6 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/bitrise-io/bitrise -go 1.18 +go 1.21 require ( github.com/bitrise-io/colorstring v0.0.0-20180614154802-a8cd70115192 diff --git a/go.sum b/go.sum index 555ebfa2..7c3e0566 100644 --- a/go.sum +++ b/go.sum @@ -1,4 +1,5 @@ github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8= +github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/Microsoft/go-winio v0.4.14 h1:+hMXMk01us9KgxGb7ftKQt2Xpf5hH/yky+TDA+qxleU= github.com/Microsoft/go-winio v0.4.14/go.mod h1:qXqCSQ3Xa7+6tgxaGTIe4Kpcdsi+P8jBhyzoq1bpyYA= @@ -89,6 +90,7 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+ github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.3.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= github.com/stretchr/objx v0.5.0 h1:1zr/of2m5FGMsad5YfcqgdqdWrIhu+EBEJRhR1U7z/c= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= diff --git a/log/event_print.go b/log/event_print.go index f818650b..c803cfe5 100644 --- a/log/event_print.go +++ b/log/event_print.go @@ -20,7 +20,7 @@ const ( // the -4 value is the four `|` separator characters in the line footerTitleBoxWidth = stepRunSummaryBoxWidthInChars - footerIconBoxWidth - footerExecutionTimeBoxWidth - 4 deprecatedPrefix = "[Deprecated]" - missingUrlPlaceholder = "Not provided" + missingURLPlaceholder = "Not provided" removalDateTitle = "Removal date:" removalNotesTitle = "Removal notes:" updateAvailableTitle = "Update available" @@ -36,7 +36,7 @@ func generateStepStartedHeaderLines(params StepStartedParams) []string { lines = append(lines, separator) lines = append(lines, getHeaderTitle(params.Position, params.Title)) lines = append(lines, separator) - lines = append(lines, getHeaderSubsection("id", params.Id)) + lines = append(lines, getHeaderSubsection("id", params.ID)) lines = append(lines, getHeaderSubsection("version", params.Version)) lines = append(lines, getHeaderSubsection("collection", params.Collection)) lines = append(lines, getHeaderSubsection("toolkit", params.Toolkit)) @@ -63,7 +63,7 @@ func getHeaderLine(content string) string { return widthConstrainedStringWithBorder(content, contentMaxWidth) } -func widthConstrainedStringWithBorder(content string, width int) string { +func widthConstrainedStringWithBorder(content string, width int) string { //nolint:unparam // Width always receives contentMaxWidth return fmt.Sprintf("| %s |", widthConstrainedString(content, width)) } @@ -233,21 +233,21 @@ func getFooterExecutionTime(duration int64) string { return fmt.Sprintf(" %s ", executionTime) } -func getIssueAndSourceSection(issueUrl, sourceUrl string) []string { - if issueUrl == "" { - issueUrl = missingUrlPlaceholder +func getIssueAndSourceSection(issueURL, sourceURL string) []string { + if issueURL == "" { + issueURL = missingURLPlaceholder } - if sourceUrl == "" { - sourceUrl = missingUrlPlaceholder + if sourceURL == "" { + sourceURL = missingURLPlaceholder } contentMaxWidth := stepRunSummaryBoxWidthInChars - 4 - issueRow := widthConstrainedStringWithBorder(fmt.Sprintf("Issue tracker: %s", issueUrl), contentMaxWidth) - sourceRow := widthConstrainedStringWithBorder(fmt.Sprintf("Source: %s", sourceUrl), contentMaxWidth) + issueRow := widthConstrainedStringWithBorder(fmt.Sprintf("Issue tracker: %s", issueURL), contentMaxWidth) + sourceRow := widthConstrainedStringWithBorder(fmt.Sprintf("Source: %s", sourceURL), contentMaxWidth) - coloredPlaceholder := corelog.AddColor(corelog.WarnLevel, missingUrlPlaceholder) - issueRow = strings.ReplaceAll(issueRow, missingUrlPlaceholder, coloredPlaceholder) - sourceRow = strings.ReplaceAll(sourceRow, missingUrlPlaceholder, coloredPlaceholder) + coloredPlaceholder := corelog.AddColor(corelog.WarnLevel, missingURLPlaceholder) + issueRow = strings.ReplaceAll(issueRow, missingURLPlaceholder, coloredPlaceholder) + sourceRow = strings.ReplaceAll(sourceRow, missingURLPlaceholder, coloredPlaceholder) return []string{issueRow, sourceRow} } diff --git a/log/event_print_test.go b/log/event_print_test.go index 91f4e4c1..cba7fab4 100644 --- a/log/event_print_test.go +++ b/log/event_print_test.go @@ -21,10 +21,10 @@ func TestStepHeaderPrinting(t *testing.T) { { name: "Only prints the values which need to appear in the console output", params: StepStartedParams{ - ExecutionId: "ExecutionId is not needed", + ExecutionID: "ExecutionId is not needed", Position: 0, Title: "xcode-test@4.1.2", - Id: "xcode-test", + ID: "xcode-test", Version: "4.1.2", Collection: "Steplib", Toolkit: "Go", @@ -46,10 +46,10 @@ func TestStepHeaderPrinting(t *testing.T) { { name: "Long step parameter values are truncated", params: StepStartedParams{ - ExecutionId: "random-uuid", + ExecutionID: "random-uuid", Position: 1, Title: "Very long step name - Very long step name - Very long step name - Very long step name - Very long step name", - Id: "this-is-the-step-this-is-the-step-this-is-the-step-this-is-the-step-this-is-the-step-this-is-the-step-this-is-the-step-this-is-the-step", + ID: "this-is-the-step-this-is-the-step-this-is-the-step-this-is-the-step-this-is-the-step-this-is-the-step-this-is-the-step-this-is-the-step", Version: "1.1.2", Collection: "Steplib", Toolkit: "Go", @@ -71,10 +71,10 @@ func TestStepHeaderPrinting(t *testing.T) { { name: "Prints empty fields", params: StepStartedParams{ - ExecutionId: "another-random-uuid", + ExecutionID: "another-random-uuid", Position: 2, Title: "git::https://github.com/org/repo", - Id: "https://github.com/org/repo", + ID: "https://github.com/org/repo", Version: "", Collection: "Git", Toolkit: "", diff --git a/log/models.go b/log/models.go index ea6cc5d6..9b9983e3 100644 --- a/log/models.go +++ b/log/models.go @@ -4,10 +4,10 @@ import "github.com/bitrise-io/bitrise/models" // StepStartedParams ... type StepStartedParams struct { - ExecutionId string `json:"uuid"` + ExecutionID string `json:"uuid"` Position int `json:"idx"` Title string `json:"title"` - Id string `json:"id"` + ID string `json:"id"` Version string `json:"version"` Collection string `json:"collection"` Toolkit string `json:"toolkit"` @@ -30,7 +30,7 @@ type StepUpdate struct { // StepFinishedParams ... type StepFinishedParams struct { - ExecutionId string `json:"uuid"` + ExecutionID string `json:"uuid"` Status string `json:"status"` StatusReason string `json:"status_reason,omitempty"` Title string `json:"title"` diff --git a/log/models_test.go b/log/models_test.go index 3a4f8610..01e21cd9 100644 --- a/log/models_test.go +++ b/log/models_test.go @@ -17,10 +17,10 @@ func TestStepStartedEventSerialisesToTheExpectedJsonMessage(t *testing.T) { { name: "Every field is serialised", params: StepStartedParams{ - ExecutionId: "ExecutionId", + ExecutionID: "ExecutionId", Position: 0, Title: "Title", - Id: "Id", + ID: "Id", Version: "Version", Collection: "Collection", Toolkit: "Toolkit", @@ -31,10 +31,10 @@ func TestStepStartedEventSerialisesToTheExpectedJsonMessage(t *testing.T) { { name: "Empty fields are kept", params: StepStartedParams{ - ExecutionId: "ExecutionId", + ExecutionID: "ExecutionId", Position: 0, Title: "Title", - Id: "Id", + ID: "Id", Version: "", Collection: "Collection", Toolkit: "", @@ -63,7 +63,7 @@ func TestStepFinishedEventSerialisesToTheExpectedJsonMessage(t *testing.T) { { name: "Fields are serialising correctly", params: StepFinishedParams{ - ExecutionId: "ExecutionId", + ExecutionID: "ExecutionId", Status: models.StepRunStatusCodeFailed.String(), StatusReason: "StatusReason", Title: "Title", @@ -93,7 +93,7 @@ func TestStepFinishedEventSerialisesToTheExpectedJsonMessage(t *testing.T) { { name: "Optional fields are omitted when empty", params: StepFinishedParams{ - ExecutionId: "ExecutionId", + ExecutionID: "ExecutionId", Status: models.StepRunStatusCodeSkipped.String(), StatusReason: "", Title: "Title", diff --git a/models/models.go b/models/models.go index 3d353ae6..19efb377 100644 --- a/models/models.go +++ b/models/models.go @@ -226,7 +226,7 @@ func (s StepRunResultsModel) error() []StepError { } func formatStatusReasonTimeInterval(timeInterval time.Duration) string { - var remaining int = int(timeInterval / time.Second) + var remaining = int(timeInterval / time.Second) h := int(remaining / 3600) remaining = remaining - h*3600 m := int(remaining / 60) diff --git a/models/models_test.go b/models/models_test.go index 875a90a6..b9d2fa05 100644 --- a/models/models_test.go +++ b/models/models_test.go @@ -9,7 +9,7 @@ import ( ) func TestStatusReasonSuccess(t *testing.T) { - var s StepRunResultsModel = StepRunResultsModel{ + var s = StepRunResultsModel{ Status: StepRunStatusCodeSuccess, } expectedStatusReason := "" @@ -21,7 +21,7 @@ func TestStatusReasonSuccess(t *testing.T) { } func TestStatusReasonFailed(t *testing.T) { - var s StepRunResultsModel = StepRunResultsModel{ + var s = StepRunResultsModel{ Status: StepRunStatusCodeFailed, ExitCode: 25, ErrorStr: "exit code: 25", @@ -35,7 +35,7 @@ func TestStatusReasonFailed(t *testing.T) { } func TestStatusReasonPreparationFailed(t *testing.T) { - var s StepRunResultsModel = StepRunResultsModel{ + var s = StepRunResultsModel{ Status: StepRunStatusCodePreparationFailed, ExitCode: 30, ErrorStr: "Failed to clone step.", @@ -75,7 +75,7 @@ func TestStatusReasonSkipped(t *testing.T) { } func TestStatusReasonSkippedWithRunIf(t *testing.T) { - var runif string = "2+2==4" + var runif = "2+2==4" var model models.StepModel = models.StepModel{ RunIf: &runif, } diff --git a/plugins/install_test.go b/plugins/install_test.go index ac56fc60..5de87bb3 100644 --- a/plugins/install_test.go +++ b/plugins/install_test.go @@ -11,7 +11,7 @@ import ( ) const examplePluginGitURL = "https://github.com/bitrise-io/bitrise-plugins-example.git" -const analyticsPluginBinURL = "https://github.com/bitrise-io/bitrise-plugins-analytics/releases/download/0.9.1/analytics-Darwin-x86_64" +const testPluginBinURL = "https://github.com/bitrise-io/bitrise-plugins-step/releases/download/0.10.4/bitrise-plugins-step-Darwin-arm64" func TestIsLocalURL(t *testing.T) { t.Log("local url - absolute") @@ -199,7 +199,6 @@ func TestValidateRequirements(t *testing.T) { func TestDownloadPluginBin(t *testing.T) { t.Log("example plugin bin - ") { - pluginBinURL := analyticsPluginBinURL destinationDir, err := pathutil.NormalizedOSTempDirPath("TestDownloadPluginBin") require.NoError(t, err) @@ -214,7 +213,7 @@ func TestDownloadPluginBin(t *testing.T) { destinationPth := filepath.Join(destinationDir, "example") - require.NoError(t, downloadPluginBin(pluginBinURL, destinationPth)) + require.NoError(t, downloadPluginBin(testPluginBinURL, destinationPth)) exist, err = pathutil.IsPathExists(destinationPth) require.NoError(t, err) @@ -228,12 +227,12 @@ func Test_isSourceURIChanged(t *testing.T) { new string want bool }{ - {installed: "https://github.com/bitrise-core/bitrise-plugins-analytics.git", new: "https://github.com/bitrise-core/bitrise-plugins-analytics.git", want: false}, - {installed: "https://github.com/bitrise-core/bitrise-plugins-analytics.git", new: "https://github.com/bitrise-io/bitrise-plugins-analytics.git", want: false}, - {installed: "https://github.com/bitrise-core/bitrise-plugins-analytics.git", new: "https://github.com/myorg/bitrise-plugins-analytics.git", want: true}, - {installed: "https://github.com/bitrise-core/bitrise-plugins-analytics.git", new: "https://github.com/bitrise-team/bitrise-plugins-analytics.git", want: true}, - {installed: "https://github.com/bitrise-custom-org/bitrise-plugins-analytics.git", new: "https://github.com/bitrise-core/bitrise-plugins-analytics.git", want: true}, - {installed: "https://github.com/bitrise-custom-org/bitrise-plugins-analytics.git", new: "https://github.com/bitrise-io/bitrise-plugins-analytics.git", want: true}, + {installed: "https://github.com/bitrise-core/bitrise-plugins-step.git", new: "https://github.com/bitrise-core/bitrise-plugins-step.git", want: false}, + {installed: "https://github.com/bitrise-core/bitrise-plugins-step.git", new: "https://github.com/bitrise-io/bitrise-plugins-step.git", want: false}, // resolves to same real URL + {installed: "https://github.com/bitrise-core/bitrise-plugins-step.git", new: "https://github.com/myorg/bitrise-plugins-step.git", want: true}, + {installed: "https://github.com/bitrise-core/bitrise-plugins-step.git", new: "https://github.com/bitrise-team/bitrise-plugins-step.git", want: true}, + {installed: "https://github.com/bitrise-custom-org/bitrise-plugins-step.git", new: "https://github.com/bitrise-core/bitrise-plugins-step.git", want: true}, + {installed: "https://github.com/bitrise-custom-org/bitrise-plugins-step.git", new: "https://github.com/bitrise-io/bitrise-plugins-step.git", want: true}, } { t.Run("", func(t *testing.T) { if got := isSourceURIChanged(tt.installed, tt.new); got != tt.want { diff --git a/toolkits/bash.go b/toolkits/bash.go index 38d9ad46..0fc3bd69 100644 --- a/toolkits/bash.go +++ b/toolkits/bash.go @@ -60,7 +60,7 @@ func (toolkit BashToolkit) ToolkitName() string { } // PrepareForStepRun ... -func (toolkit BashToolkit) PrepareForStepRun(step stepmanModels.StepModel, sIDData models.StepIDData, stepAbsDirPath string) error { +func (toolkit BashToolkit) PrepareForStepRun(_ stepmanModels.StepModel, _ models.StepIDData, _ string) error { return nil } diff --git a/toolkits/golang.go b/toolkits/golang.go index 7c206196..b0314f23 100644 --- a/toolkits/golang.go +++ b/toolkits/golang.go @@ -337,7 +337,7 @@ func (toolkit GoToolkit) PrepareForStepRun(step stepmanModels.StepModel, sIDData // === Toolkit: Step Run === // StepRunCommandArguments ... -func (toolkit GoToolkit) StepRunCommandArguments(step stepmanModels.StepModel, sIDData models.StepIDData, stepAbsDirPath string) ([]string, error) { +func (toolkit GoToolkit) StepRunCommandArguments(_ stepmanModels.StepModel, sIDData models.StepIDData, stepAbsDirPath string) ([]string, error) { fullStepBinPath := stepBinaryCacheFullPath(sIDData) return []string{fullStepBinPath}, nil } diff --git a/toolkits/golang_test.go b/toolkits/golang_test.go index d522d418..ffbff87d 100644 --- a/toolkits/golang_test.go +++ b/toolkits/golang_test.go @@ -2,7 +2,6 @@ package toolkits import ( "fmt" - "io/ioutil" "os" "path/filepath" "testing" @@ -164,12 +163,11 @@ func Test_goBuildStep(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - stepDir, err := ioutil.TempDir("", "") - require.NoError(t, err, "failed to create temp dir") + stepDir := t.TempDir() goModPath := filepath.Join(stepDir, "go.mod") if tt.isGoModStep { - err := ioutil.WriteFile(goModPath, []byte{}, 0600) + err := os.WriteFile(goModPath, []byte{}, 0600) require.NoError(t, err, "failed to create file") } @@ -179,7 +177,7 @@ func Test_goBuildStep(t *testing.T) { GOROOT: "/goroot", } - err = goBuildStep(&mockRunner, goConfig, tt.args.packageName, stepDir, tt.args.outputBinPath) + err := goBuildStep(&mockRunner, goConfig, tt.args.packageName, stepDir, tt.args.outputBinPath) require.NoError(t, err, "goBuildStep()") require.Equal(t, tt.wantCmds, mockRunner.cmds, "goBuildStep() run commands do not match") @@ -200,7 +198,7 @@ func Benchmark_goBuildStep(b *testing.B) { b.Fatalf("Failed to select an appropriate Go installation for compiling the Step") } - stepDir, err := ioutil.TempDir("", "") + stepDir := b.TempDir() require.NoError(b, err) defer func() { @@ -208,7 +206,7 @@ func Benchmark_goBuildStep(b *testing.B) { require.NoError(b, err) }() - outputDir, err := ioutil.TempDir("", "") + outputDir := b.TempDir() require.NoError(b, err) defer func() { @@ -231,7 +229,7 @@ func Benchmark_goBuildStep(b *testing.B) { b.Setenv("GO111MODULE", mode) for i := 0; i < b.N; i++ { - stepPerTestDir, err := ioutil.TempDir("", "") + stepPerTestDir := b.TempDir() require.NoError(b, err) defer func() { diff --git a/toolkits/modmigrate.go b/toolkits/modmigrate.go index abb8be8c..703d13f5 100644 --- a/toolkits/modmigrate.go +++ b/toolkits/modmigrate.go @@ -2,7 +2,6 @@ package toolkits import ( "fmt" - "io/ioutil" "os" "path/filepath" ) @@ -24,7 +23,7 @@ func migrateToGoModules(stepAbsDirPath, packageName string) error { goModTemplate := `module %s go 1.16` goModContents := fmt.Sprintf(goModTemplate, packageName) - if err := ioutil.WriteFile(filepath.Join(stepAbsDirPath, "go.mod"), []byte(goModContents), 0600); err != nil { + if err := os.WriteFile(filepath.Join(stepAbsDirPath, "go.mod"), []byte(goModContents), 0600); err != nil { return fmt.Errorf("failed to write go.mod file: %v", err) } diff --git a/toolkits/swift.go b/toolkits/swift.go index 6ed09d45..abcc4f89 100644 --- a/toolkits/swift.go +++ b/toolkits/swift.go @@ -45,7 +45,7 @@ func (toolkit SwiftToolkit) IsToolAvailableInPATH() bool { } // PrepareForStepRun ... -func (toolkit SwiftToolkit) PrepareForStepRun(step stepmanModels.StepModel, sIDData models.StepIDData, stepAbsDirPath string) error { +func (toolkit SwiftToolkit) PrepareForStepRun(step stepmanModels.StepModel, _ models.StepIDData, stepAbsDirPath string) error { binaryLocation := step.Toolkit.Swift.BinaryLocation if binaryLocation == "" { return nil diff --git a/tools/tools.go b/tools/tools.go index 3bca2b8d..00c35820 100644 --- a/tools/tools.go +++ b/tools/tools.go @@ -4,7 +4,6 @@ import ( "bytes" "fmt" "io" - "io/ioutil" "net/http" "os" "path/filepath" @@ -301,12 +300,12 @@ func MoveFile(oldpath, newpath string) error { return err } - data, err := ioutil.ReadFile(oldpath) + data, err := os.ReadFile(oldpath) if err != nil { return err } - err = ioutil.WriteFile(newpath, data, info.Mode()) + err = os.WriteFile(newpath, data, info.Mode()) if err != nil { return err } diff --git a/tools/tools_test.go b/tools/tools_test.go index e6854e33..b7b56a07 100644 --- a/tools/tools_test.go +++ b/tools/tools_test.go @@ -1,7 +1,6 @@ package tools import ( - "io/ioutil" "os" "os/exec" "path/filepath" @@ -38,8 +37,7 @@ func TestMoveFileDifferentDevices(t *testing.T) { ramdiskName := "RAMDISK" volumeName := "" if runtime.GOOS == "linux" { - tmpDir, err := ioutil.TempDir("", ramdiskName) - require.NoError(t, err) + tmpDir := t.TempDir() ramdiskPath = tmpDir require.NoError(t, exec.Command("mount", "-t", "tmpfs", "-o", "size=12m", "tmpfs", ramdiskPath).Run()) diff --git a/toolversions/toolversions_test.go b/toolversions/toolversions_test.go index 1da58684..c69a7457 100644 --- a/toolversions/toolversions_test.go +++ b/toolversions/toolversions_test.go @@ -150,7 +150,7 @@ type fakeCommandLocator struct { path string } -func (f fakeCommandLocator) LookPath(name string) (string, error) { +func (f fakeCommandLocator) LookPath(_ string) (string, error) { return f.path, nil } @@ -159,7 +159,7 @@ type fakeCommandFactory struct { exitCode int } -func (f fakeCommandFactory) Create(name string, args []string, opts *command.Opts) command.Command { +func (f fakeCommandFactory) Create(name string, args []string, _ *command.Opts) command.Command { return fakeCommand{ command: fmt.Sprintf("%s %s", name, strings.Join(args, " ")), stdout: f.stdout,