From 2e8697d35312847a60757f05cc92ca5c18370f7a Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Sat, 13 Aug 2016 12:12:37 -0500 Subject: [PATCH] Add Checking Commit Ancestry as a git til --- README.md | 3 ++- git/checking-commit-ancestry.md | 27 +++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 git/checking-commit-ancestry.md diff --git a/README.md b/README.md index b095e38..f070bf6 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ variety of languages and technologies. These are things that don't really warrant a full blog post. These are mostly things I learn by pairing with smart people at [Hashrocket](http://hashrocket.com/). -_453 TILs and counting..._ +_454 TILs and counting..._ --- @@ -101,6 +101,7 @@ _453 TILs and counting..._ - [Accessing a Lost Commit](git/accessing-a-lost-commit.md) - [Amend Author Of Previous Commit](git/amend-author-of-previous-commit.md) - [Caching Credentials](git/caching-credentials.md) +- [Checking Commit Ancestry](git/checking-commit-ancestry.md) - [Checkout Old Version Of A File](git/checkout-old-version-of-a-file.md) - [Checkout Previous Branch](git/checkout-previous-branch.md) - [Clean Out All Local Branches](git/clean-out-all-local-branches.md) diff --git a/git/checking-commit-ancestry.md b/git/checking-commit-ancestry.md new file mode 100644 index 0000000..5cab67d --- /dev/null +++ b/git/checking-commit-ancestry.md @@ -0,0 +1,27 @@ +# Checking Commit Ancestry + +I have two commit shas and I want to know if the first is an ancestor of the +second. Put another way, is this first commit somewhere in the history of +this other commit. + +Git's `merge-base` command combined with the `--is-ancestor` flag makes +answering this question easy. Furthermore, because it is a plumbing command, +it can be used in a script or sequence of commands as a switch based on the +answer. + +Here is an example of this command in action: + +```bash +$ git merge-base --is-ancestor head~ head && echo 'yes, it is' +yes, it is +$ git merge-base --is-ancestor head~ head~~ && echo 'yes, it is' +``` + +In the first command, `head~` is clearly an ancestor of `head`, so the +`echo` command is triggered. In the second, `head~` is not an ancestor of +`head~~` so the return status of 1 short-circuits the rest of the command. +Hence, no `echo`. + +See `man git-merge-base` for more details. + +[source](http://stackoverflow.com/questions/18345157/how-can-i-tell-if-one-commit-is-an-ancestor-of-another-commit-or-vice-versa)