forked from defunkt/gist
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gist.rb
executable file
·77 lines (59 loc) · 1.77 KB
/
gist.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/usr/bin/env ruby
=begin
INSTALL:
curl http://github.com/defunkt/gist/tree/master%2Fgist.rb?raw=true > gist &&
chmod 755 gist &&
sudo mv gist /usr/local/bin/gist
USE:
cat file.txt | gist
echo secret | gist -p # or --private
gist 1234 > something.txt
=end
require 'open-uri'
require 'net/http'
module Gist
extend self
@@gist_url = 'http://gist.github.com/%s.txt'
def read(gist_id)
return help if gist_id.nil? || gist_id[/^\-h|help$/]
return open(@@gist_url % gist_id).read unless gist_id.to_i.zero?
return open(gist_id + '.txt').read if gist_id[/https?:\/\/gist.github.com\/\d+$/]
end
def write(content, private_gist)
url = URI.parse('http://gist.github.com/gists')
req = Net::HTTP.post_form(url, data(nil, nil, content, private_gist))
copy req['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`.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?
puts Gist.read(ARGV.first)
else
puts Gist.write($stdin.read, %w[-p --private].include?(ARGV.first))
end