/
github.rb
127 lines (109 loc) · 2.68 KB
/
github.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
$:.unshift File.dirname(__FILE__)
require 'extensions'
require 'github/command'
require 'github/helper'
require 'rubygems'
require 'launchy'
##
# Starting simple.
#
# $ github <command> <args>
#
# GitHub.register <command> do |*args|
# whatever
# end
#
# We'll probably want to use the `choice` gem for concise, tasty DSL
# arg parsing action.
#
module GitHub
extend self
BasePath = File.expand_path(File.dirname(__FILE__) + '/..')
def command(command, &block)
debug "Registered `#{command}`"
descriptions[command] = @next_description if @next_description
@next_description = nil
flag_descriptions[command].update @next_flags if @next_flags
@next_flags = nil
commands[command.to_s] = Command.new(block)
end
def desc(str)
@next_description = str
end
def flags(hash)
@next_flags ||= {}
@next_flags.update hash
end
def helper(command, &block)
debug "Helper'd `#{command}`"
Helper.send :define_method, command, &block
end
def activate(args)
@options = parse_options(args)
load 'helpers.rb'
load 'commands.rb'
invoke(args.shift, *args)
end
def invoke(command, *args)
block = commands[command.to_s] || commands['default']
debug "Invoking `#{command}`"
block.call(*args)
end
def commands
@commands ||= {}
end
def descriptions
@descriptions ||= {}
end
def flag_descriptions
@flagdescs ||= Hash.new { |h, k| h[k] = {} }
end
def options
@options
end
def parse_options(args)
idx = 0
args.clone.inject({}) do |memo, arg|
case arg
when /^--(.+?)=(.*)/
args.delete_at(idx)
memo.merge($1.to_sym => $2)
when /^--(.+)/
args.delete_at(idx)
memo.merge($1.to_sym => true)
when "--"
args.delete_at(idx)
return memo
else
idx += 1
memo
end
end
end
def load(file)
file[0] == ?/ ? path = file : path = BasePath + "/commands/#{file}"
data = File.read(path)
GitHub.module_eval data, path
end
def debug(*messages)
puts *messages.map { |m| "== #{m}" } if debug?
end
def debug?
!!@debug
end
end
GitHub.command :default do
puts "Usage: github command <space separated arguments>", ''
puts "Available commands:", ''
longest = GitHub.descriptions.map { |d,| d.to_s.size }.max
GitHub.descriptions.each do |command, desc|
cmdstr = "%-#{longest}s" % command
puts " #{cmdstr} => #{desc}"
flongest = GitHub.flag_descriptions[command].map { |d,| "--#{d}".size }.max
GitHub.flag_descriptions[command].each do |flag, fdesc|
flagstr = "#{" " * longest} %-#{flongest}s" % "--#{flag}"
puts " #{flagstr}: #{fdesc}"
end
end
puts
end