Giter Club home page Giter Club logo

pre-commit-golang's Introduction

pre-commit-golang

๐Ÿšจ Please see the project sunsetting announcement: Issues/98 ๐Ÿšจ


golang hooks for http://pre-commit.com/

Using these hooks

Add this to your .pre-commit-config.yaml

- repo: https://github.com/dnephin/pre-commit-golang
  rev: master
  hooks:
    - id: go-fmt
    - id: go-vet
    - id: go-lint
    - id: go-imports
    - id: go-cyclo
      args: [-over=15]
    - id: validate-toml
    - id: no-go-testing
    - id: golangci-lint
    - id: go-critic
    - id: go-unit-tests
    - id: go-build
    - id: go-mod-tidy

Available hooks

  • go-fmt - Runs gofmt, requires golang
  • go-vet - Runs go vet, requires golang
  • go-lint - Runs golint, requires https://github.com/golang/lint but is unmaintained & deprecated in favour of golangci-lint
  • go-imports - Runs goimports, requires golang.org/x/tools/cmd/goimports
  • go-cyclo - Runs gocyclo, require https://github.com/fzipp/gocyclo
  • validate-toml - Runs tomlv, requires https://github.com/BurntSushi/toml/tree/master/cmd/tomlv
  • no-go-testing - Checks that no files are using testing.T, if you want developers to use a different testing framework
  • golangci-lint - run golangci-lint run ./..., requires golangci-lint
  • go-critic - run gocritic check ./..., requires go-critic
  • go-unit-tests - run go test -tags=unit -timeout 30s -short -v
  • go-build - run go build, requires golang
  • go-mod-tidy - run go mod tidy -v, requires golang
  • go-mod-vendor - run go mod vendor, requires golang

pre-commit-golang's People

Contributors

abizer avatar akostibas avatar asottile avatar borisbabic avatar burik666 avatar callofdutyops avatar ccoveille avatar colinschoen avatar covertbert avatar davidpfarrell avatar dnephin avatar dtomasi avatar echarrod avatar flw-cn avatar giorgiop avatar j2gg0s avatar jasonfriedland avatar jerome1337 avatar jjaxu avatar jonyhy96 avatar korjavin avatar larsks avatar logikone avatar mckingho avatar michilu avatar ramonhpr avatar rumyantseva avatar vallieres avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

pre-commit-golang's Issues

golangci-lint doesn't work on Windows

When trying to run the go-cyclo hook on Windows, I get:

Executable /bin/sh not found

I think this can be fixed by changing #!/bin/sh to #!/usr/bin/env sh.

I will open a PR shortly, not sure if this will cause any other problems though

exclude option for go-unit-tests hook

Currently go-unit-tests hook discovers all *.go files except vendor directory and tests them. But there may be some circumstances which you want to exclude some files from unit tests. So this feature would be great actually.

Replace `files: '\.go$'` with `types: [go]`

It might be good to switch all files: '\.go$' with types: [go]

In the end, it might not make a difference, but it might cause issues.

I just wanted to leave this here. Ofc, I can make it a PR if you agree to merge this.

[BUG] v0.5.0

when i use v0.5.0 on MacOS i see the following error

go imports...............................................................Failed
- hook id: go-imports
- exit code: 127

/Users/***/.cache/pre-commit/repoi1qjadfc/run-go-imports.sh: line 8: goimports: command not found

Manage ovh/venom hook

Hello,

Do you know this tool?
I guess it should be good to manage hook so that those tests are launched before commiting.
If you agree with that, I can do the PR.

What do you think about that, @dnephin ?

Test-only directory causes error "no non-test Go files in..."

I have a directory containing only go testing files, for integration tests. I.e.:

src/
  foo/
    impl.go        # for implementation
    impl_test.go   # for unit tests
    test/
      impl_test.go # for integration tests

When I run go build ./... in the root, this succeeds without warning (this is supported since this go commit). However, the default go-build precommit doesn't like it:

go-build.................................................................Failed
- hook id: go-build
- exit code: 1

go build mytest/foo/test: no non-test Go files in /.../repo/src/foo/test

pre-commit failed raise `Missing "sha" field`

os: mac os

failed stdout:

An error has occurred: InvalidConfigError: Missing "sha" field for repository git://github.com/dnephin/pre-commit-golang
Check the log at ~/.pre-commit/pre-commit.log

cat xx.log

An error has occurred: InvalidConfigError: Missing "sha" field for repository git://github.com/dnephin/pre-commit-golang
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/pre_commit/error_handler.py", line 47, in error_handler
    yield
  File "/Library/Python/2.7/site-packages/pre_commit/main.py", line 157, in main
    return run(runner, args)
  File "/Library/Python/2.7/site-packages/pre_commit/commands/run.py", line 195, in run
    repo_hooks = list(get_repo_hooks(runner))
  File "/Library/Python/2.7/site-packages/pre_commit/commands/run.py", line 141, in get_repo_hooks
    for repo in runner.repositories:
  File "/Library/Python/2.7/site-packages/cached_property.py", line 26, in __get__
    value = obj.__dict__[self.func.__name__] = self.func(obj)
  File "/Library/Python/2.7/site-packages/pre_commit/runner.py", line 44, in repositories
    config = load_config(self.config_file_path)
  File "/Library/Python/2.7/site-packages/pre_commit/clientlib/validate_base.py", line 63, in validate
    additional_validation_strategy(obj)
  File "/Library/Python/2.7/site-packages/pre_commit/clientlib/validate_config.py", line 75, in validate_config_extra
    'Missing "sha" field for repository {0}'.format(repo['repo'])
InvalidConfigError: Missing "sha" field for repository git://github.com/dnephin/pre-commit-golang

[BUG] goimports: command not found

our team is using the master version of pre-commit-golang but we had to rollback to version 0.4.0 because the pipeline return error:

Check JSON...............................................................Passed
Check for merge conflicts................................................Passed
Check Yaml...............................................................Passed
Detect Private Key.......................................................Passed
Pretty format JSON.......................................................Passed
Trim Trailing Whitespace.................................................Passed
Detect Private Key.......................................................Passed
Flake8 (deprecated, use gitlab.com/pycqa/flake8).....(no files to check)Skipped
Check python ast.....................................(no files to check)Skipped
Fix End of Files.........................................................Passed
markdownlint.............................................................Passed
go fmt...................................................................Passed
go imports...............................................................Failed
- hook id: go-imports
- exit code: 127

/home/runner/.cache/pre-commit/repomiw2ezxk/run-go-imports.sh: line 8: goimports: command not found
/home/runner/.cache/pre-commit/repomiw2ezxk/run-go-imports.sh: line 8: goimports: command not found

pre-commit has changed from hooks.yaml -> .pre-commit-hooks.yaml

Hello pre-commit hook implementer!

In version 0.12.0 pre-commit has changed the default location for the file formerly known as hooks.yaml to make it more convincing for others to add more hooks.

As such, a migration has to (unfortunately) occur.

For maximum compatibility it is suggested to cp hooks.yaml .pre-commit-hooks.yaml (at least for the migration period). A copy is suggested over a symlink unless you do not care for windows compatibility (and I wouldn't blame you!).

Once the migration period is over (or you no longer care to support old versions of pre-commit), the hooks.yaml file is no longer necessary and may be deleted.

See pre-commit/pre-commit#470 for more details

Thanks again for contributing to the pre-commit ecosystem, we couldn't do it without you :)
Anthony

go-unit-test script falsely succeeding if go list ./... fails

Hello! I recently encountered an edge case that causes the go-unit-tests hook to falsely succeed when it's supposed to fail. If the go list ./... command fails, the main script doesn't terminate as it directly stores the output in FILE. This causes no tests to run in the next step and hence always succeeds.

Minimum working example

One example where this can occur is if two files in the same folder have different package names, and there aren't any unit tests added yet. This example will pass the hook but will fail the go test ./... command with error found packages badname (bar.go) and lib (foo.go) in <your_dir>/lib

Here's the file structure

// main.go
package main
// go.mod
module myapp

go 1.18
# .pre-commit-config.yaml
repos:
- repo: https://github.com/dnephin/pre-commit-golang
  rev: v0.5.0
  hooks:
      - id: go-unit-tests
        always_run: true
// lib/foo.go
package lib
// lib/bar.go
package wrongname

Cut a new release

Would it be possible to make a new release off HEAD? We have a dependency manager that is set to grab the latest release of things, and thus isn't including the go vet fix from last week.

Thanks!

Cannot update because the tip of HEAD is missing these hooks: go-mod-tidy

I have go-mod-tidy configured in my .pre-commit-config.yaml and if I try to run pre-commit autoupdate I get this error

...
Updating git://github.com/dnephin/pre-commit-golang ... Cannot update because the tip of HEAD is missing these hooks:
go-mod-tidy
...

I think this is because there hasn't been a release since 3c83549 was merged.

could not pass environment variables to go-unit-tests

Currently, i have a project which gets the application configuration from remote config server on production, and gets the local configuration file while unit testing. In order to decide when we are on production or local environment, i use the below environment variable:

ACTIVE_PROFILE=unit-test

But if i run the go-unit-tests hook, it tries to fetch the configuration from remote config server as you guess. I have googled it but i could not find anything useful, is it possible to pass environment variable to go-unit-tests hook or would not be nice if we could define it like below?

- id: go-unit-tests
  args: [-e="ACTIVE_PROFILE=unit-test"]

go-fmt doesn't work on Windows

When trying to run the go-fmt hook on Windows, I get:

tee: /dev/fd/5: No such file or directory

I use a local hook to get round it, but it would be nice to be able to use this repo for all the pre-commit hooks I need

Repo doesn't have a LICENSE

This code doesn't have a LICENSE file, which means I can't use it at work (Google). Is it possible to pop a license in here so I can use it?

Thanks :)

Should go unit tests failfast?

The go test command has a flag -failfast which stop the testing after first failure. This really saves time.

What do the maintainers think on this?

pass current directory golangci-lint when specifying a configfile

  # golang pre commits
  - repo: https://github.com/dnephin/pre-commit-golang
    rev: v0.4.0
    hooks:
        - id: go-fmt
        - id: go-vet
        - id: go-lint
        - id: go-imports
        - id: no-go-testing
        - id: golangci-lint
          args: ["-vc .golang-ci.yml"]

results in

ERRO Can't read config: can't read viper config: open .golang-ci.yml: no such file or directory

is there anyway I can prepend $PWD to golangci lint pre commit hook?

support generics

latest version gives error expected '(', found '[' for generics.

The syntax -
func bootThirdPartyClient[T any](address string, isNewRelicEnabled bool, fn func(cc grpc.ClientConnInterface) T) (T, error) { client := grpcclient.New(isNewRelicEnabled) if err := client.Connect(address, log); err != nil { var tmp T return tmp, fmt.Errorf("grpcclient.New(): %w", err) } return fn(client.ClientConn), nil }

ability to pass flags onto go-unit-tests hook

I am using your hooks for a long time, but for some reason, i should be able to pass additional arguments to go test command. My exact requirement is passing -timeout 60s onto go test command. But as i see, sadly you hardcoded timeout as 30s and it cant be changed since go-unit-tests hook does not accept any argument.

go-imports doesn't work

description

enviroment:

  • go1.13 darwin/amd64
  • pre-commit 1.18.3

.pre-commit-config.yaml:

repos:
- repo: git://github.com/dnephin/pre-commit-golang
  rev: v0.3.4
  hooks:
    - id: go-fmt
    - id: go-vet
    - id: go-imports
      exclude: 'vendor'
    - id: go-lint
    - id: go-critic
      exclude: 'vendor'
    - id: golangci-lint

error:

[ERROR] `go-imports` is not present in repository git://github.com/dnephin/pre-commit-golang.  Typo? Perhaps it is introduced in a newer version?  Often `pre-commit autoupdate` fixes this.
$ pre-commit autoupdate
Updating git://github.com/dnephin/pre-commit-golang...already up to date.

Release 0.4?

A project I'm on uses a dependency manager that is set to grab the latest stable release of its dependencies, and thus isn't including the exit status fix from a couple weeks ago. Could you please release a new version that includes the latest code when you have a moment?

Thanks!

The go-build check does not support arguments.

I would like to use something like this:

    - id: go-build
      args: ["-o bin/exec"]

From looking at the code, it looks like we can change run-go-build.sh to be

#!/usr/bin/env bash
FILES=$(go list ./...  | grep -v /vendor/)
exec go build "$@" $FILES

go-cyclo doesn't work in Windows

When trying to run the go-cyclo hook on Windows, I get:

Executable /bin/bash not found

I think this can be fixed by changing #!/bin/bash to #!/usr/bin/env bash.

I will open a PR shortly, not sure if this will cause any other problems though

Create more tags/releases

I'd like to be able to pin to a specific commit without using a SHA. Conversely, the "autoupdate" feature of pre-commit by default pulls the latest tag. So for either of these use-cases, more tags would be helpful.

I believe that Github workflows would make it easy to automatically tag commits, if you'd like to make tags available without any further work from humans. (I can prepare a PR for this if it's an attractive idea)

go mod tidy doesnt work if go.mod file is in src folder (cant find go.mod)

I have a root project where all my go code is inside sub-folder src directory and i need to run go mod tidy from top level .pre-commit-config.yaml (cause i believe there is no way to pass args)

Now My pre-commit config file has mentioned the files path (where my sub-folder src/go.mod file reside.. but still go mod tidy always show pass, doesn't do anything by downloading all missing package)

- repo: git://github.com/dnephin/pre-commit-golang
  rev: master
  hooks:
    - id: go-mod-tidy
      name:go-mod-tidy
      files: 'src/.*\.go'

How about `go mod tidy` ?

In my experience, sometimes we add a wrong library to the project.

In this case, we do go mod tidy if we use go mod feature.

I'm happy if it's supported by this project.

go-vet does not work if Go code is not in the root folder

go-vet script, first runs go list in the root directory. It fails if it does not find go files.

In my case, I have multiple related projects in the same repo. Something like this

.
โ”œโ”€โ”€ LICENSE
โ”œโ”€โ”€ README.md
โ”œโ”€โ”€ backend
โ””โ”€โ”€ frontend

I need go-vet to only run the backend folder. But the way script works, it is not possible.

One way is to infer the directory from the staged files. Or add option to pass dir in the argument to the hook.

Question on test files

precommit runs on the staged files. So changing a file and not updating the test file will result in precommit passing. Therefore, go vet will pass.

e.g changing the number of parameter required by a function, and forgetting to update the test files that use that function.

Is there any way to solve this. I was thinking we always run the tools against the staged files and all the test files.

Thanks for the tool.

Can't find `go-mod-tidy` on Windows

I have the following .pre-commit-config.yaml:

repos:
- repo: git://github.com/dnephin/pre-commit-golang
  rev: master
  hooks:
    - id: go-vet
    - id: go-mod-tidy

When I try to run pre-commit run --all-files I get:

[ERROR] go-mod-tidy is not present in repository git://github.com/dnephin/pre-commit-golang. Typo? Perhaps it is introduced in a newer version? Often pre-commit autoupdate fixes this.

pre-commit autoupdate won't work whilst go-mod-tidy is in the file:

Updating git://github.com/dnephin/pre-commit-golang ... Cannot update because the tip of HEAD is missing these hooks:
go-mod-tidy

So, after removing go-mod-tidy:

Updating git://github.com/dnephin/pre-commit-golang ... updating master -> v0.3.5.

But when I add go-mod-tidy back in again, the same error is present, and it cannot be found.

I am on Windows, I'm not sure whether this affects anything. I've tried uninstalling and reinstalling the hooks too.

go-generate: Does not work for multiple files in different packages

Hi folks,

I tried to use the new go-generate hook and ran into an error:

go-generate..............................................................Failed
- hook id: go-generate
- exit code: 1

named files must all be in one directory; have path/to/a/package and path/to/another/package

As per the generate documentation it appears go generate can handle multiple files in the same package and multiple packages, however it can't handle multiple files in the same package.

go imports hook passes on command not found

% pre-commit run --files main.go -v
...
go imports...............................................................Passed
- hook id: go-imports
- duration: 0.01s

../run-go-imports.sh: line 8: goimports: command not found

It's likely that this is true for other hooks as well. A simple fix would be to add -o pipefail to the script.

Add gocyclo

Add a go cyclo commit hook. Go cyclo is a tool used by go report card that contributes to a go packages letter grade.

Error during pre-commit install --install-hooks

I added below to .pre-commit-config.yaml and got error.

- repo: git://github.com/dnephin/pre-commit-golang
  sha: HEAD
  hooks:
    - id: go-fmt

error:

pre-commit installed at .git/hooks/pre-commit
[INFO] Initializing environment for git://github.com/dnephin/pre-commit-golang.
An unexpected error has occurred: CalledProcessError: Command: ('/usr/bin/git', 'checkout', 'HEAD')
Return code: 1
Expected return code: 0
Output: (none)
Errors: 
    error: pathspec 'HEAD' did not match any file(s) known to git.

When I changed sha from 'HEAD' to 'master', no error occurs.

- repo: git://github.com/dnephin/pre-commit-golang
  sha: master
  hooks:
    - id: go-fmt

Is it okay? Or is better to use revision tag?

pre-commit failed with the latest change

The pre-commit fails with go-lint when using the latest commit: f2891a1

We fixed it by using tag v0.3, please see this PR for the fix and the build file we use: https://github.com/PaddlePaddle/edl/pull/10/files

travis build link: https://travis-ci.org/PaddlePaddle/edl/builds/353097770
go lint failed without any output (false alarm):

[INFO] Initializing environment for git://github.com/dnephin/pre-commit-golang.
go fmt...................................................................Passed
go vet...................................................................Passed
go lint..................................................................Failed

:rotating_light: Project sunsetting :city_sunset:

Hello everyone,

Unfortunately I no longer have the time or motivation to maintain this project. I have not used pre-commit or these hooks in a few years. I never added tests to the project, so it's difficult for me to review and approve pull requests with any confidence. There have been a number of PRs that have broken things for other people. There are still plenty of bugs to fix, and there are frequent requests to publish new releases.

There are already other projects offering pre-commit hooks for Go. You can find a list here: https://pre-commit.com/hooks.html. Some of those seem to offer a lot more than this project.

If someone is really keen on maintaining these hooks I can link to your fork from the README to redirect people to the new fork. Either way, I will likely be archiving this project sometime in the next year.

I'd like to thank everyone who has contributed to this project. I hope it was a reasonably pleasant experience.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.