Documentation
¶
Index ¶
- Constants
- Variables
- func DefaultConfigTemplate() string
- func DefaultDenyPaths() []string
- func EnsureGlobalConfig() (bool, string)
- func GlobalChatSettings() (maxToolRounds, toolResultCap int, denyExtra []string)
- func GlobalConfigHealthy() error
- func GlobalConfigPath() string
- func GlobalInitAIGitignore() bool
- func GlobalResolveMinConfidence() float64
- func GlobalResolveSettings() (verify []string, unionFiles []string, unionSet bool)
- func ListModify(path, dotKey, item string, add bool) (string, error)
- func LocalConfigPath(repoRoot string) string
- func ReadGK() (map[string]any, error)
- func SetConfigWarnWriter(w io.Writer) func()
- func SetList(path, dotKey string, items []string) (string, error)
- func SetValue(path, dotKey, rawValue string) (string, error)
- func UnknownKeys(path string) ([]string, error)
- func UnsetValue(path, dotKey string) (bool, error)
- func ValidKey(dotKey string) bool
- func ValueSource(dotKey, repoRoot string) string
- func WriteDefaultConfig(path string, force bool) error
- type AIAnthropicConfig
- type AIAssistConfig
- type AIChatConfig
- type AICommitConfig
- type AIConfig
- type AICustomProviderConfig
- type AIGroqConfig
- type AINvidiaConfig
- type AIOpenAIConfig
- type BranchConfig
- type CloneConfig
- type CloneMeta
- type CommitConfig
- type Config
- type FleetConfig
- type FollowConfig
- type ForgetConfig
- type GitHubConfig
- type GitHubCountsConfig
- type HostAlias
- type InitConfig
- type LandConfig
- type LogConfig
- type OutputConfig
- type PreflightConfig
- type PreflightStep
- type PrivacyConfig
- type PromoteConfig
- type PullConfig
- type PushConfig
- type RefreshConfig
- type ResolveConfig
- type ShipConfig
- type SnapshotConfig
- type StatusConfig
- type SyncConfig
- type UIConfig
- type VersionFile
- type WorktreeConfig
- type WorktreeInit
Constants ¶
const LocalConfigHeader = "" /* 129-byte string literal not displayed */
LocalConfigHeader is written at the top of a freshly created .gk.yaml so the file explains itself. The global template (default_config.yaml) is unsuited to repo-local files — it documents every field as a starting point, whereas .gk.yaml should hold only the handful of repo overrides.
Variables ¶
var ErrConfigExists = errors.New("config file already exists")
ErrConfigExists is returned by WriteDefaultConfig when the target path already exists and force=false.
var ErrNotList = errors.New("key is not a list; += / -= require a list-valued key")
ErrNotList is returned when the `+=` / `-=` list operators are applied to a key that isn't a list-valued field.
var ErrNotScalar = errors.New("key holds a list or map, not a scalar")
ErrNotScalar is returned when a key addresses a list/map node that `set` cannot write a single scalar into (e.g. ai.commit.deny_paths).
var ErrUnknownKey = errors.New("unknown config key")
ErrUnknownKey is returned when a dot-key does not correspond to any field in the Config schema (and is not under a dynamic map like ai.providers).
Functions ¶
func DefaultConfigTemplate ¶
func DefaultConfigTemplate() string
DefaultConfigTemplate returns the commented YAML template written by `gk init config` and the first-run auto-init path. Exposed so tests (and `gk config template`) can inspect what will land on disk.
func DefaultDenyPaths ¶
func DefaultDenyPaths() []string
DefaultDenyPaths returns the baked-in deny_paths used when the user has none configured. Globs are matched with filepath.Match against both basename and full path; entries containing "/" require the path shape, bare entries match anywhere.
Categories:
- secrets: .env, SSH keys, TLS material, cloud credentials
- infra state: terraform state, ansible/hashicorp vault
- data: sqlite DBs, raw dumps (often contain PII)
- compiled artifacts: __pycache__, *.class — useless for commit prose and bloat token usage
func EnsureGlobalConfig ¶
EnsureGlobalConfig is the hook wired into cmd/gk/main.go. On first run — when the global config file is missing — it writes the commented template and prints a single stderr notice so users see "where" their config lives. Failures are swallowed: a read-only home dir, sandbox, or bad $XDG_CONFIG_HOME must not break gk.
Opt-outs:
- GK_NO_AUTO_CONFIG=1 skips the attempt entirely (useful in CI and in our own test suite).
- Any IO error during write is silently ignored — tell the user next time, not now.
Returns (created, path). `created` is true only when the file was freshly written on this call.
func GlobalChatSettings ¶
GlobalChatSettings reads gk chat's tool-loop knobs from the GLOBAL config only (ai.chat.max_tool_rounds / tool_result_cap / deny_paths). Same trust boundary as resolve.verify: a cloned repo's .gk.yaml must not be able to raise the tool budget or alter the deny surface of a chat session running inside it. Zero returns mean "unset — use the caller's default"; denyExtra only ever ADDS globs (the caller unions with DefaultDenyPaths, so no layer can shrink below the defaults).
func GlobalConfigHealthy ¶
func GlobalConfigHealthy() error
GlobalConfigHealthy reports a non-nil error when the global config file EXISTS but cannot be parsed — the global-only resolve safety settings (verify, union_files, min_confidence) silently fall back to their defaults in that state, which callers should surface, not swallow.
func GlobalConfigPath ¶
func GlobalConfigPath() string
GlobalConfigPath resolves to $XDG_CONFIG_HOME/gk/config.yaml (defaulting to ~/.config/gk/config.yaml). Returns empty when the user's home directory is unknown — callers should treat that as a signal to skip writing rather than crash.
func GlobalInitAIGitignore ¶
func GlobalInitAIGitignore() bool
GlobalInitAIGitignore reports whether the GLOBAL config file turns on init.ai_gitignore. `gk init` consults this instead of the layered value: the key enables a remote AI call, so a repo-local .gk.yaml inside an untrusted checkout must not be able to switch it on silently — only the user's own global config (or an explicit --ai-gitignore flag) may.
func GlobalResolveMinConfidence ¶
func GlobalResolveMinConfidence() float64
GlobalResolveMinConfidence reads resolve.min_confidence from the GLOBAL config file only — a repo-local .gk.yaml lowering the gate would widen what gets auto-applied inside an untrusted checkout.
func GlobalResolveSettings ¶
GlobalResolveSettings reads resolve.verify and resolve.union_files from the GLOBAL config file only. Both keys shape what `gk resolve` executes or auto-merges, so a repo-local .gk.yaml inside an untrusted checkout must not be able to widen them: verify runs arbitrary shell commands (the same trust boundary as init.ai_gitignore), and union_files silently expands the auto-merge surface. unionSet distinguishes "unset → defaults" from an explicit empty list (= union merging disabled).
func ListModify ¶
ListModify adds or removes a single item from the list-valued key at dotKey, preserving comments, ordering, and the file's other entries. add=true appends item idempotently (a duplicate is a no-op); add=false removes every matching entry. Returns the resulting list rendered as "[a, b, c]" for the success line.
Mirrors SetValue's node-tree editing but targets a SequenceNode, so `set`'s scalar-only restriction no longer blocks list maintenance. Rejects scalar keys up front (ErrNotList) so `foo+=bar` on a non-list fails clearly. Removing from an absent key is a no-op (no error), matching UnsetValue's tolerance.
func LocalConfigPath ¶
LocalConfigPath returns the repo-local .gk.yaml path for a working-tree root, or "" when root is empty.
func ReadGK ¶
ReadGK returns git config entries under the gk.* namespace as a nested map suitable for viper.MergeConfigMap. Returns an empty map (nil error) when the working directory is not a git repository or there are no gk.* entries.
func SetConfigWarnWriter ¶
SetConfigWarnWriter redirects broken-config warnings (default os.Stderr) and clears the dedupe set; returns a restore func. Test hook.
func SetList ¶
SetList replaces the whole list at dotKey with items, preserving comments and ordering elsewhere in the file. ListModify edits one element at a time; this writes a chosen set wholesale — the setup wizard's vis pickers land here. Rejects scalar keys (ErrNotList); an absent key is created flow-style.
func SetValue ¶
SetValue writes rawValue at dotKey in the YAML file at path, preserving all surrounding comments and ordering. The file is created (empty root) if missing — callers that want the documented template scaffolded first should do so before calling. It returns the typed value as serialized.
func UnknownKeys ¶
UnknownKeys returns every dot-key explicitly set in the YAML file at path that is not part of the Config schema — i.e. typos or stale fields that Load silently ignores. Keys under a dynamic-map prefix (ai.providers.*) are skipped since arbitrary names are valid there. A missing file yields nil.
func UnsetValue ¶
UnsetValue removes dotKey from the YAML file at path, reverting it to its built-in default. Returns existed=false (no error) when the key was absent.
func ValidKey ¶
ValidKey reports whether dotKey is a settable Config field. A key is valid if it resolves to a leaf in the Defaults() schema, or it sits under a known dynamic map prefix (ai.providers.<name>.*, clone.hosts.<name>.*).
func ValueSource ¶
ValueSource reports which file supplies the effective value for dotKey: "local" (repo .gk.yaml), "global" ($XDG_CONFIG_HOME/gk/config.yaml), or "default" (built-in, no file sets it). repoRoot may be "" outside a repo. Note: this inspects the two config files only — it does not account for GK_* env vars or git-config gk.* overrides, which also feed Load().
func WriteDefaultConfig ¶
WriteDefaultConfig creates the commented YAML template at path.
Behaviour:
- Creates missing parent directories (0o755).
- Refuses to overwrite an existing file unless force=true. Returns ErrConfigExists so callers can distinguish that from a genuine IO failure.
- Writes the exact bytes of the embedded template (deterministic across releases — no template expansion).
Types ¶
type AIAnthropicConfig ¶
type AIAnthropicConfig struct {
Model string `mapstructure:"model" yaml:"model"`
Endpoint string `mapstructure:"endpoint" yaml:"endpoint"`
Timeout string `mapstructure:"timeout" yaml:"timeout"`
APIKey string `mapstructure:"api_key" yaml:"api_key"`
}
AIAnthropicConfig controls the Claude provider. Empty fields fall back to the adapter defaults.
APIKey, when set, takes precedence over the ANTHROPIC_API_KEY env var. Prefer the env var for shared/committed configs — a key written here lands in a plaintext yaml that is easy to leak.
type AIAssistConfig ¶
type AIAssistConfig struct {
Mode string `mapstructure:"mode" yaml:"mode"`
Status bool `mapstructure:"status" yaml:"status"`
IncludeShape bool `mapstructure:"include_shape" yaml:"include_shape"`
IncludeDiff bool `mapstructure:"include_diff" yaml:"include_diff"`
RecentCommits int `mapstructure:"recent_commits" yaml:"recent_commits"`
DiffBudget int `mapstructure:"diff_budget" yaml:"diff_budget"`
MaxTokens int `mapstructure:"max_tokens" yaml:"max_tokens"`
TimeoutSecs int `mapstructure:"timeout_secs" yaml:"timeout_secs"`
Cache bool `mapstructure:"cache" yaml:"cache"`
}
AIAssistConfig controls AI help that is attached to existing commands. Mode accepts:
- "off": never attach AI help unless a CLI flag explicitly asks for it.
- "suggest": print a lightweight hint pointing to `gk next`.
- "auto": run the configured AI assistant automatically for enabled surfaces such as `gk status`.
Status gates the `gk status` surface.
IncludeShape adds the CHANGE SHAPE to the prompt: per-file added/deleted counts plus the enclosing declarations git names in its own `@@ … @@` hunk context. On by default. Without it the assistant sees only file NAMES and can do no better than restate the file count, which is the one thing the deterministic status line already says. It ships no code body, so it stays far cheaper and narrower than IncludeDiff.
IncludeDiff adds the full working-tree diff (truncated to DiffBudget bytes and run through the privacy gate), letting the assistant reason line by line. Off by default — it raises token cost and widens the data sent to remote providers. IncludeShape usually gets most of the benefit; turn this on when you want the assistant reading actual code.
RecentCommits is how many recent commit subjects to include (default 5), giving the assistant a time axis: whether the dirty tree continues the last commit's theme or starts something new. 0 disables.
DiffBudget caps the diff size in bytes when IncludeDiff is on (default 8000). MaxTokens is the advisory response cap (default 1200). TimeoutSecs bounds a single status AI call so `gk status` never hangs on a slow provider (default 8). Cache stores the result keyed by the repo state so repeated/auto invocations on an unchanged tree skip the provider entirely (default true).
type AIChatConfig ¶
type AIChatConfig struct {
Timeout string `mapstructure:"timeout" yaml:"timeout"`
MaxTokens int `mapstructure:"max_tokens" yaml:"max_tokens"`
// RoundTimeout bounds ONE gk chat provider round-trip (default
// "120s"). Separate from Timeout (30s, sized for do/ask single
// shots): chat rounds carry tool definitions, repo context, and
// accumulated tool results, and the adapter's internal 5xx retries
// (backoff included) must fit inside this budget — a proxy that
// occasionally 500s needs ~3 attempts × response time + backoff.
RoundTimeout string `mapstructure:"round_timeout" yaml:"round_timeout,omitempty"`
// MaxToolRounds bounds provider round-trips per gk chat turn
// (default 15). Global config only.
MaxToolRounds int `mapstructure:"max_tool_rounds" yaml:"max_tool_rounds,omitempty"`
// ToolResultCap bounds one tool result's bytes (default 32768).
// Global config only.
ToolResultCap int `mapstructure:"tool_result_cap" yaml:"tool_result_cap,omitempty"`
// HistoryBudget approximates the token budget for the conversation
// replayed to the provider each round (default 32768; see
// chat.trimHistory). Provider context windows comfortably exceed
// this — trimming protects cost, not correctness. 0/negative falls
// back to the default, same convention as MaxTokens/MaxToolRounds.
HistoryBudget int `mapstructure:"history_budget" yaml:"history_budget,omitempty"`
// DenyPaths adds chat-specific deny globs on top of the defaults and
// ai.commit.deny_paths. Global config only.
DenyPaths []string `mapstructure:"deny_paths" yaml:"deny_paths,omitempty"`
// SessionRetentionDays, like Snapshot.RetentionDays, is opt-in (0 =
// never auto-prune). When set, it becomes the default --keep-days for
// `gk chat sessions prune` when the flag is not passed. Unlike
// MaxToolRounds/ToolResultCap/DenyPaths this is NOT a security-relevant
// knob — it only controls how long local session JSONL files are kept
// on disk — so it is read via the normal merged config path (repo
// .gk.yaml may set it), not GlobalChatSettings.
SessionRetentionDays int `mapstructure:"session_retention_days" yaml:"session_retention_days,omitempty"`
// AutoContext, when true, injects a depth/file-capped directory tree
// (built from `git ls-files`, like aider's repo-map but scoped down to
// structure only — no ctags/symbol index, which would overreach gk
// chat's git-Q&A position) into the system prompt as REPO_MAP. This
// saves the model from spending file_list/git_grep tool rounds just to
// learn "what does this project look like". Default FALSE: it costs
// prompt tokens on every session even when the question never touches
// repo structure, so it opts in like ai.assist.* rather than on by
// default like HistoryBudget. Same merged-config path as
// SessionRetentionDays (not security-relevant — it only widens what
// orientation text the model starts with, not what it can read or do,
// since git_grep/file_list already expose the whole tree on demand).
AutoContext bool `mapstructure:"auto_context" yaml:"auto_context,omitempty"`
}
AIChatConfig controls the AI chat subcommands (`gk do`, `gk explain`, `gk ask`, `gk chat`). Timeout is a Go duration string for AI provider calls (default "30s"). MaxTokens caps the response token budget (default 4096).
MaxToolRounds, ToolResultCap, and DenyPaths tune `gk chat`'s agentic tool loop. Like resolve.verify they are honored from the GLOBAL config only (GlobalChatSettings) — a cloned repo's .gk.yaml raising the tool budget or touching the deny list is the same attack shape as init.ai_gitignore. The struct fields exist for defaults and scaffold documentation; live reads go through the global-only path. Chat's effective deny list is always a union with DefaultDenyPaths, so no config layer can shrink it below the defaults.
HistoryBudget, like RoundTimeout, is a normal merged field (NOT global-only): it only trades off cost/context for a session already governed by the sandbox + deny list, it does not widen what the model can see or how many actions it can take, so a repo-local override is not the init.ai_gitignore attack shape.
Dangerous `gk do` commands always require an extra confirmation (unless --force); that gate is not configurable. A former `safety_confirm` field implied it could be turned off but never actually did, so it was removed.
type AICommitConfig ¶
type AICommitConfig struct {
Mode string `mapstructure:"mode" yaml:"mode"`
MaxGroups int `mapstructure:"max_groups" yaml:"max_groups"`
MaxTokens int `mapstructure:"max_tokens" yaml:"max_tokens"`
// Model overrides ai.<provider>.model for `gk commit` only. Commit
// message generation is a mechanical task that a small, fast model
// handles well, so this lets a cheaper model run commits while the
// chat/advice commands (do/ask/explain/status) keep the larger default
// model. Empty falls back to the provider's configured model. Honoured
// only by HTTP providers (anthropic/openai/nvidia/groq and custom);
// CLI providers (gemini/qwen/kiro) own their own model selection.
Model string `mapstructure:"model" yaml:"model"`
// Lang overrides ai.lang for `gk commit` only — set it to write commit
// messages in one language (e.g. "en") while keeping chat/advice commands
// (do/ask/explain) in another. Empty falls back to ai.lang (which itself
// follows output.lang). A one-shot `gk commit --lang <code>` still wins.
Lang string `mapstructure:"lang" yaml:"lang"`
Timeout string `mapstructure:"timeout" yaml:"timeout"`
DenyPaths []string `mapstructure:"deny_paths" yaml:"deny_paths"`
AllowRemote bool `mapstructure:"allow_remote" yaml:"allow_remote"`
Trailer bool `mapstructure:"trailer" yaml:"trailer"`
Audit bool `mapstructure:"audit" yaml:"audit"`
Privacy PrivacyConfig `mapstructure:"privacy" yaml:"privacy"`
// WIPPatterns are EXTRA subject regexes that mark a commit as a
// WIP-like save-point eligible for chain unwrap. They ADD to the
// hard-coded defaults (`--wip--`, `wip:`, `tmp`, `save`,
// `checkpoint`, `fixup!`, `squash!`) — empty list keeps just the
// defaults.
WIPPatterns []string `mapstructure:"wip_patterns" yaml:"wip_patterns"`
// WIPMaxChain caps how many recent commits the unwrap pass will
// consider. 0 falls back to 10. Stops a runaway chain on a branch
// that is entirely save-point commits.
WIPMaxChain int `mapstructure:"wip_max_chain" yaml:"wip_max_chain"`
// WIPEnabled is the global on/off switch for the chain unwrap
// pass. Defaults true. The CLI flag --no-wip-unwrap is OR-ed with
// `!WIPEnabled` per invocation, so users can disable entirely via
// config or one-shot via flag.
WIPEnabled bool `mapstructure:"wip_enabled" yaml:"wip_enabled"`
// Concurrency caps how many commit groups are composed in parallel.
// Compose is the dominant latency in `gk commit` — each group is an
// independent LLM round-trip — so groups fan out concurrently. 0
// falls back to 4: enough to run a typical multi-group commit fully
// in parallel while bounding burst pressure on provider rate limits
// (e.g. Groq's free tier) and the number of CLI-provider subprocesses
// (gemini/qwen/kiro) spawned at once. Lower it for strict quotas;
// raise it on a paid tier.
Concurrency int `mapstructure:"concurrency" yaml:"concurrency"`
// WarmCache, when true AND the provider caches its system prompt
// (Anthropic), composes the first group synchronously to prime the
// prompt cache before the rest fan out. Default FALSE: measurement
// showed the warm-up serialises one extra round-trip (≈1.8× slower on
// a cache-less provider), and the offsetting cache saving is unproven
// for gk's small system prompt. Enable only after measuring a net win
// on your Anthropic setup.
WarmCache bool `mapstructure:"warm_cache" yaml:"warm_cache"`
}
AICommitConfig controls `gk commit`. Mode is the default execution mode ("interactive" | "force" | "dry-run"); CLI flags override it. DenyPaths is a list of glob patterns (filepath.Match syntax) applied to every WIP file before it leaves the process — matches are either dropped silently or abort the run, never forwarded to the provider. AllowRemote gates providers whose Locality() is "remote"; when false only local providers may run (the policy layer may enforce this too). Trailer and Audit are opt-in telemetry knobs, both default off.
type AIConfig ¶
type AIConfig struct {
Enabled bool `mapstructure:"enabled" yaml:"enabled"`
Provider string `mapstructure:"provider" yaml:"provider"`
Lang string `mapstructure:"lang" yaml:"lang"`
Assist AIAssistConfig `mapstructure:"assist" yaml:"assist"`
Commit AICommitConfig `mapstructure:"commit" yaml:"commit"`
Chat AIChatConfig `mapstructure:"chat" yaml:"chat"`
Anthropic AIAnthropicConfig `mapstructure:"anthropic" yaml:"anthropic"`
OpenAI AIOpenAIConfig `mapstructure:"openai" yaml:"openai"`
Nvidia AINvidiaConfig `mapstructure:"nvidia" yaml:"nvidia"`
Groq AIGroqConfig `mapstructure:"groq" yaml:"groq"`
// Providers registers custom, user-named providers keyed by the name
// used in `provider:`. A name absent from the built-in whitelist
// (anthropic/openai/nvidia/groq/gemini/qwen/kiro) is looked up here and
// built from the named entry's Format wire protocol. Lets a user point
// `provider: kiro-api` (or any name) at an OpenAI-compatible gateway
// without colliding with the real `openai` section.
Providers map[string]AICustomProviderConfig `mapstructure:"providers" yaml:"providers"`
// Extra captures any `ai.<name>` block that is not a known field above
// (",remain" collects the leftover keys). It lets a custom provider be
// written one level shallower — `ai.kiro-api:` instead of
// `ai.providers.kiro-api:` — which reads naturally next to the built-in
// `ai.openai:` / `ai.groq:` blocks. customProvider() consults Providers
// first, then Extra.
Extra map[string]AICustomProviderConfig `mapstructure:",remain" yaml:"-"`
}
AIConfig controls AI-powered subcommands (commit, pr, review, changelog). Enabled is the master switch; flipping it false (or exporting GK_AI_DISABLE=1 which viper maps to this field) disables every AI subcommand with a clear error. Provider is the default AI CLI to use when --provider is not passed; empty means auto-detect (gemini → qwen → kiro-cli). Lang is the default message/output language (BCP-47 short code). Commit holds `gk commit` settings; Chat holds `gk do/explain/ask` settings; future ai features add sibling structs.
func (AIConfig) CustomProvider ¶
func (a AIConfig) CustomProvider(name string) (AICustomProviderConfig, bool)
CustomProvider resolves a user-named provider by the name used in `provider:`. It prefers an explicit `ai.providers.<name>` entry, then falls back to a shallow `ai.<name>` block captured in Extra. The bool reports whether a registration was found.
type AICustomProviderConfig ¶
type AICustomProviderConfig struct {
Format string `mapstructure:"format" yaml:"format"`
Model string `mapstructure:"model" yaml:"model"`
Endpoint string `mapstructure:"endpoint" yaml:"endpoint"`
Timeout string `mapstructure:"timeout" yaml:"timeout"`
APIKey string `mapstructure:"api_key" yaml:"api_key"`
}
AICustomProviderConfig defines a user-named provider built on top of an existing HTTP wire protocol. Format selects which built-in adapter speaks the protocol ("openai" | "anthropic" | "nvidia" | "groq"); empty defaults to "openai". The remaining fields override that adapter's defaults exactly like the dedicated provider sections do. APIKey, when set, takes precedence over the underlying adapter's env var (see AIAnthropicConfig for the leak caveat).
type AIGroqConfig ¶
type AIGroqConfig struct {
Model string `mapstructure:"model" yaml:"model"`
Endpoint string `mapstructure:"endpoint" yaml:"endpoint"`
Timeout string `mapstructure:"timeout" yaml:"timeout"`
APIKey string `mapstructure:"api_key" yaml:"api_key"`
}
AIGroqConfig controls the Groq AI provider. APIKey, when set, takes precedence over the GROQ_API_KEY env var.
type AINvidiaConfig ¶
type AINvidiaConfig struct {
Model string `mapstructure:"model" yaml:"model"`
Endpoint string `mapstructure:"endpoint" yaml:"endpoint"`
Timeout string `mapstructure:"timeout" yaml:"timeout"`
APIKey string `mapstructure:"api_key" yaml:"api_key"`
}
AINvidiaConfig controls the NVIDIA AI provider. Model overrides the default LLM model identifier; Endpoint overrides the default Chat Completions API URL; Timeout is a Go duration string for HTTP requests. APIKey, when set, takes precedence over the NVIDIA_API_KEY env var.
type AIOpenAIConfig ¶
type AIOpenAIConfig struct {
Model string `mapstructure:"model" yaml:"model"`
Endpoint string `mapstructure:"endpoint" yaml:"endpoint"`
Timeout string `mapstructure:"timeout" yaml:"timeout"`
APIKey string `mapstructure:"api_key" yaml:"api_key"`
}
AIOpenAIConfig controls the OpenAI provider. APIKey, when set, takes precedence over the OPENAI_API_KEY env var (see AIAnthropicConfig for the leak caveat).
type BranchConfig ¶
type BranchConfig struct {
StaleDays int `mapstructure:"stale_days" yaml:"stale_days"`
Protected []string `mapstructure:"protected" yaml:"protected"`
Patterns []string `mapstructure:"patterns" yaml:"patterns"`
AllowDetached bool `mapstructure:"allow_detached" yaml:"allow_detached"`
}
BranchConfig controls branch management + naming policy.
type CloneConfig ¶
type CloneConfig struct {
DefaultProtocol string `mapstructure:"default_protocol" yaml:"default_protocol"`
DefaultHost string `mapstructure:"default_host" yaml:"default_host"`
Root string `mapstructure:"root" yaml:"root"`
Hosts map[string]HostAlias `mapstructure:"hosts" yaml:"hosts"`
PostActions []string `mapstructure:"post_actions" yaml:"post_actions"`
// HostsOrder lists the Hosts keys in the order the user wrote them
// (global config first, repo-local additions appended). Derived by
// Load from the YAML files — not a config key itself — because the
// decoded map cannot carry document order. Consumers presenting
// aliases to a human (e.g. gk init's account picker) should follow
// it; aliases missing from it (env/git-config layers) sort after.
HostsOrder []string `mapstructure:"-" yaml:"-"`
}
func (CloneConfig) ResolveURL ¶
ResolveURL turns one spec argument into a canonical git URL using this CloneConfig's defaults and host aliases. It backs both `gk clone` and `gk init --remote`. Dispatch order matters — URL schemes and SCP URLs must passthrough before alias or `owner/repo` expansion, otherwise a legitimate ssh URL like `git@host:owner/repo` would be double-parsed.
Supported spec forms:
https://host/owner/repo(.git) → passthrough
user@host:owner/repo(.git) → passthrough (SCP style)
alias:owner/repo → clone.hosts lookup
alias:repo → clone.hosts lookup + owner from the
alias's `owner` field (error when unset)
owner/repo → default_host + default_protocol
type CloneMeta ¶
type CloneMeta struct {
Host string // "github.com"
Owner string // "JINWOO-J"
Repo string // "playground"
}
CloneMeta carries the structured pieces of a resolved clone/remote URL. Host is always the canonical host (never an ssh_host alias), so path layouts like clone.root stay stable regardless of the SSH transport. The zero value means the spec was opaque (passthrough URL gk could not parse structurally).
func ParseRemoteMeta ¶
ParseRemoteMeta extracts host/owner/repo from a git remote URL in either scheme form (https://host/owner/repo) or SCP form (user@host:owner/repo), returning a zero CloneMeta when it does not resolve to owner/repo. Used by `gk push` to derive the `gh repo create` target from an existing origin URL.
type CommitConfig ¶
type CommitConfig struct {
Types []string `mapstructure:"types" yaml:"types"`
ScopeRequired bool `mapstructure:"scope_required" yaml:"scope_required"`
MaxSubjectLength int `mapstructure:"max_subject_length" yaml:"max_subject_length"`
}
CommitConfig controls commit-message linting rules.
type Config ¶
type Config struct {
BaseBranch string `mapstructure:"base_branch" yaml:"base_branch"`
Remote string `mapstructure:"remote" yaml:"remote"`
Log LogConfig `mapstructure:"log" yaml:"log"`
Status StatusConfig `mapstructure:"status" yaml:"status"`
UI UIConfig `mapstructure:"ui" yaml:"ui"`
Branch BranchConfig `mapstructure:"branch" yaml:"branch"`
Commit CommitConfig `mapstructure:"commit" yaml:"commit"`
Push PushConfig `mapstructure:"push" yaml:"push"`
Pull PullConfig `mapstructure:"pull" yaml:"pull"`
Forget ForgetConfig `mapstructure:"forget" yaml:"forget"`
Sync SyncConfig `mapstructure:"sync" yaml:"sync"`
Refresh RefreshConfig `mapstructure:"refresh" yaml:"refresh"`
Preflight PreflightConfig `mapstructure:"preflight" yaml:"preflight"`
Ship ShipConfig `mapstructure:"ship" yaml:"ship"`
Land LandConfig `mapstructure:"land" yaml:"land"`
Promote PromoteConfig `mapstructure:"promote" yaml:"promote"`
Clone CloneConfig `mapstructure:"clone" yaml:"clone"`
Init InitConfig `mapstructure:"init" yaml:"init"`
Resolve ResolveConfig `mapstructure:"resolve" yaml:"resolve"`
Worktree WorktreeConfig `mapstructure:"worktree" yaml:"worktree"`
Snapshot SnapshotConfig `mapstructure:"snapshot" yaml:"snapshot"`
AI AIConfig `mapstructure:"ai" yaml:"ai"`
Output OutputConfig `mapstructure:"output" yaml:"output"`
Fleet FleetConfig `mapstructure:"fleet" yaml:"fleet"`
GitHub GitHubConfig `mapstructure:"github" yaml:"github"`
Follow FollowConfig `mapstructure:"follow" yaml:"follow"`
}
Config holds the full resolved configuration for gk.
func Load ¶
Load resolves the full configuration using the layered priority:
- Defaults (lowest)
- $XDG_CONFIG_HOME/gk/config.yaml (default: ~/.config/gk/config.yaml)
- .gk.yaml in the git working-tree root
- git config --get-regexp '^gk\.' entries (merged as map)
- GK_* environment variables
- CLI flags via pflag.FlagSet (highest)
flags may be nil; in that case flag binding is skipped.
type FleetConfig ¶
type FleetConfig struct {
Repos []string `mapstructure:"repos" yaml:"repos,omitempty"`
Scan []string `mapstructure:"scan" yaml:"scan,omitempty"`
Depth int `mapstructure:"depth" yaml:"depth,omitempty"`
Exclude []string `mapstructure:"exclude" yaml:"exclude,omitempty"`
Interval int `mapstructure:"interval" yaml:"interval,omitempty"`
// FeedStats controls the change feed's +/- line counts and
// changed-function names (two `git diff -U0` runs per dirty worktree per
// poll). Default ON — the feed should read like `gk status --watch` out
// of the box; a pointer so an explicit `feed_stats: false` is
// distinguishable from "unset". Same as --feed-stats.
FeedStats *bool `mapstructure:"feed_stats" yaml:"feed_stats,omitempty"`
// Notify maps a fleet transition to a shell command (`sh -c`), run with
// GK_FLEET_* context env. Keys: conflict, paused, land_ready. Opt-in.
Notify map[string]string `mapstructure:"notify" yaml:"notify,omitempty"`
// Filter is the dashboard's initial view filter (all | active | busy |
// stuck). Unset keeps the mode default: active in multi-repo, all in
// single-repo. Same as --filter.
Filter string `mapstructure:"filter" yaml:"filter,omitempty"`
}
FleetConfig configures multi-repo `gk fleet`. Repos lists explicit repo paths; Scan lists directory roots searched (Depth levels deep) for git repos; Exclude are directory-name globs skipped while scanning; Interval is the TUI poll interval in seconds. With every field empty, fleet stays single-repo unless --repos/--scan/--all is passed — config alone never auto-switches a bare `gk fleet` run from inside a repo.
type FollowConfig ¶
type FollowConfig struct {
Engine string `mapstructure:"engine" yaml:"engine"`
}
FollowConfig tunes `gk follow`. Engine picks how changes are detected:
- "ref" — poll a remote branch via git ls-remote (the original engine; no token, works on any git host, always sees the true current tip)
- "events" — poll the GitHub repo Events API (PR/issue/review events; needs a token for private repos)
- "auto" — ref when no --on trigger is given; otherwise events when a token/public repo allows, else fall back to ref for merge triggers (`--engine` overrides this per run)
type ForgetConfig ¶
type ForgetConfig struct {
Engine string `mapstructure:"engine" yaml:"engine"`
}
ForgetConfig controls gk forget behaviour. Engine selects the history-rewrite implementation: "native" (default, gk's built-in fast-export→filter→fast-import pipeline, no external install) or "filter-repo" (delegate to git filter-repo). Equivalent to passing --engine on each invocation; the flag wins when both are set.
type GitHubConfig ¶
type GitHubConfig struct {
Owner string `mapstructure:"owner" yaml:"owner"`
Counts GitHubCountsConfig `mapstructure:"counts" yaml:"counts"`
}
GitHubConfig holds the default GitHub account/org the PR and issue listing commands (`gk pr`, `gk issue`) query when no --org flag is given. Owner is intentionally NOT omitempty: `gk config set github.owner` only accepts keys that appear as a leaf in the marshaled Defaults(), and an empty omitempty field would vanish from that schema.
type GitHubCountsConfig ¶
type GitHubCountsConfig struct {
TTLMinutes int `mapstructure:"ttl_minutes" yaml:"ttl_minutes"` // freshness window for "ttl"
Context string `mapstructure:"context" yaml:"context"` // `gk context` (bare)
Include string `mapstructure:"include" yaml:"include"` // `gk context --include=github`
Status string `mapstructure:"status" yaml:"status"` // `gk status --vis github`
WarmOnList bool `mapstructure:"warm_on_list" yaml:"warm_on_list"` // `gk pr`/`gk issue` refresh the cache
}
GitHubCountsConfig tunes the open PR/issue counts surfaced by `gk context` and `gk status --vis github`. All three display surfaces read/refresh a shared on-disk cache (.git/gk-github-cache); the per-surface policy decides whether that surface may hit the network.
Policy values (per surface):
- "off" — do not show this surface at all
- "cache" — show cached counts only; NEVER fetch (safe on hot paths)
- "ttl" — show cached; fetch when older than TTLMinutes
- "force" — always fetch (ignores the TTL)
Fields are NOT omitempty so every leaf stays settable via `gk config set` (same reasoning as GitHubConfig.Owner).
type HostAlias ¶
type HostAlias struct {
Host string `mapstructure:"host" yaml:"host"`
Protocol string `mapstructure:"protocol" yaml:"protocol"`
Owner string `mapstructure:"owner" yaml:"owner,omitempty"`
SSHHost string `mapstructure:"ssh_host" yaml:"ssh_host,omitempty"`
}
HostAlias names a custom clone shorthand like `gl:` or `work:`. Protocol is optional; when empty, CloneConfig.DefaultProtocol wins.
Owner turns the alias into an account profile: `alias:repo` (no slash) expands to `owner/repo`, and `gk init` lists the alias as a remote candidate. SSHHost swaps a `~/.ssh/config` Host alias (e.g. `github.com-work`, carrying the right key for a second account on the same host) into ssh URLs; https URLs and structured metadata keep the canonical Host. Both fields are optional — aliases without them behave exactly as before.
type InitConfig ¶
type InitConfig struct {
AIGitignore bool `mapstructure:"ai_gitignore" yaml:"ai_gitignore"`
}
InitConfig controls `gk init` scaffolding.
- AIGitignore: make the opt-in `--ai-gitignore` augmentation the default — after the plan is confirmed, the configured AI provider is asked for extra project-specific .gitignore patterns. Off by default because it sends project metadata to a (possibly remote) provider; an explicit `--ai-gitignore[=false]` flag still wins for one run.
type LandConfig ¶
type LandConfig struct {
Promote string `mapstructure:"promote" yaml:"promote"`
Autostash bool `mapstructure:"autostash" yaml:"autostash"`
}
LandConfig controls gk land. Promote turns the promote step on by default, as if every invocation passed the flag:
- "" (default): promote only when --promote is passed.
- "parent": bare --promote semantics — one hop to the branch's gk-parent, falling back to the configured base. YAML booleans are tolerated ("true"/"1" read as "parent", "false"/"0"/"none"/"off" as off) so `promote: true` does the intuitive thing.
- any branch name: same as --promote=<branch> — walk the parent chain hop by hop until that branch.
An explicit --promote flag always wins over config; --no-promote skips the step for one invocation.
Autostash (default false) makes the --to / promote merge step stash a dirty receiver worktree (the parent checkout someone left mid-edit) around the merge and pop it after, as if every invocation passed --autostash. An explicit --autostash / --autostash=false flag wins.
type LogConfig ¶
type LogConfig struct {
Format string `mapstructure:"format" yaml:"format"`
Graph bool `mapstructure:"graph" yaml:"graph"`
Limit int `mapstructure:"limit" yaml:"limit"`
Vis []string `mapstructure:"vis" yaml:"vis"`
}
LogConfig controls git log output format. Vis is the default set of visualization layers applied when the caller does not pass any viz flag; pass `--vis none` or a comma-list to override for a single invocation.
type OutputConfig ¶
type OutputConfig struct {
Easy bool `mapstructure:"easy" yaml:"easy"`
Lang string `mapstructure:"lang" yaml:"lang"`
Emoji bool `mapstructure:"emoji" yaml:"emoji"`
Hints string `mapstructure:"hints" yaml:"hints"`
}
OutputConfig controls Easy Mode output behaviour.
- Easy: master switch for Easy Mode (default false).
- Lang: message catalogue language, BCP-47 short code (default "ko").
- Emoji: prepend emoji to status lines (default true).
- Hints: hint verbosity level — "verbose", "minimal", or "off" (default "verbose").
type PreflightConfig ¶
type PreflightConfig struct {
Steps []PreflightStep `mapstructure:"steps" yaml:"steps"`
}
PreflightConfig controls the sequence of checks gk preflight runs.
type PreflightStep ¶
type PreflightStep struct {
Name string `mapstructure:"name" yaml:"name"`
Command string `mapstructure:"command" yaml:"command"`
ContinueOnFailure bool `mapstructure:"continue_on_failure" yaml:"continue_on_failure"`
}
PreflightStep is one check in the preflight sequence. Command can be a shell command (e.g., "make test") or a built-in alias: "commit-lint", "branch-check", "no-conflict".
type PrivacyConfig ¶
type PrivacyConfig struct {
MaxSecrets int `mapstructure:"max_secrets" yaml:"max_secrets"`
}
PrivacyConfig tunes the Privacy Gate that runs before remote AI providers see any payload. MaxSecrets is the abort threshold for the builtin regex-based secret count (default 10); set to a negative value to disable the abort while still redacting matches.
type PromoteConfig ¶
type PromoteConfig struct {
Autostash bool `mapstructure:"autostash" yaml:"autostash"`
}
PromoteConfig controls gk promote. Autostash (default false) makes every hop's merge stash a dirty receiver worktree around the merge and pop it after, as if --autostash were passed — for worktree flows where the parent checkout is routinely dirty. An explicit --autostash / --autostash=false flag overrides it for one run.
type PullConfig ¶
type PullConfig struct {
Strategy string `mapstructure:"strategy" yaml:"strategy"`
WithBase bool `mapstructure:"with_base" yaml:"with_base"`
Autostash bool `mapstructure:"autostash" yaml:"autostash"`
}
PullConfig controls gk pull behaviour. Strategy accepts: "rebase" (default), "merge", "ff-only", "auto". "auto" reads git config pull.rebase; if unset, falls back to "rebase". WithBase makes every pull additionally fast-forward the local base branch (e.g. main) from its remote — no checkout involved, strictly FF-only, ambiguous states are skipped with a note. Equivalent to passing --with-base on each invocation. Autostash (default true) lets a dirty working tree pull without an interactive gate: tracked changes are stashed before integration and popped after, so the common no-conflict case flows through with only a status line. The pop is the one place a real conflict with local edits surfaces — and the one place pull still stops. Set false (or pass --no-autostash) to restore the old behaviour: prompt on a TTY, refuse on a non-TTY. GK_PULL_AUTOSTASH overrides per environment.
type PushConfig ¶
type PushConfig struct {
Protected []string `mapstructure:"protected" yaml:"protected"`
SecretPatterns []string `mapstructure:"secret_patterns" yaml:"secret_patterns"`
AllowForce bool `mapstructure:"allow_force" yaml:"allow_force"`
// ScanContext shows ±1 surrounding source line (masked) around each
// secret-scan hit on push/ship, so a reviewer can judge a false positive
// in place. The global --verbose / `gk push -v` flag turns it on for a
// single invocation; this makes it the default.
ScanContext bool `mapstructure:"scan_context" yaml:"scan_context"`
}
PushConfig controls gk push safety rails.
type RefreshConfig ¶
type RefreshConfig struct {
Tracked []string `mapstructure:"tracked" yaml:"tracked"`
}
RefreshConfig controls `gk refresh`. Tracked lists the long-lived branches that `gk refresh` fast-forwards to their remote counterparts (origin/<branch>). It never rebases or merges across branches, so it is safe on shared branches: a diverged branch is skipped, not rewritten.
Empty (the default) means gk resolves the list dynamically per repo: the canonical main branch (origin/HEAD → main → master) plus develop/dev when they exist locally. Set an explicit list to override — e.g. to add a long-lived release branch, or to refresh master only.
type ResolveConfig ¶
type ResolveConfig struct {
Rerere bool `mapstructure:"rerere" yaml:"rerere"`
Verify []string `mapstructure:"verify" yaml:"verify,omitempty"`
UnionFiles []string `mapstructure:"union_files" yaml:"union_files,omitempty"`
// MinConfidence gates AI hunk resolutions: below it, the hunk keeps its
// markers and the answer ships as a proposal in the paused report.
// 0 (default) disables the gate. Honored from the GLOBAL config only —
// a repo-local .gk.yaml lowering it would widen auto-apply.
MinConfidence float64 `mapstructure:"min_confidence" yaml:"min_confidence,omitempty"`
}
CloneConfig controls `gk clone` shorthand expansion and post-clone hooks.
- DefaultProtocol: "ssh" (default) or "https". Determines the URL form used when the caller passes a bare `owner/repo`.
- DefaultHost: the hostname inserted when only `owner/repo` is given ("github.com" by default).
- Root: optional filesystem root for Go-style layout. When non-empty, `gk clone owner/repo` places the checkout at `<root>/<host>/<owner>/<repo>` unless an explicit target is passed. Empty means "let git pick a directory in cwd" (the standard default).
- Hosts: alias table for multi-host / multi-account users. `gk clone gl:group/repo` looks up `gl` here, using the per-alias host + protocol (falling back to DefaultProtocol when the alias omits it). An alias with `owner` set doubles as an account profile: `gk clone gl:repo` completes the owner, and `gk init` offers the alias when wiring the origin remote. Layers merge field-by-field (viper deep merge), so a repo-local `.gk.yaml` that sets only `protocol` on an alias inherits the global entry's host/owner.
- PostActions: subcommands to run inside the freshly-cloned checkout. Supported values: "hooks-install" (invokes `gk hooks install --all`) and "doctor" (invokes `gk doctor`). Default empty — opt-in only.
ResolveConfig controls `gk resolve` behavior.
- Rerere: enable git's rerere (reuse recorded resolutions) in the repo the first time gk resolve runs, and apply any recorded resolutions before classifying — repeated conflicts (long-lived branch rebases) resolve at zero AI cost. Default true; set false to leave git config untouched.
- Verify: shell commands run from the repo root AFTER conflicts are resolved but BEFORE they are staged/continued. Any failure rolls the files back to their conflicted state (`git checkout -m`) and reports — auto-resolution becomes a reversible attempt instead of a gamble. A conflict-marker scan always runs regardless of this list.
- UnionFiles: basenames resolved by keeping both sides in the mechanical tier (default CHANGELOG.md, go.sum).
type ShipConfig ¶
type ShipConfig struct {
Watch []PreflightStep `mapstructure:"watch" yaml:"watch"`
Verify []PreflightStep `mapstructure:"verify" yaml:"verify"`
VersionFiles []VersionFile `mapstructure:"version_files" yaml:"version_files"`
Prepare []PreflightStep `mapstructure:"prepare" yaml:"prepare"`
Artifact []PreflightStep `mapstructure:"artifact" yaml:"artifact"`
PostRelease []PreflightStep `mapstructure:"post_release" yaml:"post_release"`
AutoConfirm bool `mapstructure:"auto_confirm" yaml:"auto_confirm"`
Wait bool `mapstructure:"wait" yaml:"wait"`
}
ShipConfig extends gk ship beyond the shared preflight steps with post-tag hooks and an explicit version-file list, so the whole release pipeline (checks → version → changelog → tag → push → CI watch → post-release verification) runs from one command on any project.
- Watch: commands run after the release tag is pushed — typically a blocking CI watcher (e.g. `gh run watch ...`). A failure aborts ship with a rerun hint; the tag is already published at that point.
- Verify: post-release checks run after every Watch step succeeds (artifact reachable on the CDN, tap/registry bumped, ...).
- VersionFiles: explicit version-file list (paths relative to the repo root). When set it replaces the VERSION/package.json/ marketplace.json auto-detection. Each entry is either a bare path string (the format is inferred from the filename) or a {path, pattern, key} object — see VersionFile.
- AutoConfirm: skip the final confirmation prompt by default, as if every run passed -y. An explicit --yes=false still forces the prompt for one invocation.
- Wait: run the post-tag Watch/Verify pipeline (default true). false returns right after the push — the release is published but untracked, and ship prints the skipped commands as a note. --wait / --wait=false overrides per invocation.
Watch and Verify reuse PreflightStep so `name:`/`command:`/ `continue_on_failure:` read the same in all three lists.
type SnapshotConfig ¶
type SnapshotConfig struct {
RetentionDays int `mapstructure:"retention_days" yaml:"retention_days"`
}
SnapshotConfig controls the refs/wip/* safety-net snapshots.
- RetentionDays: when > 0, every `gk snapshot` save also expires this branch's snapshot reflog entries older than that many days (best-effort and quiet, mirroring `gk snapshot prune --keep-days N`). 0 (the default) never auto-prunes — snapshots accumulate until a manual `gk snapshot prune`.
type StatusConfig ¶
type StatusConfig struct {
Vis []string `mapstructure:"vis" yaml:"vis"`
AutoFetch bool `mapstructure:"auto_fetch" yaml:"auto_fetch"`
// XYStyle controls how the two-letter porcelain code is rendered per
// entry. "labels" (default) → word labels ("new", "mod", "staged",
// "conflict"); "glyphs" → single-char markers (+ ~ ● ⚔ #); "raw"
// keeps the literal git code (`??`, `.M`, `UU`). Overridable per call
// via `--xy-style`.
XYStyle string `mapstructure:"xy_style" yaml:"xy_style"`
// Density controls how much information `gk status` packs into the
// terminal. "normal" (default) keeps the legacy compact output;
// "rich" splits the branch + working-tree + next-action sections
// into titled blocks, enables the divergence diagram and 7-day
// activity sparkline, and removes the 24h gate on the "last commit"
// tag so the SHA + age are always shown. The CLI flag `-v` /
// `--verbose` (count ≥ 1) escalates to rich for a single invocation
// regardless of the config value.
Density string `mapstructure:"density" yaml:"density"`
// Layout selects how rich-mode sections are framed. "bar" (default)
// prefixes each title with a coloured ▎ bar; "rule" brackets the
// title with horizontal rules. Both replace the legacy box layout
// because the box's per-line padding misaligned with wide-character
// content (한글/이모지/coloured glyphs). Ignored when density is
// "normal".
Layout string `mapstructure:"layout" yaml:"layout"`
}
StatusConfig controls gk status defaults. Vis is the default set of visualization layers applied when the caller does not pass --vis. Pass --vis none on the CLI to turn them all off for a single invocation.
AutoFetch controls whether `gk status` fetches the current branch's upstream before reading porcelain output. Default false — status does no network activity unless the caller passes `--fetch` / `-f`. Set `auto_fetch: true` in config to opt-in globally (equivalent to passing the flag on every invocation); the fetch itself remains strictly bounded (timeout, no prompts, no submodule recursion, no LFS side effects) and silent on failure, falling back to the local cached view.
type SyncConfig ¶
type SyncConfig struct {
Strategy string `mapstructure:"strategy" yaml:"strategy"`
}
SyncConfig controls gk sync behaviour. Strategy is the integration mode used when the current branch has diverged from its base: "rebase" (default), "merge", or "ff-only" (refuse divergence). Kept separate from PullConfig.Strategy because sync (catch-up to base) and pull (sync with @{u}) have different intents — a user may want to merge-pull from collaborators on the same branch but rebase-sync onto main, or vice versa.
type UIConfig ¶
type UIConfig struct {
Color string `mapstructure:"color" yaml:"color"`
Prefer string `mapstructure:"prefer" yaml:"prefer"`
}
UIConfig controls terminal UI behaviour.
type VersionFile ¶
type VersionFile struct {
Path string `mapstructure:"path" yaml:"path"`
Pattern string `mapstructure:"pattern" yaml:"pattern,omitempty"`
Key string `mapstructure:"key" yaml:"key,omitempty"`
}
VersionFile is one entry of ship.version_files. It decodes from either a bare string (`- pyproject.toml`, handled by the stringToVersionFile decode hook in load.go) or a mapping (`- {path: ..., pattern: ...}`):
- Path: the file to rewrite, relative to the repo root. Required.
- Pattern: a literal template containing exactly one `{version}` placeholder (e.g. `__version__ = "{version}"`). ship replaces the text that sits where `{version}` does. Works on any text file — the escape hatch for formats with no native handler.
- Key: a dotted key path into a YAML file (e.g. `version` or `tool.poetry.version`). ship rewrites that scalar while preserving comments and surrounding structure.
Pattern and Key are mutually exclusive; when both are empty ship infers the format from the filename (VERSION, package.json, pyproject.toml, Cargo.toml, *.py __version__, pubspec.yaml / Chart.yaml).
type WorktreeConfig ¶
type WorktreeConfig struct {
Base string `mapstructure:"base" yaml:"base"`
Project string `mapstructure:"project" yaml:"project"`
Init *WorktreeInit `mapstructure:"init" yaml:"init,omitempty"`
}
WorktreeConfig controls how `gk worktree add <name>` maps a relative name argument into a real filesystem path. Default layout:
<Base>/<Project>/<name>
Base defaults to `~/.gk/worktree` so worktrees live outside the main checkout (safer for IDEs and backup sweeps). Project defaults to the basename of the repo's toplevel directory — override when two clones share the same basename (e.g. `work/gk` and `personal/gk`). An absolute path passed to `gk worktree add` always wins and is used verbatim; the managed layout only applies to bare/relative names.
type WorktreeInit ¶
type WorktreeInit struct {
Link []string `mapstructure:"link" yaml:"link,omitempty"`
Copy []string `mapstructure:"copy" yaml:"copy,omitempty"`
Run []string `mapstructure:"run" yaml:"run,omitempty"`
}
WorktreeInit declares how a freshly created worktree is bootstrapped so gitignored, per-checkout state (secrets, dependency trees, virtualenvs) is reconstituted rather than left empty. The three keys map to three fundamentally different resource types — conflating them is the usual mistake:
- Link: symlink a file/dir from the main worktree. Right for secrets and shared config (.env) you want managed in ONE place and kept in sync across every worktree. NOT for virtualenvs (absolute paths baked into pyvenv.cfg/shebangs break) or node_modules (branches may pin different lockfiles → cross-contamination).
- Copy: copy a file/dir from the main worktree. Use when each worktree needs an independently editable copy (e.g. a .env whose port differs per checkout). Same anti-patterns as Link for venv/node_modules.
- Run: shell commands executed IN the new worktree, in order. The correct home for `npm ci`, `uv sync`, `python -m venv` — anything that must be regenerated against this checkout's lockfile for true isolation.
All three are idempotent on re-run via `gk worktree init`: existing correct symlinks are left alone, present copy targets are skipped, and install commands (npm ci / uv sync) are safe to repeat.