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
12const rootCommandName = "git-bug"
13
14// package scoped var to hold the repo after the PreRun execution
15var repo repository.Repo
16
17// RootCmd represents the base command when called without any subcommands
18var RootCmd = &cobra.Command{
19	Version: "0.2.0",
20
21	Use:   rootCommandName,
22	Short: "A bugtracker embedded in Git",
23	Long: `git-bug is a bugtracker embedded in git.
24
25It 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.`,
26
27	// For the root command, force the execution of the PreRun
28	// even if we just display the help. This is to make sure that we check
29	// the repository and give the user early feedback.
30	Run: func(cmd *cobra.Command, args []string) {
31		cmd.Help()
32	},
33
34	// Load the repo before any command execution
35	// Note, this concern only commands that actually have a Run function
36	PersistentPreRunE: loadRepo,
37
38	DisableAutoGenTag: true,
39
40	// Custom bash code to connect the git completion for "git bug" to the
41	// git-bug completion for "git-bug"
42	BashCompletionFunction: `
43_git_bug() {
44    __start_git-bug "$@"
45}
46`,
47}
48
49func Execute() {
50	if err := RootCmd.Execute(); err != nil {
51		os.Exit(1)
52	}
53}
54
55func loadRepo(cmd *cobra.Command, args []string) error {
56	cwd, err := os.Getwd()
57	if err != nil {
58		return fmt.Errorf("Unable to get the current working directory: %q\n", err)
59	}
60
61	repo, err = repository.NewGitRepo(cwd, bug.Witnesser)
62	if err == repository.ErrNotARepo {
63		return fmt.Errorf("%s must be run from within a git repo.\n", rootCommandName)
64	}
65
66	if err != nil {
67		return err
68	}
69
70	return nil
71}