cli

package
v0.143.0 Latest Latest
Warning

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

Go to latest
Published: Sep 15, 2026 License: MIT Imports: 71 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package cli wires all gk subcommands into a cobra tree.

Each subcommand lives in its own file (pull.go, log.go, status.go, ...) and registers itself with the root command via an init() function that appends to rootCmd.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AgentOut

func AgentOut() bool

func CandidateKey

func CandidateKey(c branchclean.CleanCandidate) string

CandidateKey returns a stable key that distinguishes a local branch from a remote-only branch with the same name (e.g. local "feat-x" vs origin's "feat-x"). Callers route deletion based on the prefix.

func CurrentVersion

func CurrentVersion() string

CurrentVersion returns the raw build-time version string set by SetVersionInfo (e.g. "v0.29.1"). Returns "dev" when running an unreleased build. Stripped of the formatted "(commit ..., built ...)" suffix so callers can pass it to semver comparisons directly.

func Dbg

func Dbg(format string, args ...interface{})

Dbg emits a diagnostic line to stderr (or SetDebugWriter target) when --debug / -d / GK_DEBUG=1 is active. No-op otherwise — so it is safe to pepper hot paths with Dbg calls without any runtime cost in the common case.

Each line is prefixed with an elapsed-since-first-call duration so a user can eyeball "which stage spent the time", and the entire line (prefix + body) is rendered in dim gray so debug output visually separates from the command's real output even when the two are interleaved on stderr:

[debug +0.003s] ai commit: provider=gemini
[debug +0.042s] ai commit: classify ok — 3 groups
[debug +2.815s] ai commit: compose(1/3) attempt=1 type=feat scope=api

func Debug

func Debug() bool

func DiffFileToPickerItem

func DiffFileToPickerItem(f diff.DiffFile, index int) ui.PickerItem

DiffFileToPickerItem converts a DiffFile into a ui.PickerItem suitable for TablePicker display. The item's Cells contain the file status, added-line count, and deleted-line count. Key holds the file index as a string so the caller can map back to the original DiffFile.

Exported for property-based testing (Property 8).

func DryRun

func DryRun() bool

func EasyEngine

func EasyEngine() *easy.Engine

EasyEngine returns the package-level Easy Mode engine, building it on first access. The construction path mirrors what PersistentPreRunE used to do eagerly: load layered config, fall back to defaults on error, then wire the debug fn when --debug is on. Tests that invoke command RunE directly (bypassing the cobra Execute path) still get a usable engine the moment they call EasyEngine().

func EasyFlag

func EasyFlag() bool

func Execute

func Execute() error

Execute runs the root command. Returns the error so main.go can set exit code.

func ExitCodeFor

func ExitCodeFor(err error) (code int, rendered bool)

ExitCodeFor maps an Execute() error to the process exit code and whether the command already rendered its output. rendered==true means main.go must NOT print an error envelope/prose on top (the paused result is already on stdout). A nil error is exit 0; a plain error is exit 1.

func FoldSummary

func FoldSummary(h diff.Hunk) string

FoldSummary returns the folded summary line for a Hunk. The format is "[+N lines]" where N is len(h.Lines).

Exported for property-based testing (Property 7).

func FormatCandidateLabel

func FormatCandidateLabel(c branchclean.CleanCandidate) string

FormatCandidateLabel은 TUI에 표시할 브랜치 라벨을 생성한다. 형식: "[local] branch-name (created 5m ago, commit 5d ago) [merged] completed: 로그인 기능 구현" remote-only 브랜치는 [remote: origin] prefix가 붙는다.

func FormatError

func FormatError(err error) string

FormatError returns the user-facing representation of an error raised by cli.Execute. Renders as:

gk: <error message>          (red)
  hint: <hint>                (magenta label, faint body)

When Easy Mode is active and --json is not set, the error is formatted with emoji and beginner-friendly language via the EasyFormatter.

func FormatErrorJSON

func FormatErrorJSON(err error) string

FormatErrorJSON renders err as the failure envelope. main.go uses it in agent mode in place of FormatError; the exit code is unchanged — the envelope is diagnosis, not control flow.

func FormatHunkDiff

func FormatHunkDiff(hunk resolve.ConflictHunk) string

FormatHunkDiff renders a conflict hunk in classic - / + diff form. Retained as the legacy formatter for callers that don't have line- number metadata; the resolve TUI uses the richer formatHunkRich (with line numbers, side labels, and optional context lines).

func HintFrom

func HintFrom(err error) string

HintFrom walks the error chain and returns the first hint found, or "".

func JSONOut

func JSONOut() bool

func NoColorFlag

func NoColorFlag() bool

func NoEasyFlag

func NoEasyFlag() bool

func ParseCandidateKey

func ParseCandidateKey(key string) (name string, isRemote bool, remote string)

ParseCandidateKey splits a CandidateKey produced by CandidateKey back into (name, isRemote, remoteName).

func RemediesFrom

func RemediesFrom(err error) []errRemedy

RemediesFrom extracts machine-executable remedies from the error chain. Explicit WithRemedy entries win; otherwise a "try: <command>" hint (the dominant hintCommand convention, ~16 call sites) is promoted into a single safe remedy so existing hints feed the agent contract without rewriting their call sites.

func RepoFlag

func RepoFlag() string

Persistent flag accessors for subcommand files.

func Root

func Root() *cobra.Command

Root returns the cobra root command. Used by subcommands in other files via init() to attach themselves: cli.Root().AddCommand(...)

func RunCleanTUI

func RunCleanTUI(allCandidates []branchclean.CleanCandidate, startWithRemote bool) ([]string, error)

RunCleanTUI presents a checkbox list of branch-clean candidates. Local-only candidates show by default; pressing 'i' toggles whether remote-only candidates are also listed. Returns the selected CandidateKeys — the caller must split them via ParseCandidateKey.

func RunInitTUI

func RunInitTUI(result *initx.AnalysisResult, plan *initx.InitPlan, remote *remoteTUIInput) (*initx.InitPlan, *remotePlan, bool, error)

RunInitTUI runs the interactive init flow: the remote account/name step (when `remote` asks for it), then the analysis summary and a single confirm covering files and remote alike. On cancel, every plan entry — the remote step included — is set to Skip; cancellation is a harmless no-op, never an error.

func RunResolveTUI

func RunResolveTUI(
	files []resolve.ConflictFile,
	aiResolutions map[string][]resolve.HunkResolution,
) ([]resolve.FileResolution, error)

RunResolveTUI walks each conflict hunk and asks the user to pick a resolution. Long hunks scroll inside ui.ScrollSelectTUI's viewport, so the diff stays visible while the user decides.

func SetDebugWriter

func SetDebugWriter(w io.Writer) io.Writer

SetDebugWriter overrides the destination for Dbg output. Returns the previous writer so callers can restore on cleanup. Safe to call from tests; not intended for runtime use.

func SetVersionInfo

func SetVersionInfo(v, c, d, b, w string)

SetVersionInfo wires build-time version metadata for `gk --version` output and prepends the version line to the root help page. branch + worktree are surfaced when known so users can tell which checkout produced the binary they're running — invaluable when juggling multiple gk worktrees.

The Long header is rendered under the canonical `gk` here; Execute rewrites it to the real invocation name (e.g. `git-kit`) once argv[0] is known.

func Verbose

func Verbose() bool

func WithBlocked

func WithBlocked(err error, code, hint string, remedies ...errRemedy) error

WithBlocked decorates err as a blocked precondition: the command made no change, but a precondition (e.g. a diverged base that cannot fast-forward) must be cleared before it can proceed. The agent envelope renders it as state:"blocked" (ok:false, non-zero exit) with the given code and remedies, so an agent runs the remedy instead of treating it as a hard failure. code is the stable error.code; hint and remedies carry the fix. Nil err → nil.

func WithHint

func WithHint(err error, hint string) error

WithHint decorates err with a one-line remediation hint. Passing a nil err returns nil. An empty hint is ignored (err is returned unchanged).

func WithRemedy

func WithRemedy(err error, hint string, remedies ...errRemedy) error

WithRemedy decorates err with a hint plus explicit machine-executable remedies. Call sites that know the exact fix command(s) use this instead of WithHint so agents get structure, not prose to parse.

Types

type BaseResolution

type BaseResolution struct {
	Resolved string
	Source   BaseSource

	ConfigEnv    string
	ConfigGit    string
	ConfigMerged string
	OriginHEAD   string
	OriginLive   string
	FallbackUsed string
	Remote       string
}

BaseResolution captures the full picture of how the base branch was chosen. Renderers consume the fields they need; Mismatch() and OriginHEADUnset() are the canonical signals that the user's config disagrees with the remote's view of "default branch".

func (BaseResolution) Mismatch

func (r BaseResolution) Mismatch() bool

Mismatch reports whether an explicitly configured base disagrees with the cached origin/HEAD — the canonical "did the remote default change out from under me?" signal.

func (BaseResolution) OriginHEADUnset

func (r BaseResolution) OriginHEADUnset() bool

OriginHEADUnset reports whether the remote has no cached HEAD symbolic-ref. The remediation is the same `git remote set-head -a` as for Mismatch, but the rendered hint differs.

type BaseSource

type BaseSource string

BaseSource identifies the layer that supplied the resolved base branch. It is rendered verbatim as a faint suffix on the "from <base>" line and in the --explain-base block, so the constants double as user-facing labels.

const (
	BaseSourceUnresolved BaseSource = ""
	BaseSourceConfig     BaseSource = "config"
	BaseSourceConfigEnv  BaseSource = "GK_BASE_BRANCH"
	BaseSourceConfigGit  BaseSource = "git config"
	BaseSourceOriginHEAD BaseSource = "origin/HEAD"
	BaseSourceFallback   BaseSource = "fallback"
)

func (BaseSource) DetailLabel

func (s BaseSource) DetailLabel() string

DetailLabel adds the technical layer name to the human-friendly label, e.g. "configured (git config)". Used by --explain-base and -v where the underlying source matters for debugging.

func (BaseSource) DisplayLabel

func (s BaseSource) DisplayLabel() string

DisplayLabel returns the human-friendly category shown on the "from <base> <label>" line. Internal source constants stay verbose for diagnostics, but the headline status output collapses them into three buckets: default / configured / guessed.

type ConflictError

type ConflictError struct {
	Code    int
	Stashed bool
	Dir     string
}

ConflictError is returned by runPullCore when a rebase conflict is detected. The caller (runPull) should exit with Code instead of printing an error. Dir, when set, names the worktree the operation paused in (merge --into runs in the receiver's worktree) so the conflict contract reads files from where the conflict actually lives, not the invoking checkout.

func (*ConflictError) Error

func (e *ConflictError) Error() string

type DivergedError

type DivergedError struct {
	Code   int
	Branch string
}

DivergedError is returned when the legacy --upstream-only path detects a branch that cannot be fast-forwarded because it has local commits not present upstream. The caller should exit with Code.

func (*DivergedError) Error

func (e *DivergedError) Error() string

type ExitError

type ExitError struct {
	Code int
	// contains filtered or unexported fields
}

ExitError requests a specific process exit code without main.go printing an extra error message — the command has already rendered its result (e.g. a paused-state envelope). It is the exit-code channel, deliberately independent of the agent/human output mode: batch/land run their child commands in human mode (GK_AGENT stripped), so the pause signal cannot ride on the JSON envelope — it must be the process exit code.

func (*ExitError) Error

func (e *ExitError) Error() string

func (*ExitError) ExitCode

func (e *ExitError) ExitCode() int

ExitCode lets callers (and exec.ExitError-style probes) read the code.

func (*ExitError) Unwrap

func (e *ExitError) Unwrap() error

type LogEntry

type LogEntry struct {
	SHA      string `json:"sha"`
	ShortSHA string `json:"short_sha"`
	Author   string `json:"author"`
	Email    string `json:"email"`
	Date     string `json:"date"`
	Subject  string `json:"subject"`
	Body     string `json:"body,omitempty"`
}

LogEntry represents a single commit in JSON output mode.

type TrackingMismatch

type TrackingMismatch struct {
	Branch       string
	RemoteBranch string
	Remote       string
}

TrackingMismatch describes a current branch whose upstream refspec (branch.<name>.merge = refs/heads/<other>) targets a differently named remote branch. Surfaced as a status footer because plain `git push` would silently push to <other>, not <branch>.

func (TrackingMismatch) IsSet

func (t TrackingMismatch) IsSet() bool

IsSet reports whether the struct describes an actual mismatch. detectTrackingMismatch returns a zero value for "no signal", so a nil-safe predicate keeps the call sites readable.

type Workflow

type Workflow struct {
	Name        string
	DisplayName string
	Description string
	Steps       []WorkflowStep
}

Workflow는 gk guide에서 제공하는 워크플로를 나타낸다.

type WorkflowStep

type WorkflowStep struct {
	Title       string
	Description string
	Command     string // 제안할 gk 명령어
}

WorkflowStep은 워크플로의 개별 단계이다.

type WorktreeEntry

type WorktreeEntry struct {
	Path     string `json:"path"`
	Head     string `json:"head"`
	Branch   string `json:"branch,omitempty"`
	Detached bool   `json:"detached"`
	Bare     bool   `json:"bare"`
	Locked   bool   `json:"locked"`
	Prunable bool   `json:"prunable"`
}

WorktreeEntry represents a single row in `gk worktree list --json`.

Source Files

Jump to

Keyboard shortcuts

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