revision

package
v0.6.2 Latest Latest
Warning

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

Go to latest
Published: Sep 13, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package revision implements the semantic layer of EasyVCS.

It is the only package that depends on the store.RepoStore interface for persistence; it encodes the two rules that make EasyVCS revision-native:

  1. A Revision has a stable id (revision_id) that is generated once and never modified, no matter how many times the revision is rebased, squashed, or amended. It is the user-facing unit of work.
  2. A Revision points at exactly one current Snapshot (1:1). Each rewrite (amend/rebase/squash/resolve) produces a new Snapshot with a new revision_hash, which replaces the previous one; the revision_id stays stable forever.

Index

Constants

This section is empty.

Variables

View Source
var ErrRevisionNotFound = errors.New("revision: not found")

ErrRevisionNotFound is returned when a revision id has no record.

Functions

func HasIgnoresCompiled

func HasIgnoresCompiled(m *ignore.Matcher) bool

HasIgnoresCompiled checks whether the root has any ignore files; used to skip filtering when none exist. Root is the repo root.

func IgnoreHash

func IgnoreHash(root string) (string, error)

IgnoreHash computes a stable hash over the current ignore files at root, for detecting when ignore rules change between commits. Files are sorted so the result is order-independent.

func IsIgnored

func IsIgnored(m *ignore.Matcher, rel string) bool

IsIgnored reports whether a repo-relative path is ignored by the matcher compiled from the given root.

func RenderUnified

func RenderUnified(aName, bName string, hunks []DiffHunk) string

RenderUnified renders a UnifiedDiff as text with unified headers.

func SnapshotID

func SnapshotID(s *store.Snapshot) object.ID

SnapshotID exposes the content-addressed hash computation for a snapshot.

func SortFileDiffs

func SortFileDiffs(ds []FileDiff)

SortFileDiffs orders file diffs by path.

Types

type AnnotationLine

type AnnotationLine struct {
	LineNumber int    // 1-based line number in the current content
	RevisionID string // revision id that introduced this line
	Message    string // that revision's description
	Author     string // that revision's author
	Content    string // the line text
}

AnnotationLine attributes one line of a file to the revision that last introduced it, following the file's change history.

type CommitParams

type CommitParams struct {
	// RevisionID, if non-empty, commits to an existing revision (amending it).
	// If empty, a new revision id is generated.
	RevisionID string
	// Parents are the parent snapshot ids (typically from a previous snapshot).
	Parents []object.ID
	// Description is the commit message.
	Description string
	// Author of the commit.
	Author store.Author
	// TreeID is the root tree for the commit.
	TreeID object.ID
}

CommitParams carries the inputs to a commit.

type DiffHunk

type DiffHunk struct {
	OldStart int // 1-based line in the old file where the hunk begins
	NewStart int // 1-based line in the new file where the hunk begins
	OldCount int // number of lines in the old file this hunk covers
	NewCount int // number of lines in the new file this hunk covers
	Lines    []DiffLine
}

DiffHunk represents a single contiguous block of changed lines within a modified file.

func UnifiedDiff

func UnifiedDiff(old, new []byte) []DiffHunk

UnifiedDiff computes a line-level unified diff between two blob contents. It returns nil if the contents are identical. This is a minimal Myers-style diff that is correct and readable without external dependencies.

type DiffLine

type DiffLine struct {
	Kind string // "context", "del", "add"
	Text string
}

DiffLine is a single comparison line in a hunk.

type FileChange

type FileChange struct {
	Path     string
	Status   Status
	OldID    object.ID
	NewID    object.ID
	Old, New []byte // content of removed/added (best-effort)
}

FileChange describes one file's change between two trees.

type FileChangeSpec

type FileChangeSpec struct {
	// Path is the repo-relative path (forward slashes).
	Path string
	// Content, if set and Delete is false, writes the given content to the path
	// (creating or replacing the file).
	Content []byte
	// Delete removes the path if true. Content is ignored.
	Delete bool
}

FileChangeSpec describes one file modification for an atomic commit.

type FileDiff

type FileDiff struct {
	Path         string
	Status       Status
	Content      string
	AddedLines   int
	RemovedLines int
}

FileDiff is a per-file line diff.

type FileEdit

type FileEdit struct {
	RevisionID   string
	RevisionHash object.ID
	Timestamp    time.Time
	Status       Status // added, modified, or removed relative to its parent
}

FileEdit records one revision that modified a given file.

type GCOptions

type GCOptions struct {
	// DryRun only reports the number of prunable objects without deleting.
	DryRun bool
}

GCOptions configures the reachable-object collection.

type GCResult

type GCResult struct {
	Total int // objects present
	Swept int // objects pruned (0 in dry-run)
}

GCResult summarizes a garbage-collection pass.

func GCRun

func GCRun(cs *store.CentralStore, opts GCOptions) (GCResult, error)

GCRun computes the set of objects reachable from every repository's snapshots (blob -> tree -> conflict, all content-addressed and shared globally), then prunes any object not reachable. It is a whole-store operation; use DryRun to preview. It returns counts.

type HistoryOpt

type HistoryOpt struct {
	// Start is a revision expression (branch name, tag name, revision id,
	// snapshot hash, "@", or "" for the newest revision). The walk begins at
	// the resolved revision and goes back through its ancestors.
	Start string
	// Desc orders the result newest-first (easylab-aligned). Default is
	// chronological (root first), matching the historical behaviour.
	Desc bool
	// Limit truncates the returned edits (0 = no limit).
	Limit int
}

HistoryOpt controls file history traversal.

type Path

type Path = string

Path is a repo-relative path with forward slashes.

type Status

type Status string

Status describes how a file changed between two trees.

const (
	StatusAdded    Status = "added"
	StatusModified Status = "modified"
	StatusRemoved  Status = "removed"
)

File change statuses.

type VerifyResult

type VerifyResult struct {
	Repos           int
	Revisions       int
	Snapshots       int
	Objects         int
	MissingObjects  int
	BrokenSnapshots int
}

VerifyResult reports the outcome of a store consistency check.

func Verify

func Verify(cs *store.CentralStore) (VerifyResult, error)

Verify checks store consistency: every snapshot's tree must be readable and every revision's current snapshot must resolve. It does not mutate anything.

type Workspace

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

Workspace is the semantic API over a repo-scoped store.

func NewWorkspace

func NewWorkspace(s store.RepoStore) *Workspace

NewWorkspace wraps a repo-scoped store in the semantic layer.

func (*Workspace) AllSnapshots

func (w *Workspace) AllSnapshots() (map[string]*store.Snapshot, map[object.ID]string, error)

AllSnapshots returns every snapshot reachable as a current snapshot of some revision, associated with its revision id, for graph display.

func (*Workspace) Annotate

func (w *Workspace) Annotate(startID, path string) ([]AnnotationLine, error)

Annotate renders the file at startID/path in the context of history, giving each line the revision that last touched it (line-level blame). A line that survives an edit keeps its original author; a line added by an edit is attributed to that edit's revision.

startID is the starting revision id (empty picks the newest revision). It works by walking the chronological file edits and replaying each content diff to update per-line ownership using the same LCS used by UnifiedDiff.

func (*Workspace) AnnotateAt

func (w *Workspace) AnnotateAt(opt HistoryOpt, path string) ([]AnnotationLine, error)

AnnotateAt is the parameterized form of Annotate: it accepts a HistoryOpt so the starting revision can be a branch/tag name, revision id, "@", or empty.

func (*Workspace) BuildTreeFromFS

func (w *Workspace) BuildTreeFromFS(dir string) (object.ID, error)

BuildTreeFromFS reads a filesystem directory and writes the corresponding Tree object plus all reachable blob objects into the store. It returns the root tree id.

func (*Workspace) BuildTreeFromFSWithMatcher

func (w *Workspace) BuildTreeFromFSWithMatcher(root string, m *ignore.Matcher) (object.ID, error)

BuildTreeFromFSWithMatcher builds a tree using an explicit matcher (exposed for tests and for external ignore.capture).

func (*Workspace) CollectPaths

func (w *Workspace) CollectPaths(treeID object.ID) ([]string, error)

CollectPaths lists every file path in a tree (exported).

func (*Workspace) Commit

Commit persists a new snapshot (with a new revision_hash) under a revision (existing or new), and returns the snapshot and the revision. Because Revision and Snapshot are 1:1, committing always creates one snapshot and points the revision's Hash at it, replacing any previous snapshot.

If CommitParams.RevisionID is empty, a new revision is created and its parent is the given Parents (used for linear history). If RevisionID is non-empty, the existing revision is amended and its ChangedPaths are updated to the paths that differ from the previous snapshot (if any) or the given Parents.

func (*Workspace) CommitFromChanges

func (w *Workspace) CommitFromChanges(parentHash object.ID, changes []FileChangeSpec, description string, author store.Author, revisionIDOverride string) (*store.Snapshot, *store.Revision, error)

CommitFromChanges atomically creates a revision from a set of file changes applied on top of a parent snapshot. It builds the new tree by starting from the parent's tree (or an empty tree for a root commit) and applying each change, then writes the snapshot and revision in a single database transaction so the commit is atomic.

A new revision_id is generated unless revisionIDOverride is non-empty (used by amend to keep the stable id). parents is the single parent_hash (or empty for a root commit). ChangedPaths is set to the changed paths. If parent_hash is non-empty but does not exist in this repository, an error is returned.

func (*Workspace) ComputeChangesFromDir

func (w *Workspace) ComputeChangesFromDir(parentHash object.ID, dir string) ([]FileChangeSpec, error)

ComputeChangesFromDir diffs the parent snapshot's tree (if any) against a read-only scan of the working directory, returning a list of file changes. This is the "no workdir persistence" path: nothing is written to the store. If parentHash is empty, all files in the directory are reported as additions.

func (*Workspace) ConflictsInTree

func (w *Workspace) ConflictsInTree(treeID object.ID) ([]merge.ConflictAtom, error)

ConflictsInTree returns the conflict atoms embedded in a tree.

func (*Workspace) DeleteRef

func (w *Workspace) DeleteRef(name string) error

DeleteRef removes a ref.

func (*Workspace) Derive

func (w *Workspace) Derive(sourceRevisionID string, description string, autoCommit bool) (*store.Snapshot, *store.Revision, error)

Derive creates a new branch revision that shares the source revision's content (same tree and parents) but carries a fresh, independent revision id, plus a ForkFrom pointer back to the source. This is the "branch = derive" primitive: the derived revision can be amended on its own branch without mutating the revision shared by any other branch (which would otherwise leak an in-place amend across branches).

Because snapshotID includes the revision id, the derived snapshot has a different hash than the source even though its content is identical, so the two revisions are never confused and never share a mutable snapshot.

description is the commit message for the derived revision. If empty, the source revision's message is used; if the source has no message either, an error is returned (a derive must always carry a commit message).

autoCommit controls what happens when the source is an uncommitted revision (a revision with no commit message): with autoCommit true the derive proceeds (the caller is asserting they want to finalize the fork point now); with autoCommit false an error is returned, requiring the caller to commit the source first.

func (*Workspace) DescendantsOf

func (w *Workspace) DescendantsOf(revID string) ([]string, error)

DescendantsOf returns the revision ids (in ancestor-first order) that are reachable from revID by following the FIRST parent chain downwards. In the linear/single-parent model this is simply the chain of commits that come after revID. The result excludes revID itself.

func (*Workspace) Diff

func (w *Workspace) Diff(a, b object.ID) ([]FileChange, error)

Diff walks two trees and lists per-file differences.

func (*Workspace) DiffBaseForRevision

func (w *Workspace) DiffBaseForRevision(revisionID string) (object.ID, error)

DiffBaseForRevision returns the tree to diff a revision against, always the first parent's tree (root -> empty tree). The model is single-parent/linear: every revision has exactly one parent, so the diff base is unambiguous.

func (*Workspace) DiffContent

func (w *Workspace) DiffContent(a, b object.ID) ([]FileDiff, error)

DiffContent computes a file-level unified diff between two trees, using the blob contents. It returns a list of per-file diffs (or nil for unchanged).

func (*Workspace) DiffContentFromChanges

func (w *Workspace) DiffContentFromChanges(changes []FileChange) ([]FileDiff, error)

DiffContentFromChanges renders pre-computed file changes as unified diffs.

func (*Workspace) Drop

func (w *Workspace) Drop(revID string) ([]*store.Revision, error)

Drop removes a revision from history by rebasing all of its descendants onto the revision's parent, then re-pointing them so the dropped revision becomes unreachable. It is the "erase from history" operation (no op-log preserved). Returns the moved descendant revisions.

func (*Workspace) DropIgnoredPathsFromTree

func (w *Workspace) DropIgnoredPathsFromTree(root string, m *ignore.Matcher, treeID object.ID) (object.ID, error)

DropIgnoredPathsFromTree removes every path in a tree that is matched by the ignore matcher (compiled from the given root). It recursively rewrites trees, dropping ignored file leaves and pruning empty directories. This is the "auto-exclude ignored files from history" operation: after a commit detects a .gitignore/.vcsignore change, the recorded tree is filtered.

func (*Workspace) FileHistory

func (w *Workspace) FileHistory(startID, path string) ([]FileEdit, error)

FileHistory returns the revisions (walking the DAG from the start revision upward to the root) that modified the given repo-relative path. A revision is included only when its ChangedPaths mentions the path and the blob hash actually differs from the previous revision that touched it.

startID is a convenience that overrides opt.Start when non-empty. When opt.Desc is set the result is ordered newest-first; otherwise it is chronological (root-first).

func (*Workspace) FileHistoryOpt

func (w *Workspace) FileHistoryOpt(opt HistoryOpt, path string) ([]FileEdit, error)

FileHistoryOpt is the parameterized form of FileHistory.

func (*Workspace) FilesChanged

func (w *Workspace) FilesChanged(revisionID string) ([]FileChange, error)

FilesChanged returns the per-file change list for a revision, expressed against its first-parent base (root -> empty). This is the "which files did this revision, and how" view.

func (*Workspace) FindEntry

func (w *Workspace) FindEntry(t *object.Tree, path string) (object.Entry, error)

FindEntry walks a tree down to the entry at path (exported).

func (*Workspace) GetRef

func (w *Workspace) GetRef(name string) (*store.Ref, error)

GetRef returns a ref by name.

func (*Workspace) GetRevision

func (w *Workspace) GetRevision(id string) (*store.Revision, error)

GetRevision returns a revision by id.

func (*Workspace) GetSnapshot

func (w *Workspace) GetSnapshot(id object.ID) (*store.Snapshot, error)

GetSnapshot returns a snapshot by id.

func (*Workspace) ListRefs

func (w *Workspace) ListRefs() ([]*store.Ref, error)

ListRefs returns all refs.

func (*Workspace) Log

func (w *Workspace) Log() ([]*store.Revision, error)

Log returns the revisions sorted by most-recent first.

func (*Workspace) Materialize

func (w *Workspace) Materialize(treeID object.ID, dest string) error

Materialize writes a tree's contents into a directory, rendering conflicts as marker files.

func (*Workspace) Merge

func (w *Workspace) Merge(base, ours, theirs object.ID) (object.ID, []merge.ConflictAtom, error)

Merge performs a 3-way merge of the trees of two snapshots, recording any conflicts as first-class objects in the resulting tree. A persistence failure while storing the merged tree (or an embedded conflict object) is returned as an error.

func (*Workspace) MustTree

func (w *Workspace) MustTree(id object.ID) *object.Tree

MustTree reads a tree by id, returning an empty tree on error (exported).

func (*Workspace) ParentsOfRevision

func (w *Workspace) ParentsOfRevision(revisionID string) ([]object.ID, error)

ParentsOfRevision returns the parent snapshot ids of a revision's current snapshot. If the revision or snapshot is missing, it returns an empty slice.

func (*Workspace) ReadBlob

func (w *Workspace) ReadBlob(id object.ID) ([]byte, error)

ReadBlob reads a blob's contents by id.

func (*Workspace) ReadTree

func (w *Workspace) ReadTree(id object.ID) (*object.Tree, error)

ReadTree reads a tree object from the store.

func (*Workspace) Rebase

func (w *Workspace) Rebase(revisionID string, newParents []object.ID) (*store.Snapshot, *store.Revision, error)

Rebase repoints a revision onto a single parent, re-creating its snapshot with a new revision_hash while keeping the same revision id. The target tree is recomputed via a 3-way merge so the revision's own diff is genuinely re-applied onto the new base (not merely re-parented). Overlapping edits are recorded as first-class conflict objects in the resulting tree.

newParents must be exactly one snapshot hash. Multi-parent rebase is not a supported operation (the model is single-parent / linear).

func (*Workspace) RebaseMany

func (w *Workspace) RebaseMany(revs []string, onto object.ID) ([]*store.Revision, error)

RebaseMany moves a set of revisions onto a new base in one chained operation, re-parenting them in ancestor order so the result is a linear sequence. It is the multi-revision convenience over Rebase: for example, rebasing [D, H] (with chain B-D-G-H) onto F yields A-B-C-E-F-D-H, dropping G. Revisions not in the set (e.g. G) become unreachable and are effectively discarded.

revs are revision ids in the order they should appear on the new line (tip last). Every moved revision keeps its own id and has its tree recomputed via 3-way merge; overlapping edits become first-class conflict objects.

func (*Workspace) RebuildTreeFiltered

func (w *Workspace) RebuildTreeFiltered(root string, m *ignore.Matcher, treeID object.ID) (object.ID, error)

RebuildTreeFiltered is a convenience that reads a tree, applies a matcher and writes back a filtered tree id. Root is the repo root (for relative ignore paths).

func (*Workspace) Resolve

func (w *Workspace) Resolve(revisionID string, path string, sideIndex int) (*store.Snapshot, *store.Revision, error)

Resolve replaces the conflict at the given path in a revision's current tree with a chosen side, keeping the same revision id. Resolution propagates to descendant revisions that still carry the same conflict.

func (*Workspace) ResolveRevisions

func (w *Workspace) ResolveRevisions(exprs []string) ([]object.ID, []*store.Revision, error)

ResolveRevisions resolves user input expressions to snapshot ids via the current revision pointers. Supported forms are '@', '@-', and a revision id.

func (*Workspace) Revert

func (w *Workspace) Revert(revID string, onto object.ID) (*store.Snapshot, *store.Revision, error)

Revert creates a new revision that undoes the changes introduced by revID, applied on top of onto (default: the current tip). The historical revision is preserved; this is the inverse-patch model (like `git revert`), distinct from Drop which erases the revision. Conflicts appear as first-class objects.

func (*Workspace) RewriteHistoryWithIgnores

func (w *Workspace) RewriteHistoryWithIgnores(root string, m *ignore.Matcher, revisionID string) (int, error)

RewriteHistoryWithIgnores rewrites all snapshots that are ancestors of revisionID so that any path now matched by the matcher is removed from every affected snapshot's tree. Each rewritten snapshot keeps its revision id and metadata; only the tree (and thus the snapshot id) changes. Descendants are automatically rebased because they reference parent snapshot ids.

It returns the number of snapshots rewritten.

func (*Workspace) SetDescription

func (w *Workspace) SetDescription(revisionID string, description string) (*store.Snapshot, *store.Revision, error)

SetDescription rewrites a revision's commit message while keeping its id, tree, parents, and author unchanged. Since the snapshot hash derives from the description, the snapshot is rewritten and the revision is repointed to it.

func (*Workspace) SetRef

func (w *Workspace) SetRef(name string, kind store.RefKind, revisionID string) (*store.Ref, error)

SetRef creates or updates a branch/tag pointing to a revision.

A tag is immutable: creating a tag with a name that already exists returns an error (delete it first via DeleteRef). Branches remain re-pointable.

func (*Workspace) Squash

func (w *Workspace) Squash(childRevisionID string) (*store.Snapshot, *store.Revision, error)

Squash absorbs the changes in a revision into its parent revision, keeping the parent revision's id stable.

func (*Workspace) WriteBlob

func (w *Workspace) WriteBlob(data []byte) (object.ID, error)

WriteBlob writes a blob object and returns its id. A persistence failure is returned as an error rather than silently returning an unreferenced id.

func (*Workspace) WriteConflict

func (w *Workspace) WriteConflict(c *object.Conflict) (object.ID, error)

WriteConflict implements merge.treeOps.

func (*Workspace) WriteTree

func (w *Workspace) WriteTree(t *object.Tree) (object.ID, error)

WriteTree stores a tree object and returns its id (exported).

Jump to

Keyboard shortcuts

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