0

I want to create bash script that squashes commits with same name in a row. The user should be able to enter the commit number between which it will search for commit names and if it finds 2 similar names in a row it should merge the commits.

Following is the code for getting the range of commits but i want to know how to merge commits having same name in a row.

#!/bin/bash

echo 'Enter starting commit number 1 or 2'
read start
echo 'Enter ending commit number 3,4 or 5'
read end

rebaser=`git rebase -i HEAD~$end HEAD~$start`
2
  • "and if it finds 2 similar names in a row" – how similar is similar? Commented Oct 20, 2022 at 12:14
  • Note that HEAD~$start will leave you in detached HEAD state. You usually want to rebase a branch, not a commit. Commented Oct 20, 2022 at 13:26

1 Answer 1

0

You can run rebase with a custom sequence editor. awk makes it simple enough (depending on your definition of "simple") to detect identical commit messages:

GIT_SEQUENCE_EDITOR='awk "!/^#/{action=\$1;commit=\$2;\$1=\$2=\"\";if(msg==\$0){action=\"fixup\"};print action,commit,\$0;msg=\$0;next}{print}" "$1" > "$1.tmp"; mv "$1.tmp" "$1";:' git rebase -i upstream

The editor command will receive the todo list and can modify it by overwriting the file passed in as $1.

It's probably best to store this sequencer command in a separate executable script and then simply do GIT_SEQUENCE_EDITOR=path/to/yourscript.sh or to define a Git alias. This would avoid the escaping madness happening above due to different contexts.

The formatted (and unescaped) awk script with explanations:

!/^#/{ # only process non-comment lines
  action=$1; # first field is the action (pick, fixup, etc.)
  commit=$2; # second field is the commit id
  $1=$2="";  # ignore first two fields when comparing message
  if(msg == $0) {
    action="fixup" # message was identical to previous line, squash commit
  };
  print action,commit,$0; # print action, commit id and message (actually, only action + id are required)
  msg=$0; # remember current message for next line
  next    # start processing next line
}
{print} # print comment lines
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.