writer

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jun 30, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Index

Constants

View Source
const ProjectLockKind = "ProjectLock"

Variables

View Source
var ErrAtomicWriteUnavailable = errors.New("atomic write unavailable")
View Source
var ErrProjectLockNotFound = errors.New("project lockfile not found")

Functions

func AtomicWriteFile

func AtomicWriteFile(ctx context.Context, targetPath string, data []byte, mode fs.FileMode) (err error)

AtomicWriteFile writes data to a same-directory temporary file, flushes and closes it, then renames it into place. If the rename is unavailable, the target is left untouched and an explicit ErrAtomicWriteUnavailable is returned.

func AttachmentID

func AttachmentID(ref components.Ref, adapterID, targetFile, targetKey string) string

AttachmentID returns a deterministic lock attachment ID.

func ChecksumBytes

func ChecksumBytes(data []byte) string

ChecksumBytes returns a stable sha256 checksum string for content.

func ChecksumFile

func ChecksumFile(path string) (string, error)

ChecksumFile returns a stable sha256 checksum string for a file.

func ChecksumFileIfExists

func ChecksumFileIfExists(path string) (checksum string, exists bool, err error)

ChecksumFileIfExists returns exists=false for missing files.

func EnsureProjectMetadata

func EnsureProjectMetadata(ctx context.Context, projectPath string) error

EnsureProjectMetadata creates <project>/.contextcart and ensures its .gitignore contains backups/ so backup snapshots are not committed.

func ManagedLineBlock

func ManagedLineBlock(id ManagedBlockID, body []byte) ([]byte, error)

ManagedLineBlock wraps line-oriented body text with ContextCart markers.

func ManagedMarkdownBlock

func ManagedMarkdownBlock(id ManagedBlockID, body []byte) ([]byte, error)

ManagedMarkdownBlock wraps Markdown body text with ContextCart HTML markers.

func ProjectLockPath

func ProjectLockPath(projectPath string) (string, error)

ProjectLockPath returns the absolute <project>/.contextcart/lock.yaml path.

func ProjectStateDir

func ProjectStateDir(projectPath string) (string, error)

ProjectStateDir returns the absolute <project>/.contextcart path.

func RemoveManagedLineBlock

func RemoveManagedLineBlock(existing []byte, id ManagedBlockID) ([]byte, bool, error)

RemoveManagedLineBlock removes exactly one matching ContextCart line block and returns removed=false when it is absent.

func RemoveManagedMarkdownBlock

func RemoveManagedMarkdownBlock(existing []byte, id ManagedBlockID) ([]byte, bool, error)

RemoveManagedMarkdownBlock removes exactly one matching ContextCart Markdown block and returns removed=false when it is absent.

func ScanPlanRawSecrets

func ScanPlanRawSecrets(plan planner.Plan) []risk.SecretFinding

ScanPlanRawSecrets returns redacted findings for planned writes.

func UpsertManagedLineBlock

func UpsertManagedLineBlock(existing []byte, id ManagedBlockID, block []byte) ([]byte, error)

UpsertManagedLineBlock replaces the matching ContextCart line block or appends it. Lines already present in user-owned content are omitted from the managed block to avoid duplicate ignore patterns.

func UpsertManagedMarkdownBlock

func UpsertManagedMarkdownBlock(existing []byte, id ManagedBlockID, block []byte) ([]byte, error)

UpsertManagedMarkdownBlock replaces the matching ContextCart block or appends it. Duplicate matching blocks are refused so user content is not guessed at.

func ValidateProjectLock

func ValidateProjectLock(lock ProjectLock, projectPath string) error

ValidateProjectLock enforces the v1 lockfile schema and project containment.

func WriteProjectLock

func WriteProjectLock(ctx context.Context, projectPath string, lock ProjectLock) error

WriteProjectLock validates and atomically writes <project>/.contextcart/lock.yaml.

Types

type ApplyOptions

type ApplyOptions struct {
	OperationType  OperationType
	CreatedAt      time.Time
	AllowRawSecret bool
	Force          bool
}

ApplyOptions controls confirmed writer execution.

type ApplyResult

type ApplyResult struct {
	OperationID      string               `json:"operationId" yaml:"operationId"`
	ProjectPath      string               `json:"projectPath" yaml:"projectPath"`
	LockPath         string               `json:"lockPath" yaml:"lockPath"`
	Completed        []CompletedOperation `json:"completed" yaml:"completed"`
	Backups          []BackupRecord       `json:"backups,omitempty" yaml:"backups,omitempty"`
	RecoveryGuidance []string             `json:"recoveryGuidance,omitempty" yaml:"recoveryGuidance,omitempty"`
}

ApplyResult reports the exact operations that reached disk.

func Apply

func Apply(ctx context.Context, plan planner.Plan, opts ApplyOptions) (ApplyResult, error)

Apply executes a confirmed plan, creates backups, and updates the project lockfile after successful writes.

func Detach

func Detach(ctx context.Context, plan planner.Plan, opts ApplyOptions) (ApplyResult, error)

Detach removes recorded ContextCart-owned attachments from a project.

type AttachmentRecord

type AttachmentRecord struct {
	ID             string              `json:"id" yaml:"id"`
	OperationID    string              `json:"operationId" yaml:"operationId"`
	Component      components.Ref      `json:"component" yaml:"component"`
	AdapterID      string              `json:"adapter" yaml:"adapter"`
	Scope          adapters.Scope      `json:"scope" yaml:"scope"`
	TargetFile     string              `json:"targetFile" yaml:"targetFile"`
	TargetKey      string              `json:"targetKey,omitempty" yaml:"targetKey,omitempty"`
	SourcePath     string              `json:"sourcePath,omitempty" yaml:"sourcePath,omitempty"`
	InstallMode    planner.InstallMode `json:"installMode" yaml:"installMode"`
	ChecksumBefore string              `json:"checksumBefore,omitempty" yaml:"checksumBefore,omitempty"`
	ChecksumAfter  string              `json:"checksumAfter,omitempty" yaml:"checksumAfter,omitempty"`
	BackupPath     string              `json:"backupPath,omitempty" yaml:"backupPath,omitempty"`
}

func AttachmentFromOperation

func AttachmentFromOperation(projectPath string, op planner.FileOperation, backup BackupRecord) (AttachmentRecord, error)

AttachmentFromOperation converts a planned file operation plus backup metadata into a lockfile attachment record.

type BackupRecord

type BackupRecord struct {
	OperationID    string    `json:"operationId" yaml:"operationId"`
	TargetPath     string    `json:"targetPath" yaml:"targetPath"`
	BackupPath     string    `json:"backupPath,omitempty" yaml:"backupPath,omitempty"`
	ChecksumBefore string    `json:"checksumBefore,omitempty" yaml:"checksumBefore,omitempty"`
	ChecksumAfter  string    `json:"checksumAfter,omitempty" yaml:"checksumAfter,omitempty"`
	TargetExisted  bool      `json:"targetExisted" yaml:"targetExisted"`
	CreatedAt      time.Time `json:"createdAt" yaml:"createdAt"`
	// contains filtered or unexported fields
}

BackupRecord captures the before/after identity of one touched target file.

func FinalizeBackup

func FinalizeBackup(ctx context.Context, record BackupRecord) (BackupRecord, error)

FinalizeBackup records the checksum after mutation. If the target no longer exists, ChecksumAfter remains empty to represent a removal.

func PrepareBackup

func PrepareBackup(ctx context.Context, req BackupRequest) (BackupRecord, error)

PrepareBackup initializes project backup storage and copies an existing target file to .contextcart/backups/<operation-id>/ when the target exists.

type BackupRequest

type BackupRequest struct {
	ProjectPath string
	OperationID string
	TargetPath  string
	CreatedAt   time.Time
}

BackupRequest selects one project target to back up before mutation.

type CleanIssue

type CleanIssue struct {
	Code         string         `json:"code" yaml:"code"`
	AttachmentID string         `json:"attachmentId,omitempty" yaml:"attachmentId,omitempty"`
	OperationID  string         `json:"operationId,omitempty" yaml:"operationId,omitempty"`
	Component    components.Ref `json:"component,omitempty" yaml:"component,omitempty"`
	AdapterID    string         `json:"adapter,omitempty" yaml:"adapter,omitempty"`
	TargetPath   string         `json:"targetPath,omitempty" yaml:"targetPath,omitempty"`
	BackupPath   string         `json:"backupPath,omitempty" yaml:"backupPath,omitempty"`
	Details      string         `json:"details,omitempty" yaml:"details,omitempty"`
}

CleanIssue describes one stale lock entry, missing target, or orphaned backup.

type CleanRequest

type CleanRequest struct {
	ProjectPath string
}

CleanRequest selects a project lockfile to inspect. Clean is read-only.

type CleanResult

type CleanResult struct {
	ProjectPath     string       `json:"projectPath" yaml:"projectPath"`
	LockPath        string       `json:"lockPath" yaml:"lockPath"`
	LockPresent     bool         `json:"lockPresent" yaml:"lockPresent"`
	StaleEntries    []CleanIssue `json:"staleEntries,omitempty" yaml:"staleEntries,omitempty"`
	MissingTargets  []CleanIssue `json:"missingTargets,omitempty" yaml:"missingTargets,omitempty"`
	OrphanedBackups []CleanIssue `json:"orphanedBackups,omitempty" yaml:"orphanedBackups,omitempty"`
}

CleanResult reports lockfile drift without deleting project files.

func Clean

func Clean(ctx context.Context, req CleanRequest) (CleanResult, error)

Clean inspects a project lockfile and backup directory without mutating them.

type CompletedOperation

type CompletedOperation struct {
	ID          string                `json:"id" yaml:"id"`
	Kind        planner.OperationKind `json:"kind" yaml:"kind"`
	TargetPath  string                `json:"targetPath" yaml:"targetPath"`
	BackupPath  string                `json:"backupPath,omitempty" yaml:"backupPath,omitempty"`
	InstallMode planner.InstallMode   `json:"installMode,omitempty" yaml:"installMode,omitempty"`
}

CompletedOperation records one successfully applied file operation.

type LockUpdateError

type LockUpdateError struct {
	Result ApplyResult
	Err    error
}

LockUpdateError is returned when file writes succeeded but lockfile persistence failed. Callers should display Result.RecoveryGuidance.

func (*LockUpdateError) Error

func (err *LockUpdateError) Error() string

func (*LockUpdateError) Unwrap

func (err *LockUpdateError) Unwrap() error

type ManagedBlockID

type ManagedBlockID struct {
	Component   components.Ref `json:"component" yaml:"component"`
	AdapterID   string         `json:"adapterId" yaml:"adapterId"`
	OperationID string         `json:"operationId,omitempty" yaml:"operationId,omitempty"`
}

ManagedBlockID identifies one ContextCart-owned managed block.

type OperationRecord

type OperationRecord struct {
	ID                string             `json:"id" yaml:"id"`
	Type              OperationType      `json:"type" yaml:"type"`
	CreatedAt         time.Time          `json:"createdAt" yaml:"createdAt"`
	Status            OperationStatus    `json:"status" yaml:"status"`
	Summary           string             `json:"summary,omitempty" yaml:"summary,omitempty"`
	RollbackSnapshots []RollbackSnapshot `json:"rollbackSnapshots,omitempty" yaml:"rollbackSnapshots,omitempty"`
}

type OperationStatus

type OperationStatus string
const (
	OperationStatusApplied    OperationStatus = "applied"
	OperationStatusRolledBack OperationStatus = "rolled-back"
	OperationStatusFailed     OperationStatus = "failed"
)

type OperationType

type OperationType string
const (
	OperationTypeAttach   OperationType = "attach"
	OperationTypeDetach   OperationType = "detach"
	OperationTypeClean    OperationType = "clean"
	OperationTypeRollback OperationType = "rollback"
)

type ProjectLock

type ProjectLock struct {
	APIVersion  string             `json:"apiVersion" yaml:"apiVersion"`
	Kind        string             `json:"kind" yaml:"kind"`
	Project     string             `json:"project" yaml:"project"`
	Operations  []OperationRecord  `json:"operations,omitempty" yaml:"operations,omitempty"`
	Attachments []AttachmentRecord `json:"attachments,omitempty" yaml:"attachments,omitempty"`
}

ProjectLock is the v1 project-scoped ownership record at <project>/.contextcart/lock.yaml.

func NewProjectLock

func NewProjectLock(projectPath string) (ProjectLock, error)

NewProjectLock returns an empty normalized project lock for projectPath.

func ReadOrNewProjectLock

func ReadOrNewProjectLock(ctx context.Context, projectPath string) (ProjectLock, error)

ReadOrNewProjectLock returns an existing lock or a new empty lock when absent.

func ReadProjectLock

func ReadProjectLock(ctx context.Context, projectPath string) (ProjectLock, error)

ReadProjectLock loads and validates <project>/.contextcart/lock.yaml.

func (*ProjectLock) AppendOperation

func (lock *ProjectLock) AppendOperation(record OperationRecord) error

AppendOperation appends a normalized operation record.

func (*ProjectLock) UpsertAttachment

func (lock *ProjectLock) UpsertAttachment(record AttachmentRecord) error

UpsertAttachment inserts or replaces an attachment by ID.

type RestoredFile

type RestoredFile struct {
	TargetPath       string `json:"targetPath" yaml:"targetPath"`
	BackupPath       string `json:"backupPath,omitempty" yaml:"backupPath,omitempty"`
	ChecksumRestored string `json:"checksumRestored,omitempty" yaml:"checksumRestored,omitempty"`
}

RestoredFile records one project path restored by rollback.

type RollbackPreview

type RollbackPreview struct {
	OperationID    string                  `json:"operationId" yaml:"operationId"`
	ProjectPath    string                  `json:"projectPath" yaml:"projectPath"`
	LockPath       string                  `json:"lockPath" yaml:"lockPath"`
	Targets        []RollbackPreviewTarget `json:"targets,omitempty" yaml:"targets,omitempty"`
	MissingBackups []string                `json:"missingBackups,omitempty" yaml:"missingBackups,omitempty"`
}

RollbackPreview reports the files a rollback would restore or remove.

func PreviewRollback

func PreviewRollback(ctx context.Context, req RollbackRequest) (RollbackPreview, error)

PreviewRollback selects rollback targets without restoring files.

type RollbackPreviewTarget

type RollbackPreviewTarget struct {
	TargetPath string `json:"targetPath" yaml:"targetPath"`
	BackupPath string `json:"backupPath,omitempty" yaml:"backupPath,omitempty"`
	Action     string `json:"action" yaml:"action"`
}

RollbackPreviewTarget is one target selected for rollback.

type RollbackRequest

type RollbackRequest struct {
	ProjectPath string
	OperationID string
	CreatedAt   time.Time
}

RollbackRequest selects an operation to restore. Empty OperationID means the latest applied operation with recorded attachments.

type RollbackResult

type RollbackResult struct {
	OperationID         string         `json:"operationId" yaml:"operationId"`
	RollbackOperationID string         `json:"rollbackOperationId" yaml:"rollbackOperationId"`
	ProjectPath         string         `json:"projectPath" yaml:"projectPath"`
	LockPath            string         `json:"lockPath" yaml:"lockPath"`
	Restored            []RestoredFile `json:"restored,omitempty" yaml:"restored,omitempty"`
	MissingBackups      []string       `json:"missingBackups,omitempty" yaml:"missingBackups,omitempty"`
}

RollbackResult reports restored files and missing backups.

func Rollback

func Rollback(ctx context.Context, req RollbackRequest) (RollbackResult, error)

Rollback restores files from backups for a recorded operation.

type RollbackSnapshot

type RollbackSnapshot struct {
	Attachment AttachmentRecord `json:"attachment" yaml:"attachment"`
	BackupPath string           `json:"backupPath,omitempty" yaml:"backupPath,omitempty"`
}

type Service

type Service struct{}

Service applies confirmed plans to project files.

func New

func New() *Service

New returns a writer service.

func (*Service) Apply

func (*Service) Apply(ctx context.Context, plan planner.Plan, opts ApplyOptions) (ApplyResult, error)

Apply executes a confirmed plan, creates backups, and updates the project lockfile after successful writes.

func (*Service) Clean

func (*Service) Clean(ctx context.Context, req CleanRequest) (CleanResult, error)

Clean inspects a project lockfile and backup directory without mutating them.

func (*Service) Detach

func (*Service) Detach(ctx context.Context, plan planner.Plan, opts ApplyOptions) (ApplyResult, error)

Detach removes only lockfile-owned attachments selected by plan operations.

func (*Service) PreviewRollback

func (*Service) PreviewRollback(ctx context.Context, req RollbackRequest) (RollbackPreview, error)

PreviewRollback selects rollback targets without restoring files.

func (*Service) Rollback

func (*Service) Rollback(ctx context.Context, req RollbackRequest) (RollbackResult, error)

Rollback restores files from backups for a recorded operation.

type UnsafeSecretError

type UnsafeSecretError struct {
	Findings []risk.SecretFinding
}

UnsafeSecretError is returned before any target write when a plan would write raw-looking secret material without an explicit override.

func (*UnsafeSecretError) Error

func (err *UnsafeSecretError) Error() string

type Writer

type Writer interface {
	Apply(ctx context.Context, plan planner.Plan, opts ApplyOptions) (ApplyResult, error)
	Detach(ctx context.Context, plan planner.Plan, opts ApplyOptions) (ApplyResult, error)
	Rollback(ctx context.Context, req RollbackRequest) (RollbackResult, error)
}

Writer is the project mutation boundary used by attach, detach, and rollback flows.

Jump to

Keyboard shortcuts

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