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