📁 File System
pkg/composerutils/fs.go provides basic file system utility functions, reused by pkg/composer, pkg/installer, and other modules.
Function List
| Function | Signature | Description |
|---|---|---|
CheckWritePermission | (dir string) error | Check directory writable (create if not exists) |
EnsureDirectoryExists | (dir string) error | Ensure directory exists, create recursively if not |
CreateFileWithContent | (filePath string, content []byte, perm os.FileMode) error | Create file and write content |
CheckWritePermission
Checks if a directory has write permission. If the directory doesn't exist, it will first attempt to create it, then verify write permission by creating a temporary file, and automatically clean up after testing.
func CheckWritePermission(dir string) error| Parameter | Type | Description |
|---|---|---|
dir | string | Directory path to check |
Possible errors: Directory creation failed, no write permission.
if err := composerutils.CheckWritePermission("/usr/local/bin"); err != nil {
log.Fatalf("Directory has no write permission: %v", err)
}EnsureDirectoryExists
Ensures specified directory exists, creates recursively if not (permission 0755).
func EnsureDirectoryExists(dir string) errorinstallDir := "/opt/composer-skills"
if err := composerutils.EnsureDirectoryExists(installDir); err != nil {
log.Fatalf("Unable to create installation directory: %v", err)
}CreateFileWithContent
Creates file at specified path and writes content, automatically ensuring parent directory exists.
func CreateFileWithContent(filePath string, content []byte, perm os.FileMode) error| Parameter | Type | Description |
|---|---|---|
filePath | string | File path (including filename) |
content | []byte | Content to write |
perm | os.FileMode | File permission (e.g., 0644, 0755) |
script := []byte("#!/bin/sh\necho 'Hello World'")
if err := composerutils.CreateFileWithContent("/usr/local/bin/hello.sh", script, 0755); err != nil {
log.Fatalf("Unable to create script: %v", err)
}Relationship with standard library
These three functions are thin wrappers around os.MkdirAll, os.WriteFile, os.Create, adding combined semantics like "ensure parent directory exists" and "write permission detection", avoiding repetitive handling.
Advanced
- For mocking file system operations in tests, see Mock Interfaces
MockFileSystemHelper. - Test file assertions see Test Utilities.