FileSystem
type FileSystem struct {
// contains filtered or unexported fields
}FileSystem accesses a sandbox's files. Obtain it from Sandbox.FS. All remote paths must start with "/" and are sent without normalization. Handles are safe for concurrent use; returned data belongs to the caller.
FileSystem.Chmod
func (f *FileSystem) Chmod(ctx context.Context, path string, opts *FilePermissionsOptions) errorChmod changes permissions and ownership. Nil opts leaves all fields unspecified.
FileSystem.Download
func (f *FileSystem) Download(ctx context.Context, path string, w io.Writer, opts *DownloadOptions) (failure error)Download streams a remote file to w without a total size cap. It does not close w. Cancellation preserves context errors and matches ErrTransferCancelled. Writes must return promptly or observe ctx themselves: an arbitrary io.Writer cannot be forcibly interrupted. Partial output is possible on failure. Destination write errors preserve their cause without an ErrConnection category. Invalid Timeout returns ErrBadRequest before any request.
FileSystem.DownloadFile
func (f *FileSystem) DownloadFile(ctx context.Context, remotePath, localPath string, opts *DownloadOptions) (
failure error,
)DownloadFile streams through an exclusive, private temporary file next to localPath, created before opening the remote stream, and renames it only on success. Failure leaves an existing destination intact and removes staging. Existing permissions are preserved; new files use mode 0600, avoiding process-global umask changes. Streams have no size cap. Invalid Timeout returns ErrBadRequest before any request.
FileSystem.Glob
func (f *FileSystem) Glob(ctx context.Context, path, pattern string) (*FileSearchResult[string], error)Glob finds paths whose base names match pattern. It does not search contents.
FileSystem.Grep
func (f *FileSystem) Grep(ctx context.Context, path, pattern string) (*FileSearchResult[FileMatch], error)Grep searches contents for a literal substring, not a regular expression. Unreadable descendants are reported in Skipped; an unreadable root returns ErrFileAccessDenied.
FileSystem.List
func (f *FileSystem) List(ctx context.Context, path string, opts *ListFilesOptions) (*Page[FileInfo], error)List returns one directory listing, accepting legacy arrays and page envelopes. There is no cursor input on the server's directory endpoint, so the page holds the whole listing and its NextCursor cannot be followed.
FileSystem.Mkdir
func (f *FileSystem) Mkdir(ctx context.Context, path string, opts *MkdirOptions) errorMkdir creates a directory, using mode 0755 by default.
FileSystem.Move
func (f *FileSystem) Move(ctx context.Context, source, destination string) errorMove moves or renames a file between absolute sandbox paths.
FileSystem.PresignedDownloadURL
func (f *FileSystem) PresignedDownloadURL(ctx context.Context, path string, opts *PresignedFileURLOptions) (
string, error,
)PresignedDownloadURL returns a GET link without exposing sandbox credentials. Unscoped direct toolbox overrides return ErrUnsupportedOperation.
FileSystem.PresignedUploadURL
func (f *FileSystem) PresignedUploadURL(ctx context.Context, path string, opts *PresignedFileURLOptions) (
string, error,
)PresignedUploadURL returns a POST link accepting multipart/form-data with a file part named "file". The URL fixes the remote path and expires after ExpiresIn.
FileSystem.ReadFile
func (f *FileSystem) ReadFile(ctx context.Context, path string, opts *ReadFileOptions) ([]byte, error)ReadFile reads exact bytes into memory. The client cap defaults to 1 GiB; opts may replace it or disable it with NoLimit. Transfers use an idle timeout, not a total deadline. A Content-Length mismatch returns ErrConnection. Content-Type never changes the returned bytes. Invalid Timeout returns ErrBadRequest. Use Download for arbitrarily large files.
FileSystem.ReadMany
func (f *FileSystem) ReadMany(ctx context.Context, paths []string, opts *ReadFileOptions) (
result *BulkReadResult, failure error,
)ReadMany reads a multipart batch into memory, capped as one complete response. A missing file appears in Errors; an HTTP failure fails the whole call. A Content-Length mismatch returns ErrConnection, as with ReadFile. Invalid Timeout returns ErrBadRequest before any request.
FileSystem.ReadText
func (f *FileSystem) ReadText(ctx context.Context, path string, opts *ReadFileOptions) (string, error)ReadText reads strict UTF-8, preserving a leading BOM. Invalid encoding returns ErrBadRequest instead of silently replacing bytes. Bounds are those of ReadFile.
FileSystem.Remove
func (f *FileSystem) Remove(ctx context.Context, path string, opts *RemoveFileOptions) errorRemove deletes a file, or recursively deletes a directory when requested.
FileSystem.Replace
func (f *FileSystem) Replace(ctx context.Context, files []string, pattern, replacement string) (
*Page[FileReplaceResult], error,
)Replace substitutes a literal substring in each requested file. Per-file failures are returned as FileReplaceResult values.
FileSystem.Stat
func (f *FileSystem) Stat(ctx context.Context, path string) (*FileInfo, error)Stat returns file metadata, or ErrFileNotFound when the path does not exist.
FileSystem.Upload
func (f *FileSystem) Upload(ctx context.Context, path string, r io.Reader, opts *UploadOptions) (failure error)Upload streams r into a remote file. It never replays a one-shot reader after a 401. An io.ReadCloser is closed when the request ends; its Close must unblock Read. Other readers must return promptly or observe ctx themselves, since Go cannot interrupt an arbitrary Reader. Nil r returns ErrBadRequest.
Example:
client, err := daytona.New()
if err != nil {
log.Fatal(err)
}
defer func() {
if closeErr := client.Close(); closeErr != nil {
log.Print(closeErr)
}
}()
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
sb, err := client.Get(ctx, "your-sandbox-id", nil)
if err != nil {
log.Fatal(err)
}
if uploadErr := sb.FS().Upload(ctx, "/tmp/data.csv", strings.NewReader("a,b\n1,2\n"), nil); uploadErr != nil {
log.Fatal(uploadErr)
}
if downloadErr := sb.FS().Download(ctx, "/tmp/data.csv", os.Stdout, nil); downloadErr != nil {
log.Fatal(downloadErr)
}FileSystem.UploadFile
func (f *FileSystem) UploadFile(ctx context.Context, localPath, remotePath string, opts *UploadOptions) errorUploadFile streams a local regular file without buffering it whole. A 401 can replay from a freshly opened file. Growth past its initial size is ignored; shrinkage returns ErrBadRequest. Remote atomicity is opt-in.
FileSystem.Watch
func (f *FileSystem) Watch(ctx context.Context, path string, opts *WatchOptions) (result *WatchHandle, failure error)Watch opens a directory stream and waits for its start handshake. Startup is limited to 4096 events and 1 MiB; subsequent frames use the client response cap. No request timeout applies after HTTP headers. Unknown SSE names are ignored. A server error event before start fails this call without invoking OnExit.
Example:
client, err := daytona.New()
if err != nil {
log.Fatal(err)
}
defer func() {
if closeErr := client.Close(); closeErr != nil {
log.Print(closeErr)
}
}()
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
sb, err := client.Get(ctx, "your-sandbox-id", nil)
if err != nil {
log.Fatal(err)
}
watch, err := sb.FS().Watch(ctx, "/tmp", &daytona.WatchOptions{Recursive: true})
if err != nil {
log.Fatal(err)
}
defer watch.Stop()
for event, err := range watch.Events(ctx) {
if err != nil {
log.Print(err)
break
}
if event.Overflow {
fmt.Println("rescan directory")
continue
}
fmt.Println(event.Type, event.Name)
break
}
if waitErr := watch.Wait(ctx); waitErr != nil {
log.Print(waitErr)
}FileSystem.WriteFile
func (f *FileSystem) WriteFile(ctx context.Context, path string, data []byte, opts *WriteFileOptions) errorWriteFile uploads exact bytes to path, optionally atomically. Nil data is an empty file.
FileSystem.WriteMany
func (f *FileSystem) WriteMany(ctx context.Context, files map[string][]byte, opts *WriteManyOptions) (
*BulkWriteResult, error,
)WriteMany uploads a map of absolute paths to bytes in one request. Atomic requests rename each file independently, not as a batch transaction. Per-file failures, including unsupported atomic replacement, appear as strings in BulkWriteResult.Errors without fallback; successful files remain in Files.
FileSystem.WriteText
func (f *FileSystem) WriteText(ctx context.Context, path, text string, opts *WriteFileOptions) errorWriteText writes valid UTF-8 text. Invalid Go string bytes return ErrBadRequest; use WriteFile for arbitrary bytes. Atomicity and progress follow UploadOptions.
WatchHandle
type WatchHandle struct {
// contains filtered or unexported fields
}WatchHandle owns one directory stream. Call Stop when done, even if Events is never consumed. The context passed to Watch or Client.Close also closes the HTTP stream. Events is single-consumer; all other methods are concurrency-safe. A server error event (for example, a macOS access denial) ends the watch with its typed error, reported by Err, Wait, Events and OnExit.
WatchHandle.Err
func (w *WatchHandle) Err() errorErr is nil while running or after Stop; otherwise it is the terminal SDK error.
WatchHandle.Events
func (w *WatchHandle) Events(ctx context.Context) iter.Seq2[FilesystemEvent, error]Events yields file and overflow events in order. Breaking iteration or canceling ctx stops the watch; Wait joins cleanup. A terminal error is yielded once. Backpressure is bounded, with no unbounded client-side event queue.
WatchHandle.Stop
func (w *WatchHandle) Stop()Stop requests shutdown without waiting, so it is safe inside OnExit. Use Wait to join shutdown and the exit callback. Stop is idempotent.
WatchHandle.Wait
func (w *WatchHandle) Wait(ctx context.Context) errorWait waits for shutdown and OnExit and returns the watch's terminal error. It does not consume events: use Events concurrently if the watch is active. Canceling this wait does not stop the watch.
BulkReadError
type BulkReadError struct {
// Path is the requested path.
Path string
// Message explains the failure.
Message string
// Code is the optional machine-readable code.
Code string
// Source identifies the optional error producer.
Source string
}BulkReadError describes a per-file failure without failing the whole ReadMany.
BulkReadResult
type BulkReadResult struct {
// Files maps full server-returned paths to exact file bytes.
Files map[string][]byte
// Errors contains files that could not be read.
Errors []BulkReadError
}BulkReadResult contains downloaded bytes and per-file failures.
BulkWriteFile
type BulkWriteFile struct {
// Path is the destination path.
Path string
// Bytes is the number of bytes written.
Bytes int64
}BulkWriteFile describes a successfully uploaded file.
BulkWriteResult
type BulkWriteResult struct {
// Files contains successful uploads.
Files []BulkWriteFile
// Errors contains server explanations of failed uploads.
Errors []string
}BulkWriteResult reports successes and per-file failures of WriteMany.
DownloadOptions
type DownloadOptions struct {
// OnProgress runs synchronously after writes; Total is nil when not reported.
// Keep it short. Callback panics are contained.
OnProgress func(TransferProgress)
// Timeout replaces the client's idle timeout; zero uses it, NoTimeout disables it.
Timeout time.Duration
}DownloadOptions configures a streaming download, which has no total size cap.
FileInfo
type FileInfo struct {
// Name is the entry name.
Name string
// Path is the absolute sandbox path.
Path string
// Size is the file size in bytes.
Size int64
// IsDir distinguishes directories.
IsDir bool
// Mode is the server's mode string.
Mode string
// Permissions is the server's permission string.
Permissions string
// Owner is the owning user.
Owner string
// Group is the owning group.
Group string
// ModifiedAt is the modification timestamp.
ModifiedAt time.Time
// ModTime is the server's legacy modification-time representation.
ModTime string
}FileInfo describes a sandbox file or directory.
FileMatch
type FileMatch struct {
// File is the matched path.
File string
// Line is the one-based line number reported by the sandbox.
Line int64
// Content is the matched line.
Content string
}FileMatch is a literal content-search match.
FilePermissionsOptions
type FilePermissionsOptions struct {
// Mode is an octal permission string; empty leaves it unchanged.
Mode string
// Owner is a user name or ID; empty leaves it unchanged.
Owner string
// Group is a group name or ID; empty leaves it unchanged.
Group string
}FilePermissionsOptions selects permissions or ownership to change.
FileReplaceResult
type FileReplaceResult struct {
// File is the affected path.
File string
// Success reports whether replacement succeeded.
Success bool
// Error is the optional server explanation; nil means absent.
Error *string
}FileReplaceResult reports a replacement's outcome for one file.
FileSearchResult
type FileSearchResult[T any] struct {
// Items contains the matches.
Items []T
// Skipped contains paths the sandbox user could not read.
Skipped []string
}FileSearchResult contains matches and unreadable descendants (at most 1000). An unreadable search root returns ErrFileAccessDenied instead.
FilesystemEvent
type FilesystemEvent struct {
// Type is the open change vocabulary, including create, write, remove,
// rename and chmod. Future values are preserved verbatim.
Type string
// Name is the path relative to the watched directory.
Name string
// IsDir reports a directory change.
IsDir bool
// Timestamp is the server event time, decoded from Unix milliseconds.
Timestamp time.Time
// Overflow identifies an overflow notification rather than a file change.
Overflow bool
// Dropped is the server's overflow indicator, meaningful when Overflow is true.
Dropped bool
}FilesystemEvent is a file change or a server overflow notification.
ListFilesOptions
type ListFilesOptions struct {
// Depth is the number of levels; zero uses the server default (1).
Depth int
}ListFilesOptions controls directory traversal.
MkdirOptions
type MkdirOptions struct {
// Mode is an octal permission string; empty means "0755".
Mode string
}MkdirOptions configures a new directory.
PresignedFileURLOptions
type PresignedFileURLOptions struct {
// ExpiresIn defaults to one hour. It must be whole seconds in [1s, 7 days].
ExpiresIn time.Duration
}PresignedFileURLOptions selects a signed-file URL lifetime.
ReadFileOptions
type ReadFileOptions struct {
// MaxResponseBytes replaces the client cap (default 1 GiB); zero uses it,
// NoLimit disables it. Larger responses return ErrPayloadTooLarge.
MaxResponseBytes int64
// Timeout replaces the client's idle timeout; zero uses it, NoTimeout disables it.
Timeout time.Duration
}ReadFileOptions configures an in-memory read, including the whole ReadMany body.
RemoveFileOptions
type RemoveFileOptions struct {
// Recursive removes directory contents too; default false.
Recursive bool
}RemoveFileOptions controls directory removal.
TransferProgress
type TransferProgress struct {
// Bytes is the number of file bytes transferred.
Bytes int64
// Total is the expected length; nil means unknown.
Total *int64
}TransferProgress reports cumulative file bytes, excluding multipart framing.
UploadOptions
type UploadOptions struct {
// Atomic writes a temporary file then renames it. Unsupported servers return
// ErrAtomicUploadUnsupported; the SDK never silently retries non-atomically.
Atomic bool
// OnProgress runs synchronously with monotonically increasing byte counts.
// Keep it short. Panics are contained, like callback failures in the other SDKs.
OnProgress func(TransferProgress)
// Timeout replaces the client's transfer idle timeout. Zero uses the default;
// NoTimeout disables it. Transfers have no total SDK deadline.
Timeout time.Duration
}UploadOptions configures uploads from bytes, local paths, or readers.
WatchOptions
type WatchOptions struct {
// Recursive includes descendants; default false.
Recursive bool
// OnExit runs once after delivery ends. Failures before Watch returns never
// call it. Panics are contained. It may call Stop or Err, but must not Wait.
// Delivery starts when Events, Wait, or Stop is called, so no callback can
// run before the caller receives the handle.
OnExit func(error)
}WatchOptions configures directory observation.
WriteFileOptions
type WriteFileOptions = UploadOptionsWriteFileOptions configures WriteFile. It shares the upload transfer contract.
WriteManyOptions
type WriteManyOptions struct {
// Atomic requests temporary-file-plus-rename for every file.
Atomic bool
// Timeout replaces the client idle timeout; NoTimeout disables it.
Timeout time.Duration
}WriteManyOptions configures WriteMany; atomicity is per file, not per batch.
SignedFileMaxTTL
const SignedFileMaxTTL = 7 * 24 * time.HourSignedFileMaxTTL is the server's seven-day maximum signed-file URL lifetime.