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

Overview

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

Issues
  • 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

    opened by Antonboom 5
  • 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.

    opened by iwankgb 4
  • 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!

    opened by mwat56 3
  • `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
    
    opened by PSalant726 3
  • 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.

    opened by tamird 3
  • 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.

    opened by ericcornelissen 2
  • 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.

    opened by alecthomas 2
  • 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

    opened by SVilgelm 1
  • 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.

    opened by mwat56 1
  • 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),"/")
    }
    
    opened by sonishailendra 1
  • 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.
            }
    
    }
    
    
    opened by TheMangoTrain 1
  • 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.

    opened by studyzy 0
  • 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](https://pkg.go.dev/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.

    opened by 0xjac 0
Releases(v1.5.1)
Owner
Jonathan Gautheron
Continuous learning - Cloud, Go, React
Jonathan Gautheron
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

null 42 Jul 23, 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

Kite 38 Jul 31, 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-

Reg 2 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

Carve Systems 44 Jul 27, 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.

John Barham 222 Jun 12, 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

Raja Bhatia 88 Jun 26, 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.

Lúcás Meier 81 Jul 7, 2022
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

Alexander Petrov 32 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

null 655 Aug 4, 2022
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

Furnace 90 Jul 10, 2022
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

idiotc4t 105 Aug 2, 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

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

ranon rat 7 Mar 9, 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

iGEM Software 2021 4 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

null 0 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. The goal is to track your time in a way that is easy to understand how much time you spend on.

Kai-Chu Chung 0 Dec 14, 2021
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

hitzhangjie 0 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

zhuaiballl 0 Dec 27, 2021
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

Jack D 0 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

null 0 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

null 49 Jul 17, 2022
Type-agnostic partitioning for Go's indexable collections and strings.

Go Type-Agnostic Collection Partitioning Type-agnostic partitioning for anything that can be indexed in Go - slices, arrays,strings. Inspired by Guava

Meir Fischer 35 Aug 11, 2021
GoLang Parse many date strings without knowing format in advance.

Go Date Parser Parse many date strings without knowing format in advance. Uses a scanner to read bytes and use a state machine to find format. Much fa

Aaron Raddon 1.8k Aug 10, 2022
A Golang library to manipulate strings according to the word parsing rules of the UNIX Bourne shell.

shellwords A Golang library to manipulate strings according to the word parsing rules of the UNIX Bourne shell. Installation go get github.com/Wing924

Wei He 17 Mar 15, 2022
i18n (Internationalization and localization) engine written in Go, used for translating locale strings.

go-localize Simple and easy to use i18n (Internationalization and localization) engine written in Go, used for translating locale strings. Use with go

Miles Croxford 38 Jul 17, 2022
[UNMANTEINED] Extract values from strings and fill your structs with nlp.

nlp nlp is a general purpose any-lang Natural Language Processor that parses the data inside a text and returns a filled model Supported types int in

Juan Alvarez 379 Jul 28, 2022
[Go] Package of validators and sanitizers for strings, numerics, slices and structs

govalidator A package of validators and sanitizers for strings, structs and collections. Based on validator.js. Installation Make sure that Go is inst

Alex Saskevich 5.4k Aug 6, 2022
Supporting your devops by shortening your strings using common abbreviations and clever guesswork

abbreviate Shorten your strings using common abbreviations. Supported by Tidelift Motivation This tool comes out of a frustration of the name of resou

Pascal Dennerly 182 Jun 30, 2022
[Go] Package of validators and sanitizers for strings, numerics, slices and structs

govalidator A package of validators and sanitizers for strings, structs and collections. Based on validator.js. Installation Make sure that Go is inst

Alex Saskevich 5.4k Aug 6, 2022
Package sanitize provides functions for sanitizing text in golang strings.

sanitize Package sanitize provides functions to sanitize html and paths with go (golang). FUNCTIONS sanitize.Accents(s string) string Accents replaces

Kenny Grant 319 Jul 17, 2022