workspace

package
v0.28.1 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: Apache-2.0 Imports: 22 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ConflictMarkerLocal  = "<<<<<<< local"
	ConflictMarkerSep    = "======="
	ConflictMarkerRemote = ">>>>>>> remote"
)
View Source
const BaseDirName = "base"
View Source
const CreghtIgnoreFileName = ".creghtignore"
View Source
const StateDirName = ".creght"

Variables

This section is empty.

Functions

func BackupOverwrittenLocalFiles

func BackupOverwrittenLocalFiles(root string, state WorkspaceState, hasState bool, localFiles map[string]SnapshotEntry, incoming map[string]string) (string, error)

backupOverwrittenLocalFiles backs up local files that are about to be overwritten by incoming content and whose current content diverged from the recorded base (uncommitted local work). Returns "" when nothing needed it.

func BuildPullEntryPlan

func BuildPullEntryPlan(kind string, base map[string]StateEntry, hasState bool, local map[string]SnapshotEntry, remote map[string]SnapshotEntry, baseBody func(hash string) (string, bool)) pullEntryPlan

buildPullEntryPlan plans a pull. baseBody looks up recorded base content by hash (nil disables merging); files changed on both sides are three-way merged when the base content is available, otherwise reported as conflicts.

func BuildSyncPlan

func BuildSyncPlan(state WorkspaceState, hasState bool, localFiles map[string]SnapshotEntry, remoteFiles map[string]SnapshotEntry, allowDelete bool) syncPlan

func CanonicalAPIHost

func CanonicalAPIHost(apiHost string) string

CanonicalAPIHost normalizes an API host URL (scheme and host lowercased, no trailing slash, query or fragment) so two spellings of one deployment compare equal. Input that is not an absolute URL is returned trimmed.

func ConflictJSONDetails

func ConflictJSONDetails(root string, planCtx syncPlanContext, remote map[string]SnapshotEntry) map[string]conflictJSONDetail

conflictJSONDetails computes per-conflict detail for diff --json from the plan context and the current remote snapshot.

func ConflictedFiles

func ConflictedFiles(root string) ([]string, error)

ConflictedFiles lists the site paths of workspace files that still hold conflict markers left by a pull.

func CreateFileAction

func CreateFileAction(path string, body string) localFileAction

func DeleteFileAction

func DeleteFileAction(remotePath string) localFileAction

func DropStateFileEntry

func DropStateFileEntry(root string, remotePath string) error

dropStateFileEntry removes one file's base entry after its remote copy is deleted, so the next plan does not see a base with no local file and offer to delete a file that is already gone.

func EnsurePulledAgentsFile

func EnsurePulledAgentsFile(root string, files []creght.File) (bool, error)

ensurePulledAgentsFile 给本地 agent 生成一份 AGENTS.md,已有(本地或远端)就不动。 这份文件会被 push 进站点,站点又会被复制成模板或别的项目,所以内容里不能写这个站点 特有的信息(project / site ID、编辑器地址)——复制过去就指错了站,而远端已有文件时 不会再生成新的去纠正它。站点身份由 .creght/state.json 记录。

func FilterIgnoredSnapshot

func FilterIgnoredSnapshot(ignore *creghtIgnore, files map[string]SnapshotEntry) map[string]SnapshotEntry

func FilterIgnoredState

func FilterIgnoredState(ignore *creghtIgnore, files map[string]StateEntry) map[string]StateEntry

func HasConflictMarkers

func HasConflictMarkers(body string) bool

func IgnoredRemotePaths

func IgnoredRemotePaths(ignore *creghtIgnore, files []creght.File) []string

ignoredRemotePaths lists remote paths that .creghtignore hides from sync.

These files stay on the site. push neither uploads nor deletes them, and saveWorkspaceState drops their base entries, so no later plan has a base to delete from — a rule added before the remote copy was removed leaves that copy live and out of the CLI's reach. Reporting the paths is the difference between "stopped syncing" and "still on your site"; dropping them silently is what makes the ordering a trap. creght rm deletes one regardless.

func IsPathInside

func IsPathInside(root string, path string) bool

func IsUTF8FileBody

func IsUTF8FileBody(body []byte) bool

func LoadCreghtIgnore

func LoadCreghtIgnore(root string) (*creghtIgnore, error)

func LocalFileSnapshot

func LocalFileSnapshot(root string) (map[string]SnapshotEntry, error)

func LocalPathToRemote

func LocalPathToRemote(root string, localPath string) (string, error)

func Merge3

func Merge3(base string, local string, remote string) (merged string, clean bool)

merge3 performs a line-level three-way merge of local and remote against their common base. Non-overlapping changes merge cleanly; overlapping changes produce git-style conflict markers and clean=false.

func MergeStateSnapshot

func MergeStateSnapshot(base map[string]StateEntry, hasState bool, local map[string]SnapshotEntry, remote map[string]SnapshotEntry) map[string]SnapshotEntry

func NewClientID

func NewClientID() string

func NormalizeSitePath

func NormalizeSitePath(p string) string

normalizeSitePath turns a site path into its canonical "/a/b" form.

func ParseSnapshotVersionNo

func ParseSnapshotVersionNo(raw string) (int64, error)

func PrintSyncPlan

func PrintSyncPlan(out io.Writer, plan syncPlan, dryRun bool)

func PutStateFileEntry

func PutStateFileEntry(root string, siteID string, apiHost string, entry SnapshotEntry) error

putStateFileEntry updates the base state for a single file (used by single-file pull/push) without rewriting the whole snapshot.

func QetagHash

func QetagHash(body []byte) (string, error)

qetagHash is the content hash the platform reports for site files; local bodies are hashed the same way so the two can be compared.

func ReadBaseObject

func ReadBaseObject(root string, hash string) (string, bool)

readBaseObject returns the stored base content for a hash, if present. Workspaces pulled by older CLI versions have no base objects; callers fall back to hash-only conflict detection.

func RefuseSnapshotWorkspace

func RefuseSnapshotWorkspace(root string, command string) error

refuseSnapshotWorkspace stops a command that would treat a snapshot directory as an editable workspace.

func RemoteFileSnapshot

func RemoteFileSnapshot(files []creght.File) map[string]SnapshotEntry

func RemoteFileSnapshotForWorkspace

func RemoteFileSnapshotForWorkspace(root string, files []creght.File) (map[string]SnapshotEntry, error)

func RemotePathToLocal

func RemotePathToLocal(root string, remotePath string) (string, error)

func ResolveConflictBody

func ResolveConflictBody(body string, keepLocal bool) (string, int, error)

resolveConflictBody rewrites a marker-laden body keeping the local side (keepLocal) or the remote side of every conflict block.

func ResolveFile

func ResolveFile(root string, remotePath string, keepLocal bool) (int, error)

ResolveFile rewrites one file's conflict blocks keeping the local side (keepLocal) or the remote side, and returns how many blocks it resolved. Purely local; a later push uploads the result.

func ResolveSiteWorkspace

func ResolveSiteWorkspace(dir string, siteID string, searchParents bool, requireWorkspace bool) (string, string, error)

resolveSiteWorkspace resolves a command's workspace directory and site ref. When searchParents is true (the caller did not explicitly pass --dir), it walks upward so commands also work from a subdirectory of a pulled workspace.

func SaveWorkspaceState

func SaveWorkspaceState(root string, siteID string, apiHost string, files map[string]SnapshotEntry) error

func ShouldSkipLocalPath

func ShouldSkipLocalPath(root string, path string) bool

func SiteActionLabel

func SiteActionLabel(action string) string

func StatePath

func StatePath(root string) string

func UnifiedLineDiff

func UnifiedLineDiff(aName string, bName string, a string, b string) string

UnifiedLineDiff produces a git-style unified diff: only hunks around changed lines, with 3 lines of context and "@@ -a,b +c,d @@" headers, so a one-line change in a long file prints a few lines instead of the whole file. The diff itself comes from go-udiff, the diff implementation extracted from x/tools (gopls).

func UpdateFileAction

func UpdateFileAction(remote SnapshotEntry, body string) localFileAction

func WalkWorkspaceFiles

func WalkWorkspaceFiles(root string, fn func(localPath string) error) error

walkWorkspaceFiles walks every syncable local file under root, calling fn with the local path. Local paths mirror remote site paths exactly (page/Index.tsx <-> /page/Index.tsx, backend/func/booking.ts <-> /backend/func/booking.ts).

func WriteBackupFiles

func WriteBackupFiles(root string, label string, files map[string]string) (string, error)

writeBackupFiles copies path->body contents into a fresh directory under .creght/backup/, mirroring the workspace layout, and returns that directory. label distinguishes what was backed up (e.g. "local", "remote").

func WritePulledFile

func WritePulledFile(root string, entry SnapshotEntry) error

func WriteRemoteFilesToWorkspace

func WriteRemoteFilesToWorkspace(root string, files []creght.File) error

Types

type DiffEntry

type DiffEntry struct {
	Path             string `json:"path"`
	Status           string `json:"status"`
	Action           string `json:"action,omitempty"`
	Reason           string `json:"reason,omitempty"`
	AutoMergeable    *bool  `json:"auto_mergeable,omitempty"`
	BaseToLocalDiff  string `json:"base_to_local_diff,omitempty"`
	BaseToRemoteDiff string `json:"base_to_remote_diff,omitempty"`
}

DiffEntry / DiffResult are the machine-readable form of a sync plan, so an agent can decide how to resolve without parsing human text. Conflict entries carry the base->local and base->remote diffs plus whether a pull would auto-merge them, when the base content is recorded.

type DiffResult

type DiffResult struct {
	HasConflicts bool        `json:"has_conflicts"`
	Files        []DiffEntry `json:"files"`
}

type FileChange

type FileChange struct {
	Path string `json:"path"`
	// Action is file_create, file_update or file_delete.
	Action string `json:"action"`
}

FileChange is one change push made to the remote site.

type Plan

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

Plan is what push would do to the remote site, against the recorded base.

func (Plan) Conflicts

func (p Plan) Conflicts() []PlanConflict

Conflicts are the files push would refuse over.

func (Plan) HasConflicts

func (p Plan) HasConflicts() bool

HasConflicts reports whether push would refuse to run.

func (Plan) LocalChanges

func (p Plan) LocalChanges() []FileChange

LocalChanges are the changes push would make.

func (Plan) Print

func (p Plan) Print(out io.Writer)

Print writes the plan as diff prints it.

func (Plan) Result

func (p Plan) Result() DiffResult

Result is the plan in diff --json form.

type PlanConflict

type PlanConflict struct {
	Kind   string
	Path   string
	Reason string
}

type PullOptions

type PullOptions struct {
	// Force overwrites local files with the remote workspace instead of
	// merging; overwritten local work is backed up under .creght/backup/.
	Force bool
	// SkipAgentsFile leaves out the AGENTS.md a pull otherwise writes into a
	// workspace that has none.
	SkipAgentsFile bool
}

PullOptions are pull's flags.

type PullOutcome

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

pullOutcome summarizes what a pull did, for reporting.

func SafePullWorkspace

func SafePullWorkspace(root string, siteID string, apiHost string, remoteFiles map[string]SnapshotEntry, out io.Writer) (PullOutcome, error)

type PullResult

type PullResult struct {
	Dir     string
	Changed int
	// Merged are files changed on both sides whose edits merged cleanly.
	Merged []string
	// Conflicted are files changed on both sides with overlapping edits; they
	// now hold conflict markers to edit or resolve before pushing.
	Conflicted []string
	// BackupDir is where overwritten local work was saved, if any.
	BackupDir         string
	AgentsFileCreated bool
}

PullResult reports what a pull did.

func Pull

func Pull(ctx context.Context, client *creght.Client, projectID string, siteID string, dir string, apiHost string, opts PullOptions, out io.Writer) (PullResult, error)

Pull merges the site's remote workspace into dir (a new directory, or a workspace of the same site), three-way against the recorded base, and records the new base. apiHost is stamped on a workspace that has none recorded.

type PushReport

type PushReport struct {
	Changes []FileChange
	// SkippedConflicts are files PushSafe's skipConflicts left out; they keep
	// their base so a later pull can still merge them.
	SkippedConflicts []string
}

PushReport is what a push did.

type SnapshotEntry

type SnapshotEntry struct {
	ID       string
	Path     string
	Hash     string
	Body     string
	Readonly bool
}

type SnapshotResult

type SnapshotResult struct {
	Dir       string
	SiteRef   string
	VersionNo int64
	// VersionID and Note are labels from the publish state; zero/empty when it
	// could not be read.
	VersionID int64
	Note      string
	// Files is how many files the version has; Removed is how many files the
	// directory held that the version does not, and were deleted.
	Files   int
	Removed int
}

SnapshotResult reports what a version pull wrote.

func PullVersionSnapshot

func PullVersionSnapshot(ctx context.Context, client *creght.Client, projectID string, realSiteID string, root string, apiHost string, versionNo int64) (SnapshotResult, error)

pullVersionSnapshot writes version versionNo of the site into root.

type StateEntry

type StateEntry struct {
	Hash     string `json:"hash"`
	Readonly bool   `json:"readonly,omitempty"`
}

type Syncer

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

func NewSyncer

func NewSyncer(client *creght.Client, projectID string, siteID string, dir string, apiHost string, out io.Writer) (*Syncer, error)

func (*Syncer) Dir

func (s *Syncer) Dir() string

Dir is the workspace root, made absolute.

func (*Syncer) Plan

func (s *Syncer) Plan(ctx context.Context, allowDelete bool) (Plan, error)

Plan compares local files, the recorded base and the remote site. allowDelete plans remote deletions for files removed locally.

func (*Syncer) Push

func (s *Syncer) Push(ctx context.Context) (PushReport, error)

Push overwrites the remote site with the local workspace (push --force): every local file that differs is uploaded and every remote file missing locally is deleted, without a three-way check.

func (*Syncer) PushSafe

func (s *Syncer) PushSafe(ctx context.Context, allowDelete bool, skipConflicts bool) (PushReport, error)

PushSafe uploads local changes after a three-way comparison. Conflicted files abort the push unless skipConflicts is set, in which case everything else is pushed and the conflicted files keep their base state so a later pull can still merge them.

type WorkspaceState

type WorkspaceState struct {
	SiteID string `json:"site_id"`
	// APIHost is the Creght deployment this workspace was pulled from. It is
	// what lets later commands here resolve the host without CREGHT_API_HOST;
	// see resolveAPIHost. Empty in workspaces pulled by older CLI versions.
	APIHost   string                `json:"api_host,omitempty"`
	UpdatedAt string                `json:"updated_at"`
	Files     map[string]StateEntry `json:"files"`
	// Snapshot is set when the directory holds one site version pulled by
	// pull --version_no rather than an editable workspace; see snapshot.go.
	Snapshot *snapshotInfo `json:"snapshot,omitempty"`
}

func FindWorkspaceState

func FindWorkspaceState(start string, searchParents bool) (string, WorkspaceState, bool, error)

func LoadWorkspaceState

func LoadWorkspaceState(root string) (WorkspaceState, bool, error)

Jump to

Keyboard shortcuts

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