rework how the usage help is handled

Michael Muré created

Change summary

git-bug.go | 60 +++++++++++++++++++++++++++++++------------------------
1 file changed, 34 insertions(+), 26 deletions(-)

Detailed changes

git-bug.go 🔗

@@ -2,13 +2,14 @@ package main
 
 import (
 	"fmt"
+	"github.com/MichaelMure/git-bug/commands"
+	"github.com/MichaelMure/git-bug/repository"
 	"os"
 	"sort"
 	"strings"
-	"github.com/MichaelMure/git-bug/repository"
-	"github.com/MichaelMure/git-bug/commands"
 )
 
+const rootCommandName = "git bug"
 const usageMessageTemplate = `Usage: %s <command>
 
 Where <command> is one of:
@@ -18,35 +19,46 @@ For individual command usage, run:
   %s help <command>
 `
 
-func usage() {
-	command := os.Args[0]
+func rootUsage() {
 	var subcommands []string
 	for subcommand := range commands.CommandMap {
 		subcommands = append(subcommands, subcommand)
 	}
 	sort.Strings(subcommands)
-	fmt.Printf(usageMessageTemplate, command, strings.Join(subcommands, "\n  "), command)
+	fmt.Printf(usageMessageTemplate, rootCommandName, strings.Join(subcommands, "\n  "), rootCommandName)
 }
 
-func help() {
-	if len(os.Args) < 3 {
-		usage()
-		return
-	}
-	subcommand, ok := commands.CommandMap[os.Args[2]]
+func help(command string) {
+	subcommand, ok := commands.CommandMap[command]
 	if !ok {
-		fmt.Printf("Unknown command %q\n", os.Args[2])
-		usage()
+		fmt.Printf("Unknown command %q\n", command)
+		rootUsage()
 		return
 	}
-	subcommand.Usage(os.Args[0])
+	subcommand.Usage(rootCommandName)
 }
 
 func main() {
-	if len(os.Args) > 1 && os.Args[1] == "help" {
-		help()
+	args := os.Args
+
+	// git bug
+	if len(args) == 1 {
+		fmt.Println("Not implemented")
+		//TODO: list bugs
 		return
 	}
+
+	if args[1] == "help" {
+		if len(args) == 2 {
+			// git bug help
+			rootUsage()
+		} else {
+			// git bug help <command>
+			help(args[2])
+		}
+		return
+	}
+
 	cwd, err := os.Getwd()
 	if err != nil {
 		fmt.Printf("Unable to get the current working directory: %q\n", err)
@@ -54,21 +66,17 @@ func main() {
 	}
 	repo, err := repository.NewGitRepo(cwd)
 	if err != nil {
-		fmt.Printf("%s must be run from within a git repo.\n", os.Args[0])
+		fmt.Printf("%s must be run from within a git repo.\n", rootCommandName)
 		return
 	}
-	if len(os.Args) < 2 {
-		// default behavior
-		fmt.Println("Not implemented")
-		return
-	}
-	subcommand, ok := commands.CommandMap[os.Args[1]]
+
+	subcommand, ok := commands.CommandMap[args[1]]
 	if !ok {
-		fmt.Printf("Unknown command: %q\n", os.Args[1])
-		usage()
+		fmt.Printf("Unknown command: %q\n", args[1])
+		rootUsage()
 		return
 	}
-	if err := subcommand.Run(repo, os.Args[2:]); err != nil {
+	if err := subcommand.Run(repo, args[2:]); err != nil {
 		fmt.Println(err.Error())
 		os.Exit(1)
 	}