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:
After an explicit IsOk() or IsErr() check: if result.IsOk() { value := result.Unwrap() // SAFE }
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)
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:
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
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
- func UnwrapResult[T any](r Result[T], context string) (T, error)
- func UserFacingError(err error) string
- func ValidateWithValidators(path string, validators []PathValidator) error
- func WrapError(err error, context string) error
- func WrapErrorf(err error, format string, args ...interface{}) error
- type AbsolutePathValidator
- type Attribute
- type CheckResult
- type CheckStatus
- type ConflictInfo
- type Contextdeprecated
- type Counter
- type DiagnosticCheck
- type DirCopy
- func (op DirCopy) Dependencies() []Operation
- func (op DirCopy) Equals(other Operation) bool
- func (op DirCopy) Execute(ctx context.Context, fs FS) error
- func (op DirCopy) ID() OperationID
- func (op DirCopy) Kind() OperationKind
- func (op DirCopy) Rollback(ctx context.Context, fs FS) error
- func (op DirCopy) String() string
- func (op DirCopy) Validate() error
- type DirCreate
- func (op DirCreate) Dependencies() []Operation
- func (op DirCreate) Equals(other Operation) bool
- func (op DirCreate) Execute(ctx context.Context, fs FS) error
- func (op DirCreate) ID() OperationID
- func (op DirCreate) Kind() OperationKind
- func (op DirCreate) Rollback(ctx context.Context, fs FS) error
- func (op DirCreate) String() string
- func (op DirCreate) Validate() error
- type DirDelete
- func (op DirDelete) Dependencies() []Operation
- func (op DirDelete) Equals(other Operation) bool
- func (op DirDelete) Execute(ctx context.Context, fs FS) error
- func (op DirDelete) ID() OperationID
- func (op DirDelete) Kind() OperationKind
- func (op DirDelete) Rollback(ctx context.Context, fs FS) error
- func (op DirDelete) String() string
- func (op DirDelete) Validate() error
- type DirEntry
- type DirRemoveAll
- func (op DirRemoveAll) Dependencies() []Operation
- func (op DirRemoveAll) Equals(other Operation) bool
- func (op DirRemoveAll) Execute(ctx context.Context, fs FS) error
- func (op DirRemoveAll) ID() OperationID
- func (op DirRemoveAll) Kind() OperationKind
- func (op DirRemoveAll) Rollback(ctx context.Context, fs FS) error
- func (op DirRemoveAll) String() string
- func (op DirRemoveAll) Validate() error
- type ErrCheckpointNotFound
- type ErrConflict
- type ErrCyclicDependency
- type ErrEmptyPlan
- type ErrExecutionCancelled
- type ErrExecutionFailed
- type ErrFilesystemOperation
- type ErrInvalidPath
- type ErrMultiple
- type ErrNotImplemented
- type ErrPackageNotFound
- type ErrParentNotFound
- type ErrPermissionDenied
- type ErrSourceNotFound
- type ExecutionResult
- type FS
- type FileBackup
- func (op FileBackup) Dependencies() []Operation
- func (op FileBackup) Equals(other Operation) bool
- func (op FileBackup) Execute(ctx context.Context, fs FS) error
- func (op FileBackup) ID() OperationID
- func (op FileBackup) Kind() OperationKind
- func (op FileBackup) Rollback(ctx context.Context, fs FS) error
- func (op FileBackup) String() string
- func (op FileBackup) Validate() error
- type FileDelete
- func (op FileDelete) Dependencies() []Operation
- func (op FileDelete) Equals(other Operation) bool
- func (op FileDelete) Execute(ctx context.Context, fs FS) error
- func (op FileDelete) ID() OperationID
- func (op FileDelete) Kind() OperationKind
- func (op FileDelete) Rollback(ctx context.Context, fs FS) error
- func (op FileDelete) String() string
- func (op FileDelete) Validate() error
- type FileDirKind
- type FileInfo
- type FileMove
- func (op FileMove) Dependencies() []Operation
- func (op FileMove) Equals(other Operation) bool
- func (op FileMove) Execute(ctx context.Context, fs FS) error
- func (op FileMove) ID() OperationID
- func (op FileMove) Kind() OperationKind
- func (op FileMove) Rollback(ctx context.Context, fs FS) error
- func (op FileMove) String() string
- func (op FileMove) Validate() error
- type FilePath
- type Gauge
- type Histogram
- type Issue
- type IssueSeverity
- type LinkCreate
- func (op LinkCreate) Dependencies() []Operation
- func (op LinkCreate) Equals(other Operation) bool
- func (op LinkCreate) Execute(ctx context.Context, fs FS) error
- func (op LinkCreate) ID() OperationID
- func (op LinkCreate) Kind() OperationKind
- func (op LinkCreate) Rollback(ctx context.Context, fs FS) error
- func (op LinkCreate) String() string
- func (op LinkCreate) Validate() error
- type LinkDelete
- func (op LinkDelete) Dependencies() []Operation
- func (op LinkDelete) Equals(other Operation) bool
- func (op LinkDelete) Execute(ctx context.Context, fs FS) error
- func (op LinkDelete) ID() OperationID
- func (op LinkDelete) Kind() OperationKind
- func (op LinkDelete) Rollback(ctx context.Context, fs FS) error
- func (op LinkDelete) String() string
- func (op LinkDelete) Validate() error
- type Logger
- type Metrics
- type Node
- type NodeType
- type NonEmptyPathValidator
- type Operation
- type OperationID
- type OperationKind
- type Package
- type PackageDirKind
- type PackagePath
- type Path
- type PathKind
- type PathValidator
- type Plan
- func (p Plan) CanParallelize() bool
- func (p Plan) HasPackage(pkg string) bool
- func (p Plan) OperationCountForPackage(pkg string) int
- func (p Plan) OperationsForPackage(pkg string) []Operation
- func (p Plan) PackageNames() []string
- func (p Plan) ParallelBatches() [][]Operation
- func (p Plan) Validate() error
- type PlanMetadata
- type RelativePathValidator
- type Remediation
- type Result
- func Collect[T any](results []Result[T]) Result[[]T]
- func Err[T any](err error) Result[T]
- func FlatMap[T, U any](r Result[T], fn func(T) Result[U]) Result[U]
- func Map[T, U any](r Result[T], fn func(T) U) Result[U]
- func NewFilePath(s string) Result[FilePath]
- func NewPackagePath(s string) Result[PackagePath]
- func NewTargetPath(s string) Result[TargetPath]
- func Ok[T any](value T) Result[T]
- type Span
- type SpanConfig
- type SpanOption
- type TargetDirKind
- type TargetPath
- type Tracer
- type TraversalFreeValidator
- type WarningInfo
Constants ¶
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.
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 ¶
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 ¶
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 ¶
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 ¶
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 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 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 (DirCopy) ID ¶
func (op DirCopy) ID() OperationID
func (DirCopy) Kind ¶
func (op DirCopy) Kind() OperationKind
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 (DirCreate) ID ¶
func (op DirCreate) ID() OperationID
func (DirCreate) Kind ¶
func (op DirCreate) Kind() OperationKind
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 (DirDelete) ID ¶
func (op DirDelete) ID() OperationID
func (DirDelete) Kind ¶
func (op DirDelete) Kind() OperationKind
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) ID ¶
func (op DirRemoveAll) ID() OperationID
func (DirRemoveAll) Kind ¶
func (op DirRemoveAll) Kind() OperationKind
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 ¶
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
ErrExecutionCancelled indicates execution was cancelled via context.
func (ErrExecutionCancelled) Error ¶ added in v0.6.3
func (e ErrExecutionCancelled) Error() string
type ErrExecutionFailed ¶
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 ¶
ErrFilesystemOperation indicates a filesystem operation failed.
func (ErrFilesystemOperation) Error ¶
func (e ErrFilesystemOperation) Error() string
func (ErrFilesystemOperation) Unwrap ¶
func (e ErrFilesystemOperation) Unwrap() error
type ErrInvalidPath ¶
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 ¶
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) ID ¶
func (op FileBackup) ID() OperationID
func (FileBackup) Kind ¶
func (op FileBackup) Kind() OperationKind
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) ID ¶
func (op FileDelete) ID() OperationID
func (FileDelete) Kind ¶
func (op FileDelete) Kind() OperationKind
func (FileDelete) String ¶
func (op FileDelete) String() string
func (FileDelete) Validate ¶
func (op FileDelete) Validate() error
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 (FileMove) ID ¶
func (op FileMove) ID() OperationID
func (FileMove) Kind ¶
func (op FileMove) Kind() OperationKind
type FilePath ¶
type FilePath = Path[FileDirKind]
FilePath is a path to a file or directory within a package.
func MustParsePath ¶
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 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) ID ¶
func (op LinkCreate) ID() OperationID
func (LinkCreate) Kind ¶
func (op LinkCreate) Kind() OperationKind
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) ID ¶
func (op LinkDelete) ID() OperationID
func (LinkDelete) Kind ¶
func (op LinkDelete) Kind() OperationKind
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 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 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.
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 ¶
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 ¶
CanParallelize returns true if the plan has computed parallel batches.
func (Plan) HasPackage ¶
HasPackage returns true if the plan contains operations for the specified package.
func (Plan) OperationCountForPackage ¶
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 ¶
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 ¶
PackageNames returns a list of all package names in the plan. Returns an empty slice if PackageOperations is not set.
func (Plan) ParallelBatches ¶
ParallelBatches returns the parallel execution batches. Returns nil if parallelization has not been computed.
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 ¶
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 FlatMap ¶
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 ¶
Map applies a function to the contained value if Ok, otherwise propagates the error. This is the functorial map operation.
func NewFilePath ¶
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 (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 ¶
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
}
type SpanConfig ¶
type SpanConfig struct {
Attributes []Attribute
}
SpanConfig holds span configuration.
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.
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.