root.go

 1package commands
 2
 3import (
 4	"fmt"
 5	"os"
 6
 7	"github.com/MichaelMure/git-bug/bug"
 8	"github.com/MichaelMure/git-bug/repository"
 9	"github.com/spf13/cobra"
10)
11
12// Will display "git bug"
13// \u00A0 is a non-breaking space
14// It's used to avoid cobra to split the Use string at the first space to get the root command name
15//const rootCommandName = "git\u00A0bug"
16const rootCommandName = "git-bug"
17
18// package scoped var to hold the repo after the PreRun execution
19var repo repository.Repo
20
21// RootCmd represents the base command when called without any subcommands
22var RootCmd = &cobra.Command{
23	Version: "0.2.0",
24
25	Use:   rootCommandName,
26	Short: "A bugtracker embedded in Git",
27	Long: `git-bug is a bugtracker embedded in git.
28
29It use the same internal storage so it doesn't pollute your project. As you would do with commits and branches, you can push your bugs to the same git remote your are already using to collaborate with other peoples.`,
30
31	// Force the execution of the PreRun while still displaying the help
32	Run: func(cmd *cobra.Command, args []string) {
33		cmd.Help()
34	},
35
36	// Load the repo before any command execution
37	// Note, this concern only commands that actually have a Run function
38	PersistentPreRunE: loadRepo,
39
40	DisableAutoGenTag: true,
41
42	BashCompletionFunction: `
43_git_bug() {
44    __start_git-bug "$@"
45}
46`,
47}
48
49func Execute() {
50	if err := RootCmd.Execute(); err != nil {
51		fmt.Println(err)
52		os.Exit(1)
53	}
54}
55
56func loadRepo(cmd *cobra.Command, args []string) error {
57	cwd, err := os.Getwd()
58	if err != nil {
59		return fmt.Errorf("Unable to get the current working directory: %q\n", err)
60	}
61
62	repo, err = repository.NewGitRepo(cwd, bug.Witnesser)
63	if err == repository.ErrNotARepo {
64		return fmt.Errorf("%s must be run from within a git repo.\n", rootCommandName)
65	}
66
67	if err != nil {
68		return err
69	}
70
71	return nil
72}