Skip to content

Instantly share code, notes, and snippets.

@mugifly
Last active Dec 26, 2015
Embed
What would you like to do?
Gist ssh-clone script (git clone via ssh)
#! /usr/bin/env perl
# Gist ssh-clone script
# Help: $ perl git-clone-ssh.pl --help
# (c) Masanori Ohgita (http://ohgita.info/) - 2013, MIT License.
use warnings;
use strict;
use utf8;
use File::Basename qw//;
our $PATH_GIT_BIN = '/usr/bin/git';
our $NAME_SCRIPT = File::Basename::basename($0, '');
our %Config = ( dry_run => 0, url => undef );
# Initialize
init();
error('URL is empty.') unless defined $Config{url};
# Get a gist-id by Gist HTTPS url
my $gist_id = get_gist_id_by_url($Config{url});
error('Invalid URL.') unless defined $gist_id;
# Get a SSH uri
my $ssh_uri = get_ssh_uri_by_gist_id($gist_id);
# Git clone using ssh
git_ssh_clone($ssh_uri);
exit;
sub init {
# Check for git
my $a = `$PATH_GIT_BIN --version`;
unless ($a =~ /git\ version.*/){
error("Not found git: $PATH_GIT_BIN");
}
# Check a parameters
foreach (@ARGV) {
if ($_ =~ /^\-\-dry\-run$/i || $_ =~ /^\-d$/){
$Config{dry_run} = 1;
} elsif ($_ =~ /^\-\-help$/i || $_ =~ /^\-h$/){
print_help();
exit;
} elsif ($_ =~ /(http|https)\:\/\/(.*)/) {
chomp($_);
$Config{url} = $_;
}
}
}
sub get_gist_id_by_url {
my $url = shift;
if ($url =~ /^(http|https)\:\/\/gist\.github\.com\/(\w+)\.git$/){
return $2;
} elsif ($url =~ /^(http|https)\:\/\/gist\.github\.com\/(\w+)\/(\w+)$/) {
return $3;
}
return undef;
}
sub get_ssh_uri_by_gist_id {
my $gist_id = shift;
return 'git@gist.github.com:' . $gist_id . '.git';
}
sub git_ssh_clone {
my $ssh_uri = shift;
if ($Config{dry_run}) {
print "[DRYRUN] $PATH_GIT_BIN clone $ssh_uri";
} else {
print `$PATH_GIT_BIN clone $ssh_uri`;
}
print "\n";
}
sub print_help {
print <<EOF;
usage: $NAME_SCRIPT URL [-h|--help] [-d|--dry-run]
URL Gist URL (https)
e.g.: https://gist.github.com/mugifly/6451502
-h | --help Help message (This message)
-d | --dry-run Dry-run mode
EOF
}
sub error {
my $msg = shift;
print "[ERROR] $msg\n";
print "-------------------------\n";
print_help();
exit(-1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment