Find in Go repeated strings that could be replaced by a constant

goconst

Find repeated strings that could be replaced by a constant.

Motivation

There are obvious benefits to using constants instead of repeating strings, mostly to ease maintenance. Cannot argue against changing a single constant versus many strings.

While this could be considered a beginner mistake, across time, multiple packages and large codebases, some repetition could have slipped in.

Get Started

$ go get github.com/jgautheron/goconst/cmd/goconst
$ goconst ./...

Usage

Usage:

  goconst ARGS <directory>

Flags:

  -ignore            exclude files matching the given regular expression
  -ignore-tests      exclude tests from the search (default: true)
  -min-occurrences   report from how many occurrences (default: 2)
  -min-length        only report strings with the minimum given length (default: 3)
  -match-constant    look for existing constants matching the values
  -numbers           search also for duplicated numbers
  -min          	   minimum value, only works with -numbers
  -max          	   maximum value, only works with -numbers
  -output            output formatting (text or json)
  -set-exit-status   Set exit status to 2 if any issues are found

Examples:

  goconst ./...
  goconst -ignore "yacc|\.pb\." $GOPATH/src/github.com/cockroachdb/cockroach/...
  goconst -min-occurrences 3 -output json $GOPATH/src/github.com/cockroachdb/cockroach
  goconst -numbers -min 60 -max 512 .

Other static analysis tools

  • gogetimports: Get a JSON-formatted list of imports.
  • usedexports: Find exported variables that could be unexported.

License

MIT

Owner
Jonathan Gautheron
Continuous learning - Cloud, Go, React
Jonathan Gautheron
Comments
  • More options for golangci-lint

    More options for golangci-lint

    Hello!

    I can see that the linter has a rich set of flags:

      -ignore            exclude files matching the given regular expression
      -ignore-tests      exclude tests from the search (default: true)
      -min-occurrences   report from how many occurrences (default: 2)
      -min-length        only report strings with the minimum given length (default: 3)
      -match-constant    look for existing constants matching the values
      -numbers           search also for duplicated numbers
    

    but only a couple of options are available here

    goconst:
        min-len: 3
        min-occurrences: 3
    

    It would be very useful for us to ignore some constants, or turn off this linter for tests without touching other linters

    Could you help with that? Thanks

  • Telling types of violations one from another

    Telling types of violations one from another

    Background information is available in https://github.com/golangci/golangci-lint/pull/1500.

    What I'm trying to achieve here is to have:

    • violation types being distinguishable one from another
    • ~types being passed back to program calling goconst.Run()~

    It useful for us in golangci-lint to start using upstream version of goconst instead of outdated fork that we have been relying on for a while.

    Fixes #11.

  • Combine matches

    Combine matches

    Using the latest release (see #7) the program prints out all matches like

    config.go:240:37:4 other occurrence(s) of "logStack" found in: config.go:241:26 config.go:366:20 config.go:368:20 pagehandler.go:160:31
    config.go:241:26:4 other occurrence(s) of "logStack" found in: config.go:240:37  config.go:366:20 config.go:368:20 pagehandler.go:160:31
    config.go:366:20:4 other occurrence(s) of "logStack" found in: config.go:240:37 config.go:241:26 config.go:368:20 pagehandler.go:160:31
    config.go:368:20:4 other occurrence(s) of "logStack" found in: config.go:240:37 config.go:241:26 config.go:366:20 pagehandler.go:160:31
    

    I'd prefer it if all matches were printed in a single line. (I seem to remember that goconst did that in the previous release.) Thank you!

  • `ignore-tests` option does not ignore test files

    `ignore-tests` option does not ignore test files

    As stated in the README:

    -ignore-tests exclude tests from the search (default: true)

    However, when using this linter as part of golangci-lint, I am met with errors in *_test.go files that live adjacent to their companion *.go file in the directory.

    I still notice this issue when adding the following to my .golangci.yml config:

    linters-settings:
      goconst:
        ignore-tests: true
    
  • work on more than strings

    work on more than strings

    This would be useful in cockroachdb/cockroach if it could also detect duplicate integers. In particular, we want to use constants for time.Durations in our tests - it'd be nice if this tool provided that check.

  • Add -set-exit-status flag

    Add -set-exit-status flag

    Closes #9. This adds a new flag to goconst that can be used to make it exit with a non-zero exit code if any issues are found.

    In short, I implemented this by having run/printOutput return an additional boolean value to indicate if any issues were found in the analysed code. If true (and -set_exit_status is used), goconst will now exit with a status code of 2. I chose 2 because goconst will already exit with the status code 1 if an error occurs.

    These changes should be completely backwards compatible. From manual testing I can say that this works as expected.

  • Support `-min-length` flag

    Support `-min-length` flag

    I feel like it would be useful to only report constants longer than some minimum length. For example, I don't really care if the constant "a" is repeated, but I do care if the constant "Some Long Text" is repeated, as it becomes more prone to error.

  • the releases should have `v` prefix

    the releases should have `v` prefix

    Hi, Could you please re-tag (at least latest) releases by adding v prefix to each release? Seems go get does not recognize the tags without v as versions.

    golangci-lint uses github.com/jgautheron/goconst v0.0.0-20201117150253-ccae5bf973f3 in go.mod file, and I tried to update it to use the latest version and expected to see github.com/jgautheron/goconst v1.4.0, but no changes. Then I found this issue: https://github.com/golang/go/issues/30146 Seems the v is a convention

  • Don't count backticks as string members

    Don't count backticks as string members

    goconst -min-length 3  ./...
    goconst -min-length 4  ./...
    

    return both e.g.

    pagehandler.go:807:7:2 other occurrence(s) of "`xt`" found in: pagehandler.go:594:18 pagehandler.go:946:14
    

    and

    goconst -min-length 5  ./..
    

    doesn't find anything (which is what I expect). Obviously the backticks in the first two calls are counted as string-members – which they are not.

    This is because #2 only expects " as string delimiter but not backticks and apostrophe.

  • Constant is not finding

    Constant is not finding

    I have following file, but when I run goconst -min-occurrences 1 -output text . , it does not return anything. As you can see in the code "http://" string has two occurrence, my expectation is that goconst will show some error but it does not display anything. Am I doing right?

    package main
    import "strings"
    
    var url string
    
    func getUrl() {
    	if strings.HasPrefix(url,"http://"){
    		url = strings.TrimPrefix(url,"http://")
    	} //esle do not control
    	url = strings.TrimPrefix(string(url),"/")
    }
    
  • Keep getting slammed with 'multiple occurrences' warning

    Keep getting slammed with 'multiple occurrences' warning

    Sorry, I made an SO post on the issue here, before I found this git: https://stackoverflow.com/questions/46389607/go-linter-on-atom

    I'm using Atom, I keep getting a long list of warnings like so, but what's the reasoning for it? "3 other occurrence(s) of "GET" found in: routes_pages.go:384:8 routes_pages.go:443:7 routes_pages.go:536:7 (goconst)", appears for each case of GET, POST, PUT, etc. basically a huge list of warnings.

    My routes:

    a.Router.HandleFunc("/login", a.PageLogin)
    a.Router.HandleFunc("/register", a.PageRegister)
    a.Router.HandleFunc("/event/add", a.PageEventCreate)
    

    My typical route funcs:

    func (a *App) PageEventCreate(w http.ResponseWriter, r *http.Request) {
    
        switch r.Method {
            case "GET":
                // Serve the resource.
            case "POST":
                // Create a new record.
            case "PUT":
                // Update an existing record.
            case "DELETE":
                // Remove the record.
            default:
                // Give an error message.
        }
    
    }
    
    
    
    func (a *App) PageLogin(res http.ResponseWriter, req *http.Request) {
            switch r.Method {
                case "GET":
                    // Serve the resource.
                case "POST":
                    // Create a new record.
                case "PUT":
                    // Update an existing record.
                case "DELETE":
                    // Remove the record.
                default:
                    // Give an error message.
            }
    
    }
    
    
  • Not support string + > += operation const scan

    Not support string + > += operation const scan

    if source like below:

    test2 := "foo" + fmt.Sprintf("%d", testInt())
    if test2 > "foo" {
        test2 += "foo"
    }
    

    goconst not support.

  • Support filtering number literals in bases other than decimals

    Support filtering number literals in bases other than decimals

    The filtering logic for numbers uses strconv.Atoi to parse the value of numbers. This however assumes decimal and values in other bases like 0x0 are ignored even though they might be under the minimum threshold.

    Replacing it by something like ParseInt(s, 0, 0) would handle parsing it in bases 2, 8, or 16 (determined by the prefix) as well as base 10.

Find outdated golang packages
Find outdated golang packages

This project is not supported anymore Go-outdated is minimalistic library that helps to find outdated packages hosted on github.com in your golang pro

Sep 27, 2022
Kiteco-public - Primary Kite repo — private bits replaced with XXXXXXX

This is a public version of the main Kite repo The main Kite repo (originally kiteco/kiteco) was intended for private use. It has been lightly adapted

Dec 30, 2022
A program to create assembly 8086 strings to print without using any printing/strings related function but only mov-xchg-int and loops

Assembly String builder tool A program to create assembly 8086 strings to print without using any printing/strings related function but only mov-xchg-

Feb 1, 2022
Find strings in Go binaries

gostringsr2 gostringsr2 extracts strings from a Go binary using radare2. Tested with radare2 3.7.0, Python 3.7, r2pipe 1.4.1, on OS X and Linux. Teste

Oct 20, 2022
Pure Go implementation of D. J. Bernstein's cdb constant database library.

Pure Go implementation of D. J. Bernstein's cdb constant database library.

Oct 19, 2022
Argon2 password hashing package for go with constant time hash comparison

argon2pw Argon2 password hashing package with constant time hash comparison Preface: Argon2 was selected as the winner of the Password Hashing Competi

Sep 27, 2022
Constant time big numbers for Go

The purpose of this package is to provide a version of arbitrary sized arithmetic, in a safe (i.e. constant-time) way, for cryptography.

Jan 2, 2023
Constant Database native golang implementation

CDB golang implementation cdb is a fast, reliable, simple package for creating and reading constant databases see docs for more details Advantages Ite

Jul 15, 2022
Active Directory & Red-Team Cheat-Sheet in constant expansion.

This AD attacks CheatSheet, made by RistBS is inspired by the Active-Directory-Exploitation-Cheat-Sheet repo. Edit : Thanks for 100 stars :D it is the

Jan 4, 2023
A file find utility modeled after the unix find written in Go

gofind A file find utility modeled after the unix find written in Go. Why This p

Dec 17, 2021
Cf-cli-find-app-plugin - CF CLI plugin to find applications containing a search string

Overview This cf cli plugin allows users to search for application names that co

Jan 3, 2022
Proto-find is a tool for researchers that lets you find client side prototype pollution vulnerability.

proto-find proto-find is a tool for researchers that lets you find client side prototype pollution vulnerability. How it works proto-find open URL in

Dec 6, 2022
Go Hosting Solution for AWS, Google Could and Digital Ocean
Go Hosting Solution for AWS, Google Could and Digital Ocean

Furnace Intro Brief Explanation Here is a very short description of what Furnace does in a handy IKEA manual format. In More Depth AWS Cloud Formation

Jan 3, 2023
hack-browser-data is an open-source tool that could help you decrypt data from the browser.
hack-browser-data is an open-source tool that could help you decrypt data  from the browser.

hack-browser-data is an open-source tool that could help you decrypt data ( password|bookmark|cookie|history|credit card|download

Dec 23, 2022
its a simple backdoor service that im making cuz i think that it could be cool its not finished but this is a cool project
  its a simple backdoor service that im making cuz i think that it could be cool its not finished but this is a cool project

yackdoor its a simple backdoor service that im making cuz i think that it could be cool its not finished but this is a cool project how it looks backd

Aug 18, 2022
A Github action to check if IDT could synthesize a given DNA sequence.

dna-is-synthesizable A github action to check if a part is synthesizable from a given Genbank file. dna-is-synthesizable is a Github Action that recei

Oct 28, 2021
How fast could I write tic tac toe in Go, while not knowing Go, but with the aid of GitHub Copilot?

tictactoe-go-with-copilot How fast could I write tic tac toe in Go, while not knowing Go, but with the aid of GitHub Copilot? This took me about 30 mi

Dec 9, 2021
You could leverage Alfred and Google Sheets to track your time with ease.
You could leverage Alfred and Google Sheets to track your time with ease.

You could leverage Alfred and Google Sheets to track your time with ease. The goal is to track your time in a way that is easy to understand how much time you spend on.

Dec 25, 2022
fswatch, this library could help watching filesystem changes, like macOS fswatch

fswatch go library for simple UNIX file system watching fswatch provides simple UNIX file system watching in Go. It is based around the Watcher struct

Jan 7, 2022
Output all versions of a local git repo, which could be used as test data for your ML program.

gitwalker Output all versions of a local git repo, which could be used as test data for your ML program. Notice This program is under development. Cur

Dec 27, 2021