2013-02-20 23:43:01 -05:00
|
|
|
package util
|
2013-02-18 20:44:00 -05:00
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
"io/ioutil"
|
|
|
|
"os"
|
|
|
|
"path"
|
2013-08-13 23:12:08 -04:00
|
|
|
"syscall"
|
2013-02-18 20:44:00 -05:00
|
|
|
)
|
|
|
|
|
2013-02-20 23:43:01 -05:00
|
|
|
func EnsureDirExists(dir string) error {
|
2013-02-18 20:44:00 -05:00
|
|
|
_, err := os.Lstat(dir)
|
|
|
|
if err != nil {
|
2013-08-14 22:59:40 -04:00
|
|
|
var fi os.FileInfo
|
|
|
|
curDir := dir
|
|
|
|
for dir != "" && err != nil {
|
|
|
|
curDir = path.Dir(curDir)
|
|
|
|
fi, err = os.Lstat(curDir)
|
|
|
|
}
|
2013-02-18 20:44:00 -05:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2013-08-14 22:59:40 -04:00
|
|
|
err = os.MkdirAll(dir, fi.Mode().Perm())
|
2013-02-18 20:44:00 -05:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2013-08-28 23:05:28 -04:00
|
|
|
func FileExistsAndHasPermissions(file string, mode os.FileMode) bool {
|
|
|
|
info, err := os.Stat(file)
|
|
|
|
if err != nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return info.Mode().Perm() == mode
|
|
|
|
}
|
|
|
|
|
2013-08-14 22:59:40 -04:00
|
|
|
//TODO maybe this shouldn't fail silently?
|
|
|
|
func RecursiveRemoveEmptyDirs(dir string) {
|
|
|
|
var err error = nil
|
|
|
|
curDir := dir
|
|
|
|
for err == nil {
|
|
|
|
err = os.Remove(curDir)
|
|
|
|
curDir = path.Dir(curDir)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-09-09 22:59:18 -04:00
|
|
|
func CopyReaderToTmp(src io.Reader, tmpdir string) (string, error) {
|
|
|
|
outfile, err := ioutil.TempFile(tmpdir, "asink")
|
2013-02-18 20:44:00 -05:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2013-09-09 22:59:18 -04:00
|
|
|
defer outfile.Close()
|
2013-02-18 20:44:00 -05:00
|
|
|
|
2013-09-09 22:59:18 -04:00
|
|
|
_, err = io.Copy(outfile, src)
|
2013-02-18 20:44:00 -05:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
2013-09-09 22:59:18 -04:00
|
|
|
return outfile.Name(), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func CopyToTmp(src string, tmpdir string) (string, error) {
|
|
|
|
infile, err := os.Open(src)
|
2013-02-18 20:44:00 -05:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2013-09-09 22:59:18 -04:00
|
|
|
defer infile.Close()
|
2013-02-18 20:44:00 -05:00
|
|
|
|
2013-09-09 22:59:18 -04:00
|
|
|
return CopyReaderToTmp(infile, tmpdir)
|
2013-02-18 20:44:00 -05:00
|
|
|
}
|
2013-08-13 23:12:08 -04:00
|
|
|
|
|
|
|
func ErrorFileNotFound(err error) bool {
|
|
|
|
if e, ok := err.(*os.PathError); ok && e.Err == syscall.ENOENT {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|