Skip to content

Instantly share code, notes, and snippets.

@kou1okada
Last active November 13, 2022 13:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kou1okada/6680cb2aedb5af890f44 to your computer and use it in GitHub Desktop.
Save kou1okada/6680cb2aedb5af890f44 to your computer and use it in GitHub Desktop.
gistlist.rb - 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}"
URI.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