# FileSystem (/docs/go-sdk/file-system)

> For AI agents: the complete documentation index is at https://www.daytona.com/llms.txt.

## FileSystem [#filesystem]

```go
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 [#filesystemchmod]

```go
func (f *FileSystem) Chmod(ctx context.Context, path string, opts *FilePermissionsOptions) error
```

Chmod changes permissions and ownership. Nil opts leaves all fields unspecified.

#### FileSystem.Download [#filesystemdownload]

```go
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 [#filesystemdownloadfile]

```go
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 [#filesystemglob]

```go
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 [#filesystemgrep]

```go
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 [#filesystemlist]

```go
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 [#filesystemmkdir]

```go
func (f *FileSystem) Mkdir(ctx context.Context, path string, opts *MkdirOptions) error
```

Mkdir creates a directory, using mode 0755 by default.

#### FileSystem.Move [#filesystemmove]

```go
func (f *FileSystem) Move(ctx context.Context, source, destination string) error
```

Move moves or renames a file between absolute sandbox paths.

#### FileSystem.PresignedDownloadURL [#filesystempresigneddownloadurl]

```go
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 [#filesystempresigneduploadurl]

```go
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 [#filesystemreadfile]

```go
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 [#filesystemreadmany]

```go
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 [#filesystemreadtext]

```go
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 [#filesystemremove]

```go
func (f *FileSystem) Remove(ctx context.Context, path string, opts *RemoveFileOptions) error
```

Remove deletes a file, or recursively deletes a directory when requested.

#### FileSystem.Replace [#filesystemreplace]

```go
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 [#filesystemstat]

```go
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 [#filesystemupload]

```go
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**:

```go
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 [#filesystemuploadfile]

```go
func (f *FileSystem) UploadFile(ctx context.Context, localPath, remotePath string, opts *UploadOptions) error
```

UploadFile 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 [#filesystemwatch]

```go
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**:

```go
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 [#filesystemwritefile]

```go
func (f *FileSystem) WriteFile(ctx context.Context, path string, data []byte, opts *WriteFileOptions) error
```

WriteFile uploads exact bytes to path, optionally atomically. Nil data is an empty file.

#### FileSystem.WriteMany [#filesystemwritemany]

```go
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 [#filesystemwritetext]

```go
func (f *FileSystem) WriteText(ctx context.Context, path, text string, opts *WriteFileOptions) error
```

WriteText writes valid UTF-8 text. Invalid Go string bytes return ErrBadRequest;
use WriteFile for arbitrary bytes. Atomicity and progress follow UploadOptions.

## WatchHandle [#watchhandle]

```go
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 [#watchhandleerr]

```go
func (w *WatchHandle) Err() error
```

Err is nil while running or after Stop; otherwise it is the terminal SDK error.

#### WatchHandle.Events [#watchhandleevents]

```go
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 [#watchhandlestop]

```go
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 [#watchhandlewait]

```go
func (w *WatchHandle) Wait(ctx context.Context) error
```

Wait 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 [#bulkreaderror]

```go
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 [#bulkreadresult]

```go
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 [#bulkwritefile]

```go
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 [#bulkwriteresult]

```go
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 [#downloadoptions]

```go
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 [#fileinfo]

```go
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 [#filematch]

```go
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 [#filepermissionsoptions]

```go
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 [#filereplaceresult]

```go
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 [#filesearchresult]

```go
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 [#filesystemevent]

```go
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 [#listfilesoptions]

```go
type ListFilesOptions struct {
	// Depth is the number of levels; zero uses the server default (1).
	Depth int
}
```

ListFilesOptions controls directory traversal.

## MkdirOptions [#mkdiroptions]

```go
type MkdirOptions struct {
	// Mode is an octal permission string; empty means "0755".
	Mode string
}
```

MkdirOptions configures a new directory.

## PresignedFileURLOptions [#presignedfileurloptions]

```go
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 [#readfileoptions]

```go
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 [#removefileoptions]

```go
type RemoveFileOptions struct {
	// Recursive removes directory contents too; default false.
	Recursive bool
}
```

RemoveFileOptions controls directory removal.

## TransferProgress [#transferprogress]

```go
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 [#uploadoptions]

```go
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 [#watchoptions]

```go
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 [#writefileoptions]

```go
type WriteFileOptions = UploadOptions
```

WriteFileOptions configures WriteFile. It shares the upload transfer contract.

## WriteManyOptions [#writemanyoptions]

```go
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 [#signedfilemaxttl]

```go
const SignedFileMaxTTL = 7 * 24 * time.Hour
```

SignedFileMaxTTL is the server's seven-day maximum signed-file URL lifetime.
