fix(fs): copy file if symlink failed (#3368)

This commit is contained in:
NewbieOrange
2023-02-13 14:41:35 +08:00
committed by GitHub
parent e1b6368343
commit 22843ffc70
2 changed files with 24 additions and 8 deletions

View File

@ -40,7 +40,7 @@ func CopyFile(src, dst string) error {
}
// CopyDir Dir copies a whole directory recursively
func CopyDir(src string, dst string) error {
func CopyDir(src, dst string) error {
var err error
var fds []os.DirEntry
var srcinfo os.FileInfo
@ -71,6 +71,17 @@ func CopyDir(src string, dst string) error {
return nil
}
// SymlinkOrCopyFile symlinks a file or copy if symlink failed
func SymlinkOrCopyFile(src, dst string) error {
if err := CreateNestedDirectory(filepath.Dir(dst)); err != nil {
return err
}
if err := os.Symlink(src, dst); err != nil {
return CopyFile(src, dst)
}
return nil
}
// Exists determine whether the file exists
func Exists(name string) bool {
if _, err := os.Stat(name); err != nil {
@ -81,15 +92,20 @@ func Exists(name string) bool {
return true
}
// CreateNestedDirectory create nested directory
func CreateNestedDirectory(path string) error {
err := os.MkdirAll(path, 0700)
if err != nil {
log.Errorf("can't create folder, %s", err)
}
return err
}
// CreateNestedFile create nested file
func CreateNestedFile(path string) (*os.File, error) {
basePath := filepath.Dir(path)
if !Exists(basePath) {
err := os.MkdirAll(basePath, 0700)
if err != nil {
log.Errorf("can't create folder, %s", err)
return nil, err
}
if err := CreateNestedDirectory(basePath); err != nil {
return nil, err
}
return os.Create(path)
}