Skip to content
This repository was archived by the owner on Sep 9, 2020. It is now read-only.

Commit 2fd3763

Browse files
committed
improve godoc; replace Loggers with embeded fields; refactor Ctx api
1 parent 9e747df commit 2fd3763

14 files changed

+174
-127
lines changed

cmd/dep/ensure.go

+5-5
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ type ensureCommand struct {
104104

105105
func (cmd *ensureCommand) Run(ctx *dep.Ctx, args []string) error {
106106
if cmd.examples {
107-
ctx.Loggers.Err.Println(strings.TrimSpace(ensureExamples))
107+
ctx.Err.Println(strings.TrimSpace(ensureExamples))
108108
return nil
109109
}
110110

@@ -121,8 +121,8 @@ func (cmd *ensureCommand) Run(ctx *dep.Ctx, args []string) error {
121121
defer sm.Release()
122122

123123
params := p.MakeParams()
124-
if ctx.Loggers.Verbose {
125-
params.TraceLogger = ctx.Loggers.Err
124+
if ctx.Verbose {
125+
params.TraceLogger = ctx.Err
126126
}
127127
params.RootPackageTree, err = pkgtree.ListPackages(p.AbsRoot, string(p.ImportRoot))
128128
if err != nil {
@@ -136,7 +136,7 @@ func (cmd *ensureCommand) Run(ctx *dep.Ctx, args []string) error {
136136
if cmd.update {
137137
applyUpdateArgs(args, &params)
138138
} else {
139-
err := applyEnsureArgs(ctx.Loggers.Err, args, cmd.overrides, p, sm, &params)
139+
err := applyEnsureArgs(ctx.Err, args, cmd.overrides, p, sm, &params)
140140
if err != nil {
141141
return err
142142
}
@@ -169,7 +169,7 @@ func (cmd *ensureCommand) Run(ctx *dep.Ctx, args []string) error {
169169
return err
170170
}
171171
if cmd.dryRun {
172-
return sw.PrintPreparedActions(ctx.Loggers.Out)
172+
return sw.PrintPreparedActions(ctx.Out)
173173
}
174174

175175
return errors.Wrap(sw.Write(p.AbsRoot, sm, false), "grouped write of manifest, lock and vendor")

cmd/dep/glide_importer_test.go

+4-4
Original file line numberDiff line numberDiff line change
@@ -21,16 +21,16 @@ import (
2121
const testGlideProjectRoot = "github.com/golang/notexist"
2222

2323
var (
24-
discardLogger = log.New(ioutil.Discard, "", 0)
25-
discardLoggers = &dep.Loggers{Out: discardLogger, Err: discardLogger}
24+
discardLogger = log.New(ioutil.Discard, "", 0)
2625
)
2726

2827
func newTestContext(h *test.Helper) *dep.Ctx {
2928
h.TempDir("src")
3029
pwd := h.Path(".")
3130
return &dep.Ctx{
32-
GOPATH: pwd,
33-
Loggers: discardLoggers,
31+
GOPATH: pwd,
32+
Out: discardLogger,
33+
Err: discardLogger,
3434
}
3535
}
3636

cmd/dep/gopath_scanner.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ func newGopathScanner(ctx *dep.Ctx, directDeps map[string]bool, sm gps.SourceMan
4646
func (g *gopathScanner) InitializeRootManifestAndLock(rootM *dep.Manifest, rootL *dep.Lock) error {
4747
var err error
4848

49-
g.ctx.Loggers.Err.Println("Searching GOPATH for projects...")
49+
g.ctx.Err.Println("Searching GOPATH for projects...")
5050
g.pd, err = g.scanGopathForDependencies()
5151
if err != nil {
5252
return err
@@ -123,7 +123,7 @@ func (g *gopathScanner) overlay(rootM *dep.Manifest, rootL *dep.Lock) {
123123
unlockedProjects = append(unlockedProjects, string(pr))
124124
}
125125
if len(unlockedProjects) > 0 {
126-
g.ctx.Loggers.Err.Printf("Following dependencies were not found in GOPATH. "+
126+
g.ctx.Err.Printf("Following dependencies were not found in GOPATH. "+
127127
"Dep will use the most recent versions of these projects.\n %s",
128128
strings.Join(unlockedProjects, "\n "))
129129
}
@@ -211,7 +211,7 @@ func (g *gopathScanner) scanGopathForDependencies() (projectData, error) {
211211
var syncDepGroup sync.WaitGroup
212212
syncDep := func(pr gps.ProjectRoot, sm gps.SourceManager) {
213213
if err := sm.SyncSourceFor(gps.ProjectIdentifier{ProjectRoot: pr}); err != nil {
214-
g.ctx.Loggers.Err.Printf("%+v", errors.Wrapf(err, "Unable to cache %s", pr))
214+
g.ctx.Err.Printf("%+v", errors.Wrapf(err, "Unable to cache %s", pr))
215215
}
216216
syncDepGroup.Done()
217217
}

cmd/dep/hash_in.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,6 @@ func (hashinCommand) Run(ctx *dep.Ctx, args []string) error {
5151
if err != nil {
5252
return errors.Wrap(err, "prepare solver")
5353
}
54-
ctx.Loggers.Out.Println(gps.HashingInputsAsString(s))
54+
ctx.Out.Println(gps.HashingInputsAsString(s))
5555
return nil
5656
}

cmd/dep/init.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -135,8 +135,8 @@ func (cmd *initCommand) Run(ctx *dep.Ctx, args []string) error {
135135
ProjectAnalyzer: rootAnalyzer,
136136
}
137137

138-
if ctx.Loggers.Verbose {
139-
params.TraceLogger = ctx.Loggers.Err
138+
if ctx.Verbose {
139+
params.TraceLogger = ctx.Err
140140
}
141141

142142
s, err := gps.Prepare(params, sm)
@@ -169,7 +169,7 @@ func (cmd *initCommand) Run(ctx *dep.Ctx, args []string) error {
169169
return err
170170
}
171171
if vendorbak != "" {
172-
ctx.Loggers.Err.Printf("Old vendor backed up to %v", vendorbak)
172+
ctx.Err.Printf("Old vendor backed up to %v", vendorbak)
173173
}
174174

175175
sw, err := dep.NewSafeWriter(m, nil, l, dep.VendorAlways)

cmd/dep/main.go

+23-11
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import (
1212
"io"
1313
"log"
1414
"os"
15+
"path/filepath"
1516
"strings"
1617
"text/tabwriter"
1718

@@ -46,11 +47,10 @@ func main() {
4647

4748
// A Config specifies a full configuration for a dep execution.
4849
type Config struct {
49-
// Args hold the command-line arguments, starting with the program name.
50-
Args []string
51-
Stdout, Stderr io.Writer
52-
WorkingDir string
53-
Env []string
50+
WorkingDir string // Where to execute
51+
Args []string // Command-line arguments, starting with the program name.
52+
Env []string // Environment variables
53+
Stdout, Stderr io.Writer // Log output
5454
}
5555

5656
// Run executes a configuration and returns an exit code.
@@ -135,23 +135,23 @@ func (c *Config) Run() (exitCode int) {
135135
}
136136

137137
// Parse the flags the user gave us.
138-
// flag package automaticly prints usage and error message in err != nil
138+
// flag package automatically prints usage and error message in err != nil
139139
// or if '-h' flag provided
140140
if err := fs.Parse(c.Args[2:]); err != nil {
141141
exitCode = 1
142142
return
143143
}
144144

145-
loggers := &dep.Loggers{
145+
// Set up the dep context.
146+
ctx := &dep.Ctx{
146147
Out: log.New(c.Stdout, "", 0),
147148
Err: errLogger,
148149
Verbose: *verbose,
149150
}
150-
151-
// Set up the dep context.
152-
ctx, err := dep.NewContext(c.WorkingDir, c.Env, loggers)
151+
gopaths := filepath.SplitList(getEnv(c.Env, "GOPATH"))
152+
err := ctx.SetPaths(c.WorkingDir, gopaths...)
153153
if err != nil {
154-
loggers.Err.Println(err)
154+
errLogger.Printf("%q not in any GOPATH: %s\n", c.WorkingDir, err)
155155
exitCode = 1
156156
return
157157
}
@@ -174,6 +174,18 @@ func (c *Config) Run() (exitCode int) {
174174
return
175175
}
176176

177+
// getEnv returns the last instance of the environment variable.
178+
func getEnv(env []string, key string) string {
179+
pre := key + "="
180+
for i := len(env) - 1; i >= 0; i-- {
181+
v := env[i]
182+
if strings.HasPrefix(v, pre) {
183+
return strings.TrimPrefix(v, pre)
184+
}
185+
}
186+
return ""
187+
}
188+
177189
func resetUsage(logger *log.Logger, fs *flag.FlagSet, name, args, longHelp string) {
178190
var (
179191
hasFlags bool

cmd/dep/prune.go

+4-4
Original file line numberDiff line numberDiff line change
@@ -59,8 +59,8 @@ func (cmd *pruneCommand) Run(ctx *dep.Ctx, args []string) error {
5959
params := p.MakeParams()
6060
params.RootPackageTree = ptree
6161

62-
if ctx.Loggers.Verbose {
63-
params.TraceLogger = ctx.Loggers.Err
62+
if ctx.Verbose {
63+
params.TraceLogger = ctx.Err
6464
}
6565

6666
s, err := gps.Prepare(params, sm)
@@ -77,8 +77,8 @@ func (cmd *pruneCommand) Run(ctx *dep.Ctx, args []string) error {
7777
}
7878

7979
var pruneLogger *log.Logger
80-
if ctx.Loggers.Verbose {
81-
pruneLogger = ctx.Loggers.Err
80+
if ctx.Verbose {
81+
pruneLogger = ctx.Err
8282
}
8383
return dep.PruneProject(p, sm, pruneLogger)
8484
}

cmd/dep/root_analyzer.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ func (a *rootAnalyzer) importManifestAndLock(dir string, pr gps.ProjectRoot, sup
7777

7878
for _, i := range importers {
7979
if i.HasDepMetadata(dir) {
80-
a.ctx.Loggers.Err.Printf("Importing configuration from %s. These are only initial constraints, and are further refined during the solve process.", i.Name())
80+
a.ctx.Err.Printf("Importing configuration from %s. These are only initial constraints, and are further refined during the solve process.", i.Name())
8181
m, l, err := i.Import(dir, pr)
8282
a.removeTransitiveDependencies(m)
8383
return m, l, err

cmd/dep/status.go

+11-11
Original file line numberDiff line numberDiff line change
@@ -215,22 +215,22 @@ func (cmd *statusCommand) Run(ctx *dep.Ctx, args []string) error {
215215
}
216216
}
217217

218-
digestMismatch, hasMissingPkgs, err := runStatusAll(ctx.Loggers, out, p, sm)
218+
digestMismatch, hasMissingPkgs, err := runStatusAll(ctx, out, p, sm)
219219
if err != nil {
220220
return err
221221
}
222222

223223
if digestMismatch {
224224
if hasMissingPkgs {
225-
ctx.Loggers.Err.Printf("Lock inputs-digest mismatch due to the following packages missing from the lock:\n\n")
226-
ctx.Loggers.Out.Print(buf.String())
227-
ctx.Loggers.Err.Printf("\nThis happens when a new import is added. Run `dep ensure` to install the missing packages.\n")
225+
ctx.Err.Printf("Lock inputs-digest mismatch due to the following packages missing from the lock:\n\n")
226+
ctx.Out.Print(buf.String())
227+
ctx.Err.Printf("\nThis happens when a new import is added. Run `dep ensure` to install the missing packages.\n")
228228
} else {
229-
ctx.Loggers.Err.Printf("Lock inputs-digest mismatch. This happens when Gopkg.toml is modified.\n" +
229+
ctx.Err.Printf("Lock inputs-digest mismatch. This happens when Gopkg.toml is modified.\n" +
230230
"Run `dep ensure` to regenerate the inputs-digest.")
231231
}
232232
} else {
233-
ctx.Loggers.Out.Print(buf.String())
233+
ctx.Out.Print(buf.String())
234234
}
235235

236236
return nil
@@ -253,7 +253,7 @@ type MissingStatus struct {
253253
MissingPackages []string
254254
}
255255

256-
func runStatusAll(loggers *dep.Loggers, out outputter, p *dep.Project, sm gps.SourceManager) (bool, bool, error) {
256+
func runStatusAll(ctx *dep.Ctx, out outputter, p *dep.Project, sm gps.SourceManager) (bool, bool, error) {
257257
var digestMismatch, hasMissingPkgs bool
258258

259259
if p.Lock == nil {
@@ -276,8 +276,8 @@ func runStatusAll(loggers *dep.Loggers, out outputter, p *dep.Project, sm gps.So
276276
Manifest: p.Manifest,
277277
// Locks aren't a part of the input hash check, so we can omit it.
278278
}
279-
if loggers.Verbose {
280-
params.TraceLogger = loggers.Err
279+
if ctx.Verbose {
280+
params.TraceLogger = ctx.Err
281281
}
282282

283283
s, err := gps.Prepare(params, sm)
@@ -412,9 +412,9 @@ func runStatusAll(loggers *dep.Loggers, out outputter, p *dep.Project, sm gps.So
412412
// TODO this is just a fix quick so staticcheck doesn't complain.
413413
// Visually reconciling failure to deduce project roots with the rest of
414414
// the mismatch output is a larger problem.
415-
loggers.Err.Printf("Failed to deduce project roots for import paths:\n")
415+
ctx.Err.Printf("Failed to deduce project roots for import paths:\n")
416416
for _, fail := range errs {
417-
loggers.Err.Printf("\t%s: %s\n", fail.ex, fail.err.Error())
417+
ctx.Err.Printf("\t%s: %s\n", fail.ex, fail.err.Error())
418418
}
419419

420420
return digestMismatch, hasMissingPkgs, errors.New("address issues with undeducible import paths to get more status information")

0 commit comments

Comments
 (0)