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
- Variables
- func APIParts(r *http.Request) ([]string, string, bool)
- func ASCIIName(name string) string
- func AllowedContextRoot(dir string, roots []string) bool
- func Answer(r *http.Request, status int, v Object, h http.Header) (int, any, http.Header)
- func AppendJSON(b []byte, v any) []byte
- func BaseName(p string) string
- func CheckEntryName(name string) error
- func DecodeComponent(s string) string
- func DecodeName(header string) ([]rune, bool)
- func DecodeUTF8(b []byte) string
- func ETag(body []byte) string
- func EncodeURIComponent(s string) string
- func ExtName(p string) string
- func FileRevision(st os.FileInfo) string
- func Fresh(r *http.Request, etag string) bool
- func FuzzyScore(candidate string, query []uint16) (float64, bool)
- func GitMarks(dir string) map[string]string
- func HomeCredentials(home string) []string
- func ImageType(mime string) bool
- func ListProject(root, relative string) (Object, *EditorError)
- func MemoryName(name string) bool
- func NewEmptyFile(dir, name string) (string, error)
- func NodeTempDir() string
- func OpenWithoutSession(apiPath string) bool
- func PreviewRange(header string, size int64) (start, end int64, ok bool)
- func PreviewType(ext string) (contentType string, video bool)
- func QueryUnits(q string) []uint16
- func ReadDeliveredFile(file, sha string) (Object, *EditorError)
- func ReadProjectFile(root, relative string) (Object, *EditorError)
- func Realpath(p string) (string, error)
- func Ref(values []string, fallback string) (string, bool)
- func RenameEntry(abs, name string) (string, error)
- func RepoPath(values []string) (string, bool)
- func RouteIs(r *http.Request, route string) bool
- func SafeZipName(name string) bool
- func SaveProjectFile(root, relative, content, revision string) (Object, *EditorError)
- func SearchContext(root string, query []uint16) []string
- func SecretName(name string) bool
- func ServeFileDownload(w http.ResponseWriter, r *http.Request, real string)
- func ServeShown(w http.ResponseWriter, r *http.Request, real string)
- func ServeUpload(w http.ResponseWriter, r *http.Request, dir string, segments []string)
- func TrashDir() (string, error)
- func TrashEntry(abs, trash string, now time.Time) error
- func UploadPath(dir string, segments []string) (string, bool)
- func UploadRange(header string, size int64) (start, end int64, present, satisfiable bool)
- func UploadType(p string) string
- func WriteJSON(w http.ResponseWriter, r *http.Request, status int, v Object)
- func WriteProjectFile(root, relative, content, revision string, loneSurrogate bool) (Object, *EditorError)
- func WriteUnauthorized(w http.ResponseWriter)
- func ZipName(items []DownloadItem, asked string) string
- type Access
- func (a *Access) Allowed(real string) bool
- func (a *Access) Deny(places, open, keep []string)
- func (a *Access) Download(requested string) Target
- func (a *Access) HoldsSecret(p string) bool
- func (a *Access) Preview(requested string) Target
- func (a *Access) ResolveDownload(requested string, allow func(real string) bool) (DownloadItem, *Target)
- func (a *Access) Secret(p string) bool
- func (a *Access) ServeFileBytes(w http.ResponseWriter, r *http.Request)
- func (a *Access) ServePreview(w http.ResponseWriter, r *http.Request, q Query)
- func (a *Access) ServeZip(w http.ResponseWriter, r *http.Request, q Query)
- func (a *Access) ServeZipDownload(w http.ResponseWriter, r *http.Request, items []DownloadItem, name string, ...)
- func (a *Access) WriteZip(ctx context.Context, w io.Writer, folder DownloadItem, ...) error
- type Cleanup
- type DownloadItem
- type EditorError
- type EntryError
- type Field
- type MemoryFile
- type Object
- type Query
- type Side
- type Target
- type TextHit
- type Uploads
- type Version
Constants ¶
const ( GitMarkNew = "new" GitMarkChanged = "changed" )
const ( MaxPreviewBytes = 15 * 1024 * 1024 // MaxVideoBytes bounds what the viewer plays in place; a download has no bound. MaxVideoBytes = 500 * 1024 * 1024 )
const ( // ImageMaxBytes and FileMaxBytes are the largest image and other file an upload takes. ImageMaxBytes = 10 * 1024 * 1024 FileMaxBytes = 50 * 1024 * 1024 )
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 )
const (
// ContextMaxQuery is how much of the query counts, in UTF-16 units.
ContextMaxQuery = 200
)
const MaxSaveBytes = 200 * 1024 * 1024
MaxSaveBytes is the largest file the viewer may write back.
const (
// MaxVersionBytes is the largest file kept in the history: a bigger one is saved with none.
MaxVersionBytes = 100 * 1024 * 1024
)
const (
// NotebookMaxBytes allows embedded cell output without raising the limit for ordinary text files.
NotebookMaxBytes = 16 << 20
)
const PreviewCSP = "" /* 161-byte string literal not displayed */
PreviewCSP is the policy a shown document runs under (all but PDFs and videos).
const (
// SearchMaxQuery is how long a query may be, in bytes.
SearchMaxQuery = 200
)
Variables ¶
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.
var ErrEntryExists = entryError("Something of this name is there already", "Здесь уже есть что-то с таким именем")
ErrEntryExists: the name is taken in the folder.
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.
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 ¶
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 ¶
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 ¶
AllowedContextRoot: dir (resolved) is one of the roots or inside one, each root compared by its resolved path.
func Answer ¶
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 ¶
AppendJSON writes v (string, bool, int kinds, float64, []string, []any, []Object, Object, nil).
func CheckEntryName ¶ added in v0.16.123
CheckEntryName refuses a name that is not one entry of a folder, or that looks like credentials.
func DecodeComponent ¶
DecodeComponent is a path segment decoded as the old router did: percent-decoded when that is valid, as it was otherwise.
func DecodeName ¶
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 ¶
DecodeUTF8 turns bytes into text the way a WHATWG decoder does: each maximal invalid subsequence becomes one U+FFFD.
func EncodeURIComponent ¶
EncodeURIComponent percent-encodes all but the unreserved marks, as browsers' encodeURIComponent.
func ExtName ¶
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
FileRevision names a file's state: a save over an older one is refused.
func Fresh ¶
Fresh: the caller already holds this entity (If-None-Match), and did not ask to revalidate with no-cache.
func FuzzyScore ¶
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 HomeCredentials ¶
HomeCredentials are the credential places of the home folder home.
func ImageType ¶
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
MemoryName reports whether name is a note's file name the memory accepts.
func NewEmptyFile ¶ added in v0.16.123
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 ¶
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 ¶
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 ¶
PreviewType is the content type the viewer serves a file of this extension with, and whether it is read in ranges.
func QueryUnits ¶
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 ¶
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 ¶
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
RenameEntry gives the entry at abs a new name in its folder; it answers the new path.
func RepoPath ¶
RepoPath is a path inside the repository, or ok false: absent, repeated, /dev/null, absolute, with a NUL, or climbing above the repository.
func SafeZipName ¶ added in v0.16.5
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 ¶
SearchContext is up to 20 files under root (resolved) matching the query, best first.
func SecretName ¶ added in v0.16.123
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 ¶
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
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
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 ¶
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 ¶
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 ¶
UploadType is the content type an upload is served with, "" for a type that is not served.
func WriteJSON ¶
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 ¶
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) Deny ¶
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 ¶
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
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 ¶
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) 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 ¶
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
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 DownloadItem ¶ added in v0.16.123
DownloadItem is one path asked for, resolved: its real path and whether it is a folder.
type EditorError ¶
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 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 FileContent ¶
FileContent is the answer of both sides.
func ParseMemoryNote ¶
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 ¶
ReadMemoryNote is the freshest copy of the named memory under the parents, or ok false.
func (Object) MarshalJSON ¶
MarshalJSON lets an Object be handed to encoding/json too.
type Query ¶
Query is a parsed query string: every value of each key, in order.
func ParseQuery ¶
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 ¶
RequestQuery is the request's query: what follows the first '?' of the target as it was sent.
type Side ¶
Side is one side of the diff.
func GitBlob ¶ added in v0.16.123
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.
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 ¶
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 ¶
FileName is a file's stored name: <ms>-<8 hex>-<name><extension, its letters, digits and dots, at most 16>.