Documentation
¶
Index ¶
- Constants
- Variables
- func AllowsLocalRunner(allowed []string) bool
- func AssertAbsExecRoot(execRoot string) error
- func EnsureGoferGitignore(projectRoot string) error
- func ExchangeDir(cfg *config.Config, proj config.ProjectConfig) (string, error)
- func ExistsInRoot(root, rel string) (bool, error)
- func GitRO(dir string, capBytes int, args ...string) (string, error)
- func JobResultDir(cfg *config.Config, projKey string, proj config.ProjectConfig, jobID string) (string, error)
- func OpenInRoot(root, rel string) (*os.File, error)
- func ResolveByCwd(cfg *config.Config, absCwd string) (key, relCwd string, ok bool)
- func ResultBaseDir(cfg *config.Config, projKey string, proj config.ProjectConfig) (string, error)
- func SafeJoin(execRoot string, cwd string) (string, error)
- func SafeJoinReal(execRoot, rel string) (string, error)
- type ApplyProjects
- type CheckResult
- type Commit
- type DocContent
- type FileContent
- type GitStatus
- type Option
- type Placement
- type Registry
- func (r *Registry) Add(key string, proj config.ProjectConfig, force bool) error
- func (r *Registry) Config() *config.Config
- func (r *Registry) Get(key string) (config.ProjectConfig, error)
- func (r *Registry) List() []string
- func (r *Registry) Path() string
- func (r *Registry) Reload(newCfg *config.Config)
- func (r *Registry) Remove(key string) error
- func (r *Registry) Validate(key string) ([]CheckResult, bool, error)
- type RepoCache
- type RepoInfo
Constants ¶
const DefaultRepoCacheTTL = 30 * time.Second
DefaultRepoCacheTTL is how long a DiscoverRepos result is reused.
Variables ¶
var ErrBinary = errors.New("file is not text")
ErrBinary is returned by ReadKeyFile when the target is not text (handler → 415). The web preview only renders text/markdown/json.
var ErrForbiddenDoc = errors.New("forbidden doc")
ErrForbiddenDoc is returned by ReadDoc when the request is not an allowed doc read: empty / absolute / traversing / hidden-segment / ':' or '\' paths, or an extension outside the markdown whitelist (handler → 403).
var ErrForbiddenFile = errors.New("file not in key-file allowlist")
ErrForbiddenFile is returned by ReadKeyFile when the requested basename is not in keyFileAllowlist (handler → 403). It guards against arbitrary file reads (e.g. .env exfiltration), independent of path traversal.
var ErrProjectNotLocal = errors.New("project_not_local")
ErrProjectNotLocal is returned by ReadDoc when the project does not run on the server's own machine (allowed_runners excludes local), so the server cannot read its files (handler → 409 project_not_local).
Functions ¶
func AllowsLocalRunner ¶
AllowsLocalRunner reports whether the allowlist permits the built-in local runner: an empty allowlist defaults to local, otherwise it must be listed — under either of its accepted spellings ("local" canonical, "server" the CLI alias; see config.BuiltinLocalRunner), because the two name one runner.
"server" / "local" are reserved names, so an allowlist entry spelled either way can only mean the built-in runner.
func AssertAbsExecRoot ¶ added in v0.176.0
AssertAbsExecRoot rejects a configured project path (host_path / container_path, as picked by Config.ExecPath) that is not absolute for the OS gofer runs on. Without it filepath.Abs would join the path onto the process cwd, so e.g. `D:/projects/demo` on Linux silently became `<cwd>/D:/projects/demo` and a job ran (and created) there.
func EnsureGoferGitignore ¶ added in v0.204.0
EnsureGoferGitignore makes the generated .gofer/jobs and .gofer/attachments directories untracked without changing any existing project-owned .gofer entries. It is best-effort at call sites: a failure must not fail a job or transfer.
func ExchangeDir ¶
ExchangeDir returns the absolute exchange directory for a project: <exec_path>/<resolved exchange_subdir> (exec_path = Config.ExecPath, E29/D10). The exchange subdir is validated to stay inside the project root.
func ExistsInRoot ¶ added in v0.213.0
ExistsInRoot reports whether something (file, directory or any link, even a dangling or escaping one) exists at rel, using Lstat so the link itself is judged. A missing path (or a missing parent) is false, nil; an intermediate directory that escapes root is an error, not "absent".
func GitRO ¶ added in v0.219.0
GitRO runs a read-only git subcommand in dir (fixed args from the caller, never user concatenation) under the same timeout, output cap and no-optional-locks rules as the browse layer (runGitRO). A failure is returned as it came out of the process, so a caller that must tell a git "no" (exit status 1, e.g. merge-base --is-ancestor) from a git that could not run can inspect it with errors.As on *exec.ExitError.
func JobResultDir ¶
func JobResultDir(cfg *config.Config, projKey string, proj config.ProjectConfig, jobID string) (string, error)
JobResultDir returns the result directory for a specific job id.
func OpenInRoot ¶ added in v0.213.0
OpenInRoot opens the file rel (slash or OS separators, relative to root) for reading, refusing any link on the way that escapes root. A missing file keeps the os.IsNotExist semantics; an escaping link is a different error.
func ResolveByCwd ¶
ResolveByCwd returns the project key whose host_path or container_path is the longest prefix of absCwd, plus cwd relative to that root (D7). It only uses the 注册锚 (host/container path), never the overlay. ok=false on zero match or a tie (两个项目同长前缀 → 让用户显式 -p, 避免误派).
func ResultBaseDir ¶
ResultBaseDir returns the base directory under which per-job result dirs are created. Explicit storage/project path settings preserve the old exchange-based layout; when none are set, the default is <project root>/.gofer/jobs.
func SafeJoin ¶
SafeJoin resolves a request-supplied relative cwd against a project's execution root (execRoot, = Config.ExecPath(proj), E29/D10) and guarantees the result stays inside that root. Only relative cwd values are accepted; an empty cwd is treated as ".".
It returns the absolute directory (under execRoot) to run in.
The code runs on Linux but must reject Windows-style absolute inputs too (drive letters like `D:\x` / `C:/y`, and backslash-rooted `\x`), since the caller may be a host on Windows. We therefore do manual detection instead of relying solely on the platform's filepath.IsAbs.
func SafeJoinReal ¶ added in v0.213.0
SafeJoinReal is SafeJoin plus symlink resolution, for READING project files: it returns the real (symlink-free) path of the target, and rejects a target whose real path leaves the real execRoot (a symlink file or an intermediate symlink directory pointing outside). Symlinks that stay inside the project are allowed. A missing target returns an error wrapping os.ErrNotExist; an escape returns a generic error that does not carry the resolved path.
Types ¶
type ApplyProjects ¶
type ApplyProjects func(mut func(projects map[string]config.ProjectConfig) error) error
ApplyProjects is the injected serial-write seam (B2 / plan T1-B). The applier owns the config write transaction; it calls mut with a NON-NIL projects map it may set/delete whole entries on, and — on mut success — persists and publishes the new config. The contract is deliberately narrow: mut MUST NOT edit a ProjectConfig value's fields or touch any other top-level config field, so the applier's one-level clone (config.Config.Clone) is sufficient.
type CheckResult ¶
CheckResult is a single named validation outcome.
type Commit ¶
type Commit struct {
Hash string `json:"hash"`
Subject string `json:"subject"`
Author string `json:"author"`
Ts int64 `json:"ts"`
}
Commit is one entry of GitStatus.RecentCommits (E20). Ts is the committer date as a unix second timestamp.
type DocContent ¶ added in v0.213.0
type DocContent struct {
Path string `json:"path"`
Size int64 `json:"size"`
Content string `json:"content"`
Truncated bool `json:"truncated"`
}
DocContent is the ReadDoc result. Path is the hit candidate relative to the project root, slash-separated (never an absolute path).
func ReadDoc ¶ added in v0.213.0
func ReadDoc(cfg *config.Config, proj config.ProjectConfig, base, rel string) (DocContent, error)
ReadDoc reads a markdown document under a project's execution root for the web doc reader. Order: AllowsLocalRunner (else ErrProjectNotLocal) → path rules (else ErrForbiddenDoc) → extension whitelist (else ErrForbiddenDoc) → candidates base/rel then rel, each resolved with SafeJoinReal (symlink-aware; a failure or escape counts as not found) and required to be a regular file → read with the maxKeyFileBytes cap (truncated, not rejected) → NUL means ErrBinary. Every not-found case returns the same path-free error wrapping os.ErrNotExist.
type FileContent ¶
type FileContent struct {
Name string `json:"name"`
Size int64 `json:"size"`
Content string `json:"content"`
Truncated bool `json:"truncated"`
}
FileContent is a read whitelisted key file (E32, design §6.4). Truncated is true when the file exceeds maxKeyFileBytes and Content is the leading slice.
func ReadKeyFile ¶
func ReadKeyFile(cfg *config.Config, proj config.ProjectConfig, rel string) (FileContent, error)
ReadKeyFile reads a whitelisted key file under a project's execution root (E32, D3, §8). Layered guards, in order: basename ∈ keyFileAllowlist (else ErrForbiddenFile) → SafeJoinReal(ExecPath, rel) anti-traversal + symlink escape (escape → error) → the resolved real basename must also be allowlisted (else fs.ErrNotExist) → must be a regular file (else fs.ErrNotExist) → text-only (binary → ErrBinary). Content over maxKeyFileBytes is truncated (Truncated=true), not rejected.
type GitStatus ¶
type GitStatus struct {
IsGitRepo bool `json:"is_git_repo"`
Branch string `json:"branch"`
Dirty bool `json:"dirty"`
RecentCommits []Commit `json:"recent_commits"`
}
GitStatus is the current git state of a project root (E20, design §6.3). When the root is not a git work tree (or not locally reachable) IsGitRepo is false and the rest is zero.
func ProjectGit ¶
ProjectGit returns the current git state of a project's execution root (E20). IsGitRepo is false when the root is not a git work tree (or not locally reachable / git absent) — never an error in that case. Branch / dirty / recent commits are best-effort (a degraded field stays zero, the call still succeeds).
type Option ¶
type Option func(*Registry)
Option customises a Registry at construction.
func WithProjectApplier ¶
func WithProjectApplier(a ApplyProjects) Option
WithProjectApplier injects the serial-write seam (core.Core.Update adapter in a serve/mcp process). A nil applier is ignored, leaving the localApply default — that is the standalone CLI degradation (`gofer project add` with no running core): clone + save + atomic Store, in-process, no reload/push.
type Placement ¶ added in v0.213.0
type Placement struct {
// contains filtered or unexported fields
}
Placement is a destination being written inside a root: the caller writes the payload to File() (and does its own size / sha256 checks), then Commit()s to move it into place or Abort()s to drop it. A half-written file is therefore never visible under the destination name.
func PlaceInRoot ¶ added in v0.213.0
PlaceInRoot creates the parent directories of rel inside root and opens the temp file rel+".gofer-tmp-"+tmpSuffix next to the destination (same directory, so the final Rename stays on one filesystem and is atomic). Errors are wrapped as "create destination directory: …" / "open temp file: …" (the callers' historic wording) and keep the os.Root error underneath. Any link on the way that escapes root fails the call and leaves nothing outside root.
func (*Placement) Abort ¶ added in v0.213.0
func (p *Placement) Abort()
Abort closes the temp file and removes it. Safe to call repeatedly, and after Commit (then it does nothing).
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry manages project entries over a loaded config and persists changes back to the config file via config.Save.
The config is held behind an atomic.Pointer so SIGHUP-driven hot-reload (C3) can atomically swap in a freshly loaded config without locking every read path. Each read takes one snapshot (cfg.Load()) and uses it for the whole call so a concurrent Reload can never make a single call observe two configs.
func NewRegistry ¶
NewRegistry builds a registry over cfg loaded from path. path may be empty (no config file yet); the localApply default resolves a user-level path on first write. Opts may inject a project applier (WithProjectApplier).
func (*Registry) Add ¶
Add registers proj under key and writes the config back. It refuses to overwrite an existing key unless force is true.
The existence check and the mutation run INSIDE the apply seam's transaction (on the map the applier hands over), never on a pre-read snapshot: routing every write through the one serial transaction is what makes concurrent POST/DELETE lose no updates and share no Rev (B2 / plan T1-C). Add never edits a ProjectConfig value in place — it sets a whole entry — honouring the seam contract.
func (*Registry) Get ¶
func (r *Registry) Get(key string) (config.ProjectConfig, error)
Get returns the project config for key, or an error if not registered.
func (*Registry) Reload ¶
Reload atomically swaps the registry's config to newCfg (C3 hot-reload). It is safe to call concurrently with any read path; in-flight reads keep using the snapshot they already loaded.
type RepoCache ¶ added in v0.176.0
type RepoCache struct {
// contains filtered or unexported fields
}
RepoCache memoises DiscoverRepos per project. The scan walks the whole project tree and runs git per repo (hundreds of ms on a big workspace) while the Projects and New job pages both ask on every open. An entry is keyed by project key + resolved exec path and is dropped when the TTL passes or the config snapshot it was built from is replaced (a reload / project edit). The zero value is ready to use.
func (*RepoCache) Discover ¶ added in v0.176.0
func (c *RepoCache) Discover(cfg *config.Config, key string, proj config.ProjectConfig, refresh bool) ([]RepoInfo, error)
Discover returns the cached repos of project key, or scans (and caches) when there is no fresh entry or refresh is true. The returned slice is a copy.
type RepoInfo ¶
type RepoInfo struct {
RelPath string `json:"rel_path"`
Branch string `json:"branch"`
Dirty bool `json:"dirty"`
}
RepoInfo is one discovered git repo under a project root (E32, design §6.4). RelPath is "." for the root repo, else slash-separated relative to ExecPath.
func DiscoverRepos ¶
DiscoverRepos walks a project's execution root up to repoScanDepth, skipping repoSkipDirs, and returns each directory that contains a .git entry with its branch + dirty flag (E32, D4). The hit count is capped at maxRepos. The root itself is included when it is a repo (RelPath "."). Always returns a non-nil slice. Unreadable entries are skipped (best-effort), not fatal.