wal-g

Форк
0
/
local_file_helpers.go 
96 строк · 2.6 Кб
1
package utility
2

3
import (
4
	"archive/tar"
5
	"io"
6
	"os"
7
	"path/filepath"
8
	"strings"
9

10
	"github.com/pkg/errors"
11
	"github.com/wal-g/tracelog"
12
)
13

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)
17
	} else {
18
		localFile, err = CreateLocalFile(targetPath, header.Name)
19
		isNewFile = true
20
	}
21
	return localFile, isNewFile, err
22
}
23

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) {
28
		return nil, err
29
	}
30
	if info.IsDir() {
31
		return nil, errors.New("requested file is directory. Aborting")
32
	}
33
	return info, nil
34
}
35

36
// create new local file on disk
37
func CreateLocalFile(targetPath, name string) (*os.File, error) {
38
	err := CreateParentDirs(name, targetPath)
39
	if err != nil {
40
		return nil, errors.Wrap(err, "failed to create all directories")
41
	}
42
	file, err := os.OpenFile(targetPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
43
	if err != nil {
44
		return nil, errors.Wrapf(err, "failed to create new file: '%s'", targetPath)
45
	}
46
	return file, nil
47
}
48

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
53
	}
54
	base := filepath.Base(fileName)
55
	dir := strings.TrimSuffix(targetPath, base)
56
	err := os.MkdirAll(dir, 0755)
57
	return err
58
}
59

60
func WriteLocalFile(fileReader io.Reader, header *tar.Header, localFile *os.File, fsync bool) error {
61
	_, err := io.Copy(localFile, fileReader)
62
	if err != nil {
63
		err1 := os.Remove(localFile.Name())
64
		if err1 != nil {
65
			tracelog.ErrorLogger.Fatalf("failed to remove localFile '%s' because of error: %v",
66
				localFile.Name(), err1)
67
		}
68
		return errors.Wrap(err, "copy failed")
69
	}
70

71
	mode := os.FileMode(header.Mode)
72
	if err = localFile.Chmod(mode); err != nil {
73
		return errors.Wrap(err, "chmod failed")
74
	}
75

76
	if fsync {
77
		err = localFile.Sync()
78
		return errors.Wrap(err, "fsync failed")
79
	}
80

81
	return nil
82
}
83

84
func IsDirectoryEmpty(directoryPath string) (bool, error) {
85
	var isEmpty = true
86

87
	searchLambda := func(path string, info os.FileInfo, err error) error {
88
		if path != directoryPath {
89
			isEmpty = false
90
			tracelog.InfoLogger.Printf("found file '%s' in directory: '%s'\n", path, directoryPath)
91
		}
92
		return nil
93
	}
94
	err := filepath.Walk(directoryPath, searchLambda)
95
	return isEmpty, errors.Wrapf(err, "can't check, that directory: '%s' is empty", directoryPath)
96
}
97

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.