git-bug.go

 1package main
 2
 3import (
 4	"fmt"
 5	"github.com/MichaelMure/git-bug/commands"
 6	"github.com/MichaelMure/git-bug/repository"
 7	"os"
 8	"sort"
 9	"strings"
10)
11
12const rootCommandName = "git bug"
13const usageMessageTemplate = `Usage: %s <command>
14
15Where <command> is one of:
16  %s
17
18For individual command usage, run:
19  %s help <command>
20`
21
22func rootUsage() {
23	var subcommands []string
24	for subcommand := range commands.CommandMap {
25		subcommands = append(subcommands, subcommand)
26	}
27	sort.Strings(subcommands)
28	fmt.Printf(usageMessageTemplate, rootCommandName, strings.Join(subcommands, "\n  "), rootCommandName)
29}
30
31func help(command string) {
32	subcommand, ok := commands.CommandMap[command]
33	if !ok {
34		fmt.Printf("Unknown command %q\n", command)
35		rootUsage()
36		return
37	}
38	subcommand.Usage(rootCommandName)
39}
40
41func main() {
42	args := os.Args
43
44	// git bug
45	if len(args) == 1 {
46		fmt.Println("Will list bugs, not implemented yet")
47		//TODO: list bugs
48		return
49	}
50
51	if args[1] == "help" {
52		if len(args) == 2 {
53			// git bug help
54			rootUsage()
55		} else {
56			// git bug help <command>
57			help(args[2])
58		}
59		return
60	}
61
62	cwd, err := os.Getwd()
63	if err != nil {
64		fmt.Printf("Unable to get the current working directory: %q\n", err)
65		return
66	}
67	repo, err := repository.NewGitRepo(cwd)
68	if err != nil {
69		fmt.Printf("%s must be run from within a git repo.\n", rootCommandName)
70		return
71	}
72
73	subcommand, ok := commands.CommandMap[args[1]]
74	if !ok {
75		fmt.Printf("Unknown command: %q\n", args[1])
76		rootUsage()
77		return
78	}
79	if err := subcommand.Run(repo, args[2:]); err != nil {
80		fmt.Println(err.Error())
81		os.Exit(1)
82	}
83}