Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A command line interface for linting Git commits.

License

NotificationsYou must be signed in to change notification settings

bkuhlmann/git-lint

Repository files navigation

Git Lint is a command line interface for linting Git commits by ensuring you maintain a clean, easyto read, debuggable, and maintainable project history. Having a consistent commit history leads toimproved code reviews and is a perfect companion to tools likeMilestoner for versioning and producingautomated release notes of your deploys.

Table of Contents

Features

  • Enforces aGit Rebase Workflow.

  • Enforces a clean and consistent Git commit history.

  • Supports Git default branch configuration.

  • Provides a customizable suite of analyzers.

  • Provides Git Hook support for local use.

  • Provides Continuous Integration (CI) support.

Requirements

Setup

To installwith security, run:

# 💡 Skip this line if you already have the public certificate installed.gem cert --add<(curl --compressed --location https://alchemists.io/gems.pem)gem install git-lint --trust-policy HighSecurity

To installwithout security, run:

gem install git-lint

Usage

Command Line Interface (CLI)

From the command line, type:git-lint --help

Usage

To check if your Git commit history is clean, run:git-lint analyze --branch. It will exit with a failure if at least one issue with error severity is detected.

This gem does not check commits on your default branch (i.e.main). This is intentional as youwould, generally, not want to rewrite or fix commits on themain branch. This gem is best used onfeature branches as it automatically detects all commits made since creation of the feature branch.

Here is an example workflow, using gem defaults with issues detected:

cd examplegit checkout -btesttouch text.txtgit add --all.git commit --message"This is a bogus commit message that is also terribly long and will word wrap"git-lint analyze --branch

Output:

Running Git Lint...83dbad531d84a184e55cbb38c5b2a4e5fa5bcaee (Brooke Kuhlmann, 0 seconds ago): This is a bogus commit message that is also terribly long and will word wrap.  Commit Body Presence Warning. Use minimum of 1 line (non-empty).  Commit Subject Length Error. Use 72 characters or less.  Commit Subject Prefix Error. Use: /Added /, /Updated /, /Fixed /, /Removed /, or /Refactored /.  Commit Subject Suffix Error. Avoid: /\./, /\?/, /\!/.1 commit inspected. 4 issues detected (1 warning, 3 errors).

Configuration

This gem can be configured via a global configuration:

$HOME/.config/git-lint/configuration.yml

It can also be configured viaXDG environmentvariables. The default configuration is:

commits:author:capitalization:enabled:trueseverity:erroremail:enabled:trueseverity:errorname:enabled:trueseverity:errorminimum:2body:bullet_capitalization:enabled:trueseverity:errorincludes:        -"\\*"        -"\\-"bullet_delimiter:enabled:trueseverity:errorincludes:        -"\\*"        -"\\-"bullet_only:enabled:trueseverity:errorincludes:        -"\\*"        -"\\-"leading_line:enabled:trueseverity:warnline_length:enabled:falseseverity:errormaximum:72paragraph_capitalization:enabled:trueseverity:errorphrase:enabled:trueseverity:errorexcludes:        -"absolutely"        -"actually"        -"all intents and purposes"        -"along the lines"        -"at this moment in time"        -"basically"        -"blacklist"        -"each and every one"        -"everyone knows"        -"fact of the matter"        -"furthermore"        -"however"        -"in due course"        -"in the end"        -"last but not least"        -"matter of fact"        -"obviously"        -"of course"        -"really"        -"simply"        -"things being equal"        -"whitelist"        -"would like to"        -"\\beasy\\b"        -"\\bjust\\b"        -"\\bquite\\b"        -"as\\sfar\\sas\\s.+\\sconcerned"        -"of\\sthe\\s(fact|opinion)\\sthat"presence:enabled:trueseverity:warnminimum:1tracker_shorthand:enabled:trueseverity:errorexcludes:        -"(c|C)lose(s|d)?\\s\\#\\d+"        -"(f|F)ix(es|ed)?\\s\\#\\d+"        -"(r|R)esolve(s|d)?\\s\\#\\d+"word_repeat:enabled:trueseverity:errorsignature:enabled:falseseverity:errorincludes:      -Goodsubject:length:enabled:trueseverity:errormaximum:72prefix:enabled:trueseverity:errordelimiter:""includes:        -Added        -Updated        -Fixed        -Removed        -Refactoredsuffix:enabled:trueseverity:errorexcludes:        -"\\!"        -"\\."        -"\\?"word_repeat:enabled:trueseverity:errortrailer:collaborator_capitalization:enabled:trueseverity:errorcollaborator_email:enabled:trueseverity:errorcollaborator_key:enabled:trueseverity:errorcollaborator_name:enabled:trueseverity:errorminimum:2duplicate:enabled:trueseverity:errorformat_key:enabled:trueseverity:errorformat_value:enabled:trueseverity:errorincludes:        -asciidoc        -markdownissue_key:enabled:trueseverity:errorissue_value:enabled:trueseverity:errorincludes:        -"[\\w-]+"milestone_key:enabled:trueseverity:errormilestone_value:enabled:trueseverity:errorincludes:        -major        -minor        -patchorder:enabled:trueseverity:errorreviewer_key:enabled:trueseverity:errorreviewer_value:enabled:trueseverity:errorincludes:        -clickup        -github        -jira        -linear        -shortcut        -tanasigner_capitalization:enabled:trueseverity:errorsigner_email:enabled:trueseverity:errorsigner_key:enabled:trueseverity:errorsigner_name:enabled:trueseverity:errorminimum:2tracker_key:enabled:trueseverity:errortracker_value:enabled:trueseverity:errorincludes:        -"[\\w\\-\\s]+"

Enablement

By default, most analyzers are enabled. Accepted values aretrue orfalse. If you wish todisable a analyzer, set it tofalse.

Severity

By default, most analyzers are set toerror severity. If you wish to reduce the severity level ofa analyzer, you can set it towarn instead. Here are the accepted values and what each means:

  • warn: Will count as an issue and display a warning but will not cause the program/build tofail. Use this if you want to display issues as reminders or cautionary warnings.

  • error: Will count as an issue, display error output, and cause the program/build to fail. Usethis setting if you want to ensure bad commits are prevented.

Regular Expressions

Some analyzers supportinclude orexclude lists. These lists can consist of strings, regularexpressions, or a combination thereof. Regardless of your choice, all lists are automaticallyconverted to regular expression for use by the analyzers. This means a string like"example"becomes/example/ and a regular expression of"\\AExample."` becomes `/\AExample./.

If you need help constructing complex regular expressions for these lists, try launching an IRBsession and usingRegexp.new orRegexp.escape to experiment with the types of words/phrases youwant to turn into regular expressions.For purposes of the YAML configuration, these need to beexpressed as strings with special characters escaped properly for internal conversion to a regularexpression.

Analyzers

The following details the various analyzers provided by this gem to ensure a high standard ofcommits for your project.

Commit Author Capitalization

EnabledSeverityDefaults

true

error

none

Ensures author name is properly capitalized. Example:

# Disallowedjayne cobbdr. simon tam# AllowedJayne CobbDr. Simon Tam

Commit Author Email

EnabledSeverityDefaults

true

error

none

Ensures author email address exists. Git requires an author email when you use it for the first timetoo. This takes it a step further to ensure the email address loosely resembles an email address.

# Disallowedmudder_man# Allowedjayne@serenity.com

Commit Author Name

EnabledSeverityDefaults

true

error

minimum: 2

Ensures author name consists of, at least, a first and last name. Example:

# DisallowedKaylee# AllowedKaywinnet Lee Frye

Commit Body Bullet Capitalization

EnabledSeverityDefaults

true

error

includes:["\\*", "\\-"]

Ensures commit body bullet lines are capitalized. Example:

# Disallowed- an example bullet.# Allowed* An ASCII Doc bullet.* link:https://demo.com[Demo]* link:https://demo.com[demo]- A Markdown bullet.- [Demo](https://demo.com)- [demo](https://demo.com)

In general, usingASCII Doc orMarkdown syntax directly after a bullet will cause capitalization checks to be ignored because there can be valid reasons for wanting to avoid capitalization in those situations.

Commit Body Bullet Delimiter

EnabledSeverityDefaults

true

error

includes:["\\*", "\\-"]

Ensures commit body bullets are delimited by a space. Example:

# Disallowed-An example bullet.# Allowed- An example bullet.

Commit Body Bullet Only

EnabledSeverityDefaults

true

error

includes:["\\*", "\\-"]

Ensures a single bullet is never used when a paragraph could be used instead. Example:

# Disallowed- Pellentque morbi-trist sentus et netus et malesuada fames ac turpis egestas. Vestibulum tortor  quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu_libero sit amet quam.# AllowedPellentque morbi-trist sentus et netus et malesuada fames ac turpis egestas. Vestibulum tortorquam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu_libero sit amet quam.

Commit Body Leading Line

EnabledSeverityDefaults

true

error

none

Ensures there is a leading, empty line, between the commit subject and body. Generally, this isn’tan issue but sometimes the Git CLI can be misused or a misconfigured Git editor will smash thesubject line and start of the body as one run-on paragraph. Example:

# DisallowedCurabitur eleifend wisi iaculis ipsum.Pellentque morbi-trist sentus et netus et malesuada fames ac turpis egestas. Vestibulum tortorquam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu_libero sit amet quamegestas semper. Aenean ultricies mi vitae est. Mauris placerat's eleifend leo. Quisque et sapienullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, orn si amt wit.# AllowedCurabitur eleifend wisi iaculis ipsum.Pellentque morbi-trist sentus et netus et malesuada fames ac turpis egestas. Vestibulum tortorquam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu_libero sit amet quamegestas semper. Aenean ultricies mi vitae est. Mauris placerat's eleifend leo. Quisque et sapienullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, orn si amt wit.

Commit Body Line Length

EnabledSeverityDefaults

false

error

maximum: 72

Ensures each line of the commit body doesn’t extend beyond the maximum column limit.

Commit Body Paragraph Capitalization

EnabledSeverityDefaults

true

error

none

Ensures each paragraph of the commit body is capitalized. Example:

# Disallowedcurabitur eleifend wisi iaculis ipsum.# AllowedCurabitur eleifend wisi iaculis ipsum.

ASCII Doc andMarkdown code blocks are ignored since a paragraph that only consists of a code block is common practice. For ASCII Doc, this includes the following to be separate paragraphs if desired:

Commit Body Phrase

EnabledSeverityDefaults

true

error

excludes: (see configuration)

Ensures non-descriptive words/phrases are avoided in order to keep commit message bodies informativeand specific. The exclude list is case insensitive. Detection of excluded words/phrases is caseinsensitive as well. Example:

# DisallowedObviously, the existing implementation was too simple for my tastes. Of course, this couldn't beallowed. Everyone knows the correct way to implement this code is to do just what I've added inthis commit. Easy!# AllowedNecessary to fix due to a bug detected in production. The included implementation fixes the bugand provides the missing spec to ensure this doesn't happen again.

Commit Body Presence

EnabledSeverityDefaults

true

warn

minimum: 1

Ensures a minimum number of lines are present within the commit body. Lines with empty characters(i.e. whitespace, carriage returns, etc.) are considered to be empty.

Automatically ignoresfixup! commits as they are not meant to have bodies.

Commit Body Tracker Shorthand

EnabledSeverityDefaults

true

error

excludes: (see configuration)

Ensures commit body doesn’t use issue tracker shorthand. The exclude list defaults to GitHub Issuesbut can be customized for any issue tracker.

There are several reasons for excluding issue tracker links from commit bodies:

  1. Not all issue trackers preserve issues (meaning they can be deleted). This makes make readinghistoric commits harder to understand why the change was made when the reference no longer works.

  2. When disconnected from the internet or working on a laggy connection, it’s hard to understand whya commit was made when all you have is a shorthand issue reference with no supporting context.

  3. During the course of a repository’s life, issue trackers can be replaced (rare but does happen).If the old issue tracker service is no longer in use, none of the commit body shorthand willbe of any relevance.

Instead of using tracker shorthand syntax, take the time to write a short summary as towhy thecommit was made. Doing this will make it easier to understandwhy the commit was made, keeps thecommit self-contained, and makes learning about/debugging the commit faster.

Commit Body Word Repeat

EnabledSeverity

true

error

Ensures commit bodies don’t contain repeated words. Example:

# DisallowedNecessary to to fix production error.# AllowedNecessary to fix production error.

Commit Signature

EnabledSeverityDefaults

false

error

includes:["Good"]

Ensures all commit signatures are properly signed for improved security and validity of code being committed by various authors. By default, only "Good" signatures are allowed but you can expand this list if desired (although not recommended for security reasons). Valid options are:

  • Bad (B)

  • Error (E)

  • Good (G)

  • None (N)

  • Revoked (R)

  • Unknown (U)

  • Expired (X)

  • Expired Key (Y)

All of the above obtained when using the pretty formats as provided byGit Log.

Commit Subject Length

EnabledSeverityDefaults

true

error

maximum: 72

Ensures the commit subject length is no more than 72 characters in length. This default is morelenient than the50/72rule as it gives one the ability to formulate a more descriptive subject line without being toowordy or suffer being word wrapped.

Automatically ignoresfixup! orsquash! commit prefixes when calculating subject length.

Commit Subject Prefix

EnabledSeverityDefaults

true

error

includes: (see below)

delimiter: " "

Ensures each commit subject uses consistent prefixes that explainwhat is being committed. Theincludes arecase sensitive and default to the following prefixes:

  • Added - Identifies what was added. The commit should be as small as possible and consist ofimplementation and spec. Otherwise, it might be a change to an existing file which adds newbehavior.

  • Updated - Identifies what was updated. The commit should be as small as possible andnot addor fix existing behavior. This can sometimes be a grey area but is typically reserved for updatesto documentation, code comments, dependencies, etc.

  • Fixed - Identifies what was fixed. The commit should be as small as possible and consist ofchanges to implementation and spec only. In some cases this might be a single line change. Theimportant point is the change is applied to existing code which corrects behavior that wasn’tproperly implemented earlier.

  • Removed - Identifies what was removed. The commit should be as small as possible and consistonly of removed lines/files from the existing implementation. This might also mean breakingchanges requiring the publishing of amajor version release in the future.

  • Refactored - Identifies what was refactored.Refactoring is for changing codestructure without changing observable behavior. The commit should be as small as possible andnot mix multiple kinds of changes at once. Refactored code should never break existingimplementation behavior or corresponding specs because, if that happens, then one of the otherfour prefixes is what you want to use instead.

In practice, it is quite rare to need a prefix other than what has been detailed above to explainwhat is being committed. These prefixes are not only short and easy to remember but also have theadded benefit of categorizing the commits for building release notes, change logs, etc. This becomeshandy when coupled with another tool,Milestoner, for producing consistent projectmilestones and Git tag histories. For a deeper dive on subject prefixes and good commit messages ingeneral, please read aboutcommit anatomy to learn more. 🎉

Each prefix is delimited by a space which is the default setting but can be customized if desired.Whatever you choose for a delimiter will not affect Git’s special bang prefixes as described in thetip below.

💡 This analyzer automatically ignoresamend!,fixup!, orsquash! commit prefixes when used asa Git Hook in order to not disturb interactive rebase workflows.

Commit Subject Suffix

EnabledSeverityDefaults

true

error

excludes:["\\!", "\\.", "\\?"]

Ensures commit subjects are suffixed consistently. The exclude listis case sensitive and preventsthe use of punctuation. This is handy when coupled with a tool, likeMilestoner, which automates project milestonereleases.

Commit Subject Word Repeat

EnabledSeverity

true

error

Ensures commit subjects don’t contain repeated words. Example:

# DisallowedAdded specs specs# AllowedAdded specs

Commit Trailer Collaborator Capitalization

EnabledSeverityDefaults

true

error

none

Ensures collaborator name is properly capitalized. Example:

# Disallowedshepherd derrial book# AllowedShepherd Derrial Book

Commit Trailer Collaborator Email

EnabledSeverityDefaults

true

error

none

Ensures collaborator email address is valid for commit trailer.

# DisallowedCo-authored-by: River Tam <invalid># AllowedCo-authored-by: River Tam <river@firefly.com>

Commit Trailer Collaborator Key

EnabledSeverity

true

error

Ensures collaborator trailer key is correct format.

# Disallowedco-authored-by: River Tam <river@firefly.com># AllowedCo-authored-by: River Tam <river@firefly.com>

Commit Trailer Collaborator Name

EnabledSeverityDefaults

true

error

minimum: 2

Ensures collaborator name consists of, at least, a first and last name. Example:

# DisallowedCo-authored-by: River <river@firefly.com># AllowedCo-authored-by: River Tam <river@firefly.com>

Commit Trailer Duplicate

EnabledSeverityDefaults

true

error

minimum: 2

Ensures commit trailer keys are not duplicated. Example:

# DisallowedCo-authored-by: Shepherd Derrial Book <shepherd@firefly.com>Co-authored-by: Shepherd Derrial Book <shepherd@firefly.com># AllowedCo-authored-by: Malcolm Reynolds <malcolm@firefly.com>Co-authored-by: Shepherd Derrial Book <shepherd@firefly.com>

Commit Trailer Format Key

EnabledSeverity

true

error

Ensures format trailer key is correct format.

# Disallowedformat: markdown# AllowedFormat: markdown

Commit Trailer Format Value

EnabledSeverityDefaults

true

error

includes:["asciidoc", "markdown"]

Ensures format trailer value is a valid value.

# DisallowedFormat: plain# AllowedFormat: asciidoc

Commit Trailer Issue Key

EnabledSeverity

true

error

Ensures issue trailer key is correct format.

# Disallowedissue: 123# AllowedIssue: 123

Commit Trailer Issue Value

EnabledSeverityDefaults

true

error

includes:["[\\w-]+"]

Ensures issue trailer value is correct format.

# DisallowedIssue: 123+45# AllowedIssue: 123

Commit Trailer Milestone Key

EnabledSeverity

true

error

Ensures milestone trailer key is correct format.

# Disallowedmilestone: patch# AllowedMilestone: patch

Commit Trailer Milestone Value

EnabledSeverityDefaults

true

error

includes:[major, minor, patch]

Ensures milestone trailer value is correct format forsemantic versioning purposes.

# DisallowedMilestone: bogus# AllowedMilestone: patch

Commit Trailer Order

EnabledSeverity

true

error

Ensures milestone trailers are alphabetically sorted.

# DisallowedIssue: 123Milestone: patchFormat: asciidoc# AllowedFormat: asciidocIssue: 123Milestone: patch

Commit Trailer Reviewer Key

EnabledSeverity

true

error

Ensures reviewer trailer key is correct format.

# Disallowedreviewer: tana# AllowedReviewer: tana

Commit Trailer Reviewer Value

EnabledSeverityDefaults

true

error

includes:[clickup, github, jira, linear, shortcut, tana]

Ensures reviewer trailer value is correct format for linking/referencing the code review system.

# DisallowedReviewer: bogus# AllowedReviewer: tana

Commit Trailer Signer Capitalization

EnabledSeverityDefaults

true

error

none

Ensures commit signer trailer name is properly capitalized.

# DisallowedSigned-off-by: jayne cobb# AllowedSigned-off-by: Jayne Cobb

Commit Trailer Signer Email

EnabledSeverityDefaults

true

error

none

Ensures commit signer trailer email is properly capitalized.

# DisallowedSigned-off-by: Jayne Cobb <invalid># AllowedSigned-off-by: Jayne Cobb <jcobb@firefly.com>

Commit Trailer Signer Key

EnabledSeverity

true

error

Ensures signer trailer key is correct format.

# Disallowedsigned-off-by: Jayne Cobb# AllowedSigned-off-by: Jayne Cobb

Commit Trailer Signer Name

EnabledSeverityDefaults

true

error

minimum: 2

Ensures signer name consists of, at least, a first and last name.

# DisallowedSigned-off-by: Jayne# AllowedSigned-off-by: Jayne Cobb

Commit Trailer Tracker Key

EnabledSeverity

true

error

Ensures tracker trailer key is correct format.

# Disallowedtracker: linear# AllowedTracker: linear

Commit Trailer Tracker Value

EnabledSeverityDefaults

true

error

includes:["[\\w\\-\\s]+"]

Ensures tracker trailer key is correct format.

# DisallowedTracker: *ACME$# AllowedTracker: ACME Issues

Git

Default Branch

Your default branch configuration is respected no matter if it is set globally or locally. If thedefault branch isnot set then Git Lint will fall back tomain. You can set your default branch at any time by running the following from the command line:

git configset init.defaultBranch main

💡 When setting your default branch, ensure you use a consistent Git configuration across all ofyour environments.

Hooks

This gem supportsGit Hooks.

It ishighly recommended you manage Git Hooks as global scripts as it’ll reduce projectmaintenance costs for you. To configure global Git Hooks, add the following to your$HOME/.gitconfig:

[core]  hooksPath = ~/.git_template/hooks

Then you can customize Git Hooks for all of your projects.Check out theseexamples.

If a global configuration is not desired, you can add Git Hooks at a per project level by editingany of the scripts within the.git/hooks directory of the repository.

Commit Message

Thecommit-msg hook — which is the best way to use this gem as a Git Hook — is provided as a--hook option. Usage:

git-lint --hook PATH

As shown above, the--hook command accepts a file path (i.e..git/COMMIT_EDITMSG) whichis provided to you by Git within the.git/hooks/commit-msg script. Here is a working example ofwhat that script might look like:

#! /usr/bin/env bashset -o nounsetset -o errexitset -o pipefailIFS=$'\n\t'if!command -v git-lint> /dev/null;thenprintf"%s\n""[git]: Git Lint not found. To install, run: gem install git-lint."exit 1figit-lint --hook"${BASH_ARGV[0]}"

Whenever you attempt to add a commit, Git Lint will check your commit for issues prior to saving it.

Post Commit

Thepost-commit hook is possible via theanalyze command. Usage:

git-lint analyze --commit SHA

Thepost-commit hook can be used multiple ways but, generally, you’ll want to check the lastcommit made. Here is a working example which can be used as a.git/hooks/post-commit script:

#! /usr/bin/env bashset -o nounsetset -o errexitset -o pipefailIFS=$'\n\t'if!command -v git-lint> /dev/null;thenprintf"%s\n""[git]: Git Lint not found. To install, run: gem install git-lint."exit 1figit-lint analyze --commit$(git log --pretty=format:%H -1)

Whenever a commit has been saved, this script will run Git Lint to check for issues.

Rake

You can add Rake support by adding the following to yourRakefile:

beginrequire"git/lint/rake/register"rescueLoadError=>errorputserror.messageendGit::Lint::Rake::Register.call

Once required and registered, the following tasks will be available (i.e.bundle exec rake -T):

rake git_lint

Continuous Integration (CI)

This gem automatically configures itself for known CI build servers (see below for details). If youhave a build server that is not listed, please log an issue or provide an implementation withsupport.

Calculation of commits is done by analyzing all feature branch commits ahead of the default branch (i.e. "main"). In other words,git log --oneline main..your_feature_branch.

Detection and configuration happens automatically by checking theCIRCLECI environment variable.No additional setup required!

Detection happens automatically by checking theGITHUB_ACTIONS environment variable as supplied bythe GitHub environment. The only configuration required is to add a.github/workflows/git_lint.ymlto your repository with the following contents:

name:Git Linton:pull_requestjobs:run:runs-on:ubuntu-latestcontainer:image:ruby:lateststeps:      -name:Checkoutuses:actions/checkout@v4with:fetch-depth:0ref:${{github.head_ref}}      -name:Installrun:gem install git-lint      -name:Analyzerun:git-lint --analyze

The above will ensure Git Lint runs as an additional check on each Pull Request.

Detection and configuration happens automatically by checking theNETLIFY environment variable. Noadditional setup required!

Style Guide

In addition to what is described above and automated for you, the following style guide is alsoworth considering:

General

  • Use aGit Rebase Workflow instead of a Git Merge Workflow.

  • Usegit commit --amend when fixing a previous commit, addressing code review feedback, etc.

  • Usegit commit --fixup when fixing an earlier commit, addressing code review feedback, etc., anddon’t need to modify the original commit message.

  • Usegit commit --squash when fixing an earlier commit, addressing code review feedback, etc.,and want to combine multiple commit messages into a single commit message.Avoid using squash toblindly combine multiple commit messages without editing them into a single, coherent message.

  • Usegit rebase --interactive when cleaning up commit history, order, messages, etc. This shouldbe done prior to submitting a code review or when code review feedback has been addressed andyou are ready to rebase ontomain.

  • Usegit push --force-with-lease instead ofgit push --force when pushing changes after aninteractive rebasing session.

  • Avoid checking in development-specific configuration files (add to.gitignore instead).

  • Avoid checking in sensitive information (i.e. security keys, passphrases, etc).

  • Avoid "WIP" (a.k.a. "Work in Progress") commits and/or code review labels. Be confident with yourcode and colleagues' time. Use branches, stashes, etc. instead — share a link to a feature branchdiff if you have questions/concerns during development.

  • Avoid usingGit Submodules. Thispractice leads to complicated project cloning, deployments, maintenance, etc. Use separaterepositories to better organize and split out this work. Sophisticated package managers, likeBundler, exist to manage these dependencies better than what multiple GitSubmodules can accomplish.

  • Avoid usingGit LFS for tracking binary artifacts/resources.These files are not meant for version control and lead to large repositories that are timeconsuming to clone/deploy. Use storage managers likeGitAnnex,Amazon S3, orLakeFS which arebetter suited for binary assets that don’t change often.

Security

Ensure signed commits, pushes, and tags are enabled within your global Git Configuration to reduceanattackvector. Run the following commands to enable:

git config --global commit.gpgSigntruegit config --global push.gpgSigntruegit config --global tag.gpgSigntrue

⚠️ GitHub, unfortunately, doesn’t support signed pushes so you might need to leave thatconfiguration disabled.

Commits

  • Use a commit subject that explainswhat is being committed.

  • Use a commit message body that explainswhy the commit is necessary. Additional considerations:

    • If the commit has a dependency to the previous commit or is a precursor to the commit that willfollow, make sure to explain that.

    • Include links to dependent projects, stories, etc. if available.

  • Use small, atomic commits:

    • Easier to review and provide feedback.

    • Easier to review implementation and corresponding tests.

    • Easier to document with detailed subjects (especially when grouped together in a pull request).

    • Easier to reword, edit, squash, fix, or drop when interactively rebasing.

    • Easier to combine together versus tearing apart a larger commit into smaller commits.

  • Use logically ordered commits:

    • Each commit should tell a story and be a logical building block to the next commit.

    • Each commit should, ideally, be the implementation plus corresponding test. Avoid committingchanges that are a jumble of mixed ideas as they are hard to decipher and a huge insult not onlyto the reviewer but your future self.

    • Each commit, when reviewed in order, should be able to explainhow the feature or bug fix wascompleted and implemented properly.

  • Keep refactored code separate from behavioral changes. This makes the review process easierbecause you don’t have to sift through all the line and format changes to figure out what is newor changed.

Branches

  • Use feature branches for new work.

  • Maintain branches by rebasing uponmain on a regular basis.

Tags

  • Use tags to denotemilestones:

    • Makes it easier to record milestones and capture associated release notes.

    • Makes it easier to compare differences between versions.

    • Provides a starting point for debugging production issues (if any).

Rebases

  • Avoid rebasing a shared branch. If you must do this, clear communication should be used to warnthose ahead of time, ensure that all of their work is checked in, and that their local branch isdeleted first.

Hooks

  • Use hooks to augment and automate your personal workflow such as checking code quality, detectingforgotten debug statements, etc.

  • Use hooks globally rather than locally per project. Doing this applies the same functionalityacross all projects automatically, reduces maintenance per project, and provides consistencyacross all projects. This can best be managed via yourDotfiles.

  • Avoid forcing global or local project hooks as a team-wide mandate. Hooks are a personal tool muchlike editors or other tools one choose to do their work. For team consistency, use a continuousintegration build server instead.

Code Reviews

For an in depth look at how to conduct code reviews, please read myarticle on this subject to learn more.

Development

To contribute, run:

git clone https://github.com/bkuhlmann/git-lintcd git-lintbin/setup

You can also use the IRB console for direct access to all objects:

bin/console

Tests

To test, run:

bin/rake

Credits

About

A command line interface for linting Git commits.

Resources

License

Stars

Watchers

Forks

Sponsor this project

 

Packages

No packages published

Languages


[8]ページ先頭

©2009-2025 Movatter.jp