@@ -27,24 +27,37 @@ func NewCacheDirectory(path string) CacheDirectory {
27
27
}
28
28
}
29
29
30
- func isEmptyOrNonExistentDirectory (path string ) (bool , error ) {
31
- f , err := os .Open (path )
30
+ func isAccessibleDirectory (path string ) (bool , error ) {
31
+ _ , err := os .Stat (path )
32
+
32
33
if err != nil {
33
34
if os .IsNotExist (err ) {
34
- return true , nil
35
+ return false , nil
35
36
}
36
37
return false , errors .Wrapf (err , "Could not access directory %s." , path )
37
38
}
38
- defer f .Close ()
39
+
40
+ return true , nil
41
+ }
39
42
40
- _ , err = f .Readdirnames (1 )
43
+ func isEmptyDirectory (path string ) (bool , error ) {
44
+ files , err := ioutil .ReadDir (path )
41
45
if err != nil {
42
- if err == io .EOF {
43
- return true , nil
44
- }
45
46
return false , errors .Wrapf (err , "Could not read contents of directory %s." , path )
46
47
}
47
- return false , nil
48
+
49
+ return len (files ) == 0 , nil
50
+ }
51
+
52
+ func existsDirectory (path string ) (bool , error ) {
53
+ _ , err := os .Stat (path )
54
+ if os .IsNotExist (err ) {
55
+ return false , nil
56
+ }
57
+ if err != nil {
58
+ return false , errors .Wrapf (err , "Could not access directory %s." , path )
59
+ }
60
+ return true , nil
48
61
}
49
62
50
63
func (cacheDirectory * CacheDirectory ) CheckOrCreateVersionFile (pull bool , version string ) error {
@@ -77,20 +90,37 @@ func (cacheDirectory *CacheDirectory) CheckOrCreateVersionFile(pull bool, versio
77
90
}
78
91
}
79
92
80
- isEmptyOrNonExistent , err := isEmptyOrNonExistentDirectory (cacheDirectory .path )
93
+ existsDirectory , err := existsDirectory (cacheDirectory .path )
81
94
if err != nil {
82
95
return err
83
96
}
84
- if isEmptyOrNonExistent {
97
+ if ! existsDirectory {
85
98
err := os .Mkdir (cacheDirectory .path , 0755 )
86
99
if err != nil {
87
100
return errors .Wrap (err , "Could not create cache directory." )
88
101
}
89
- err = ioutil .WriteFile (cacheVersionFilePath , []byte (version ), 0644 )
102
+
103
+ } else {
104
+ isAccessible , err := isAccessibleDirectory (cacheDirectory .path )
105
+ if err != nil {
106
+ return err
107
+ }
108
+ if ! isAccessible {
109
+ return errors .Wrap (err , "Cache dir exists, but the current user can't write to it." )
110
+ }
111
+
112
+ isEmpty , err := isEmptyDirectory (cacheDirectory .path )
90
113
if err != nil {
91
- return errors .Wrap (err , "Could not create cache version file." )
114
+ return err
115
+ }
116
+ if isEmpty {
117
+ err = ioutil .WriteFile (cacheVersionFilePath , []byte (version ), 0644 )
118
+ if err != nil {
119
+ return errors .Wrap (err , "Could not create cache version file." )
120
+ }
92
121
}
93
122
return nil
123
+
94
124
}
95
125
return usererrors .New (errorNotACacheOrEmpty )
96
126
}
0 commit comments