evertils-gist 5.1.3

Sign up to get free protection for your applications and to get access to all the features.
data/build/gist.1 ADDED
@@ -0,0 +1,277 @@
1
+ .\" generated with Ronn/v0.7.3
2
+ .\" http://github.com/rtomayko/ronn/tree/0.7.3
3
+ .
4
+ .TH "GIST" "1" "May 2018" "" "Gist manual"
5
+ .
6
+ .SH "NAME"
7
+ \fBgist\fR \- upload code to https://gist\.github\.com
8
+ .
9
+ .SH "Synopsis"
10
+ The gist gem provides a \fBgist\fR command that you can use from your terminal to upload content to https://gist\.github\.com/\.
11
+ .
12
+ .SH "Installation"
13
+ .
14
+ .IP "\(bu" 4
15
+ If you have ruby installed:
16
+ .
17
+ .IP
18
+ gem install gist
19
+ .
20
+ .IP "\(bu" 4
21
+ If you\'re using Bundler:
22
+ .
23
+ .IP
24
+ source :rubygems gem \'gist\'
25
+ .
26
+ .IP "\(bu" 4
27
+ For OS X, gist lives in Homebrew
28
+ .
29
+ .IP
30
+ brew install gist
31
+ .
32
+ .IP "" 0
33
+ .
34
+ .SH "Command"
35
+ .
36
+ .IP "\(bu" 4
37
+ To upload the contents of \fBa\.rb\fR just:
38
+ .
39
+ .IP
40
+ gist a\.rb
41
+ .
42
+ .IP "\(bu" 4
43
+ Upload multiple files:
44
+ .
45
+ .IP
46
+ gist a b c gist *\.rb
47
+ .
48
+ .IP "\(bu" 4
49
+ By default it reads from STDIN, and you can set a filename with \fB\-f\fR\.
50
+ .
51
+ .IP
52
+ gist \-f test\.rb <a\.rb
53
+ .
54
+ .IP "\(bu" 4
55
+ Alternatively, you can just paste from the clipboard:
56
+ .
57
+ .IP
58
+ gist \-P
59
+ .
60
+ .IP "\(bu" 4
61
+ Use \fB\-p\fR to make the gist private:
62
+ .
63
+ .IP
64
+ gist \-p a\.rb
65
+ .
66
+ .IP "\(bu" 4
67
+ Use \fB\-d\fR to add a description:
68
+ .
69
+ .IP
70
+ gist \-d "Random rbx bug" a\.rb
71
+ .
72
+ .IP "\(bu" 4
73
+ You can update existing gists with \fB\-u\fR:
74
+ .
75
+ .IP
76
+ gist \-u GIST_ID FILE_NAME gist \-u 42f2c239d2eb57299408 test\.txt
77
+ .
78
+ .IP "\(bu" 4
79
+ If you\'d like to copy the resulting URL to your clipboard, use \fB\-c\fR\.
80
+ .
81
+ .IP
82
+ gist \-c <a\.rb
83
+ .
84
+ .IP "\(bu" 4
85
+ If you\'d like to copy the resulting embeddable URL to your clipboard, use \fB\-e\fR\.
86
+ .
87
+ .IP
88
+ gist \-e <a\.rb
89
+ .
90
+ .IP "\(bu" 4
91
+ And you can just ask gist to open a browser window directly with \fB\-o\fR\.
92
+ .
93
+ .IP
94
+ gist \-o <a\.rb
95
+ .
96
+ .IP "\(bu" 4
97
+ To list (public gists or all gists for authed user) gists for user
98
+ .
99
+ .IP
100
+ gist \-l : all gists for authed user gist \-l defunkt : list defunkt\'s public gists
101
+ .
102
+ .IP "" 0
103
+ .
104
+ .P
105
+ To read a gist and print it to STDOUT
106
+ .
107
+ .IP "" 4
108
+ .
109
+ .nf
110
+
111
+ gist \-r GIST_ID
112
+ gist \-r 374130
113
+ .
114
+ .fi
115
+ .
116
+ .IP "" 0
117
+ .
118
+ .IP "\(bu" 4
119
+ See \fBgist \-\-help\fR for more detail\.
120
+ .
121
+ .IP "" 0
122
+ .
123
+ .SH "Login"
124
+ If you want to associate your gists with your GitHub account, you need to login with gist\. It doesn\'t store your username and password, it just uses them to get an OAuth2 token (with the "gist" permission)\.
125
+ .
126
+ .IP "" 4
127
+ .
128
+ .nf
129
+
130
+ gist \-\-login
131
+ Obtaining OAuth2 access_token from github\.
132
+ GitHub username: ConradIrwin
133
+ GitHub password:
134
+ 2\-factor auth code:
135
+ Success! https://github\.com/settings/tokens
136
+ .
137
+ .fi
138
+ .
139
+ .IP "" 0
140
+ .
141
+ .P
142
+ This token is stored in \fB~/\.gist\fR and used for all future gisting\. If you need to you can revoke it from https://github\.com/settings/tokens, or just delete the file\.
143
+ .
144
+ .IP "\(bu" 4
145
+ After you\'ve done this, you can still upload gists anonymously with \fB\-a\fR\.
146
+ .
147
+ .IP
148
+ gist \-a a\.rb
149
+ .
150
+ .IP "" 0
151
+ .
152
+ .P
153
+ If you have a complicated authorization requirement you can manually create a token file by pasting a Github token with only the \fBgist\fR permission into a file called \fB~/\.gist\fR\. You can create one from https://github\.com/settings/tokens
154
+ .
155
+ .P
156
+ This file should contain only the token (~40 hex characters), and to make it easier to edit, can optionally have a final newline (\en or \er\en)\.
157
+ .
158
+ .P
159
+ For example, one way to create this file would be to run:
160
+ .
161
+ .IP "" 4
162
+ .
163
+ .nf
164
+
165
+ echo MY_SECRET_TOKEN > ~/\.gist
166
+ .
167
+ .fi
168
+ .
169
+ .IP "" 0
170
+ .
171
+ .SS "GitHub Enterprise"
172
+ If you\'d like \fBgist\fR to use your locally installed GitHub Enterprise \fIhttps://enterprise\.github\.com/\fR, you need to export the \fBGITHUB_URL\fR environment variable (usually done in your \fB~/\.bashrc\fR)\.
173
+ .
174
+ .IP "" 4
175
+ .
176
+ .nf
177
+
178
+ export GITHUB_URL=http://github\.internal\.example\.com/
179
+ .
180
+ .fi
181
+ .
182
+ .IP "" 0
183
+ .
184
+ .P
185
+ Once you\'ve done this and restarted your terminal (or run \fBsource ~/\.bashrc\fR), gist will automatically use github enterprise instead of the public github\.com
186
+ .
187
+ .P
188
+ Your token for GitHub Enterprise will be stored in \fB\.gist\.<protocol>\.<server\.name>[\.<port>]\fR (e\.g\. \fB~/\.gist\.http\.github\.internal\.example\.com\fR for the GITHUB_URL example above) instead of \fB~/\.gist\fR\.
189
+ .
190
+ .P
191
+ If you have multiple servers or use Enterprise and public GitHub often, you can work around this by creating scripts that set the env var and then run \fBgist\fR\. Keep in mind that to use the public GitHub you must unset the env var\. Just setting it to the public URL will not work\. Use \fBunset GITHUB_URL\fR
192
+ .
193
+ .SS "Token file format"
194
+ If you cannot use passwords, as most Enterprise installations do, you can generate the token via the web interface and then simply save the string in the correct file\. Avoid line breaks or you might see: \fB$ gist \-l Error: Bad credentials\fR
195
+ .
196
+ .TP
197
+ You can also use Gist as a library from inside your ruby code:
198
+ .
199
+ .IP
200
+ Gist\.gist("Look\.at(:my => \'awesome\')\.code")
201
+ .
202
+ .P
203
+ If you need more advanced features you can also pass:
204
+ .
205
+ .IP "\(bu" 4
206
+ \fB:access_token\fR to authenticate using OAuth2 (default is `File\.read("~/\.gist"))\.
207
+ .
208
+ .IP "\(bu" 4
209
+ \fB:filename\fR to change the syntax highlighting (default is \fBa\.rb\fR)\.
210
+ .
211
+ .IP "\(bu" 4
212
+ \fB:public\fR if you want your gist to have a guessable url\.
213
+ .
214
+ .IP "\(bu" 4
215
+ \fB:description\fR to add a description to your gist\.
216
+ .
217
+ .IP "\(bu" 4
218
+ \fB:update\fR to update an existing gist (can be a URL or an id)\.
219
+ .
220
+ .IP "\(bu" 4
221
+ \fB:anonymous\fR to submit an anonymous gist (default is false)\.
222
+ .
223
+ .IP "\(bu" 4
224
+ \fB:copy\fR to copy the resulting URL to the clipboard (default is false)\.
225
+ .
226
+ .IP "\(bu" 4
227
+ \fB:open\fR to open the resulting URL in a browser (default is false)\.
228
+ .
229
+ .IP "" 0
230
+ .
231
+ .P
232
+ NOTE: The access_token must have the "gist" scope\.
233
+ .
234
+ .IP "\(bu" 4
235
+ If you want to upload multiple files in the same gist, you can:
236
+ .
237
+ .IP
238
+ Gist\.multi_gist("a\.rb" => "Foo\.bar", "a\.py" => "Foo\.bar")
239
+ .
240
+ .IP "\(bu" 4
241
+ If you\'d rather use gist\'s builtin access_token, then you can force the user to obtain one by calling:
242
+ .
243
+ .IP
244
+ Gist\.login!
245
+ .
246
+ .IP "\(bu" 4
247
+ This will take them through the process of obtaining an OAuth2 token, and storing it in \fB~/\.gist\fR, where it can later be read by \fBGist\.gist\fR
248
+ .
249
+ .IP "" 0
250
+ .
251
+ .SH "Configuration"
252
+ .
253
+ .IP "\(bu" 4
254
+ If you\'d like \fB\-o\fR or \fB\-c\fR to be the default when you use the gist executable, add an alias to your \fB~/\.bashrc\fR (or equivalent)\. For example:
255
+ .
256
+ .IP
257
+ alias gist=\'gist \-c\'
258
+ .
259
+ .IP "\(bu" 4
260
+ If you\'d prefer gist to open a different browser, then you can export the BROWSER environment variable:
261
+ .
262
+ .IP
263
+ export BROWSER=google\-chrome
264
+ .
265
+ .IP "" 0
266
+ .
267
+ .P
268
+ If clipboard or browser integration don\'t work on your platform, please file a bug or (more ideally) a pull request\.
269
+ .
270
+ .P
271
+ If you need to use an HTTP proxy to access the internet, export the \fBHTTP_PROXY\fR or \fBhttp_proxy\fR environment variable and gist will use it\.
272
+ .
273
+ .SH "Meta\-fu"
274
+ Thanks to @defunkt and @indirect for writing and maintaining versions 1 through 3\. Thanks to @rking and @ConradIrwin for maintaining version 4\.
275
+ .
276
+ .P
277
+ Licensed under the MIT license\. Bug\-reports, and pull requests are welcome\.
data/egist.gemspec ADDED
@@ -0,0 +1,21 @@
1
+ # encoding: utf-8
2
+ require './lib/egist'
3
+ Gem::Specification.new do |s|
4
+ s.name = 'evertils-gist'
5
+ s.version = Gist::VERSION
6
+ s.summary = 'Just allows you to upload gists'
7
+ s.description = 'Provides a single function (Gist.gist) that uploads a gist.'
8
+ s.homepage = 'https://github.com/defunkt/gist'
9
+ s.email = ['conrad.irwin@gmail.com', 'rkingist@sharpsaw.org', 'rpriebe@me.com']
10
+ s.authors = ['Conrad Irwin', '☈king', 'aapis']
11
+ s.license = 'MIT'
12
+ s.files = `git ls-files`.split("\n")
13
+ s.require_paths = ["lib"]
14
+
15
+ s.executables << 'egist'
16
+
17
+ s.add_development_dependency 'rake'
18
+ s.add_development_dependency 'ronn'
19
+ s.add_development_dependency 'webmock'
20
+ s.add_development_dependency 'rspec', '>3'
21
+ end
data/lib/egist.rb ADDED
@@ -0,0 +1,586 @@
1
+ require 'net/https'
2
+ require 'cgi'
3
+ require 'uri'
4
+
5
+ begin
6
+ require 'json'
7
+ rescue LoadError
8
+ require File.join File.dirname(File.dirname(__FILE__)), 'vendor', 'json.rb'
9
+ end
10
+
11
+ # It just gists.
12
+ module Gist
13
+ extend self
14
+
15
+ VERSION = '5.1.3'
16
+
17
+ # A list of clipboard commands with copy and paste support.
18
+ CLIPBOARD_COMMANDS = {
19
+ 'pbcopy' => 'pbpaste',
20
+ 'xclip' => 'xclip -o',
21
+ 'xsel -i' => 'xsel -o',
22
+ 'putclip' => 'getclip',
23
+ }
24
+
25
+ GITHUB_API_URL = URI("https://api.github.com/")
26
+ GIT_IO_URL = URI("https://git.io")
27
+
28
+ GITHUB_BASE_PATH = ""
29
+ GHE_BASE_PATH = "/api/v3"
30
+
31
+ URL_ENV_NAME = "GITHUB_URL"
32
+
33
+ USER_AGENT = "gist/#{VERSION} (Net::HTTP, #{RUBY_DESCRIPTION})"
34
+
35
+ # Exception tag for errors raised while gisting.
36
+ module Error;
37
+ def self.exception(*args)
38
+ RuntimeError.new(*args).extend(self)
39
+ end
40
+ end
41
+ class ClipboardError < RuntimeError; include Error end
42
+
43
+ # helper module for authentication token actions
44
+ module AuthTokenFile
45
+ def self.filename
46
+ if ENV.key?(URL_ENV_NAME)
47
+ File.expand_path "~/.gist.#{ENV[URL_ENV_NAME].gsub(/:/, '.').gsub(/[^a-z0-9.]/, '')}"
48
+ else
49
+ File.expand_path "~/.gist"
50
+ end
51
+ end
52
+
53
+ def self.read
54
+ File.read(filename).chomp
55
+ end
56
+
57
+ def self.write(token)
58
+ File.open(filename, 'w', 0600) do |f|
59
+ f.write token
60
+ end
61
+ end
62
+ end
63
+
64
+ # auth token for authentication
65
+ #
66
+ # @return [String] string value of access token or `nil`, if not found
67
+ def auth_token
68
+ @token ||= AuthTokenFile.read rescue nil
69
+ end
70
+
71
+ # Upload a gist to https://gist.github.com
72
+ #
73
+ # @param [String] content the code you'd like to gist
74
+ # @param [Hash] options more detailed options, see
75
+ # the documentation for {multi_gist}
76
+ #
77
+ # @see http://developer.github.com/v3/gists/
78
+ def gist(content, options = {})
79
+ filename = options[:filename] || default_filename
80
+ multi_gist({filename => content}, options)
81
+ end
82
+
83
+ def default_filename
84
+ "gistfile1.txt"
85
+ end
86
+
87
+ # Upload a gist to https://gist.github.com
88
+ #
89
+ # @param [Hash] files the code you'd like to gist: filename => content
90
+ # @param [Hash] options more detailed options
91
+ #
92
+ # @option options [String] :description the description
93
+ # @option options [Boolean] :public (false) is this gist public
94
+ # @option options [Boolean] :anonymous (false) is this gist anonymous
95
+ # @option options [String] :access_token (`File.read("~/.gist")`) The OAuth2 access token.
96
+ # @option options [String] :update the URL or id of a gist to update
97
+ # @option options [Boolean] :copy (false) Copy resulting URL to clipboard, if successful.
98
+ # @option options [Boolean] :open (false) Open the resulting URL in a browser.
99
+ # @option options [Boolean] :skip_empty (false) Skip gisting empty files.
100
+ # @option options [Symbol] :output (:all) The type of return value you'd like:
101
+ # :html_url gives a String containing the url to the gist in a browser
102
+ # :short_url gives a String contianing a git.io url that redirects to html_url
103
+ # :javascript gives a String containing a script tag suitable for embedding the gist
104
+ # :all gives a Hash containing the parsed json response from the server
105
+ #
106
+ # @return [String, Hash] the return value as configured by options[:output]
107
+ # @raise [Gist::Error] if something went wrong
108
+ #
109
+ # @see http://developer.github.com/v3/gists/
110
+ def multi_gist(files, options={})
111
+ if options[:anonymous]
112
+ raise 'Anonymous gists are no longer supported. Please log in with `gist --login`. ' \
113
+ '(GitHub now requires credentials to gist https://bit.ly/2GBBxKw)'
114
+ else
115
+ access_token = (options[:access_token] || auth_token())
116
+ end
117
+
118
+ json = {}
119
+
120
+ json[:description] = options[:description] if options[:description]
121
+ json[:public] = !!options[:public]
122
+ json[:files] = {}
123
+
124
+ files.each_pair do |(name, content)|
125
+ if content.to_s.strip == ""
126
+ raise "Cannot gist empty files" unless options[:skip_empty]
127
+ else
128
+ name = name == "-" ? default_filename : File.basename(name)
129
+ json[:files][name] = {:content => content}
130
+ end
131
+ end
132
+
133
+ return if json[:files].empty? && options[:skip_empty]
134
+
135
+ existing_gist = options[:update].to_s.split("/").last
136
+
137
+ url = "#{base_path}/gists"
138
+ url << "/" << CGI.escape(existing_gist) if existing_gist.to_s != ''
139
+
140
+ request = Net::HTTP::Post.new(url)
141
+ request['Authorization'] = "token #{access_token}" if access_token.to_s != ''
142
+ request.body = JSON.dump(json)
143
+ request.content_type = 'application/json'
144
+
145
+ retried = false
146
+
147
+ begin
148
+ response = http(api_url, request)
149
+ if Net::HTTPSuccess === response
150
+ on_success(response.body, options)
151
+ else
152
+ raise "Got #{response.class} from gist: #{response.body}"
153
+ end
154
+ rescue => e
155
+ raise if retried
156
+ retried = true
157
+ retry
158
+ end
159
+
160
+ rescue => e
161
+ raise e.extend Error
162
+ end
163
+
164
+ # List all gists(private also) for authenticated user
165
+ # otherwise list public gists for given username (optional argument)
166
+ #
167
+ # @param [String] user
168
+ # @deprecated
169
+ #
170
+ # see https://developer.github.com/v3/gists/#list-gists
171
+ def list_gists(user = "")
172
+ url = "#{base_path}"
173
+
174
+ if user == ""
175
+ access_token = auth_token()
176
+ if access_token.to_s != ''
177
+ url << "/gists"
178
+
179
+ request = Net::HTTP::Get.new(url)
180
+ request['Authorization'] = "token #{access_token}"
181
+ response = http(api_url, request)
182
+
183
+ pretty_gist(response)
184
+
185
+ else
186
+ raise Error, "Not authenticated. Use 'gist --login' to login or 'gist -l username' to view public gists."
187
+ end
188
+
189
+ else
190
+ url << "/users/#{user}/gists"
191
+
192
+ request = Net::HTTP::Get.new(url)
193
+ response = http(api_url, request)
194
+
195
+ pretty_gist(response)
196
+ end
197
+ end
198
+
199
+ def list_all_gists(user = "")
200
+ url = "#{base_path}"
201
+
202
+ if user == ""
203
+ access_token = auth_token()
204
+ if access_token.to_s != ''
205
+ url << "/gists?per_page=100"
206
+ get_gist_pages(url, access_token)
207
+ else
208
+ raise Error, "Not authenticated. Use 'gist --login' to login or 'gist -l username' to view public gists."
209
+ end
210
+
211
+ else
212
+ url << "/users/#{user}/gists?per_page=100"
213
+ get_gist_pages(url)
214
+ end
215
+
216
+ end
217
+
218
+ def gist_exists?(id)
219
+ url = "#{base_path}/gists/#{id}"
220
+ access_token = auth_token()
221
+ request = Net::HTTP::Get.new(url)
222
+
223
+ request['Authorization'] = "token #{access_token}" if access_token.to_s != ''
224
+ response = http(api_url, request)
225
+
226
+ response.code == 200
227
+ end
228
+
229
+ def read_gist(id, file_name=nil)
230
+ url = "#{base_path}/gists/#{id}"
231
+
232
+ access_token = auth_token()
233
+
234
+ request = Net::HTTP::Get.new(url)
235
+ request['Authorization'] = "token #{access_token}" if access_token.to_s != ''
236
+ response = http(api_url, request)
237
+
238
+ if response.code == '200'
239
+ body = JSON.parse(response.body)
240
+ files = body["files"]
241
+
242
+ if file_name
243
+ file = files[file_name]
244
+ raise Error, "Gist with id of #{id} and file #{file_name} does not exist." unless file
245
+ else
246
+ file = files.values.first
247
+ end
248
+
249
+ puts file["content"]
250
+ else
251
+ raise Error, "Gist with id of #{id} does not exist."
252
+ end
253
+ end
254
+
255
+ def delete_gist(id)
256
+ id = id.split("/").last
257
+ url = "#{base_path}/gists/#{id}"
258
+
259
+ access_token = auth_token()
260
+ if access_token.to_s != ''
261
+ request = Net::HTTP::Delete.new(url)
262
+ request["Authorization"] = "token #{access_token}"
263
+ response = http(api_url, request)
264
+ else
265
+ raise Error, "Not authenticated. Use 'gist --login' to login."
266
+ end
267
+
268
+ if response.code == '204'
269
+ puts "Deleted!"
270
+ else
271
+ raise Error, "Gist with id of #{id} does not exist."
272
+ end
273
+ end
274
+
275
+ def get_gist_pages(url, access_token = "")
276
+
277
+ request = Net::HTTP::Get.new(url)
278
+ request['Authorization'] = "token #{access_token}" if access_token.to_s != ''
279
+ response = http(api_url, request)
280
+ pretty_gist(response)
281
+
282
+ link_header = response.header['link']
283
+
284
+ if link_header
285
+ links = Hash[ link_header.gsub(/(<|>|")/, "").split(',').map { |link| link.split('; rel=') } ].invert
286
+ get_gist_pages(links['next'], access_token) if links['next']
287
+ end
288
+
289
+ end
290
+
291
+ # return prettified string result of response body for all gists
292
+ #
293
+ # @params [Net::HTTPResponse] response
294
+ # @return [String] prettified result of listing all gists
295
+ #
296
+ # see https://developer.github.com/v3/gists/#response
297
+ def pretty_gist(response)
298
+ body = JSON.parse(response.body)
299
+ if response.code == '200'
300
+ body.each do |gist|
301
+ description = "#{gist['description'] || gist['files'].keys.join(" ")} #{gist['public'] ? '' : '(secret)'}"
302
+ puts "#{gist['html_url']} #{description.tr("\n", " ")}\n"
303
+ $stdout.flush
304
+ end
305
+
306
+ else
307
+ raise Error, body['message']
308
+ end
309
+ end
310
+
311
+ # Convert long github urls into short git.io ones
312
+ #
313
+ # @param [String] url
314
+ # @return [String] shortened url, or long url if shortening fails
315
+ def shorten(url)
316
+ request = Net::HTTP::Post.new("/create")
317
+ request.set_form_data(:url => url)
318
+ response = http(GIT_IO_URL, request)
319
+ case response.code
320
+ when "200"
321
+ URI.join(GIT_IO_URL, response.body).to_s
322
+ when "201"
323
+ response['Location']
324
+ else
325
+ url
326
+ end
327
+ end
328
+
329
+ # Convert github url into raw file url
330
+ #
331
+ # Unfortunately the url returns from github's api is legacy,
332
+ # we have to taking a HTTPRedirection before appending it
333
+ # with '/raw'. Let's looking forward for github's api fix :)
334
+ #
335
+ # @param [String] url
336
+ # @return [String] the raw file url
337
+ def rawify(url)
338
+ uri = URI(url)
339
+ request = Net::HTTP::Get.new(uri.path)
340
+ response = http(uri, request)
341
+ if Net::HTTPSuccess === response
342
+ url + '/raw'
343
+ elsif Net::HTTPRedirection === response
344
+ rawify(response.header['location'])
345
+ end
346
+ end
347
+
348
+ # Log the user into gist.
349
+ #
350
+ # This method asks the user for a username and password, and tries to obtain
351
+ # and OAuth2 access token, which is then stored in ~/.gist
352
+ #
353
+ # @raise [Gist::Error] if something went wrong
354
+ # @param [Hash] credentials login details
355
+ # @option credentials [String] :username
356
+ # @option credentials [String] :password
357
+ # @see http://developer.github.com/v3/oauth/
358
+ def login!(credentials={})
359
+ puts "Obtaining OAuth2 access_token from GitHub."
360
+ loop do
361
+ print "GitHub username: "
362
+ username = credentials[:username] || $stdin.gets.strip
363
+ print "GitHub password: "
364
+ password = credentials[:password] || begin
365
+ `stty -echo` rescue nil
366
+ $stdin.gets.strip
367
+ ensure
368
+ `stty echo` rescue nil
369
+ end
370
+ puts ""
371
+
372
+ request = Net::HTTP::Post.new("#{base_path}/authorizations")
373
+ request.body = JSON.dump({
374
+ :scopes => [:gist],
375
+ :note => "The gist gem (#{Time.now})",
376
+ :note_url => "https://github.com/ConradIrwin/gist"
377
+ })
378
+ request.content_type = 'application/json'
379
+ request.basic_auth(username, password)
380
+
381
+ response = http(api_url, request)
382
+
383
+ if Net::HTTPUnauthorized === response && response['X-GitHub-OTP']
384
+ print "2-factor auth code: "
385
+ twofa_code = $stdin.gets.strip
386
+ puts ""
387
+
388
+ request['X-GitHub-OTP'] = twofa_code
389
+ response = http(api_url, request)
390
+ end
391
+
392
+ if Net::HTTPCreated === response
393
+ AuthTokenFile.write JSON.parse(response.body)['token']
394
+ puts "Success! #{ENV[URL_ENV_NAME] || "https://github.com/"}settings/tokens"
395
+ return
396
+ elsif Net::HTTPUnauthorized === response
397
+ puts "Error: #{JSON.parse(response.body)['message']}"
398
+ next
399
+ else
400
+ raise "Got #{response.class} from gist: #{response.body}"
401
+ end
402
+ end
403
+ rescue => e
404
+ raise e.extend Error
405
+ end
406
+
407
+ # Return HTTP connection
408
+ #
409
+ # @param [URI::HTTP] The URI to which to connect
410
+ # @return [Net::HTTP]
411
+ def http_connection(uri)
412
+ env = ENV['http_proxy'] || ENV['HTTP_PROXY']
413
+ connection = if env
414
+ proxy = URI(env)
415
+ Net::HTTP::Proxy(proxy.host, proxy.port).new(uri.host, uri.port)
416
+ else
417
+ Net::HTTP.new(uri.host, uri.port)
418
+ end
419
+ if uri.scheme == "https"
420
+ connection.use_ssl = true
421
+ connection.verify_mode = OpenSSL::SSL::VERIFY_NONE
422
+ end
423
+ connection.open_timeout = 10
424
+ connection.read_timeout = 10
425
+ connection
426
+ end
427
+
428
+ # Run an HTTP operation
429
+ #
430
+ # @param [URI::HTTP] The URI to which to connect
431
+ # @param [Net::HTTPRequest] The request to make
432
+ # @return [Net::HTTPResponse]
433
+ def http(url, request)
434
+ request['User-Agent'] = USER_AGENT
435
+
436
+ http_connection(url).start do |http|
437
+ http.request request
438
+ end
439
+ rescue Timeout::Error
440
+ raise "Could not connect to #{api_url}"
441
+ end
442
+
443
+ # Called after an HTTP response to gist to perform post-processing.
444
+ #
445
+ # @param [String] body the text body from the github api
446
+ # @param [Hash] options more detailed options, see
447
+ # the documentation for {multi_gist}
448
+ def on_success(body, options={})
449
+ json = JSON.parse(body)
450
+
451
+ output = case options[:output]
452
+ when :javascript
453
+ %Q{<script src="#{json['html_url']}.js"></script>}
454
+ when :html_url
455
+ json['html_url']
456
+ when :raw_url
457
+ rawify(json['html_url'])
458
+ when :short_url
459
+ shorten(json['html_url'])
460
+ when :short_raw_url
461
+ shorten(rawify(json['html_url']))
462
+ else
463
+ json
464
+ end
465
+
466
+ Gist.copy(output.to_s) if options[:copy]
467
+ Gist.open(json['html_url']) if options[:open]
468
+
469
+ output
470
+ end
471
+
472
+ # Copy a string to the clipboard.
473
+ #
474
+ # @param [String] content
475
+ # @raise [Gist::Error] if no clipboard integration could be found
476
+ #
477
+ def copy(content)
478
+ IO.popen(clipboard_command(:copy), 'r+') { |clip| clip.print content }
479
+
480
+ unless paste == content
481
+ message = 'Copying to clipboard failed.'
482
+
483
+ if ENV["TMUX"] && clipboard_command(:copy) == 'pbcopy'
484
+ message << "\nIf you're running tmux on a mac, try http://robots.thoughtbot.com/post/19398560514/how-to-copy-and-paste-with-tmux-on-mac-os-x"
485
+ end
486
+
487
+ raise Error, message
488
+ end
489
+ rescue Error => e
490
+ raise ClipboardError, e.message + "\nAttempted to copy: #{content}"
491
+ end
492
+
493
+ # Get a string from the clipboard.
494
+ #
495
+ # @param [String] content
496
+ # @raise [Gist::Error] if no clipboard integration could be found
497
+ def paste
498
+ `#{clipboard_command(:paste)}`
499
+ end
500
+
501
+ # Find command from PATH environment.
502
+ #
503
+ # @param [String] cmd command name to find
504
+ # @param [String] options PATH environment variable
505
+ # @return [String] the command found
506
+ def which(cmd, path=ENV['PATH'])
507
+ if RUBY_PLATFORM.downcase =~ /mswin(?!ce)|mingw|bccwin|cygwin/
508
+ path.split(File::PATH_SEPARATOR).each {|dir|
509
+ f = File.join(dir, cmd+".exe")
510
+ return f if File.executable?(f) && !File.directory?(f)
511
+ }
512
+ nil
513
+ else
514
+ return system("which #{cmd} > /dev/null 2>&1")
515
+ end
516
+ end
517
+
518
+ # Get the command to use for the clipboard action.
519
+ #
520
+ # @param [Symbol] action either :copy or :paste
521
+ # @return [String] the command to run
522
+ # @raise [Gist::ClipboardError] if no clipboard integration could be found
523
+ def clipboard_command(action)
524
+ command = CLIPBOARD_COMMANDS.keys.detect do |cmd|
525
+ which cmd
526
+ end
527
+ raise ClipboardError, <<-EOT unless command
528
+ Could not find copy command, tried:
529
+ #{CLIPBOARD_COMMANDS.values.join(' || ')}
530
+ EOT
531
+ action == :copy ? command : CLIPBOARD_COMMANDS[command]
532
+ end
533
+
534
+ # Open a URL in a browser.
535
+ #
536
+ # @param [String] url
537
+ # @raise [RuntimeError] if no browser integration could be found
538
+ #
539
+ # This method was heavily inspired by defunkt's Gist#open,
540
+ # @see https://github.com/defunkt/gist/blob/bca9b29/lib/gist.rb#L157
541
+ def open(url)
542
+ command = if ENV['BROWSER']
543
+ ENV['BROWSER']
544
+ elsif RUBY_PLATFORM =~ /darwin/
545
+ 'open'
546
+ elsif RUBY_PLATFORM =~ /linux/
547
+ %w(
548
+ sensible-browser
549
+ xdg-open
550
+ firefox
551
+ firefox-bin
552
+ ).detect do |cmd|
553
+ which cmd
554
+ end
555
+ elsif ENV['OS'] == 'Windows_NT' || RUBY_PLATFORM =~ /djgpp|(cyg|ms|bcc)win|mingw|wince/i
556
+ 'start ""'
557
+ else
558
+ raise "Could not work out how to use a browser."
559
+ end
560
+
561
+ `#{command} #{url}`
562
+ end
563
+
564
+ # Get the API base path
565
+ def base_path
566
+ ENV.key?(URL_ENV_NAME) ? GHE_BASE_PATH : GITHUB_BASE_PATH
567
+ end
568
+
569
+ # Get the API URL
570
+ def api_url
571
+ ENV.key?(URL_ENV_NAME) ? URI(ENV[URL_ENV_NAME]) : GITHUB_API_URL
572
+ end
573
+
574
+ def legacy_private_gister?
575
+ return unless which('git')
576
+ `git config --global gist.private` =~ /\Ayes|1|true|on\z/i
577
+ end
578
+
579
+ def should_be_public?(options={})
580
+ if options.key? :private
581
+ !options[:private]
582
+ else
583
+ !Gist.legacy_private_gister?
584
+ end
585
+ end
586
+ end