store

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: 24 Imported by: 0

Documentation

Overview

Package store defines the persistent storage boundary for EasyVCS.

EasyVCS uses a single central SQL database (default ~/.easyvcs/easyvcs.db, overridable via EASYVCS_HOME). All repositories live in that one database, keyed by a (namespace, name) pair. Content-addressed objects are global and deduplicated across repositories; revisions, snapshots, and refs are scoped to a repository via a repo id.

The semantic layer depends on the repo-scoped RepoStore interface, never on a concrete backend. This lets the same code run against SQLite (local) or Postgres (server) with no changes, and no cgo.

Index

Constants

View Source
const (
	KindSQLite   = "sqlite"
	KindPostgres = "postgres"
	KindMySQL    = "mysql"
)

Kinds of metadata backends.

View Source
const (
	RoleReadonly = "readonly"
	RoleMember   = "member"
	RoleAdmin    = "admin"
	RoleOwner    = "owner"
)

Namespace member roles. Write access requires member/admin/owner; readonly grants read only.

View Source
const DefaultDBFile = "easyvcs.db"

DefaultDBFile is the file name of the central database inside the home dir.

View Source
const WorkspaceMarkerFile = ".easyvcs-workspace"

WorkspaceMarkerFile is the name of the workspace pointer file placed at a working directory root.

Variables

View Source
var ErrNotFound = errors.New("store: not found")

ErrNotFound is returned when a keyed entity is absent.

View Source
var ErrRepoExists = errors.New("store: repository already exists")

ErrRepoExists is returned when trying to create a repository that already exists.

View Source
var ErrRepoNotFound = errors.New("store: repository not found")

ErrRepoNotFound is returned when a repository is absent.

View Source
var ErrRevisionChanged = errors.New("store: revision changed concurrently")

ErrRevisionChanged is returned by an optimistic update (CAS) when a revision's current hash no longer matches the value the caller read, meaning another writer modified the revision concurrently. Callers should retry.

View Source
var ErrTokenNotFound = errors.New("store: token not found")

ErrTokenNotFound is returned when a token is unknown.

View Source
var ErrUsernameTaken = errors.New("store: username already exists")

ErrUsernameTaken is returned when creating a user that already exists.

Functions

func DBPath

func DBPath() string

DBPath returns the path to the central database file.

func HomeDir

func HomeDir() string

HomeDir returns the EasyVCS home directory (default ~/.easyvcs, overridable via EASYVCS_HOME).

func SnapshotHashFor

func SnapshotHashFor(s *Snapshot) object.ID

SnapshotHashFor computes the content-addressed revision hash for a snapshot. It is the store-level canonical form (matching the revision package's snapshotID): the hash is derived from the revision id, tree, parents, description, and author. It is exported so the store can recompute a hash when re-keying a snapshot (e.g. forked revisions get a fresh identity).

func WriteMarker

func WriteMarker(dir string, m *WorkspaceMarker) error

WriteMarker writes a workspace marker file at the given directory root. If the marker does not already record a store location (Home/DSN), the process's HomeDir() is recorded so the workspace is self-describing; a caller that binds a workspace to a different store sets Home/DSN explicitly beforehand.

Types

type AuditEvent

type AuditEvent struct {
	Timestamp int64
	Action    string // "advertise" | "fetch" | "push"
	Namespace string
	Repo      string
	UserID    *int64
	IP        string
	Outcome   string // "ok" | "denied" | "error"
	Detail    string
}

AuditEvent is a plain append-only record of an access attempt.

type Author

type Author struct {
	Name  string
	Email string
}

Author is a named identity.

func (Author) String

func (a Author) String() string

String renders an author as "Name <email>".

type CentralStore

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

sqlDialect is defined in driver.go; it provides both the raw *sql.DB handle (for SetWAL and legacy helpers) and the GORM session used for model queries. CentralStore is the single-database store. It holds many repositories, each identified by (namespace, name). Objects are global (content-addressed and deduplicated); metadata tables are scoped by a repo id.

func Open

func Open(path string) (*CentralStore, error)

Open opens the central store at the given SQLite file path (legacy helper).

func OpenDefault

func OpenDefault() (*CentralStore, error)

OpenDefault opens the central store at the default SQLite path.

func OpenDriver

func OpenDriver(cfg DriverConfig) (*CentralStore, error)

OpenDriver opens the central store on the configured backend. The semantic layer (revision/merge/transfer) is agnostic; only this boundary changes. Storage is now GORM-backed so the three dialects share one code path.

func OpenStoreForMarker

func OpenStoreForMarker(m *WorkspaceMarker) (*CentralStore, error)

OpenStoreForMarker opens the central store that a workspace marker belongs to. The marker must record a store location (Home for a sqlite store, or DSN as an override). Unlike the legacy fallback, there is no silent reliance on the process EASYVCS_HOME: an empty Home and DSN is treated as an invalid marker.

func (*CentralStore) AddComment

func (s *CentralStore) AddComment(mrID int64, authorID *int64, body, path string) (*Comment, error)

AddComment appends a comment to an MR.

func (*CentralStore) AddNamespaceMember

func (s *CentralStore) AddNamespaceMember(namespace string, userID int64, role string) error

AddNamespaceMember grants a user membership in a namespace with a role. The row's tenant is taken from the USER (users are 1:1 tenants), which also pins the membership to that tenant's namespace of the same name.

func (*CentralStore) AddReview

func (s *CentralStore) AddReview(mrID int64, reviewerID *int64, state, body string) (*Review, error)

AddReview appends a review to an MR.

func (*CentralStore) AllMirrors

func (s *CentralStore) AllMirrors() ([]*Repo, RepoMetaMap, error)

AllMirrors lists every read-only mirror repository (scheduler). The mirror token is decrypted (RepoMeta.UpdateMirrorMeta encrypts on write; this raw row read must mirror that).

func (*CentralStore) AllPushMirrors

func (s *CentralStore) AllPushMirrors() ([]*PushMirror, error)

AllPushMirrors lists every push-mirror across all repositories (scheduler). Tokens are decrypted for the scheduler's authenticated pushes.

func (*CentralStore) Close

func (s *CentralStore) Close() error

Close closes the underlying database.

func (*CentralStore) Create

func (s *CentralStore) Create(r RepoRef) (*Repo, error)

Create creates a new repository and returns a repo-scoped handle.

func (*CentralStore) CreateMergeRequest

func (s *CentralStore) CreateMergeRequest(repoID int64, mr *MergeRequest) (*MergeRequest, error)

CreateMergeRequest inserts a new MR and returns it. IID is assigned monotonically per repo.

func (*CentralStore) CreateMirror

func (s *CentralStore) CreateMirror(r RepoRef, meta RepoMeta) (*Repo, error)

CreateMirror creates a read-only mirror repository and returns its handle.

func (*CentralStore) CreateTenant added in v0.6.0

func (s *CentralStore) CreateTenant(slug, displayName string) (*Tenant, error)

CreateTenant inserts a tenant. The slug must be unique.

func (*CentralStore) CreateToken

func (s *CentralStore) CreateToken(token string, userID int64, level string) (*Token, error)

CreateToken inserts a bearer token for a user. The token is stored as its SHA-256 hash; the returned Token carries the plaintext for one-time display.

func (*CentralStore) CreateUser

func (s *CentralStore) CreateUser(username, displayName string) (*User, error)

CreateUser inserts a new user. Creating the first user closes the instance (anonymous access stops being allowed). TenantID 0 pins the user to the default tenant.

func (*CentralStore) CreateUserTenant added in v0.6.0

func (s *CentralStore) CreateUserTenant(tid int64, username, displayName string) (*User, error)

CreateUserTenant is the tenant-explicit form.

func (*CentralStore) Delete

func (s *CentralStore) Delete(r RepoRef) error

Delete removes a repository and all of its scoped metadata. Reviews and comments are removed via a subquery on the repo's MR ids; any failure is returned (no silent partial deletes).

func (*CentralStore) DeleteToken

func (s *CentralStore) DeleteToken(token string) error

DeleteToken removes a token by its secret value.

func (*CentralStore) Fork

func (s *CentralStore) Fork(src RepoRef, dst RepoRef) (*Repo, error)

Fork copies a repository's scoped data (snapshots, revisions, refs) plus its hosting metadata into a new (namespace, name), sharing the global object store. The source repository is left untouched. It returns the new repo.

func (*CentralStore) GetMergeRequest

func (s *CentralStore) GetMergeRequest(repoID, iid int64) (*MergeRequest, error)

GetMergeRequest returns an MR by repo + iid.

func (*CentralStore) GetNamespaceMember

func (s *CentralStore) GetNamespaceMember(namespace string, userID int64) (*NamespaceMember, error)

GetNamespaceMember returns a user's membership in a namespace.

func (*CentralStore) GetTenant added in v0.6.0

func (s *CentralStore) GetTenant(id int64) (*Tenant, error)

GetTenant returns a tenant by id.

func (*CentralStore) GetTenantBySlug added in v0.6.0

func (s *CentralStore) GetTenantBySlug(slug string) (*Tenant, error)

GetTenantBySlug returns a tenant by slug.

func (*CentralStore) GetUser

func (s *CentralStore) GetUser(id int64) (*User, error)

GetUser returns a user by id.

func (*CentralStore) GetUserByUsername

func (s *CentralStore) GetUserByUsername(username string) (*User, error)

GetUserByUsername returns a user by username.

func (*CentralStore) GetWorkspaceByPath

func (s *CentralStore) GetWorkspaceByPath(path string) (*WorkspaceRow, error)

GetWorkspaceByPath looks up a workspace row by path.

func (*CentralStore) Init

func (s *CentralStore) Init() error

Init creates the schema via GORM AutoMigrate, generating portable DDL (sqlite / postgres / mysql). Idempotent.

func (*CentralStore) IsNamespaceMember

func (s *CentralStore) IsNamespaceMember(namespace string, userID int64) bool

IsNamespaceMember reports whether a user belongs to a namespace, regardless of role. The user has read access to that namespace's private repositories.

func (*CentralStore) IsOpenInstance

func (s *CentralStore) IsOpenInstance() bool

IsOpenInstance is the exported form of instanceIsOpen for callers outside the store package (e.g. easyvcs-server). It reports whether the instance has no registered users, in which case anonymous access is allowed (CLI default).

func (*CentralStore) List

func (s *CentralStore) List() ([]RepoRef, error)

func (*CentralStore) ListAudit

func (s *CentralStore) ListAudit(limit int) ([]AuditEvent, error)

ListAudit returns the most recent audit records (newest first), used for verification/diagnostics.

func (*CentralStore) ListComments

func (s *CentralStore) ListComments(mrID int64) ([]*Comment, error)

ListComments returns comments for an MR.

func (*CentralStore) ListForTenant added in v0.6.0

func (s *CentralStore) ListForTenant(tid int64) ([]RepoRef, error)

List returns all repositories sorted by namespace/name. ListForTenant returns every repository of one tenant.

func (*CentralStore) ListMergeRequests

func (s *CentralStore) ListMergeRequests(repoID int64, state string) ([]*MergeRequest, error)

ListMergeRequests returns MRs for a repo, optionally filtered by state.

func (*CentralStore) ListNamespaceMembers

func (s *CentralStore) ListNamespaceMembers(namespace string) ([]*NamespaceMember, error)

ListNamespaceMembers lists members of a namespace. ListNamespaceMembers lists members of a namespace within one tenant.

func (*CentralStore) ListNamespaceMembersTenant added in v0.6.0

func (s *CentralStore) ListNamespaceMembersTenant(tid int64, namespace string) ([]*NamespaceMember, error)

ListNamespaceMembersTenant is the tenant-scoped form.

func (*CentralStore) ListReviews

func (s *CentralStore) ListReviews(mrID int64) ([]*Review, error)

ListReviews returns reviews for an MR.

func (*CentralStore) ListTenants added in v0.6.0

func (s *CentralStore) ListTenants() ([]*Tenant, error)

ListTenants returns all tenants ordered by slug.

func (*CentralStore) ListTokens

func (s *CentralStore) ListTokens(userID int64) ([]*Token, error)

ListTokens returns all tokens for a user. The stored value is a SHA-256 hash and is NOT returned; Token.Token is empty (the plaintext is only available from CreateToken at creation time).

func (*CentralStore) ListUserNamespaces

func (s *CentralStore) ListUserNamespaces(userID int64) ([]*NamespaceMember, error)

ListUserNamespaces returns the namespaces a user belongs to.

func (*CentralStore) ListUsers

func (s *CentralStore) ListUsers() ([]*User, error)

ListUsers returns all users ordered by username.

func (*CentralStore) ListWorkspaces

func (s *CentralStore) ListWorkspaces() ([]*WorkspaceRow, error)

ListWorkspaces returns all registered workspaces.

func (*CentralStore) LookupToken

func (s *CentralStore) LookupToken(token string) (*Token, error)

LookupToken resolves a token string to its user and level. It returns ErrTokenNotFound when the token is unknown. The plaintext token is echoed back in the returned record for interface stability (the caller supplied it).

func (*CentralStore) OpenRepo

func (s *CentralStore) OpenRepo(r RepoRef) (*Repo, error)

OpenRepo opens an existing repository. Returns ErrRepoNotFound if missing.

func (*CentralStore) PutWorkspace

func (s *CentralStore) PutWorkspace(w *WorkspaceRow) error

PutWorkspace registers or updates a workspace row in the central store.

func (*CentralStore) QueryCount

func (s *CentralStore) QueryCount(count *int) error

QueryCount returns the total number of content-addressed objects. It is a convenience for tests to verify global deduplication.

func (*CentralStore) RecordAudit

func (s *CentralStore) RecordAudit(ev AuditEvent) error

RecordAudit appends an audit event to the append-only audit_log table. It never updates or deletes (no undo/reflog semantics).

func (*CentralStore) RemoveNamespaceMember

func (s *CentralStore) RemoveNamespaceMember(namespace string, userID int64) error

RemoveNamespaceMember revokes a user's membership in a namespace (scoped to the user's tenant).

func (*CentralStore) RepoExists

func (s *CentralStore) RepoExists(r RepoRef) (bool, error)

RepoExists reports whether a repository exists.

func (*CentralStore) ResolveWorkspace

func (s *CentralStore) ResolveWorkspace(dir string) (*WorkspaceMarker, *Repo, error)

FindRepo walks up from dir to locate the repo a workspace belongs to. It returns the workspace marker and the repo-scoped handle, opening the store recorded by the marker (Home/DSN) rather than assuming this store instance. If the marker's repo is missing from its store, an error is returned.

func (*CentralStore) SetWAL

func (s *CentralStore) SetWAL() error

SetWAL enables SQLite WAL mode for safe concurrent access across processes (many workspaces sharing one DB), plus a busy timeout so concurrent writers queue instead of failing with SQLITE_BUSY. No-op for Postgres/MySQL.

func (*CentralStore) UpdateMergeRequestState

func (s *CentralStore) UpdateMergeRequestState(repoID, iid int64, state string) error

UpdateMergeRequestState updates an MR state (merged/closed/reopen).

func (*CentralStore) UserCanReadRepo

func (s *CentralStore) UserCanReadRepo(r RepoRef, userID *int64) bool

UserCanReadRepo reports whether a user may read a repository. Public repositories are always readable; private repositories require namespace membership. When no user is supplied the repository is readable only if it is public (or the Lab has no users at all, i.e. an open single-user instance).

func (*CentralStore) UserCanWriteRepo

func (s *CentralStore) UserCanWriteRepo(r RepoRef, userID *int64) bool

UserCanWriteRepo reports whether a user may write to a repository (push). Write access requires the instance to be open OR the user to be a namespace member with a write-capable role (member/admin/owner; readonly is denied). A nil userID is only allowed when the instance is open.

type Comment

type Comment struct {
	ID       int64
	MRID     int64
	AuthorID *int64
	Body     string
	Path     string
	Created  time.Time
}

Comment is a discussion line on a merge request.

type DriverConfig

type DriverConfig struct {
	Kind string
	DSN  string
}

DriverConfig selects the metadata backend. Kind is "sqlite", "postgres", or "mysql"/"mariadb". All dialects are pure-Go (no cgo): sqlite via glebarez/sqlite (modernc), postgres via pgx, mysql via go-sql-driver.

type MergeRequest

type MergeRequest struct {
	ID          int64
	RepoID      int64
	IID         int64
	Title       string
	Description string
	Source      string // revision id or branch name
	Target      string // revision id or branch name
	State       string // "open" | "merged" | "closed"
	AuthorID    *int64
	Created     time.Time
	Updated     time.Time
}

MergeRequest models a change-tracking request between two revisions.

type NamespaceMember

type NamespaceMember struct {
	Namespace string
	UserID    int64
	Role      string // "readonly" | "member" | "admin" | "owner"
}

NamespaceMember is a user's membership in a namespace (org).

type PushMirror

type PushMirror struct {
	ID        int64
	RepoID    int64
	Name      string
	URL       string
	Branch    string // branch name to push (default "main")
	Token     string
	LastRev   string // last revision id pushed (dirty detection)
	LastError string
}

PushMirror is a named external git destination that receives a force push of a single branch's tree. A normal (read-write) repository may have several.

type Ref

type Ref struct {
	Name   string
	Kind   RefKind
	Target string // revision id
}

Ref is a named pointer to a revision.

type RefKind

type RefKind string

RefKind distinguishes mutable branchs from immutable tags.

const (
	RefBranch RefKind = "branch"
	RefTag    RefKind = "tag"
)

Ref kinds.

type Remote

type Remote struct {
	Name  string
	URL   string
	Token string
}

Remote is a named URL to another EasyVCS server. Token is the optional bearer token used to authenticate writes against that server.

type RemoteRef

type RemoteRef struct {
	RemoteName string
	Kind       RefKind
	Name       string
	Target     string // revision id on the remote
}

RemoteRef is a snapshot of a remote's ref as last fetched, scoped to a remote name (e.g. "origin.main", kind=branch). This mirrors git's refs/remotes.

type Repo

type Repo struct {
	TenantID  int64
	Namespace string
	Name      string
	// contains filtered or unexported fields
}

Repo is a repo-scoped handle bound to a specific repository in the central store. It implements RepoStore.

func (*Repo) AddBranchACL

func (r *Repo) AddBranchACL(userID int64, branch string) error

AddBranchACL grants a user push access to a specific branch of a repository.

func (*Repo) BeginTx

func (r *Repo) BeginTx() *gorm.DB

BeginTx starts a GORM transaction on the central store.

func (*Repo) CanPushBranch

func (r *Repo) CanPushBranch(userID int64, branch string) (bool, error)

CanPushBranch reports whether a user may push the given branch. Semantics:

  • a branch ACL row for (user, branch) => allowed;
  • a user with at least one branch ACL row for this repo => allowed only for listed branches (the allowlist is in effect);
  • a user with no branch ACL rows for this repo => falls back to the repo's write role (repo-wide access).

func (*Repo) Close

func (r *Repo) Close() error

Close is a no-op for the repo handle (the CentralStore is shared).

func (*Repo) DeleteObject

func (r *Repo) DeleteObject(id object.ID) error

DeleteObject removes a single content-addressed object (global). It is used by the GC command to prune objects no longer referenced by any snapshot. The caller is responsible for reachability analysis.

func (*Repo) DeletePushMirror

func (r *Repo) DeletePushMirror(name string) error

DeletePushMirror removes a push-mirror by name.

func (*Repo) DeleteRef

func (r *Repo) DeleteRef(name string) error

DeleteRef removes a ref scoped to this repository.

func (*Repo) DeleteRemote

func (r *Repo) DeleteRemote(name string) error

DeleteRemote removes a remote by name.

func (*Repo) DeleteRemoteRefsForRemote

func (r *Repo) DeleteRemoteRefsForRemote(remoteName string) error

DeleteRemoteRefsForRemote clears all recorded refs for a remote (used when a remote is deleted or force-refreshed).

func (*Repo) GetLastSyncTip

func (r *Repo) GetLastSyncTip(name string) (string, error)

GetLastSyncTip returns the last synced tip for a remote ("" if none).

func (*Repo) GetPushMirror

func (r *Repo) GetPushMirror(name string) (*PushMirror, error)

GetPushMirror returns one push-mirror by name (token decrypted).

func (*Repo) GetRef

func (r *Repo) GetRef(name string) (*Ref, error)

GetRef reads a ref scoped to this repository.

func (*Repo) GetRemote

func (r *Repo) GetRemote(name string) (*Remote, error)

GetRemote returns a remote by name.

func (*Repo) GetRemoteDefaultBranch

func (r *Repo) GetRemoteDefaultBranch(name string) (string, error)

GetRemoteDefaultBranch returns the remote's default branch ("" if none).

func (*Repo) GetRevision

func (r *Repo) GetRevision(id string) (*Revision, error)

GetRevision reads a revision scoped to this repository.

func (*Repo) GetSnapshot

func (r *Repo) GetSnapshot(id object.ID) (*Snapshot, error)

GetSnapshot reads a snapshot scoped to this repository.

func (*Repo) GitCommitForRevision

func (r *Repo) GitCommitForRevision(revID string) (string, error)

GitCommitForRevision returns the last exported commit sha for a revision, if any.

func (*Repo) IsMirror

func (r *Repo) IsMirror() bool

IsMirror reports whether the repository is a read-only external mirror.

func (*Repo) ListBranchACL

func (r *Repo) ListBranchACL(userID int64) ([]string, error)

ListBranchACL returns the branches a user may push in this repo.

func (*Repo) ListPushMirrors

func (r *Repo) ListPushMirrors() ([]*PushMirror, error)

ListPushMirrors lists all push-mirrors for this repo (tokens omitted).

func (*Repo) ListRefs

func (r *Repo) ListRefs() ([]*Ref, error)

ListRefs lists refs scoped to this repository.

func (*Repo) ListRemoteRefs

func (r *Repo) ListRemoteRefs(remoteName string) ([]*RemoteRef, error)

ListRemoteRefs lists all remote refs for this repo (optionally filtered by remote name). Returns refs keyed under the remote (name is bare, e.g. "main").

func (*Repo) ListRemotes

func (r *Repo) ListRemotes() ([]*Remote, error)

ListRemotes lists all remotes for this repository. Tokens are omitted from the returned list to avoid leaking secrets.

func (*Repo) ListRevisions

func (r *Repo) ListRevisions() ([]*Revision, error)

ListRevisions lists revisions scoped to this repository.

func (*Repo) ObjectExists

func (r *Repo) ObjectExists(id object.ID) (bool, error)

ObjectExists reports whether an object is present.

func (*Repo) ObjectIDs

func (r *Repo) ObjectIDs() ([]object.ID, error)

ObjectIDs returns all content-addressed object ids held anywhere in the central store (objects are global and deduplicated across repositories). It is used by clients to advertise "have" objects during fetch/push so a peer only sends objects the destination lacks.

func (r *Repo) PutGitLink(revID, commitSHA, ref, side string) error

PutGitLink records a revision<->commit traceability link for the git bridge.

func (*Repo) PutPushMirror

func (r *Repo) PutPushMirror(m *PushMirror) error

PutPushMirror inserts or replaces a push-mirror for this repo. The token is encrypted at rest (EASYVCS_SECRET_KEY; plaintext when unset).

func (*Repo) PutRef

func (r *Repo) PutRef(ref *Ref) error

PutRef stores a ref scoped to this repository.

func (*Repo) PutRefTx

func (r *Repo) PutRefTx(tx *gorm.DB, ref *Ref) error

PutRefTx upserts a ref within an open transaction.

func (*Repo) PutRemote

func (r *Repo) PutRemote(name, url, token string) error

PutRemote registers or updates a remote for this repository. An empty token clears the stored token.

func (*Repo) PutRevision

func (r *Repo) PutRevision(rev *Revision) error

PutRevision stores a revision scoped to this repository.

func (*Repo) PutRevisionTx

func (r *Repo) PutRevisionTx(tx *gorm.DB, rev *Revision) error

PutRevisionTx inserts a revision within an open transaction.

func (*Repo) PutSnapshot

func (r *Repo) PutSnapshot(snap *Snapshot) error

PutSnapshot stores a snapshot scoped to this repository. Parents, author, and description are packed into a single compact meta BLOB (see encoding pkg).

func (*Repo) PutSnapshotTx

func (r *Repo) PutSnapshotTx(tx *gorm.DB, snap *Snapshot) error

PutSnapshotTx inserts a snapshot within an open transaction.

func (*Repo) ReadObject

func (r *Repo) ReadObject(id object.ID) (*object.Object, error)

ReadObject reads a global content-addressed object.

func (*Repo) RemoveBranchACL

func (r *Repo) RemoveBranchACL(userID int64, branch string) error

RemoveBranchACL revokes a user's push access to a branch.

func (*Repo) RepoID

func (r *Repo) RepoID() int64

RepoID returns the numeric repo id used internally.

func (*Repo) RepoMeta

func (r *Repo) RepoMeta() (RepoMeta, error)

RepoMeta returns the hosting metadata for a repository.

func (*Repo) RepoRef

func (r *Repo) RepoRef() RepoRef

RepoRef returns the RepoRef for this handle.

func (*Repo) RevisionForGitCommit

func (r *Repo) RevisionForGitCommit(commitSHA string) (string, error)

RevisionForGitCommit returns the easyvcs revision that a commit sha was imported as, if any.

func (*Repo) SetRemoteDefaultBranch

func (r *Repo) SetRemoteDefaultBranch(name, def string) error

SetRemoteDefaultBranch records which branch on a remote is its default.

func (*Repo) SetRemoteRef

func (r *Repo) SetRemoteRef(remoteName string, ref *RemoteRef) error

SetRemoteRef upserts a remote ref. Primary key is remote+kind+name.

func (*Repo) String

func (r *Repo) String() string

func (*Repo) TouchMirrorSync

func (r *Repo) TouchMirrorSync(lastRev string, syncEpoch int64, lastErr string) error

TouchMirrorSync updates a mirror's last sync time/rev/error.

func (*Repo) Transaction

func (r *Repo) Transaction(fn func(tx *gorm.DB) error) error

Transaction runs fn inside a database transaction, committing on success and rolling back on error or panic. This is the preferred entry point for atomic multi-table writes (BeginTx + manual Commit is easy to leak).

func (*Repo) UpdateMirrorMeta

func (r *Repo) UpdateMirrorMeta(m RepoMeta) error

UpdateMirrorMeta records mirror state (url, branch, interval, last result).

func (*Repo) UpdatePushMirrorSync

func (r *Repo) UpdatePushMirrorSync(name, lastRev, lastErr string) error

UpdatePushMirrorSync records the last pushed revision / error for a push-mirror.

func (*Repo) UpdateRemoteSyncTip

func (r *Repo) UpdateRemoteSyncTip(name, lastSyncTip string) error

UpdateRemoteSyncTip records the last successfully synced tip for a remote branch (the local revision id that mirrors the remote's tip after a pull). Empty clears it. This enables incremental/conflict-aware pulls.

func (*Repo) UpdateRepoMeta

func (r *Repo) UpdateRepoMeta(m RepoMeta) error

UpdateRepoMeta updates description/visibility/default branch.

func (*Repo) UpdateRevisionHash

func (r *Repo) UpdateRevisionHash(revisionID string, hash object.ID) error

UpdateRevisionHash atomically repoints a revision's Hash field. It preserves the existing ChangedPaths.

func (*Repo) UpdateRevisionHashCAS

func (r *Repo) UpdateRevisionHashCAS(revisionID string, expectHash, newHash object.ID) error

UpdateRevisionHashCAS repoints a revision's Hash to a new snapshot hash only if the revision still points at `expectHash`. This is an optimistic-concurrency (compare-and-swap) guard: if another writer amended the revision in between, ErrRevisionChanged is returned instead of silently last-write-wins. The snapshot is written only when the CAS succeeds.

func (*Repo) WriteObject

func (r *Repo) WriteObject(o *object.Object) error

WriteObject stores a global content-addressed object. Objects are immutable, so an existing object is never overwritten.

func (*Repo) WriteObjectsBatch

func (r *Repo) WriteObjectsBatch(objs []*object.Object) error

WriteObjectsBatch stores many objects in a single transaction, reducing round-trips when applying a bundle. Each object's id is recomputed from its content; duplicate ids are ignored (idempotent).

func (*Repo) WriteObjectsBatchTx

func (r *Repo) WriteObjectsBatchTx(tx *gorm.DB, objs []*object.Object) error

WriteObjectsBatchTx stores objects in the given transaction.

type RepoMeta

type RepoMeta struct {
	Description   string
	Visibility    string // "public" | "private"
	DefaultBranch string
	// Kind is "normal" (read-write) or "mirror" (read-only clone of an external
	// git repo; edits are forbidden).
	Kind string
	// Mirror fields are relevant only when Kind == "mirror".
	MirrorURL      string
	MirrorBranch   string
	MirrorInterval int // seconds between scheduled pulls; 0 = manual only
	MirrorLastRev  string
	MirrorLastSync int64 // epoch millis
	MirrorLastErr  string
	MirrorToken    string // never returned by API
}

RepoMeta is the hosting metadata for a repository.

type RepoMetaMap

type RepoMetaMap map[string]RepoMeta

RepoMetaMap keys a RepoMeta by "namespace/name".

type RepoRef

type RepoRef struct {
	Tenant    int64
	Namespace string
	Name      string
}

RepoRef uniquely identifies a repository within the central store. Tenant scopes the (namespace, name) pair: 0 means the default tenant (id 1), which keeps every pre-tenancy call site behaving exactly as before.

func (RepoRef) String

func (r RepoRef) String() string

func (RepoRef) TenantID added in v0.6.0

func (r RepoRef) TenantID() int64

TenantID resolves the effective tenant id (0 → default tenant 1).

type RepoStore

type RepoStore interface {
	// Object access (content-addressed, immutable, global).
	WriteObject(o *object.Object) error
	ReadObject(id object.ID) (*object.Object, error)
	ObjectExists(id object.ID) (bool, error)

	// Snapshot access.
	PutSnapshot(s *Snapshot) error
	GetSnapshot(id object.ID) (*Snapshot, error)

	// Revision access.
	PutRevision(r *Revision) error
	GetRevision(id string) (*Revision, error)
	// UpdateRevisionHash atomically points a revision's Hash to a new
	// snapshot hash.
	UpdateRevisionHash(revisionID string, hash object.ID) error
	// UpdateRevisionHashCAS repoints a revision's Hash only if it still points
	// at expectHash (optimistic concurrency; ErrRevisionChanged otherwise).
	UpdateRevisionHashCAS(revisionID string, expectHash, newHash object.ID) error
	ListRevisions() ([]*Revision, error)

	// Refs.
	PutRef(r *Ref) error
	DeleteRef(name string) error
	GetRef(name string) (*Ref, error)
	ListRefs() ([]*Ref, error)

	// Transactional writes (for atomic commit from changes).
	BeginTx() *gorm.DB
	WriteObjectsBatchTx(tx *gorm.DB, objs []*object.Object) error
	PutSnapshotTx(tx *gorm.DB, s *Snapshot) error
	PutRevisionTx(tx *gorm.DB, r *Revision) error

	// Close flushes and closes the backend.
	Close() error
}

RepoStore is the repo-scoped persistence boundary used by the semantic layer. Object primitives are content-addressed and global; the metadata methods are scoped to a single repository.

type Review

type Review struct {
	ID         int64
	MRID       int64
	ReviewerID *int64
	State      string // "approved" | "request_changes" | "comment"
	Body       string
	Created    time.Time
}

Review is a reviewer's verdict on a merge request.

type Revision

type Revision struct {
	// ID is the stable revision id (hex). Generated once and never modified.
	ID string
	// Hash points at the current snapshot's revision_hash.
	Hash object.ID
	// Created time.
	Created time.Time
	// ForkFrom records the revision id this revision was forked from, if any.
	// Used by workspace auto-fork so the origin is traceable.
	ForkFrom string
	// ChangedPaths lists the repo-relative paths whose content changed in this
	// revision relative to its parent (or all paths for the root revision). It
	// is used to cheaply answer "which revisions modified a given file" by
	// filtering the DAG walk without re-reading every tree.
	ChangedPaths []string
}

Revision is the stable, user-facing unit of work. It holds a pointer to its single current snapshot. The revision_id never changes; the pointed-to snapshot's hash does change as the revision is rewritten. Revision and Snapshot are strictly 1:1: a revision always points at one current snapshot, and rewriting replaces that snapshot entirely (old object remains in the content-addressed store if still referenced).

type Snapshot

type Snapshot struct {
	// RevisionHash is the content-addressed id (sha) of this snapshot. It is
	// mutable: it changes whenever the revision is rewritten.
	RevisionHash object.ID
	// RevisionID is the stable identity this snapshot belongs to (never
	// changes). It is a random stable id (hex), independent of content.
	RevisionID string
	// Parents contains the ids of the parent snapshots (DAG edges).
	Parents []object.ID
	// TreeID is the root tree of this snapshot.
	TreeID object.ID
	// Description is the commit message.
	Description string
	// Author identity.
	Author Author
	// CommitTime is the creation time.
	CommitTime time.Time
}

Snapshot is the content-addressed view of a revision: it is the graph node. A Snapshot belongs to exactly one Revision (1:1), so its hash changes on rewrite (rebase) while the revision_id stays stable.

type Tenant added in v0.6.0

type Tenant struct {
	ID          int64
	Slug        string
	DisplayName string
	Disabled    bool
	Created     time.Time
}

Tenant is the top-level isolation boundary (orgs, repos, users, and the matching agent tenant all belong to one).

type Token

type Token struct {
	ID      int64
	Token   string
	UserID  int64
	Level   string // "read" or "write"
	Created time.Time
}

Token is a bearer token bound to a user with an access level.

type User

type User struct {
	ID          int64
	TenantID    int64
	Username    string
	DisplayName string
	Created     time.Time
}

User is a Lab account. A user owns namespaces (orgs) and repositories. Users are 1:1 with tenants: TenantID pins every credential to exactly one isolation boundary (0 = default tenant 1 for legacy rows).

type WorkspaceMarker

type WorkspaceMarker struct {
	Repo            RepoRef `json:"repo"`
	CurrentRevision string  `json:"current_revision"`
	Branch          string  `json:"branch,omitempty"`
	IgnoreHash      string  `json:"ignore_hash,omitempty"`
	// Home is the central store root directory this workspace belongs to.
	// Empty means "use the process's HomeDir()".
	Home string `json:"home,omitempty"`
	// DSN optionally overrides the metadata backend location (e.g. a sqlite
	// file path or a postgres connection string). When set it takes precedence
	// over Home<DBFile>. Empty means default (Home/easyvcs.db, sqlite).
	DSN string `json:"dsn,omitempty"`
}

WorkspaceMarker is the pointer content stored at a working directory root. It records which repository (namespace/name) this checkout belongs to, which revision is currently checked out, and the location of the central store (home path and optional DSN) so a workspace is self-describing even when its store lives outside the process's EASYVCS_HOME. IgnoreHash tracks the hash of the ignore files at the last commit so a revision in .gitignore/.vcsignore can trigger history rewriting.

func LoadMarker

func LoadMarker(dir string) (string, *WorkspaceMarker, error)

LoadMarker reads and parses the workspace marker from a directory, walking upward. It returns the directory that contains the marker and the marker itself, or ErrNotFound if no marker exists above dir.

func LookupMarker

func LookupMarker(dir string) (*WorkspaceMarker, error)

LookupMarker loads a marker and returns it (without the directory). It is a convenience for callers that already know the root.

type WorkspaceRow

type WorkspaceRow struct {
	Path            string
	Repo            RepoRef
	CurrentRevision string
	Branch          string
}

WorkspaceRow is the workspaces table entry tracking a registered workspace.

Jump to

Keyboard shortcuts

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