diff --git a/.circleci/config.yml b/.circleci/config.yml index 55ac6bd2f..c8c25620f 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -104,7 +104,7 @@ jobs: - run: name: lint command: | - /go/bin/golangci-lint run --no-config --issues-exit-code=1 --timeout=5m -v + /go/bin/golangci-lint run --issues-exit-code=1 --timeout=5m -v ./... no_output_timeout: 5m horus: diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 000000000..111728048 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,104 @@ +run: + timeout: 10m + issues-exit-code: 1 + tests: true + skip-dirs: + - vendor + modules-download-mode: vendor +output: + format: colored-line-number + print-issued-lines: true + print-linter-name: true + +linters-settings: + errcheck: + check-type-assertions: false + check-blank: false + exclude: ./errcheck_excludes.txt + golint: + min-confidence: 0.8 + maligned: + suggest-new: true + +linters: + disable-all: true + enable: + - deadcode + - errcheck + - gosimple + - govet + - ineffassign + - staticcheck + - structcheck + - typecheck + - unused + - varcheck + - asciicheck + - bodyclose + - depguard + - dogsled + - dupl + - exhaustive + - exportloopref + - gochecknoinits + - gocyclo + - godox + - gofmt + - goheader + - goimports + - gomodguard + - goprintffuncname + - misspell + - nakedret + - nolintlint + - prealloc + - rowserrcheck + - sqlclosecheck + - unconvert + - unparam + presets: + fast: false + + +issues: + exclude-rules: + - path: _test\.go + linters: + - dupl + - errcheck + - gocritic + - gocyclo + - gosec + - lll + - goconst + - unparam + - unused + - sqlclosecheck + - stylecheck + + - linters: + - lll + source: "^//go:generate " + + # error strings should not be capitalized + - linters: + - stylecheck + text: "ST1005:" + + # at least one file in a package should have a package comment + - linters: + - stylecheck + text: "ST1000:" + + # comment on exported method Name should be of the form "Name ..." + - linters: + - stylecheck + text: "ST1020:" + + - linters: + - gocritic + text: "sloppyLen:" + + exclude-use-default: false + max-issues-per-linter: 0 + max-same-issues: 0 diff --git a/errcheck_excludes.txt b/errcheck_excludes.txt new file mode 100644 index 000000000..fb76631fc --- /dev/null +++ b/errcheck_excludes.txt @@ -0,0 +1,5 @@ +(io.Closer).Close +(*os.File).Close +(*io.PipeReader).Close +(*io.PipeWriter).Close +(*archive/zip.ReadCloser).Close diff --git a/functional/runner.go b/functional/runner.go index 6773fe00e..f448f7be3 100644 --- a/functional/runner.go +++ b/functional/runner.go @@ -54,7 +54,7 @@ func (scenario *Scenario) RunSteps() (string, error) { ginkgo.Skip("Scenarios with multi steps for windows doesnt work") return "", nil } else { - err, resp := scenario.runStepsForUnix() + resp, err := scenario.runStepsForUnix() return resp, err } } @@ -101,7 +101,7 @@ func LoadScenarios(file string) []Scenario { if err != nil { log.Fatal("Error reading scenarios json:", err) } - err = json.Unmarshal([]byte(b), &res) + err = json.Unmarshal(b, &res) if err != nil { log.Fatal("Error unmarshal json:", err) } diff --git a/functional/runner_unix.go b/functional/runner_unix.go index 040b6d318..ea90ed8c0 100644 --- a/functional/runner_unix.go +++ b/functional/runner_unix.go @@ -94,7 +94,7 @@ func setUpRitSingleUnix() { init := Scenario{Entry: "Running Init", Result: "", Steps: []Step{initStepRit, initAcceptsMetrics, initAddRepo, initSetRunType}} - err, _ := init.runStepsForUnix() + _, err := init.runStepsForUnix() if err != nil { log.Printf("Error when do init: %q", err) } @@ -111,7 +111,7 @@ func setUpClearSetupUnix() { } } -func (scenario *Scenario) runStepsForUnix() (error, string) { +func (scenario *Scenario) runStepsForUnix() (string, error) { args := strings.Fields(scenario.Steps[0].Value) cmd, stdin, out, err := execRit(args) if err == nil { @@ -147,7 +147,7 @@ func (scenario *Scenario) runStepsForUnix() (error, string) { fmt.Println(resp) fmt.Println("--------") - return err, resp + return resp, err } func commandInit(cmdIn *exec.Cmd) (stdin io.WriteCloser, out io.Reader, err error) { diff --git a/functional/runner_win.go b/functional/runner_win.go index 2aa5f440e..86637a9d4 100644 --- a/functional/runner_win.go +++ b/functional/runner_win.go @@ -34,6 +34,8 @@ func (scenario *Scenario) runStdinForWindows() (bytes.Buffer, error) { args := append([]string{"-Command", "Write-Output", "'" + writeOutput + "'", "|", "rit"}, rit...) cmd := exec.Command("powershell", args...) _, pipeWriter := io.Pipe() + defer pipeWriter.Close() + cmd.Stdout = pipeWriter var stderr bytes.Buffer @@ -53,8 +55,6 @@ func (scenario *Scenario) runStdinForWindows() (bytes.Buffer, error) { b2 = stderr } - pipeWriter.Close() - fmt.Println(&b2) fmt.Println("--------") return b2, err diff --git a/pkg/autocomplete/generator.go b/pkg/autocomplete/generator.go index 13da2081b..68131411a 100644 --- a/pkg/autocomplete/generator.go +++ b/pkg/autocomplete/generator.go @@ -99,14 +99,14 @@ func loadToFish(cmd *cobra.Command) (string, error) { func loadToBash(t formula.Tree) string { a := autoCompletionBash - a = strings.Replace(a, binaryNamePattern, binaryName, -1) + a = strings.ReplaceAll(a, binaryNamePattern, binaryName) a = strings.Replace(a, dynamicCodePattern, loadDynamicCommands(t), 1) return a } func loadToZsh(t formula.Tree) string { a := autoCompletionZsh - a = strings.Replace(a, binaryNamePattern, binaryName, -1) + a = strings.ReplaceAll(a, binaryNamePattern, binaryName) a = strings.Replace(a, autocompleteBashPattern, loadToBash(t), 1) return a } @@ -118,10 +118,10 @@ func loadDynamicCommands(t formula.Tree) string { var allCommands string for _, b := range bashCommands { functionName := formatterFunctionName(b.RootCommand) - c := strings.Replace(command, rootCommandPattern, b.RootCommand, -1) - c = strings.Replace(c, lastCommandPattern, b.LastCommand, -1) - c = strings.Replace(c, funcNamePattern, functionName, -1) - allCommands += strings.Replace(c, commandsPattern, b.Commands, -1) + c := strings.ReplaceAll(command, rootCommandPattern, b.RootCommand) + c = strings.ReplaceAll(c, lastCommandPattern, b.LastCommand) + c = strings.ReplaceAll(c, funcNamePattern, functionName) + allCommands += strings.ReplaceAll(c, commandsPattern, b.Commands) } return allCommands } @@ -160,13 +160,13 @@ func loadCommands(cc []api.Command) map[string]CompletionCommand { } func loadBashCommands(cc map[string]CompletionCommand) []BashCommand { - var bb []BashCommand + bb := make([]BashCommand, 0, len(cc)) for key, val := range cc { rootCommand := key level := len(strings.Split(key, "_")) var commands string for _, v := range val.Content { - commands += strings.Replace(lineCommand, "${command}", v, -1) + "\n" + commands += strings.ReplaceAll(lineCommand, "${command}", v) + "\n" } if rootCommand == firstLevel { rootCommand = fmt.Sprintf("%s_%s", binaryName, rootCommand) diff --git a/pkg/cmd/add.go b/pkg/cmd/add.go index c1ed17d56..48b31e338 100644 --- a/pkg/cmd/add.go +++ b/pkg/cmd/add.go @@ -20,7 +20,7 @@ import ( "github.com/spf13/cobra" ) -// NewAddCmd create a new add instance +// NewAddCmd create a new add instance. func NewAddCmd() *cobra.Command { return &cobra.Command{ Use: "add SUBCOMMAND", diff --git a/pkg/cmd/add_repo.go b/pkg/cmd/add_repo.go index 956b37bd4..16c881d7a 100644 --- a/pkg/cmd/add_repo.go +++ b/pkg/cmd/add_repo.go @@ -29,7 +29,7 @@ import ( "github.com/ZupIT/ritchie-cli/pkg/stdin" ) -const defaultRepoUrl = "https://github.com/ZupIT/ritchie-formulas" +const defaultRepoURL = "https://github.com/ZupIT/ritchie-formulas" var ErrRepoNameNotEmpty = errors.New("the field repository name must not be empty") @@ -50,7 +50,7 @@ func NewAddRepoCmd( repoProviders formula.RepoProviders, inText prompt.InputTextValidator, inPass prompt.InputPassword, - inUrl prompt.InputURL, + inURL prompt.InputURL, inList prompt.InputList, inBool prompt.InputBool, inInt prompt.InputInt, @@ -60,7 +60,7 @@ func NewAddRepoCmd( repo: repo, repoProviders: repoProviders, InputTextValidator: inText, - InputURL: inUrl, + InputURL: inURL, InputList: inList, InputBool: inBool, InputInt: inInt, @@ -119,7 +119,7 @@ func (ad addRepoCmd) runPrompt() CommandRunnerFunc { } } - url, err := ad.URL("Repository URL:", defaultRepoUrl) + url, err := ad.URL("Repository URL:", defaultRepoURL) if err != nil { return err } @@ -177,7 +177,10 @@ func (ad addRepoCmd) runPrompt() CommandRunnerFunc { return err } - successMsg := fmt.Sprintf("The %q repository was added with success, now you can use your formulas with the Ritchie!", repository.Name) + successMsg := fmt.Sprintf( + "The %q repository was added with success, now you can use your formulas with the Ritchie!", + repository.Name, + ) prompt.Success(successMsg) tutorialHolder, err := ad.rt.Find() @@ -203,7 +206,10 @@ func (ad addRepoCmd) runStdin() CommandRunnerFunc { return err } - successMsg := fmt.Sprintf("The %q repository was added with success, now you can use your formulas with the Ritchie!", r.Name) + successMsg := fmt.Sprintf( + "The %q repository was added with success, now you can use your formulas with the Ritchie!", + r.Name, + ) prompt.Success(successMsg) tutorialHolder, err := ad.rt.Find() diff --git a/pkg/cmd/autocomplete.go b/pkg/cmd/autocomplete.go index 193b0290c..6a5ed49ba 100644 --- a/pkg/cmd/autocomplete.go +++ b/pkg/cmd/autocomplete.go @@ -34,12 +34,12 @@ const ( var supportedShell = []string{zsh.String(), bash.String(), fish.String(), powerShell.String()} -// autocompleteCmd type for set autocomplete command +// autocompleteCmd type for set autocomplete command. type autocompleteCmd struct { autocomplete.Generator } -// NewAutocompleteCmd creates a new cmd instance +// NewAutocompleteCmd creates a new cmd instance. func NewAutocompleteCmd() *cobra.Command { shells := strings.Join(supportedShell, ", ") @@ -53,7 +53,7 @@ func NewAutocompleteCmd() *cobra.Command { } } -// NewAutocompleteZsh creates a new cmd instance zsh +// NewAutocompleteZsh creates a new cmd instance zsh. func NewAutocompleteZsh(g autocomplete.Generator) *cobra.Command { a := &autocompleteCmd{g} @@ -79,7 +79,7 @@ To install run: } } -// NewAutocompleteBash creates a new cmd instance zsh +// NewAutocompleteBash creates a new cmd instance zsh. func NewAutocompleteBash(g autocomplete.Generator) *cobra.Command { a := &autocompleteCmd{g} @@ -105,7 +105,7 @@ To install run: } } -// NewAutocompleteFish creates a new cmd instance fish +// NewAutocompleteFish creates a new cmd instance fish. func NewAutocompleteFish(g autocomplete.Generator) *cobra.Command { a := &autocompleteCmd{g} @@ -130,7 +130,7 @@ To install run: } } -// NewAutocompletePowerShell creates a new cmd instance PowerShell +// NewAutocompletePowerShell creates a new cmd instance PowerShell. func NewAutocompletePowerShell(g autocomplete.Generator) *cobra.Command { a := &autocompleteCmd{g} diff --git a/pkg/cmd/build_formula_test.go b/pkg/cmd/build_formula_test.go index e00fd201c..d983a0867 100644 --- a/pkg/cmd/build_formula_test.go +++ b/pkg/cmd/build_formula_test.go @@ -157,7 +157,7 @@ func TestBuildFormulaCmd(t *testing.T) { wantErr: true, }, { - name: "Run with sucess when the selected formula is deeper in the tree", + name: "Run with success when the selected formula is deeper in the tree", fields: fieldsTestBuildFormulaCmd{ directory: DirManagerCustomMock{ exists: func(dir string) bool { @@ -191,7 +191,7 @@ func TestBuildFormulaCmd(t *testing.T) { wantErr: false, }, { - name: "Run with sucess when selected formula is less deep in the tree", + name: "Run with success when selected formula is less deep in the tree", fields: fieldsTestBuildFormulaCmd{ directory: DirManagerCustomMock{ exists: func(dir string) bool { diff --git a/pkg/cmd/cmd.go b/pkg/cmd/cmd.go index c5aa41121..efd481b19 100644 --- a/pkg/cmd/cmd.go +++ b/pkg/cmd/cmd.go @@ -22,10 +22,10 @@ import ( "github.com/ZupIT/ritchie-cli/pkg/api" ) -// CommandRunnerFunc represents that runner func for commands +// CommandRunnerFunc represents that runner func for commands. type CommandRunnerFunc func(cmd *cobra.Command, args []string) error -// RunFuncE delegates to stdinFunc if --stdin flag is passed otherwise delegates to promptFunc +// RunFuncE delegates to stdinFunc if --stdin flag is passed otherwise delegates to promptFunc. func RunFuncE(stdinFunc, promptFunc CommandRunnerFunc) CommandRunnerFunc { return func(cmd *cobra.Command, args []string) error { stdin, err := cmd.Flags().GetBool(api.Stdin.ToLower()) diff --git a/pkg/cmd/create.go b/pkg/cmd/create.go index f96a3999f..80d609b7e 100644 --- a/pkg/cmd/create.go +++ b/pkg/cmd/create.go @@ -20,7 +20,7 @@ import ( "github.com/spf13/cobra" ) -// NewCreateCmd creates new cmd instance +// NewCreateCmd creates new cmd instance. func NewCreateCmd() *cobra.Command { return &cobra.Command{ Use: "create SUBCOMMAND", diff --git a/pkg/cmd/create_formula.go b/pkg/cmd/create_formula.go index 5e5391433..a98f00ecc 100644 --- a/pkg/cmd/create_formula.go +++ b/pkg/cmd/create_formula.go @@ -35,7 +35,7 @@ import ( "github.com/ZupIT/ritchie-cli/pkg/stdin" ) -// createFormulaCmd type for add formula command +// createFormulaCmd type for add formula command. type createFormulaCmd struct { homeDir string formula formula.CreateBuilder @@ -47,7 +47,7 @@ type createFormulaCmd struct { rt rtutorial.Finder } -// CreateFormulaCmd creates a new cmd instance +// CreateFormulaCmd creates a new cmd instance. func NewCreateFormulaCmd( homeDir string, formula formula.CreateBuilder, @@ -190,7 +190,7 @@ func buildSuccess(formulaPath, formulaCmd, tutorialStatus string) { prompt.Info(fmt.Sprintf("Formula path is %s", formulaPath)) if tutorialStatus == tutorialStatusEnabled { - tutorialCreateFormula(tutorialStatus, formulaCmd) + tutorialCreateFormula(formulaCmd) } else { prompt.Info(fmt.Sprintf("Now you can run your formula with the following command %q", formulaCmd)) } @@ -265,7 +265,7 @@ func FormulaWorkspaceInput( inList prompt.InputList, inText prompt.InputText, ) (formula.Workspace, error) { - var items []string + items := make([]string, 0, len(workspaces)) for k, v := range workspaces { kv := fmt.Sprintf("%s (%s)", k, v) items = append(items, kv) @@ -307,7 +307,7 @@ func FormulaWorkspaceInput( return wspace, nil } -func tutorialCreateFormula(tutorialStatus string, formulaCmd string) { +func tutorialCreateFormula(formulaCmd string) { const tagTutorial = "\n[TUTORIAL]" const messageTitle = "In order to test your new formula:" const messageBody = ` ∙ Run %q diff --git a/pkg/cmd/delete.go b/pkg/cmd/delete.go index 980fee034..d18bbdeb7 100644 --- a/pkg/cmd/delete.go +++ b/pkg/cmd/delete.go @@ -18,7 +18,7 @@ package cmd import "github.com/spf13/cobra" -// NewDeleteCmd create a new delete instance +// NewDeleteCmd create a new delete instance. func NewDeleteCmd() *cobra.Command { return &cobra.Command{ Use: "delete SUBCOMMAND", diff --git a/pkg/cmd/delete_context.go b/pkg/cmd/delete_context.go index d4977f470..f323d4083 100644 --- a/pkg/cmd/delete_context.go +++ b/pkg/cmd/delete_context.go @@ -27,14 +27,14 @@ import ( "github.com/ZupIT/ritchie-cli/pkg/stdin" ) -// deleteContextCmd type for clean repo command +// deleteContextCmd type for clean repo command. type deleteContextCmd struct { rcontext.FindRemover prompt.InputBool prompt.InputList } -// deleteContext type for stdin json decoder +// deleteContext type for stdin json decoder. type deleteContext struct { Context string `json:"context"` } diff --git a/pkg/cmd/delete_formula.go b/pkg/cmd/delete_formula.go index fcf362b62..bed35a124 100644 --- a/pkg/cmd/delete_formula.go +++ b/pkg/cmd/delete_formula.go @@ -35,9 +35,9 @@ import ( ) const ( - msgFormulaNotFound = "Could not find formula" - msgIncorrectFormulaName = "Formula name is incorrect" - foundFormulaQuestion = "We found a formula, which one do you want to delete: " + msgFormulaNotFound = "could not find formula" + msgIncorrectFormulaName = "formula name is incorrect" + foundFormulaQuestion = "we found a formula, which one do you want to delete: " ) var ( @@ -144,7 +144,7 @@ func (d deleteFormulaCmd) runPrompt() CommandRunnerFunc { return err } - if err := d.recreateTreeJson(ritchieLocalWorkspace); err != nil { + if err := d.recreateTreeJSON(ritchieLocalWorkspace); err != nil { return err } } @@ -181,7 +181,7 @@ func (d deleteFormulaCmd) runStdin() CommandRunnerFunc { return err } - if err := d.recreateTreeJson(ritchieLocalWorkspace); err != nil { + if err := d.recreateTreeJSON(ritchieLocalWorkspace); err != nil { return err } } @@ -298,15 +298,15 @@ func (d deleteFormulaCmd) safeRemoveFormula(path string) error { return nil } -func (d deleteFormulaCmd) recreateTreeJson(workspace string) error { +func (d deleteFormulaCmd) recreateTreeJSON(workspace string) error { localTree, err := d.treeGen.Generate(workspace) if err != nil { return err } jsonString, _ := json.MarshalIndent(localTree, "", "\t") - pathLocalTreeJson := filepath.Join(d.ritchieHomeDir, "repos", "local", "tree.json") - if err = d.fileManager.Write(pathLocalTreeJson, jsonString); err != nil { + pathLocalTreeJSON := filepath.Join(d.ritchieHomeDir, "repos", "local", "tree.json") + if err = d.fileManager.Write(pathLocalTreeJSON, jsonString); err != nil { return err } diff --git a/pkg/cmd/delete_formula_test.go b/pkg/cmd/delete_formula_test.go index dc372834e..0d50e3da3 100644 --- a/pkg/cmd/delete_formula_test.go +++ b/pkg/cmd/delete_formula_test.go @@ -161,7 +161,7 @@ func TestNewDeleteFormulaCmd(t *testing.T) { wantErr: true, }, { - name: "Run with sucess when the selected formula is deeper in the tree", + name: "Run with success when the selected formula is deeper in the tree", fields: fieldsTestDeleteFormulaCmd{ directory: DirManagerCustomMock{ exists: func(dir string) bool { @@ -195,7 +195,7 @@ func TestNewDeleteFormulaCmd(t *testing.T) { wantErr: false, }, { - name: "Run with sucess when selected formula is less deep in the tree", + name: "Run with success when selected formula is less deep in the tree", fields: fieldsTestDeleteFormulaCmd{ directory: DirManagerCustomMock{ exists: func(dir string) bool { diff --git a/pkg/cmd/delete_workspace.go b/pkg/cmd/delete_workspace.go index 8e425999a..2f733702d 100644 --- a/pkg/cmd/delete_workspace.go +++ b/pkg/cmd/delete_workspace.go @@ -30,8 +30,8 @@ import ( ) const ( - msgWorkspaceIsNotValid = "The workspace informed is not valid" - msgEmptyWorkspaces = "There are no workspaces to delete" + msgWorkspaceIsNotValid = "the workspace informed is not valid" + msgEmptyWorkspaces = "there are no workspaces to delete" ) var ( @@ -130,7 +130,7 @@ func WorkspaceListInput( workspaces formula.Workspaces, inList prompt.InputList, ) (formula.Workspace, error) { - var items []string + items := make([]string, 0, len(workspaces)) for k, v := range workspaces { kv := fmt.Sprintf("%s (%s)", k, v) items = append(items, kv) diff --git a/pkg/cmd/formula.go b/pkg/cmd/formula.go index 63474f970..c2f249baf 100644 --- a/pkg/cmd/formula.go +++ b/pkg/cmd/formula.go @@ -217,7 +217,7 @@ func (f FormulaCommand) execFormulaFunc(repo, path string) func(cmd *cobra.Comma func addReservedFlags(flags *pflag.FlagSet) { for _, flag := range reservedFlags { - switch flag.kind { + switch flag.kind { //nolint:exhaustive case reflect.String: flags.StringP(flag.name, flag.shortName, flag.defValue.(string), flag.description) case reflect.Bool: diff --git a/pkg/cmd/init.go b/pkg/cmd/init.go index 1e9e80bc9..11d644f7c 100644 --- a/pkg/cmd/init.go +++ b/pkg/cmd/init.go @@ -54,14 +54,17 @@ if you don't want to install choose to run the formulas inside the docker. but you will need to provide a git repo with the formulas templates and add them with rit add repo command, naming this repository obligatorily as "commons". - See how to do this on the example: [https://github.com/ZupIT/ritchie-formulas/blob/master/templates/create_formula/README.md]` + "\n" + See how to do this on the example: +[https://github.com/ZupIT/ritchie-formulas/blob/master/templates/create_formula/README.md]` + "\n" CommonsRepoURL = "https://github.com/ZupIT/ritchie-formulas" ) var ( - errMsg = prompt.Yellow("It was not possible to add the commons repository at this time, please try again later.") + errMsg = prompt.Yellow("It was not possible to add the commons" + + " repository at this time, please try again later.") ErrInitCommonsRepo = errors.New(errMsg) - ErrInvalidRunType = fmt.Errorf("invalid formula run type, these run types are enabled [%v]", strings.Join(formula.RunnerTypes, ", ")) + ErrInvalidRunType = fmt.Errorf("invalid formula run type, these run types are enabled [%v]", + strings.Join(formula.RunnerTypes, ", ")) ) type initStdin struct { @@ -343,7 +346,8 @@ func (in initCmd) tutorialInit() error { const MessageTitle = "How to create new formulas:" const MessageBody = ` ∙ Run "rit create formula" ∙ Open the project with your favorite text editor.` + "\n" - const MessageCommons = "Take a look at the formulas you can run and test to see what you can with Ritchie using \"rit\"\n" + const MessageCommons = "Take a look at the formulas you can run and" + + " test to see what you can with Ritchie using \"rit\"\n" if tutorialHolder.Current == tutorialStatusEnabled { prompt.Info(tagTutorial) diff --git a/pkg/cmd/init_test.go b/pkg/cmd/init_test.go index facab3aa0..bc5e91b6b 100644 --- a/pkg/cmd/init_test.go +++ b/pkg/cmd/init_test.go @@ -372,7 +372,7 @@ func Test_initCmd_runAnyEntry(t *testing.T) { field.inList, field.inBool, metricSender, - ) + ) initStdin := NewInitCmd( field.repo, field.git, @@ -382,7 +382,7 @@ func Test_initCmd_runAnyEntry(t *testing.T) { field.inList, field.inBool, metricSender, - ) + ) initPrompt.PersistentFlags().Bool("stdin", false, "input by stdin") initStdin.PersistentFlags().Bool("stdin", true, "input by stdin") diff --git a/pkg/cmd/list.go b/pkg/cmd/list.go index 78432be66..546848d30 100644 --- a/pkg/cmd/list.go +++ b/pkg/cmd/list.go @@ -24,7 +24,7 @@ This command consists of multiple subcommands to interact with ritchie. It can be used to list repositories, credentials, or workspaces. ` -// NewListCmd create a new list instance +// NewListCmd create a new list instance. func NewListCmd() *cobra.Command { return &cobra.Command{ Use: "list SUBCOMMAND", diff --git a/pkg/cmd/list_workspace.go b/pkg/cmd/list_workspace.go index a1e749a8a..cdf1ca15a 100644 --- a/pkg/cmd/list_workspace.go +++ b/pkg/cmd/list_workspace.go @@ -95,4 +95,3 @@ func tutorialListWorkspaces(tutorialStatus string) { fmt.Println(MessageBody) } } - diff --git a/pkg/cmd/metrics.go b/pkg/cmd/metrics.go index ced0101cc..e916d9e21 100644 --- a/pkg/cmd/metrics.go +++ b/pkg/cmd/metrics.go @@ -35,7 +35,10 @@ func NewMetricsCmd(file stream.FileWriteReadExister, inList prompt.InputList) *c func (m metricsCmd) run() CommandRunnerFunc { return func(cmd *cobra.Command, args []string) error { options := []string{"yes", "no"} - choose, err := m.input.List("You want to send anonymous data about the product, feature use, statistics and crash reports?", options) + choose, err := m.input.List( + "You want to send anonymous data about the product, feature use, statistics and crash reports?", + options, + ) if err != nil { return err } diff --git a/pkg/cmd/set.go b/pkg/cmd/set.go index 0c57d46e4..27e0b8759 100644 --- a/pkg/cmd/set.go +++ b/pkg/cmd/set.go @@ -20,7 +20,7 @@ import ( "github.com/spf13/cobra" ) -// NewSetCmd creates new cmd instance +// NewSetCmd creates new cmd instance. func NewSetCmd() *cobra.Command { return &cobra.Command{ Use: "set SUBCOMMAND", diff --git a/pkg/cmd/set_context.go b/pkg/cmd/set_context.go index 45d03f4f9..bec97dfab 100644 --- a/pkg/cmd/set_context.go +++ b/pkg/cmd/set_context.go @@ -28,14 +28,14 @@ import ( const newCtx = "Type new context?" -// setContextCmd type for clean repo command +// setContextCmd type for clean repo command. type setContextCmd struct { rcontext.FindSetter prompt.InputText prompt.InputList } -// setContext type for stdin json decoder +// setContext type for stdin json decoder. type setContext struct { Context string `json:"context"` } diff --git a/pkg/cmd/set_credential.go b/pkg/cmd/set_credential.go index c33e29f84..ec70d077d 100644 --- a/pkg/cmd/set_credential.go +++ b/pkg/cmd/set_credential.go @@ -32,7 +32,7 @@ import ( var inputTypes = []string{"plain text", "secret"} var inputWay = []string{"type", "file"} -// setCredentialCmd type for set credential command +// setCredentialCmd type for set credential command. type setCredentialCmd struct { credential.Setter credential.ReaderWriterPather @@ -43,7 +43,7 @@ type setCredentialCmd struct { prompt.InputPassword } -// NewSetCredentialCmd creates a new cmd instance +// NewSetCredentialCmd creates a new cmd instance. func NewSetCredentialCmd( credSetter credential.Setter, credFile credential.ReaderWriterPather, diff --git a/pkg/cmd/tutorial.go b/pkg/cmd/tutorial.go index c36af8692..6f468a648 100644 --- a/pkg/cmd/tutorial.go +++ b/pkg/cmd/tutorial.go @@ -36,7 +36,7 @@ const ( tutorialStatusDisabled = "disabled" ) -// NewTutorialCmd creates tutorial command +// NewTutorialCmd creates tutorial command. func NewTutorialCmd(homePath string, il prompt.InputList, fs rtutorial.FindSetter) *cobra.Command { o := tutorialCmd{homePath, il, fs} diff --git a/pkg/cmd/update.go b/pkg/cmd/update.go index 2772c2acd..44749e038 100644 --- a/pkg/cmd/update.go +++ b/pkg/cmd/update.go @@ -18,7 +18,7 @@ package cmd import "github.com/spf13/cobra" -// NewUpdateCmd create a new update instance +// NewUpdateCmd create a new update instance. func NewUpdateCmd() *cobra.Command { return &cobra.Command{ Use: "update SUBCOMMAND", diff --git a/pkg/cmd/update_repo.go b/pkg/cmd/update_repo.go index 798e12ab6..0f564f9cc 100644 --- a/pkg/cmd/update_repo.go +++ b/pkg/cmd/update_repo.go @@ -50,7 +50,7 @@ func NewUpdateRepoCmd( repoProviders formula.RepoProviders, inText prompt.InputText, inPass prompt.InputPassword, - inUrl prompt.InputURL, + inURL prompt.InputURL, inList prompt.InputList, inBool prompt.InputBool, inInt prompt.InputInt, @@ -60,7 +60,7 @@ func NewUpdateRepoCmd( repo: repo, repoProviders: repoProviders, InputText: inText, - InputURL: inUrl, + InputURL: inURL, InputList: inList, InputBool: inBool, InputInt: inInt, diff --git a/pkg/cmd/upgrade.go b/pkg/cmd/upgrade.go index 2d2b798fb..dcfd5de2f 100644 --- a/pkg/cmd/upgrade.go +++ b/pkg/cmd/upgrade.go @@ -88,8 +88,8 @@ func (u UpgradeCmd) runFunc() CommandRunnerFunc { return prompt.NewError(err.Error() + "\n") } - upgradeUrl := u.Url(runtime.GOOS) - if err := u.Run(upgradeUrl); err != nil { + upgradeURL := u.Url(runtime.GOOS) + if err := u.Run(upgradeURL); err != nil { return prompt.NewError(err.Error() + "\n") } diff --git a/pkg/commands/builder.go b/pkg/commands/builder.go index f0de44a01..fa5b52e70 100644 --- a/pkg/commands/builder.go +++ b/pkg/commands/builder.go @@ -170,7 +170,7 @@ func Build() *cobra.Command { createBuilder := formula.NewCreateBuilder(formulaCreator, formulaLocalBuilder) versionManager := version.NewManager( - version.StableVersionUrl, + version.StableVersionURL, fileManager, ) upgradeDefaultUpdater := upgrade.NewDefaultUpdater() diff --git a/pkg/credential/credential.go b/pkg/credential/credential.go index 2040b6e67..8a8a3201c 100644 --- a/pkg/credential/credential.go +++ b/pkg/credential/credential.go @@ -16,7 +16,7 @@ package credential -// Info represents a credential information of the user. +// Detail represents a credential information of the user. type Detail struct { Username string `json:"username"` Credential Credential `json:"credential"` diff --git a/pkg/file/fileutil/file_util.go b/pkg/file/fileutil/file_util.go index 9cb5d7f78..e3ec54027 100644 --- a/pkg/file/fileutil/file_util.go +++ b/pkg/file/fileutil/file_util.go @@ -78,8 +78,12 @@ func readFilesDir(path string) ([]os.FileInfo, error) { if err != nil { return nil, err } + defer f.Close() + fl, err := f.Readdir(-1) - f.Close() + if err != nil { + return nil, err + } return fl, err } diff --git a/pkg/formula/builder/shell.go b/pkg/formula/builder/shell.go index 63afabf8d..e998c0b09 100644 --- a/pkg/formula/builder/shell.go +++ b/pkg/formula/builder/shell.go @@ -49,7 +49,7 @@ func (sh ShellManager) Build(formulaPath string) error { } var stderr bytes.Buffer execFile := filepath.Join(formulaPath, buildSh) - cmd := exec.Command(execFile) + cmd := exec.Command(execFile) //nolint:gosec cmd.Stderr = &stderr if err := cmd.Run(); err != nil { return fmt.Errorf(errMsgFmt, ErrBuildFormulaShell, stderr.String()) diff --git a/pkg/formula/creator/creator.go b/pkg/formula/creator/creator.go index 8b2a743d1..96ec1c03c 100644 --- a/pkg/formula/creator/creator.go +++ b/pkg/formula/creator/creator.go @@ -81,7 +81,13 @@ func (c CreateManager) isValidCmd(fPath string) error { return nil } -func (c CreateManager) generateFormulaFiles(fPath, lang, fCmdName, workSpcPath string, modifiers []modifier.Modifier) error { +func (c CreateManager) generateFormulaFiles( + fPath, + lang, + fCmdName, + workSpcPath string, + modifiers []modifier.Modifier, +) error { if err := c.dir.Create(fPath); err != nil { return err diff --git a/pkg/formula/creator/template/manager.go b/pkg/formula/creator/template/manager.go index 6766ffdca..d063e08f6 100644 --- a/pkg/formula/creator/template/manager.go +++ b/pkg/formula/creator/template/manager.go @@ -107,7 +107,7 @@ func readDirRecursive(dir string) ([]File, error) { if err != nil { return nil, err } - var fileNames []File + var fileNames []File //nolint:prealloc for _, f := range files { if f.IsDir() { dirFiles, err := readDirRecursive(filepath.Join(dir, f.Name())) diff --git a/pkg/formula/input/prompt/prompt.go b/pkg/formula/input/prompt/prompt.go index 296087303..4dd42d911 100644 --- a/pkg/formula/input/prompt/prompt.go +++ b/pkg/formula/input/prompt/prompt.go @@ -132,11 +132,11 @@ func (in InputManager) Inputs(cmd *exec.Cmd, setup formula.Setup, _ *pflag.FlagS return nil } -func checkForSameEnv(envKey string){ +func checkForSameEnv(envKey string) { envKey = strings.ToUpper(envKey) if _, exist := os.LookupEnv(envKey); exist { warnMsg := fmt.Sprintf( - "The input param %s has the same name of a machine variable." + + "The input param %s has the same name of a machine variable."+ " It will probably result on unexpect behavior", envKey) prompt.Warning(warnMsg) } @@ -265,15 +265,23 @@ func makeRequest(info formula.RequestInfo) (interface{}, error) { if err != nil { return nil, err } + defer response.Body.Close() if response.StatusCode < 200 || response.StatusCode > 299 { return nil, fmt.Errorf("dynamic list request got http status %d expecting some 2xx range", response.StatusCode) } - body, _ := ioutil.ReadAll(response.Body) + body, err := ioutil.ReadAll(response.Body) + if err != nil { + return nil, err + } + requestData := interface{}(nil) - _ = json.Unmarshal(body, &requestData) + if err := json.Unmarshal(body, &requestData); err != nil { + return nil, err + } + return requestData, nil } diff --git a/pkg/formula/repo.go b/pkg/formula/repo.go index 8eb2d51e8..77dac3baf 100644 --- a/pkg/formula/repo.go +++ b/pkg/formula/repo.go @@ -81,7 +81,7 @@ func (re RepoProviders) Resolve(provider RepoProvider) Git { } func (re RepoProviders) List() []string { - var providers []string + providers := make([]string, 0, len(re)) for provider := range re { providers = append(providers, provider.String()) } diff --git a/pkg/formula/repo/list_creator.go b/pkg/formula/repo/list_creator.go index 329f79126..ae90b8f2b 100644 --- a/pkg/formula/repo/list_creator.go +++ b/pkg/formula/repo/list_creator.go @@ -23,7 +23,10 @@ type ListCreateManager struct { formula.RepositoryCreator } -func NewListCreator(repoList formula.RepositoryLister, repoCreate formula.RepositoryCreator) formula.RepositoryListCreator { +func NewListCreator( + repoList formula.RepositoryLister, + repoCreate formula.RepositoryCreator, +) formula.RepositoryListCreator { return ListCreateManager{ RepositoryLister: repoList, RepositoryCreator: repoCreate, diff --git a/pkg/formula/repo/list_updater.go b/pkg/formula/repo/list_updater.go index 2e659dda6..e63f135f7 100644 --- a/pkg/formula/repo/list_updater.go +++ b/pkg/formula/repo/list_updater.go @@ -23,7 +23,10 @@ type ListUpdateManager struct { formula.RepositoryUpdater } -func NewListUpdater(repoList formula.RepositoryLister, repoUpdate formula.RepositoryUpdater) formula.RepositoryListUpdater { +func NewListUpdater( + repoList formula.RepositoryLister, + repoUpdate formula.RepositoryUpdater, +) formula.RepositoryListUpdater { return ListUpdateManager{ RepositoryLister: repoList, RepositoryUpdater: repoUpdate, diff --git a/pkg/formula/repo/priority_setter_test.go b/pkg/formula/repo/priority_setter_test.go index 4c6d8d9f5..a7433134d 100644 --- a/pkg/formula/repo/priority_setter_test.go +++ b/pkg/formula/repo/priority_setter_test.go @@ -51,7 +51,7 @@ func TestSetPriorityManager_SetPriority(t *testing.T) { name: "Setting priority test success", fields: fields{ ritHome: func() string { - ritHomePath := filepath.Join(os.TempDir(), "test-priority-setter-repo-sucess") + ritHomePath := filepath.Join(os.TempDir(), "test-priority-setter-repo-success") _ = dirManager.Remove(ritHomePath) _ = dirManager.Create(ritHomePath) _ = dirManager.Create(filepath.Join(ritHomePath, "repos")) diff --git a/pkg/formula/runner/config_runner_test.go b/pkg/formula/runner/config_runner_test.go index 9c8f77f6b..2321f6392 100644 --- a/pkg/formula/runner/config_runner_test.go +++ b/pkg/formula/runner/config_runner_test.go @@ -190,4 +190,4 @@ func (fi fileManagerMock) Remove(path string) error { func (fi fileManagerMock) ListNews(oldPath, newPath string) ([]string, error) { return fi.listNews, fi.lErr -} \ No newline at end of file +} diff --git a/pkg/formula/runner/docker/pre_run.go b/pkg/formula/runner/docker/pre_run.go index 98d1a6c7f..1b59a968f 100644 --- a/pkg/formula/runner/docker/pre_run.go +++ b/pkg/formula/runner/docker/pre_run.go @@ -42,9 +42,15 @@ Config file path not found: %s` ) var ( - ErrDockerNotInstalled = errors.New("you must have the docker installed to run formulas inside it, check how to install it at: [https://docs.docker.com/get-docker]") - ErrDockerImageNotFound = errors.New("config.json does not contain the \"dockerImageBuilder\" field, to run this formula with docker add a docker image name to it") - ErrDockerfileNotFound = errors.New("the formula cannot be executed inside the docker, you must add a \"Dockerfile\" to execute the formula inside the docker") + ErrDockerNotInstalled = errors.New( + "you must have the docker installed to run formulas inside it, check how to install it at: [https://docs.docker.com/get-docker]", + ) + ErrDockerImageNotFound = errors.New( + "config.json does not contain the \"dockerImageBuilder\" field, to run this formula with docker add a docker image name to it", + ) + ErrDockerfileNotFound = errors.New( + "the formula cannot be executed inside the docker, you must add a \"Dockerfile\" to execute the formula inside the docker", + ) ) var _ formula.PreRunner = PreRunManager{} @@ -185,6 +191,7 @@ func buildRunImg(def formula.Definition) (string, error) { containerId = strings.ToLower(containerId) args := []string{"build", "-t", containerId, "."} + //nolint:gosec cmd := exec.Command(dockerCmd, args...) // Run command "docker build -t (randomId) ." cmd.Stderr = os.Stderr cmd.Stdout = os.Stdout diff --git a/pkg/formula/runner/docker/runner.go b/pkg/formula/runner/docker/runner.go index e875ce6e3..d8f929602 100644 --- a/pkg/formula/runner/docker/runner.go +++ b/pkg/formula/runner/docker/runner.go @@ -96,11 +96,37 @@ func (ru RunManager) runDocker(setup formula.Setup, inputType api.TermInputType, homeDirVolume := fmt.Sprintf("%s/.rit:/root/.rit", ru.homeDir) var args []string if isatty.IsTerminal(os.Stdout.Fd()) && inputType != api.Stdin { - args = []string{"run", "--rm", "-it", "--env-file", envFile, "-v", volume, "-v", homeDirVolume, "--name", setup.ContainerId, setup.ContainerId} + args = []string{ + "run", + "--rm", + "-it", + "--env-file", + envFile, + "-v", + volume, + "-v", + homeDirVolume, + "--name", + setup.ContainerId, + setup.ContainerId, + } } else { - args = []string{"run", "--rm", "--env-file", envFile, "-v", volume, "-v", homeDirVolume, "--name", setup.ContainerId, setup.ContainerId} + args = []string{ + "run", + "--rm", + "--env-file", + envFile, + "-v", + volume, + "-v", + homeDirVolume, + "--name", + setup.ContainerId, + setup.ContainerId, + } } + //nolint:gosec,lll cmd := exec.Command(dockerCmd, args...) // Run command "docker run -env-file .env -v "$(pwd):/app" --name (randomId) (randomId)" cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout diff --git a/pkg/formula/tree/default_tree.go b/pkg/formula/tree/default_tree.go index 0b6a77e84..ac595198b 100644 --- a/pkg/formula/tree/default_tree.go +++ b/pkg/formula/tree/default_tree.go @@ -42,8 +42,22 @@ type Manager struct { isRootCommand bool } -func NewTreeManager(ritchieHome string, rl formula.RepositoryLister, coreCmds []api.Command, file stream.FileReadExister, rp formula.RepoProviders, isRootCommand bool) Manager { - return Manager{ritchieHome: ritchieHome, repoLister: rl, coreCmds: coreCmds, file: file, repoProviders: rp, isRootCommand: isRootCommand} +func NewTreeManager( + ritchieHome string, + rl formula.RepositoryLister, + coreCmds []api.Command, + file stream.FileReadExister, + rp formula.RepoProviders, + isRootCommand bool, +) Manager { + return Manager{ + ritchieHome: ritchieHome, + repoLister: rl, + coreCmds: coreCmds, + file: file, + repoProviders: rp, + isRootCommand: isRootCommand, + } } func (d Manager) Tree() (map[string]formula.Tree, error) { diff --git a/pkg/formula/tree/default_tree_test.go b/pkg/formula/tree/default_tree_test.go index 3bff9a4ca..768e8925f 100644 --- a/pkg/formula/tree/default_tree_test.go +++ b/pkg/formula/tree/default_tree_test.go @@ -213,7 +213,7 @@ func TestTree(t *testing.T) { expectedTree map[string]formula.Tree }{ { - name: "run in sucess", + name: "run in success", in: in{ repo: repositoryListerCustomMock{ list: func() (formula.Repos, error) { diff --git a/pkg/git/git.go b/pkg/git/git.go index 4f9580015..e8834ca2f 100644 --- a/pkg/git/git.go +++ b/pkg/git/git.go @@ -24,7 +24,7 @@ type Tag struct { type Tags []Tag func (t Tags) Names() []string { - var tags []string + tags := make([]string, 0, len(t)) for i := range t { tags = append(tags, t[i].Name) } diff --git a/pkg/git/github/github.go b/pkg/git/github/github.go index 1107d0a6e..31564cbed 100644 --- a/pkg/git/github/github.go +++ b/pkg/git/github/github.go @@ -24,9 +24,9 @@ import ( ) const ( - ZipUrlPattern = "https://api.github.com/repos/%s/%s/zipball/%s" - TagsUrlPattern = "https://api.github.com/repos/%s/%s/releases" - LatestTagUrlPattern = "https://api.github.com/repos/%s/%s/releases/latest" + ZipUrlPattern = "https://api.github.com/repos/%s/%s/zipball/%s" //nolint:stylecheck + TagsUrlPattern = "https://api.github.com/repos/%s/%s/releases" //nolint:stylecheck + LatestTagUrlPattern = "https://api.github.com/repos/%s/%s/releases/latest" //nolint:stylecheck ) type DefaultRepoInfo struct { @@ -51,19 +51,19 @@ func NewRepoInfo(url string, token string) git.RepoInfo { // ZipUrl returns the GitHub API URL for download zipball repository // e.g. https://api.github.com/repos/{{owner}}/{{repo}}/zipball/{{tag-version}} -func (in DefaultRepoInfo) ZipUrl(version string) string { +func (in DefaultRepoInfo) ZipUrl(version string) string { //nolint:stylecheck return fmt.Sprintf(ZipUrlPattern, in.owner, in.repo, version) } // TagsUrl returns the GitHub API URL for get all tags // e.g. https://api.github.com/repos/{{owner}}/{{repo}}/tags -func (in DefaultRepoInfo) TagsUrl() string { +func (in DefaultRepoInfo) TagsUrl() string { //nolint:stylecheck return fmt.Sprintf(TagsUrlPattern, in.owner, in.repo) } // LatestTagUrl returns the GitHub API URL for get latest tag release // https://api.github.com/repos/:owner/:repo/releases/latest -func (in DefaultRepoInfo) LatestTagUrl() string { +func (in DefaultRepoInfo) LatestTagUrl() string { //nolint:stylecheck return fmt.Sprintf(LatestTagUrlPattern, in.owner, in.repo) } diff --git a/pkg/git/github/repository.go b/pkg/git/github/repository.go index b25bc5f00..553fba7e2 100644 --- a/pkg/git/github/repository.go +++ b/pkg/git/github/repository.go @@ -17,6 +17,7 @@ package github import ( + "context" "encoding/json" "errors" "fmt" @@ -37,8 +38,8 @@ func NewRepoManager(client *http.Client) RepoManager { } func (re RepoManager) Zipball(info git.RepoInfo, version string) (io.ReadCloser, error) { - zipUrl := info.ZipUrl(version) - req, err := http.NewRequest(http.MethodGet, zipUrl, nil) + zipURL := info.ZipUrl(version) + req, err := http.NewRequestWithContext(context.TODO(), http.MethodGet, zipURL, nil) if err != nil { return nil, err } @@ -49,7 +50,7 @@ func (re RepoManager) Zipball(info git.RepoInfo, version string) (io.ReadCloser, } req.Header.Add(headers.Accept, "application/vnd.github.v3+json") - resp, err := re.client.Do(req) + resp, err := re.client.Do(req) //nolint:bodyclose if err != nil { return nil, err } @@ -58,8 +59,8 @@ func (re RepoManager) Zipball(info git.RepoInfo, version string) (io.ReadCloser, } func (re RepoManager) Tags(info git.RepoInfo) (git.Tags, error) { - apiUrl := info.TagsUrl() - req, err := http.NewRequest(http.MethodGet, apiUrl, nil) + apiURL := info.TagsUrl() + req, err := http.NewRequestWithContext(context.TODO(), http.MethodGet, apiURL, nil) if err != nil { return git.Tags{}, err } @@ -78,7 +79,8 @@ func (re RepoManager) Tags(info git.RepoInfo) (git.Tags, error) { defer res.Body.Close() if res.StatusCode != http.StatusOK { - errorMessage := fmt.Sprintf("There was an error adding the repository, status: %d - %s.", res.StatusCode, http.StatusText(res.StatusCode)) + errorMessage := fmt.Sprintf("There was an error adding the repository,"+ + " status: %d - %s.", res.StatusCode, http.StatusText(res.StatusCode)) return git.Tags{}, errors.New(errorMessage) } @@ -91,8 +93,8 @@ func (re RepoManager) Tags(info git.RepoInfo) (git.Tags, error) { } func (re RepoManager) LatestTag(info git.RepoInfo) (git.Tag, error) { - apiUrl := info.LatestTagUrl() - req, err := http.NewRequest(http.MethodGet, apiUrl, nil) + apiURL := info.LatestTagUrl() + req, err := http.NewRequestWithContext(context.TODO(), http.MethodGet, apiURL, nil) if err != nil { return git.Tag{}, err } diff --git a/pkg/git/gitlab/repository.go b/pkg/git/gitlab/repository.go index 5c068e9fa..2a5176405 100644 --- a/pkg/git/gitlab/repository.go +++ b/pkg/git/gitlab/repository.go @@ -16,6 +16,7 @@ package gitlab import ( + "context" "encoding/json" "errors" "fmt" @@ -37,7 +38,7 @@ func NewRepoManager(client *http.Client) RepoManager { func (re RepoManager) Zipball(info git.RepoInfo, version string) (io.ReadCloser, error) { zipUrl := info.ZipUrl(version) - req, err := http.NewRequest(http.MethodGet, zipUrl, nil) + req, err := http.NewRequestWithContext(context.TODO(), http.MethodGet, zipUrl, nil) if err != nil { return nil, err } @@ -65,7 +66,7 @@ func (re RepoManager) Zipball(info git.RepoInfo, version string) (io.ReadCloser, func (re RepoManager) Tags(info git.RepoInfo) (git.Tags, error) { apiUrl := info.TagsUrl() - req, err := http.NewRequest(http.MethodGet, apiUrl, nil) + req, err := http.NewRequestWithContext(context.TODO(), http.MethodGet, apiUrl, nil) if err != nil { return git.Tags{}, err } @@ -97,7 +98,7 @@ func (re RepoManager) Tags(info git.RepoInfo) (git.Tags, error) { func (re RepoManager) LatestTag(info git.RepoInfo) (git.Tag, error) { apiUrl := info.LatestTagUrl() - req, err := http.NewRequest(http.MethodGet, apiUrl, nil) + req, err := http.NewRequestWithContext(context.TODO(), http.MethodGet, apiUrl, nil) if err != nil { return git.Tag{}, err } diff --git a/pkg/metric/data_collector.go b/pkg/metric/data_collector.go index 7192af511..08917efef 100644 --- a/pkg/metric/data_collector.go +++ b/pkg/metric/data_collector.go @@ -53,7 +53,11 @@ func NewDataCollector( } } -func (d DataCollectorManager) Collect(commandExecutionTime float64, ritVersion string, commandError ...string) (APIData, error) { +func (d DataCollectorManager) Collect( + commandExecutionTime float64, + ritVersion string, + commandError ...string, +) (APIData, error) { userId, err := d.userId.Generate() if err != nil { return APIData{}, err diff --git a/pkg/metric/http_sender.go b/pkg/metric/http_sender.go index b2386134b..de9809d47 100644 --- a/pkg/metric/http_sender.go +++ b/pkg/metric/http_sender.go @@ -18,6 +18,7 @@ package metric import ( "bytes" + "context" "encoding/json" "net/http" ) @@ -47,12 +48,18 @@ func (sm SendManagerHttp) Send(APIData APIData) { return } - req, err := http.NewRequest(http.MethodPost, sm.URL, bytes.NewBuffer(reqBody)) + req, err := http.NewRequestWithContext(context.TODO(), http.MethodPost, sm.URL, bytes.NewBuffer(reqBody)) if err != nil { return } req.SetBasicAuth(BasicUser, BasicPass) req.Header.Add("Content-Type", "application/json") - _, _ = sm.client.Do(req) + resp, err := sm.client.Do(req) + if err != nil { + return + } + if err := resp.Body.Close(); err != nil { + return + } } diff --git a/pkg/metric/user_id_generator.go b/pkg/metric/user_id_generator.go index cffa7af4d..db86aa204 100644 --- a/pkg/metric/user_id_generator.go +++ b/pkg/metric/user_id_generator.go @@ -30,7 +30,7 @@ type UserIdManager struct { hash hash.Hash } -func NewUserIdGenerator() UserIdManager { +func NewUserIdGenerator() UserIdManager { //nolint:stylecheck return UserIdManager{hash: sha256.New()} } @@ -45,7 +45,7 @@ func (us UserIdManager) Generate() (UserId, error) { return "", err } - userId := hex.EncodeToString(us.hash.Sum(nil)) + userID := hex.EncodeToString(us.hash.Sum(nil)) - return UserId(userId), nil + return UserId(userID), nil } diff --git a/pkg/stream/mocks/mock.go b/pkg/stream/mocks/mock.go index 96945af36..cbf0a3d62 100644 --- a/pkg/stream/mocks/mock.go +++ b/pkg/stream/mocks/mock.go @@ -17,7 +17,7 @@ package stream type FileReaderCustomMock struct { - ReadMock func(path string) ([]byte, error) + ReadMock func(path string) ([]byte, error) } func (fmr FileReaderCustomMock) Read(path string) ([]byte, error) { diff --git a/pkg/stream/streams/stream.go b/pkg/stream/streams/stream.go index 1f2a9bd7c..a6172ef01 100644 --- a/pkg/stream/streams/stream.go +++ b/pkg/stream/streams/stream.go @@ -29,7 +29,6 @@ func Unzip(src string, dest string) error { if err != nil { return err } - defer reader.Close() for _, file := range reader.Reader.File { diff --git a/pkg/upgrade/manager.go b/pkg/upgrade/manager.go index d3b299c1b..449e728d5 100644 --- a/pkg/upgrade/manager.go +++ b/pkg/upgrade/manager.go @@ -25,7 +25,7 @@ import ( ) type Manager interface { - Run(upgradeUrl string) error + Run(upgradeURL string) error } type DefaultManager struct { @@ -36,12 +36,12 @@ func NewDefaultManager(Updater updater) DefaultManager { return DefaultManager{updater: Updater} } -func (m DefaultManager) Run(upgradeUrl string) error { - if upgradeUrl == "" { +func (m DefaultManager) Run(upgradeURL string) error { + if upgradeURL == "" { return errors.New("fail to resolve upgrade url") } - resp, err := http.Get(upgradeUrl) + resp, err := http.Get(upgradeURL) //nolint:noctx if err != nil { return errors.New("fail to download stable version") } diff --git a/pkg/upgrade/manager_test.go b/pkg/upgrade/manager_test.go index 6f216234e..8744b5650 100644 --- a/pkg/upgrade/manager_test.go +++ b/pkg/upgrade/manager_test.go @@ -37,7 +37,7 @@ func (u stubUpdater) Apply(reader io.Reader, opts update.Options) error { func TestDefaultManager_Run(t *testing.T) { type in struct { updater updater - upgradeUrl string + upgradeURL string } type args struct { } @@ -51,7 +51,7 @@ func TestDefaultManager_Run(t *testing.T) { name: "Run with success", in: in{ updater: NewDefaultUpdater(), - upgradeUrl: httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})).URL, + upgradeURL: httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})).URL, }, wantErr: false, }, @@ -61,7 +61,7 @@ func TestDefaultManager_Run(t *testing.T) { updater: stubUpdater{apply: func(reader io.Reader, opts update.Options) error { return nil }}, - upgradeUrl: "", + upgradeURL: "", }, wantErr: true, }, @@ -71,7 +71,7 @@ func TestDefaultManager_Run(t *testing.T) { updater: stubUpdater{apply: func(reader io.Reader, opts update.Options) error { return nil }}, - upgradeUrl: "some url", + upgradeURL: "some url", }, wantErr: true, }, @@ -81,7 +81,7 @@ func TestDefaultManager_Run(t *testing.T) { updater: stubUpdater{apply: func(reader io.Reader, opts update.Options) error { return nil }}, - upgradeUrl: httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + upgradeURL: httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(404) })).URL, }, @@ -93,7 +93,7 @@ func TestDefaultManager_Run(t *testing.T) { updater: stubUpdater{apply: func(reader io.Reader, opts update.Options) error { return errors.New("some error") }}, - upgradeUrl: httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})).URL, + upgradeURL: httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})).URL, }, wantErr: true, }, @@ -101,7 +101,7 @@ func TestDefaultManager_Run(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { m := NewDefaultManager(tt.in.updater) - if err := m.Run(tt.in.upgradeUrl); (err != nil) != tt.wantErr { + if err := m.Run(tt.in.upgradeURL); (err != nil) != tt.wantErr { t.Errorf("Run() error = %v, wantErr %v", err, tt.wantErr) } }) diff --git a/pkg/upgrade/updater.go b/pkg/upgrade/updater.go index 0c02cec08..cb1880cfb 100644 --- a/pkg/upgrade/updater.go +++ b/pkg/upgrade/updater.go @@ -23,7 +23,7 @@ import ( ) const ( - upgradeUrlFormat = "https://commons-repo.ritchiecli.io/%s/%s/rit" + upgradeURLFormat = "https://commons-repo.ritchiecli.io/%s/%s/rit" ) type updater interface { diff --git a/pkg/upgrade/url_finder.go b/pkg/upgrade/url_finder.go index 8312317a4..a5600ae33 100644 --- a/pkg/upgrade/url_finder.go +++ b/pkg/upgrade/url_finder.go @@ -23,31 +23,30 @@ import ( "github.com/ZupIT/ritchie-cli/pkg/version" ) -type UrlFinder interface { +type UrlFinder interface { //nolint:stylecheck Url(os string) string } -type DefaultUrlFinder struct { +type DefaultUrlFinder struct { //nolint:stylecheck version version.Resolver } -func NewDefaultUrlFinder(version version.Resolver) DefaultUrlFinder { +func NewDefaultUrlFinder(version version.Resolver) DefaultUrlFinder { //nolint:stylecheck return DefaultUrlFinder{version: version} } -func (duf DefaultUrlFinder) Url(os string) string { - //stableVersion, err := resolver.StableVersion() +func (duf DefaultUrlFinder) Url(os string) string { //nolint:stylecheck stableVersion, err := duf.version.StableVersion() if err != nil { return "" } - upgradeUrl := fmt.Sprintf(upgradeUrlFormat, stableVersion, os) + upgradeURL := fmt.Sprintf(upgradeURLFormat, stableVersion, os) if os == osutil.Windows { - upgradeUrl += ".exe" + upgradeURL += ".exe" } - return upgradeUrl + return upgradeURL } diff --git a/pkg/version/version.go b/pkg/version/version.go index 12e962761..bf61c9db9 100644 --- a/pkg/version/version.go +++ b/pkg/version/version.go @@ -35,22 +35,22 @@ const ( // stableVersionFileCache is the file name to cache stableVersion stableVersionFileCache = "stable-version-cache.json" - StableVersionUrl = "https://commons-repo.ritchiecli.io/stable.txt" + StableVersionURL = "https://commons-repo.ritchiecli.io/stable.txt" ) type Manager struct { - stableUrl string + stableURL string file stream.FileWriteReadExister } var _ Resolver = Manager{} func NewManager( - stableVersionUrl string, + stableVersionURL string, file stream.FileWriteReadExister, ) Manager { return Manager{ - stableUrl: stableVersionUrl, + stableURL: stableVersionURL, file: file, } } @@ -86,7 +86,7 @@ func (m Manager) StableVersion() (string, error) { } if shouldRequestAndSave { - stableVersion, err := requestStableVersion(m.stableUrl) + stableVersion, err := requestStableVersion(m.stableURL) if err != nil { return "", err } @@ -110,7 +110,7 @@ func (m Manager) VerifyNewVersion(current, installed string) string { func (m Manager) UpdateCache() error { cachePath := filepath.Join(api.RitchieHomeDir(), stableVersionFileCache) - stableVersion, err := requestStableVersion(m.stableUrl) + stableVersion, err := requestStableVersion(m.stableURL) if err != nil { return err } @@ -121,11 +121,12 @@ func (m Manager) UpdateCache() error { return nil } -func requestStableVersion(stableVersionUrl string) (string, error) { - response, err := http.Get(stableVersionUrl) +func requestStableVersion(stableVersionURL string) (string, error) { + response, err := http.Get(stableVersionURL) if err != nil { return "", err } + defer response.Body.Close() if response.StatusCode != http.StatusOK { return "", fmt.Errorf("response status is not %d", http.StatusOK) @@ -151,9 +152,12 @@ func saveCache( ExpiresAt: time.Now().Add(time.Hour * 10).Unix(), } - newCacheJson, _ := json.Marshal(newCache) + newCacheJSON, err := json.Marshal(newCache) + if err != nil { + return err + } - if err := file.Write(cachePath, newCacheJson); err != nil { + if err := file.Write(cachePath, newCacheJSON); err != nil { return err } return nil diff --git a/pkg/version/version_test.go b/pkg/version/version_test.go index 1b0e0de68..3aa37644f 100644 --- a/pkg/version/version_test.go +++ b/pkg/version/version_test.go @@ -55,9 +55,9 @@ func TestManager_StableVersion(t *testing.T) { notExpiredCache := time.Now().Add(time.Hour).Unix() type in struct { - StableVersionUrl string + StableVersionURL string file stream.FileWriteReadExister - HttpClient *http.Client + HTTPClient *http.Client } tests := []struct { name string @@ -68,7 +68,7 @@ func TestManager_StableVersion(t *testing.T) { { name: "success get stableVersion from cache", in: in{ - StableVersionUrl: "any value", + StableVersionURL: "any value", file: sMocks.FileWriteReadExisterCustomMock{ ExistsMock: func(path string) bool { return true @@ -84,7 +84,7 @@ func TestManager_StableVersion(t *testing.T) { { name: "error reading from cache", in: in{ - StableVersionUrl: "any value", + StableVersionURL: "any value", file: sMocks.FileWriteReadExisterCustomMock{ ExistsMock: func(path string) bool { return true @@ -99,7 +99,7 @@ func TestManager_StableVersion(t *testing.T) { { name: "error on unmarshal cache data", in: in{ - StableVersionUrl: "any value", + StableVersionURL: "any value", file: sMocks.FileWriteReadExisterCustomMock{ ExistsMock: func(path string) bool { return true @@ -114,7 +114,7 @@ func TestManager_StableVersion(t *testing.T) { { name: "error on request stable version with no url", in: in{ - StableVersionUrl: "", + StableVersionURL: "", file: sMocks.FileWriteReadExisterCustomMock{ ExistsMock: func(path string) bool { return true @@ -123,14 +123,14 @@ func TestManager_StableVersion(t *testing.T) { return buildStableBody(1), nil }, }, - HttpClient: okStub.Client(), + HTTPClient: okStub.Client(), }, wantErr: true, }, { name: "error on request stable status not 200", in: in{ - StableVersionUrl: internalErrorStub.URL, + StableVersionURL: internalErrorStub.URL, file: sMocks.FileWriteReadExisterCustomMock{ ExistsMock: func(path string) bool { return false @@ -145,7 +145,7 @@ func TestManager_StableVersion(t *testing.T) { { name: "error on saving cache", in: in{ - StableVersionUrl: okStub.URL, + StableVersionURL: okStub.URL, file: sMocks.FileWriteReadExisterCustomMock{ ExistsMock: func(path string) bool { return true @@ -163,7 +163,7 @@ func TestManager_StableVersion(t *testing.T) { { name: "error reading bytes from response body", in: in{ - StableVersionUrl: wrongContentLengthStub.URL, + StableVersionURL: wrongContentLengthStub.URL, file: sMocks.FileWriteReadExisterCustomMock{ ExistsMock: func(path string) bool { return false @@ -181,7 +181,7 @@ func TestManager_StableVersion(t *testing.T) { { name: "success case when cache expired", in: in{ - StableVersionUrl: okStub.URL, + StableVersionURL: okStub.URL, file: sMocks.FileWriteReadExisterCustomMock{ ExistsMock: func(path string) bool { return false @@ -200,7 +200,7 @@ func TestManager_StableVersion(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - r := NewManager(tt.in.StableVersionUrl, tt.in.file) + r := NewManager(tt.in.StableVersionURL, tt.in.file) got, err := r.StableVersion() if (err != nil) != tt.wantErr { t.Errorf("StableVersion() error = %v, wantErr %v", err, tt.wantErr) @@ -214,9 +214,9 @@ func TestManager_StableVersion(t *testing.T) { func TestManager_UpdateCache(t *testing.T) { type in struct { - StableVersionUrl string + StableVersionURL string file stream.FileWriteReadExister - HttpClient *http.Client + HTTPClient *http.Client } tests := []struct { name string @@ -226,39 +226,39 @@ func TestManager_UpdateCache(t *testing.T) { { name: "success get update cache", in: in{ - StableVersionUrl: okStub.URL, + StableVersionURL: okStub.URL, file: sMocks.FileWriteReadExisterCustomMock{ WriteMock: func(path string, content []byte) error { return nil }, }, - HttpClient: okStub.Client(), + HTTPClient: okStub.Client(), }, wantErr: false, }, { name: "error on request during update cache", in: in{ - StableVersionUrl: internalErrorStub.URL, + StableVersionURL: internalErrorStub.URL, file: sMocks.FileWriteReadExisterCustomMock{ WriteMock: func(path string, content []byte) error { return nil }, }, - HttpClient: internalErrorStub.Client(), + HTTPClient: internalErrorStub.Client(), }, wantErr: true, }, { name: "error on writing file", in: in{ - StableVersionUrl: okStub.URL, + StableVersionURL: okStub.URL, file: sMocks.FileWriteReadExisterCustomMock{ WriteMock: func(path string, content []byte) error { return errors.New("writing file error") }, }, - HttpClient: internalErrorStub.Client(), + HTTPClient: internalErrorStub.Client(), }, wantErr: true, }, @@ -266,7 +266,7 @@ func TestManager_UpdateCache(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - r := NewManager(tt.in.StableVersionUrl, tt.in.file) + r := NewManager(tt.in.StableVersionURL, tt.in.file) err := r.UpdateCache() if (err != nil) != tt.wantErr { t.Errorf("UpdateCache() error = %v, wantErr %v", err, tt.wantErr)