Skip to content

📁 文件系统

pkg/composerutils/fs.go 提供文件系统相关的基础工具函数,被 pkg/composerpkg/installer 等模块复用。

函数清单

函数签名说明
CheckWritePermission(dir string) error检查目录可写(不存在则创建)
EnsureDirectoryExists(dir string) error确保目录存在,不存在则递归创建
CreateFileWithContent(filePath string, content []byte, perm os.FileMode) error创建文件并写入内容

CheckWritePermission

检查目录是否具有写入权限。若目录不存在会先尝试创建,然后通过创建临时文件验证写权限,测试后自动清理。

go
func CheckWritePermission(dir string) error
参数类型说明
dirstring要检查的目录路径

可能错误:目录创建失败、无写权限。

go
if err := composerutils.CheckWritePermission("/usr/local/bin"); err != nil {
    log.Fatalf("目录无写入权限: %v", err)
}

EnsureDirectoryExists

确保指定目录存在,不存在则递归创建(权限 0755)。

go
func EnsureDirectoryExists(dir string) error
go
installDir := "/opt/composer-skills"
if err := composerutils.EnsureDirectoryExists(installDir); err != nil {
    log.Fatalf("无法创建安装目录: %v", err)
}

CreateFileWithContent

在指定路径创建文件并写入内容,自动确保父目录存在。

go
func CreateFileWithContent(filePath string, content []byte, perm os.FileMode) error
参数类型说明
filePathstring文件路径(含文件名)
content[]byte写入内容
permos.FileMode文件权限(如 06440755
go
script := []byte("#!/bin/sh\necho 'Hello World'")
if err := composerutils.CreateFileWithContent("/usr/local/bin/hello.sh", script, 0755); err != nil {
    log.Fatalf("无法创建脚本: %v", err)
}

与标准库的关系

这三个函数是对 os.MkdirAllos.WriteFileos.Create 的薄封装,增加了「确保父目录存在」「写权限探测」等组合语义,避免每次重复处理。

进阶

  • 若需在测试中 Mock 文件系统操作,见 Mock 接口MockFileSystemHelper
  • 测试文件断言见 测试辅助

基于 MIT 许可证发布