diff

package
v0.145.0 Latest Latest
Warning

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

Go to latest
Published: Sep 28, 2026 License: MIT Imports: 9 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 diff implements unified diff parsing, rendering, and formatting for the `gk diff` command. Parsing and rendering are separated into pure functions for testability.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConflictFileIndices

func ConflictFileIndices(result *DiffResult) []int

ConflictFileIndices는 result 안에서 conflict marker를 포함한 파일의 인덱스 슬라이스를 반환한다 (오름차순). TUI 내비게이션의 "다음 충돌 파일로 점프" 동작이 이 결과를 사용한다.

func FileHasConflictMarker

func FileHasConflictMarker(f DiffFile) bool

FileHasConflictMarker는 파일의 어느 hunk에라도 conflict marker가 포함되어 있는지 검사한다.

func FormatUnifiedDiff

func FormatUnifiedDiff(result *DiffResult) string

FormatUnifiedDiff는 DiffResult를 다시 unified diff 텍스트로 변환한다. 라운드트립 속성 검증에 사용된다: FormatUnifiedDiff → ParseUnifiedDiff가 원본 구조를 보존해야 한다.

func HunkHasConflictMarker

func HunkHasConflictMarker(h Hunk) bool

HunkHasConflictMarker는 hunk의 라인 중 하나라도 conflict marker가 포함되어 있으면 true를 반환한다. 마커는 보통 컨텍스트 라인으로 보이지만 신뢰성을 위해 Kind와 무관하게 검사한다.

func IsConflictMarkerLine

func IsConflictMarkerLine(content string) bool

IsConflictMarkerLine은 한 줄이 git merge conflict 마커인지 판단한다. hunk line의 prefix(+/-/space)는 이미 제거된 Content 기준이다.

정확히 7개 문자 + (EOL | space | tab)만 인정 → git 본인 동작과 일치. 8개 이상이거나 6개 이하는 우연한 코드 토큰(예: shell heredoc, 코드 주석 구분선)으로 간주해서 false.

func IsWhitespaceOnlyChange

func IsWhitespaceOnlyChange(oldLine, newLine string) bool

IsWhitespaceOnlyChange는 두 라인의 차이가 공백 변경만인지 확인한다. 중간 공백, 앞뒤 공백 등 모든 공백 차이를 감지한다.

func Render

func Render(w io.Writer, result *DiffResult, opts RenderOptions) error

Render는 DiffResult를 터미널 출력으로 변환하여 w에 쓴다.

func RenderLine

func RenderLine(line DiffLine, noColor bool) string

RenderLine은 단일 DiffLine을 렌더링하여 문자열로 반환한다. 속성 테스트에서 개별 라인 렌더링 동작을 검증할 수 있도록 export한다.

func RenderStat

func RenderStat(w io.Writer, result *DiffResult, noColor bool) error

RenderStat는 DiffResult에서 파일별 통계 요약을 생성한다. git diff --stat과 유사한 형식으로 출력한다.

func WriteJSON

func WriteJSON(w io.Writer, result *DiffResult) error

WriteJSON은 DiffResult를 JSON으로 변환하여 w에 출력한다. 가독성을 위해 들여쓰기된 JSON을 출력한다.

Types

type DiffFile

type DiffFile struct {
	OldPath      string     // 원본 경로 (rename 시 이전 경로)
	NewPath      string     // 새 경로
	Status       FileStatus // Added, Modified, Deleted, Renamed, Copied, ModeChanged
	IsBinary     bool       // 바이너리 파일 여부
	OldMode      string     // 이전 파일 모드 (예: "100644")
	NewMode      string     // 새 파일 모드
	Hunks        []Hunk
	AddedLines   int // 추가된 라인 총 수
	DeletedLines int // 삭제된 라인 총 수
}

DiffFile은 단일 파일의 diff 정보를 담는다.

type DiffFileJSON

type DiffFileJSON struct {
	Path         string         `json:"path"`
	OldPath      string         `json:"old_path,omitempty"`
	Status       string         `json:"status"`
	IsBinary     bool           `json:"is_binary"`
	AddedLines   int            `json:"added_lines"`
	DeletedLines int            `json:"deleted_lines"`
	Hunks        []DiffHunkJSON `json:"hunks"`
}

DiffFileJSON은 JSON 출력에서 단일 파일의 diff 정보이다.

type DiffHunkJSON

type DiffHunkJSON struct {
	Header string         `json:"header"`
	Lines  []DiffLineJSON `json:"lines"`
}

DiffHunkJSON은 JSON 출력에서 하나의 Hunk 정보이다.

type DiffJSON

type DiffJSON struct {
	Files []DiffFileJSON `json:"files"`
	Stat  DiffStatJSON   `json:"stat"`
}

DiffJSON은 --json 출력 형식이다.

func ToJSON

func ToJSON(result *DiffResult) *DiffJSON

ToJSON은 DiffResult를 JSON 출력용 DiffJSON 구조체로 변환한다.

type DiffLine

type DiffLine struct {
	Kind    LineKind // Context, Added, Deleted
	Content string   // 라인 내용 (접두사 제외)
	OldNum  int      // 원본 파일 라인 번호 (Added일 때 0)
	NewNum  int      // 새 파일 라인 번호 (Deleted일 때 0)
}

DiffLine은 diff의 개별 라인을 나타낸다.

type DiffLineJSON

type DiffLineJSON struct {
	Kind    string `json:"kind"` // "context", "added", "deleted"
	Content string `json:"content"`
	OldNum  int    `json:"old_num,omitempty"`
	NewNum  int    `json:"new_num,omitempty"`
}

DiffLineJSON은 JSON 출력에서 개별 라인 정보이다.

type DiffResult

type DiffResult struct {
	Files []DiffFile
}

DiffResult는 전체 diff 파싱 결과를 담는 최상위 구조체이다.

func FilterConflictHunks

func FilterConflictHunks(result *DiffResult) *DiffResult

FilterConflictHunks는 result의 깊은 복사본을 반환하되, 각 파일에서 conflict marker가 없는 hunk를 제거하고, 결과적으로 hunk가 0개가 된 파일도 함께 제거한다. 원본 result는 변경하지 않는다.

"충돌만 보기" 모드(--conflicts 플래그 / TUI c 단축키)가 이 함수의 결과를 렌더한다.

func ParseUnifiedDiff

func ParseUnifiedDiff(r io.Reader) (*DiffResult, error)

ParseUnifiedDiff는 git diff의 unified diff 출력을 파싱하여 DiffResult를 반환한다. 순수 함수로 구현되어 io.Reader에서 읽는다.

라인 길이 한계는 scannerMaxLineBytes(64MB). 일반 소스 파일의 한 줄은 수십~수백 바이트지만, 생성된 lockfile, minified bundle, 또는 한 줄에 수백만 토큰이 들어간 vendored 파일은 1MB도 쉽게 넘는다. 한계를 넘으면 `bufio.ErrTooLong` 으로 파싱 자체가 실패하므로 caller가 raw bytes 출력으로 fallback해 무엇이 잘못됐는지조차 모르게 된다 — 64MB로 두어 현실의 거대 입력은 다 흡수하면서도 무제한 메모리는 막는다.

type DiffSpan

type DiffSpan struct {
	Start   int  // 바이트 오프셋
	End     int  // 바이트 오프셋 (exclusive)
	Changed bool // true면 변경된 구간
}

DiffSpan은 워드 diff에서 변경된 구간을 나타낸다.

func ComputeWordDiff

func ComputeWordDiff(oldLine, newLine string) (oldSpans, newSpans []DiffSpan)

ComputeWordDiff는 삭제 라인(oldLine)과 추가 라인(newLine) 쌍에서 단어 단위 차이를 계산한다. 반환값은 각 라인의 변경된 구간(spans)이다. oldSpans는 oldLine 전체를, newSpans는 newLine 전체를 빈틈 없이 커버한다.

알고리즘: 공백 기준 토큰화 → LCS(최장 공통 부분 수열) → 바이트 오프셋 매핑

한 줄이 wordDiffMaxLineBytes를 넘거나 LCS DP 테이블 크기가 wordDiffMaxCells를 초과하면 word-diff를 건너뛰고 라인 전체를 변경(Changed: true)으로 표시한다 — 인스턴스 메모리가 폭발하면 `gk diff`가 OOM으로 중단되므로, 거대한 한 줄(minified JS, 생성 코드)에는 intra-line 하이라이트를 포기하는 게 옳다.

type DiffStatJSON

type DiffStatJSON struct {
	TotalFiles   int `json:"total_files"`
	TotalAdded   int `json:"total_added"`
	TotalDeleted int `json:"total_deleted"`
}

DiffStatJSON은 JSON 출력에서 diff 통계 요약이다.

type Digest

type Digest struct {
	Files []FileDigest
	Stat  DigestStat
}

Digest is the semantic summary of a diff — what an agent (or human) needs to know what changed without reading the patch: per-file change kind, hunk count, line deltas, and the symbols (function contexts) the hunks touched. It is the data model behind `gk diff --digest`.

func BuildDigest

func BuildDigest(res *DiffResult) Digest

BuildDigest reduces a parsed diff to its digest.

type DigestStat

type DigestStat struct {
	Files   int
	Hunks   int
	Added   int
	Deleted int
}

DigestStat aggregates the whole diff.

type FileDigest

type FileDigest struct {
	Path    string
	OldPath string // set on rename/copy
	Status  FileStatus
	Binary  bool
	Hunks   int
	Added   int
	Deleted int
	// Symbols are the deduplicated function contexts from this file's hunk
	// headers, in first-seen order — "which functions changed" at a glance.
	Symbols []string
}

FileDigest summarizes one file's change.

type FileStatus

type FileStatus int

FileStatus는 파일의 변경 상태를 나타낸다.

const (
	StatusModified    FileStatus = iota // 수정됨
	StatusAdded                         // 추가됨
	StatusDeleted                       // 삭제됨
	StatusRenamed                       // 이름 변경됨
	StatusCopied                        // 복사됨
	StatusModeChanged                   // 모드 변경됨
)

func (FileStatus) String

func (s FileStatus) String() string

String은 FileStatus의 사람이 읽을 수 있는 문자열 표현을 반환한다.

type Hunk

type Hunk struct {
	OldStart int    // 원본 시작 라인
	OldCount int    // 원본 라인 수
	NewStart int    // 새 파일 시작 라인
	NewCount int    // 새 파일 라인 수
	Header   string // @@ 헤더 전체 텍스트
	// FuncName은 git이 hunk header 뒤에 붙이는 함수 컨텍스트
	// ("@@ ... @@ func runPull(...) error {" → "func runPull(...) error").
	// git의 기본 휴리스틱만으로 채워지며(.gitattributes 불필요), 없으면 빈 값.
	FuncName string
	Lines    []DiffLine
}

Hunk는 하나의 변경 블록을 나타낸다.

func BuildConflictHunks

func BuildConflictHunks(rawLines []string, contextLines int) []Hunk

BuildConflictHunks는 conflict marker가 박힌 파일의 원시 라인을 받아, marker block마다 한 hunk를 만들어 반환한다 — 파일 전체를 한 hunk로 출력하면 사용자가 변경 영역을 찾기 어렵고 정상 diff UI와도 결이 다르다.

라인 분류:

  • <<<<<<<와 ======= 사이 ("ours") → LineDeleted (◀, red)
  • =======와 >>>>>>> 사이 ("theirs") → LineAdded (▶, green)
  • ||||||| (diff3 ancestor) ~ ======= → LineContext (사용자가 직접 판단)
  • marker 라인 자체 → LineContext
  • block 바깥의 ±context 라인 → LineContext

각 hunk는 block 위/아래로 contextLines 만큼의 컨텍스트를 포함한다. 인접한 block의 context가 겹치면 두 block을 한 hunk로 합친다 — 일반 `git diff -U3`이 인접 변경을 합치는 동작과 일치.

type LineKind

type LineKind int

LineKind는 diff 라인의 종류를 나타낸다.

const (
	LineContext LineKind = iota // 컨텍스트 라인
	LineAdded                   // 추가된 라인
	LineDeleted                 // 삭제된 라인
)

func (LineKind) String

func (k LineKind) String() string

String은 LineKind의 문자열 표현을 반환한다.

type RenderOptions

type RenderOptions struct {
	NoColor    bool // ANSI 이스케이프 코드 비활성화
	NoWordDiff bool // 단어 단위 하이라이트 비활성화
	Context    int  // 컨텍스트 라인 수 (기본 3, 현재 파서에서 제어)

	// ShowRefs는 파일 헤더 바로 아래에 ◀ LeftRef / ▶ RightRef 한 줄을
	// 표시할지 결정한다. LeftRef/RightRef 둘 다 비어있으면 무시된다.
	ShowRefs bool
	LeftRef  string // ◀ 쪽 비교 대상 라벨 (예: "develop")
	RightRef string // ▶ 쪽 비교 대상 라벨 (예: "origin/main")
}

RenderOptions는 렌더링 동작을 제어하는 옵션이다.

Jump to

Keyboard shortcuts

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