root.go

 1// Package commands contains the CLI commands
 2package commands
 3
 4import (
 5	"fmt"
 6	"os"
 7
 8	"github.com/MichaelMure/git-bug/bug"
 9	"github.com/MichaelMure/git-bug/repository"
10	"github.com/spf13/cobra"
11)
12
13const rootCommandName = "git-bug"
14
15// package scoped var to hold the repo after the PreRun execution
16var repo repository.ClockedRepo
17
18// RootCmd represents the base command when called without any subcommands
19var RootCmd = &cobra.Command{
20	Version: "0.3.0",
21
22	Use:   rootCommandName,
23	Short: "A bug tracker embedded in Git",
24	Long: `git-bug is a bug tracker embedded in git.
25
26git-hub use git objects to store the bug tracking separated from the files
27history. As bugs are regular git objects, they can be pushed and pulled from/to
28the same git remote your are already using to collaborate with other peoples.
29
30`,
31
32	// For the root command, force the execution of the PreRun
33	// even if we just display the help. This is to make sure that we check
34	// the repository and give the user early feedback.
35	Run: func(cmd *cobra.Command, args []string) {
36		if err := cmd.Help(); err != nil {
37			os.Exit(1)
38		}
39	},
40
41	// Load the repo before any command execution
42	// Note, this concern only commands that actually have a Run function
43	PersistentPreRunE: loadRepo,
44
45	DisableAutoGenTag: true,
46
47	// Custom bash code to connect the git completion for "git bug" to the
48	// git-bug completion for "git-bug"
49	BashCompletionFunction: `
50_git_bug() {
51    __start_git-bug "$@"
52}
53`,
54}
55
56func Execute() {
57	if err := RootCmd.Execute(); err != nil {
58		os.Exit(1)
59	}
60}
61
62func loadRepo(cmd *cobra.Command, args []string) error {
63	cwd, err := os.Getwd()
64	if err != nil {
65		return fmt.Errorf("Unable to get the current working directory: %q\n", err)
66	}
67
68	repo, err = repository.NewGitRepo(cwd, bug.Witnesser)
69	if err == repository.ErrNotARepo {
70		return fmt.Errorf("%s must be run from within a git repo.\n", rootCommandName)
71	}
72
73	if err != nil {
74		return err
75	}
76
77	return nil
78}