文件打包与敏感信息扫描工具架构设计与实现分析
工具架构设计主要包含这4个模块入口层 (main.go) - CLI命令行界面,使用Cobra框架命令层 (cmd/) - 各个子命令的具体实现业务层 (internal/) - 核心业务逻辑模块工具层 - 日志、文件操作等基础设施入口层设计Main.go代码分析核心逻辑在 PackFiles() 和 Search() 两个方法(位于 internal/ 包),主程序只是 CLI 封装。最完整的是
工具架构设计
主要包含这4个模块
入口层 (main.go) - CLI命令行界面,使用Cobra框架
命令层 (cmd/) - 各个子命令的具体实现
业务层 (internal/) - 核心业务逻辑模块
工具层 - 日志、文件操作等基础设施
file-packer-tool/
├── main.go # 程序入口,CLI命令定义
├── cmd/ # 子命令实现
│ ├── pack.go # 打包命令 ✅
│ ├── info.go # 文件信息命令 ✅
│ ├── extract.go # 解压命令 (占位)
│ └── list.go # 列表命令 (占位)
└── internal/ # 内部模块
├── fileops/ # 文件操作核心
│ ├── packer.go # 文件打包器
│ └── stream_reader.go # 文件流读取器
├── logger/ # 日志模块
│ └── logger.go # 简单日志实现
└── search/ # 搜索模块
└── searcher.go # 文件搜索器
入口层设计
Main.go
代码分析
核心逻辑在 PackFiles() 和 Search() 两个方法(位于 internal/ 包),主程序只是 CLI 封装。
最完整的是 search,最有用的是 pack,但都存在小缺陷(如 GZIP 多文件、密码明文)。
package main
import (
"context"
"errors"
"fmt"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/spf13/cobra"
"file-packer-tool/internal/fileops"
"file-packer-tool/internal/logger"
"file-packer-tool/internal/search"
)
func main() {
var rootCmd = &cobra.Command{
Use: "filepacker",
Short: "高级文件打包压缩工具",
Long: `
╔══════════════════════════════════════════════════════════════════════════════╗
║ 高级文件打包压缩工具 v1.0.0 ║
║ ║
║ 功能特性: ║
║ • 支持多种压缩格式 (ZIP, GZIP) ║
║ • 智能处理被占用的文件 ║
║ • 高级文件过滤和排除规则 ║
║ • 全局敏感文件搜索 ║
║ ║
║ 支持的操作: ║
║ • pack - 打包压缩文件和目录 ║
║ • info - 获取文件详细信息 ║
║ • search - 全局搜索敏感文件 ║
║ • extract - 解压缩文件 ║
║ • list - 列出压缩包内容 ║
║ ║
║ 使用示例: ║
║ filepacker pack ./logs --output logs.zip --format zip ║
║ filepacker pack C:\\Project --recursive --exclude "*.tmp" ║
║ filepacker info C:\\Windows\\System32\\kernel32.dll ║
║ filepacker search C:\\ --sensitive --extensions .txt,.doc,.pdf ║
║ ║
╚══════════════════════════════════════════════════════════════════════════════╝
`,
Run: func(cmd *cobra.Command, args []string) {
cmd.Help()
},
}
rootCmd.AddCommand(NewPackCommand())
rootCmd.AddCommand(NewInfoCommand())
rootCmd.AddCommand(NewSearchCommand())
rootCmd.AddCommand(NewExtractCommand())
rootCmd.AddCommand(NewListCommand())
if err := rootCmd.Execute(); err != nil {
fmt.Printf("执行失败: %v\n", err)
os.Exit(1)
}
}
func NewPackCommand() *cobra.Command {
var (
output string
format string
compressionLevel int
include []string
exclude []string
maxFileSize int64
maxTotalSize int64
recursive bool
followSymlinks bool
preservePaths bool
password string
excludeLargeFiles bool
largeFileThreshold int64
showSkipped bool
)
cmd := &cobra.Command{
Use: "pack [files/directories...]",
Short: "打包压缩文件和目录",
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
finalMaxFileSize := maxFileSize
if excludeLargeFiles && maxFileSize == 0 {
finalMaxFileSize = largeFileThreshold
}
log := logger.New()
packer := fileops.NewFilePacker(log)
fmt.Println("开始文件打包...")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
go func() { <-sig; fmt.Println("中断,正在停止..."); cancel() }()
result, err := packer.PackFiles(ctx, args, fileops.PackOptions{
OutputPath: output,
Format: format,
CompressionLevel: compressionLevel,
IncludePatterns: include,
ExcludePatterns: exclude,
MaxFileSize: finalMaxFileSize,
MaxTotalSize: maxTotalSize,
Recursive: recursive,
FollowSymlinks: followSymlinks,
PreservePaths: preservePaths,
Password: password,
})
if err != nil {
fmt.Printf("打包失败: %v\n", err)
return err
}
fmt.Println("文件打包完成!")
fmt.Printf("处理文件: %d 个\n", result.TotalFiles)
fmt.Printf("原始大小: %s\n", formatFileSize(result.TotalSize))
fmt.Printf("压缩大小: %s\n", formatFileSize(result.CompressedSize))
fmt.Printf("压缩比: %.2f%%\n", result.CompressionRatio*100)
fmt.Printf("处理时间: %s\n", result.Duration.String())
if len(result.SkippedFiles) > 0 {
fmt.Printf("跳过了 %d 个文件\n", len(result.SkippedFiles))
if showSkipped {
for _, s := range result.SkippedFiles {
fmt.Printf("- %s (%s): %s\n", s.Path, formatFileSize(s.Size), s.Reason)
}
}
}
fmt.Printf("输出文件: %s\n", result.OutputPath)
return nil
},
}
cmd.Flags().StringVarP(&output, "output", "o", "", "输出文件路径")
cmd.Flags().StringVarP(&format, "format", "f", "zip", "压缩格式 (zip, gzip)")
cmd.Flags().IntVar(&compressionLevel, "compression", 6, "压缩级别 (1-9)")
cmd.Flags().StringSliceVar(&include, "include", []string{}, "包含文件模式")
cmd.Flags().StringSliceVar(&exclude, "exclude", []string{}, "排除文件模式")
cmd.Flags().Int64Var(&maxFileSize, "max-file-size", 0, "单个文件最大大小 (字节)")
cmd.Flags().Int64Var(&maxTotalSize, "max-total-size", 0, "总大小限制 (字节)")
cmd.Flags().BoolVar(&excludeLargeFiles, "exclude-large", false, "自动排除大文件")
cmd.Flags().Int64Var(&largeFileThreshold, "large-threshold", 100*1024*1024, "大文件阈值")
cmd.Flags().BoolVarP(&recursive, "recursive", "r", true, "递归处理目录")
cmd.Flags().BoolVar(&followSymlinks, "follow-symlinks", false, "跟随符号链接")
cmd.Flags().BoolVar(&preservePaths, "preserve-paths", true, "保留完整路径")
cmd.Flags().StringVar(&password, "password", "", "密码保护 (ZIP格式)")
cmd.Flags().BoolVar(&showSkipped, "show-skipped", false, "显示跳过文件")
return cmd
}
func NewInfoCommand() *cobra.Command {
var (
showProcesses bool
tryAllMethods bool
)
cmd := &cobra.Command{
Use: "info [file]",
Short: "获取文件流信息",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
log := logger.New()
packer := fileops.NewFilePacker(log)
info, err := packer.GetFileStreamInfo(args[0])
if err != nil {
fmt.Printf("获取文件信息失败: %v\n", err)
return err
}
fmt.Printf("文件路径: %s\n", info.Path)
fmt.Printf("文件大小: %s\n", formatFileSize(info.Size))
fmt.Printf("访问方法: %s\n", info.AccessMethod)
_ = showProcesses
_ = tryAllMethods
return nil
},
}
cmd.Flags().BoolVar(&showProcesses, "processes", false, "显示占用进程信息")
cmd.Flags().BoolVar(&tryAllMethods, "all-methods", false, "测试所有访问方法")
return cmd
}
func NewSearchCommand() *cobra.Command {
var (
extensions []string
keywords []string
sensitive bool
recursive bool
maxDepth int
fileSizeLimit int64
outputFile string
showContent bool
contentPreview int
excludeDirs []string
includeDirs []string
timeRange string
regexPattern string
)
cmd := &cobra.Command{
Use: "search [directory]",
Short: "全局搜索敏感文件",
Long: `
全局搜索敏感文件 - 支持多种搜索模式和敏感信息检测
功能特性:
- 文件扩展名过滤
- 关键词内容搜索
- 敏感信息模式识别
- 正则表达式匹配
- 递归深度控制
- 文件大小限制
- 时间范围过滤
- 目录包含/排除规则
- 内容预览和导出
敏感信息类型:
- 密码和密钥文件
- 配置文件
- 日志文件
- 数据库文件
- 备份文件
- 临时文件
- 系统文件
示例:
# 搜索所有文本文件
filepacker search C:\\ --extensions .txt,.log,.ini
# 搜索包含关键词的文件
filepacker search C:\\Project --keywords password,secret,key
# 敏感文件搜索
filepacker search C:\\ --sensitive --recursive
# 正则表达式搜索
filepacker search C:\\ --regex "password.*=.*[a-zA-Z0-9]{8,}"
# 导出搜索结果
filepacker search C:\\ --sensitive --output results.txt
`,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
searchDir := args[0]
log := logger.New()
// 创建搜索器
searcher := search.NewFileSearcher(log, search.FileSearchOptions{
Extensions: extensions,
Keywords: keywords,
Sensitive: sensitive,
Recursive: recursive,
MaxDepth: maxDepth,
FileSizeLimit: fileSizeLimit,
OutputFile: outputFile,
ShowContent: showContent,
ContentPreview: contentPreview,
ExcludeDirs: excludeDirs,
IncludeDirs: includeDirs,
TimeRange: timeRange,
RegexPattern: regexPattern,
})
fmt.Printf("开始搜索目录: %s\n", searchDir)
fmt.Printf("搜索模式: %s\n", getSearchModeDescription(search.FileSearchOptions{
Extensions: extensions,
Keywords: keywords,
Sensitive: sensitive,
Recursive: recursive,
MaxDepth: maxDepth,
FileSizeLimit: fileSizeLimit,
OutputFile: outputFile,
ShowContent: showContent,
ContentPreview: contentPreview,
ExcludeDirs: excludeDirs,
IncludeDirs: includeDirs,
TimeRange: timeRange,
RegexPattern: regexPattern,
}))
// 创建上下文和信号处理
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-sig
fmt.Println("\n收到中断信号,正在停止搜索...")
cancel()
}()
// 执行搜索
start := time.Now()
results, err := searcher.Search(ctx, searchDir)
if err != nil {
fmt.Printf("搜索失败: %v\n", err)
return err
}
duration := time.Since(start)
fmt.Printf("\n搜索完成! 耗时: %s\n", duration.String())
fmt.Printf("找到文件: %d 个\n", len(results))
// 显示结果
if len(results) > 0 {
searcher.DisplayResults(results)
if outputFile != "" {
if err := searcher.ExportResults(results, outputFile); err != nil {
fmt.Printf("导出结果失败: %v\n", err)
} else {
fmt.Printf("结果已导出到: %s\n", outputFile)
}
}
}
return nil
},
}
// 搜索选项
cmd.Flags().StringSliceVar(&extensions, "extensions", []string{}, "文件扩展名过滤 (如: .txt,.doc,.pdf)")
cmd.Flags().StringSliceVar(&keywords, "keywords", []string{}, "关键词搜索 (如: password,secret,key)")
cmd.Flags().BoolVar(&sensitive, "sensitive", false, "启用敏感信息检测")
cmd.Flags().BoolVarP(&recursive, "recursive", "r", true, "递归搜索子目录")
cmd.Flags().IntVar(&maxDepth, "max-depth", 10, "最大递归深度")
cmd.Flags().Int64Var(&fileSizeLimit, "file-size-limit", 10*1024*1024, "文件大小限制 (字节)")
// 输出选项
cmd.Flags().StringVar(&outputFile, "output", "", "导出结果到文件")
cmd.Flags().BoolVar(&showContent, "show-content", false, "显示文件内容预览")
cmd.Flags().IntVar(&contentPreview, "content-preview", 200, "内容预览字符数")
// 过滤选项
cmd.Flags().StringSliceVar(&excludeDirs, "exclude-dirs", []string{}, "排除的目录")
cmd.Flags().StringSliceVar(&includeDirs, "include-dirs", []string{}, "包含的目录")
cmd.Flags().StringVar(&timeRange, "time-range", "", "时间范围过滤 (如: 7d, 1m, 2023-01-01:2023-12-31)")
cmd.Flags().StringVar(®exPattern, "regex", "", "正则表达式模式")
return cmd
}
func NewExtractCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "extract [archive]",
Short: "解压缩文件 (占位)",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return errors.New("extract 功能暂未实现")
},
}
return cmd
}
func NewListCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "list [archive]",
Short: "列出压缩包内容 (占位)",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return errors.New("list 功能暂未实现")
},
}
return cmd
}
func formatFileSize(size int64) string {
const unit = 1024
if size < unit {
return fmt.Sprintf("%d B", size)
}
div, exp := int64(unit), 0
for n := size / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %cB", float64(size)/float64(div), "KMGTPE"[exp])
}
// getSearchModeDescription 获取搜索模式描述
func getSearchModeDescription(options search.FileSearchOptions) string {
var modes []string
if len(options.Extensions) > 0 {
modes = append(modes, fmt.Sprintf("扩展名过滤(%s)", strings.Join(options.Extensions, ",")))
}
if len(options.Keywords) > 0 {
modes = append(modes, fmt.Sprintf("关键词搜索(%s)", strings.Join(options.Keywords, ",")))
}
if options.Sensitive {
modes = append(modes, "敏感文件检测")
}
if options.RegexPattern != "" {
modes = append(modes, "正则表达式匹配")
}
if options.Recursive {
modes = append(modes, "递归搜索")
}
if len(modes) == 0 {
return "默认搜索模式"
}
return strings.Join(modes, ", ")
}
命令功能模块设计
packer.go
代码分析:
PackFiles() 确实是总入口,负责格式判断、路径处理、调用具体打包函数,并汇总结果(文件数、大小、耗时等),也正确处理了 GZIP 仅支持单文件的限制,并支持 Ctrl+C 中断。
createZipArchive() 和 addToZip() 实现了 ZIP 的递归打包、过滤、大文件跳过、符号链接控制,对被占用文件有兜底尝试(虽然 openLockedFile 未在此定义,但调用逻辑存在),并用互斥锁保护共享状态,线程安全。
createGzipArchive() 明确只处理单个文件,符合 GZIP 规范,同样尝试处理被占用文件,输出文件名由用户指定(因 GZIP 不存储原始文件名)。
shouldExclude() / shouldInclude() 使用 filepath.Match 同时匹配文件名和完整路径,使通配符规则(如 *.tmp 或 C:\temp\*.log)能正常工作,逻辑合理。

logger.go
代码分析:
- 定义了 Info、Error、Debug 三个方法,都直接用 fmt.Println 打印。
- 每条日志前面加了级别(如 [INFO])和当前时间(时:分:秒)。
- 调用时可以附带 key-value 字段,比如
Info("start", "files", 10)。
问题:
- 字段会原样打印成数组形式,比如
[files 10],看着乱,也不好读。 - 没有日志级别开关,Debug 日志没法关闭,总会输出。
- 所有日志都打到控制台,不能写文件或关掉。

searcher.go


代码分析:
通过文件名、扩展名、路径是否包含关键词(如 password、.env、System32)来判断是否敏感,并给每个文件打分,分数高的列入结果。支持按大小、时间、目录深度过滤,也能跳过系统目录和用户指定的排除目录。
结果可以显示在终端或导出到文本文件,还能预览文件开头内容。
问题:
- 不搜索文件内容,只看文件名和路径;
- 读文件内容的逻辑有 bug(用
ReadString(0)会提前结束); - 时间范围解析错误(比如 “7d” 被当成 7 小时);
- 隐藏文件处理简单(只跳过以 . 开头的)。
stream_reader.go

代码分析
它按顺序试四种方法:
- 用 Windows API 以共享模式打开;
- 用系统备份权限打开;
- 从系统卷影副本(如还原点)里找文件;
- 用内存映射方式读。

pack.go
代码分析:
用户可以指定输出路径、压缩格式、排除/包含哪些文件、跳过大文件等。程序会显示处理了多少文件、压缩前后的大小、耗时等信息。如果按 Ctrl+C,会尝试安全中断。

info.go
代码分析:
代码实现了 info 命令,用来查看一个文件的基本信息,比如路径、大小,以及程序是用哪种方式读到它的(比如普通读取、备份权限、卷影副本等)。
它调用了底层的 GetFileStreamInfo 函数,能检测文件是否被占用,并尝试用不同方法读取。

extract.go
实现 extract 命令的基本功能
package main
import (
"archive/zip"
"compress/gzip"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/spf13/cobra"
)
func NewExtractCommand() *cobra.Command {
var outputDir string
cmd := &cobra.Command{
Use: "extract [archive]",
Short: "解压缩文件",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
archivePath := args[0]
// 自动推断输出目录
if outputDir == "" {
ext := filepath.Ext(archivePath)
base := strings.TrimSuffix(archivePath, ext)
if ext == ".gz" && len(filepath.Ext(base)) > 0 {
// 处理 .tar.gz 情况,但这里简化为去掉 .gz
base = strings.TrimSuffix(base, filepath.Ext(base))
}
outputDir = base + "_extracted"
}
// 创建输出目录
if err := os.MkdirAll(outputDir, 0755); err != nil {
return fmt.Errorf("创建输出目录失败: %w", err)
}
// 判断格式并解压
lowerName := strings.ToLower(archivePath)
switch {
case strings.HasSuffix(lowerName, ".zip"):
return extractZip(archivePath, outputDir)
case strings.HasSuffix(lowerName, ".gz"):
return extractGzip(archivePath, outputDir)
default:
return errors.New("不支持的压缩格式,仅支持 .zip 和 .gz")
}
},
}
cmd.Flags().StringVarP(&outputDir, "output", "o", "", "解压到指定目录(默认为 原文件名_extracted)")
return cmd
}
// 解压 ZIP 文件
func extractZip(zipPath, dest string) error {
r, err := zip.OpenReader(zipPath)
if err != nil {
return fmt.Errorf("打开 ZIP 文件失败: %w", err)
}
defer r.Close()
for _, f := range r.File {
fPath := filepath.Join(dest, f.Name)
// 防止路径穿越(安全)
if !strings.HasPrefix(fPath, filepath.Clean(dest)+string(os.PathSeparator)) {
return fmt.Errorf("非法文件路径: %s", f.Name)
}
if f.FileInfo().IsDir() {
os.MkdirAll(fPath, f.Mode())
continue
}
// 创建父目录
if err := os.MkdirAll(filepath.Dir(fPath), 0755); err != nil {
return err
}
src, err := f.Open()
if err != nil {
return fmt.Errorf("打开压缩项失败 %s: %w", f.Name, err)
}
dst, err := os.OpenFile(fPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, f.Mode())
if err != nil {
src.Close()
return err
}
_, err = io.Copy(dst, src)
src.Close()
dst.Close()
if err != nil {
return fmt.Errorf("写入文件失败 %s: %w", f.Name, err)
}
}
fmt.Printf("ZIP 解压完成: %s -> %s\n", zipPath, dest)
return nil
}
// 解压 GZIP 文件(仅单文件)
func extractGzip(gzPath, destDir string) error {
gzFile, err := os.Open(gzPath)
if err != nil {
return fmt.Errorf("打开 GZ 文件失败: %w", err)
}
defer gzFile.Close()
gzReader, err := gzip.NewReader(gzFile)
if err != nil {
return fmt.Errorf("创建 GZIP 读取器失败: %w", err)
}
defer gzReader.Close()
// 输出文件名:去掉 .gz 后缀
baseName := filepath.Base(gzPath)
outputName := strings.TrimSuffix(baseName, ".gz")
if outputName == baseName {
outputName += "_uncompressed"
}
outputPath := filepath.Join(destDir, outputName)
outFile, err := os.Create(outputPath)
if err != nil {
return fmt.Errorf("创建输出文件失败: %w", err)
}
defer outFile.Close()
_, err = io.Copy(outFile, gzReader)
if err != nil {
return fmt.Errorf("解压数据失败: %w", err)
}
fmt.Printf("GZIP 解压完成: %s -> %s\n", gzPath, outputPath)
return nil
}list.go
代码分析:
- 支持 ZIP 和 GZIP 两种格式,通过文件后缀判断。
- ZIP 列表:用
zip.OpenReader读取压缩包内容,显示每个文件的大小、修改时间和路径,目录会加/标识。 - GZIP 列表:因为 GZIP 只是单文件压缩流,不存文件名和原始大小,所以只能显示压缩后的文件大小,并推测原文件名(去掉
.gz)。 - 格式统一:用
formatFileSize把字节转成 KB/MB 等,输出整齐。
package main
import (
"archive/zip"
"compress/gzip"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/spf13/cobra"
)
func NewListCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "list [archive]",
Short: "列出压缩包内容",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
archivePath := args[0]
if _, err := os.Stat(archivePath); err != nil {
return fmt.Errorf("文件不存在: %s", archivePath)
}
lowerName := strings.ToLower(archivePath)
switch {
case strings.HasSuffix(lowerName, ".zip"):
return listZip(archivePath)
case strings.HasSuffix(lowerName, ".gz"):
return listGzip(archivePath)
default:
return errors.New("不支持的格式,仅支持 .zip 和 .gz")
}
},
}
return cmd
}
// 列出 ZIP 内容
func listZip(zipPath string) error {
r, err := zip.OpenReader(zipPath)
if err != nil {
return fmt.Errorf("打开 ZIP 失败: %w", err)
}
defer r.Close()
if len(r.File) == 0 {
fmt.Println("压缩包为空")
return nil
}
fmt.Printf("%-12s %-8s %s\n", "大小", "修改时间", "路径")
fmt.Println(strings.Repeat("-", 50))
for _, f := range r.File {
size := f.UncompressedSize64
modTime := f.Modified.Format("2006-01-02 15:04")
name := f.Name
if f.FileInfo().IsDir() {
name += "/"
}
fmt.Printf("%-12s %-16s %s\n", formatFileSize(int64(size)), modTime, name)
}
return nil
}
// 列出 GZIP 信息(单文件)
func listGzip(gzPath string) error {
file, err := os.Open(gzPath)
if err != nil {
return fmt.Errorf("打开 GZ 文件失败: %w", err)
}
defer file.Close()
gzReader, err := gzip.NewReader(file)
if err != nil {
return fmt.Errorf("解析 GZ 头失败: %w", err)
}
defer gzReader.Close()
// GZIP 本身不存原始文件名,但可从路径推测
baseName := filepath.Base(gzPath)
origName := strings.TrimSuffix(baseName, ".gz")
if origName == baseName {
origName = "<unknown>"
}
stat, _ := file.Stat()
fmt.Printf("GZIP 文件: %s\n", gzPath)
fmt.Printf("推测原文件名: %s\n", origName)
fmt.Printf("压缩后大小: %s\n", formatFileSize(stat.Size()))
// 注意:无法在不解压的情况下获取原始大小
fmt.Println("(GZIP 格式不包含原始文件大小和修改时间)")
return nil
}
// 复用 formatFileSize(需确保 main.go 或其他地方有定义)
func formatFileSize(size int64) string {
const unit = 1024
if size < unit {
return fmt.Sprintf("%d B", size)
}
div, exp := int64(unit), 0
for n := size / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %cB", float64(size)/float64(div), "KMGTPE"[exp])
}功能测试:
成功编译三个文件



总结:
目前已实现 打包压缩(pack)、文件信息查看(info) 和 敏感文件搜索(search) 三大核心功能。
它能智能处理被占用的文件(尤其在 Windows 下)、识别常见敏感文件(如密钥、配置、日志),并支持灵活过滤与中断操作。
本文解析了一个CLI文件处理工具的架构,涵盖打包、搜索、日志等功能模块的设计与问题。
由 AI 根据全文自动生成,仅供参考,以原文为准