Module: Gist

Extended by:
Gist
Included in:
Gist
Defined in:
lib/gist.rb

Overview

It just gists.

Defined Under Namespace

Modules: AuthTokenFile, Error Classes: ClipboardError

Constant Summary collapse

VERSION =
'6.0.0'
CLIPBOARD_COMMANDS =

A list of clipboard commands with copy and paste support.

{
  'pbcopy'  => 'pbpaste',
  'xclip'   => 'xclip -o',
  'xsel -i' => 'xsel -o',
  'putclip' => 'getclip',
}
GITHUB_API_URL =
URI("https://api.github.com/")
GITHUB_URL =
URI("https://github.com/")
GIT_IO_URL =
URI("https://git.io")
GITHUB_BASE_PATH =
""
GHE_BASE_PATH =
"/api/v3"
GITHUB_CLIENT_ID =
'4f7ec0d4eab38e74384e'
URL_ENV_NAME =
"GITHUB_URL"
CLIENT_ID_ENV_NAME =
"GIST_CLIENT_ID"
USER_AGENT =
"gist/#{VERSION} (Net::HTTP, #{RUBY_DESCRIPTION})"

Instance Method Summary collapse

Instance Method Details

#access_token_login!(credentials = {}) ⇒ Object

Logs the user into gist.

This method asks the user for a username and password, and tries to obtain and OAuth2 access token, which is then stored in ~/.gist

Raises:

See Also:



400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
# File 'lib/gist.rb', line 400

def access_token_login!(credentials={})
  puts "Obtaining OAuth2 access_token from GitHub."
  loop do
    print "GitHub username: "
    username = credentials[:username] || $stdin.gets.strip
    print "GitHub password: "
    password = credentials[:password] || begin
      `stty -echo` rescue nil
      $stdin.gets.strip
    ensure
      `stty echo` rescue nil
    end
    puts ""

    request = Net::HTTP::Post.new("#{base_path}/authorizations")
    request.body = JSON.dump({
      :scopes => [:gist],
      :note => "The gist gem (#{Time.now})",
      :note_url => "https://github.com/ConradIrwin/gist"
    })
    request.content_type = 'application/json'
    request.basic_auth(username, password)

    response = http(api_url, request)

    if Net::HTTPUnauthorized === response && response['X-GitHub-OTP']
      print "2-factor auth code: "
      twofa_code = $stdin.gets.strip
      puts ""

      request['X-GitHub-OTP'] = twofa_code
      response = http(api_url, request)
    end

    if Net::HTTPCreated === response
      AuthTokenFile.write JSON.parse(response.body)['token']
      puts "Success! #{ENV[URL_ENV_NAME] || "https://github.com/"}settings/tokens"
      return
    elsif Net::HTTPUnauthorized === response
      puts "Error: #{JSON.parse(response.body)['message']}"
      next
    else
      raise "Got #{response.class} from gist: #{response.body}"
    end
  end
rescue => e
  raise e.extend Error
end

#api_urlObject

Get the API URL



620
621
622
# File 'lib/gist.rb', line 620

def api_url
  ENV.key?(URL_ENV_NAME) ? URI(ENV[URL_ENV_NAME]) : GITHUB_API_URL
end

#auth_tokenString

auth token for authentication

Returns:

  • (String)

    string value of access token or ‘nil`, if not found



71
72
73
# File 'lib/gist.rb', line 71

def auth_token
  @token ||= AuthTokenFile.read rescue nil
end

#base_pathObject

Get the API base path



611
612
613
# File 'lib/gist.rb', line 611

def base_path
  ENV.key?(URL_ENV_NAME) ? GHE_BASE_PATH : GITHUB_BASE_PATH
end

#client_idObject



624
625
626
# File 'lib/gist.rb', line 624

def client_id
  ENV.key?(CLIENT_ID_ENV_NAME) ? URI(ENV[CLIENT_ID_ENV_NAME]) : GITHUB_CLIENT_ID
end

#clipboard_command(action) ⇒ String

Get the command to use for the clipboard action.

Parameters:

  • action (Symbol)

    either :copy or :paste

Returns:

  • (String)

    the command to run

Raises:



569
570
571
572
573
574
575
576
577
578
# File 'lib/gist.rb', line 569

def clipboard_command(action)
  command = CLIPBOARD_COMMANDS.keys.detect do |cmd|
    which cmd
  end
  raise ClipboardError, <<-EOT unless command
Could not find copy command, tried:
  #{CLIPBOARD_COMMANDS.values.join(' || ')}
  EOT
  action == :copy ? command : CLIPBOARD_COMMANDS[command]
end

#copy(content) ⇒ Object

Copy a string to the clipboard.

Parameters:

  • content (String)

Raises:

  • (Gist::Error)

    if no clipboard integration could be found



523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
# File 'lib/gist.rb', line 523

def copy(content)
  IO.popen(clipboard_command(:copy), 'r+') { |clip| clip.print content }

  unless paste == content
    message = 'Copying to clipboard failed.'

    if ENV["TMUX"] && clipboard_command(:copy) == 'pbcopy'
      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"
    end

    raise Error, message
  end
rescue Error => e
  raise ClipboardError, e.message + "\nAttempted to copy: #{content}"
end

#default_filenameObject



87
88
89
# File 'lib/gist.rb', line 87

def default_filename
  "gistfile1.txt"
end

#delete_gist(id) ⇒ Object



241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'lib/gist.rb', line 241

def delete_gist(id)
  id = id.split("/").last
  url = "#{base_path}/gists/#{id}"

  access_token = auth_token()
  if access_token.to_s != ''
    request = Net::HTTP::Delete.new(url)
    request["Authorization"] = "token #{access_token}"
    response = http(api_url, request)
  else
    raise Error, "Not authenticated. Use 'gist --login' to login."
  end

  if response.code == '204'
    puts "Deleted!"
  else
    raise Error, "Gist with id of #{id} does not exist."
  end
end

#device_flow_login!Object



344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
# File 'lib/gist.rb', line 344

def device_flow_login!
  puts "Requesting login parameters..."
  request = Net::HTTP::Post.new("/login/device/code")
  request.body = JSON.dump({
    :scope => 'gist',
    :client_id => client_id,
  })
  request.content_type = 'application/json'
  request['accept'] = "application/json"
  response = http(, request)

  if response.code != '200'
    raise Error, "HTTP #{response.code}: #{response.body}"
  end

  body = JSON.parse(response.body)

  puts "Please sign in at #{body['verification_uri']}"
  puts "  and enter code: #{body['user_code']}"
  device_code = body['device_code']
  interval = body['interval']

  loop do
    sleep(interval.to_i)
    request = Net::HTTP::Post.new("/login/oauth/access_token")
    request.body = JSON.dump({
      :client_id => client_id,
      :grant_type => 'urn:ietf:params:oauth:grant-type:device_code',
      :device_code => device_code
    })
    request.content_type = 'application/json'
    request['Accept'] = 'application/json'
    response = http(, request)
    if response.code != '200'
      raise Error, "HTTP #{response.code}: #{response.body}"
    end
    body = JSON.parse(response.body)
    break unless body['error'] == 'authorization_pending'
  end

  if body['error']
    raise Error, body['error_description']
  end

  AuthTokenFile.write JSON.parse(response.body)['access_token']

  puts "Success! #{ENV[URL_ENV_NAME] || "https://github.com/"}settings/connections/applications/#{client_id}"
end

#get_gist_pages(url, access_token = "") ⇒ Object



261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
# File 'lib/gist.rb', line 261

def get_gist_pages(url, access_token = "")

  request = Net::HTTP::Get.new(url)
  request['Authorization'] = "token #{access_token}" if access_token.to_s != ''
  response = http(api_url, request)
  pretty_gist(response)

  link_header = response.header['link']

  if link_header
    links = Hash[ link_header.gsub(/(<|>|")/, "").split(',').map { |link| link.split('; rel=') } ].invert
    get_gist_pages(links['next'], access_token) if links['next']
  end

end

#gist(content, options = {}) ⇒ Object

Upload a gist to gist.github.com

Parameters:

  • content (String)

    the code you’d like to gist

  • options (Hash) (defaults to: {})

    more detailed options, see the documentation for #multi_gist

See Also:



82
83
84
85
# File 'lib/gist.rb', line 82

def gist(content, options = {})
  filename = options[:filename] || default_filename
  multi_gist({filename => content}, options)
end

#http(url, request) ⇒ Net::HTTPResponse

Run an HTTP operation

Parameters:

  • The (URI::HTTP)

    URI to which to connect

  • The (Net::HTTPRequest)

    request to make

Returns:

  • (Net::HTTPResponse)


479
480
481
482
483
484
485
486
487
# File 'lib/gist.rb', line 479

def http(url, request)
  request['User-Agent'] = USER_AGENT

  http_connection(url).start do |http|
    http.request request
  end
rescue Timeout::Error
  raise "Could not connect to #{api_url}"
end

#http_connection(uri) ⇒ Net::HTTP

Return HTTP connection

Parameters:

  • The (URI::HTTP)

    URI to which to connect

Returns:

  • (Net::HTTP)


453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
# File 'lib/gist.rb', line 453

def http_connection(uri)
  env = ENV['http_proxy'] || ENV['HTTP_PROXY']
  connection = if env
                 proxy = URI(env)
                 if proxy.user
                   Net::HTTP::Proxy(proxy.host, proxy.port, proxy.user, proxy.password).new(uri.host, uri.port)
                 else
                   Net::HTTP::Proxy(proxy.host, proxy.port).new(uri.host, uri.port)
                 end
               else
                 Net::HTTP.new(uri.host, uri.port)
               end
  if uri.scheme == "https"
    connection.use_ssl = true
    connection.verify_mode = OpenSSL::SSL::VERIFY_NONE
  end
  connection.open_timeout = 10
  connection.read_timeout = 10
  connection
end

#legacy_private_gister?Boolean

Returns:

  • (Boolean)


628
629
630
631
# File 'lib/gist.rb', line 628

def legacy_private_gister?
  return unless which('git')
  `git config --global gist.private` =~ /\Ayes|1|true|on\z/i
end

#list_all_gists(user = "") ⇒ Object



203
204
205
206
207
208
209
210
211
212
213
# File 'lib/gist.rb', line 203

def list_all_gists(user = "")
  url = "#{base_path}"

  if user == ""
    url << "/gists?per_page=100"
  else
    url << "/users/#{user}/gists?per_page=100"
  end

  get_gist_pages(url, auth_token())
end

#list_gists(user = "") ⇒ Object

Deprecated.

List all gists(private also) for authenticated user otherwise list public gists for given username (optional argument)

see developer.github.com/v3/gists/#list-gists

Parameters:

  • user (String) (defaults to: "")


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
# File 'lib/gist.rb', line 175

def list_gists(user = "")
  url = "#{base_path}"

  if user == ""
    access_token = auth_token()
    if access_token.to_s != ''
      url << "/gists"

      request = Net::HTTP::Get.new(url)
      request['Authorization'] = "token #{access_token}"
      response = http(api_url, request)

      pretty_gist(response)

    else
      raise Error, "Not authenticated. Use 'gist --login' to login or 'gist -l username' to view public gists."
    end

  else
    url << "/users/#{user}/gists"

    request = Net::HTTP::Get.new(url)
    response = http(api_url, request)

    pretty_gist(response)
  end
end

#login!(credentials = {}) ⇒ Object

Log the user into gist.



336
337
338
339
340
341
342
# File 'lib/gist.rb', line 336

def login!(credentials={})
  if ( == GITHUB_URL || ENV.key?(CLIENT_ID_ENV_NAME)) && credentials.empty? && !ENV.key?('GIST_USE_USERNAME_AND_PASSWORD')
    device_flow_login!
  else
    access_token_login!(credentials)
  end
end

#login_urlObject



615
616
617
# File 'lib/gist.rb', line 615

def 
  ENV.key?(URL_ENV_NAME) ? URI(ENV[URL_ENV_NAME]) : GITHUB_URL
end

#multi_gist(files, options = {}) ⇒ String, Hash

Upload a gist to gist.github.com

Parameters:

  • files (Hash)

    the code you’d like to gist: filename => content

  • options (Hash) (defaults to: {})

    more detailed options

Options Hash (options):

  • :description (String)

    the description

  • :public (Boolean) — default: false

    is this gist public

  • :anonymous (Boolean) — default: false

    is this gist anonymous

  • :access_token (String) — default: `File.read("~/.gist")`

    The OAuth2 access token.

  • :update (String)

    the URL or id of a gist to update

  • :copy (Boolean) — default: false

    Copy resulting URL to clipboard, if successful.

  • :open (Boolean) — default: false

    Open the resulting URL in a browser.

  • :skip_empty (Boolean) — default: false

    Skip gisting empty files.

  • :output (Symbol) — default: :all

    The type of return value you’d like: :html_url gives a String containing the url to the gist in a browser :short_url gives a String contianing a git.io url that redirects to html_url :javascript gives a String containing a script tag suitable for embedding the gist :all gives a Hash containing the parsed json response from the server

Returns:

  • (String, Hash)

    the return value as configured by options

Raises:

See Also:



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
# File 'lib/gist.rb', line 114

def multi_gist(files, options={})
  if options[:anonymous]
    raise 'Anonymous gists are no longer supported. Please log in with `gist --login`. ' \
      '(GitHub now requires credentials to gist https://bit.ly/2GBBxKw)'
  else
    access_token = (options[:access_token] || auth_token())
  end

  json = {}

  json[:description] = options[:description] if options[:description]
  json[:public] = !!options[:public]
  json[:files] = {}

  files.each_pair do |(name, content)|
    if content.to_s.strip == ""
      raise "Cannot gist empty files" unless options[:skip_empty]
    else
      name = name == "-" ? default_filename : File.basename(name)
      json[:files][name] = {:content => content}
    end
  end

  return if json[:files].empty? && options[:skip_empty]

  existing_gist = options[:update].to_s.split("/").last

  url = "#{base_path}/gists"
  url << "/" << CGI.escape(existing_gist) if existing_gist.to_s != ''

  request = Net::HTTP::Post.new(url)
  request['Authorization'] = "token #{access_token}" if access_token.to_s != ''
  request.body = JSON.dump(json)
  request.content_type = 'application/json'

  retried = false

  begin
    response = http(api_url, request)
    if Net::HTTPSuccess === response
      on_success(response.body, options)
    else
      raise "Got #{response.class} from gist: #{response.body}"
    end
  rescue => e
    raise if retried
    retried = true
    retry
  end

rescue => e
  raise e.extend Error
end

#on_success(body, options = {}) ⇒ Object

Called after an HTTP response to gist to perform post-processing.

Parameters:

  • body (String)

    the text body from the github api

  • options (Hash) (defaults to: {})

    more detailed options, see the documentation for #multi_gist



494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
# File 'lib/gist.rb', line 494

def on_success(body, options={})
  json = JSON.parse(body)

  output = case options[:output]
           when :javascript
             %Q{<script src="#{json['html_url']}.js"></script>}
           when :html_url
             json['html_url']
           when :raw_url
             rawify(json['html_url'])
           when :short_url
             shorten(json['html_url'])
           when :short_raw_url
             shorten(rawify(json['html_url']))
           else
             json
           end

  Gist.copy(output.to_s) if options[:copy]
  Gist.open(json['html_url']) if options[:open]

  output
end

#open(url) ⇒ Object

Open a URL in a browser.

This method was heavily inspired by defunkt’s Gist#open,

Parameters:

  • url (String)

Raises:

  • (RuntimeError)

    if no browser integration could be found

See Also:



587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
# File 'lib/gist.rb', line 587

def open(url)
  command = if ENV['BROWSER']
              ENV['BROWSER']
            elsif RUBY_PLATFORM =~ /darwin/
              'open'
            elsif RUBY_PLATFORM =~ /linux/
              %w(
                sensible-browser
                xdg-open
                firefox
                firefox-bin
              ).detect do |cmd|
                which cmd
              end
            elsif ENV['OS'] == 'Windows_NT' || RUBY_PLATFORM =~ /djgpp|(cyg|ms|bcc)win|mingw|wince/i
              'start ""'
            else
              raise "Could not work out how to use a browser."
            end

  `#{command} #{url}`
end

#pasteObject

Get a string from the clipboard.

Parameters:

  • content (String)

Raises:

  • (Gist::Error)

    if no clipboard integration could be found



543
544
545
# File 'lib/gist.rb', line 543

def paste
  `#{clipboard_command(:paste)}`
end

#pretty_gist(response) ⇒ String

return prettified string result of response body for all gists

see developer.github.com/v3/gists/#response

Returns:

  • (String)

    prettified result of listing all gists



283
284
285
286
287
288
289
290
291
292
293
294
295
# File 'lib/gist.rb', line 283

def pretty_gist(response)
  body = JSON.parse(response.body)
  if response.code == '200'
    body.each do |gist|
      description = "#{gist['description'] || gist['files'].keys.join(" ")} #{gist['public'] ? '' : '(secret)'}"
      puts "#{gist['html_url']} #{description.tr("\n", " ")}\n"
      $stdout.flush
    end

  else
    raise Error, body['message']
  end
end

#rawify(url) ⇒ String

Convert github url into raw file url

Unfortunately the url returns from github’s api is legacy, we have to taking a HTTPRedirection before appending it with ‘/raw’. Let’s looking forward for github’s api fix :)

Parameters:

  • url (String)

Returns:

  • (String)

    the raw file url



323
324
325
326
327
328
329
330
331
332
# File 'lib/gist.rb', line 323

def rawify(url)
  uri = URI(url)
  request = Net::HTTP::Get.new(uri.path)
  response = http(uri, request)
  if Net::HTTPSuccess === response
    url + '/raw'
  elsif Net::HTTPRedirection === response
    rawify(response.header['location'])
  end
end

#read_gist(id, file_name = nil) ⇒ Object



215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
# File 'lib/gist.rb', line 215

def read_gist(id, file_name=nil)
  url = "#{base_path}/gists/#{id}"

  access_token = auth_token()

  request = Net::HTTP::Get.new(url)
  request['Authorization'] = "token #{access_token}" if access_token.to_s != ''
  response = http(api_url, request)

  if response.code == '200'
    body = JSON.parse(response.body)
    files = body["files"]

    if file_name
      file = files[file_name]
      raise Error, "Gist with id of #{id} and file #{file_name} does not exist." unless file
    else
      file = files.values.first
    end

    puts file["content"]
  else
    raise Error, "Gist with id of #{id} does not exist."
  end
end

#shorten(url) ⇒ String

Convert long github urls into short git.io ones

Parameters:

  • url (String)

Returns:

  • (String)

    shortened url, or long url if shortening fails



301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/gist.rb', line 301

def shorten(url)
  request = Net::HTTP::Post.new("/create")
  request.set_form_data(:url => url)
  response = http(GIT_IO_URL, request)
  case response.code
  when "200"
    URI.join(GIT_IO_URL, response.body).to_s
  when "201"
    response['Location']
  else
    url
  end
end

#should_be_public?(options = {}) ⇒ Boolean

Returns:

  • (Boolean)


633
634
635
636
637
638
639
# File 'lib/gist.rb', line 633

def should_be_public?(options={})
  if options.key? :private
    !options[:private]
  else
    !Gist.legacy_private_gister?
  end
end

#which(cmd, path = ) ⇒ String

Find command from PATH environment.

Parameters:

  • cmd (String)

    command name to find

  • options (String)

    PATH environment variable

Returns:

  • (String)

    the command found



552
553
554
555
556
557
558
559
560
561
562
# File 'lib/gist.rb', line 552

def which(cmd, path=ENV['PATH'])
  if RUBY_PLATFORM.downcase =~ /mswin(?!ce)|mingw|bccwin|cygwin/
    path.split(File::PATH_SEPARATOR).each {|dir|
      f = File.join(dir, cmd+".exe")
      return f if File.executable?(f) && !File.directory?(f)
    }
    nil
  else
    return system("which #{cmd} > /dev/null 2>&1")
  end
end