10
"github.com/pkg/errors"
11
"github.com/wal-g/tracelog"
14
func GetLocalFile(targetPath string, header *tar.Header) (localFile *os.File, isNewFile bool, err error) {
15
if localFileInfo, _ := GetLocalFileInfo(targetPath); localFileInfo != nil {
16
localFile, err = os.OpenFile(targetPath, os.O_RDWR, 0666)
18
localFile, err = CreateLocalFile(targetPath, header.Name)
21
return localFile, isNewFile, err
24
// get file info by file path
25
func GetLocalFileInfo(targetPath string) (fileInfo os.FileInfo, err error) {
26
info, err := os.Stat(targetPath)
27
if os.IsNotExist(err) {
31
return nil, errors.New("requested file is directory. Aborting")
36
// create new local file on disk
37
func CreateLocalFile(targetPath, name string) (*os.File, error) {
38
err := CreateParentDirs(name, targetPath)
40
return nil, errors.Wrap(err, "failed to create all directories")
42
file, err := os.OpenFile(targetPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
44
return nil, errors.Wrapf(err, "failed to create new file: '%s'", targetPath)
49
// creates parent dirs of the file
50
func CreateParentDirs(fileName string, targetPath string) error {
51
if fileName == targetPath {
52
return nil // because it runs in the local directory
54
base := filepath.Base(fileName)
55
dir := strings.TrimSuffix(targetPath, base)
56
err := os.MkdirAll(dir, 0755)
60
func WriteLocalFile(fileReader io.Reader, header *tar.Header, localFile *os.File, fsync bool) error {
61
_, err := io.Copy(localFile, fileReader)
63
err1 := os.Remove(localFile.Name())
65
tracelog.ErrorLogger.Fatalf("failed to remove localFile '%s' because of error: %v",
66
localFile.Name(), err1)
68
return errors.Wrap(err, "copy failed")
71
mode := os.FileMode(header.Mode)
72
if err = localFile.Chmod(mode); err != nil {
73
return errors.Wrap(err, "chmod failed")
77
err = localFile.Sync()
78
return errors.Wrap(err, "fsync failed")
84
func IsDirectoryEmpty(directoryPath string) (bool, error) {
87
searchLambda := func(path string, info os.FileInfo, err error) error {
88
if path != directoryPath {
90
tracelog.InfoLogger.Printf("found file '%s' in directory: '%s'\n", path, directoryPath)
94
err := filepath.Walk(directoryPath, searchLambda)
95
return isEmpty, errors.Wrapf(err, "can't check, that directory: '%s' is empty", directoryPath)