Skip to content

Instantly share code, notes, and snippets.

@tokubass
Created March 21, 2015 04:25
Show Gist options
  • Save tokubass/8dcae97d98b59ed28dda to your computer and use it in GitHub Desktop.
Save tokubass/8dcae97d98b59ed28dda to your computer and use it in GitHub Desktop.
デザイナー向けブランチ切り替える君
#!/usr/bin/env perl
use strict;
use warnings;
use Getopt::Long qw/ :config no_ignore_case /;
use Cwd qw/getcwd/;
use IPC::Run qw/ timeout /;
my %OPT;
my $GIT = ( eval { require File::Which; } ) ? File::Which::which('git') : 'git';
my $CWD = getcwd();
my $HOME_DIR = '/home/hoge';
my $PROJECT_NAME = 'project';
my $PROJECT_DIR = "${HOME_DIR}/${PROJECT_NAME}";
main();
exit;
sub main {
GetOptions(
"v|verbose" => \$OPT{v},
"l|link-only=s" => \$OPT{l},
"m|message=s" => \$OPT{git_opt_m},
"author=s" => \$OPT{git_opt_author},
) or die 'opt error';
return symlink_to_project_by_branch($OPT{l}) if $OPT{l};
my $branch_name = checkout_to_correct_branch();
my $author = $OPT{git_opt_author} ? sprintf( "--author=%s", $OPT{git_opt_author} ) : '';
my $message = sprintf( "-m %s", $OPT{git_opt_m} || 'update' );
git_run( pull => 'origin', $branch_name )->{print}->();
git_run( commit => $author, $message, '-v' )->{print}->();
git_run( push => 'origin', $branch_name )->{print}->();
symlink_to_project_by_branch($branch_name);
}
sub symlink_to_project_by_branch {
my $branch_name = shift or die 'need branch_name';
if ( ! -f $PROJECT_DIR && -l $PROJECT_DIR ) {
unlink $PROJECT_DIR;
}
if ( ! -e $PROJECT_DIR ) {
(symlink "${HOME_DIR}/${PROJECT_NAME}.${branch_name}", $PROJECT_DIR) ? print "change link to $branch_name\n"
: print "error! can not change link to $branch_name\n";
}
}
sub checkout_to_correct_branch {
my $expected_branch_name = expected_branch_name();
if ( $expected_branch_name ne current_branch_name() ) {
git_run( 'checkout', $expected_branch_name );
}
if ( $expected_branch_name ne current_branch_name() ) {
die 'can not checkout';
}
return $expected_branch_name;
}
sub expected_branch_name {
opendir my $dh, $CWD or die $!;
my @file = grep { /\Abranch_.+/ } readdir($dh);
die 'branh name file not found' if ( @file == 0 );
die 'more than one branh name file' if ( @file != 1 );
$file[0] =~ s/\Abranch_//;
return $file[0];
}
sub current_branch_name {
my $branch_res = git_run('branch');
my $out = $branch_res->{out} or die 'failed git branch command';
my ($current_branch) = ($out =~ /^\* ([^\n]+)/m);
die 'current branch not found' unless $current_branch;
return $current_branch;
}
sub git_run {
my @cmd = @_ or die 'please input git command name';
unshift @cmd, $GIT;
IPC::Run::run(
\@cmd,
\my $in,
\my $out,
\my $err,
timeout(10)
);
print "@cmd\n" if $OPT{v};
return {
in => $in,
out => $out,
err => $err,
cmd => join(' ', @cmd),
print => sub { print $out ? "$out\n" : "$err\n" },
};
}
__END__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment