This repository has been archived on 2026-07-17. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
2026-07-02 17:22:26 +08:00

90 lines
2.6 KiB
Go

package service
import (
"codespace/internal/fs"
"codespace/internal/util"
"codespace/internal/workspace"
)
// FileService handles file operations within workspaces.
type FileService struct {
workspaces workspace.Manager
maxWriteBytes int64
}
// NewFileService creates a FileService with a per-write byte limit.
// If maxWriteBytes is zero or negative, a 1 MiB default is applied.
func NewFileService(workspaces workspace.Manager, maxWriteBytes int64) *FileService {
if maxWriteBytes <= 0 {
maxWriteBytes = 1 << 20
}
return &FileService{workspaces: workspaces, maxWriteBytes: maxWriteBytes}
}
// List lists files at the given workspace-relative path.
func (s *FileService) List(workspaceID, path string) ([]fs.FileInfo, error) {
ws, err := s.workspaces.Get(workspaceID)
if err != nil {
return nil, err
}
return fs.NewLocal(ws.Root).List(path)
}
// Read reads a file at the given workspace-relative path.
func (s *FileService) Read(workspaceID, path string) ([]byte, error) {
ws, err := s.workspaces.Get(workspaceID)
if err != nil {
return nil, err
}
return fs.NewLocal(ws.Root).Read(path)
}
// Write writes data to a file at the given workspace-relative path.
// Writes exceeding maxWriteBytes are rejected before touching the filesystem.
func (s *FileService) Write(workspaceID, path string, data []byte) error {
if int64(len(data)) > s.maxWriteBytes {
return util.New(util.CodeBadRequest, "file exceeds max write size")
}
ws, err := s.workspaces.Get(workspaceID)
if err != nil {
return err
}
return fs.NewLocal(ws.Root).Write(path, data)
}
// Mkdir creates a directory at the given workspace-relative path.
func (s *FileService) Mkdir(workspaceID, path string) error {
ws, err := s.workspaces.Get(workspaceID)
if err != nil {
return err
}
return fs.NewLocal(ws.Root).Mkdir(path)
}
// Remove removes a file or directory at the given workspace-relative path.
func (s *FileService) Remove(workspaceID, path string) error {
ws, err := s.workspaces.Get(workspaceID)
if err != nil {
return err
}
return fs.NewLocal(ws.Root).Remove(path)
}
// Rename renames a file or directory from oldPath to newPath.
func (s *FileService) Rename(workspaceID, oldPath, newPath string) error {
ws, err := s.workspaces.Get(workspaceID)
if err != nil {
return err
}
return fs.NewLocal(ws.Root).Rename(oldPath, newPath)
}
// Stat returns file info for the given workspace-relative path.
func (s *FileService) Stat(workspaceID, path string) (*fs.FileInfo, error) {
ws, err := s.workspaces.Get(workspaceID)
if err != nil {
return nil, err
}
return fs.NewLocal(ws.Root).Stat(path)
}