-
Notifications
You must be signed in to change notification settings - Fork 87
/
github-upload.rb
211 lines (158 loc) · 5.97 KB
/
github-upload.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
#!/usr/bin/env ruby
# Die if something goes wrong.
def die(msg); puts(msg); exit!(1); end
# First thing we do is check the ruby version. This script requires 1.9, die
# if that's not the case.
die("This script requires ruby 1.9") unless RUBY_VERSION =~ /^1.9/
require 'json'
require 'net/https'
require 'pathname'
require 'optparse'
# Extensions
# ----------
# We extend Pathname a bit to get the content type.
class Pathname
def type
if $options[:mime_type] then
$options[:mime_type]
else
flags = RUBY_PLATFORM =~ /darwin/ ? 'Ib' : 'ib'
`file -#{flags} #{realpath}`.chomp.gsub(/;.*/,'')
end
end
end
# Helpers
# -------
def get_http_request(uri, token, request, params = "")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE if $options[:skip_ssl_verification]
request['Authorization'] = "token #{token}" if token
return http.request(request, params)
end
def get(url, token)
uri = URI.parse(url)
req = Net::HTTP::Get.new(uri.path)
return get_http_request(uri, token, req)
end
# Do a post to the given url, with the payload and optional basic auth.
def post(url, token, params, headers)
uri = URI.parse(url)
req = Net::HTTP::Post.new(uri.path, headers)
return get_http_request(uri, token, req, params)
end
def delete(url, token)
uri = URI.parse(url)
req = Net::HTTP::Delete.new(uri.path)
return get_http_request(uri, token, req)
end
def urlencode(str)
str.gsub(/[^a-zA-Z0-9_\.\-]/n) {|s| sprintf('%%%02x', s[0].to_i) }
end
# Yep, ruby net/http doesn't support multipart. Write our own multipart generator.
# The order of the params is important, the file needs to go as last!
def build_multipart_content(params)
parts, boundary = [], "#{rand(1000000)}-we-are-all-doomed-#{rand(1000000)}"
params.each do |name, value|
data = []
if value.is_a?(Pathname) then
data << "Content-Disposition: form-data; name=\"#{urlencode(name.to_s)}\"; filename=\"#{value.basename}\""
data << "Content-Type: #{value.type}"
data << "Content-Length: #{value.size}"
data << "Content-Transfer-Encoding: binary"
data << ""
data << value.binread
else
data << "Content-Disposition: form-data; name=\"#{urlencode(name.to_s)}\""
data << ""
data << value
end
parts << data.join("\r\n") + "\r\n"
end
[ "--#{boundary}\r\n" + parts.join("--#{boundary}\r\n") + "--#{boundary}--", {
"Content-Type" => "multipart/form-data; boundary=#{boundary}"
}]
end
# Parse command line options using OptionParser
# -----------------------
$options = {}
OptionParser.new do |opts|
opts.banner = "Usage: github-upload.rb <file-name> [<repository>] [options]"
opts.on("-d", "--description [DESCRIPTION]",
"Add a description to the uploaded file.") do |arg_description|
$options[:file_description] = arg_description
end
opts.on("-n", "--name [NAME]",
"New name of the uploaded file.") do |arg_name|
$options[:file_name] = arg_name
end
opts.on("-f", "--force",
"If a file with that name already exists on the server, replace it with this one.") do
$options[:force_upload] = true
end
opts.on("-t", "--token [TOKEN]",
"Manually specify a GitHub API token. Useful if you want to temporarily upload a file under a different GitHub account.") do |arg_token|
$options[:token] = arg_token
end
opts.on("--skip-ssl-verification",
"Skip SSL Verification in the HTTP Request.") do
$options[:skip_ssl_verification] = true
end
opts.on("-m", "--mime-type [TYPE]",
"Manually specify mime-type instead autodetection.") do |arg_type|
$options[:mime_type] = arg_type
end
opts.on("-h", "--help",
"Show this message") do
puts opts
exit
end
end.parse!
# Configuration and setup
# -----------------------
# The file we want to upload, and repo where to upload it to.
die("Please specify a file to upload.") if ARGV.length < 1
file = Pathname.new(ARGV[0])
repo = ARGV[1] || `git config --get remote.origin.url`.match(/github.com[:\/](.+?)\.git/)[1]
file_name = $options[:file_name] || file.basename.to_s
file_description = $options[:file_description] || ""
# The actual, hard work
# ---------------------
# Get Oauth token for this script.
$options[:token] = `git config --get github.upload-script-token`.chomp unless $options[:token]
if $options[:force_upload]
# Make sure the file doesn't already exist
res = get("https://api.github.com/repos/#{repo}/downloads", $options[:token])
info = JSON.parse(res.body)
info.each do |remote_file|
remote_file_name = remote_file["name"].to_s
if remote_file_name == file_name then
# Delete already existing files
puts "Deleting existing file '#{remote_file_name}'"
remote_file_id = remote_file["id"].to_s
res = delete("https://api.github.com/repos/#{repo}/downloads/#{remote_file_id}", $options[:token])
end
end
end
# Register the download at github.
res = post("https://api.github.com/repos/#{repo}/downloads", $options[:token], {
'name' => file_name, 'size' => file.size.to_s,
'description' => file_description,
'content_type' => file.type.gsub(/;.*/, '')
}.to_json, {})
die("File already exists named '#{file_name}'.") if res.class == Net::HTTPClientError
die("GitHub doesn't want us to upload the file.") unless res.class == Net::HTTPCreated
# The URL where people can download the file. At the end of the script, we
# print it out for convenience.
html_url = JSON.parse(res.body)['html_url']
# Parse the body and use the info to upload the file to S3.
info = JSON.parse(res.body)
res = post(info['s3_url'], nil, *build_multipart_content({
'key' => info['path'], 'acl' => info['acl'], 'success_action_status' => 201,
'Filename' => info['name'], 'AWSAccessKeyId' => info['accesskeyid'],
'Policy' => info['policy'], 'signature' => info['signature'],
'Content-Type' => info['mime_type'], 'file' => file
}))
die("S3 is mean to us.") unless res.class == Net::HTTPCreated
# Print the URL to the file to stdout.
puts html_url