files

package
v0.16.521 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 2, 2026 License: AGPL-3.0 Imports: 36 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package files answers the runtime's read-only file routes: a file of a tab's project for the editor, both sides of a changed file, a picture or document the agent produced, the «@»-context picker, a memory note the agent cited and an uploaded attachment. The answers keep the shape, the texts and the edge behaviour of the routes they replace, so the helpers here reproduce the few places where that behaviour comes from the old runtime's platform: how a query string and invalid UTF-8 are decoded, how JSON is written and an ETag computed, how names are sorted and paths split.

Index

Constants

View Source
const (
	GitMarkNew     = "new"
	GitMarkChanged = "changed"
)
View Source
const (
	MaxPreviewBytes = 15 * 1024 * 1024
	// MaxVideoBytes bounds what the viewer plays in place; a download has no bound.
	MaxVideoBytes = 500 * 1024 * 1024
)
View Source
const (
	// ImageMaxBytes and FileMaxBytes are the largest image and other file an upload takes.
	ImageMaxBytes = 10 * 1024 * 1024
	FileMaxBytes  = 50 * 1024 * 1024
)
View Source
const (
	// MaxZipEntries is how many entries the list shows; an archive with more says so.
	MaxZipEntries = 2000
	// MaxZipEntryBytes is the biggest file taken out of an archive.
	MaxZipEntryBytes = 200 * 1024 * 1024
)
View Source
const (

	// ContextMaxQuery is how much of the query counts, in UTF-16 units.
	ContextMaxQuery = 200
)
View Source
const MaxSaveBytes = 200 * 1024 * 1024

MaxSaveBytes is the largest file the viewer may write back.

View Source
const (
	// MaxVersionBytes is the largest file kept in the history: a bigger one is saved with none.
	MaxVersionBytes = 100 * 1024 * 1024
)
View Source
const (

	// NotebookMaxBytes allows embedded cell output without raising the limit for ordinary text files.
	NotebookMaxBytes = 16 << 20
)
View Source
const PreviewCSP = "" /* 161-byte string literal not displayed */

PreviewCSP is the policy a shown document runs under (all but PDFs and videos).

View Source
const (

	// SearchMaxQuery is how long a query may be, in bytes.
	SearchMaxQuery = 200
)

Variables

View Source
var EditableTypes = map[string]bool{"xlsx": true, "xlsm": true, "csv": true, "tsv": true, "docx": true, "docm": true, "pptx": true, "pptm": true}

EditableTypes are the files the viewer edits as bytes. Only a file that exists is written: this is no way to make files.

View Source
var ErrEntryExists = entryError("Something of this name is there already", "Здесь уже есть что-то с таким именем")

ErrEntryExists: the name is taken in the folder.

View Source
var PreviewTypes = map[string]string{
	"png": "image/png", "jpg": "image/jpeg", "jpeg": "image/jpeg", "gif": "image/gif", "webp": "image/webp", "svg": "image/svg+xml",
	"avif": "image/avif", "bmp": "image/bmp", "ico": "image/x-icon",
	"pdf": "application/pdf", "html": "text/html; charset=utf-8", "htm": "text/html; charset=utf-8",
	"md": "text/markdown; charset=utf-8", "markdown": "text/markdown; charset=utf-8",
	"mp4": "video/mp4", "m4v": "video/mp4", "webm": "video/webm", "mov": "video/quicktime", "mkv": "video/x-matroska", "ogv": "video/ogg",
	"mp3": "audio/mpeg", "wav": "audio/wav", "m4a": "audio/mp4", "aac": "audio/aac", "ogg": "audio/ogg", "oga": "audio/ogg", "opus": "audio/ogg", "flac": "audio/flac",
	"xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "xlsm": "application/vnd.ms-excel.sheet.macroEnabled.12",
	"csv": "text/csv; charset=utf-8", "tsv": "text/tab-separated-values; charset=utf-8",
	"docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "docm": "application/vnd.ms-word.document.macroEnabled.12",
	"pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation", "pptm": "application/vnd.ms-powerpoint.presentation.macroEnabled.12",
}

PreviewTypes are what the viewer shows, by extension.

View Source
var VideoTypes = map[string]string{
	"pdf":  "application/pdf",
	"xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "xlsm": "application/vnd.ms-excel.sheet.macroEnabled.12",
	"csv": "text/csv; charset=utf-8", "tsv": "text/tab-separated-values; charset=utf-8",
	"docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "docm": "application/vnd.ms-word.document.macroEnabled.12",
	"pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation", "pptm": "application/vnd.ms-powerpoint.presentation.macroEnabled.12",
	"mp4": "video/mp4", "m4v": "video/mp4", "webm": "video/webm", "mov": "video/quicktime", "mkv": "video/x-matroska", "ogv": "video/ogg",
	"mp3": "audio/mpeg", "wav": "audio/wav", "m4a": "audio/mp4", "aac": "audio/aac", "ogg": "audio/ogg", "oga": "audio/ogg", "opus": "audio/ogg", "flac": "audio/flac",
}

VideoTypes are read in ranges: video, sound, and a PDF, whose viewer asks for the pages it draws.

Functions

func APIParts

func APIParts(r *http.Request) ([]string, string, bool)

APIParts is the request path as the old API router split it: "/agents" taken off, empty segments dropped, each segment percent-decoded on its own (so an encoded "/" stays inside its segment). ok is false for a path outside "/api".

func ASCIIName

func ASCIIName(name string) string

ASCIIName is a file name safe inside a quoted header parameter: every UTF-16 unit outside printable ASCII, and quotes and backslashes, become "_".

func AllowedContextRoot

func AllowedContextRoot(dir string, roots []string) bool

AllowedContextRoot: dir (resolved) is one of the roots or inside one, each root compared by its resolved path.

func Answer

func Answer(r *http.Request, status int, v Object, h http.Header) (int, any, http.Header)

Answer is a whole JSON answer as the old runtime gave it: the value, its ETag, and 304 to a caller that holds it. Headers given are kept; a 304 keeps the JSON content type the old runtime had already set.

func AppendJSON

func AppendJSON(b []byte, v any) []byte

AppendJSON writes v (string, bool, int kinds, float64, []string, []any, []Object, Object, nil).

func BaseName

func BaseName(p string) string

BaseName is the last segment of an absolute path, "" for "/".

func CheckEntryName added in v0.16.123

func CheckEntryName(name string) error

CheckEntryName refuses a name that is not one entry of a folder, or that looks like credentials.

func DecodeComponent

func DecodeComponent(s string) string

DecodeComponent is a path segment decoded as the old router did: percent-decoded when that is valid, as it was otherwise.

func DecodeName

func DecodeName(header string) ([]rune, bool)

DecodeName is a file name header as the previous runtime read it: the header's bytes as Latin-1 characters, then decodeURIComponent; false where that threw.

func DecodeUTF8

func DecodeUTF8(b []byte) string

DecodeUTF8 turns bytes into text the way a WHATWG decoder does: each maximal invalid subsequence becomes one U+FFFD.

func ETag

func ETag(body []byte) string

ETag is the old runtime's entity tag of a body.

func EncodeURIComponent

func EncodeURIComponent(s string) string

EncodeURIComponent percent-encodes all but the unreserved marks, as browsers' encodeURIComponent.

func ExtName

func ExtName(p string) string

ExtName is the extension of the last path segment, the way the old runtime cut it: from the last dot, "" for a name that only starts with a dot, trailing slashes ignored.

func FileRevision added in v0.16.86

func FileRevision(st os.FileInfo) string

FileRevision names a file's state: a save over an older one is refused.

func Fresh

func Fresh(r *http.Request, etag string) bool

Fresh: the caller already holds this entity (If-None-Match), and did not ask to revalidate with no-cache.

func FuzzyScore

func FuzzyScore(candidate string, query []uint16) (float64, bool)

FuzzyScore matches every query unit in order, case-insensitively; lower is better (a tighter, earlier match). ok is false when the query does not match. Offsets count UTF-16 units, as the picker always did.

func GitMarks added in v0.16.123

func GitMarks(dir string) map[string]string

GitMarks is the marks of the entries of dir, by name.

func HomeCredentials

func HomeCredentials(home string) []string

HomeCredentials are the credential places of the home folder home.

func ImageType

func ImageType(mime string) bool

ImageType says whether an image upload takes this content type. Unlike the previous runtime, a name its lookup found on every object (constructor, toString…) is no type.

func ListProject

func ListProject(root, relative string) (Object, *EditorError)

ListProject is one folder of a tab's project for the editor: folders first, then files, by name; links are left out; at most 2000 entries are looked at.

func MemoryName added in v0.16.154

func MemoryName(name string) bool

MemoryName reports whether name is a note's file name the memory accepts.

func NewEmptyFile added in v0.16.123

func NewEmptyFile(dir, name string) (string, error)

NewEmptyFile makes an empty file in dir; it answers its path.

func NodeTempDir

func NodeTempDir() string

NodeTempDir is the temporary folder the old runtime counted as one of the viewer's places: TMPDIR, TMP or TEMP, else /tmp, without a trailing slash.

func OpenWithoutSession

func OpenWithoutSession(apiPath string) bool

OpenWithoutSession: a path served to anyone. An extension opens only a page asset, never an API path: the old rule let /api/uploads/<anything>.png through without a session (closed in both runtimes).

func PreviewRange

func PreviewRange(header string, size int64) (start, end int64, ok bool)

PreviewRange is the byte range of a video the viewer asks for: "bytes=a-b", "bytes=a-" or "bytes=-n"; ok is false when the header asks for nothing that can be served.

func PreviewType

func PreviewType(ext string) (contentType string, video bool)

PreviewType is the content type the viewer serves a file of this extension with, and whether it is read in ranges.

func QueryUnits

func QueryUnits(q string) []uint16

QueryUnits is the picker's query: its first 200 UTF-16 units.

func ReadDeliveredFile added in v0.16.86

func ReadDeliveredFile(file, sha string) (Object, *EditorError)

ReadDeliveredFile is a file the agent handed over on purpose (deliver_file), which may lie outside the project (in /tmp). Only that one file opens: the path must be clean and absolute with no link in it, and the bytes must be the ones the card vouched for (sha256), so a file swapped or replaced by a link after the hand-over is refused.

func ReadProjectFile

func ReadProjectFile(root, relative string) (Object, *EditorError)

ReadProjectFile is a text file of a tab's project for the editor, with the revision a save must name.

func Realpath

func Realpath(p string) (string, error)

Realpath resolves every link of an absolute path. The result is text as the old runtime held it (invalid UTF-8 replaced), so what follows works on the same name it did.

func Ref

func Ref(values []string, fallback string) (string, bool)

Ref is a revision to read a side from: fallback when absent, WORKTREE for the working tree, ok false when it does not look like a revision.

func RenameEntry added in v0.16.123

func RenameEntry(abs, name string) (string, error)

RenameEntry gives the entry at abs a new name in its folder; it answers the new path.

func RepoPath

func RepoPath(values []string) (string, bool)

RepoPath is a path inside the repository, or ok false: absent, repeated, /dev/null, absolute, with a NUL, or climbing above the repository.

func RouteIs

func RouteIs(r *http.Request, route string) bool

RouteIs: the request path is this fixed API route, as the old router matched it.

func SafeZipName added in v0.16.5

func SafeZipName(name string) bool

SafeZipName: a name that stays inside the archive: relative, no "..", no backslash, no NUL.

func SaveProjectFile added in v0.15.40

func SaveProjectFile(root, relative, content, revision string) (Object, *EditorError)

SaveProjectFile saves a file of a tab's project over the revision the page opened, whole or not at all: the text goes to a temporary file beside it, which takes the file's mode and replaces it by a rename. What leaves the project is refused as for reading, and so is a file the person cannot write.

func SearchContext

func SearchContext(root string, query []uint16) []string

SearchContext is up to 20 files under root (resolved) matching the query, best first.

func SecretName added in v0.16.123

func SecretName(name string) bool

SecretName is whether a file's name looks like credentials (.env, keys, certificates).

func ServeFileDownload added in v0.16.123

func ServeFileDownload(w http.ResponseWriter, r *http.Request, real string)

ServeFileDownload sends one file to be saved, whole or in the ranges asked (a resumed download), with no limit of size.

func ServeShown

func ServeShown(w http.ResponseWriter, r *http.Request, real string)

ServeShown shows the file at a resolved path the caller has already allowed (a file of a chat's folder): the same types, sizes, ranges and policy as ServePreview.

func ServeUpload

func ServeUpload(w http.ResponseWriter, r *http.Request, dir string, segments []string)

ServeUpload answers a GET of an uploaded attachment: the file the segments name under dir, in ranges for media.

func TrashDir added in v0.16.123

func TrashDir() (string, error)

TrashDir is the system's trash of the person (the freedesktop.org one): $XDG_DATA_HOME/Trash, or ~/.local/share/Trash.

func TrashEntry added in v0.16.123

func TrashEntry(abs, trash string, now time.Time) error

TrashEntry moves the entry at abs into trash (a folder as TrashDir names it), with the note a file manager reads to put it back. An entry on another disk than the trash is not moved: it would have to be copied.

func UploadPath

func UploadPath(dir string, segments []string) (string, bool)

UploadPath is the file the segments name inside dir, or ok false: no segments, an empty, ".", ".." or NUL segment, a segment with a slash or backslash, or a path that is the folder itself or outside it. A link inside is followed when the file is read only while it stays inside the folder (ServeUpload).

func UploadRange

func UploadRange(header string, size int64) (start, end int64, present, satisfiable bool)

UploadRange is the single byte range a media element asks for. present is false when there is no range to answer (no header, or not a single range); satisfiable is false for a range outside the file.

func UploadType

func UploadType(p string) string

UploadType is the content type an upload is served with, "" for a type that is not served.

func WriteJSON

func WriteJSON(w http.ResponseWriter, r *http.Request, status int, v Object)

WriteJSON writes a JSON answer as the old runtime did: its content type, ETag and length, 304 to a caller that already holds it.

func WriteProjectFile

func WriteProjectFile(root, relative, content, revision string, loneSurrogate bool) (Object, *EditorError)

WriteProjectFile saves a file of a tab's project over the revision the page opened, through the descriptor it checked: no truncation on open, no final link followed. loneSurrogate says the text held a lone UTF-16 surrogate, which the previous runtime could not write back as it came.

func WriteUnauthorized

func WriteUnauthorized(w http.ResponseWriter)

WriteUnauthorized is the old API's refusal of a caller with neither a page session nor the cli-token.

func ZipName added in v0.16.123

func ZipName(items []DownloadItem, asked string) string

ZipName is the name a zip of these items is saved under: the folder's name, or "files" for several.

Types

type Access

type Access struct {
	// VersionsDir keeps the earlier states of the files the viewer edits; "" keeps none.
	VersionsDir string
	Roots       []string
	// contains filtered or unexported fields
}

Access says which files may be opened: under the roots, and not secret-looking.

func NewAccess

func NewAccess(roots, configDirs []string) *Access

NewAccess builds the rules. roots are the folders files may be in (made absolute and clean); configDirs are more home-relative folders that hold credentials (".config/<app>"), refused like ".ssh".

func (*Access) Allowed added in v0.16.123

func (a *Access) Allowed(real string) bool

Allowed: under one of the roots.

func (*Access) Deny

func (a *Access) Deny(places, open, keep []string)

Deny closes the places (files or folders, by their own path and by the real one behind links) to every root, except the folders of open that lie inside them. A place that is or holds one of keep (the home folder, the workspace) cannot be closed whole without closing that too: its known secret files are closed instead.

func (*Access) Download

func (a *Access) Download(requested string) Target

Download resolves a file the agent sent to be saved: any type and size, the same places, secrets kept out.

func (*Access) HoldsSecret added in v0.16.123

func (a *Access) HoldsSecret(p string) bool

HoldsSecret: a new name or a move of the folder p would take a secret folder of several parts out of the rule (p is ".config" of ".config/acme"). Such a folder keeps its name and its place.

func (*Access) Preview

func (a *Access) Preview(requested string) Target

Preview resolves a file the viewer may show: an existing picture, video or document under the roots.

func (*Access) ResolveDownload added in v0.16.123

func (a *Access) ResolveDownload(requested string, allow func(real string) bool) (DownloadItem, *Target)

ResolveDownload resolves a path asked for under allow and the secrets rule: a regular file or a folder.

func (*Access) Secret

func (a *Access) Secret(p string) bool

Secret: the path looks like it holds credentials.

func (*Access) ServeFileBytes added in v0.16.86

func (a *Access) ServeFileBytes(w http.ResponseWriter, r *http.Request)

ServeFileBytes answers /api/v2/file-bytes?path=: GET the file's revision (of anything the pane can open, which is how an open file hears it changed); of a file it edits, GET &versions=1 its history, PUT the whole new file over the ?revision= it was read at (a file changed since is a 409 and stays as it is; no ?revision= writes over whatever is there), and POST &restore=<id> a kept state back.

func (*Access) ServePreview

func (a *Access) ServePreview(w http.ResponseWriter, r *http.Request, q Query)

ServePreview answers a GET of the viewer: a file shown in place (a video in ranges), or with download=1 any allowed file handed over to be saved. The caller has a page session.

func (*Access) ServeZip added in v0.16.5

func (a *Access) ServeZip(w http.ResponseWriter, r *http.Request, q Query)

ServeZip answers GET file-preview?zip=list&path= (the entries) and ?zip=entry&path=&name= (one file as an attachment).

func (*Access) ServeZipDownload added in v0.16.123

func (a *Access) ServeZipDownload(w http.ResponseWriter, r *http.Request, items []DownloadItem, name string, allow func(real string) bool)

ServeZipDownload writes the items as one zip while it is sent: a folder with all it holds under its name, a file by its name. Nothing is counted ahead, so the answer has no length; a failure in the middle breaks the connection, so a cut archive is never saved as a whole one.

func (*Access) WriteZip

func (a *Access) WriteZip(ctx context.Context, w io.Writer, folder DownloadItem, allow func(real string) bool) error

WriteZip writes one folder as a zip, under its own name inside, by the same rules as a download of it: the secrets are left out, a link is taken only to a file allow lets out.

type Cleanup

type Cleanup struct {
	Deleted    int
	FreedBytes int64
}

Cleanup is what a clean-up removed: files and their bytes.

type DownloadItem added in v0.16.123

type DownloadItem struct {
	Real string
	Name string
	Dir  bool
}

DownloadItem is one path asked for, resolved: its real path and whether it is a folder.

type EditorError

type EditorError struct {
	Status int
	Text   string
}

EditorError is a refusal of the editor routes: a status and the text shown to the person.

func ProjectFilePath added in v0.16.5

func ProjectFilePath(root, relative string) (string, *EditorError)

ProjectFilePath is the absolute, resolved path of a file of a tab's project, under the same refusals as the editor's.

func (*EditorError) Error

func (e *EditorError) Error() string

type EntryError added in v0.16.123

type EntryError struct {
	// contains filtered or unexported fields
}

EntryError is a refusal of a change said for the person: it names no path.

func (*EntryError) Error added in v0.16.123

func (e *EntryError) Error() string

type Field

type Field struct {
	K string
	V any
}

Field is one key of an Object.

type MemoryFile added in v0.16.154

type MemoryFile struct {
	Name string
	Path string
	// MtimeMs is the modification time in milliseconds, as ReadMemoryNote counts it.
	MtimeMs float64
}

MemoryFile is one note found on disk: the freshest copy of its name.

func ListMemoryFiles added in v0.16.154

func ListMemoryFiles(parents []string) []MemoryFile

ListMemoryFiles is every note under the parents, one per name (the freshest copy), by name.

type Object

type Object []Field

Object is a JSON object with its keys in order.

func Error

func Error(text string) Object

Error is {"error": text}.

func FileContent

func FileContent(oldSide, newSide Side) Object

FileContent is the answer of both sides.

func ParseMemoryNote

func ParseMemoryNote(name, raw string) Object

ParseMemoryNote reads the title (the first heading, else the front matter's name, else the file name), the description and the text of a note.

func ReadMemoryNote

func ReadMemoryNote(name string, parents []string) (Object, bool)

ReadMemoryNote is the freshest copy of the named memory under the parents, or ok false.

func (Object) MarshalJSON

func (o Object) MarshalJSON() ([]byte, error)

MarshalJSON lets an Object be handed to encoding/json too.

type Query

type Query map[string][]string

Query is a parsed query string: every value of each key, in order.

func ParseQuery

func ParseQuery(raw string) Query

ParseQuery reads a raw query string the way the old runtime did: pairs split on '&' and the first '=', '+' is a space, valid escapes decoded, invalid ones kept, at most 1000 pairs.

func RequestQuery

func RequestQuery(r *http.Request) Query

RequestQuery is the request's query: what follows the first '?' of the target as it was sent.

func (Query) String

func (q Query) String(key string) (string, bool)

String is the value of a key given exactly once; a missing or repeated key is not a string.

type Side

type Side struct {
	Content   string
	Truncated bool
	Binary    bool
}

Side is one side of the diff.

func GitBlob added in v0.16.123

func GitBlob(abs, ref string) (side Side, inRepo, tracked bool)

GitBlob is a file as a git revision has it, for the editor's diff: read from the file's own folder by a path relative to it ("./name"), so any file of any repository works without knowing where the repository starts. inRepo is false outside a repository; tracked is false for a file the revision does not have.

func LoadSide

func LoadSide(cwd, ref, rel string, has bool) Side

LoadSide reads one side; an empty relative path is an empty side.

type Target

type Target struct {
	OK     bool
	Real   string
	Ext    string
	Size   int64
	Status int
	Text   string
}

Target is a file that may be served, or the refusal.

type TextHit added in v0.16.123

type TextHit struct {
	Path string `json:"path"`
	Line int    `json:"line"`
	Col  int    `json:"col"`
	Text string `json:"text"`
}

TextHit is one line holding the query: the file (relative to the folder searched, with slashes), the line and the column from 1 (the column in characters), and the line itself, cut around the match when it is long.

func SearchText added in v0.16.123

func SearchText(ctx context.Context, root, query string, secret func(abs string) bool) (hits []TextHit, truncated bool)

SearchText finds the query under root. The case is ignored unless the query has a capital letter. secret, when set, says a file (by its absolute path) is not to be read. truncated is true when the search stopped before the end.

type Uploads

type Uploads struct {
	Dir string
	// Now and Random make names reproducible in tests.
	Now    func() time.Time
	Random func() string
}

Uploads is the uploads folder.

func (*Uploads) Clean

func (u *Uploads) Clean(all bool) Cleanup

Clean removes the uploads older than a day, or all of them, then the folders it emptied. Only files at <workspace>/<tab>/<file> are looked at, as before; a file of no bytes is removed but not counted, as before. Unlike before, links are never followed: a linked folder is not entered and a linked file not removed.

func (*Uploads) FileName

func (u *Uploads) FileName(original []rune) string

FileName is a file's stored name: <ms>-<8 hex>-<name><extension, its letters, digits and dots, at most 16>.

func (*Uploads) ImageName

func (u *Uploads) ImageName(original []rune, mime string) string

ImageName is an image's stored name: <ms>-<8 hex>-<name>.<type>.

func (*Uploads) Save

func (u *Uploads) Save(data []byte, wsID, tabID, name string) (string, error)

Save writes an upload of a tab and gives its path. The tab's folder must be inside the uploads folder once its links are resolved, and the file is created new, never through a link.

type Version added in v0.16.86

type Version struct {
	ID   string
	At   int64 // ms
	Size int64
}

Version is one kept state of a file; its ID is the revision the file had.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL