Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to avoid global variables? #1336

Closed
frederikhors opened this issue Feb 3, 2021 · 6 comments
Closed

How to avoid global variables? #1336

frederikhors opened this issue Feb 3, 2021 · 6 comments

Comments

@frederikhors
Copy link

Using code like this:

  var cmdPrint = &cobra.Command{
    Use:   "print [string to print]",
    Short: "Print anything to the screen",
    Args: cobra.MinimumNArgs(1),
    Run: func(cmd *cobra.Command, args []string) {
      fmt.Println("Print: " + strings.Join(args, " "))
    },
  }
``

I get this error from golangci-lint:

cmdPrint is a global variable (gochecknoglobals)


Is there a way to satisfy the linter and to write a batter code?
@frederikhors
Copy link
Author

I opened leighmcculloch/gochecknoglobals#17.

@quasilyte
Copy link

quasilyte commented Feb 4, 2021

You can make it local by moving it to a function where you're using it.
(leighmcculloch/gochecknoglobals#17 (comment) recommends the same.)

This example from the README:

var rootCmd = &cobra.Command{
  Use:   "hugo",
  Short: "Hugo is a very fast static site generator",
  Long: `A Fast and Flexible Static Site Generator built with
                love by spf13 and friends in Go.
                Complete documentation is available at http://hugo.spf13.com`,
  Run: func(cmd *cobra.Command, args []string) {
    // Do Stuff Here
  },
}

func Execute() {
  if err := rootCmd.Execute(); err != nil {
    fmt.Fprintln(os.Stderr, err)
    os.Exit(1)
  }
}

Can be rewritten like this:

func Execute() {
  rootCmd := &cobra.Command{
    Use:   "hugo",
    Short: "Hugo is a very fast static site generator",
    Long: `A Fast and Flexible Static Site Generator built with
                  love by spf13 and friends in Go.
                  Complete documentation is available at http://hugo.spf13.com`,
    Run: func(cmd *cobra.Command, args []string) {
      // Do Stuff Here
    },
  }
  if err := rootCmd.Execute(); err != nil {
    fmt.Fprintln(os.Stderr, err)
    os.Exit(1)
  }
}

@MichaelMure
Copy link
Contributor

This is what I came up with: https://github.com/MichaelMure/git-bug/tree/master/commands
Bonus point for testability.

@github-actions
Copy link

This issue is being marked as stale due to a long period of inactivity

@frederikhors
Copy link
Author

Nope

@johnSchnake
Copy link
Collaborator

Options given here already and other tickets discuss the same issue (e.g. #1599). Closing motivated by #1600

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants