Skip to content

Instantly share code, notes, and snippets.

@numberten
Created October 17, 2013 06:16
Show Gist options
  • Save numberten/7019855 to your computer and use it in GitHub Desktop.
Save numberten/7019855 to your computer and use it in GitHub Desktop.
A compact perl script for gisting files from the command line.
#!/usr/bin/perl
use Getopt::Long;
#Parse flags using Getopt::Long.
my $desc = '';
my $public = 0;
my $user = '';
my $verbose = 0;
GetOptions ('desc:s' => \$desc,
'public' => \$public,
'user:s' => \$user,
'verbose' => \$verbose);
#Convert $public to a boolean string.
$public = ($public == 1 ? 'true' : 'false');
#Check number of commandline args. Print usage if wrong number.
if (@ARGV != 1) {
print "Usage: gist [--public] [--verbose] [--desc \"description\"] [--user \"username\"] <file-to-upload>\n";
exit 1;
}
#Load file contents into $document. Replace newlines with \\n.
my $file = "$ARGV[0]";
my $document = do {
local $/ = undef;
open my $fh, "<", $file
or die "could not open $file: $!";
<$fh>;
};
#Converts a string into an array.
sub str2ary{
return split //, $_[0];
}
#Converts an array into a string.
sub ary2str{
my $str = "@_";
$str =~ s/(.)\s/$1/g;
return $str;
}
#Converts an ascii character into its unicode equivalent.
sub char2hex{
my $newchar = "\\u00" . sprintf("%x",ord($_[0]));
$newchar = ($newchar cmp "\\u00a" ? $newchar : "\\u000d\\u000a");
return $newchar;
}
$document = ary2str(map char2hex($_), str2ary($document));
#Make sure $filename doesn't contain path to file.
my @xs = split(/\//, $ARGV[0]);
my $filename = $xs[@xs-1];
#Append description field to $desc.
$desc = ($desc cmp '' ? ('"description": "' . $desc . '", ') : '');
#Append '--user' to $user if defined.
$user = ($user cmp '' ? ('--user "' . $user . '" ') : '');
#Submits a gist. Returns entire gist response if verbose, only html_url otherwise.
sub submit_gist{
$response = `curl -s -X POST \\
$user--data-binary '{$desc"public": $public, "files": {"$filename": {"content": "$document"}}}' \\
https://api.github.com/gists`;
my @group = $response =~ /"html_url": "(https:\/\/gist\.github\.com\/(.+?))",/;
print ($verbose ? $response : "$group[0]\n");
}
&submit_gist();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment