watcher

package
v0.9.7 Latest Latest
Warning

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

Go to latest
Published: Sep 2, 2026 License: Apache-2.0 Imports: 22 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package watcher turns fsnotify notifications for registered repositories into repository-qualified filesystem events. It intentionally does not debounce, hash, classify, or invalidate events; those responsibilities belong to later incremental stages.

Event granularity follows the platform backend. inotify reports the write that fills a file created moments earlier; kqueue sees only the directory change, because the new file is not watched until it already exists, so the same sequence arrives as a lone Create. A consumer therefore treats Create as a content change, and Reconciler stays the recovery path for whatever a backend does not report. Modifying a file that existed when the watch was installed is a Write on every backend.

On kqueue platforms - macOS and the BSDs - the backend holds one descriptor per watched file and directory: 787 for the Kivgraph checkout itself, which has 659 files in 152 watched directories, against a per-process ceiling of kern.maxfilesperproc, 92160 on macOS 26. A tree past that ceiling fails in New with an explicit descriptor error rather than watching a subset of it.

Index

Constants

View Source
const (
	// DefaultDebounce is the quiet period after the last raw event.
	DefaultDebounce = 150 * time.Millisecond
	// DefaultMaximumBatch is the upper bound from the first event to a flush.
	DefaultMaximumBatch = 500 * time.Millisecond
)
View Source
const (
	// ContentHashAlgorithm is the stable digest algorithm used for source bytes.
	ContentHashAlgorithm = "sha256"
)

Variables

View Source
var (
	// ErrAlreadyRunning indicates that Run was called more than once.
	ErrAlreadyRunning = errors.New("watcher is already running or has run")
)

Functions

func CommitsHaveIdenticalTrees

func CommitsHaveIdenticalTrees(ctx context.Context, repositoryPath, from, to string) bool

CommitsHaveIdenticalTrees reports whether two commits of a repository record exactly the same files with exactly the same contents.

It is what tells a commit apart from a checkout. Both move HEAD; only one changes the code, and rebuilding a corpus to discover that nothing changed costs seconds of every commit for a graph identical to the one already published.

Unlike ReadGitHead this does run git, and it may: a HEAD movement is rare by construction, so the cost is paid once per checkout rather than on every poll. Anything it cannot answer -- a commit the repository no longer has, git missing from the PATH -- is reported as "not identical", because the honest answer to "may I skip the rebuild?" when the question cannot be settled is no.

func GitCommonDirectory added in v0.9.6

func GitCommonDirectory(repositoryPath string) (string, error)

GitCommonDirectory returns the directory that owns the references shared by every linked worktree of the repository rooted at repositoryPath.

The main checkout returns its .git directory. A linked worktree follows its gitdir pointer and commondir file, so comparing this value identifies two checkout paths as views of the same Git repository without spawning git.

func GitOperationInProgress

func GitOperationInProgress(repositoryPath string) bool

GitOperationInProgress reports whether git currently holds the index lock of the repository.

A checkout is not atomic seen from outside: HEAD moves early and the working tree is rewritten after. `.git/index.lock` exists for the duration of the operation, which makes it the cheapest honest answer to "is git still inside?" -- one stat, no subprocess. A repository whose layout cannot be resolved is reported as not busy: the caller already has to handle a HEAD it could not read, and inventing a lock would stall it forever.

func GitWatchPaths

func GitWatchPaths(repositoryPath string) ([]string, error)

GitWatchPaths returns the directories that must be watched for the repository rooted at repositoryPath so that a HEAD movement is observed: the git directory, which holds HEAD and packed-refs, and refs/heads, which holds the branch reference that a commit advances. A linked worktree resolves the last two through the common git directory, so that one appears as well.

The result never contains a file, on purpose. Git publishes HEAD and every reference by writing a temporary file and renaming it over the target, so the path gets a new inode on every move; a watch installed on the file itself keeps pointing at the old, already unlinked inode and never reports again. Watching the containing directory observes the rename.

Only existing directories are returned, as absolute cleaned paths.

Types

type Batch

type Batch struct {
	// Events preserves first-seen order. Events with the same repository and
	// path are merged by OR-ing their Operations.
	Events []Event
}

Batch is an ordered set of coalesced filesystem events.

type Batcher

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

Batcher coalesces raw events using a quiet-period debounce and a hard batch deadline. It does not inspect the filesystem or calculate content hashes.

func NewBatcher

func NewBatcher(debounce, maximum time.Duration) (*Batcher, error)

NewBatcher creates a Batcher with the supplied durations. The maximum batch duration must be at least the debounce duration, matching watcher config validation. Use DefaultDebounce and DefaultMaximumBatch for project defaults.

func (*Batcher) Run

func (batcher *Batcher) Run(ctx context.Context, input <-chan Event) <-chan Batch

Run consumes raw events and returns batches until input closes or ctx is cancelled. Input closure flushes the pending batch immediately. Context cancellation stops without emitting a pending batch because the caller has explicitly abandoned the update cycle.

type ContentHasher

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

ContentHasher compares filesystem content against the last indexed hash. Process is serialized so a failed batch cannot partially update the cache.

func NewContentHasher

func NewContentHasher(known []FileHash) (*ContentHasher, error)

NewContentHasher creates a content hasher seeded with known indexed hashes. Hashes must be lowercase or uppercase hexadecimal SHA-256 digests.

func (*ContentHasher) KnownFiles

func (hasher *ContentHasher) KnownFiles() []FileHash

KnownFiles returns a sorted copy of all hashes currently in the cache.

func (*ContentHasher) KnownHash

func (hasher *ContentHasher) KnownHash(repository, path string) (string, bool)

KnownHash returns the currently indexed hash for a repository path.

func (*ContentHasher) Process

func (hasher *ContentHasher) Process(ctx context.Context, batch Batch) (HashResult, error)

Process hashes every unique event path in batch. A regular file with no known hash or a different hash is Changed; a matching hash is Unchanged. A missing or non-regular path is Removed only when it was previously known, otherwise it is Skipped so directory notifications cannot masquerade as source-file deletions.

type Event

type Event struct {
	// Repository is the registered repository name owning Path.
	Repository string
	// Path is an absolute, cleaned path. It is not resolved through symlinks.
	Path string
	// Operations contains one or more portable filesystem operations.
	Operations Operation
}

Event is a repository-qualified filesystem notification.

type FileHash

type FileHash struct {
	Repository  string
	Path        string
	ContentHash string
}

FileHash seeds a ContentHasher with the hash already associated with a file in the indexed graph.

type FileKey

type FileKey struct {
	Repository string
	Path       string
}

FileKey is the stable in-memory key for a repository-qualified path.

func (FileKey) String

func (key FileKey) String() string

type FileState

type FileState struct {
	Repository  string
	Path        string
	Operations  Operation
	ContentHash string
	Size        int64
}

FileState is the current hash observation for one event path.

type GitHead

type GitHead struct {
	// Commit is the object id HEAD resolves to, lowercase hexadecimal, always
	// populated on success. It is 40 characters in a sha1 repository and 64 in
	// a sha256 one.
	Commit string
	// Branch is the short branch name, empty when HEAD is detached. A HEAD that
	// points outside refs/heads keeps its full reference name, because nothing
	// shorter identifies it unambiguously.
	Branch string
	// Detached reports that HEAD names an object id directly instead of a
	// branch.
	Detached bool
}

GitHead is the resolved position of a repository's HEAD.

func ReadGitHead

func ReadGitHead(repositoryPath string) (GitHead, error)

ReadGitHead resolves the HEAD of the repository rooted at repositoryPath.

It reads the repository layout directly instead of running git: the watcher calls this once per filesystem event batch and a process per check is not affordable.

type HashResult

type HashResult struct {
	Changed   []FileState
	Unchanged []FileState
	Removed   []FileState
	Skipped   []FileState
}

HashResult separates files that need reindexing from files whose bytes are unchanged, paths removed from the tracked set, and non-regular paths such as directories. Only Changed should trigger source reindexing.

type Operation

type Operation uint8

Operation is a portable bitmask describing a filesystem change.

const (
	// OperationCreate reports a newly created path.
	OperationCreate Operation = 1 << iota
	// OperationWrite reports a path whose contents or size may have changed.
	OperationWrite
	// OperationRemove reports a removed path.
	OperationRemove
	// OperationRename reports a renamed path.
	OperationRename
	// OperationChmod reports an attribute change. On Linux it can also be the
	// first notification for a removed path, so consumers must not treat it as
	// proof that the path still exists.
	OperationChmod
)

func (Operation) Has

func (operation Operation) Has(flag Operation) bool

Has reports whether the operation contains flag.

func (Operation) String

func (operation Operation) String() string

String returns the stable, pipe-separated operation names.

type Reconciler

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

Reconciler periodically scans registered repositories and feeds the observed paths through a ContentHasher. It is the recovery path for dropped or missed filesystem notifications.

func NewReconciler

func NewReconciler(repositories []workspace.Repository, hasher *ContentHasher) (*Reconciler, error)

NewReconciler creates a reconciler for registered repositories and an existing content-hash cache. Roots that do not exist yet are retained and treated as empty during a scan so deletions can still be detected.

func (*Reconciler) Reconcile

func (reconciler *Reconciler) Reconcile(ctx context.Context) (ReconciliationResult, error)

Reconcile scans manifests and configured source files once. It detects additions, modifications, removals, unchanged files and unambiguous renames without relying on an fsnotify event having arrived.

func (*Reconciler) Run

func (reconciler *Reconciler) Run(ctx context.Context, interval time.Duration, sink func(ReconciliationResult) error) error

Run performs one reconciliation immediately and repeats it at interval until ctx is cancelled. The sink is called synchronously, so a failed sink or scan is returned instead of being hidden behind a background goroutine.

type ReconciliationResult

type ReconciliationResult struct {
	Added           []FileState
	Modified        []FileState
	Unchanged       []FileState
	Removed         []FileState
	Skipped         []FileState
	Renamed         []Rename
	ManifestChanges []FileState
}

ReconciliationResult is the filesystem state recovered independently of fsnotify delivery.

type Rename

type Rename struct {
	From FileState
	To   FileState
}

Rename is an unambiguous same-content path move found during reconciliation.

type Watcher

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

Watcher recursively watches registered repository directories.

A Watcher must be run by exactly one call to Run. Run owns delivery on Events and Errors and closes both channels before returning. The watcher reports raw notifications; it deliberately performs no debounce or content hashing.

func New

func New(repositories []workspace.Repository) (*Watcher, error)

New creates a recursive watcher for the supplied immutable repository metadata. Each repository root is watched immediately, including directories that already exist below it. Symlinked entries and default dependency trees are not watched; configured exclusions use the same path-segment and `**` semantics as workspace discovery.

func (*Watcher) Close

func (watcher *Watcher) Close() error

Close stops all filesystem watches. It is safe to call repeatedly and from a goroutine concurrent with Run.

func (*Watcher) Errors

func (watcher *Watcher) Errors() <-chan error

Errors returns backend and dynamic-watch errors. Errors are never silently discarded; callers should drain this channel while consuming Events.

func (*Watcher) Events

func (watcher *Watcher) Events() <-chan Event

Events returns raw repository-qualified filesystem notifications.

func (*Watcher) Run

func (watcher *Watcher) Run(ctx context.Context) error

Run forwards notifications until ctx is cancelled or Close is called. Context cancellation is returned to the caller; Close is a clean nil return.

func (*Watcher) WatchedPaths

func (watcher *Watcher) WatchedPaths() []string

WatchedPaths returns the currently registered directory watches in sorted order. It is intended for diagnostics and tests.

Jump to

Keyboard shortcuts

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