Documentation
¶
Overview ¶
Package txtar implements a pure-stdlib reader, formatter, manifest builder, and versioned in-memory virtual workspace (VFS) for txtar archives.
The archive format matches golang.org/x/tools/txtar: an optional header comment followed by one or more files delimited by "-- name --\n" markers, with trailing-newline normalization on non-empty comments and file bodies.
Archives and Manifests ¶
Use Parse and Format to decode and encode archives, Archive.Sort for deterministic entry ordering, Archive.Digest for a canonical SHA-256 hex digest, and Archive.BuildManifest for a JSON manifest listing per-file SHA-256 digests and byte lengths:
a := txtar.Parse(raw) a.Sort() manifestJSON, err := a.BuildManifest()
Versioned Virtual Workspace ¶
VFS provides an in-memory, revisioned workspace seeded from an *Archive (revision 0) with per-path access policies (ModeWritable, ModeReadOnly, ModeDerived) and syntax gates (GateStrict, GateWarn, GateOff).
Every accepted edit via VFS.EditLines or VFS.ApplyBytes checks the caller's compare-and-swap expected revision, runs any configured syntax checker and policy guard hooks, and appends an immutable revision N+1. Server-side derived artifacts (such as compiled PTX, SASS, or diagnostic reports) are updated via VFS.SetDerived without relaxing ModeReadOnly files or invalidating compare-and-swap revisions. Use VFS.Diff, VFS.Revert, and VFS.Snapshot to inspect history, roll back state, and export a complete deterministic archive with manifest.json.
All VFS methods are safe for concurrent use by multiple goroutines. The zero value of VFS is not usable; construct one with NewVFS.
This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/txtar"
)
func main() {
raw := []byte("# kernel bundle\n-- b.txt --\nbeta\n-- a.txt --\nalpha\n")
a := txtar.Parse(raw)
a.Sort()
fmt.Printf("files: %d (%s, %s)\n", len(a.Files), a.Files[0].Name, a.Files[1].Name)
fmt.Printf("digest len: %d\n", len(a.Digest()))
}
Output: files: 2 (a.txt, b.txt) digest len: 64
Index ¶
- Constants
- Variables
- func Format(a *Archive) []byte
- func UnifiedDiff(oldName, newName string, oldData, newData []byte) string
- type Archive
- type CheckFinding
- type CheckFunc
- type CheckReport
- type CheckSeverity
- type EditOptions
- type EditResult
- type File
- type FileInfo
- type LineEdit
- type Manifest
- type ManifestFile
- type Mode
- type Policy
- type ReadResult
- type SyntaxGate
- type VFS
- func (v *VFS) ApplyBytes(p string, expectedRev uint64, newBytes []byte, opts EditOptions) (EditResult, error)
- func (v *VFS) Diff(fromRev, toRev uint64) (string, error)
- func (v *VFS) EditLines(p string, expectedRev uint64, edits []LineEdit, opts EditOptions) (EditResult, error)
- func (v *VFS) List() []FileInfo
- func (v *VFS) Read(p string, startLine, endLine int) (ReadResult, error)
- func (v *VFS) Rev() uint64
- func (v *VFS) Revert(targetRev uint64) (uint64, error)
- func (v *VFS) SetDerived(p string, data []byte) error
- func (v *VFS) Snapshot(headerComment string) *Archive
- func (v *VFS) SnapshotAt(rev uint64, headerComment string) (*Archive, error)
- type VFSOption
Examples ¶
Constants ¶
const ManifestSchema = "txtar-manifest/v1"
ManifestSchema is the schema identifier emitted by Archive.BuildManifest.
Variables ¶
var ( ErrNotFound = errors.New("file not found") ErrReadOnly = errors.New("file is read-only") ErrDerived = errors.New("file is derived") ErrNotDerived = errors.New("file is not derived") ErrRevMismatch = errors.New("revision mismatch") ErrInvalidRev = errors.New("invalid revision") ErrInvalidPath = errors.New("invalid path") ErrInvalidRange = errors.New("invalid line range") ErrAnchorMismatch = errors.New("expected old text mismatch") ErrOverlappingEdits = errors.New("overlapping edits") ErrSyntaxGate = errors.New("syntax gate rejected edit") ErrGuardRejected = errors.New("guard rejected edit") )
Sentinel errors returned by VFS operations. Callers should inspect errors with errors.Is.
Functions ¶
func Format ¶
Format encodes an *Archive into the canonical txtar wire format. A nil archive formats to nil.
func UnifiedDiff ¶
UnifiedDiff returns a unified diff of the named byte sequences. It returns an empty string when both sequences are identical.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/txtar"
)
func main() {
fmt.Print(txtar.UnifiedDiff("old", "new", []byte("before\n"), []byte("after\n")))
}
Output: --- old +++ new @@ -1,1 +1,1 @@ -before +after
Types ¶
type Archive ¶
An Archive is a collection of named files with an optional header comment.
func Parse ¶
Parse decodes a txtar-formatted byte slice into an *Archive. The returned archive does not alias data.
func (*Archive) BuildManifest ¶
BuildManifest encodes Archive.Manifest as indented UTF-8 JSON with a trailing newline.
Example ¶
package main
import (
"encoding/json"
"fmt"
"github.com/tmc/lib/nvidia/x/host/txtar"
)
func main() {
a := txtar.Parse([]byte("-- kernel.cu --\n__global__ void k() {}\n"))
raw, err := a.BuildManifest()
if err != nil {
fmt.Println("error:", err)
return
}
var m txtar.Manifest
if err := json.Unmarshal(raw, &m); err != nil {
fmt.Println("error:", err)
return
}
fmt.Printf("schema=%s file=%s bytes=%d\n", m.Schema, m.Files[0].Path, m.Files[0].Bytes)
}
Output: schema=txtar-manifest/v1 file=kernel.cu bytes=23
type CheckFinding ¶
type CheckFinding struct {
Line int `json:"line,omitempty"`
Column int `json:"column,omitempty"`
Severity CheckSeverity `json:"severity"`
Code string `json:"code,omitempty"`
Message string `json:"message"`
}
CheckFinding describes one syntax error, warning, or guard violation.
type CheckFunc ¶
type CheckFunc func(path string, oldSrc, newSrc []byte) (CheckReport, error)
CheckFunc inspects a proposed file mutation from oldSrc to newSrc at path. It is used for both syntax checkers and policy guards.
type CheckReport ¶
type CheckReport struct {
Errors []CheckFinding `json:"errors,omitempty"`
Warnings []CheckFinding `json:"warnings,omitempty"`
}
CheckReport is returned by a CheckFunc syntax checker or policy guard.
func (CheckReport) HasErrors ¶
func (r CheckReport) HasErrors() bool
HasErrors reports whether r contains at least one error finding.
type CheckSeverity ¶
type CheckSeverity string
CheckSeverity classifies a finding in a CheckReport.
const ( SeverityError CheckSeverity = "error" SeverityWarning CheckSeverity = "warning" SeverityInfo CheckSeverity = "info" )
type EditOptions ¶
type EditOptions struct {
// AllowSyntaxError permits an edit to commit even when SyntaxGate is
// GateStrict and the syntax checker reports errors. It never bypasses
// policy guards.
AllowSyntaxError bool
// SyntaxChecker overrides the VFS default syntax checker for this call.
SyntaxChecker CheckFunc
// Guard runs in addition to any VFS-level guards for this call.
Guard CheckFunc
}
EditOptions customizes a single VFS.EditLines or VFS.ApplyBytes call.
type EditResult ¶
type EditResult struct {
Path string `json:"path"`
OldRev uint64 `json:"old_rev"`
NewRev uint64 `json:"new_rev"`
SHA256 string `json:"sha256"`
Bytes int `json:"bytes"`
UnifiedDiff string `json:"unified_diff"`
SyntaxErrors []CheckFinding `json:"syntax_errors,omitempty"`
GuardErrors []CheckFinding `json:"guard_errors,omitempty"`
Warnings []CheckFinding `json:"warnings,omitempty"`
}
EditResult is returned by VFS.EditLines and VFS.ApplyBytes. When an edit is rejected by a syntax gate or guard, EditResult is still populated with Path, OldRev, UnifiedDiff, SyntaxErrors, GuardErrors, and Warnings so callers can surface structured diagnostics.
type FileInfo ¶
type FileInfo struct {
Path string `json:"path"`
Mode Mode `json:"mode"`
Lang string `json:"lang,omitempty"`
Rev uint64 `json:"rev"`
Bytes int `json:"bytes"`
SHA256 string `json:"sha256"`
}
FileInfo describes a virtual file at the current workspace revision.
type LineEdit ¶
type LineEdit struct {
StartLine int `json:"start_line"`
EndLine int `json:"end_line"`
ExpectedOld string `json:"expected_old,omitempty"`
NewText string `json:"new_text"`
}
LineEdit describes an atomic 1-based inclusive line replacement [StartLine, EndLine].
If EndLine >= StartLine, lines StartLine..EndLine are replaced with NewText (empty NewText deletes those lines). If EndLine == StartLine-1 (for example StartLine=1, EndLine=0 to insert at the top of the file, or StartLine=totalLines+1, EndLine=totalLines to append), NewText is inserted before StartLine without removing existing lines.
If ExpectedOld is non-empty, the current text in [StartLine, EndLine] must match ExpectedOld (tolerating a single trailing newline difference) or the edit fails with ErrAnchorMismatch.
type Manifest ¶
type Manifest struct {
Schema string `json:"schema"`
ArchiveSHA256 string `json:"archive_sha256"`
Files []ManifestFile `json:"files"`
}
Manifest is the structured JSON summary emitted by Archive.BuildManifest.
type ManifestFile ¶
type ManifestFile struct {
Path string `json:"path"`
Bytes int `json:"bytes"`
SHA256 string `json:"sha256"`
}
ManifestFile records the byte length and SHA-256 hex digest of one file.
type Mode ¶
type Mode string
Mode controls how a virtual file in a VFS may be modified.
const ( // ModeWritable allows edits via [VFS.EditLines] and [VFS.ApplyBytes]. ModeWritable Mode = "writable" // ModeReadOnly allows reading, listing, and diffing, but rejects all writes. ModeReadOnly Mode = "readonly" // ModeDerived allows server-side updates via [VFS.SetDerived] only. ModeDerived Mode = "derived" )
type Policy ¶
type Policy struct {
Mode Mode `json:"mode"`
SyntaxGate SyntaxGate `json:"syntax_gate,omitempty"`
Lang string `json:"lang,omitempty"`
}
Policy configures the access mode, syntax gate, and language tag for a path or path pattern in a VFS.
type ReadResult ¶
type ReadResult struct {
Path string `json:"path"`
Mode Mode `json:"mode"`
Lang string `json:"lang,omitempty"`
Text string `json:"text"`
StartLine int `json:"start_line"`
EndLine int `json:"end_line"`
TotalLines int `json:"total_lines"`
Rev uint64 `json:"rev"`
SHA256 string `json:"sha256"` // SHA-256 hex digest of the full file content
}
ReadResult is returned by VFS.Read.
type SyntaxGate ¶
type SyntaxGate string
SyntaxGate controls how findings from a syntax checker affect an edit.
const ( // GateStrict rejects edits when the syntax checker reports any error, // unless [EditOptions.AllowSyntaxError] is set. GateStrict SyntaxGate = "strict" // GateWarn admits edits even when the syntax checker reports errors, // surfacing them in [EditResult.SyntaxErrors]. GateWarn SyntaxGate = "warn" // GateOff skips running the syntax checker for the path. GateOff SyntaxGate = "off" )
type VFS ¶
type VFS struct {
// contains filtered or unexported fields
}
VFS is a thread-safe, revisioned in-memory txtar workspace. Construct a VFS with NewVFS.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/txtar"
)
func main() {
seed := txtar.Parse([]byte(`-- host/launch.go --
package host
-- kernel/add.cu --
__global__ void add(float* x) {
x[0] = 1.0f;
}
`))
vfs, err := txtar.NewVFS(seed, map[string]txtar.Policy{
"kernel/add.cu": {Mode: txtar.ModeWritable},
"host/launch.go": {Mode: txtar.ModeReadOnly},
"compiled/": {Mode: txtar.ModeDerived},
})
if err != nil {
fmt.Println("error:", err)
return
}
res, err := vfs.EditLines("kernel/add.cu", 0, []txtar.LineEdit{
{StartLine: 2, EndLine: 2, ExpectedOld: " x[0] = 1.0f;", NewText: " x[0] = 2.0f;"},
}, txtar.EditOptions{})
if err != nil {
fmt.Println("error:", err)
return
}
if err := vfs.SetDerived("compiled/add.ptx", []byte(".version 8.5\n")); err != nil {
fmt.Println("error:", err)
return
}
snap := vfs.Snapshot("# rev 1\n")
fmt.Printf("rev: %d, snapshot files: %d\n", res.NewRev, len(snap.Files))
}
Output: rev: 1, snapshot files: 4
func NewVFS ¶
NewVFS constructs a VFS seeded from archive at revision 0.
Files present in seed without an explicit policy default to ModeReadOnly and GateStrict. Keys in policies may be exact relative POSIX paths, directory prefixes ending in "/" (e.g. "compiled/"), or path.Match patterns (e.g. "compiled/*.ptx"). Exact policies take precedence over patterns; among matching patterns, the longest pattern wins.
func (*VFS) ApplyBytes ¶
func (v *VFS) ApplyBytes(p string, expectedRev uint64, newBytes []byte, opts EditOptions) (EditResult, error)
ApplyBytes replaces the full contents of a ModeWritable file at path with newBytes, enforcing the same CAS expectedRev, policy, unified diff, syntax gate, and guard checks as VFS.EditLines.
func (*VFS) Diff ¶
Diff returns a deterministic unified diff across all files that differ between fromRev and toRev.
func (*VFS) EditLines ¶
func (v *VFS) EditLines(p string, expectedRev uint64, edits []LineEdit, opts EditOptions) (EditResult, error)
EditLines atomically applies non-overlapping 1-based line edits to a ModeWritable file at path, checking expectedRev (CAS), optional ExpectedOld anchors, syntax gate, and policy guards.
func (*VFS) Read ¶
func (v *VFS) Read(p string, startLine, endLine int) (ReadResult, error)
Read returns the full content or a 1-based inclusive line slice [startLine, endLine] of the file at path in the current revision.
Pass startLine=0, endLine=0 to read the entire file. Pass endLine=0 with startLine>0 to read from startLine through the end of the file. If endLine exceeds the total number of lines, it is clamped to the final line.
func (*VFS) Revert ¶
Revert appends a new immutable revision whose file states match targetRev and returns the new revision number. History is preserved intact.
func (*VFS) SetDerived ¶
SetDerived updates or creates a ModeDerived file in the current revision without requiring CAS or advancing the revision counter. It refuses any path whose policy is ModeReadOnly or ModeWritable.
type VFSOption ¶
type VFSOption func(*VFS)
VFSOption configures optional defaults on a VFS created by NewVFS.
func WithGuard ¶
WithGuard appends a policy guard hook that runs on every writable edit. Guard errors are always blocking and are not bypassed by GateWarn, GateOff, or EditOptions.AllowSyntaxError.
func WithSyntaxChecker ¶
WithSyntaxChecker configures the default syntax checker run on edits when EditOptions.SyntaxChecker is nil.