Trevor Norris
Trevor Norris

Reputation: 21099

automatically select sha's to edit during git rebase

I have a branch with a few dozen commits that was recently rebased on top of master. During conflict resolution some mistakes were made and now half a dozen of those commits need to be edited.

The list of sha's that need to be edited can be found via:

$ git log --format=format:%H master..branch-in-question -- file/path

Which can be used with git rebase -i to individually select each one for edit (and would probably be faster than taking the time to ask this question, but I'm sure you all understand). My question is whether it's possible to pass in the list of sha's from the git log above into git rebase and have it automatically select those commits for edit.

Upvotes: 3

Views: 340

Answers (1)

Scott Weldon
Scott Weldon

Reputation: 10227

I don't know of a built-in way to do this, but I have a workaround that should save you some time.

First, start the interactive rebase:

git rebase -i

Change the command for the first (and only the first) commit from pick to edit, then save and exit.

Run this script:

#!/bin/bash

for sha in $(git log --format=format:%H master..branch-in-question -- file/path)
do
  sha=${sha:0:7}
  sed -i "s/pick $sha/edit $sha/" .git/rebase-merge/git-rebase-todo
done

Then do:

git rebase --continue

This pauses the rebase immediately, applies the edits that you would have done by hand to the todo file, and continues.

You are not able to create the todo file ahead of time, because doing so causes Git to assume that you have already started the rebase.


Thanks to some help from @torek, I have a way to automate this. Modify the script as follows:

#!/bin/bash

# editor=$(git config --get core.editor);
# editor=${editor:-${VISUAL:-${EDITOR:-vi}}};
for sha in $(git log --format=format:%H master..branch-in-question -- file/path)
do
  sha=${sha:0:7}
  sed -i "s/pick $sha/edit $sha/" $@
done

# $editor $@

(If you want a chance to modify the todo file before running the rebase, uncomment the editor lines.)

Then, start the rebase as:

GIT_SEQUENCE_EDITOR=/path/to/script.sh git rebase -i

This will automatically change the command for all commits output by your command from pick to edit, without the need to manually change the first commit yourself.


Neither version of the script allows you to customize what command is run to calculate which commits to use, but if this is an issue, you could probably pass in an environment variable to allow such customization.

Upvotes: 4

Related Questions