forked from golang/dep
/
main.go
232 lines (209 loc) · 5.4 KB
/
main.go
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Command dep is a prototype dependency management tool.
package main
import (
"bytes"
"flag"
"fmt"
"io"
"log"
"os"
"strings"
"text/tabwriter"
"github.com/golang/dep"
)
type command interface {
Name() string // "foobar"
Args() string // "<baz> [quux...]"
ShortHelp() string // "Foo the first bar"
LongHelp() string // "Foo the first bar meeting the following conditions..."
Register(*flag.FlagSet) // command-specific flags
Hidden() bool // indicates whether the command should be hidden from help output
Run(*dep.Ctx, []string) error
}
func main() {
wd, err := os.Getwd()
if err != nil {
fmt.Fprintln(os.Stderr, "failed to get working directory", err)
os.Exit(1)
}
c := &Config{
Args: os.Args,
Stdout: os.Stdout,
Stderr: os.Stderr,
WorkingDir: wd,
Env: os.Environ(),
}
os.Exit(c.Run())
}
// A Config specifies a full configuration for a dep execution.
type Config struct {
// Args hold the command-line arguments, starting with the program name.
Args []string
Stdout, Stderr io.Writer
WorkingDir string
Env []string
}
// Run executes a configuration and returns an exit code.
func (c *Config) Run() (exitCode int) {
// Build the list of available commands.
commands := []command{
&initCommand{},
&statusCommand{},
&ensureCommand{},
&removeCommand{},
&hashinCommand{},
&pruneCommand{},
}
examples := [][2]string{
{
"dep init",
"set up a new project",
},
{
"dep ensure",
"install the project's dependencies",
},
{
"dep ensure -update",
"update the locked versions of all dependencies",
},
{
"dep ensure github.com/pkg/errors",
"add a dependency to the project",
},
}
errLogger := log.New(c.Stderr, "", 0)
usage := func() {
errLogger.Println("dep is a tool for managing dependencies for Go projects")
errLogger.Println()
errLogger.Println("Usage: dep <command>")
errLogger.Println()
errLogger.Println("Commands:")
errLogger.Println()
w := tabwriter.NewWriter(c.Stderr, 0, 4, 2, ' ', 0)
for _, cmd := range commands {
if !cmd.Hidden() {
fmt.Fprintf(w, "\t%s\t%s\n", cmd.Name(), cmd.ShortHelp())
}
}
w.Flush()
errLogger.Println()
errLogger.Println("Examples:")
for _, example := range examples {
fmt.Fprintf(w, "\t%s\t%s\n", example[0], example[1])
}
w.Flush()
errLogger.Println()
errLogger.Println("Use \"dep help [command]\" for more information about a command.")
}
cmdName, printCommandHelp, exit := parseArgs(c.Args)
if exit {
usage()
exitCode = 1
return
}
for _, cmd := range commands {
if cmd.Name() == cmdName {
// Build flag set with global flags in there.
fs := flag.NewFlagSet(cmdName, flag.ContinueOnError)
fs.SetOutput(c.Stderr)
verbose := fs.Bool("v", false, "enable verbose logging")
// Register the subcommand flags in there, too.
cmd.Register(fs)
// Override the usage text to something nicer.
resetUsage(errLogger, fs, cmdName, cmd.Args(), cmd.LongHelp())
if printCommandHelp {
fs.Usage()
exitCode = 1
return
}
// Parse the flags the user gave us.
// flag package automaticly prints usage and error message in err != nil
// or if '-h' flag provided
if err := fs.Parse(c.Args[2:]); err != nil {
exitCode = 1
return
}
loggers := &dep.Loggers{
Out: log.New(c.Stdout, "", 0),
Err: errLogger,
Verbose: *verbose,
}
// Set up the dep context.
ctx, err := dep.NewContext(c.WorkingDir, c.Env, loggers)
if err != nil {
loggers.Err.Println(err)
exitCode = 1
return
}
// Run the command with the post-flag-processing args.
if err := cmd.Run(ctx, fs.Args()); err != nil {
errLogger.Printf("%v\n", err)
exitCode = 1
return
}
// Easy peasy livin' breezy.
return
}
}
errLogger.Printf("dep: %s: no such command\n", cmdName)
usage()
exitCode = 1
return
}
func resetUsage(logger *log.Logger, fs *flag.FlagSet, name, args, longHelp string) {
var (
hasFlags bool
flagBlock bytes.Buffer
flagWriter = tabwriter.NewWriter(&flagBlock, 0, 4, 2, ' ', 0)
)
fs.VisitAll(func(f *flag.Flag) {
hasFlags = true
// Default-empty string vars should read "(default: <none>)"
// rather than the comparatively ugly "(default: )".
defValue := f.DefValue
if defValue == "" {
defValue = "<none>"
}
fmt.Fprintf(flagWriter, "\t-%s\t%s (default: %s)\n", f.Name, f.Usage, defValue)
})
flagWriter.Flush()
fs.Usage = func() {
logger.Printf("Usage: dep %s %s\n", name, args)
logger.Println()
logger.Println(strings.TrimSpace(longHelp))
logger.Println()
if hasFlags {
logger.Println("Flags:")
logger.Println()
logger.Println(flagBlock.String())
}
}
}
// parseArgs determines the name of the dep command and whether the user asked for
// help to be printed.
func parseArgs(args []string) (cmdName string, printCmdUsage bool, exit bool) {
isHelpArg := func() bool {
return strings.Contains(strings.ToLower(args[1]), "help") || strings.ToLower(args[1]) == "-h"
}
switch len(args) {
case 0, 1:
exit = true
case 2:
if isHelpArg() {
exit = true
}
cmdName = args[1]
default:
if isHelpArg() {
cmdName = args[2]
printCmdUsage = true
} else {
cmdName = args[1]
}
}
return cmdName, printCmdUsage, exit
}