Skip to content

Instantly share code, notes, and snippets.

@headius
Forked from evanphx/gist:663404
Created November 19, 2010 20:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save headius/707061 to your computer and use it in GitHub Desktop.
Save headius/707061 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
=begin
INSTALL:
curl http://github.com/defunkt/gist/raw/master/gist.rb > gist &&
chmod 755 gist &&
sudo mv gist /usr/local/bin/gist
USE:
gist < file.txt
echo secret | gist -p # or --private
echo secret | gist --copy # replace contents of paste buffer
gist 1234 > something.txt
=end
require 'open-uri'
require 'net/http'
require 'net/https'
module Gist
extend self
@@gist_url = 'https://gist.github.com/%s.txt'
def read(gist_id)
return help if gist_id == '-h' || gist_id.nil? || gist_id[/help/]
open(@@gist_url % gist_id).read
end
def write(content, private_gist)
url = URI.parse('https://gist.github.com/gists')
obj = Net::HTTP.new(url.host, url.port)
# IGNORE
def obj.warn(str); end
obj.use_ssl = true
req = Net::HTTP::Post.new(url.path)
req.form_data = data(nil, nil, content, private_gist)
res = obj.start { |h| h.request(req) }
if ARGV.include? "--copy"
copy res['Location']
end
res['location']
end
def help
"USE:\n " + File.read(__FILE__).match(/USE:(.+?)=end/m)[1].strip
end
private
def copy(content)
case RUBY_PLATFORM
when /darwin/
return content if `which pbcopy`.strip == ''
IO.popen('pbcopy', 'r+') { |clip| clip.puts content }
when /linux/
return content if `which xclip 2> /dev/null`.strip == ''
IO.popen('xclip', 'r+') { |clip| clip.puts content }
end
content
end
def data(name, ext, content, private_gist)
return {
'file_ext[gistfile1]' => ext,
'file_name[gistfile1]' => name,
'file_contents[gistfile1]' => content
}.merge(private_gist ? { 'private' => 'on' } : {}).merge(auth)
end
def auth
user = `git config --global github.user`.strip
token = `git config --global github.token`.strip
user.empty? ? {} : { :login => user, :token => token }
end
end
if $stdin.tty?
output = Gist.read(ARGV.first)
$stdout.tty? ? puts(output) : print(output)
else
output = Gist.write($stdin.read, %w[-p --private].include?(ARGV.first))
$stdout.tty? ? puts(output) : print(output)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment