gitgit-amend

How can I detect whether a git commit is a parent of other commits?


I'm writing a script that makes some trivial changes and then commits them to git. Because these are trivial changes, I want to do git commit --amend whenever I can get away with it -- specifically, when an amend won't "mess up" any other branches' history. If an amend would mess up another branch, I want to do a standard git commit instead.

For example, if my branches looked like this (a la "Visualize all branch history" in Git GUI):

* [experimental branch] Added feature.
* [master branch] Trivial change from script
* ...

and I'm running this script on the master branch, then I don't want to do an amend, because I would be replacing part of the experimental branch's history. Technically, this won't actually break anything -- the original commit will still be part of experimental's history, and will still be referenced so it won't get garbage collected -- but having nearly-but-not-quite-identical commits in two different branches makes life difficult when I later want to rebase or merge, so it's a situation I want to avoid.

How can I make my script automatically detect whether a commit has anything branched from it?

If simplifying assumptions help, I always run this script on the head of master, and I only use git as a local repository -- I don't push or pull changes anywhere.

This script is in Ruby, so I can either shell out to the git command line, or I can use Ruby bindings for git -- whichever would make this task easier.


Solution

  • Just run git branch --contains HEAD to get a list of branches that "contain" this commit. If the list is empty, that commit should be safe for ammending. You also might want to include the -a flag to list local AND remote branches.

    Alternatively, you could compare the output of git rev-parse HEAD with git merge-base HEAD other-branch. If these commit IDs are identical, the current commit is in other-branch's commit history.