diff --git a/README.md b/README.md index 8353bdd..d35c8c0 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1565 TILs and counting..._ +_1566 TILs and counting..._ See some of the other learning resources I work on: - [Ruby Operator Lookup](https://www.visualmode.dev/ruby-operators) @@ -304,6 +304,7 @@ See some of the other learning resources I work on: - [Configuring The Pager](git/configuring-the-pager.md) - [Copy A File From Another Branch](git/copy-a-file-from-another-branch.md) - [Count All Files Of Specific Type Tracked By Git](git/count-all-files-of-specific-type-tracked-by-git.md) +- [Count Number Of Commits On A Branch](git/count-number-of-commits-on-a-branch.md) - [Create A New Branch With Git Switch](git/create-a-new-branch-with-git-switch.md) - [Delete All Untracked Files](git/delete-all-untracked-files.md) - [Determine The Hash Id For A Blob](git/determine-the-hash-id-for-a-blob.md) diff --git a/git/count-number-of-commits-on-a-branch.md b/git/count-number-of-commits-on-a-branch.md new file mode 100644 index 0000000..bd8ff08 --- /dev/null +++ b/git/count-number-of-commits-on-a-branch.md @@ -0,0 +1,48 @@ +# Count Number Of Commits On A Branch + +The `git rev-list` command will show all commits that fit the given revision +criteria. By adding in the `--count` flag, we get a count of the number of +commits that would have been displayed. Knowing this, we can get the count of +commits for the current branch like so: + +```bash +$ git rev-list --count HEAD +4 +``` + +This finds and counts commits from `HEAD` (usually the top of the current +branch) all the back in reverse chronological order to the beginning of the +branch (typically the beginning of the repository). This works exactly as +expected for a the `main` branch. + +What about when we are on a feature branch though? + +Let's say we've branched off `main` and made a few commits. And now we want the +count. + +```bash +$ git rev-list --count HEAD +7 +``` + +Unfortunately, that is counting up the commits on the feature branch but it +keeps counting all the way back to the beginning of the repo. + +If we want a count of just the commits on the current branch, then we can +specify a range: from whatever `main` was when we branched to the `HEAD` of +this branch. + +```bash +$ git rev-list --count HEAD +3 +``` + +This is the same as saying, I want all commits on `HEAD`, but exclude (`^`) the +commits on `main`: + +```bash +git rev-list --count HEAD ^main +3 +``` + +See `man git-rev-list` for more details.