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/identity"
10 "github.com/MichaelMure/git-bug/repository"
11 "github.com/spf13/cobra"
12)
13
14const rootCommandName = "git-bug"
15
16// package scoped var to hold the repo after the PreRun execution
17var repo repository.ClockedRepo
18
19// RootCmd represents the base command when called without any subcommands
20var RootCmd = &cobra.Command{
21 Use: rootCommandName,
22 Short: "A bug tracker embedded in Git",
23 Long: `git-bug is a bug tracker embedded in git.
24
25git-bug use git objects to store the bug tracking separated from the files
26history. As bugs are regular git objects, they can be pushed and pulled from/to
27the same git remote your are already using to collaborate with other peoples.
28
29`,
30
31 // For the root command, force the execution of the PreRun
32 // even if we just display the help. This is to make sure that we check
33 // the repository and give the user early feedback.
34 Run: func(cmd *cobra.Command, args []string) {
35 if err := cmd.Help(); err != nil {
36 os.Exit(1)
37 }
38 },
39
40 DisableAutoGenTag: true,
41
42 // Custom bash code to connect the git completion for "git bug" to the
43 // git-bug completion for "git-bug"
44 BashCompletionFunction: `
45_git_bug() {
46 __start_git-bug "$@"
47}
48`,
49}
50
51func Execute() {
52 if err := RootCmd.Execute(); err != nil {
53 os.Exit(1)
54 }
55}
56
57// loadRepo is a pre-run function that load the repository for use in a command
58func loadRepo(cmd *cobra.Command, args []string) error {
59 cwd, err := os.Getwd()
60 if err != nil {
61 return fmt.Errorf("Unable to get the current working directory: %q\n", err)
62 }
63
64 repo, err = repository.NewGitRepo(cwd, bug.Witnesser)
65 if err == repository.ErrNotARepo {
66 return fmt.Errorf("%s must be run from within a git repo.\n", rootCommandName)
67 }
68
69 if err != nil {
70 return err
71 }
72
73 return nil
74}
75
76// loadRepoEnsureUser is the same as loadRepo, but also ensure that the user has configured
77// an identity. Use this pre-run function when an error after using the configured user won't
78// do.
79func loadRepoEnsureUser(cmd *cobra.Command, args []string) error {
80 err := loadRepo(cmd, args)
81 if err != nil {
82 return err
83 }
84
85 set, err := identity.IsUserIdentitySet(repo)
86 if err != nil {
87 return err
88 }
89
90 if !set {
91 return identity.ErrNoIdentitySet
92 }
93
94 return nil
95}