Hunter0x7c7
2022-08-11 b8230139fb40edea387617b6accd8371e37eda58
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package base
 
import (
    "flag"
    "fmt"
    "os"
    "sort"
    "strings"
)
 
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// copied from "github.com/golang/go/main.go"
 
// Execute excute the commands
func Execute() {
    flag.Parse()
    args := flag.Args()
    if len(args) < 1 {
        PrintUsage(os.Stderr, RootCommand)
        return
    }
    cmdName := args[0] // for error messages
    if args[0] == "help" {
        Help(os.Stdout, args[1:])
        return
    }
 
BigCmdLoop:
    for bigCmd := RootCommand; ; {
        for _, cmd := range bigCmd.Commands {
            if cmd.Name() != args[0] {
                continue
            }
            if len(cmd.Commands) > 0 {
                // test sub commands
                bigCmd = cmd
                args = args[1:]
                if len(args) == 0 {
                    PrintUsage(os.Stderr, bigCmd)
                    SetExitStatus(2)
                    Exit()
                }
                if args[0] == "help" {
                    // Accept 'go mod help' and 'go mod help foo' for 'go help mod' and 'go help mod foo'.
                    Help(os.Stdout, append(strings.Split(cmdName, " "), args[1:]...))
                    return
                }
                cmdName += " " + args[0]
                continue BigCmdLoop
            }
            if !cmd.Runnable() {
                continue
            }
            cmd.Flag.Usage = func() { cmd.Usage() }
            if cmd.CustomFlags {
                args = args[1:]
            } else {
                cmd.Flag.Parse(args[1:])
                args = cmd.Flag.Args()
            }
 
            buildCommandText(cmd)
            cmd.Run(cmd, args)
            Exit()
            return
        }
        helpArg := ""
        if i := strings.LastIndex(cmdName, " "); i >= 0 {
            helpArg = " " + cmdName[:i]
        }
        fmt.Fprintf(os.Stderr, "%s %s: unknown command\nRun '%s help%s' for usage.\n", CommandEnv.Exec, cmdName, CommandEnv.Exec, helpArg)
        SetExitStatus(2)
        Exit()
    }
}
 
// SortCommands sorts the first level sub commands
func SortCommands() {
    sort.Slice(RootCommand.Commands, func(i, j int) bool {
        return SortLessFunc(RootCommand.Commands[i], RootCommand.Commands[j])
    })
}
 
// SortLessFunc used for sort commands list, can be override from outside
var SortLessFunc = func(i, j *Command) bool {
    return i.Name() < j.Name()
}