The scope of this question is GitHub repositories.
Is there an easy option to enforce a few code quality rules before a commit?
I have linting tools that I can run in a GitHub action runner. I hope I can run the linting scripts and prevent the commit if the lint program has an error output.
I think I am missing a pattern or special GitHub feature here. A link to documentation would be a great help.
If you're using github.com (that is, not a GitHub Enterprise Server instance), then you cannot run hooks on the server side. That's because hooks execute arbitrary code, which is of course a security concern.
The easiest way to do this is to run a CI job, such as you have in the GitHub Actions runner. You'd create the workflow file that runs the linting tools, such that the linting tool or your check script exits nonzero if the commit should be rejected. You can see the workflow file for Git LFS that runs script/cibuild
to perform this kind of check.
Once you have your CI job working as you expect, you can protect the branch by going into the repository settings. Choose Branches → Branch Protection Rules, and create a check for whatever branch you want to require checks for. Usually this is your default branch. Choose “Require status checks to pass before merging” and then enable the relevant checks to make them required.
From that point on, in order to merge code into the protected branch, the checks must pass. If you want to require this for all branches in the repository, then you can use a wildcard, but you'll need to use a forking model since this will prevent people from pushing branches into the repository.
Note that this is much better than trying to use a pre-commit
hook on the user system. As the Git FAQ explains, pre-commit
hooks are easily bypassed, so while you can provide them for developers who want to use them, you can't require them. pre-commit
hooks are also an impediment to certain workflows, so advanced developers may not care for them.