📁 文件系统
pkg/composerutils/fs.go 提供文件系统相关的基础工具函数,被 pkg/composer、pkg/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| 参数 | 类型 | 说明 |
|---|---|---|
dir | string | 要检查的目录路径 |
可能错误:目录创建失败、无写权限。
go
if err := composerutils.CheckWritePermission("/usr/local/bin"); err != nil {
log.Fatalf("目录无写入权限: %v", err)
}EnsureDirectoryExists
确保指定目录存在,不存在则递归创建(权限 0755)。
go
func EnsureDirectoryExists(dir string) errorgo
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| 参数 | 类型 | 说明 |
|---|---|---|
filePath | string | 文件路径(含文件名) |
content | []byte | 写入内容 |
perm | os.FileMode | 文件权限(如 0644、0755) |
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.MkdirAll、os.WriteFile、os.Create 的薄封装,增加了「确保父目录存在」「写权限探测」等组合语义,避免每次重复处理。