-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #31 from Ccheers/dev
feat(xfs): xfs 包 用于处理文件系统业务, 目前支持文件拷贝 & 文件夹递归拷贝
- Loading branch information
Showing
2 changed files
with
105 additions
and
50 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,92 @@ | ||
package xfs | ||
|
||
import ( | ||
"fmt" | ||
"io" | ||
"os" | ||
"path/filepath" | ||
) | ||
|
||
// CopyDirectory 递归地复制整个目录 | ||
func CopyDirectory(src string, dst string) error { | ||
src = filepath.Clean(src) | ||
dst = filepath.Clean(dst) | ||
|
||
si, err := os.Stat(src) | ||
if err != nil { | ||
return err | ||
} | ||
if !si.IsDir() { | ||
return fmt.Errorf("source is not a directory") | ||
} | ||
|
||
_, err = os.Stat(dst) | ||
if err != nil && !os.IsNotExist(err) { | ||
return err | ||
} | ||
|
||
err = os.MkdirAll(dst, si.Mode()) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
entries, err := os.ReadDir(src) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
for _, entry := range entries { | ||
srcPath := filepath.Join(src, entry.Name()) | ||
dstPath := filepath.Join(dst, entry.Name()) | ||
|
||
if entry.IsDir() { | ||
err = CopyDirectory(srcPath, dstPath) | ||
if err != nil { | ||
return err | ||
} | ||
} else { | ||
// 跳过符号链接 | ||
if entry.Type()&os.ModeSymlink != 0 { | ||
continue | ||
} | ||
|
||
err = CopyFile(srcPath, dstPath) | ||
if err != nil { | ||
return err | ||
} | ||
} | ||
} | ||
|
||
return nil | ||
} | ||
|
||
// CopyFile 复制单个文件 | ||
func CopyFile(src, dst string) error { | ||
sourceFileStat, err := os.Stat(src) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
if !sourceFileStat.Mode().IsRegular() { | ||
return fmt.Errorf("%s is not a regular file", src) | ||
} | ||
|
||
source, err := os.Open(src) | ||
if err != nil { | ||
return err | ||
} | ||
defer source.Close() | ||
|
||
destination, err := os.Create(dst) | ||
if err != nil { | ||
return err | ||
} | ||
defer destination.Close() | ||
|
||
_, err = io.Copy(destination, source) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
return os.Chmod(dst, sourceFileStat.Mode()) | ||
} |