@@ -2,7 +2,6 @@ package cachedirectory
22
33import (
44 usererrors "errors"
5- "io"
65 "io/ioutil"
76 "os"
87 "path"
@@ -27,24 +26,37 @@ func NewCacheDirectory(path string) CacheDirectory {
2726 }
2827}
2928
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+
3232 if err != nil {
3333 if os .IsNotExist (err ) {
34- return true , nil
34+ return false , nil
3535 }
3636 return false , errors .Wrapf (err , "Could not access directory %s." , path )
3737 }
38- defer f .Close ()
3938
40- _ , err = f .Readdirnames (1 )
39+ return true , nil
40+ }
41+
42+ func isEmptyDirectory (path string ) (bool , error ) {
43+ files , err := ioutil .ReadDir (path )
4144 if err != nil {
42- if err == io .EOF {
43- return true , nil
44- }
4545 return false , errors .Wrapf (err , "Could not read contents of directory %s." , path )
4646 }
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
4860}
4961
5062func (cacheDirectory * CacheDirectory ) CheckOrCreateVersionFile (pull bool , version string ) error {
@@ -77,15 +89,30 @@ func (cacheDirectory *CacheDirectory) CheckOrCreateVersionFile(pull bool, versio
7789 }
7890 }
7991
80- isEmptyOrNonExistent , err := isEmptyOrNonExistentDirectory (cacheDirectory .path )
92+ existsDirectory , err := existsDirectory (cacheDirectory .path )
8193 if err != nil {
8294 return err
8395 }
84- if isEmptyOrNonExistent {
96+ if ! existsDirectory {
8597 err := os .Mkdir (cacheDirectory .path , 0755 )
8698 if err != nil {
8799 return errors .Wrap (err , "Could not create cache directory." )
88100 }
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 {
89116 err = ioutil .WriteFile (cacheVersionFilePath , []byte (version ), 0644 )
90117 if err != nil {
91118 return errors .Wrap (err , "Could not create cache version file." )
0 commit comments