92 lines
1.9 KiB
Go
92 lines
1.9 KiB
Go
package systemfs
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"sort"
|
|
"strings"
|
|
)
|
|
|
|
type DirectoryEntry struct {
|
|
Name string `json:"name"`
|
|
Path string `json:"path"`
|
|
IsGit bool `json:"is_git"`
|
|
}
|
|
|
|
type DirectoryListing struct {
|
|
Current string `json:"current"`
|
|
CurrentIsGit bool `json:"current_is_git"`
|
|
Parent string `json:"parent"`
|
|
Directories []DirectoryEntry `json:"dirs"`
|
|
}
|
|
|
|
type Service struct{}
|
|
|
|
func NewService() *Service {
|
|
return &Service{}
|
|
}
|
|
|
|
func (s *Service) ListDirectories(current string) (DirectoryListing, error) {
|
|
current = strings.TrimSpace(current)
|
|
if current == "" {
|
|
wd, err := os.Getwd()
|
|
if err != nil {
|
|
return DirectoryListing{}, err
|
|
}
|
|
current = wd
|
|
}
|
|
|
|
current, err := filepath.Abs(current)
|
|
if err != nil {
|
|
return DirectoryListing{}, err
|
|
}
|
|
|
|
entries, err := os.ReadDir(current)
|
|
if err != nil {
|
|
return DirectoryListing{}, err
|
|
}
|
|
|
|
dirs := make([]DirectoryEntry, 0, len(entries))
|
|
for _, entry := range entries {
|
|
if !entry.IsDir() {
|
|
continue
|
|
}
|
|
fullPath := filepath.Join(current, entry.Name())
|
|
dirs = append(dirs, DirectoryEntry{
|
|
Name: entry.Name(),
|
|
Path: fullPath,
|
|
IsGit: pathHasGitDir(fullPath),
|
|
})
|
|
}
|
|
sort.Slice(dirs, func(i, j int) bool {
|
|
return dirs[i].Name < dirs[j].Name
|
|
})
|
|
|
|
return DirectoryListing{
|
|
Current: current,
|
|
CurrentIsGit: pathHasGitDir(current),
|
|
Parent: filepath.Dir(current),
|
|
Directories: dirs,
|
|
}, nil
|
|
}
|
|
|
|
func (s *Service) CreateDirectory(parent, name string) (string, error) {
|
|
parent = strings.TrimSpace(parent)
|
|
name = strings.TrimSpace(name)
|
|
if parent == "" || name == "" {
|
|
return "", fmt.Errorf("parent and name are required")
|
|
}
|
|
|
|
path := filepath.Join(parent, name)
|
|
if err := os.MkdirAll(path, 0o755); err != nil {
|
|
return "", err
|
|
}
|
|
return path, nil
|
|
}
|
|
|
|
func pathHasGitDir(path string) bool {
|
|
_, err := os.Stat(filepath.Join(path, ".git"))
|
|
return err == nil
|
|
}
|