1// Package commands contains the CLI commands
2package commands
3
4import (
5 "fmt"
6 "os"
7
8 "github.com/spf13/cobra"
9
10 "github.com/MichaelMure/git-bug/bug"
11 "github.com/MichaelMure/git-bug/identity"
12 "github.com/MichaelMure/git-bug/repository"
13)
14
15const rootCommandName = "git-bug"
16
17// package scoped var to hold the repo after the PreRun execution
18var repo repository.ClockedRepo
19
20// RootCmd represents the base command when called without any subcommands
21var RootCmd = &cobra.Command{
22 Use: rootCommandName,
23 Short: "A bug tracker embedded in Git.",
24 Long: `git-bug is a bug tracker embedded in git.
25
26git-bug 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 you are already using to collaborate with other people.
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 SilenceUsage: true,
42 DisableAutoGenTag: true,
43
44 // Custom bash code to connect the git completion for "git bug" to the
45 // git-bug completion for "git-bug"
46 BashCompletionFunction: `
47_git_bug() {
48 __start_git-bug "$@"
49}
50`,
51}
52
53func Execute() {
54 if err := RootCmd.Execute(); err != nil {
55 os.Exit(1)
56 }
57}
58
59// loadRepo is a pre-run function that load the repository for use in a command
60func loadRepo(cmd *cobra.Command, args []string) error {
61 cwd, err := os.Getwd()
62 if err != nil {
63 return fmt.Errorf("unable to get the current working directory: %q", err)
64 }
65
66 repo, err = repository.NewGitRepo(cwd, bug.Witnesser)
67 if err == repository.ErrNotARepo {
68 return fmt.Errorf("%s must be run from within a git repo", rootCommandName)
69 }
70
71 if err != nil {
72 return err
73 }
74
75 return nil
76}
77
78// loadRepoEnsureUser is the same as loadRepo, but also ensure that the user has configured
79// an identity. Use this pre-run function when an error after using the configured user won't
80// do.
81func loadRepoEnsureUser(cmd *cobra.Command, args []string) error {
82 err := loadRepo(cmd, args)
83 if err != nil {
84 return err
85 }
86
87 _, err = identity.GetUserIdentity(repo)
88 if err != nil {
89 return err
90 }
91
92 return nil
93}