Last active
December 16, 2016 00:31
-
-
Save nixpulvis/87c542cd6d8aac1b8ed094ed7a886edf to your computer and use it in GitHub Desktop.
CLIs with subcommands that don't suck.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# NOTE: This is a WIP, please pardon our dust. | |
# | |
# Example: | |
# | |
# git --namespace=foobar clone https://github.com/nixpulvis/seali | |
# #<Git @args=[], @flags={namespace: "foobar"}, @sub=#<Clone @args=["https://github.com/nixpulvis/seali"], @flags=[], @sub=nil>> | |
class Seali | |
class << self | |
attr_accessor :subs | |
attr_accessor :cmd_func | |
attr_accessor :flg_funcs | |
def cmd(&block) | |
self.cmd_func = block | |
end | |
def flg(short, long = nil, argument = nil, &block) | |
self.flg_funcs[name] = block | |
end | |
def sub(name, cli) | |
self.subs[name.to_s] = cli | |
end | |
def inherited(subclass) | |
subclass.cmd_func = Proc.new { p "???" } | |
subclass.flg_funcs = {} | |
subclass.subs = {} | |
end | |
end | |
def initialize(args) | |
@args = [] | |
@flags = {} | |
parse(args[0], args[1..-1]) | |
end | |
def parse(first, rest) | |
return if first.nil? | |
if self.class.subs[first] | |
@sub = self.class.subs[first].new(rest) | |
return | |
end | |
if first.start_with?('-') | |
@flags[first] = nil # TODO: Parse the value if there is one. All flags with values MUST use an `=`. | |
else | |
@args << first | |
end | |
parse(rest[0], rest[1..-1]) | |
end | |
def run(&block) | |
self.class.flg_funcs.each do |name, func| | |
func.call | |
end | |
if @sub | |
@sub.run | |
else | |
self.instance_eval(&self.class.cmd_func) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment