package main import ( "os" "fmt" "log" "flag" // "strings" // "bufio" db "sanine.net/git/phlox/db" ) var Params struct { InitDb string Db string } var p *db.Phlox type Command struct { Name string Help string subcommands map[string]*Command Branch bool Execute func([]string) } func (c *Command) errNoSubCommand() { fmt.Println("error: a subcommand was required but not provided.") fmt.Println("available options are:\n") for name := range c.subcommands { fmt.Printf("\t* %v\n", name) } fmt.Println() } func (c *Command) Parse(args []string) { if !c.Branch { c.Execute(args) } else { if len(args) > 0 { cn, ok := c.subcommands[args[0]] if ok { cn.Parse(args[1:]) } else { c.errNoSubCommand() } } else { c.errNoSubCommand() } } } func (c *Command) AddCommand(cn *Command) { if c.subcommands == nil { c.subcommands = make(map[string]*Command) } c.subcommands[cn.Name] = cn } var parser *Command func main() { p = &db.Phlox{} flag.StringVar(&Params.InitDb, "init", "", "initialize a new database at the given path") flag.StringVar(&Params.Db, "db", "/etc/phlox/phlox.conf", "open the database at the given path for processing") flag.Parse() if Params.InitDb != "" { // initialize a new db err := p.Create(Params.InitDb) if err != nil { log.Fatal(err) } fmt.Printf("created new database at %v\n", Params.InitDb) p.Close() os.Exit(0) } err := p.Open(Params.Db) if err != nil { log.Fatal(err) } defer p.Close() parser = &Command{Branch: true} ListInit(parser) CreateInit(parser) RmInit(parser) parser.Parse(flag.Args()) }