Skip to content

Instantly share code, notes, and snippets.

@kou1okada kou1okada/gistlist.rb
Last active Feb 5, 2016

Embed
What would you like to do?
List up all gist items.
#!/usr/bin/env ruby
#
# gistlist.rb
# Copyright (c) 2016 Koichi OKADA. All rights reserved.
# This script is distributed under the MIT license.
#
require 'io/console'
require 'json'
require 'open-uri'
require 'optparse'
def error(msg)
STDERR.puts "\e[31;1mError:\e[30;0m #{msg}"
end
def verbose(msg)
STDERR.puts msg if $config[:verbose]
end
http_params = {}
json = ""
$config = {
:cachedir => "/tmp/gistlist",
}
opts = OptionParser.new
opts.banner = "Usage: #{File.basename $0} [options] [github_username ...]"
opts.on("-u", "--http-username USERNAME", "your github username") {|v| $config[:username] = v}
opts.on("-p", "--http-password PASSWORD", "your github password") {|v| $config[:password] = v}
opts.on("-f", "--force" , "force refresh cache" ) {|v| $config[:force] = true}
opts.on("-c", "--cachedir CACHEDIR" , "change cache dir" ) {|v| $config[:cachedir] = v}
opts.on("-v", "--verbose" , "verbose" ) {|v| $config[:verbose] = true}
opts.parse! ARGV
if (!$config[:username] && ARGV.count < 1)
puts opts.help
puts
error "require least one of username or targetuser."
exit 1
end
ARGV.unshift $config[:username] if (ARGV.count < 1)
if ($config[:username] && !$config[:password])
STDERR.print "password: "
$config[:password] = STDIN.noecho(&:gets).chop
puts
end
http_params[:http_basic_authentication] = [ $config[:username], $config[:password] ] if $config[:username]
if (!Dir.exists?($config[:cachedir]))
if (File.exists?($config[:cachedir]))
error "#{$config[:cachedir]} already exists, but it is not a directory."
exit 1
end
Dir.mkdir($config[:cachedir])
end
ARGV.each {|username|
fn = "#{$config[:cachedir]}/#{username}"
base_uri = "https://api.github.com/users/#{username}/gists"
verbose "base_uri: #{base_uri}"
if (!File.exists?(fn) || $config[:force])
page = 1
tmp = ""
sep = "["
begin
uri = "#{base_uri}?page=#{page}"
open(uri, http_params) {|f|
verbose "open: #{uri}"
tmp = f.read
json += sep + tmp unless tmp =~ /^\[[:space]*\]$/
sep = ","
}
page += 1
end until tmp =~ /^\[[:space]*\]$/
json += "]"
open(fn, "w") {|fw|
fw.write json
}
else
open(fn) {|f|
verbose "open: #{fn}"
json = f.read
}
end
sep = nil
gists = JSON.parse(json).flatten(1)
gists.each {|gist|
puts sep = "-" * 40
["public", "description", "html_url"].each {|key|
puts "%-11s: %s" % [key, gist[key]]
}
}
if sep
puts sep
else
verbose "There are no gists."
end
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.