Skip to content

Instantly share code, notes, and snippets.

@mzp
Created May 29, 2010 06:41
Show Gist options
  • Save mzp/418091 to your computer and use it in GitHub Desktop.
Save mzp/418091 to your computer and use it in GitHub Desktop.
github util command
#!/usr/bin/env ruby
require 'ostruct'
require 'rubygems'
require 'net/http'
require 'yaml'
require 'pit'
class Hash
def to_url_params
elements = []
keys.size.times do |i|
elements << "#{keys[i]}=#{values[i]}"
end
elements.join('&')
end
end
class User
def initialize
@pit = Pit.get('github',:require => {
'username' => '',
'password' => '',
})
end
def private_url(name)
"git@github.com:#{self.name}/#{name}.git"
end
def name; @pit['username'] end
def password; @pit['password'] end
end
class Github
def initialize(host)
@http = Net::HTTP.new(host)
end
def post(path, params={})
req = Net::HTTP::Post.new "/api/v2/yaml/#{path}"
req.basic_auth $config.user.name, $config.user.password
YAML.load_stream @http.request(req, params.to_url_params).body
end
end
$config = OpenStruct.new({
:github => Github.new('github.com'),
:user => User.new,
})
def git(cmd)
code = "git #{cmd}"
puts code
system(code)
end
class Submodule
def help; "<name> [path]" end
def run(name, path=name)
git "submodule add #{$config.user.private_url(name)} #{path}"
end
end
class Init
def help; "<repos_name>" end
def run(name)
res = $config.github.post("repos/create", :name=>name)
if res[0].key?('error') then
abort "github says '#{res[0]['error']}'"
else
git "init"
git "remote add origin #{$config.user.private_url(name)}"
end
end
end
Commands = {
:submodule => Submodule,
:init => Init
}
if __FILE__ == $0 then
if ARGV.empty? then
puts "usage: #{$0} <cmd>"
exit 0
end
cmd = ARGV.shift.downcase.to_sym
if Commands.key? cmd then
obj = Commands[cmd].new
begin
obj.run(*ARGV)
rescue ArgumentError => e
puts "#{$0} #{cmd} #{obj.help}"
raise e
end
else
abort <<END
I dont know how to '#{cmd}'
END
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment