resolve

package
v0.151.4 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2026 License: MIT Imports: 12 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

Index

Constants

This section is empty.

Variables

View Source
var DefaultUnionFiles = []string{"CHANGELOG.md", "go.sum"}

DefaultUnionFiles are basenames whose conflicts are line-set additions from both sides: keeping both is the correct merge. CHANGELOG entries are append-only prose; go.sum is a hash database where extra entries are harmless and missing ones fail loudly at build time.

Functions

func ApplyResolutions

func ApplyResolutions(cf ConflictFile, resolutions []HunkResolution) ([]byte, error)

ApplyResolutions는 ConflictFile에 해결 결과를 적용하여 conflict marker가 제거된 최종 파일 내용을 반환한다.

func BackupOriginal

func BackupOriginal(writeFn func(string, []byte, os.FileMode) error, path string, data []byte) error

BackupOriginal은 원본 충돌 파일의 .orig 백업을 생성한다.

func CheckStuck

func CheckStuck(state *gitstate.State) error

CheckStuck returns a *StuckError when state is a paused rebase with no merge conflicts to resolve. It returns nil otherwise (no rebase, or rebase progressing normally). Callers are expected to have already confirmed there are zero unmerged paths.

func FormatStuckGuidance

func FormatStuckGuidance(stuck gitstate.RebaseStuck) string

FormatStuckGuidance returns a human-readable message explaining why a rebase is paused with no merge conflicts and how to resume it.

The message has a stable prefix that callers and tests can match against:

rebase is in progress but no conflicted files found.

`cli.FormatError` prepends "gk:" when this string is returned as an error, producing the final user-facing form. Only RebaseStuckEmptyCommit / Edit / Exec / Unknown are formatted. For RebaseStuckNone the function returns an empty string — callers should not invoke it in that case.

func GitAdd

func GitAdd(ctx context.Context, runner git.Runner, path string) error

GitAdd는 해결된 파일을 git staging area에 추가한다.

func Print

func Print(cf ConflictFile) []byte

Print는 ConflictFile을 conflict marker 형식의 바이트 슬라이스로 변환한다. 비충돌 라인(Context)을 그대로 보존한다.

func WriteResolved

func WriteResolved(writeFn func(string, []byte, os.FileMode) error, path string, data []byte) error

WriteResolved는 해결된 파일 내용을 디스크에 쓴다.

Types

type ConflictFile

type ConflictFile struct {
	Path     string
	Segments []Segment // 충돌/비충돌 영역의 순서 보존 목록
}

ConflictFile은 하나의 충돌 파일이다.

func Parse

func Parse(path string, content []byte) (ConflictFile, error)

Parse는 충돌 파일의 내용을 ConflictFile로 파싱한다. conflict marker가 없으면 빈 Hunk 슬라이스를 가진 ConflictFile을 반환한다. 유효하지 않은 marker (열린 마커에 닫는 마커 없음)는 에러를 반환한다. diff3 형식의 ||||||| base marker를 지원한다.

type ConflictHunk

type ConflictHunk struct {
	Ours        []string // <<<<<<< 와 ======= 사이 라인
	Theirs      []string // ======= 와 >>>>>>> 사이 라인
	Base        []string // ||||||| 와 ======= 사이 라인 (diff3, 없으면 nil)
	OursLabel   string   // <<<<<<< 뒤의 라벨 (e.g. "HEAD")
	TheirsLabel string   // >>>>>>> 뒤의 라벨 (e.g. "feature-branch")
	BaseLabel   string   // ||||||| 뒤의 라벨 (diff3, 없으면 "")
}

ConflictHunk는 하나의 충돌 영역이다.

type FileResolution

type FileResolution struct {
	Path        string
	Resolutions []HunkResolution // ConflictFile.Segments 내 Hunk 순서와 1:1 대응
}

FileResolution은 하나의 파일에 대한 전체 해결 결과이다.

type HunkProposal

type HunkProposal struct {
	File       string   `json:"file"`
	Hunk       int      `json:"hunk"` // 1-based conflict-hunk index within the file
	Strategy   string   `json:"strategy"`
	Confidence float64  `json:"confidence"`
	Rationale  string   `json:"rationale,omitempty"`
	Resolved   []string `json:"resolved"`
}

HunkProposal is an AI resolution that was NOT applied — its confidence sat below resolve.min_confidence — carried in the paused report so an agent can review and act without another "resolve it for me" round-trip.

type HunkResolution

type HunkResolution struct {
	Strategy      Strategy
	ResolvedLines []string // 해결된 코드 라인
	Rationale     string   // AI 선택 근거 (최대 120자)
	// Confidence는 AI가 보고한 확신도(0.0~1.0). 0 = 미보고.
	Confidence float64
}

HunkResolution은 하나의 충돌 영역에 대한 해결 결과이다.

type ResolveOptions

type ResolveOptions struct {
	DryRun   bool
	NoAI     bool
	NoBackup bool
	Strategy Strategy // 빈 문자열이면 TUI/interactive 모드
	Files    []string // 빈 슬라이스면 모든 충돌 파일
	Lang     string
	// UnionFiles overrides the basenames resolved by union merge in the
	// mechanical tier (nil = DefaultUnionFiles).
	UnionFiles []string
	// MinConfidence gates AI resolutions per hunk: below it, the hunk keeps
	// its conflict markers and the AI's answer ships as a proposal instead.
	// 0 disables the gate (an unreported confidence then passes through);
	// with a positive gate, unreported counts as below.
	MinConfidence float64
	// DeferStage: write resolved contents but do NOT `git add` them —
	// the caller stages after its verification gate passes, and can restore
	// the conflict (`git checkout -m`) on failure because the unmerged
	// index stages are still intact.
	DeferStage bool
}

ResolveOptions는 Resolver의 실행 옵션이다.

type ResolveResult

type ResolveResult struct {
	Resolved []string         // 해결 완료된 파일 경로
	Failed   map[string]error // 실패한 파일과 에러
	Skipped  []string         // 건너뛴 파일 (파싱 에러 등)
	Total    int              // 전체 충돌 파일 수
	AIUsed   bool
	AIModel  string
	// Mechanical lists the Resolved subset handled by the deterministic
	// tier (no AI involved).
	Mechanical []string
	// Remaining lists conflicts strategy "safe" deliberately left alone —
	// they need AI or a human, and are still marked/unmerged.
	Remaining []string
	// PendingStage lists resolved paths gk WROTE but did not stage
	// (DeferStage) — the caller stages them after verification, and may
	// restore their conflict with `git checkout -m` on failure.
	PendingStage []string
	// PendingAccept lists markerless files whose existing (user-authored)
	// content was accepted — stage-deferred like PendingStage, but NEVER
	// rolled back: gk did not write them, so restoring markers would
	// destroy the user's manual resolution.
	PendingAccept []string
	// PendingDelete lists delete/modify resolutions whose worktree file was
	// removed but whose index deletion is deferred until the verification
	// gate passes — the intact stages make `git checkout -m` restoration
	// possible on failure.
	PendingDelete []string
	// PendingPartial lists partially resolved files gk WROTE (some hunks
	// fixed, the rest keeping markers). Never staged; on gate failure they
	// are restored with checkout -m like PendingStage.
	PendingPartial []string
	// Proposals carries the AI resolutions the confidence gate did NOT
	// apply — their hunks stay conflicted (partially resolved files land in
	// Remaining). An agent reads these from the paused envelope and either
	// applies them by hand or re-runs after review.
	Proposals []HunkProposal
}

ResolveResult는 해결 실행 결과이다.

type Resolver

type Resolver struct {
	Runner   git.Runner
	Client   *git.Client
	Provider provider.Provider // nil이면 AI 비활성
	Stderr   io.Writer
	Stdout   io.Writer
	// Root는 worktree 최상위 디렉토리. git이 주는 충돌 경로는 repo-root
	// 상대 경로이므로, 여기서 join해야 --repo로 밖에서 실행하거나 repo
	// 하위 디렉토리에서 실행해도 파일 IO가 맞는다. 빈 문자열이면 cwd 기준
	// (기존 동작).
	Root string
	// ReadFile은 파일 읽기 함수. 테스트에서 override 가능. nil이면 os.ReadFile.
	ReadFile func(path string) ([]byte, error)
	// WriteFile은 파일 쓰기 함수. 테스트에서 override 가능. nil이면 os.WriteFile.
	WriteFile func(path string, data []byte, perm os.FileMode) error

	// RemoveFile은 워크트리 파일 삭제 함수. 테스트에서 override 가능.
	// nil이면 os.Remove.
	RemoveFile func(path string) error
	// contains filtered or unexported fields
}

Resolver는 충돌 해결의 전체 흐름을 orchestrate한다.

func (*Resolver) ApplyFileResolution

func (r *Resolver) ApplyFileResolution(
	ctx context.Context,
	cf ConflictFile,
	resolutions []HunkResolution,
	backup bool,
	dryRun bool,
) error

ApplyFileResolution은 하나의 파일에 해결을 적용한다. backup=true이면 .orig 파일을 생성한다.

func (*Resolver) CollectConflictedFiles

func (r *Resolver) CollectConflictedFiles(ctx context.Context) ([]string, error)

CollectConflictedFiles는 git status에서 unmerged 파일 경로를 수집한다.

func (*Resolver) ParseConflictFiles

func (r *Resolver) ParseConflictFiles(paths []string) ([]ConflictFile, []string, error)

ParseConflictFiles는 파일 목록을 파싱하여 ConflictFile 슬라이스를 반환한다. 파싱 실패한 파일은 건너뛰고 경고를 stderr에 출력한다.

func (*Resolver) ResolveWithAI

func (r *Resolver) ResolveWithAI(
	ctx context.Context,
	cf ConflictFile,
	opType string,
	lang string,
) ([]HunkResolution, error)

ResolveWithAI는 AI provider를 통해 충돌 해결 제안을 가져온다. 실패 시 nil을 반환한다 (graceful fallback).

func (*Resolver) Run

func (r *Resolver) Run(ctx context.Context, state *gitstate.State, opts ResolveOptions) (*ResolveResult, error)

Run은 옵션에 따라 충돌 해결을 실행한다.

type Segment

type Segment struct {
	Context []string      // 비충돌 라인 (Hunk가 nil일 때)
	Hunk    *ConflictHunk // 충돌 영역 (Context가 nil일 때)
}

Segment는 파일 내 하나의 영역이다. 충돌 영역이면 Hunk가 non-nil.

type Strategy

type Strategy string

Strategy는 충돌 해결 전략이다.

const (
	StrategyOurs   Strategy = "ours"
	StrategyTheirs Strategy = "theirs"
	StrategyMerged Strategy = "merged"
	// StrategyUnresolved marks a hunk deliberately left conflicted —
	// ApplyResolutions re-emits its original markers verbatim. Used by the
	// confidence gate for partial file resolution.
	StrategyUnresolved Strategy = "unresolved"
)
const StrategyMechanical Strategy = "mechanical"

StrategyMechanical marks hunks resolved by the deterministic pre-pass.

const StrategySafe Strategy = "safe"

StrategySafe resolves only the mechanical tier and leaves every other conflict untouched (still marked, still unmerged) for AI or a human.

type StuckError

type StuckError struct {
	Stuck gitstate.RebaseStuck
}

StuckError signals that `gk resolve` was called on a rebase that is paused with no merge conflicts to resolve. Its Error() returns the multi-line guidance from FormatStuckGuidance, so the standard cli error path renders the full message to stderr and exits non-zero.

func (*StuckError) Error

func (e *StuckError) Error() string

Jump to

Keyboard shortcuts

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