52 lines
1.4 KiB
Go
52 lines
1.4 KiB
Go
package fileops
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"gitea.maximumdirect.net/eric/narratio/internal/pathsafe"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
)
|
|
|
|
// EnsureWorkspaceDirectoryUnderRoot creates real directories beneath an
|
|
// existing root and rejects symlink components instead of following them.
|
|
func EnsureWorkspaceDirectoryUnderRoot(rootPath, relative string) error {
|
|
if _, err := pathsafe.NormalizeRelativeDestination(relative); err != nil {
|
|
return err
|
|
}
|
|
root, err := os.OpenRoot(rootPath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer root.Close()
|
|
return ensureWorkspaceDirectory(root, relative)
|
|
}
|
|
|
|
func ensureWorkspaceDirectory(root *os.Root, relative string) error {
|
|
current := ""
|
|
for _, component := range strings.Split(filepath.ToSlash(relative), "/") {
|
|
if component == "" || component == "." || component == ".." {
|
|
return fmt.Errorf("invalid directory component %q", component)
|
|
}
|
|
current = filepath.Join(current, component)
|
|
info, err := root.Lstat(current)
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
if err := root.Mkdir(current, WorkspaceDirectoryMode.Perm()); err != nil && !errors.Is(err, os.ErrExist) {
|
|
return err
|
|
}
|
|
info, err = root.Lstat(current)
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
|
|
return fmt.Errorf("workspace directory %q is not a real directory", current)
|
|
}
|
|
if err := root.Chmod(current, WorkspaceDirectoryMode); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|