Skip to content

Instantly share code, notes, and snippets.

@geraldlai
Last active October 17, 2021 04:58
Show Gist options
  • Save geraldlai/92c4b372a9e320280c119770a4cdb6fe to your computer and use it in GitHub Desktop.
Save geraldlai/92c4b372a9e320280c119770a4cdb6fe to your computer and use it in GitHub Desktop.
git-mergic: easy merge
#!/usr/bin/env perl
# git (mer)ge ma(gic) - DWIM rebasing
# $ git mergic master
# # Merging from: [origin] master
# ( merges or rebases current branch onto origin/master )
# Author: Gerald Lai
# License: 0BSD
use warnings;
use strict;
if (@ARGV && $ARGV[0] eq "-h") {
print "usage: git mergic <branch> [<remote>]\n";
exit 0;
}
my ($branch, $remote) = @ARGV;
unless (defined $remote) {
chomp(my @remotes = qx{ git remote 2> /dev/null });
die "Not a git repo.\n" unless $? == 0;
die "No remotes found.\n" unless @remotes;
if (@remotes == 1) {
$remote = $remotes[0];
} else {
die sprintf("More than one remote found: %s\n",
join ", " => @remotes,
);
}
}
unless (defined $branch) {
for my $b (qw(main master)) {
if (0 == system "git show-branch 'remotes/$remote/$b' > /dev/null 2>&1") {
$branch = $b;
}
}
}
unless (defined $branch) {
chomp($branch = qx{ git symbolic-ref --short --quiet HEAD });
}
print STDERR "# Merging from: [$remote] $branch\n";
exec <<"EOC";
git fetch '$remote' --prune && (git merge --ff-only '$remote/$branch' || git rebase --rebase-merges '$remote/$branch')
EOC
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment