| 1 | package commands |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "fmt" |
| 6 | "log" |
| 7 | "os" |
| 8 | "path/filepath" |
| 9 | "strings" |
| 10 | "sync" |
| 11 | "time" |
| 12 | |
| 13 | "github.com/git-lfs/git-lfs/v3/config" |
| 14 | "github.com/git-lfs/git-lfs/v3/tools" |
| 15 | "github.com/git-lfs/git-lfs/v3/tr" |
| 16 | "github.com/spf13/cobra" |
| 17 | ) |
| 18 | |
| 19 | var ( |
| 20 | commandFuncs []func() *cobra.Command |
| 21 | commandMu sync.Mutex |
| 22 | |
| 23 | rootVersion bool |
| 24 | ) |
| 25 | |
| 26 | // NewCommand creates a new 'git-lfs' sub command, given a command name and |
| 27 | // command run function. |
| 28 | // |
| 29 | // Each command will initialize the local storage ('.git/lfs') directory when |
| 30 | // run, unless the PreRun hook is set to nil. |
| 31 | func NewCommand(name string, runFn func(*cobra.Command, []string)) *cobra.Command { |
| 32 | return &cobra.Command{Use: name, Run: runFn, PreRun: setupHTTPLogger} |
| 33 | } |
| 34 | |
| 35 | // RegisterCommand creates a direct 'git-lfs' subcommand, given a command name, |
| 36 | // a command run function, and an optional callback during the command |
| 37 | // initialization process. |
| 38 | // |
| 39 | // The 'git-lfs' command initialization is deferred until the `commands.Run()` |
| 40 | // function is called. The fn callback is passed the output from NewCommand, |
| 41 | // and gives the caller the flexibility to customize the command by adding |
| 42 | // flags, tweaking command hooks, etc. |
| 43 | func RegisterCommand(name string, runFn func(cmd *cobra.Command, args []string), fn func(cmd *cobra.Command)) { |
| 44 | commandMu.Lock() |
| 45 | commandFuncs = append(commandFuncs, func() *cobra.Command { |
| 46 | cmd := NewCommand(name, runFn) |
| 47 | if fn != nil { |
| 48 | fn(cmd) |
| 49 | } |
| 50 | return cmd |
| 51 | }) |
| 52 | commandMu.Unlock() |
| 53 | } |
| 54 | |
| 55 | // Run initializes the 'git-lfs' command and runs it with the given stdin and |
| 56 | // command line args. |
| 57 | // |
| 58 | // It returns an exit code. |
| 59 | func Run() int { |
| 60 | log.SetOutput(ErrorWriter) |
| 61 | tr.InitializeLocale() |
| 62 | |
| 63 | root := NewCommand("git-lfs", gitlfsCommand) |
| 64 | root.PreRun = nil |
| 65 | |
| 66 | completionCmd := &cobra.Command{ |
| 67 | Use: "completion [bash|fish|zsh]", |
| 68 | DisableFlagsInUseLine: true, |
| 69 | ValidArgs: []string{"bash", "fish", "zsh"}, |
| 70 | Args: cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs), |
| 71 | Run: func(cmd *cobra.Command, args []string) { |
| 72 | switch args[0] { |
| 73 | case "bash": |
| 74 | completion := new(bytes.Buffer) |
| 75 | cmd.Root().GenBashCompletionV2(completion, false) |
| 76 | |
| 77 | // this is needed for git bash completion to pick up the completion for the subcommand |
| 78 | completionSource := []byte(` local out directive |
| 79 | __git-lfs_get_completion_results |
| 80 | `) |
| 81 | completionReplace := []byte(` if [[ ${words[0]} == "git" && ${words[1]} == "lfs" ]]; then |
| 82 | words=("git-lfs" "${words[@]:2:${#words[@]}-2}") |
| 83 | __git-lfs_debug "Rewritten words[*]: ${words[*]}," |
| 84 | fi |
| 85 | |
| 86 | local out directive |
| 87 | __git-lfs_get_completion_results |
| 88 | `) |
| 89 | newCompletion := bytes.NewBuffer(bytes.Replace(completion.Bytes(), completionSource, completionReplace, 1)) |
| 90 | newCompletion.WriteString("_git_lfs() { __start_git-lfs; }\n") |
| 91 | |
| 92 | newCompletion.WriteTo(os.Stdout) |
| 93 | case "fish": |
| 94 | cmd.Root().GenFishCompletion(os.Stdout, false) |
| 95 | case "zsh": |
| 96 | completion := new(bytes.Buffer) |
| 97 | cmd.Root().GenZshCompletionNoDesc(completion) |
| 98 | |
| 99 | // this is needed for git zsh completion to use the right command for completion |
| 100 | completionSource := []byte(` requestComp="${words[1]} __completeNoDesc ${words[2,-1]}"`) |
| 101 | completionReplace := []byte(` requestComp="git-${words[1]#*git-} __completeNoDesc ${words[2,-1]}"`) |
| 102 | newCompletion := bytes.NewBuffer(bytes.Replace(completion.Bytes(), completionSource, completionReplace, 1)) |
| 103 | |
| 104 | newCompletion.WriteTo(os.Stdout) |
| 105 | } |
| 106 | }, |
| 107 | } |
| 108 | |
| 109 | root.AddCommand(completionCmd) |
| 110 | |
| 111 | // Set up help/usage funcs based on manpage text |
| 112 | helpcmd := &cobra.Command{ |
| 113 | Use: "help [command]", |
| 114 | Short: "Help about any command", |
| 115 | Long: `Help provides help for any command in the application. |
| 116 | Simply type ` + root.Name() + ` help [path to command] for full details.`, |
| 117 | |
| 118 | Run: func(c *cobra.Command, args []string) { |
| 119 | cmd, _, e := c.Root().Find(args) |
| 120 | // In the case of "git lfs help config" or "git lfs help |
| 121 | // faq", pretend the last arg was "help" so our command |
| 122 | // lookup succeeds, since cmd will be ignored in |
| 123 | // helpCommand(). |
| 124 | if e != nil && (args[0] == "config" || args[0] == "faq") { |
| 125 | cmd, _, e = c.Root().Find([]string{"help"}) |
| 126 | } |
| 127 | if cmd == nil || e != nil { |
| 128 | c.Println(tr.Tr.Get("Unknown help topic %#q", args)) |
| 129 | c.Root().Usage() |
| 130 | } else { |
| 131 | c.HelpFunc()(cmd, args) |
| 132 | } |
| 133 | }, |
| 134 | } |
| 135 | |
| 136 | root.SetHelpCommand(helpcmd) |
| 137 | |
| 138 | root.SetHelpTemplate("{{.UsageString}}") |
| 139 | root.SetHelpFunc(helpCommand) |
| 140 | root.SetUsageFunc(usageCommand) |
| 141 | |
| 142 | root.Flags().BoolVarP(&rootVersion, "version", "v", false, "") |
| 143 | |
| 144 | canonicalizeEnvironment() |
| 145 | |
| 146 | cfg = config.New() |
| 147 | |
| 148 | for _, f := range commandFuncs { |
| 149 | if cmd := f(); cmd != nil { |
| 150 | root.AddCommand(cmd) |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | err := root.Execute() |
| 155 | |
| 156 | if err != nil { |
| 157 | return 127 |
| 158 | } |
| 159 | return 0 |
| 160 | } |
| 161 | |
| 162 | func gitlfsCommand(cmd *cobra.Command, args []string) { |
| 163 | versionCommand(cmd, args) |
| 164 | if !rootVersion { |
| 165 | cmd.Usage() |
| 166 | } |
| 167 | } |
| 168 | |
| 169 | func helpCommand(cmd *cobra.Command, args []string) { |
| 170 | if len(args) == 0 { |
| 171 | printHelp("git-lfs") |
| 172 | } else { |
| 173 | printHelp(args[0]) |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | func usageCommand(cmd *cobra.Command) error { |
| 178 | printHelp(cmd.Name()) |
| 179 | return nil |
| 180 | } |
| 181 | |
| 182 | func printHelp(commandName string) { |
| 183 | switch commandName { |
| 184 | case "--help", "-h": |
| 185 | commandName = "git-lfs" |
| 186 | } |
| 187 | if txt, ok := ManPages[commandName]; ok { |
| 188 | fmt.Println(strings.TrimSpace(txt)) |
| 189 | } else { |
| 190 | fmt.Println(tr.Tr.Get("Sorry, no usage text found for %q", commandName)) |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | func setupHTTPLogger(cmd *cobra.Command, args []string) { |
| 195 | if len(os.Getenv("GIT_LOG_STATS")) < 1 { |
| 196 | return |
| 197 | } |
| 198 | |
| 199 | logBase := filepath.Join(cfg.LocalLogDir(), "http") |
| 200 | if err := tools.MkdirAll(logBase, cfg); err != nil { |
| 201 | fmt.Fprintln(os.Stderr, tr.Tr.Get("Error logging HTTP stats: %s", err)) |
| 202 | return |
| 203 | } |
| 204 | |
| 205 | logFile := fmt.Sprintf("http-%d.log", time.Now().Unix()) |
| 206 | file, err := os.Create(filepath.Join(logBase, logFile)) |
| 207 | if err != nil { |
| 208 | fmt.Fprintln(os.Stderr, tr.Tr.Get("Error logging HTTP stats: %s", err)) |
| 209 | } else { |
| 210 | getAPIClient().LogHTTPStats(file) |
| 211 | } |
| 212 | } |