From 4fb6d689534471f9f6bb8f41f54a42f46b358bd1 Mon Sep 17 00:00:00 2001 From: chengsiyuan Date: Tue, 19 Nov 2024 13:13:05 +0800 Subject: [PATCH] print Dir Files and Subdirectories when upload pair is Dir. --- cmd/upload.go | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/cmd/upload.go b/cmd/upload.go index c232fad..d2878c7 100644 --- a/cmd/upload.go +++ b/cmd/upload.go @@ -79,7 +79,9 @@ var uplaodCmd = &cobra.Command{ } else { info, _ := os.Stat(absLocalFilePath) if info.IsDir() { - log.DefaultLogger(log.LogLevelInfo, "Upload Dir Success: %s", UploadFile.RemotePath) + // 统计文件和子文件夹数量 + fileCount, dirCount := countFilesAndDirs(absLocalFilePath) + log.DefaultLogger(log.LogLevelInfo, "Upload Dir Success: %s, Files: %d, Subdirectories: %d", UploadFile.RemotePath, fileCount, dirCount) } else { log.DefaultLogger(log.LogLevelInfo, "Upload File Success: %s", UploadFile.RemotePath) } @@ -89,6 +91,33 @@ var uplaodCmd = &cobra.Command{ }, } +// countFilesAndDirs 递归统计文件和子文件夹数量 +func countFilesAndDirs(dirPath string) (int, int) { + var fileCount, dirCount int + + err := filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error { + if err != nil { + // 忽略单个文件/文件夹的错误 + log.DefaultLogger(log.LogLevelWarn, "Error accessing %s: %v", path, err) + return nil + } + + if info.IsDir() { + dirCount++ + } else { + fileCount++ + } + return nil + }) + + if err != nil { + log.DefaultLogger(log.LogLevelError, "Error walking the directory %s: %v", dirPath, err) + } + + // 返回文件数和子文件夹数 + return fileCount, dirCount - 1 // 减去根目录本身 +} + func init() { RootCmd.AddCommand(uplaodCmd)