|
package filesystem
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"path"
|
|
|
|
log "github.com/Sirupsen/logrus"
|
|
)
|
|
|
|
func CopyFile(src string, destination string) error {
|
|
log.Debugln("FileManager.copyFile:>", src, destination)
|
|
if fp, e := os.Open(src); nil != e {
|
|
log.Errorln("FileManager.copyFile:> open src file failed:", e)
|
|
return e
|
|
} else if out, e := CreateFile(destination); nil != e {
|
|
log.Errorln("FileManager.copyFile:> create file failed:", e)
|
|
return e
|
|
} else if _, e := io.Copy(out, fp); nil != e {
|
|
log.Errorln("FileManager.copyFile:> Copy failed:", e)
|
|
return e
|
|
} else {
|
|
return nil
|
|
}
|
|
}
|
|
|
|
func CreateFile(destination string) (*os.File, error) {
|
|
//destination = path.Join(fileManager.root, destination)
|
|
if _, e := os.Stat(destination); nil == e {
|
|
log.Errorln("FileManager.createFile:> target file already exists!", destination)
|
|
return nil, fmt.Errorf("target file '%s' already exists", destination)
|
|
}
|
|
dir := path.Dir(destination)
|
|
if dirInfo, e := os.Stat(dir); nil != e {
|
|
if e := os.MkdirAll(dir, 0755); nil != e {
|
|
return nil, e
|
|
}
|
|
} else if !dirInfo.IsDir() {
|
|
log.Errorln("FileManager.createFile:> target path is not a dir:", dir)
|
|
return nil, fmt.Errorf("target path '%s' is already exists and it is not a directory", dir)
|
|
}
|
|
if fp, e := os.OpenFile(destination, os.O_CREATE|os.O_WRONLY, 0644); nil != e {
|
|
log.Errorln("FileManager.createFile:> OpenFile failed:", e)
|
|
return nil, e
|
|
} else {
|
|
return fp, nil
|
|
}
|
|
}
|