domain

package
v0.6.3 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2025 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package domain provides core domain types and error handling primitives.

Result[T] Usage Guidelines

The Result[T] type provides monadic error handling for composing fallible operations. Follow these guidelines to use Result safely and idiomatically:

## When to Use Result[T]

Use Result[T] for:

  • Pure functional transformations with Map/FlatMap
  • Composing multiple fallible operations
  • Internal pipeline stages
  • Functions that benefit from monadic composition

## When to Use (T, error)

Use (T, error) for:

  • Public API boundaries (pkg/dot interfaces)
  • Leaf functions interfacing with Go stdlib/external libraries
  • Functions where error details are more important than composition
  • CLI command handlers

## Safe Unwrap() Usage

Unwrap() and UnwrapErr() panic if called on the wrong variant. Only use them when:

  1. After an explicit IsOk() or IsErr() check: if result.IsOk() { value := result.Unwrap() // SAFE }

  2. When you have a compile-time or logical guarantee about the variant: // Example: op.Target is already a validated FilePath, so String() -> NewFilePath cannot fail path := domain.NewFilePath(validatedPath).Unwrap() // SAFE (but redundant)

  3. In test code where panics are acceptable: got := ComputeResult().Unwrap() // OK in tests assert.Equal(t, expected, got)

## Prefer Safe Alternatives

Instead of Unwrap/UnwrapErr, prefer:

  • UnwrapOr(default) for values with acceptable fallbacks: count := CountItems().UnwrapOr(0) // Returns 0 on error

  • OrElse(fn) for lazy fallback computation: config := LoadConfig().OrElse(func() Config { return DefaultConfig() })

  • Explicit error checking and propagation: result := Compute() if !result.IsOk() { return fmt.Errorf("computation failed: %w", result.UnwrapErr()) } value := result.Unwrap() // Safe after check

## Converting Between Result[T] and (T, error)

From Result[T] to (T, error):

func ToError(result domain.Result[T]) (T, error) {
    if result.IsOk() {
        return result.Unwrap(), nil
    }
    return zero, result.UnwrapErr()
}

From (T, error) to Result[T]:

func FromError(value T, err error) domain.Result[T] {
    if err != nil {
        return domain.Err[T](err)
    }
    return domain.Ok(value)
}

## Example: Pipeline Stage

Good use of Result for composition:

func ProcessPipeline(input string) domain.Result[Output] {
    return domain.FlatMap(
        Parse(input),
        func(parsed Parsed) domain.Result[Output] {
            return domain.FlatMap(
                Validate(parsed),
                func(validated Validated) domain.Result[Output] {
                    return Transform(validated)
                },
            )
        },
    )
}

## Example: Error Path (Safe Unwrap)

Common pattern in pipeline/planner code:

scanResult := ScanStage()(ctx, input)
if scanResult.IsErr() {
    return domain.Err[Plan](scanResult.UnwrapErr())  // SAFE: checked IsErr()
}
packages := scanResult.Unwrap()  // SAFE: checked above via negation

## Known Patterns

These patterns are safe but may appear risky:

  1. Reconstructing already-validated paths: // op.Target is already a FilePath, so String() -> NewFilePath is redundant but safe path := domain.NewFilePath(op.Target.String()).Unwrap()

    Better: Just use op.Target directly

  2. Checked in previous conditional: if result.IsErr() { return domain.Err[T](result.UnwrapErr()) } value := result.Unwrap() // Safe: IsErr() checked above, so this must be Ok()

## Testing Helpers

In test code, MustUnwrap variants are acceptable:

got := domain.MustOk(ComputeValue())        // Panics on error (fine in tests)
err := domain.MustErr(ExpectFailure())      // Panics on Ok (fine in tests)

These are defined in internal/domain/testing.go and should NEVER be used in production code.

Index

Constants

View Source
const (
	// DefaultDirPerms is the default permission mode for directories (rwxr-xr-x).
	// Owner can read, write, and execute. Group and others can read and execute.
	DefaultDirPerms os.FileMode = 0755

	// DefaultFilePerms is the default permission mode for regular files (rw-r--r--).
	// Owner can read and write. Group and others can read only.
	DefaultFilePerms os.FileMode = 0644

	// SecureFilePerms is the permission mode for sensitive files (rw-------).
	// Only owner can read and write. No permissions for group or others.
	SecureFilePerms os.FileMode = 0600

	// SecureDirPerms is the permission mode for sensitive directories (rwx------).
	// Only owner can read, write, and execute. No permissions for group or others.
	SecureDirPerms os.FileMode = 0700
)

File and directory permission constants. These define the default permissions for filesystem operations.

View Source
const (
	// PermUserR is the user read permission bit (0400).
	PermUserR os.FileMode = 0400

	// PermUserW is the user write permission bit (0200).
	PermUserW os.FileMode = 0200

	// PermUserX is the user execute permission bit (0100).
	PermUserX os.FileMode = 0100

	// PermUserRW is the user read+write permission bits (0600).
	PermUserRW os.FileMode = 0600

	// PermUserRWX is the user read+write+execute permission bits (0700).
	PermUserRWX os.FileMode = 0700

	// PermGroupR is the group read permission bit (0040).
	PermGroupR os.FileMode = 0040

	// PermGroupW is the group write permission bit (0020).
	PermGroupW os.FileMode = 0020

	// PermGroupX is the group execute permission bit (0010).
	PermGroupX os.FileMode = 0010

	// PermOtherR is the other read permission bit (0004).
	PermOtherR os.FileMode = 0004

	// PermOtherW is the other write permission bit (0002).
	PermOtherW os.FileMode = 0002

	// PermOtherX is the other execute permission bit (0001).
	PermOtherX os.FileMode = 0001
)

Permission bit constants for testing file mode permissions. These can be used with bitwise AND to check specific permission bits.

Variables

This section is empty.

Functions

func UnwrapResult

func UnwrapResult[T any](r Result[T], context string) (T, error)

UnwrapResult extracts the value from a Result or returns an error with context. This helper simplifies the common pattern of checking Result.IsOk() and unwrapping.

Returns:

  • (value, nil) if Result is Ok
  • (zero value, wrapped error) if Result is Err

Example usage:

// Old pattern (5 lines):
result := NewFilePath(path)
if !result.IsOk() {
    return WrapError(result.UnwrapErr(), "invalid path")
}
value := result.Unwrap()

// New pattern (2 lines):
value, err := UnwrapResult(NewFilePath(path), "invalid path")
if err != nil { return err }

The error chain is preserved, allowing errors.Is() and errors.As() to work correctly.

func UserFacingError

func UserFacingError(err error) string

UserFacingError converts an error into a user-friendly message. Removes technical jargon and provides actionable information.

func ValidateWithValidators

func ValidateWithValidators(path string, validators []PathValidator) error

ValidateWithValidators runs multiple validators in sequence. Returns the first error encountered, or nil if all validators pass.

func WrapError

func WrapError(err error, context string) error

WrapError wraps an error with contextual message while preserving the error chain. Returns nil if the provided error is nil, allowing for safe usage in conditional checks.

Example usage:

err := someOperation()
if err != nil {
    return WrapError(err, "operation failed")
}

The resulting error message format is: "context: original error"

func WrapErrorf

func WrapErrorf(err error, format string, args ...interface{}) error

WrapErrorf wraps an error with formatted contextual message while preserving the error chain. Returns nil if the provided error is nil, allowing for safe usage in conditional checks.

Example usage:

err := loadFile(path)
if err != nil {
    return WrapErrorf(err, "load config from %s", path)
}

The resulting error message format is: "formatted context: original error"

Types

type AbsolutePathValidator

type AbsolutePathValidator struct{}

AbsolutePathValidator ensures paths are absolute.

func (*AbsolutePathValidator) Validate

func (v *AbsolutePathValidator) Validate(path string) error

Validate checks if the path is absolute.

type Attribute

type Attribute struct {
	Key   string
	Value any
}

Attribute represents a key-value span attribute.

type CheckResult

type CheckResult struct {
	CheckName string
	Status    CheckStatus
	Issues    []Issue
	Stats     map[string]any
}

CheckResult contains the outcome of a diagnostic check.

type CheckStatus

type CheckStatus string

CheckStatus represents the high-level outcome of a check.

const (
	CheckStatusPass    CheckStatus = "pass"
	CheckStatusWarning CheckStatus = "warning"
	CheckStatusFail    CheckStatus = "fail"
	CheckStatusSkipped CheckStatus = "skipped"
)

type ConflictInfo

type ConflictInfo struct {
	Type    string            `json:"type"`
	Path    string            `json:"path"`
	Details string            `json:"details"`
	Context map[string]string `json:"context,omitempty"`
}

ConflictInfo represents conflict information in plan metadata. This is a simplified view of conflicts for plan consumers.

type Context deprecated

type Context = context.Context

Context is an alias for context.Context to maintain interface compatibility.

Deprecated: Use context.Context directly instead.

type Counter

type Counter interface {
	Inc(labels ...string)
	Add(value float64, labels ...string)
}

Counter represents a monotonically increasing metric.

type DiagnosticCheck

type DiagnosticCheck interface {
	// Name returns the unique identifier for this check.
	Name() string
	// Description returns a human-readable description of what this check does.
	Description() string
	// Run executes the check and returns the result.
	Run(ctx context.Context) (CheckResult, error)
}

DiagnosticCheck represents a pluggable health check.

type DirCopy

type DirCopy struct {
	OpID   OperationID
	Source FilePath
	Dest   FilePath
}

DirCopy recursively copies a directory without removing the source.

func NewDirCopy

func NewDirCopy(id OperationID, source, dest FilePath) DirCopy

NewDirCopy creates a new directory copy operation.

func (DirCopy) Dependencies

func (op DirCopy) Dependencies() []Operation

func (DirCopy) Equals

func (op DirCopy) Equals(other Operation) bool

func (DirCopy) Execute

func (op DirCopy) Execute(ctx context.Context, fs FS) error

func (DirCopy) ID

func (op DirCopy) ID() OperationID

func (DirCopy) Kind

func (op DirCopy) Kind() OperationKind

func (DirCopy) Rollback

func (op DirCopy) Rollback(ctx context.Context, fs FS) error

func (DirCopy) String

func (op DirCopy) String() string

func (DirCopy) Validate

func (op DirCopy) Validate() error

type DirCreate

type DirCreate struct {
	OpID OperationID
	Path FilePath
}

DirCreate creates a directory at path.

func NewDirCreate

func NewDirCreate(id OperationID, path FilePath) DirCreate

NewDirCreate creates a new directory creation operation.

func (DirCreate) Dependencies

func (op DirCreate) Dependencies() []Operation

func (DirCreate) Equals

func (op DirCreate) Equals(other Operation) bool

func (DirCreate) Execute

func (op DirCreate) Execute(ctx context.Context, fs FS) error

func (DirCreate) ID

func (op DirCreate) ID() OperationID

func (DirCreate) Kind

func (op DirCreate) Kind() OperationKind

func (DirCreate) Rollback

func (op DirCreate) Rollback(ctx context.Context, fs FS) error

func (DirCreate) String

func (op DirCreate) String() string

func (DirCreate) Validate

func (op DirCreate) Validate() error

type DirDelete

type DirDelete struct {
	OpID OperationID
	Path FilePath
}

DirDelete removes an empty directory at path.

func NewDirDelete

func NewDirDelete(id OperationID, path FilePath) DirDelete

NewDirDelete creates a new directory deletion operation.

func (DirDelete) Dependencies

func (op DirDelete) Dependencies() []Operation

func (DirDelete) Equals

func (op DirDelete) Equals(other Operation) bool

func (DirDelete) Execute

func (op DirDelete) Execute(ctx context.Context, fs FS) error

func (DirDelete) ID

func (op DirDelete) ID() OperationID

func (DirDelete) Kind

func (op DirDelete) Kind() OperationKind

func (DirDelete) Rollback

func (op DirDelete) Rollback(ctx context.Context, fs FS) error

func (DirDelete) String

func (op DirDelete) String() string

func (DirDelete) Validate

func (op DirDelete) Validate() error

type DirEntry

type DirEntry interface {
	Name() string
	IsDir() bool
	Type() os.FileMode
	Info() (FileInfo, error)
}

DirEntry provides information about a directory entry.

type DirRemoveAll

type DirRemoveAll struct {
	OpID OperationID
	Path FilePath
}

DirRemoveAll recursively removes a directory and all its contents.

func NewDirRemoveAll

func NewDirRemoveAll(id OperationID, path FilePath) DirRemoveAll

NewDirRemoveAll creates a new recursive directory deletion operation.

func (DirRemoveAll) Dependencies

func (op DirRemoveAll) Dependencies() []Operation

func (DirRemoveAll) Equals

func (op DirRemoveAll) Equals(other Operation) bool

func (DirRemoveAll) Execute

func (op DirRemoveAll) Execute(ctx context.Context, fs FS) error

func (DirRemoveAll) ID

func (op DirRemoveAll) ID() OperationID

func (DirRemoveAll) Kind

func (op DirRemoveAll) Kind() OperationKind

func (DirRemoveAll) Rollback

func (op DirRemoveAll) Rollback(ctx context.Context, fs FS) error

func (DirRemoveAll) String

func (op DirRemoveAll) String() string

func (DirRemoveAll) Validate

func (op DirRemoveAll) Validate() error

type ErrCheckpointNotFound

type ErrCheckpointNotFound struct {
	ID string
}

ErrCheckpointNotFound indicates a checkpoint ID was not found.

func (ErrCheckpointNotFound) Error

func (e ErrCheckpointNotFound) Error() string

type ErrConflict

type ErrConflict struct {
	Path   string
	Reason string
}

ErrConflict indicates a conflict that prevents an operation.

func (ErrConflict) Error

func (e ErrConflict) Error() string

type ErrCyclicDependency

type ErrCyclicDependency struct {
	Cycle []string
}

ErrCyclicDependency indicates a circular dependency in operations.

func (ErrCyclicDependency) Error

func (e ErrCyclicDependency) Error() string

type ErrEmptyPlan

type ErrEmptyPlan struct{}

ErrEmptyPlan indicates an attempt to execute a plan with no operations.

func (ErrEmptyPlan) Error

func (e ErrEmptyPlan) Error() string

type ErrExecutionCancelled added in v0.6.3

type ErrExecutionCancelled struct {
	Executed int
	Skipped  int
}

ErrExecutionCancelled indicates execution was cancelled via context.

func (ErrExecutionCancelled) Error added in v0.6.3

func (e ErrExecutionCancelled) Error() string

type ErrExecutionFailed

type ErrExecutionFailed struct {
	Executed   int
	Failed     int
	RolledBack int
	Errors     []error
}

ErrExecutionFailed indicates one or more operations failed during execution.

func (ErrExecutionFailed) Error

func (e ErrExecutionFailed) Error() string

func (ErrExecutionFailed) Unwrap

func (e ErrExecutionFailed) Unwrap() []error

Unwrap returns the underlying errors.

type ErrFilesystemOperation

type ErrFilesystemOperation struct {
	Operation string
	Path      string
	Err       error
}

ErrFilesystemOperation indicates a filesystem operation failed.

func (ErrFilesystemOperation) Error

func (e ErrFilesystemOperation) Error() string

func (ErrFilesystemOperation) Unwrap

func (e ErrFilesystemOperation) Unwrap() error

type ErrInvalidPath

type ErrInvalidPath struct {
	Path   string
	Reason string
}

ErrInvalidPath indicates a path failed validation.

func (ErrInvalidPath) Error

func (e ErrInvalidPath) Error() string

type ErrMultiple

type ErrMultiple struct {
	Errors []error
}

ErrMultiple aggregates multiple errors into one.

func (ErrMultiple) Error

func (e ErrMultiple) Error() string

func (ErrMultiple) Unwrap

func (e ErrMultiple) Unwrap() []error

Unwrap returns the underlying errors for errors.Is and errors.As support.

type ErrNotImplemented

type ErrNotImplemented struct {
	Feature string
}

ErrNotImplemented indicates functionality is not yet implemented.

func (ErrNotImplemented) Error

func (e ErrNotImplemented) Error() string

type ErrPackageNotFound

type ErrPackageNotFound struct {
	Package string
}

ErrPackageNotFound indicates a requested package does not exist.

func (ErrPackageNotFound) Error

func (e ErrPackageNotFound) Error() string

type ErrParentNotFound

type ErrParentNotFound struct {
	Path string
}

ErrParentNotFound indicates a parent directory does not exist.

func (ErrParentNotFound) Error

func (e ErrParentNotFound) Error() string

type ErrPermissionDenied

type ErrPermissionDenied struct {
	Path      string
	Operation string
}

ErrPermissionDenied indicates insufficient permissions for an operation.

func (ErrPermissionDenied) Error

func (e ErrPermissionDenied) Error() string

type ErrSourceNotFound

type ErrSourceNotFound struct {
	Path string
}

ErrSourceNotFound indicates an operation source file does not exist.

func (ErrSourceNotFound) Error

func (e ErrSourceNotFound) Error() string

type ExecutionResult

type ExecutionResult struct {
	Executed   []OperationID
	Failed     []OperationID
	RolledBack []OperationID
	Errors     []error
}

ExecutionResult contains the outcome of plan execution.

func (ExecutionResult) PartialFailure

func (r ExecutionResult) PartialFailure() bool

PartialFailure returns true if some but not all operations succeeded.

func (ExecutionResult) Success

func (r ExecutionResult) Success() bool

Success returns true if all operations executed successfully.

type FS

type FS interface {
	// Read operations
	Stat(ctx context.Context, path string) (FileInfo, error)
	Lstat(ctx context.Context, path string) (FileInfo, error)
	ReadDir(ctx context.Context, path string) ([]DirEntry, error)
	ReadLink(ctx context.Context, path string) (string, error)
	ReadFile(ctx context.Context, path string) ([]byte, error)

	// Write operations
	WriteFile(ctx context.Context, path string, data []byte, perm os.FileMode) error
	Mkdir(ctx context.Context, path string, perm os.FileMode) error
	MkdirAll(ctx context.Context, path string, perm os.FileMode) error
	Remove(ctx context.Context, path string) error
	RemoveAll(ctx context.Context, path string) error
	Symlink(ctx context.Context, oldname, newname string) error
	Rename(ctx context.Context, oldpath, newpath string) error

	// Queries
	Exists(ctx context.Context, path string) bool
	IsDir(ctx context.Context, path string) (bool, error)
	IsSymlink(ctx context.Context, path string) (bool, error)
}

FS defines the filesystem abstraction interface.

type FileBackup

type FileBackup struct {
	OpID   OperationID
	Source FilePath
	Backup FilePath
}

FileBackup creates a backup copy of a file.

func NewFileBackup

func NewFileBackup(id OperationID, source, backup FilePath) FileBackup

NewFileBackup creates a new file backup operation.

func (FileBackup) Dependencies

func (op FileBackup) Dependencies() []Operation

func (FileBackup) Equals

func (op FileBackup) Equals(other Operation) bool

func (FileBackup) Execute

func (op FileBackup) Execute(ctx context.Context, fs FS) error

func (FileBackup) ID

func (op FileBackup) ID() OperationID

func (FileBackup) Kind

func (op FileBackup) Kind() OperationKind

func (FileBackup) Rollback

func (op FileBackup) Rollback(ctx context.Context, fs FS) error

func (FileBackup) String

func (op FileBackup) String() string

func (FileBackup) Validate

func (op FileBackup) Validate() error

type FileDelete

type FileDelete struct {
	OpID OperationID
	Path FilePath
}

FileDelete deletes a file.

func NewFileDelete

func NewFileDelete(id OperationID, path FilePath) FileDelete

NewFileDelete creates a new file delete operation.

func (FileDelete) Dependencies

func (op FileDelete) Dependencies() []Operation

func (FileDelete) Equals

func (op FileDelete) Equals(other Operation) bool

func (FileDelete) Execute

func (op FileDelete) Execute(ctx context.Context, fs FS) error

func (FileDelete) ID

func (op FileDelete) ID() OperationID

func (FileDelete) Kind

func (op FileDelete) Kind() OperationKind

func (FileDelete) Rollback

func (op FileDelete) Rollback(ctx context.Context, fs FS) error

func (FileDelete) String

func (op FileDelete) String() string

func (FileDelete) Validate

func (op FileDelete) Validate() error

type FileDirKind

type FileDirKind struct{}

FileDirKind marks paths pointing to file directories.

type FileInfo

type FileInfo interface {
	Name() string
	Size() int64
	Mode() os.FileMode
	ModTime() any
	IsDir() bool
	Sys() any
}

FileInfo provides information about a file.

type FileMove

type FileMove struct {
	OpID   OperationID
	Source TargetPath
	Dest   FilePath
}

FileMove moves a file from source to destination.

func NewFileMove

func NewFileMove(id OperationID, source TargetPath, dest FilePath) FileMove

NewFileMove creates a new file move operation.

func (FileMove) Dependencies

func (op FileMove) Dependencies() []Operation

func (FileMove) Equals

func (op FileMove) Equals(other Operation) bool

func (FileMove) Execute

func (op FileMove) Execute(ctx context.Context, fs FS) error

func (FileMove) ID

func (op FileMove) ID() OperationID

func (FileMove) Kind

func (op FileMove) Kind() OperationKind

func (FileMove) Rollback

func (op FileMove) Rollback(ctx context.Context, fs FS) error

func (FileMove) String

func (op FileMove) String() string

func (FileMove) Validate

func (op FileMove) Validate() error

type FilePath

type FilePath = Path[FileDirKind]

FilePath is a path to a file or directory within a package.

func MustParsePath

func MustParsePath(s string) FilePath

MustParsePath creates a FilePath from a string, panicking on error. This function is intended for use in tests only and should not be used in production code.

type Gauge

type Gauge interface {
	Set(value float64, labels ...string)
	Inc(labels ...string)
	Dec(labels ...string)
}

Gauge represents a value that can go up or down.

type Histogram

type Histogram interface {
	Observe(value float64, labels ...string)
}

Histogram represents a distribution of values.

type Issue

type Issue struct {
	Code        string
	Message     string
	Severity    IssueSeverity
	Path        string // Optional: associated file path
	Context     map[string]any
	Remediation *Remediation
}

Issue represents a specific problem found during a check.

type IssueSeverity

type IssueSeverity string

IssueSeverity indicates the impact of an issue.

const (
	IssueSeverityInfo    IssueSeverity = "info"
	IssueSeverityWarning IssueSeverity = "warning"
	IssueSeverityError   IssueSeverity = "error"
	IssueSeverityFatal   IssueSeverity = "fatal"
)

type LinkCreate

type LinkCreate struct {
	OpID   OperationID
	Source FilePath
	Target TargetPath
}

LinkCreate creates a symbolic link from source to target.

func NewLinkCreate

func NewLinkCreate(id OperationID, source FilePath, target TargetPath) LinkCreate

NewLinkCreate creates a new link creation operation.

func (LinkCreate) Dependencies

func (op LinkCreate) Dependencies() []Operation

func (LinkCreate) Equals

func (op LinkCreate) Equals(other Operation) bool

func (LinkCreate) Execute

func (op LinkCreate) Execute(ctx context.Context, fs FS) error

func (LinkCreate) ID

func (op LinkCreate) ID() OperationID

func (LinkCreate) Kind

func (op LinkCreate) Kind() OperationKind

func (LinkCreate) Rollback

func (op LinkCreate) Rollback(ctx context.Context, fs FS) error

func (LinkCreate) String

func (op LinkCreate) String() string

func (LinkCreate) Validate

func (op LinkCreate) Validate() error

type LinkDelete

type LinkDelete struct {
	OpID   OperationID
	Target TargetPath
}

LinkDelete removes a symbolic link at target.

func NewLinkDelete

func NewLinkDelete(id OperationID, target TargetPath) LinkDelete

NewLinkDelete creates a new link deletion operation.

func (LinkDelete) Dependencies

func (op LinkDelete) Dependencies() []Operation

func (LinkDelete) Equals

func (op LinkDelete) Equals(other Operation) bool

func (LinkDelete) Execute

func (op LinkDelete) Execute(ctx context.Context, fs FS) error

func (LinkDelete) ID

func (op LinkDelete) ID() OperationID

func (LinkDelete) Kind

func (op LinkDelete) Kind() OperationKind

func (LinkDelete) Rollback

func (op LinkDelete) Rollback(ctx context.Context, fs FS) error

func (LinkDelete) String

func (op LinkDelete) String() string

func (LinkDelete) Validate

func (op LinkDelete) Validate() error

type Logger

type Logger interface {
	Debug(ctx context.Context, msg string, fields ...any)
	Info(ctx context.Context, msg string, fields ...any)
	Warn(ctx context.Context, msg string, fields ...any)
	Error(ctx context.Context, msg string, fields ...any)
	With(fields ...any) Logger
}

Logger defines the logging abstraction interface.

type Metrics

type Metrics interface {
	Counter(name string, labels ...string) Counter
	Histogram(name string, labels ...string) Histogram
	Gauge(name string, labels ...string) Gauge
}

Metrics defines the metrics collection abstraction interface.

func NewNoopMetrics

func NewNoopMetrics() Metrics

NewNoopMetrics returns a metrics implementation that does nothing.

type Node

type Node struct {
	Path     FilePath
	Type     NodeType
	Children []Node
}

Node represents a node in a filesystem tree.

func (Node) IsDir

func (n Node) IsDir() bool

IsDir returns true if the node is a directory.

func (Node) IsFile

func (n Node) IsFile() bool

IsFile returns true if the node is a file.

func (n Node) IsSymlink() bool

IsSymlink returns true if the node is a symbolic link.

type NodeType

type NodeType int

NodeType identifies the type of filesystem node.

const (
	// NodeFile represents a regular file.
	NodeFile NodeType = iota

	// NodeDir represents a directory.
	NodeDir

	// NodeSymlink represents a symbolic link.
	NodeSymlink
)

func (NodeType) String

func (t NodeType) String() string

String returns the string representation of a NodeType.

type NonEmptyPathValidator

type NonEmptyPathValidator struct{}

NonEmptyPathValidator ensures paths are not empty.

func (*NonEmptyPathValidator) Validate

func (v *NonEmptyPathValidator) Validate(path string) error

Validate checks if the path is non-empty.

type Operation

type Operation interface {
	// ID returns the unique identifier for this operation.
	ID() OperationID

	// Kind returns the operation type.
	Kind() OperationKind

	// Validate checks if the operation is valid.
	Validate() error

	// Dependencies returns operations that must execute before this one.
	Dependencies() []Operation

	// Execute performs the operation with side effects.
	Execute(ctx context.Context, fs FS) error

	// Rollback undoes the operation.
	Rollback(ctx context.Context, fs FS) error

	// String returns a human-readable description.
	String() string

	// Equals checks if two operations are equivalent.
	Equals(other Operation) bool
}

Operation represents a filesystem operation. Operations are pure data structures with no side effects.

type OperationID

type OperationID string

OperationID uniquely identifies an operation.

type OperationKind

type OperationKind int

OperationKind identifies the type of operation.

const (
	// OpKindLinkCreate creates a symbolic link.
	OpKindLinkCreate OperationKind = iota

	// OpKindLinkDelete removes a symbolic link.
	OpKindLinkDelete

	// OpKindDirCreate creates a directory.
	OpKindDirCreate

	// OpKindDirDelete removes an empty directory.
	OpKindDirDelete

	// OpKindDirRemoveAll recursively removes a directory and all its contents.
	OpKindDirRemoveAll

	// OpKindFileMove moves a file.
	OpKindFileMove

	// OpKindFileBackup creates a backup copy of a file.
	OpKindFileBackup

	// OpKindFileDelete deletes a file.
	OpKindFileDelete

	// OpKindDirCopy recursively copies a directory.
	OpKindDirCopy
)

func (OperationKind) String

func (k OperationKind) String() string

String returns the string representation of an OperationKind.

type Package

type Package struct {
	Name string
	Path PackagePath
	Tree *Node // Optional: file tree for the package
}

Package represents a collection of configuration files to be managed.

type PackageDirKind

type PackageDirKind struct{}

PackageDirKind marks paths pointing to package directories.

type PackagePath

type PackagePath = Path[PackageDirKind]

PackagePath is a path to a package directory.

type Path

type Path[K PathKind] struct {
	// contains filtered or unexported fields
}

Path represents a filesystem path with phantom typing for compile-time safety. The type parameter K ensures paths of different kinds cannot be mixed accidentally.

func (Path[K]) Equals

func (p Path[K]) Equals(other Path[K]) bool

Equals checks if two paths are equal.

func (Path[K]) Join

func (p Path[K]) Join(elem string) Path[K]

Join appends a path component, returning a FilePath.

func (Path[K]) Parent

func (p Path[K]) Parent() Result[Path[K]]

Parent returns the parent directory of this path.

func (Path[K]) String

func (p Path[K]) String() string

String returns the string representation of the path.

type PathKind

type PathKind interface {
	// contains filtered or unexported methods
}

PathKind is a marker interface for phantom type parameters. Implementations exist only at compile time to enforce type safety.

type PathValidator

type PathValidator interface {
	Validate(path string) error
}

PathValidator validates path strings according to specific rules. Multiple validators can be composed to enforce complex validation requirements.

type Plan

type Plan struct {
	Operations []Operation
	Metadata   PlanMetadata
	Batches    [][]Operation // Parallel execution batches (if computed)

	// PackageOperations maps package names to operation IDs that belong to that package.
	// This enables tracking which operations were generated for which packages,
	// allowing accurate manifest updates and selective operations.
	// Optional field for backward compatibility.
	PackageOperations map[string][]OperationID `json:"package_operations,omitempty"`
}

Plan represents a set of operations to execute.

func (Plan) CanParallelize

func (p Plan) CanParallelize() bool

CanParallelize returns true if the plan has computed parallel batches.

func (Plan) HasPackage

func (p Plan) HasPackage(pkg string) bool

HasPackage returns true if the plan contains operations for the specified package.

func (Plan) OperationCountForPackage

func (p Plan) OperationCountForPackage(pkg string) int

OperationCountForPackage returns the number of operations for the specified package. Returns 0 if the package is not in the plan or if PackageOperations is not set.

func (Plan) OperationsForPackage

func (p Plan) OperationsForPackage(pkg string) []Operation

OperationsForPackage returns all operations that belong to the specified package. Returns an empty slice if the package is not in the plan or if PackageOperations is not set.

func (Plan) PackageNames

func (p Plan) PackageNames() []string

PackageNames returns a list of all package names in the plan. Returns an empty slice if PackageOperations is not set.

func (Plan) ParallelBatches

func (p Plan) ParallelBatches() [][]Operation

ParallelBatches returns the parallel execution batches. Returns nil if parallelization has not been computed.

func (Plan) Validate

func (p Plan) Validate() error

Validate checks if the plan is valid.

type PlanMetadata

type PlanMetadata struct {
	PackageCount   int            `json:"package_count"`
	OperationCount int            `json:"operation_count"`
	LinkCount      int            `json:"link_count"`
	DirCount       int            `json:"dir_count"`
	Conflicts      []ConflictInfo `json:"conflicts,omitempty"`
	Warnings       []WarningInfo  `json:"warnings,omitempty"`
}

PlanMetadata contains statistics and diagnostic information about a plan.

type RelativePathValidator

type RelativePathValidator struct{}

RelativePathValidator ensures paths are relative.

func (*RelativePathValidator) Validate

func (v *RelativePathValidator) Validate(path string) error

Validate checks if the path is relative.

type Remediation

type Remediation struct {
	Description string
	// Action is a function that attempts to fix the issue.
	// It returns an error if the fix failed.
	Action func(context.Context) error
}

Remediation describes how to fix an issue.

type Result

type Result[T any] struct {
	// contains filtered or unexported fields
}

Result represents a value or an error, implementing a Result monad for error handling. This provides a functional approach to error handling with composition support.

func Collect

func Collect[T any](results []Result[T]) Result[[]T]

Collect aggregates a slice of Results into a Result containing a slice. Returns Err if any Result is Err, otherwise returns Ok with all values.

func Err

func Err[T any](err error) Result[T]

Err creates a failed Result containing an error.

func FlatMap

func FlatMap[T, U any](r Result[T], fn func(T) Result[U]) Result[U]

FlatMap applies a function that returns a Result to the contained value if Ok. This is the monadic bind operation, enabling composition of Result-returning functions.

func Map

func Map[T, U any](r Result[T], fn func(T) U) Result[U]

Map applies a function to the contained value if Ok, otherwise propagates the error. This is the functorial map operation.

func NewFilePath

func NewFilePath(s string) Result[FilePath]

NewFilePath creates a new file path with validation. Returns error if path is not absolute or contains traversal sequences.

func NewPackagePath

func NewPackagePath(s string) Result[PackagePath]

NewPackagePath creates a new package path with validation. Returns error if path is not absolute or contains traversal sequences.

func NewTargetPath

func NewTargetPath(s string) Result[TargetPath]

NewTargetPath creates a new target path with validation. Returns error if path is not absolute or contains traversal sequences.

func Ok

func Ok[T any](value T) Result[T]

Ok creates a successful Result containing a value.

func (Result[T]) IsErr

func (r Result[T]) IsErr() bool

IsErr returns true if the Result contains an error.

func (Result[T]) IsOk

func (r Result[T]) IsOk() bool

IsOk returns true if the Result contains a value.

func (Result[T]) OrDefault

func (r Result[T]) OrDefault() T

OrDefault returns the contained value or zero value for the type.

func (Result[T]) OrElse

func (r Result[T]) OrElse(fn func() T) T

OrElse returns the contained value or executes fallback function. The fallback is only called if the Result is Err.

func (Result[T]) Unwrap

func (r Result[T]) Unwrap() T

Unwrap returns the contained value.

Panics if the Result contains an error. This is by design to enforce proper error handling. In production code, prefer UnwrapOr() to provide a safe default, or check IsOk() before calling Unwrap().

Unwrap is appropriate when you have proven the Result must be Ok, such as in tests or after explicit IsOk() checks.

Example:

// Safe - explicit check
if result.IsOk() {
    value := result.Unwrap()
}

// Safer - provides default
value := result.UnwrapOr(defaultValue)

func (Result[T]) UnwrapErr

func (r Result[T]) UnwrapErr() error

UnwrapErr returns the contained error.

Panics if the Result contains a value. Use IsErr() to check before calling, or use pattern matching with IsOk()/IsErr() branches.

Appropriate for error handling paths where you've confirmed the Result is Err.

Example:

// Safe - explicit check
if result.IsErr() {
    err := result.UnwrapErr()
    // handle error
}

func (Result[T]) UnwrapOr

func (r Result[T]) UnwrapOr(defaultValue T) T

UnwrapOr returns the contained value or a default if Result is Err.

type Span

type Span interface {
	End()
	RecordError(err error)
	SetAttributes(attrs ...Attribute)
}

Span represents a single span in a trace.

type SpanConfig

type SpanConfig struct {
	Attributes []Attribute
}

SpanConfig holds span configuration.

type SpanOption

type SpanOption func(*SpanConfig)

SpanOption configures span creation.

type TargetDirKind

type TargetDirKind struct{}

TargetDirKind marks paths pointing to target directories.

type TargetPath

type TargetPath = Path[TargetDirKind]

TargetPath is a path to a target directory.

func MustParseTargetPath

func MustParseTargetPath(s string) TargetPath

MustParseTargetPath creates a TargetPath from a string, panicking on error. This function is intended for use in tests only and should not be used in production code.

type Tracer

type Tracer interface {
	Start(ctx context.Context, name string, opts ...SpanOption) (context.Context, Span)
}

Tracer defines the distributed tracing abstraction interface.

func NewNoopTracer

func NewNoopTracer() Tracer

NewNoopTracer returns a tracer that does nothing.

type TraversalFreeValidator

type TraversalFreeValidator struct{}

TraversalFreeValidator ensures paths do not contain traversal sequences. Rejects paths containing ".." or paths that are not in canonical form. This prevents both explicit traversal and disguised traversal (e.g., "a/./b", "a//b").

func (*TraversalFreeValidator) Validate

func (v *TraversalFreeValidator) Validate(path string) error

Validate checks if the path is free of traversal sequences and in canonical form.

type WarningInfo

type WarningInfo struct {
	Message  string            `json:"message"`
	Severity string            `json:"severity"`
	Context  map[string]string `json:"context,omitempty"`
}

WarningInfo represents warning information in plan metadata. This is a simplified view of warnings for plan consumers.

Jump to

Keyboard shortcuts

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