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

Commit bff0adc

Browse files
committed
do not create cachedir recursively
source - main.go: Try to ensure directory for given `cachedir` path. - context.go: Create the default cache directory, `$GOPATH/pkg/dep`, if the user did not override it. - source_manager.go: Use `fs.EnsureDir` instead of `os.MkdirAll` for creating sources folder in cache directory. - fs.go: - Add func `EnsureDir` to create a directory if it does not exist. - Remove func `IsValidPath`. test - integration_test.go: Improve tests for invalid cache directory. - fs_test.go: Add test for `EnsureDir`, remove test for `IsValidPath`. - manager_test.go: fix TestSourceManagerInit - Re-create cache directory before trying to call `NewSourceManager` the 2nd time and defer it's removal. - If `NewSourceManager` fails the 2nd time, exit the error using `t.Fatal` to avoid panic in `sm.Release` misc - language - {fallback => default} for cachedir
1 parent 833bcaf commit bff0adc

File tree

8 files changed

+98
-59
lines changed

8 files changed

+98
-59
lines changed

cmd/dep/integration_test.go

+30-14
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ package main
77
import (
88
"fmt"
99
"io"
10+
"io/ioutil"
1011
"os"
1112
"os/exec"
1213
"path/filepath"
@@ -98,21 +99,36 @@ func TestDepCachedir(t *testing.T) {
9899
testProj := integration.NewTestProject(t, initPath, wd, runMain)
99100
defer testProj.Cleanup()
100101

101-
cachedir := "/invalid/path"
102-
testProj.Setenv("DEPCACHEDIR", cachedir)
103-
wantErr := fmt.Sprintf(
104-
"dep: $DEPCACHEDIR set to an invalid or inaccessible path: %q", cachedir,
105-
)
106-
107-
// Running `dep ensure` will pull in the dependency into cachedir.
108-
err = testProj.DoRun([]string{"ensure"})
102+
var d []byte
103+
tmpFp := testProj.Path("tmp-file")
104+
ioutil.WriteFile(tmpFp, d, 0644)
105+
cases := []string{
106+
// invalid path
107+
"\000",
108+
// parent directory does not exist
109+
testProj.Path("non-existent-fldr", "cachedir"),
110+
// path is a regular file
111+
tmpFp,
112+
// invalid path, tmp-file is a regular file
113+
testProj.Path("tmp-file", "cachedir"),
114+
}
109115

110-
if err == nil {
111-
// Log the output from running `dep ensure`, could be useful.
112-
t.Logf("test run output: \n%s\n%s", testProj.GetStdout(), testProj.GetStderr())
113-
t.Error("unexpected result: \n\t(GOT) nil\n\t(WNT) exit status 1")
114-
} else if gotErr := strings.TrimSpace(testProj.GetStderr()); gotErr != wantErr {
115-
t.Errorf("unexpected error output: \n\t(GOT) %s\n\t(WNT) %s", gotErr, wantErr)
116+
wantErr := "dep: $DEPCACHEDIR set to an invalid or inaccessible path"
117+
for _, c := range cases {
118+
testProj.Setenv("DEPCACHEDIR", c)
119+
120+
err = testProj.DoRun([]string{"ensure"})
121+
122+
if err == nil {
123+
// Log the output from running `dep ensure`, could be useful.
124+
t.Logf("test run output: \n%s\n%s", testProj.GetStdout(), testProj.GetStderr())
125+
t.Error("unexpected result: \n\t(GOT) nil\n\t(WNT) exit status 1")
126+
} else if stderr := testProj.GetStderr(); !strings.Contains(stderr, wantErr) {
127+
t.Errorf(
128+
"unexpected error output: \n\t(GOT) %s\n\t(WNT) %s",
129+
strings.TrimSpace(stderr), wantErr,
130+
)
131+
}
116132
}
117133
})
118134

cmd/dep/main.go

+9-6
Original file line numberDiff line numberDiff line change
@@ -182,13 +182,16 @@ func (c *Config) Run() int {
182182
}
183183

184184
// Cachedir is loaded from env if present. `$GOPATH/pkg/dep` is used as the
185-
// fallback cache location.
185+
// default cache location.
186186
cachedir := getEnv(c.Env, "DEPCACHEDIR")
187-
if cachedir != "" && !fs.IsValidPath(cachedir) {
188-
errLogger.Printf(
189-
"dep: $DEPCACHEDIR set to an invalid or inaccessible path: %q\n", cachedir,
190-
)
191-
return errorExitCode
187+
if cachedir != "" {
188+
if err := fs.EnsureDir(cachedir, 0777); err != nil {
189+
errLogger.Printf(
190+
"dep: $DEPCACHEDIR set to an invalid or inaccessible path: %q\n", cachedir,
191+
)
192+
errLogger.Printf("dep: failed to ensure cache directory: %v\n", err)
193+
return errorExitCode
194+
}
192195
}
193196

194197
// Set up dep context.

context.go

+5-1
Original file line numberDiff line numberDiff line change
@@ -90,8 +90,12 @@ func defaultGOPATH() string {
9090
func (c *Ctx) SourceManager() (*gps.SourceMgr, error) {
9191
cachedir := c.Cachedir
9292
if cachedir == "" {
93-
// When `DEPCACHEDIR` isn't set in the env, fallback to `$GOPATH/pkg/dep`.
93+
// When `DEPCACHEDIR` isn't set in the env, use the default - `$GOPATH/pkg/dep`.
9494
cachedir = filepath.Join(c.GOPATH, "pkg", "dep")
95+
// Create the default cachedir if it does not exist.
96+
if err := os.MkdirAll(cachedir, 0777); err != nil {
97+
return nil, errors.Wrap(err, "failed to create default cache directory")
98+
}
9599
}
96100

97101
return gps.NewSourceManager(gps.SourceManagerConfig{

context_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -491,7 +491,7 @@ func TestDepCachedir(t *testing.T) {
491491
defer h.Cleanup()
492492

493493
h.TempDir("cache")
494-
// Create the directory for fallback cachedir location.
494+
// Create the directory for default cachedir location.
495495
h.TempDir(filepath.Join("go", "pkg", "dep"))
496496

497497
testCachedir := h.Path("cache")

gps/manager_test.go

+11-5
Original file line numberDiff line numberDiff line change
@@ -121,17 +121,23 @@ func TestSourceManagerInit(t *testing.T) {
121121
t.Fatalf("Global cache lock file not cleared correctly on Release()")
122122
}
123123

124+
err = os.MkdirAll(cpath, 0777)
125+
if err != nil {
126+
t.Errorf("Failed to re-create temp dir: %s", err)
127+
}
128+
defer func() {
129+
err = os.RemoveAll(cpath)
130+
if err != nil {
131+
t.Errorf("removeAll failed: %s", err)
132+
}
133+
}()
124134
// Set another one up at the same spot now, just to be sure
125135
sm, err = NewSourceManager(cfg)
126136
if err != nil {
127-
t.Errorf("Creating a second SourceManager should have succeeded when the first was released, but failed with err %s", err)
137+
t.Fatalf("Creating a second SourceManager should have succeeded when the first was released, but failed with err %s", err)
128138
}
129139

130140
sm.Release()
131-
err = os.RemoveAll(cpath)
132-
if err != nil {
133-
t.Errorf("removeAll failed: %s", err)
134-
}
135141
}
136142

137143
func TestSourceInit(t *testing.T) {

gps/source_manager.go

+2-1
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import (
2020
"time"
2121

2222
"github.com/golang/dep/gps/pkgtree"
23+
"github.com/golang/dep/internal/fs"
2324
"github.com/nightlyone/lockfile"
2425
"github.com/pkg/errors"
2526
"github.com/sdboyer/constext"
@@ -197,7 +198,7 @@ func NewSourceManager(c SourceManagerConfig) (*SourceMgr, error) {
197198
c.Logger = log.New(ioutil.Discard, "", 0)
198199
}
199200

200-
err := os.MkdirAll(filepath.Join(c.Cachedir, "sources"), 0777)
201+
err := fs.EnsureDir(filepath.Join(c.Cachedir, "sources"), 0777)
201202
if err != nil {
202203
return nil, err
203204
}

internal/fs/fs.go

+12-13
Original file line numberDiff line numberDiff line change
@@ -480,22 +480,21 @@ func cloneSymlink(sl, dst string) error {
480480
return os.Symlink(resolved, dst)
481481
}
482482

483-
// IsValidPath checks if the given string is a valid path.
484-
func IsValidPath(fp string) bool {
485-
// See https://stackoverflow.com/questions/35231846/golang-check-if-string-is-valid-path
486-
// Check if file/dir already exists
487-
if _, err := os.Stat(fp); err == nil {
488-
return true
489-
}
483+
// EnsureDir tries to ensure that a directory is present at the given path. It first
484+
// checks if the directory already exists at the given path. If there isn't one, it tries
485+
// to create it with the given permissions. However, it does not try to create the
486+
// directory recursively.
487+
func EnsureDir(path string, perm os.FileMode) error {
488+
_, err := IsDir(path)
490489

491-
// Attempt to create it
492-
var d []byte
493-
if err := ioutil.WriteFile(fp, d, 0644); err == nil {
494-
os.Remove(fp) // And delete it
495-
return true
490+
if os.IsNotExist(err) {
491+
err = os.Mkdir(path, perm)
492+
if err != nil {
493+
return errors.Wrapf(err, "failed to ensure directory at %q", path)
494+
}
496495
}
497496

498-
return false
497+
return err
499498
}
500499

501500
// IsDir determines is the path given is a directory or not.

internal/fs/fs_test.go

+28-18
Original file line numberDiff line numberDiff line change
@@ -837,28 +837,32 @@ func setupInaccessibleDir(t *testing.T, op func(dir string) error) func() {
837837
return cleanup
838838
}
839839

840-
func TestIsValidPath(t *testing.T) {
841-
wd, err := os.Getwd()
842-
if err != nil {
843-
t.Fatal(err)
844-
}
840+
func TestEnsureDir(t *testing.T) {
841+
h := test.NewHelper(t)
842+
defer h.Cleanup()
843+
h.TempDir(".")
844+
h.TempFile("file", "")
845845

846-
var dn string
846+
tmpPath := h.Path(".")
847847

848+
var dn string
848849
cleanup := setupInaccessibleDir(t, func(dir string) error {
849850
dn = filepath.Join(dir, "dir")
850851
return os.Mkdir(dn, 0777)
851852
})
852853
defer cleanup()
853854

854855
tests := map[string]bool{
855-
wd: true,
856-
filepath.Join(wd, "testdata"): true,
857-
filepath.Join(wd, "main.go"): true,
858-
filepath.Join(wd, "this_file_does_not_exist.thing"): true,
859-
dn: false,
860-
"": false,
861-
"/invalid/path": false,
856+
// [success] A dir already exists for the given path.
857+
tmpPath: true,
858+
// [success] Dir does not exist but parent dir exists, so should get created.
859+
filepath.Join(tmpPath, "testdir"): true,
860+
// [failure] Dir and parent dir do not exist, should return an error.
861+
filepath.Join(tmpPath, "notexist", "testdir"): false,
862+
// [failure] Regular file present at given path.
863+
h.Path("file"): false,
864+
// [failure] Path inaccessible.
865+
dn: false,
862866
}
863867

864868
if runtime.GOOS == "windows" {
@@ -869,11 +873,17 @@ func TestIsValidPath(t *testing.T) {
869873
delete(tests, dn)
870874
}
871875

872-
for fp, want := range tests {
873-
got := IsValidPath(fp)
874-
875-
if got != want {
876-
t.Fatalf("expected %t for %s, got %t", want, fp, got)
876+
for path, shouldEnsure := range tests {
877+
err := EnsureDir(path, 0777)
878+
if shouldEnsure {
879+
if err != nil {
880+
t.Fatalf("unexpected error %q for %q", err, path)
881+
} else if ok, err := IsDir(path); !ok {
882+
t.Fatalf("expected directory to be preset at %q", path)
883+
t.Fatal(err)
884+
}
885+
} else if err == nil {
886+
t.Fatalf("expected error for path %q, got none", path)
877887
}
878888
}
879889
}

0 commit comments

Comments
 (0)