diff --git a/go.mod b/go.mod index 8a68ef2..c9e1b87 100644 --- a/go.mod +++ b/go.mod @@ -14,7 +14,7 @@ require ( github.com/charmbracelet/x/term v0.2.2 github.com/google/uuid v1.6.0 github.com/mattn/go-runewidth v0.0.31 - github.com/pb33f/doctor v0.0.87 + github.com/pb33f/doctor v0.0.88 github.com/pb33f/go-yaml v0.1.1 github.com/pb33f/libasyncapi v0.0.7 github.com/pb33f/libopenapi v0.42.3 diff --git a/go.sum b/go.sum index 6106a8b..11b8a20 100644 --- a/go.sum +++ b/go.sum @@ -99,8 +99,8 @@ github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELU github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk= github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g= -github.com/pb33f/doctor v0.0.87 h1:4PQgjs+sjYDL8VxnUJhZLHDWl0+zYcCgfsVD/m7231c= -github.com/pb33f/doctor v0.0.87/go.mod h1:9TCfRtf+g+WJArC1jga31KP2fzCggg0W0RrVWryh9Vc= +github.com/pb33f/doctor v0.0.88 h1:4hX+P2jxFyF/lfGKw9imOUC2c44exVYDcD5T6r6Zq4I= +github.com/pb33f/doctor v0.0.88/go.mod h1:kFgQgvAm9ESjpaQAzyn82NzQpqpM+zwjZdovS2IeX/Q= github.com/pb33f/go-yaml v0.1.1 h1:yWGmhVdwzionRnSc/hEJwcfq6PaZL2QdYzyReXBbX7Q= github.com/pb33f/go-yaml v0.1.1/go.mod h1:QvWdkHP5VjFYAeHMQUkaPQqREaQnBNOXmWzAjNrnSdo= github.com/pb33f/jsonpath v0.8.4 h1:Yx7fxsKl8scgERL22WhKDs2c6gYNNUonPSWEG8Y194s= diff --git a/tui/v2/block_range.go b/tui/v2/block_range.go deleted file mode 100644 index 9c663f2..0000000 --- a/tui/v2/block_range.go +++ /dev/null @@ -1,332 +0,0 @@ -// Copyright 2023-2026 Princess Beef Heavy Industries, LLC / Dave Shanley -// SPDX-License-Identifier: Apache-2.0 - -package v2 - -import ( - "strings" - - whatChangedModel "github.com/pb33f/libopenapi/what-changed/model" -) - -// highlightRange represents a range of lines to highlight in the code view. -type highlightRange struct { - start int // 1-based start line (inclusive) — the "primary" line for centering - end int // 1-based end line (inclusive) -} - -const maxBlockSize = 500 - -// singleLineRange returns a highlightRange covering a single line. -func singleLineRange(line int) highlightRange { - return highlightRange{start: line, end: line} -} - -// computeBlockRange returns the 1-based start and end lines for the highlight range. -// It expands to cover the full YAML/JSON block rooted at changeLn. -// For single-line values (no children), the forward scan finds nothing and -// returns (changeLn, changeLn), so callers don't need to pre-filter by change type. -func computeBlockRange(lines []string, changeLn int) (startLine, endLine int) { - if changeLn <= 0 || len(lines) == 0 || changeLn > len(lines) { - return changeLn, changeLn - } - - // Phase 1 — Backward scan to find the parent key line. - // changeLn often points to the first child (e.g., "description: OK") - // rather than the parent key ("200:"). Find the nearest line above - // with strictly less indent. - changeIdx := changeLn - 1 // 0-based - changeIndent := measureIndent(lines[changeIdx]) - keyIdx := changeIdx - - for i := changeIdx - 1; i >= 0; i-- { - line := lines[i] - if isBlankOrComment(line) { - continue - } - if measureIndent(line) < changeIndent { - keyIdx = i - break - } - } - - refIndent := measureIndent(lines[keyIdx]) - startLine = keyIdx + 1 // 1-based - - // Phase 2 — Forward scan from changeLn while indent > refIndent. - endIdx := changeIdx - for i := changeIdx + 1; i < len(lines) && (i-keyIdx) < maxBlockSize; i++ { - line := lines[i] - if isBlankOrComment(line) { - // Blank/comment lines within a block don't end it; - // trailing blanks are trimmed after the scan. - endIdx = i - continue - } - if measureIndent(line) > refIndent { - endIdx = i - } else { - break - } - } - - // Trim trailing blank lines from the range. - for endIdx > keyIdx && isBlankOrComment(lines[endIdx]) { - endIdx-- - } - - // Phase 3 — JSON peek-ahead: include closing brace/bracket at refIndent. - if endIdx+1 < len(lines) { - next := lines[endIdx+1] - trimmed := trimLeft(next) - if len(trimmed) > 0 && measureIndent(next) == refIndent { - first := trimmed[0] - if first == '}' || first == ']' { - endIdx = endIdx + 1 - } - } - } - - endLine = endIdx + 1 // 1-based - if endLine < startLine { - endLine = startLine - } - return startLine, endLine -} - -// findChildKeyLine scans forward from parentLn to find a direct child entry matching property. -// parentLn is 1-based. Returns the 1-based line number of the child, or 0 if not found. -func findChildKeyLine(lines []string, parentLn int, property string) int { - return findChildLine(lines, parentLn, []string{property}) -} - -// computeChildBlockRange returns the 1-based start and end lines for a child key block. -// childKeyLn is 1-based and must point to the key line itself (no backward scan). -func computeChildBlockRange(lines []string, childKeyLn int) (startLine, endLine int) { - if childKeyLn <= 0 || len(lines) == 0 || childKeyLn > len(lines) { - return childKeyLn, childKeyLn - } - - childIdx := childKeyLn - 1 - childIndent := measureIndent(lines[childIdx]) - startLine = childKeyLn - - // Forward scan: include all lines with indent > childIndent - endIdx := childIdx - for i := childIdx + 1; i < len(lines) && (i-childIdx) < maxBlockSize; i++ { - line := lines[i] - if isBlankOrComment(line) { - endIdx = i - continue - } - if measureIndent(line) > childIndent { - endIdx = i - } else { - break - } - } - - // Trim trailing blank lines - for endIdx > childIdx && isBlankOrComment(lines[endIdx]) { - endIdx-- - } - - // JSON peek-ahead: include closing brace/bracket at childIndent - if endIdx+1 < len(lines) { - next := lines[endIdx+1] - trimmed := trimLeft(next) - if len(trimmed) > 0 && measureIndent(next) == childIndent { - first := trimmed[0] - if first == '}' || first == ']' { - endIdx = endIdx + 1 - } - } - } - - endLine = endIdx + 1 // 1-based - if endLine < startLine { - endLine = startLine - } - return startLine, endLine -} - -// computeBlockRangeForChange dispatches to the appropriate block range function -// based on change type. For ObjectAdded/ObjectRemoved, it tries to find the -// specific child key line to scope the highlight to just that child block. -func computeBlockRangeForChange(lines []string, changeLn int, ch *whatChangedModel.Change) (int, int) { - if ch != nil { - switch ch.ChangeType { - case whatChangedModel.ObjectAdded, whatChangedModel.ObjectRemoved, - whatChangedModel.PropertyAdded, whatChangedModel.PropertyRemoved, - whatChangedModel.Modified: - candidates := changeLookupCandidates(ch) - for line := changeLn; line > 0; { - if lineMatchesAnyCandidate(lines, line, candidates) { - return computeChildBlockRange(lines, line) - } - if childLn := findChildLine(lines, line, candidates); childLn > 0 { - return computeChildBlockRange(lines, childLn) - } - next := findAncestorLine(lines, line) - if next <= 0 || next == line { - break - } - line = next - } - } - } - return computeBlockRange(lines, changeLn) -} - -func changeLookupCandidates(ch *whatChangedModel.Change) []string { - if ch == nil { - return nil - } - - seen := make(map[string]struct{}, 3) - var candidates []string - add := func(value string) { - token := normalizeLookupToken(value) - if token == "" { - return - } - if _, ok := seen[token]; ok { - return - } - seen[token] = struct{}{} - candidates = append(candidates, token) - } - - add(ch.Property) - add(ch.Original) - add(ch.New) - - return candidates -} - -func normalizeLookupToken(value string) string { - value = strings.TrimSpace(value) - value = strings.TrimSuffix(value, ",") - value = strings.TrimSpace(value) - value = strings.Trim(value, `"'`) - return strings.ToLower(strings.TrimSpace(value)) -} - -func lineMatchesAnyCandidate(lines []string, line int, candidates []string) bool { - if line <= 0 || line > len(lines) || len(candidates) == 0 { - return false - } - token, ok := extractLineToken(lines[line-1]) - if !ok { - return false - } - for _, candidate := range candidates { - if token == candidate { - return true - } - } - return false -} - -func findChildLine(lines []string, parentLn int, candidates []string) int { - if parentLn <= 0 || parentLn > len(lines) || len(candidates) == 0 { - return 0 - } - - parentIdx := parentLn - 1 - parentIndent := measureIndent(lines[parentIdx]) - childIndent := -1 - - for i := parentIdx + 1; i < len(lines); i++ { - line := lines[i] - if isBlankOrComment(line) { - continue - } - ind := measureIndent(line) - if ind <= parentIndent { - break - } - if childIndent == -1 { - childIndent = ind - } - if ind != childIndent { - continue - } - if lineMatchesAnyCandidate(lines, i+1, candidates) { - return i + 1 - } - } - return 0 -} - -func findAncestorLine(lines []string, line int) int { - if line <= 1 || line > len(lines) { - return 0 - } - - idx := line - 1 - indent := measureIndent(lines[idx]) - for i := idx - 1; i >= 0; i-- { - if isBlankOrComment(lines[i]) { - continue - } - if measureIndent(lines[i]) < indent { - return i + 1 - } - } - return 0 -} - -func extractLineToken(line string) (string, bool) { - trimmed := trimLeft(line) - if trimmed == "" { - return "", false - } - - if strings.HasPrefix(trimmed, "- ") { - item := strings.TrimSpace(trimmed[2:]) - if item == "" { - return "", false - } - if colonIdx := strings.IndexByte(item, ':'); colonIdx > 0 { - return normalizeLookupToken(item[:colonIdx]), true - } - return normalizeLookupToken(item), true - } - - if colonIdx := strings.IndexByte(trimmed, ':'); colonIdx > 0 { - return normalizeLookupToken(trimmed[:colonIdx]), true - } - - switch trimmed[0] { - case '{', '}', '[', ']': - return "", false - } - - return normalizeLookupToken(trimmed), true -} - -// measureIndent returns the number of leading space/tab bytes. -func measureIndent(line string) int { - for i := 0; i < len(line); i++ { - if line[i] != ' ' && line[i] != '\t' { - return i - } - } - return len(line) -} - -// isBlankOrComment returns true if the line is empty, whitespace-only, or a YAML comment. -func isBlankOrComment(line string) bool { - trimmed := trimLeft(line) - return len(trimmed) == 0 || trimmed[0] == '#' -} - -// trimLeft trims leading spaces and tabs (byte-level, no allocation for ASCII). -func trimLeft(s string) string { - i := 0 - for i < len(s) && (s[i] == ' ' || s[i] == '\t') { - i++ - } - return s[i:] -} diff --git a/tui/v2/block_range_test.go b/tui/v2/block_range_test.go deleted file mode 100644 index 37ce41f..0000000 --- a/tui/v2/block_range_test.go +++ /dev/null @@ -1,637 +0,0 @@ -// Copyright 2023-2026 Princess Beef Heavy Industries, LLC / Dave Shanley -// SPDX-License-Identifier: Apache-2.0 - -package v2 - -import ( - "fmt" - "testing" - - whatChangedModel "github.com/pb33f/libopenapi/what-changed/model" - "github.com/pb33f/testify/assert" -) - -func TestComputeBlockRange_ObjectAdded(t *testing.T) { - lines := []string{ - "openapi: '3.0'", // 1 - "paths:", // 2 - " /pets:", // 3 - " get:", // 4 - " summary: List", // 5 - " responses:", // 6 - " 200:", // 7 - " description: OK", // 8 - " /users:", // 9 - " get:", // 10 - } - - // changeLn points to the first child line (line 4: "get:") - start, end := computeBlockRange(lines, 4) - // Should expand backward to the parent key "/pets:" (line 3) and forward through line 8 - assert.Equal(t, 3, start) - assert.Equal(t, 8, end) -} - -func TestComputeBlockRange_PropertyAdded_SingleLine(t *testing.T) { - lines := []string{ - "info:", - " title: Test", - " description: Added", - } - - // Single-line scalar property — backward scan finds parent "info:" (line 1), - // forward scan covers all children at deeper indent. - start, end := computeBlockRange(lines, 3) - assert.Equal(t, 1, start) - assert.Equal(t, 3, end) -} - -func TestComputeBlockRange_PropertyAdded_MultiLine(t *testing.T) { - // PropertyAdded for a multi-line block (e.g., adding a new operation) - lines := []string{ - "paths:", // 1 - " /pets:", // 2 - " get:", // 3 - " summary: List pets", // 4 - " responses:", // 5 - " 200:", // 6 - " description: OK", // 7 - " put:", // 8 - " summary: Update pet", // 9 - " responses:", // 10 - " 200:", // 11 - " description: Updated", // 12 - " /users:", // 13 - } - - // changeLn=9 points to "summary: Update pet" (child of "put:") - // Should expand backward to "put:" (line 8) and forward through line 12 - start, end := computeBlockRange(lines, 9) - assert.Equal(t, 8, start) - assert.Equal(t, 12, end) -} - -func TestComputeBlockRange_Modified(t *testing.T) { - lines := []string{ - "info:", - " title: Test", - } - - // Backward scan finds parent "info:" (line 1), forward scan covers child. - start, end := computeBlockRange(lines, 2) - assert.Equal(t, 1, start) - assert.Equal(t, 2, end) -} - -func TestComputeBlockRange_EmptyLines(t *testing.T) { - // nil/empty input - start, end := computeBlockRange(nil, 1) - assert.Equal(t, 1, start) - assert.Equal(t, 1, end) - - start, end = computeBlockRange([]string{}, 1) - assert.Equal(t, 1, start) - assert.Equal(t, 1, end) -} - -func TestComputeBlockRange_BlankLinesInBlock(t *testing.T) { - lines := []string{ - "paths:", // 1 - " /pets:", // 2 - " get:", // 3 - "", // 4 blank - " summary: X", // 5 - " /users:", // 6 - } - - start, end := computeBlockRange(lines, 3) - assert.Equal(t, 2, start) - assert.Equal(t, 5, end) -} - -func TestComputeBlockRange_EndOfFile(t *testing.T) { - lines := []string{ - "paths:", - " /pets:", - " get:", - " summary: List", - } - - start, end := computeBlockRange(lines, 3) - assert.Equal(t, 2, start) - assert.Equal(t, 4, end) -} - -func TestComputeBlockRange_JSONClosingBrace(t *testing.T) { - lines := []string{ - `{`, // 1 - ` "paths": {`, // 2 - ` "/pets": {`, // 3 - ` "get": {}`, // 4 - ` }`, // 5 - ` }`, // 6 - `}`, // 7 - } - - start, end := computeBlockRange(lines, 4) - // Should backward-scan to "/pets" (line 3), forward through "get" (line 4), - // then peek-ahead to include closing "}" (line 5) - assert.Equal(t, 3, start) - assert.Equal(t, 5, end) -} - -func TestComputeBlockRange_SingleLineObject(t *testing.T) { - lines := []string{ - "paths:", - " /pets: {}", - " /users:", - } - - // When changeLn IS the key line with no children, the backward scan - // finds the parent "paths:" and the forward scan includes siblings. - // This is slightly over-inclusive for single-line objects but acceptable - // since multi-line ObjectAdded (the primary use case) works correctly. - start, end := computeBlockRange(lines, 2) - assert.Equal(t, 1, start) // includes parent "paths:" - assert.Equal(t, 3, end) // includes sibling "/users:" -} - -func TestComputeBlockRange_SiblingAbove(t *testing.T) { - // changeLn-1 is the last child of a PREVIOUS sibling, not the parent - lines := []string{ - "paths:", // 1 - " /pets:", // 2 - " get:", // 3 - " summary: X", // 4 - " /users:", // 5 - " post:", // 6 - " summary: Y", // 7 - } - - // changeLn=6 points to "post:" (child of /users), backward scan should find "/users:" (line 5) - start, end := computeBlockRange(lines, 6) - assert.Equal(t, 5, start) - assert.Equal(t, 7, end) -} - -func TestComputeBlockRange_KeyLineInclusion(t *testing.T) { - lines := []string{ - "responses:", // 1 - " 200:", // 2 - " description: OK", // 3 - " 404:", // 4 - } - - // changeLn=3 points to "description: OK", backward scan should find "200:" (line 2) - start, end := computeBlockRange(lines, 3) - assert.Equal(t, 2, start) - assert.Equal(t, 3, end) -} - -func TestComputeBlockRange_KeyLineSeparatedByBlank(t *testing.T) { - lines := []string{ - "responses:", // 1 - " 200:", // 2 - "", // 3 blank - " description: OK", // 4 - " 404:", // 5 - } - - // changeLn=4, backward scan should skip blank and find "200:" (line 2) - start, end := computeBlockRange(lines, 4) - assert.Equal(t, 2, start) - assert.Equal(t, 4, end) -} - -func TestComputeBlockRange_MaxBlockSize(t *testing.T) { - lines := make([]string, 600) - lines[0] = "root:" - lines[1] = " key:" - for i := 2; i < 600; i++ { - lines[i] = fmt.Sprintf(" line%d: value", i) - } - - start, end := computeBlockRange(lines, 3) - assert.Equal(t, 2, start) - // Should cap at maxBlockSize (500) lines from key line - assert.LessOrEqual(t, end-start+1, maxBlockSize+1) -} - -func TestMeasureIndent(t *testing.T) { - assert.Equal(t, 0, measureIndent("hello")) - assert.Equal(t, 2, measureIndent(" hello")) - assert.Equal(t, 4, measureIndent(" hello")) - assert.Equal(t, 1, measureIndent("\thello")) - assert.Equal(t, 0, measureIndent("")) - assert.Equal(t, 3, measureIndent(" ")) // all whitespace -} - -func TestComputeBlockRange_InvalidInputs(t *testing.T) { - lines := []string{"a", "b", "c"} - - // changeLn = 0 (invalid) - start, end := computeBlockRange(lines, 0) - assert.Equal(t, 0, start) - assert.Equal(t, 0, end) - - // changeLn beyond end - start, end = computeBlockRange(lines, 10) - assert.Equal(t, 10, start) - assert.Equal(t, 10, end) -} - -// --- findChildKeyLine tests --- - -func TestFindChildKeyLine_YAML(t *testing.T) { - lines := []string{ - "paths:", // 1 - " /pet:", // 2 - " put:", // 3 - " summary: U", // 4 - " post:", // 5 - " summary: C", // 6 - " get:", // 7 - " summary: R", // 8 - } - - // parentLn=2 (/pet:), looking for "post" - got := findChildKeyLine(lines, 2, "post") - assert.Equal(t, 5, got) -} - -func TestFindChildKeyLine_JSON(t *testing.T) { - lines := []string{ - `{`, // 1 - ` "paths": {`, // 2 - ` "/pet": {`, // 3 - ` "put": {},`, // 4 - ` "post": {},`, // 5 - ` "get": {}`, // 6 - ` }`, // 7 - ` }`, // 8 - `}`, // 9 - } - - // parentLn=3 ("/pet"), looking for "post" - got := findChildKeyLine(lines, 3, "post") - assert.Equal(t, 5, got) -} - -func TestFindChildKeyLine_NotFound(t *testing.T) { - lines := []string{ - "paths:", // 1 - " /pet:", // 2 - " get:", // 3 - " put:", // 4 - } - - got := findChildKeyLine(lines, 2, "delete") - assert.Equal(t, 0, got) -} - -func TestFindChildKeyLine_StopsAtParentScope(t *testing.T) { - lines := []string{ - "paths:", // 1 - " /pet:", // 2 - " get:", // 3 - " /users:", // 4 - " post:", // 5 - } - - // Looking for "post" under /pet — should NOT find it under /users - got := findChildKeyLine(lines, 2, "post") - assert.Equal(t, 0, got) -} - -func TestFindChildKeyLine_CaseInsensitive(t *testing.T) { - lines := []string{ - "responses:", // 1 - " 200:", // 2 - " description: OK", // 3 - " 404:", // 4 - " description: NF", // 5 - } - - got := findChildKeyLine(lines, 1, "404") - assert.Equal(t, 4, got) -} - -func TestFindChildKeyLine_InvalidInputs(t *testing.T) { - lines := []string{"a:", " b: c"} - assert.Equal(t, 0, findChildKeyLine(lines, 0, "b")) - assert.Equal(t, 0, findChildKeyLine(lines, 1, "")) - assert.Equal(t, 0, findChildKeyLine(nil, 1, "b")) -} - -// --- computeChildBlockRange tests --- - -func TestComputeChildBlockRange_SingleVerb(t *testing.T) { - lines := []string{ - "paths:", // 1 - " /pet:", // 2 - " put:", // 3 - " summary: U", // 4 - " post:", // 5 - " summary: C", // 6 - " description: D", // 7 - " get:", // 8 - " summary: R", // 9 - } - - // childKeyLn=5 (post:) - s, e := computeChildBlockRange(lines, 5) - assert.Equal(t, 5, s) - assert.Equal(t, 7, e) -} - -func TestComputeChildBlockRange_WithChildren(t *testing.T) { - lines := []string{ - "paths:", // 1 - " /pet:", // 2 - " post:", // 3 - " summary: C", // 4 - " responses:", // 5 - " 200:", // 6 - " desc: OK", // 7 - " get:", // 8 - } - - s, e := computeChildBlockRange(lines, 3) - assert.Equal(t, 3, s) - assert.Equal(t, 7, e) -} - -func TestComputeChildBlockRange_JSONBrace(t *testing.T) { - lines := []string{ - ` "paths": {`, // 1 - ` "/pet": {`, // 2 - ` "post": {`, // 3 - ` "summary": "C"`, // 4 - ` },`, // 5 - ` "get": {}`, // 6 - ` }`, // 7 - ` }`, // 8 - } - - s, e := computeChildBlockRange(lines, 3) - assert.Equal(t, 3, s) - assert.Equal(t, 5, e) // includes closing } -} - -func TestComputeChildBlockRange_EndOfFile(t *testing.T) { - lines := []string{ - "paths:", // 1 - " /pet:", // 2 - " delete:", // 3 - " summary: D", // 4 - } - - s, e := computeChildBlockRange(lines, 3) - assert.Equal(t, 3, s) - assert.Equal(t, 4, e) -} - -func TestComputeChildBlockRange_SingleLine(t *testing.T) { - lines := []string{ - "paths:", // 1 - " /pet:", // 2 - " get: {}", // 3 - " post: {}", // 4 - } - - s, e := computeChildBlockRange(lines, 3) - assert.Equal(t, 3, s) - assert.Equal(t, 3, e) -} - -func TestComputeChildBlockRange_InvalidInputs(t *testing.T) { - s, e := computeChildBlockRange(nil, 1) - assert.Equal(t, 1, s) - assert.Equal(t, 1, e) - - s, e = computeChildBlockRange([]string{"a"}, 0) - assert.Equal(t, 0, s) - assert.Equal(t, 0, e) -} - -// --- computeBlockRangeForChange tests --- - -func TestComputeBlockRangeForChange_ObjectRemoved(t *testing.T) { - lines := []string{ - "paths:", // 1 - " /pet:", // 2 - " put:", // 3 - " summary: U", // 4 - " post:", // 5 - " summary: C", // 6 - " description: D", // 7 - " get:", // 8 - " summary: R", // 9 - } - - ch := &whatChangedModel.Change{ - ChangeType: whatChangedModel.ObjectRemoved, - Property: "post", - } - - // changeLn=2 points to /pet: (the parent), but we should scope to just "post:" - s, e := computeBlockRangeForChange(lines, 2, ch) - assert.Equal(t, 5, s) - assert.Equal(t, 7, e) -} - -func TestComputeBlockRangeForChange_ObjectAdded(t *testing.T) { - lines := []string{ - "paths:", // 1 - " /pet:", // 2 - " get:", // 3 - " summary: R", // 4 - " patch:", // 5 - " summary: P", // 6 - } - - ch := &whatChangedModel.Change{ - ChangeType: whatChangedModel.ObjectAdded, - Property: "patch", - } - - s, e := computeBlockRangeForChange(lines, 2, ch) - assert.Equal(t, 5, s) - assert.Equal(t, 6, e) -} - -func TestComputeBlockRangeForChange_Modified(t *testing.T) { - lines := []string{ - "info:", - " title: Test", - } - - ch := &whatChangedModel.Change{ - ChangeType: whatChangedModel.Modified, - Property: "title", - } - - // Modified changes should find the specific property line, not the parent block - s, e := computeBlockRangeForChange(lines, 2, ch) - assert.Equal(t, 2, s) - assert.Equal(t, 2, e) -} - -func TestComputeBlockRangeForChange_ChildNotFound_Fallback(t *testing.T) { - lines := []string{ - "paths:", // 1 - " /pet:", // 2 - " get:", // 3 - " summary: R", // 4 - } - - ch := &whatChangedModel.Change{ - ChangeType: whatChangedModel.ObjectRemoved, - Property: "delete", // doesn't exist in the lines - } - - // Should fall back to computeBlockRange - s, e := computeBlockRangeForChange(lines, 2, ch) - sExpected, eExpected := computeBlockRange(lines, 2) - assert.Equal(t, sExpected, s) - assert.Equal(t, eExpected, e) -} - -func TestComputeBlockRangeForChange_NilChange(t *testing.T) { - lines := []string{ - "info:", - " title: Test", - } - - s, e := computeBlockRangeForChange(lines, 2, nil) - sExpected, eExpected := computeBlockRange(lines, 2) - assert.Equal(t, sExpected, s) - assert.Equal(t, eExpected, e) -} - -func TestComputeBlockRangeForChange_ResponseCodes(t *testing.T) { - lines := []string{ - "responses:", // 1 - " 200:", // 2 - " description: OK", // 3 - " 400:", // 4 - " description: Bad", // 5 - " 404:", // 6 - " description: NF", // 7 - } - - ch := &whatChangedModel.Change{ - ChangeType: whatChangedModel.ObjectRemoved, - Property: "404", - } - - // changeLn=1 points to "responses:" (the parent) - s, e := computeBlockRangeForChange(lines, 1, ch) - assert.Equal(t, 6, s) - assert.Equal(t, 7, e) -} - -func TestComputeBlockRangeForChange_ResponseCodes_SemanticPropertyOnChildLine(t *testing.T) { - lines := []string{ - ` "responses": {`, // 1 - ` "200": {`, // 2 - ` "description": "successful",`, // 3 - ` "content": {`, // 4 - ` "application/json": {}`, // 5 - ` }`, // 6 - ` },`, // 7 - ` "400": {`, // 8 - ` "description": "Invalid ID"`, // 9 - ` },`, // 10 - ` "404": {`, // 11 - ` "description": "Order not found"`, // 12 - ` }`, // 13 - ` }`, // 14 - } - - ch := &whatChangedModel.Change{ - ChangeType: whatChangedModel.ObjectRemoved, - Property: "codes", - Original: "404", - } - - s, e := computeBlockRangeForChange(lines, 11, ch) - assert.Equal(t, 11, s) - assert.Equal(t, 13, e) -} - -func TestComputeBlockRangeForChange_ResponseCodes_SemanticPropertyOnParentLine(t *testing.T) { - lines := []string{ - ` "responses": {`, // 1 - ` "200": {`, // 2 - ` "description": "successful",`, // 3 - ` },`, // 4 - ` "400": {`, // 5 - ` "description": "Invalid ID"`, // 6 - ` },`, // 7 - ` "404": {`, // 8 - ` "description": "Order not found"`, // 9 - ` }`, // 10 - ` }`, // 11 - } - - ch := &whatChangedModel.Change{ - ChangeType: whatChangedModel.ObjectRemoved, - Property: "codes", - Original: "404", - } - - s, e := computeBlockRangeForChange(lines, 1, ch) - assert.Equal(t, 8, s) - assert.Equal(t, 10, e) -} - -func TestComputeBlockRangeForChange_PropertyRemoved_UsesKeyLine(t *testing.T) { - lines := []string{ - "paths:", // 1 - " /pet:", // 2 - " put:", // 3 - " summary: U", // 4 - " post:", // 5 - " summary: C", // 6 - " description: D", // 7 - " get:", // 8 - " summary: R", // 9 - } - - ch := &whatChangedModel.Change{ - ChangeType: whatChangedModel.PropertyRemoved, - Property: "post", - } - - s, e := computeBlockRangeForChange(lines, 5, ch) - assert.Equal(t, 5, s) - assert.Equal(t, 7, e) -} - -func TestComputeBlockRangeForChange_SchemaProperties_SemanticProperty(t *testing.T) { - lines := []string{ - ` "properties": {`, // 1 - ` "id": {`, // 2 - ` "type": "integer"`, // 3 - ` },`, // 4 - ` "name": {`, // 5 - ` "type": "string",`, // 6 - ` "example": "doggie"`, // 7 - ` },`, // 8 - ` "photoUrls": {`, // 9 - ` "type": "array"`, // 10 - ` }`, // 11 - ` }`, // 12 - } - - ch := &whatChangedModel.Change{ - ChangeType: whatChangedModel.ObjectRemoved, - Property: "properties", - Original: "name", - } - - s, e := computeBlockRangeForChange(lines, 5, ch) - assert.Equal(t, 5, s) - assert.Equal(t, 8, e) -} diff --git a/tui/v2/diff.go b/tui/v2/diff.go index ab2e4ac..a0c74ef 100644 --- a/tui/v2/diff.go +++ b/tui/v2/diff.go @@ -1,600 +1,68 @@ // Copyright 2023-2026 Princess Beef Heavy Industries, LLC / Dave Shanley // SPDX-License-Identifier: Apache-2.0 - package v2 import ( - "fmt" - "regexp" - "strconv" - "strings" - - "charm.land/lipgloss/v2" - "github.com/pmezard/go-difflib/difflib" - + "github.com/pb33f/doctor/terminal/diffview" whatChangedModel "github.com/pb33f/libopenapi/what-changed/model" ) -const ( - regionRadius = 5 // lines above/below change to extract for file-region fallback diffing - contextBefore = 5 // lines above change for spec context view - contextAfter = 120 // lines below change for spec context view - diffContext = 3 // context lines in unified diff output -) - -var hunkHeaderRe = regexp.MustCompile(`@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@`) - -// hasValueData returns true if the Change carries authoritative value data -// (Original/New/OriginalEncoded/NewEncoded or their object counterparts). -func hasValueData(ch *whatChangedModel.Change) bool { - return ch.OriginalObject != nil || ch.NewObject != nil || - ch.Original != "" || ch.New != "" || - ch.OriginalEncoded != "" || ch.NewEncoded != "" -} - -// resolveOldValue returns the best available old value, preferring Encoded. -func resolveOldValue(ch *whatChangedModel.Change) string { - if ch.OriginalEncoded != "" { - return ch.OriginalEncoded - } - return ch.Original -} - -// resolveNewValue returns the best available new value, preferring Encoded. -func resolveNewValue(ch *whatChangedModel.Change) string { - if ch.NewEncoded != "" { - return ch.NewEncoded - } - return ch.New -} - -// renderDiff renders a diff card for a single change. -// newLines/oldLines are pre-split spec lines from the cache. -// The value diff is shown first, then the surrounding spec context. -func renderDiff(ch *whatChangedModel.Change, newLines, oldLines []string, width int, styles consoleStyles) string { - if ch == nil { - return "" - } - - var sb strings.Builder - sb.Grow(width * 40) - - switch ch.ChangeType { - case whatChangedModel.PropertyAdded, whatChangedModel.ObjectAdded: - if hasValueData(ch) { - sb.WriteString(renderDiffHeader(ch, width, styles, false)) - val := resolveNewValue(ch) - sb.WriteString(renderValueOneSided(ch.Property, val, "+", styles.added)) - if ch.Context != nil && ch.Context.NewLine != nil { - s, e := computeBlockRangeForChange(newLines, *ch.Context.NewLine, ch) - hl := highlightRange{start: s, end: e} - sb.WriteString(renderFileContext(newLines, ch.Context.NewLine, hl, ch.ChangeType, width, styles)) - } - } else if ch.Context != nil && ch.Context.NewLine != nil { - sb.WriteString(renderDiffHeader(ch, width, styles, true)) - region, start := extractRegion(newLines, ch.Context.NewLine, regionRadius) - if region == nil { - sb.WriteString(styles.grey.Render(" Added: no line information")) - } else { - sb.WriteString(renderOneSided(region, start, "+", styles.added, styles)) - } - } else { - sb.WriteString(renderDiffHeader(ch, width, styles, true)) - sb.WriteString(styles.grey.Render(" Added: no line information")) - } - - case whatChangedModel.PropertyRemoved, whatChangedModel.ObjectRemoved: - if hasValueData(ch) { - sb.WriteString(renderDiffHeader(ch, width, styles, false)) - val := resolveOldValue(ch) - sb.WriteString(renderValueOneSided(ch.Property, val, "-", styles.removed)) - if ch.Context != nil && ch.Context.OriginalLine != nil { - s, e := computeBlockRangeForChange(oldLines, *ch.Context.OriginalLine, ch) - hl := highlightRange{start: s, end: e} - sb.WriteString(renderFileContext(oldLines, ch.Context.OriginalLine, hl, ch.ChangeType, width, styles)) - } - } else if ch.Context != nil && ch.Context.OriginalLine != nil { - sb.WriteString(renderDiffHeader(ch, width, styles, true)) - region, start := extractRegion(oldLines, ch.Context.OriginalLine, regionRadius) - if region == nil { - sb.WriteString(styles.grey.Render(" Removed: no line information")) - } else { - sb.WriteString(renderOneSided(region, start, "-", styles.removed, styles)) - } - } else { - sb.WriteString(renderDiffHeader(ch, width, styles, true)) - sb.WriteString(styles.grey.Render(" Removed: no line information")) - } - - case whatChangedModel.Modified: - if hasValueData(ch) { - sb.WriteString(renderDiffHeader(ch, width, styles, false)) - oldVal := resolveOldValue(ch) - newVal := resolveNewValue(ch) - sb.WriteString(renderValueDiff(ch.Property, oldVal, newVal, styles)) - if ch.Context != nil && ch.Context.NewLine != nil { - hl := singleLineRange(*ch.Context.NewLine) - sb.WriteString(renderFileContext(newLines, ch.Context.NewLine, hl, ch.ChangeType, width, styles)) - } - } else if ch.Context != nil && - (ch.Context.OriginalLine != nil || ch.Context.NewLine != nil) { - // Tier 1 fallback: file-region diffing - sb.WriteString(renderDiffHeader(ch, width, styles, true)) - oldRegion, oldStart := extractRegion(oldLines, ch.Context.OriginalLine, regionRadius) - newRegion, newStart := extractRegion(newLines, ch.Context.NewLine, regionRadius) - if oldRegion == nil && newRegion == nil { - sb.WriteString(styles.grey.Render(" no line information")) - } else if oldRegion == nil { - sb.WriteString(renderOneSided(newRegion, newStart, "+", styles.added, styles)) - } else if newRegion == nil { - sb.WriteString(renderOneSided(oldRegion, oldStart, "-", styles.removed, styles)) - } else { - sb.WriteString(renderUnifiedDiff(oldRegion, newRegion, oldStart, newStart, styles)) - } - } else { - // Tier 2 fallback: nothing available - sb.WriteString(renderDiffHeader(ch, width, styles, true)) - sb.WriteString(styles.grey.Render(" no line information")) - } - - default: - sb.WriteString(renderDiffHeader(ch, width, styles, true)) - sb.WriteByte('\n') - sb.WriteString(styles.grey.Render(" Unknown change type")) +func (s consoleStyles) diffStyles() diffview.Styles { + return diffview.Styles{ + SelectedRow: s.selectedRow, + RangeHighlight: s.rangeHighlight, + AddedRow: s.addedRow, + AddedRange: s.addedRange, + RemovedRow: s.removedRow, + RemovedRange: s.removedRange, + Added: s.added, + Modified: s.modified, + Removed: s.removed, + Breaking: s.breaking, + Grey: s.grey, + Detail: s.detail, + YAMLKey: s.yamlKey, } - - return sb.String() } -// renderFileContext renders a region of the spec file around the change line, -// with YAML highlighting. Lines in hl.start..hl.end are highlighted using -// change-type-specific styles: green for added, red for removed, pink for modified. -func renderFileContext(lines []string, centerLine *int, hl highlightRange, changeType, width int, styles consoleStyles) string { - if centerLine == nil || len(lines) == 0 { - return "" - } - - idx := *centerLine - 1 - if idx < 0 { - idx = 0 - } - - // Extend the region to include the full highlight range with a little context. - beforeStart := contextBefore - if hl.start > 0 { - desiredStart := hl.start - 3 - if desiredStart < 1 { - desiredStart = 1 - } - neededBefore := idx - (desiredStart - 1) - if neededBefore > beforeStart { - beforeStart = neededBefore - } - } +type highlightRange struct{ start, end int } - afterEnd := contextAfter - if hl.end > 0 { - neededAfter := hl.end + 3 - (idx + 1) - if neededAfter > afterEnd { - afterEnd = neededAfter - } - } - start, end := clampRange(idx, beforeStart, afterEnd, len(lines)) - if start >= end { - return "" - } - region := lines[start:end] - startOffset := start - - // Pick styles and gutter chars based on change type. - primaryStyle, rangeStyle, bodyGutter := contextHighlightStyles(changeType, styles) - - var sb strings.Builder - sb.WriteByte('\n') - sb.WriteString(styles.grey.Render(" ── spec context ──")) - sb.WriteByte('\n') - - lastLine := startOffset + len(region) - numWidth := digitCount(lastLine) - - for i, line := range region { - lineNo := startOffset + i + 1 - numStr := fmt.Sprintf("%*d", numWidth, lineNo) - - if lineNo == hl.start { - // Primary line — bold with > arrow. - content := fmt.Sprintf(" > %s │ %s", numStr, line) - if pad := width - visualLen(content); pad > 0 { - content += strings.Repeat(" ", pad) - } - sb.WriteString(primaryStyle.Render(content)) - } else if lineNo > hl.start && lineNo <= hl.end { - // Body line — gutter marker (+/-/│) before line number. - content := fmt.Sprintf(" %s %s │ %s", bodyGutter, numStr, line) - if pad := width - visualLen(content); pad > 0 { - content += strings.Repeat(" ", pad) - } - sb.WriteString(rangeStyle.Render(content)) - } else { - // Normal context line - sb.WriteString(fmt.Sprintf(" %s %s %s %s", - styles.grey.Render(" "), - styles.grey.Render(numStr), - styles.grey.Render("│"), - highlightLine(line, styles))) - } - sb.WriteByte('\n') - } - return sb.String() -} - -// contextHighlightStyles returns the primary/range styles and body gutter char -// for a given change type. -func contextHighlightStyles(changeType int, styles consoleStyles) (primary, rangeS lipgloss.Style, gutter string) { - switch changeType { - case whatChangedModel.PropertyAdded, whatChangedModel.ObjectAdded: - return styles.addedRow, styles.addedRange, "+" - case whatChangedModel.PropertyRemoved, whatChangedModel.ObjectRemoved: - return styles.removedRow, styles.removedRange, "-" - default: - return styles.selectedRow, styles.rangeHighlight, "│" - } -} - -// renderDiffSummary renders the diff header and value diff for a change, -// without spec context. Used as a fixed header in the code modal. func renderDiffSummary(ch *whatChangedModel.Change, width int, styles consoleStyles) string { - if ch == nil { - return "" - } - var sb strings.Builder - sb.WriteString(renderDiffHeader(ch, width, styles, false)) - - switch ch.ChangeType { - case whatChangedModel.PropertyAdded, whatChangedModel.ObjectAdded: - if hasValueData(ch) { - val := resolveNewValue(ch) - sb.WriteString(renderValueOneSided(ch.Property, val, "+", styles.added)) - } - case whatChangedModel.PropertyRemoved, whatChangedModel.ObjectRemoved: - if hasValueData(ch) { - val := resolveOldValue(ch) - sb.WriteString(renderValueOneSided(ch.Property, val, "-", styles.removed)) - } - case whatChangedModel.Modified: - if hasValueData(ch) { - oldVal := resolveOldValue(ch) - newVal := resolveNewValue(ch) - sb.WriteString(renderValueDiff(ch.Property, oldVal, newVal, styles)) - } - } - return sb.String() -} - -// renderValueDiff renders a diff of the change's own values (primary path for Modified). -func renderValueDiff(property, oldVal, newVal string, styles consoleStyles) string { - var sb strings.Builder - - isMultiOld := strings.Contains(oldVal, "\n") - isMultiNew := strings.Contains(newVal, "\n") - - if !isMultiOld && !isMultiNew { - // Single-line path - if oldVal == newVal { - sb.WriteString(styles.grey.Render(" (values are identical)")) - sb.WriteByte('\n') - return sb.String() - } - sb.WriteString(styles.removed.Render(fmt.Sprintf(" - %s: %s", property, oldVal))) - sb.WriteByte('\n') - sb.WriteString(styles.added.Render(fmt.Sprintf(" + %s: %s", property, newVal))) - sb.WriteByte('\n') - return sb.String() - } - - // Multi-line path: use difflib - diff, err := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{ - A: appendNewlines(strings.Split(oldVal, "\n")), - B: appendNewlines(strings.Split(newVal, "\n")), - Context: diffContext, - }) - if err != nil || diff == "" { - sb.WriteString(styles.grey.Render(" (values are identical)")) - sb.WriteByte('\n') - return sb.String() - } - - for _, line := range strings.Split(strings.TrimRight(diff, "\n"), "\n") { - if hunkHeaderRe.MatchString(line) { - // Line numbers are already 1-based relative to the value — no rewriting needed - sb.WriteString(styles.grey.Render(" " + line)) - } else if strings.HasPrefix(line, "-") { - sb.WriteString(styles.removed.Render(" " + line)) - } else if strings.HasPrefix(line, "+") { - sb.WriteString(styles.added.Render(" " + line)) - } else { - sb.WriteString(" " + highlightLine(strings.TrimPrefix(line, " "), styles)) - } - sb.WriteByte('\n') - } - return sb.String() + return diffview.RenderSummary(ch, width, styles.diffStyles()) } - -// renderValueOneSided renders a one-sided view of a change's value (primary path for Added/Removed). -func renderValueOneSided(property, val, prefix string, style lipgloss.Style) string { - var sb strings.Builder - - if !strings.Contains(val, "\n") { - // Single-line - sb.WriteString(style.Render(fmt.Sprintf(" %s %s: %s", prefix, property, val))) - sb.WriteByte('\n') - return sb.String() - } - - // Multi-line - for _, line := range strings.Split(val, "\n") { - sb.WriteString(style.Render(fmt.Sprintf(" %s %s", prefix, line))) - sb.WriteByte('\n') - } - return sb.String() +func renderDiff(ch *whatChangedModel.Change, newLines, oldLines []string, width int, styles consoleStyles) string { + source := resolveChangeSource(ch, newLines, oldLines) + return diffview.RenderChange(ch, source, width, styles.diffStyles()) } - -// extractRegion extracts a region of lines centered on lineNum with the given radius. -// Returns nil if lineNum is nil or lines is empty. -// The returned int is the 0-based start offset of the region within lines. -func extractRegion(lines []string, lineNum *int, radius int) ([]string, int) { - if lineNum == nil || len(lines) == 0 { - return nil, 0 - } - idx := *lineNum - 1 - if idx < 0 { - idx = 0 - } - start, end := clampRange(idx, radius, radius, len(lines)) - return lines[start:end], start +func computeBlockRangeForChange(lines []string, line int, ch *whatChangedModel.Change) (int, int) { + r := diffview.RangeForChange(lines, line, ch) + return r.Start, r.End } - -// renderOneSided renders a one-sided view for Added or Removed changes (file-region fallback). -func renderOneSided(region []string, startOffset int, prefix string, style lipgloss.Style, styles consoleStyles) string { - var sb strings.Builder - - firstLine := startOffset + 1 - lastLine := startOffset + len(region) - sb.WriteString(styles.grey.Render(fmt.Sprintf(" Lines %d\u2013%d:", firstLine, lastLine))) - sb.WriteByte('\n') - - numWidth := digitCount(lastLine) - for i, line := range region { - lineNo := startOffset + i + 1 - numStr := fmt.Sprintf("%*d", numWidth, lineNo) - sb.WriteString(style.Render(fmt.Sprintf(" %s %s│ %s", prefix, numStr, line))) - sb.WriteByte('\n') - } - return sb.String() +func renderSpecLines(lines []string, hl highlightRange, changeType, width int, styles consoleStyles) string { + return diffview.RenderSource(lines, diffview.Range{Start: hl.start, End: hl.end}, changeType, width, styles.diffStyles()) } -// renderUnifiedDiff computes and renders a real unified diff between two regions (file-region fallback). -func renderUnifiedDiff(oldRegion, newRegion []string, oldStart, newStart int, styles consoleStyles) string { - diff, err := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{ - A: appendNewlines(oldRegion), - B: appendNewlines(newRegion), - Context: diffContext, - }) - if err != nil || diff == "" { - return styles.grey.Render(" (no differences in this region)") + "\n" +// resolveChangeSource accepts root coordinates only. A missing candidate +// coordinate cannot be replaced by an original coordinate after edits. +func resolveChangeSource(ch *whatChangedModel.Change, newLines, oldLines []string) diffview.Source { + if ch == nil || ch.Context == nil || ch.Context.DocumentLocation != "" { + return diffview.Source{} } - - var sb strings.Builder - for _, line := range strings.Split(strings.TrimRight(diff, "\n"), "\n") { - if hunkHeaderRe.MatchString(line) { - sb.WriteString(styles.grey.Render(" " + rewriteHunkHeader(line, oldStart, newStart))) - } else if strings.HasPrefix(line, "-") { - sb.WriteString(styles.removed.Render(" " + line)) - } else if strings.HasPrefix(line, "+") { - sb.WriteString(styles.added.Render(" " + line)) - } else { - // Context line (starts with space) - sb.WriteString(" " + highlightLine(strings.TrimPrefix(line, " "), styles)) + source := diffview.Source{Lines: newLines, Side: diffview.Candidate} + if ch.ChangeType == whatChangedModel.PropertyRemoved || ch.ChangeType == whatChangedModel.ObjectRemoved { + source.Lines, source.Side = oldLines, diffview.Original + if ch.Context.OriginalLine != nil { + source.Line = *ch.Context.OriginalLine } - sb.WriteByte('\n') - } - return sb.String() -} - -// rewriteHunkHeader adjusts the line numbers in a @@ hunk header by adding region offsets. -func rewriteHunkHeader(header string, oldStart, newStart int) string { - m := hunkHeaderRe.FindStringSubmatch(header) - if m == nil { - return header - } - - oldLine, _ := strconv.Atoi(m[1]) - oldLine += oldStart - newLine, _ := strconv.Atoi(m[3]) - newLine += newStart - - oldPart := fmt.Sprintf("%d", oldLine) - if m[2] != "" { - oldPart += "," + m[2] + } else if ch.Context.NewLine != nil { + source.Line = *ch.Context.NewLine } - newPart := fmt.Sprintf("%d", newLine) - if m[4] != "" { - newPart += "," + m[4] + if source.Line < 1 || source.Line > len(source.Lines) { + return diffview.Source{} } - - return fmt.Sprintf("@@ -%s +%s @@", oldPart, newPart) + return source } - -// renderDiffHeader renders the metadata card at the top of the diff. -// When showValues is false, the Original/New/Value rows are suppressed -// (because the diff body already shows the values). -func renderDiffHeader(ch *whatChangedModel.Change, width int, styles consoleStyles, showValues bool) string { - var sb strings.Builder - - // Action label - action := changeAction(ch.ChangeType) - actionStyle := changeStyle(ch.ChangeType, styles) - - sb.WriteString(actionStyle.Render(fmt.Sprintf(" %s: %s", action, ch.Property))) - sb.WriteByte('\n') - - // Breaking indicator - if ch.Breaking { - sb.WriteString(styles.breaking.Render(" BREAKING CHANGE")) - sb.WriteByte('\n') - } - - // Values (only when diff body doesn't show them) - if showValues { - origVal := resolveOldValue(ch) - newVal := resolveNewValue(ch) - - // Truncate long values - maxVal := width/2 - 20 - if maxVal < 20 { - maxVal = 20 - } - - switch ch.ChangeType { - case whatChangedModel.PropertyAdded, whatChangedModel.ObjectAdded: - if newVal != "" { - sb.WriteString(styles.added.Render(fmt.Sprintf(" Value: %s", truncateStr(newVal, maxVal)))) - sb.WriteByte('\n') - } - case whatChangedModel.PropertyRemoved, whatChangedModel.ObjectRemoved: - if origVal != "" { - sb.WriteString(styles.removed.Render(fmt.Sprintf(" Value: %s", truncateStr(origVal, maxVal)))) - sb.WriteByte('\n') - } - case whatChangedModel.Modified: - if origVal != "" || newVal != "" { - sb.WriteString(fmt.Sprintf(" %s %s %s %s", - styles.grey.Render("Original:"), - truncateStr(origVal, maxVal), - styles.grey.Render("->"), - truncateStr(newVal, maxVal))) - sb.WriteByte('\n') - } - } - } - - // Blank line separating header from diff content - sb.WriteByte('\n') - - return sb.String() -} - -func changeAction(ct int) string { - switch ct { - case whatChangedModel.PropertyAdded, whatChangedModel.ObjectAdded: - return "Added" - case whatChangedModel.PropertyRemoved, whatChangedModel.ObjectRemoved: - return "Removed" - case whatChangedModel.Modified: - return "Modified" - default: - return "Changed" - } -} - -func changeStyle(ct int, styles consoleStyles) lipgloss.Style { - switch ct { - case whatChangedModel.PropertyAdded, whatChangedModel.ObjectAdded: - return styles.added - case whatChangedModel.PropertyRemoved, whatChangedModel.ObjectRemoved: - return styles.removed - case whatChangedModel.Modified: - return styles.modified - default: - return styles.grey - } -} - -// appendNewlines converts lines to the newline-terminated format difflib expects. -func appendNewlines(lines []string) []string { - out := make([]string, len(lines)) - for i, l := range lines { - out[i] = l + "\n" - } - return out -} - -func truncateStr(s string, max int) string { - runes := []rune(s) - if len(runes) <= max { - return s - } - return string(runes[:max-3]) + "..." -} - -func digitCount(n int) int { - if n <= 0 { - return 1 - } - d := 0 - for n > 0 { - n /= 10 - d++ - } - return d -} - -// resolveSpecAndLine picks the correct spec lines and change line number -// based on change type. Removals use oldLines + OriginalLine; everything -// else uses newLines + NewLine (with OriginalLine fallback). -func resolveSpecAndLine(ch *whatChangedModel.Change, newLines, oldLines []string) (lines []string, changeLn int) { - switch ch.ChangeType { - case whatChangedModel.PropertyRemoved, whatChangedModel.ObjectRemoved: - lines = oldLines - if ch.Context != nil && ch.Context.OriginalLine != nil { - changeLn = *ch.Context.OriginalLine - } - default: - lines = newLines - if ch.Context != nil && ch.Context.NewLine != nil { - changeLn = *ch.Context.NewLine - } else if ch.Context != nil && ch.Context.OriginalLine != nil { - changeLn = *ch.Context.OriginalLine - } - } - return -} - -// renderSpecLines renders all spec lines with highlight formatting matching -// the code modal style. The primary line gets "> NNN│", body lines get -// "{gutter} NNN│", and normal lines get grey line numbers with YAML -// key highlighting. Returns all lines joined with \n. -func renderSpecLines(lines []string, hl highlightRange, changeType int, contentW int, styles consoleStyles) string { - primaryStyle, rangeStyle, bodyGutter := contextHighlightStyles(changeType, styles) - - numWidth := digitCount(len(lines)) - var sb strings.Builder - sb.Grow(len(lines) * (numWidth + contentW + 20)) - - for i, line := range lines { - if i > 0 { - sb.WriteByte('\n') - } - lineNo := i + 1 - numStr := fmt.Sprintf("%*d", numWidth, lineNo) - if lineNo == hl.start { - content := fmt.Sprintf("> %s│ %s", numStr, line) - if pad := contentW - visualLen(content); pad > 0 { - content += strings.Repeat(" ", pad) - } - sb.WriteString(primaryStyle.Render(content)) - } else if lineNo > hl.start && lineNo <= hl.end { - content := fmt.Sprintf("%s %s│ %s", bodyGutter, numStr, line) - if pad := contentW - visualLen(content); pad > 0 { - content += strings.Repeat(" ", pad) - } - sb.WriteString(rangeStyle.Render(content)) - } else { - sb.WriteString(fmt.Sprintf(" %s%s %s", - styles.grey.Render(numStr), - styles.grey.Render("│"), - highlightLine(line, styles))) - } - } - return sb.String() +func resolveSpecAndLine(ch *whatChangedModel.Change, newLines, oldLines []string) ([]string, int) { + source := resolveChangeSource(ch, newLines, oldLines) + return source.Lines, source.Line } diff --git a/tui/v2/diff_test.go b/tui/v2/diff_test.go index 50bc34f..e0f62b2 100644 --- a/tui/v2/diff_test.go +++ b/tui/v2/diff_test.go @@ -1,643 +1,12 @@ -// Copyright 2023-2026 Princess Beef Heavy Industries, LLC / Dave Shanley -// SPDX-License-Identifier: Apache-2.0 - package v2 import ( - "fmt" - "strings" - "testing" - whatChangedModel "github.com/pb33f/libopenapi/what-changed/model" "github.com/pb33f/testify/assert" + "testing" ) func ptrInt(n int) *int { return &n } - -var testStyles = newConsoleStyles() - -func TestRenderDiff_Modified(t *testing.T) { - ch := &whatChangedModel.Change{ - ChangeType: whatChangedModel.Modified, - Property: "description", - Original: "old desc", - New: "new desc", - Context: &whatChangedModel.ChangeContext{ - OriginalLine: ptrInt(5), - NewLine: ptrInt(5), - }, - } - - result := renderDiff(ch, nil, nil, 140, testStyles) - assert.Contains(t, result, "Modified") - assert.Contains(t, result, "description") - // Value-based: should show property with old/new values - assert.Contains(t, result, "- description: old desc") - assert.Contains(t, result, "+ description: new desc") - // Single-line value diff should NOT have @@ headers - assert.NotContains(t, result, "@@") -} - -func TestRenderDiff_Added(t *testing.T) { - ch := &whatChangedModel.Change{ - ChangeType: whatChangedModel.PropertyAdded, - Property: "newProp", - New: "value", - Context: &whatChangedModel.ChangeContext{ - NewLine: ptrInt(3), - }, - } - - result := renderDiff(ch, nil, nil, 140, testStyles) - assert.Contains(t, result, "Added") - assert.Contains(t, result, "newProp") - // Value-based: should show + prefixed property - assert.Contains(t, result, "+ newProp: value") -} - -func TestRenderDiff_Removed(t *testing.T) { - ch := &whatChangedModel.Change{ - ChangeType: whatChangedModel.PropertyRemoved, - Property: "removedProp", - Original: "was here", - Breaking: true, - Context: &whatChangedModel.ChangeContext{ - OriginalLine: ptrInt(4), - }, - } - - result := renderDiff(ch, nil, nil, 140, testStyles) - assert.Contains(t, result, "Removed") - assert.Contains(t, result, "BREAKING") - assert.Contains(t, result, "removedProp") - // Value-based: should show - prefixed property - assert.Contains(t, result, "- removedProp: was here") -} - -func TestRenderDiff_NilChange(t *testing.T) { - assert.Equal(t, "", renderDiff(nil, nil, nil, 80, testStyles)) -} - -func TestRenderDiff_NilLineNum(t *testing.T) { - ch := &whatChangedModel.Change{ - ChangeType: whatChangedModel.Modified, - Property: "test", - Context: &whatChangedModel.ChangeContext{}, - } - - result := renderDiff(ch, nil, nil, 80, testStyles) - assert.Contains(t, result, "no line information") -} - -func TestRenderDiff_EncodedValues(t *testing.T) { - ch := &whatChangedModel.Change{ - ChangeType: whatChangedModel.Modified, - Property: "schema", - Original: "simple", - New: "simple", - OriginalEncoded: "type: object\nproperties:\n name: string", - NewEncoded: "type: object\nproperties:\n name: integer", - Context: &whatChangedModel.ChangeContext{ - OriginalLine: ptrInt(1), - NewLine: ptrInt(1), - }, - } - - result := renderDiff(ch, nil, nil, 140, testStyles) - // Should prefer encoded values and show multi-line diff - assert.Contains(t, result, "type:") - assert.Contains(t, result, "object") - assert.Contains(t, result, "- name: string") - assert.Contains(t, result, "+ name: integer") - assert.Contains(t, result, "@@") -} - -func TestRenderDiff_MultiLineEncoded(t *testing.T) { - ch := &whatChangedModel.Change{ - ChangeType: whatChangedModel.Modified, - Property: "schema", - OriginalEncoded: "type: object\nproperties:\n name: string", - NewEncoded: "type: object\nproperties:\n name: integer\n age: integer", - Context: &whatChangedModel.ChangeContext{ - OriginalLine: ptrInt(10), - NewLine: ptrInt(10), - }, - } - - result := renderDiff(ch, nil, nil, 120, testStyles) - assert.Contains(t, result, "@@") - // Lines should be properly separated (not concatenated) - assert.Contains(t, result, "- name: string") - assert.Contains(t, result, "+ name: integer") - assert.Contains(t, result, "+ age: integer") -} - -func TestRenderDiff_IdenticalValues(t *testing.T) { - ch := &whatChangedModel.Change{ - ChangeType: whatChangedModel.Modified, - Property: "test", - Original: "same value", - New: "same value", - Context: &whatChangedModel.ChangeContext{ - OriginalLine: ptrInt(3), - NewLine: ptrInt(3), - }, - } - - result := renderDiff(ch, nil, nil, 120, testStyles) - assert.Contains(t, result, "(values are identical)") -} - -func TestRenderDiff_YAMLDocMarker(t *testing.T) { - // YAML --- document marker in encoded values should be preserved - ch := &whatChangedModel.Change{ - ChangeType: whatChangedModel.Modified, - Property: "schema", - OriginalEncoded: "---\nopenapi: '3.0.0'\ninfo:\n title: Old", - NewEncoded: "---\nopenapi: '3.0.0'\ninfo:\n title: New", - Context: &whatChangedModel.ChangeContext{ - OriginalLine: ptrInt(1), - NewLine: ptrInt(1), - }, - } - - result := renderDiff(ch, nil, nil, 120, testStyles) - // The YAML --- should appear in the diff output - assert.Contains(t, result, "---") -} - -func TestRenderDiff_FallbackToFileRegion(t *testing.T) { - // Modified with no values but valid line numbers → tier 1 fallback - oldLines := make([]string, 20) - newLines := make([]string, 20) - for i := 0; i < 20; i++ { - oldLines[i] = fmt.Sprintf("line%d: value", i) - newLines[i] = fmt.Sprintf("line%d: value", i) - } - oldLines[4] = "description: old" - newLines[4] = "description: new" - - ch := &whatChangedModel.Change{ - ChangeType: whatChangedModel.Modified, - Property: "test", - // No Original/New/Encoded/Object fields → hasValueData returns false - Context: &whatChangedModel.ChangeContext{ - OriginalLine: ptrInt(5), - NewLine: ptrInt(5), - }, - } - - result := renderDiff(ch, newLines, oldLines, 120, testStyles) - // Should fall back to file-region diff with @@ headers - assert.Contains(t, result, "@@") - assert.Contains(t, result, "-description: old") - assert.Contains(t, result, "+description: new") - // Fallback shows values in header - assert.NotContains(t, result, "no line information") -} - -func TestRenderDiff_OneSidedLabel(t *testing.T) { - // Added with value: shows value-based rendering, no "Lines N–M:" label - ch := &whatChangedModel.Change{ - ChangeType: whatChangedModel.PropertyAdded, - Property: "prop", - New: "val", - Context: &whatChangedModel.ChangeContext{ - NewLine: ptrInt(5), - }, - } - - result := renderDiff(ch, nil, nil, 120, testStyles) - assert.Contains(t, result, "+ prop: val") - assert.NotContains(t, result, "Lines") - assert.NotContains(t, result, "@@") -} - -func TestRenderDiff_SingleLineModified(t *testing.T) { - // Scalar Original/New, no Encoded → two-line diff, no @@ - ch := &whatChangedModel.Change{ - ChangeType: whatChangedModel.Modified, - Property: "version", - Original: "1.0.0", - New: "2.0.0", - Context: &whatChangedModel.ChangeContext{ - OriginalLine: ptrInt(2), - NewLine: ptrInt(2), - }, - } - - result := renderDiff(ch, nil, nil, 120, testStyles) - assert.Contains(t, result, "- version: 1.0.0") - assert.Contains(t, result, "+ version: 2.0.0") - assert.NotContains(t, result, "@@") -} - -func TestRenderDiff_AddedMultiLine(t *testing.T) { - ch := &whatChangedModel.Change{ - ChangeType: whatChangedModel.PropertyAdded, - Property: "schema", - NewEncoded: "type: object\nproperties:\n name: string", - Context: &whatChangedModel.ChangeContext{ - NewLine: ptrInt(10), - }, - } - - result := renderDiff(ch, nil, nil, 120, testStyles) - assert.Contains(t, result, "+ type: object") - assert.Contains(t, result, "+ properties:") - assert.Contains(t, result, "+ name: string") - assert.NotContains(t, result, "@@") -} - -func TestRenderDiff_RemovedMultiLine(t *testing.T) { - ch := &whatChangedModel.Change{ - ChangeType: whatChangedModel.PropertyRemoved, - Property: "schema", - OriginalEncoded: "type: array\nitems:\n type: string", - Breaking: true, - Context: &whatChangedModel.ChangeContext{ - OriginalLine: ptrInt(5), - }, - } - - result := renderDiff(ch, nil, nil, 120, testStyles) - assert.Contains(t, result, "BREAKING") - assert.Contains(t, result, "- type: array") - assert.Contains(t, result, "- items:") - assert.Contains(t, result, "- type: string") - assert.NotContains(t, result, "@@") -} - -func TestRenderDiff_EncodedPreferredOverPlain(t *testing.T) { - ch := &whatChangedModel.Change{ - ChangeType: whatChangedModel.Modified, - Property: "schema", - Original: "plain-old", - New: "plain-new", - OriginalEncoded: "encoded: old-value", - NewEncoded: "encoded: new-value", - Context: &whatChangedModel.ChangeContext{ - OriginalLine: ptrInt(1), - NewLine: ptrInt(1), - }, - } - - result := renderDiff(ch, nil, nil, 120, testStyles) - // Should use Encoded content, not plain - assert.Contains(t, result, "encoded: old-value") - assert.Contains(t, result, "encoded: new-value") - assert.NotContains(t, result, "plain-old") - assert.NotContains(t, result, "plain-new") -} - -func TestRenderDiff_EmptyStringValue(t *testing.T) { - // Added with New: "" but NewObject: "" (non-nil interface) → renders via value path - ch := &whatChangedModel.Change{ - ChangeType: whatChangedModel.PropertyAdded, - Property: "emptyField", - New: "", - NewObject: "", // non-nil any value - Context: &whatChangedModel.ChangeContext{ - NewLine: ptrInt(5), - }, - } - - result := renderDiff(ch, nil, nil, 120, testStyles) - // Should use value path (not fallback) - assert.Contains(t, result, "+ emptyField:") - assert.NotContains(t, result, "no line information") -} - -func TestRenderDiff_HeaderNoValueDuplication(t *testing.T) { - // Modified with values → header should NOT show "Original: X -> Y" - ch := &whatChangedModel.Change{ - ChangeType: whatChangedModel.Modified, - Property: "title", - Original: "Old Title", - New: "New Title", - Context: &whatChangedModel.ChangeContext{ - OriginalLine: ptrInt(3), - NewLine: ptrInt(3), - }, - } - - result := renderDiff(ch, nil, nil, 140, testStyles) - assert.NotContains(t, result, "Original:") - assert.NotContains(t, result, "->") - // But should show the diff body - assert.Contains(t, result, "- title: Old Title") - assert.Contains(t, result, "+ title: New Title") -} - -func TestRenderDiff_IdenticalValuesSingleLine(t *testing.T) { - // Specifically tests the explicit oldVal == newVal check (not difflib empty output) - ch := &whatChangedModel.Change{ - ChangeType: whatChangedModel.Modified, - Property: "format", - Original: "int64", - New: "int64", - Context: &whatChangedModel.ChangeContext{ - OriginalLine: ptrInt(10), - NewLine: ptrInt(10), - }, - } - - result := renderDiff(ch, nil, nil, 120, testStyles) - assert.Contains(t, result, "(values are identical)") - // Should NOT show diff lines - assert.NotContains(t, result, "- format:") - assert.NotContains(t, result, "+ format:") -} - -func TestRenderDiff_NoValuesNoLines(t *testing.T) { - // Modified with all fields empty/nil → tier 2 fallback - ch := &whatChangedModel.Change{ - ChangeType: whatChangedModel.Modified, - Property: "unknown", - Context: &whatChangedModel.ChangeContext{}, - } - - result := renderDiff(ch, nil, nil, 120, testStyles) - assert.Contains(t, result, "no line information") -} - -func TestRenderDiff_FallbackOneSideNil(t *testing.T) { - // Modified fallback with only NewLine set → renders one-sided + view - newLines := []string{"line1", "line2", "line3", "line4", "line5"} - - ch := &whatChangedModel.Change{ - ChangeType: whatChangedModel.Modified, - Property: "test", - Context: &whatChangedModel.ChangeContext{ - NewLine: ptrInt(3), - }, - } - - result := renderDiff(ch, newLines, nil, 120, testStyles) - assert.Contains(t, result, "+") - assert.NotContains(t, result, "no line information") -} - -func TestHasValueData(t *testing.T) { - tests := []struct { - name string - change *whatChangedModel.Change - want bool - }{ - {"original set", &whatChangedModel.Change{Original: "x"}, true}, - {"new set", &whatChangedModel.Change{New: "x"}, true}, - {"original encoded set", &whatChangedModel.Change{OriginalEncoded: "x"}, true}, - {"new encoded set", &whatChangedModel.Change{NewEncoded: "x"}, true}, - {"original object set", &whatChangedModel.Change{OriginalObject: "x"}, true}, - {"new object set", &whatChangedModel.Change{NewObject: ""}, true}, // empty string is non-nil - {"all empty", &whatChangedModel.Change{}, false}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - assert.Equal(t, tt.want, hasValueData(tt.change)) - }) - } -} - -func TestRenderValueDiff_MultiLineIdentical(t *testing.T) { - // Multi-line values that are identical → difflib returns empty → "(values are identical)" - val := "type: object\nproperties:\n name: string" - result := renderValueDiff("schema", val, val, testStyles) - assert.Contains(t, result, "(values are identical)") -} - -func TestRenderValueOneSided_SingleLine(t *testing.T) { - result := renderValueOneSided("prop", "hello", "+", testStyles.added) - assert.Contains(t, result, "+ prop: hello") - // Should be single line output - lines := strings.Split(strings.TrimRight(result, "\n"), "\n") - assert.Equal(t, 1, len(lines)) -} - -func TestRenderValueOneSided_MultiLine(t *testing.T) { - result := renderValueOneSided("prop", "line1\nline2\nline3", "-", testStyles.removed) - assert.Contains(t, result, "- line1") - assert.Contains(t, result, "- line2") - assert.Contains(t, result, "- line3") -} - -func TestRenderDiff_ModifiedWithContext(t *testing.T) { - // When spec lines are provided, the value diff should be followed by spec context - specLines := make([]string, 30) - for i := range specLines { - specLines[i] = fmt.Sprintf("spec-line-%d: content", i) - } - specLines[9] = "description: new desc" - - ch := &whatChangedModel.Change{ - ChangeType: whatChangedModel.Modified, - Property: "description", - Original: "old desc", - New: "new desc", - Context: &whatChangedModel.ChangeContext{ - OriginalLine: ptrInt(10), - NewLine: ptrInt(10), - }, - } - - result := renderDiff(ch, specLines, specLines, 140, testStyles) - // Value diff at top - assert.Contains(t, result, "- description: old desc") - assert.Contains(t, result, "+ description: new desc") - // Spec context section below - assert.Contains(t, result, "spec context") - // Should show surrounding spec lines with line numbers - assert.Contains(t, result, "spec-line-") - // The change line should be highlighted with > - assert.Contains(t, result, ">") - assert.Contains(t, result, "10 │") -} - -func TestRenderDiff_AddedWithContext(t *testing.T) { - specLines := make([]string, 20) - for i := range specLines { - specLines[i] = fmt.Sprintf("line-%d: yaml", i) - } - - ch := &whatChangedModel.Change{ - ChangeType: whatChangedModel.PropertyAdded, - Property: "newProp", - New: "value", - Context: &whatChangedModel.ChangeContext{ - NewLine: ptrInt(5), - }, - } - - result := renderDiff(ch, specLines, nil, 120, testStyles) - assert.Contains(t, result, "+ newProp: value") - assert.Contains(t, result, "spec context") - assert.Contains(t, result, "line-") -} - -func TestRenderDiff_NoContextWhenNoLines(t *testing.T) { - // When no spec lines provided, no context section should appear - ch := &whatChangedModel.Change{ - ChangeType: whatChangedModel.Modified, - Property: "description", - Original: "old", - New: "new", - Context: &whatChangedModel.ChangeContext{ - OriginalLine: ptrInt(5), - NewLine: ptrInt(5), - }, - } - - result := renderDiff(ch, nil, nil, 120, testStyles) - assert.Contains(t, result, "- description: old") - assert.Contains(t, result, "+ description: new") - assert.NotContains(t, result, "spec context") -} - -func TestRenderFileContext(t *testing.T) { - lines := []string{"line0", "line1", "line2", "line3", "line4"} - center := 3 - - result := renderFileContext(lines, ¢er, singleLineRange(3), whatChangedModel.Modified, 120, testStyles) - assert.Contains(t, result, "spec context") - // Line 3 should be highlighted with > - assert.Contains(t, result, ">") - assert.Contains(t, result, "3 │") - // Other lines should also appear - assert.Contains(t, result, "line0") - assert.Contains(t, result, "line4") -} - -func TestRenderFileContext_NilCenter(t *testing.T) { - lines := []string{"a", "b", "c"} - result := renderFileContext(lines, nil, singleLineRange(1), whatChangedModel.Modified, 120, testStyles) - assert.Equal(t, "", result) -} - -func TestRenderFileContext_EmptyLines(t *testing.T) { - center := 1 - result := renderFileContext(nil, ¢er, singleLineRange(1), whatChangedModel.Modified, 120, testStyles) - assert.Equal(t, "", result) -} - -func TestRenderFileContext_RangeHighlight(t *testing.T) { - lines := []string{ - "openapi: '3.0'", - "paths:", - " /pets:", - " get:", - " summary: List pets", - " responses:", - " 200:", - " description: OK", - " /users:", - " get:", - } - center := 3 - hl := highlightRange{start: 3, end: 8} - - result := renderFileContext(lines, ¢er, hl, whatChangedModel.ObjectAdded, 120, testStyles) - assert.Contains(t, result, "spec context") - // Primary line should have > marker - assert.Contains(t, result, ">") - // Body lines should have + gutter marker for ObjectAdded - assert.Contains(t, result, "+") - // All highlighted lines should appear (keys are ANSI-styled separately) - assert.Contains(t, result, "/pets:") - assert.Contains(t, result, "description:") - assert.Contains(t, result, "OK") - // Context line after range should appear - assert.Contains(t, result, "/users:") -} - -func TestRenderFileContext_IncludesHighlightStartAboveCenter(t *testing.T) { - lines := []string{ - "line 1", - "line 2", - "line 3", - "line 4", - "line 5", - "line 6", - "line 7", - "line 8", - "line 9", - "line 10", - "line 11", - "line 12", - } - center := 10 - hl := highlightRange{start: 3, end: 10} - - result := renderFileContext(lines, ¢er, hl, whatChangedModel.ObjectRemoved, 120, newNoColorStyles()) - assert.Contains(t, result, "spec context") - assert.Contains(t, result, "> 3") - assert.Contains(t, result, "line 3") - assert.Contains(t, result, "line 10") -} - -// --- renderSpecLines tests --- - -func TestRenderSpecLines_Added(t *testing.T) { - lines := []string{"openapi: '3.0'", "info:", " title: Test", "paths: {}"} - hl := highlightRange{start: 3, end: 3} - styles := newNoColorStyles() - - result := renderSpecLines(lines, hl, whatChangedModel.PropertyAdded, 80, styles) - // Primary line should have > marker - assert.Contains(t, result, ">") - assert.Contains(t, result, "3│") - // Normal lines should have line numbers - assert.Contains(t, result, "1│") - assert.Contains(t, result, "openapi:") -} - -func TestRenderSpecLines_Removed(t *testing.T) { - lines := []string{"a: 1", "b: 2", "c: 3"} - hl := highlightRange{start: 2, end: 2} - styles := newNoColorStyles() - - result := renderSpecLines(lines, hl, whatChangedModel.PropertyRemoved, 80, styles) - assert.Contains(t, result, ">") - assert.Contains(t, result, "2│") -} - -func TestRenderSpecLines_Modified(t *testing.T) { - lines := []string{"a: 1", "b: 2", "c: 3"} - hl := highlightRange{start: 2, end: 2} - styles := newNoColorStyles() - - result := renderSpecLines(lines, hl, whatChangedModel.Modified, 80, styles) - assert.Contains(t, result, ">") - assert.Contains(t, result, "2│") -} - -func TestRenderSpecLines_EmptyHighlight(t *testing.T) { - lines := []string{"a: 1", "b: 2", "c: 3"} - hl := highlightRange{start: 0, end: 0} - styles := newNoColorStyles() - - // Should not crash — all lines rendered as normal - result := renderSpecLines(lines, hl, whatChangedModel.Modified, 80, styles) - assert.Contains(t, result, "1│") - assert.Contains(t, result, "2│") - assert.Contains(t, result, "3│") - assert.NotContains(t, result, ">") -} - -func TestRenderSpecLines_RangeHighlight(t *testing.T) { - lines := []string{"a: 1", "b: 2", "c: 3", "d: 4", "e: 5"} - hl := highlightRange{start: 2, end: 4} - styles := newNoColorStyles() - - result := renderSpecLines(lines, hl, whatChangedModel.ObjectAdded, 80, styles) - // Primary line 2 should have > - assert.Contains(t, result, ">") - // Body lines 3-4 should have + gutter for ObjectAdded - assert.Contains(t, result, "+") -} - -// --- resolveSpecAndLine tests --- - func TestResolveSpecAndLine_Removed(t *testing.T) { newLines := []string{"new1", "new2"} oldLines := []string{"old1", "old2"} @@ -687,7 +56,7 @@ func TestResolveSpecAndLine_Modified(t *testing.T) { assert.Equal(t, 2, changeLn) // prefers NewLine } -func TestResolveSpecAndLine_ModifiedFallbackToOriginal(t *testing.T) { +func TestResolveSpecAndLine_MissingCandidateCoordinate(t *testing.T) { newLines := []string{"new1", "new2"} oldLines := []string{"old1", "old2"} @@ -699,8 +68,8 @@ func TestResolveSpecAndLine_ModifiedFallbackToOriginal(t *testing.T) { } lines, changeLn := resolveSpecAndLine(ch, newLines, oldLines) - assert.Equal(t, newLines, lines) - assert.Equal(t, 1, changeLn) // falls back to OriginalLine + assert.Empty(t, lines) + assert.Equal(t, 0, changeLn) } func TestResolveSpecAndLine_NilContext(t *testing.T) { @@ -712,6 +81,30 @@ func TestResolveSpecAndLine_NilContext(t *testing.T) { } lines, changeLn := resolveSpecAndLine(ch, newLines, oldLines) - assert.Equal(t, newLines, lines) - assert.Equal(t, 0, changeLn) // no line info + assert.Empty(t, lines) + assert.Equal(t, 0, changeLn) +} + +func TestResolveSpecAndLine_ExternalSourceIsNotRoot(t *testing.T) { + ch := &whatChangedModel.Change{ChangeType: whatChangedModel.Modified, Context: &whatChangedModel.ChangeContext{DocumentLocation: "schemas/pet.yaml", NewLine: ptrInt(1)}} + lines, line := resolveSpecAndLine(ch, []string{"unrelated: root"}, []string{"old: root"}) + assert.Empty(t, lines) + assert.Zero(t, line) + assert.NotContains(t, renderDiff(ch, []string{"unrelated: root"}, nil, 80, newNoColorStyles()), "unrelated: root") } + +func TestDiffAdapterPreservesSemanticCardAndCodeLines(t *testing.T) { + ch := &whatChangedModel.Change{ChangeType: whatChangedModel.Modified, Property: "description", Original: "old", New: "new", Breaking: true, Context: &whatChangedModel.ChangeContext{NewLine: ptrInt(2)}} + lines := []string{"Pet:", " description: new"} + card := renderDiff(ch, lines, nil, 80, newNoColorStyles()) + assert.Contains(t, card, "Modified: description") + assert.Contains(t, card, "BREAKING CHANGE") + assert.Contains(t, card, "- description: old") + assert.Contains(t, card, "+ description: new") + assert.Contains(t, card, "> 2") + source := renderSpecLines(lines, highlightRange{2, 2}, ch.ChangeType, 80, newNoColorStyles()) + assert.Contains(t, source, "1│ Pet:") + assert.Contains(t, source, "> 2│") +} + +func singleLineRange(line int) highlightRange { return highlightRange{line, line} } diff --git a/tui/v2/highlight.go b/tui/v2/highlight.go deleted file mode 100644 index 8927196..0000000 --- a/tui/v2/highlight.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2023-2026 Princess Beef Heavy Industries, LLC / Dave Shanley -// SPDX-License-Identifier: Apache-2.0 - -package v2 - -import ( - "strings" -) - -// highlightLine applies syntax highlighting to a single line. -// YAML keys (text before the first colon) are styled with yamlKey. -// Must only be called from View() with pre-computed styles. -func highlightLine(line string, styles consoleStyles) string { - trimmed := strings.TrimLeft(line, " ") - if trimmed == "" || strings.HasPrefix(trimmed, "#") { - return styles.grey.Render(line) - } - - // Find the first colon that's not inside a quoted string - colonIdx := findYAMLColon(trimmed) - if colonIdx < 0 { - return styles.detail.Render(line) - } - - indent := line[:len(line)-len(trimmed)] - key := trimmed[:colonIdx+1] - rest := trimmed[colonIdx+1:] - return styles.detail.Render(indent) + styles.yamlKey.Render(key) + styles.detail.Render(rest) -} - -// findYAMLColon finds the index of the first colon that looks like a YAML key separator. -// Returns -1 if not found. Skips colons inside quoted strings. -func findYAMLColon(s string) int { - inSingle := false - inDouble := false - for i, ch := range s { - switch ch { - case '\'': - if !inDouble { - inSingle = !inSingle - } - case '"': - if !inSingle { - inDouble = !inDouble - } - case ':': - if !inSingle && !inDouble { - return i - } - } - } - return -1 -} diff --git a/tui/v2/highlight_test.go b/tui/v2/highlight_test.go deleted file mode 100644 index 5df4a4c..0000000 --- a/tui/v2/highlight_test.go +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2023-2026 Princess Beef Heavy Industries, LLC / Dave Shanley -// SPDX-License-Identifier: Apache-2.0 - -package v2 - -import ( - "testing" - - "github.com/pb33f/testify/assert" -) - -func TestFindYAMLColon_Simple(t *testing.T) { - assert.Equal(t, 4, findYAMLColon("name: Dave")) -} - -func TestFindYAMLColon_NoColon(t *testing.T) { - assert.Equal(t, -1, findYAMLColon("no colon here")) -} - -func TestFindYAMLColon_ColonInDoubleQuotes(t *testing.T) { - // Colon inside double quotes should be skipped - idx := findYAMLColon(`desc: "value: with colon"`) - assert.Equal(t, 4, idx) -} - -func TestFindYAMLColon_ColonInSingleQuotes(t *testing.T) { - idx := findYAMLColon(`desc: 'value: with colon'`) - assert.Equal(t, 4, idx) -} - -func TestFindYAMLColon_OnlyQuotedColon(t *testing.T) { - assert.Equal(t, -1, findYAMLColon(`"no:colon:outside"`)) -} - -func TestFindYAMLColon_Empty(t *testing.T) { - assert.Equal(t, -1, findYAMLColon("")) -} - -func TestFindYAMLColon_ColonAtStart(t *testing.T) { - assert.Equal(t, 0, findYAMLColon(": value")) -} - -func TestHighlightLine_EmptyLine(t *testing.T) { - styles := newConsoleStyles() - result := highlightLine("", styles) - assert.Contains(t, result, "") // grey render of empty -} - -func TestHighlightLine_Comment(t *testing.T) { - styles := newConsoleStyles() - result := highlightLine("# This is a comment", styles) - assert.NotEqual(t, "# This is a comment", result) // should be styled -} - -func TestHighlightLine_YAMLKeyValue(t *testing.T) { - styles := newConsoleStyles() - result := highlightLine("name: Dave", styles) - // The key portion should be styled differently from the value - assert.NotEqual(t, "name: Dave", result) -} - -func TestHighlightLine_NoColon(t *testing.T) { - styles := newConsoleStyles() - result := highlightLine(" - item", styles) - // No colon found, body text should still be styled explicitly - assert.NotEqual(t, " - item", result) -} - -func TestHighlightLine_PreservesIndent(t *testing.T) { - styles := newConsoleStyles() - result := highlightLine(" name: value", styles) - // Should start with spaces (indent preserved) - assert.True(t, len(result) > 4) -} - -func TestHighlightLine_WhitespaceOnly(t *testing.T) { - styles := newConsoleStyles() - result := highlightLine(" ", styles) - // All whitespace trimmed to empty, treated as blank line - assert.NotEmpty(t, result) -}