on main help sign in
chore: remove unused diff funcs
a4a9297Kujtim Hoxha
internal/diff/diff.go−609
@@ -1,621 +1,12 @@
1package diff
1package diff
2
2
3import (
3import (
4− "fmt"
5− "image/color"
6− "regexp"
7− "strconv"
8 "strings"
4 "strings"
9
5
10 "github.com/aymanbagabas/go-udiff"
6 "github.com/aymanbagabas/go-udiff"
11 "github.com/charmbracelet/crush/internal/config"
7 "github.com/charmbracelet/crush/internal/config"
12− "github.com/charmbracelet/crush/internal/highlight"
13− "github.com/charmbracelet/crush/internal/tui/styles"
14− "github.com/charmbracelet/lipgloss/v2"
15− "github.com/charmbracelet/x/ansi"
16− "github.com/sergi/go-diff/diffmatchpatch"
17)
8)
18
9
19−// Pre-compiled regex patterns for better performance
20−var (
21− hunkHeaderRegex = regexp.MustCompile(`^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@`)
22− ansiRegex = regexp.MustCompile(`\x1b(?:[@-Z\\-_]|\[[0-9?]*(?:;[0-9?]*)*[@-~])`)
23−)
24−
25−// -------------------------------------------------------------------------
26−// Core Types
27−// -------------------------------------------------------------------------
28−
29−// LineType represents the kind of line in a diff.
30−type LineType int
31−
32−const (
33− LineContext LineType = iota // Line exists in both files
34− LineAdded // Line added in the new file
35− LineRemoved // Line removed from the old file
36−)
37−
38−// Segment represents a portion of a line for intra-line highlighting
39−type Segment struct {
40− Start int
41− End int
42− Type LineType
43− Text string
44−}
45−
46−// DiffLine represents a single line in a diff
47−type DiffLine struct {
48− OldLineNo int // Line number in old file (0 for added lines)
49− NewLineNo int // Line number in new file (0 for removed lines)
50− Kind LineType // Type of line (added, removed, context)
51− Content string // Content of the line
52− Segments []Segment // Segments for intraline highlighting
53−}
54−
55−// Hunk represents a section of changes in a diff
56−type Hunk struct {
57− Header string
58− Lines []DiffLine
59−}
60−
61−// DiffResult contains the parsed result of a diff
62−type DiffResult struct {
63− OldFile string
64− NewFile string
65− Hunks []Hunk
66−}
67−
68−// linePair represents a pair of lines for side-by-side display
69−type linePair struct {
70− left *DiffLine
71− right *DiffLine
72−}
73−
74−// -------------------------------------------------------------------------
75−// Parse Configuration
76−// -------------------------------------------------------------------------
77−
78−// ParseConfig configures the behavior of diff parsing
79−type ParseConfig struct {
80− ContextSize int // Number of context lines to include
81−}
82−
83−// ParseOption modifies a ParseConfig
84−type ParseOption func(*ParseConfig)
85−
86−// WithContextSize sets the number of context lines to include
87−func WithContextSize(size int) ParseOption {
88− return func(p *ParseConfig) {
89− if size >= 0 {
90− p.ContextSize = size
91− }
92− }
93−}
94−
95−// -------------------------------------------------------------------------
96−// Side-by-Side Configuration
97−// -------------------------------------------------------------------------
98−
99−// SideBySideConfig configures the rendering of side-by-side diffs
100−type SideBySideConfig struct {
101− TotalWidth int
102−}
103−
104−// SideBySideOption modifies a SideBySideConfig
105−type SideBySideOption func(*SideBySideConfig)
106−
107−// NewSideBySideConfig creates a SideBySideConfig with default values
108−func NewSideBySideConfig(opts ...SideBySideOption) SideBySideConfig {
109− config := SideBySideConfig{
110− TotalWidth: 160, // Default width for side-by-side view
111− }
112−
113− for _, opt := range opts {
114− opt(&config)
115− }
116−
117− return config
118−}
119−
120−// WithTotalWidth sets the total width for side-by-side view
121−func WithTotalWidth(width int) SideBySideOption {
122− return func(s *SideBySideConfig) {
123− if width > 0 {
124− s.TotalWidth = width
125− }
126− }
127−}
128−
129−// -------------------------------------------------------------------------
130−// Diff Parsing
131−// -------------------------------------------------------------------------
132−
133−// ParseUnifiedDiff parses a unified diff format string into structured data
134−func ParseUnifiedDiff(diff string) (DiffResult, error) {
135− var result DiffResult
136− var currentHunk *Hunk
137−
138− lines := strings.Split(diff, "\n")
139−
140− var oldLine, newLine int
141− inFileHeader := true
142−
143− for _, line := range lines {
144− // Parse file headers
145− if inFileHeader {
146− if strings.HasPrefix(line, "--- a/") {
147− result.OldFile = strings.TrimPrefix(line, "--- a/")
148− continue
149− }
150− if strings.HasPrefix(line, "+++ b/") {
151− result.NewFile = strings.TrimPrefix(line, "+++ b/")
152− inFileHeader = false
153− continue
154− }
155− }
156−
157− // Parse hunk headers
158− if matches := hunkHeaderRegex.FindStringSubmatch(line); matches != nil {
159− if currentHunk != nil {
160− result.Hunks = append(result.Hunks, *currentHunk)
161− }
162− currentHunk = &Hunk{
163− Header: line,
164− Lines: []DiffLine{},
165− }
166−
167− oldStart, _ := strconv.Atoi(matches[1])
168− newStart, _ := strconv.Atoi(matches[3])
169− oldLine = oldStart
170− newLine = newStart
171− continue
172− }
173−
174− // Ignore "No newline at end of file" markers
175− if strings.HasPrefix(line, "\\ No newline at end of file") {
176− continue
177− }
178−
179− if currentHunk == nil {
180− continue
181− }
182−
183− // Process the line based on its prefix
184− if len(line) > 0 {
185− switch line[0] {
186− case '+':
187− currentHunk.Lines = append(currentHunk.Lines, DiffLine{
188− OldLineNo: 0,
189− NewLineNo: newLine,
190− Kind: LineAdded,
191− Content: line[1:],
192− })
193− newLine++
194− case '-':
195− currentHunk.Lines = append(currentHunk.Lines, DiffLine{
196− OldLineNo: oldLine,
197− NewLineNo: 0,
198− Kind: LineRemoved,
199− Content: line[1:],
200− })
201− oldLine++
202− default:
203− currentHunk.Lines = append(currentHunk.Lines, DiffLine{
204− OldLineNo: oldLine,
205− NewLineNo: newLine,
206− Kind: LineContext,
207− Content: line,
208− })
209− oldLine++
210− newLine++
211− }
212− } else {
213− // Handle empty lines
214− currentHunk.Lines = append(currentHunk.Lines, DiffLine{
215− OldLineNo: oldLine,
216− NewLineNo: newLine,
217− Kind: LineContext,
218− Content: "",
219− })
220− oldLine++
221− newLine++
222− }
223− }
224−
225− // Add the last hunk if there is one
226− if currentHunk != nil {
227− result.Hunks = append(result.Hunks, *currentHunk)
228− }
229−
230− return result, nil
231−}
232−
233−// HighlightIntralineChanges updates lines in a hunk to show character-level differences
234−func HighlightIntralineChanges(h *Hunk) {
235− var updated []DiffLine
236− dmp := diffmatchpatch.New()
237−
238− for i := 0; i < len(h.Lines); i++ {
239− // Look for removed line followed by added line
240− if i+1 < len(h.Lines) && h.Lines[i].Kind == LineRemoved && h.Lines[i+1].Kind == LineAdded {
241− oldLine := h.Lines[i]
242− newLine := h.Lines[i+1]
243−
244− // Find character-level differences
245− patches := dmp.DiffMain(oldLine.Content, newLine.Content, false)
246− patches = dmp.DiffCleanupSemantic(patches)
247− patches = dmp.DiffCleanupMerge(patches)
248− patches = dmp.DiffCleanupEfficiency(patches)
249−
250− segments := make([]Segment, 0)
251−
252− removeStart := 0
253− addStart := 0
254− for _, patch := range patches {
255− switch patch.Type {
256− case diffmatchpatch.DiffDelete:
257− segments = append(segments, Segment{
258− Start: removeStart,
259− End: removeStart + len(patch.Text),
260− Type: LineRemoved,
261− Text: patch.Text,
262− })
263− removeStart += len(patch.Text)
264− case diffmatchpatch.DiffInsert:
265− segments = append(segments, Segment{
266− Start: addStart,
267− End: addStart + len(patch.Text),
268− Type: LineAdded,
269− Text: patch.Text,
270− })
271− addStart += len(patch.Text)
272− default:
273− // Context text, no highlighting needed
274− removeStart += len(patch.Text)
275− addStart += len(patch.Text)
276− }
277− }
278− oldLine.Segments = segments
279− newLine.Segments = segments
280−
281− updated = append(updated, oldLine, newLine)
282− i++ // Skip the next line as we've already processed it
283− } else {
284− updated = append(updated, h.Lines[i])
285− }
286− }
287−
288− h.Lines = updated
289−}
290−
291−// pairLines converts a flat list of diff lines to pairs for side-by-side display
292−func pairLines(lines []DiffLine) []linePair {
293− var pairs []linePair
294− i := 0
295−
296− for i < len(lines) {
297− switch lines[i].Kind {
298− case LineRemoved:
299− // Check if the next line is an addition, if so pair them
300− if i+1 < len(lines) && lines[i+1].Kind == LineAdded {
301− pairs = append(pairs, linePair{left: &lines[i], right: &lines[i+1]})
302− i += 2
303− } else {
304− pairs = append(pairs, linePair{left: &lines[i], right: nil})
305− i++
306− }
307− case LineAdded:
308− pairs = append(pairs, linePair{left: nil, right: &lines[i]})
309− i++
310− case LineContext:
311− pairs = append(pairs, linePair{left: &lines[i], right: &lines[i]})
312− i++
313− }
314− }
315−
316− return pairs
317−}
318−
319−// -------------------------------------------------------------------------
320−// Syntax Highlighting
321−// -------------------------------------------------------------------------
322−func getColor(c color.Color) string {
323− rgba := color.RGBAModel.Convert(c).(color.RGBA)
324− return fmt.Sprintf("#%02x%02x%02x", rgba.R, rgba.G, rgba.B)
325−}
326−
327−// highlightLine applies syntax highlighting to a single line
328−func highlightLine(fileName string, line string, bg color.Color) string {
329− highlighted, err := highlight.SyntaxHighlight(line, fileName, bg)
330− if err != nil {
331− return line
332− }
333− return highlighted
334−}
335−
336−// createStyles generates the lipgloss styles needed for rendering diffs
337−func createStyles(t *styles.Theme) (removedLineStyle, addedLineStyle, contextLineStyle, lineNumberStyle lipgloss.Style) {
338− removedLineStyle = lipgloss.NewStyle().Background(t.S().Diff.RemovedBg)
339− addedLineStyle = lipgloss.NewStyle().Background(t.S().Diff.AddedBg)
340− contextLineStyle = lipgloss.NewStyle().Background(t.S().Diff.ContextBg)
341− lineNumberStyle = lipgloss.NewStyle().Foreground(t.S().Diff.LineNumber)
342− return
343−}
344−
345−// -------------------------------------------------------------------------
346−// Rendering Functions
347−// -------------------------------------------------------------------------
348−
349−// applyHighlighting applies intra-line highlighting to a piece of text
350−func applyHighlighting(content string, segments []Segment, segmentType LineType, highlightBg color.Color) string {
351− // Find all ANSI sequences in the content using pre-compiled regex
352− ansiMatches := ansiRegex.FindAllStringIndex(content, -1)
353−
354− // Build a mapping of visible character positions to their actual indices
355− visibleIdx := 0
356− ansiSequences := make(map[int]string)
357− lastAnsiSeq := "\x1b[0m" // Default reset sequence
358−
359− for i := 0; i < len(content); {
360− isAnsi := false
361− for _, match := range ansiMatches {
362− if match[0] == i {
363− ansiSequences[visibleIdx] = content[match[0]:match[1]]
364− lastAnsiSeq = content[match[0]:match[1]]
365− i = match[1]
366− isAnsi = true
367− break
368− }
369− }
370− if isAnsi {
371− continue
372− }
373−
374− // For non-ANSI positions, store the last ANSI sequence
375− if _, exists := ansiSequences[visibleIdx]; !exists {
376− ansiSequences[visibleIdx] = lastAnsiSeq
377− }
378− visibleIdx++
379− i++
380− }
381−
382− // Apply highlighting
383− var sb strings.Builder
384− inSelection := false
385− currentPos := 0
386−
387− // Get the appropriate color based on terminal background
388− bgColor := lipgloss.Color(getColor(highlightBg))
389− // fgColor := lipgloss.Color(getColor(theme.CurrentTheme().Background()))
390−
391− for i := 0; i < len(content); {
392− // Check if we're at an ANSI sequence
393− isAnsi := false
394− for _, match := range ansiMatches {
395− if match[0] == i {
396− sb.WriteString(content[match[0]:match[1]]) // Preserve ANSI sequence
397− i = match[1]
398− isAnsi = true
399− break
400− }
401− }
402− if isAnsi {
403− continue
404− }
405−
406− // Check for segment boundaries
407− for _, seg := range segments {
408− if seg.Type == segmentType {
409− if currentPos == seg.Start {
410− inSelection = true
411− }
412− if currentPos == seg.End {
413− inSelection = false
414− }
415− }
416− }
417−
418− // Get current character
419− char := string(content[i])
420−
421− if inSelection {
422− // Get the current styling
423− currentStyle := ansiSequences[currentPos]
424−
425− // Apply foreground and background highlight
426− // sb.WriteString("\x1b[38;2;")
427− // r, g, b, _ := fgColor.RGBA()
428− // sb.WriteString(fmt.Sprintf("%d;%d;%dm", r>>8, g>>8, b>>8))
429− sb.WriteString("\x1b[48;2;")
430− r, g, b, _ := bgColor.RGBA()
431− sb.WriteString(fmt.Sprintf("%d;%d;%dm", r>>8, g>>8, b>>8))
432− sb.WriteString(char)
433− // Reset foreground and background
434− // sb.WriteString("\x1b[39m")
435−
436− // Reapply the original ANSI sequence
437− sb.WriteString(currentStyle)
438− } else {
439− // Not in selection, just copy the character
440− sb.WriteString(char)
441− }
442−
443− currentPos++
444− i++
445− }
446−
447− return sb.String()
448−}
449−
450−// renderLeftColumn formats the left side of a side-by-side diff
451−func renderLeftColumn(fileName string, dl *DiffLine, colWidth int) string {
452− t := styles.CurrentTheme()
453−
454− if dl == nil {
455− contextLineStyle := t.S().Base.Background(t.S().Diff.ContextBg)
456− return contextLineStyle.Width(colWidth).Render("")
457− }
458−
459− removedLineStyle, _, contextLineStyle, lineNumberStyle := createStyles(t)
460−
461− // Determine line style based on line type
462− var marker string
463− var bgStyle lipgloss.Style
464− switch dl.Kind {
465− case LineRemoved:
466− marker = removedLineStyle.Foreground(t.S().Diff.Removed).Render("-")
467− bgStyle = removedLineStyle
468− lineNumberStyle = lineNumberStyle.Foreground(t.S().Diff.Removed).Background(t.S().Diff.RemovedLineNumberBg)
469− case LineAdded:
470− marker = "?"
471− bgStyle = contextLineStyle
472− case LineContext:
473− marker = contextLineStyle.Render(" ")
474− bgStyle = contextLineStyle
475− }
476−
477− // Format line number
478− lineNum := ""
479− if dl.OldLineNo > 0 {
480− lineNum = fmt.Sprintf("%6d", dl.OldLineNo)
481− }
482−
483− // Create the line prefix
484− prefix := lineNumberStyle.Render(lineNum + " " + marker)
485−
486− // Apply syntax highlighting
487− content := highlightLine(fileName, dl.Content, bgStyle.GetBackground())
488−
489− // Apply intra-line highlighting for removed lines
490− if dl.Kind == LineRemoved && len(dl.Segments) > 0 {
491− content = applyHighlighting(content, dl.Segments, LineRemoved, t.S().Diff.HighlightRemoved)
492− }
493−
494− // Add a padding space for removed lines
495− if dl.Kind == LineRemoved {
496− content = bgStyle.Render(" ") + content
497− }
498−
499− // Create the final line and truncate if needed
500− lineText := prefix + content
501− return bgStyle.MaxHeight(1).Width(colWidth).Render(
502− ansi.Truncate(
503− lineText,
504− colWidth,
505− lipgloss.NewStyle().Background(bgStyle.GetBackground()).Foreground(t.FgMuted).Render("..."),
506− ),
507− )
508−}
509−
510−// renderRightColumn formats the right side of a side-by-side diff
511−func renderRightColumn(fileName string, dl *DiffLine, colWidth int) string {
512− t := styles.CurrentTheme()
513−
514− if dl == nil {
515− contextLineStyle := lipgloss.NewStyle().Background(t.S().Diff.ContextBg)
516− return contextLineStyle.Width(colWidth).Render("")
517− }
518−
519− _, addedLineStyle, contextLineStyle, lineNumberStyle := createStyles(t)
520−
521− // Determine line style based on line type
522− var marker string
523− var bgStyle lipgloss.Style
524− switch dl.Kind {
525− case LineAdded:
526− marker = addedLineStyle.Foreground(t.S().Diff.Added).Render("+")
527− bgStyle = addedLineStyle
528− lineNumberStyle = lineNumberStyle.Foreground(t.S().Diff.Added).Background(t.S().Diff.AddedLineNumberBg)
529− case LineRemoved:
530− marker = "?"
531− bgStyle = contextLineStyle
532− case LineContext:
533− marker = contextLineStyle.Render(" ")
534− bgStyle = contextLineStyle
535− }
536−
537− // Format line number
538− lineNum := ""
539− if dl.NewLineNo > 0 {
540− lineNum = fmt.Sprintf("%6d", dl.NewLineNo)
541− }
542−
543− // Create the line prefix
544− prefix := lineNumberStyle.Render(lineNum + " " + marker)
545−
546− // Apply syntax highlighting
547− content := highlightLine(fileName, dl.Content, bgStyle.GetBackground())
548−
549− // Apply intra-line highlighting for added lines
550− if dl.Kind == LineAdded && len(dl.Segments) > 0 {
551− content = applyHighlighting(content, dl.Segments, LineAdded, t.S().Diff.HighlightAdded)
552− }
553−
554− // Add a padding space for added lines
555− if dl.Kind == LineAdded {
556− content = bgStyle.Render(" ") + content
557− }
558−
559− // Create the final line and truncate if needed
560− lineText := prefix + content
561− return bgStyle.MaxHeight(1).Width(colWidth).Render(
562− ansi.Truncate(
563− lineText,
564− colWidth,
565− lipgloss.NewStyle().Background(bgStyle.GetBackground()).Foreground(t.FgMuted).Render("..."),
566− ),
567− )
568−}
569−
570−// -------------------------------------------------------------------------
571−// Public API
572−// -------------------------------------------------------------------------
573−
574−// RenderSideBySideHunk formats a hunk for side-by-side display
575−func RenderSideBySideHunk(fileName string, h Hunk, opts ...SideBySideOption) string {
576− // Apply options to create the configuration
577− config := NewSideBySideConfig(opts...)
578−
579− // Make a copy of the hunk so we don't modify the original
580− hunkCopy := Hunk{Lines: make([]DiffLine, len(h.Lines))}
581− copy(hunkCopy.Lines, h.Lines)
582−
583− // Highlight changes within lines
584− HighlightIntralineChanges(&hunkCopy)
585−
586− // Pair lines for side-by-side display
587− pairs := pairLines(hunkCopy.Lines)
588−
589− // Calculate column width
590− colWidth := config.TotalWidth / 2
591−
592− leftWidth := colWidth
593− rightWidth := config.TotalWidth - colWidth
594− var sb strings.Builder
595− for _, p := range pairs {
596− leftStr := renderLeftColumn(fileName, p.left, leftWidth)
597− rightStr := renderRightColumn(fileName, p.right, rightWidth)
598− sb.WriteString(leftStr + rightStr + "\n")
599− }
600−
601− return sb.String()
602−}
603−
604−// FormatDiff creates a side-by-side formatted view of a diff
605−func FormatDiff(diffText string, opts ...SideBySideOption) (string, error) {
606− diffResult, err := ParseUnifiedDiff(diffText)
607− if err != nil {
608− return "", err
609− }
610−
611− var sb strings.Builder
612− for _, h := range diffResult.Hunks {
613− sb.WriteString(RenderSideBySideHunk(diffResult.OldFile, h, opts...))
614− }
615−
616− return sb.String(), nil
617−}
618−
619// GenerateDiff creates a unified diff from two file contents
10// GenerateDiff creates a unified diff from two file contents
620func GenerateDiff(beforeContent, afterContent, fileName string) (string, int, int) {
11func GenerateDiff(beforeContent, afterContent, fileName string) (string, int, int) {
621 // remove the cwd prefix and ensure consistent path format
12 // remove the cwd prefix and ensure consistent path format
internal/diff/patch.godeleted−740
@@ -1,740 +0,0 @@
1−package diff
2−
3−import (
4− "errors"
5− "fmt"
6− "os"
7− "path/filepath"
8− "strings"
9−)
10−
11−type ActionType string
12−
13−const (
14− ActionAdd ActionType = "add"
15− ActionDelete ActionType = "delete"
16− ActionUpdate ActionType = "update"
17−)
18−
19−type FileChange struct {
20− Type ActionType
21− OldContent *string
22− NewContent *string
23− MovePath *string
24−}
25−
26−type Commit struct {
27− Changes map[string]FileChange
28−}
29−
30−type Chunk struct {
31− OrigIndex int // line index of the first line in the original file
32− DelLines []string // lines to delete
33− InsLines []string // lines to insert
34−}
35−
36−type PatchAction struct {
37− Type ActionType
38− NewFile *string
39− Chunks []Chunk
40− MovePath *string
41−}
42−
43−type Patch struct {
44− Actions map[string]PatchAction
45−}
46−
47−type DiffError struct {
48− message string
49−}
50−
51−func (e DiffError) Error() string {
52− return e.message
53−}
54−
55−// Helper functions for error handling
56−func NewDiffError(message string) DiffError {
57− return DiffError{message: message}
58−}
59−
60−func fileError(action, reason, path string) DiffError {
61− return NewDiffError(fmt.Sprintf("%s File Error: %s: %s", action, reason, path))
62−}
63−
64−func contextError(index int, context string, isEOF bool) DiffError {
65− prefix := "Invalid Context"
66− if isEOF {
67− prefix = "Invalid EOF Context"
68− }
69− return NewDiffError(fmt.Sprintf("%s %d:\n%s", prefix, index, context))
70−}
71−
72−type Parser struct {
73− currentFiles map[string]string
74− lines []string
75− index int
76− patch Patch
77− fuzz int
78−}
79−
80−func NewParser(currentFiles map[string]string, lines []string) *Parser {
81− return &Parser{
82− currentFiles: currentFiles,
83− lines: lines,
84− index: 0,
85− patch: Patch{Actions: make(map[string]PatchAction, len(currentFiles))},
86− fuzz: 0,
87− }
88−}
89−
90−func (p *Parser) isDone(prefixes []string) bool {
91− if p.index >= len(p.lines) {
92− return true
93− }
94− for _, prefix := range prefixes {
95− if strings.HasPrefix(p.lines[p.index], prefix) {
96− return true
97− }
98− }
99− return false
100−}
101−
102−func (p *Parser) startsWith(prefix any) bool {
103− var prefixes []string
104− switch v := prefix.(type) {
105− case string:
106− prefixes = []string{v}
107− case []string:
108− prefixes = v
109− }
110−
111− for _, pfx := range prefixes {
112− if strings.HasPrefix(p.lines[p.index], pfx) {
113− return true
114− }
115− }
116− return false
117−}
118−
119−func (p *Parser) readStr(prefix string, returnEverything bool) string {
120− if p.index >= len(p.lines) {
121− return "" // Changed from panic to return empty string for safer operation
122− }
123− if strings.HasPrefix(p.lines[p.index], prefix) {
124− var text string
125− if returnEverything {
126− text = p.lines[p.index]
127− } else {
128− text = p.lines[p.index][len(prefix):]
129− }
130− p.index++
131− return text
132− }
133− return ""
134−}
135−
136−func (p *Parser) Parse() error {
137− endPatchPrefixes := []string{"*** End Patch"}
138−
139− for !p.isDone(endPatchPrefixes) {
140− path := p.readStr("*** Update File: ", false)
141− if path != "" {
142− if _, exists := p.patch.Actions[path]; exists {
143− return fileError("Update", "Duplicate Path", path)
144− }
145− moveTo := p.readStr("*** Move to: ", false)
146− if _, exists := p.currentFiles[path]; !exists {
147− return fileError("Update", "Missing File", path)
148− }
149− text := p.currentFiles[path]
150− action, err := p.parseUpdateFile(text)
151− if err != nil {
152− return err
153− }
154− if moveTo != "" {
155− action.MovePath = &moveTo
156− }
157− p.patch.Actions[path] = action
158− continue
159− }
160−
161− path = p.readStr("*** Delete File: ", false)
162− if path != "" {
163− if _, exists := p.patch.Actions[path]; exists {
164− return fileError("Delete", "Duplicate Path", path)
165− }
166− if _, exists := p.currentFiles[path]; !exists {
167− return fileError("Delete", "Missing File", path)
168− }
169− p.patch.Actions[path] = PatchAction{Type: ActionDelete, Chunks: []Chunk{}}
170− continue
171− }
172−
173− path = p.readStr("*** Add File: ", false)
174− if path != "" {
175− if _, exists := p.patch.Actions[path]; exists {
176− return fileError("Add", "Duplicate Path", path)
177− }
178− if _, exists := p.currentFiles[path]; exists {
179− return fileError("Add", "File already exists", path)
180− }
181− action, err := p.parseAddFile()
182− if err != nil {
183− return err
184− }
185− p.patch.Actions[path] = action
186− continue
187− }
188−
189− return NewDiffError(fmt.Sprintf("Unknown Line: %s", p.lines[p.index]))
190− }
191−
192− if !p.startsWith("*** End Patch") {
193− return NewDiffError("Missing End Patch")
194− }
195− p.index++
196−
197− return nil
198−}
199−
200−func (p *Parser) parseUpdateFile(text string) (PatchAction, error) {
201− action := PatchAction{Type: ActionUpdate, Chunks: []Chunk{}}
202− fileLines := strings.Split(text, "\n")
203− index := 0
204−
205− endPrefixes := []string{
206− "*** End Patch",
207− "*** Update File:",
208− "*** Delete File:",
209− "*** Add File:",
210− "*** End of File",
211− }
212−
213− for !p.isDone(endPrefixes) {
214− defStr := p.readStr("@@ ", false)
215− sectionStr := ""
216− if defStr == "" && p.index < len(p.lines) && p.lines[p.index] == "@@" {
217− sectionStr = p.lines[p.index]
218− p.index++
219− }
220− if defStr == "" && sectionStr == "" && index != 0 {
221− return action, NewDiffError(fmt.Sprintf("Invalid Line:\n%s", p.lines[p.index]))
222− }
223− if strings.TrimSpace(defStr) != "" {
224− found := false
225− for i := range fileLines[:index] {
226− if fileLines[i] == defStr {
227− found = true
228− break
229− }
230− }
231−
232− if !found {
233− for i := index; i < len(fileLines); i++ {
234− if fileLines[i] == defStr {
235− index = i + 1
236− found = true
237− break
238− }
239− }
240− }
241−
242− if !found {
243− for i := range fileLines[:index] {
244− if strings.TrimSpace(fileLines[i]) == strings.TrimSpace(defStr) {
245− found = true
246− break
247− }
248− }
249− }
250−
251− if !found {
252− for i := index; i < len(fileLines); i++ {
253− if strings.TrimSpace(fileLines[i]) == strings.TrimSpace(defStr) {
254− index = i + 1
255− p.fuzz++
256− found = true
257− break
258− }
259− }
260− }
261− }
262−
263− nextChunkContext, chunks, endPatchIndex, eof := peekNextSection(p.lines, p.index)
264− newIndex, fuzz := findContext(fileLines, nextChunkContext, index, eof)
265− if newIndex == -1 {
266− ctxText := strings.Join(nextChunkContext, "\n")
267− return action, contextError(index, ctxText, eof)
268− }
269− p.fuzz += fuzz
270−
271− for _, ch := range chunks {
272− ch.OrigIndex += newIndex
273− action.Chunks = append(action.Chunks, ch)
274− }
275− index = newIndex + len(nextChunkContext)
276− p.index = endPatchIndex
277− }
278− return action, nil
279−}
280−
281−func (p *Parser) parseAddFile() (PatchAction, error) {
282− lines := make([]string, 0, 16) // Preallocate space for better performance
283− endPrefixes := []string{
284− "*** End Patch",
285− "*** Update File:",
286− "*** Delete File:",
287− "*** Add File:",
288− }
289−
290− for !p.isDone(endPrefixes) {
291− s := p.readStr("", true)
292− if !strings.HasPrefix(s, "+") {
293− return PatchAction{}, NewDiffError(fmt.Sprintf("Invalid Add File Line: %s", s))
294− }
295− lines = append(lines, s[1:])
296− }
297−
298− newFile := strings.Join(lines, "\n")
299− return PatchAction{
300− Type: ActionAdd,
301− NewFile: &newFile,
302− Chunks: []Chunk{},
303− }, nil
304−}
305−
306−// Refactored to use a matcher function for each comparison type
307−func findContextCore(lines []string, context []string, start int) (int, int) {
308− if len(context) == 0 {
309− return start, 0
310− }
311−
312− // Try exact match
313− if idx, fuzz := tryFindMatch(lines, context, start, func(a, b string) bool {
314− return a == b
315− }); idx >= 0 {
316− return idx, fuzz
317− }
318−
319− // Try trimming right whitespace
320− if idx, fuzz := tryFindMatch(lines, context, start, func(a, b string) bool {
321− return strings.TrimRight(a, " \t") == strings.TrimRight(b, " \t")
322− }); idx >= 0 {
323− return idx, fuzz
324− }
325−
326− // Try trimming all whitespace
327− if idx, fuzz := tryFindMatch(lines, context, start, func(a, b string) bool {
328− return strings.TrimSpace(a) == strings.TrimSpace(b)
329− }); idx >= 0 {
330− return idx, fuzz
331− }
332−
333− return -1, 0
334−}
335−
336−// Helper function to DRY up the match logic
337−func tryFindMatch(lines []string, context []string, start int,
338− compareFunc func(string, string) bool,
339−) (int, int) {
340− for i := start; i < len(lines); i++ {
341− if i+len(context) <= len(lines) {
342− match := true
343− for j := range context {
344− if !compareFunc(lines[i+j], context[j]) {
345− match = false
346− break
347− }
348− }
349− if match {
350− // Return fuzz level: 0 for exact, 1 for trimRight, 100 for trimSpace
351− var fuzz int
352− if compareFunc("a ", "a") && !compareFunc("a", "b") {
353− fuzz = 1
354− } else if compareFunc("a ", "a") {
355− fuzz = 100
356− }
357− return i, fuzz
358− }
359− }
360− }
361− return -1, 0
362−}
363−
364−func findContext(lines []string, context []string, start int, eof bool) (int, int) {
365− if eof {
366− newIndex, fuzz := findContextCore(lines, context, len(lines)-len(context))
367− if newIndex != -1 {
368− return newIndex, fuzz
369− }
370− newIndex, fuzz = findContextCore(lines, context, start)
371− return newIndex, fuzz + 10000
372− }
373− return findContextCore(lines, context, start)
374−}
375−
376−func peekNextSection(lines []string, initialIndex int) ([]string, []Chunk, int, bool) {
377− index := initialIndex
378− old := make([]string, 0, 32) // Preallocate for better performance
379− delLines := make([]string, 0, 8)
380− insLines := make([]string, 0, 8)
381− chunks := make([]Chunk, 0, 4)
382− mode := "keep"
383−
384− // End conditions for the section
385− endSectionConditions := func(s string) bool {
386− return strings.HasPrefix(s, "@@") ||
387− strings.HasPrefix(s, "*** End Patch") ||
388− strings.HasPrefix(s, "*** Update File:") ||
389− strings.HasPrefix(s, "*** Delete File:") ||
390− strings.HasPrefix(s, "*** Add File:") ||
391− strings.HasPrefix(s, "*** End of File") ||
392− s == "***" ||
393− strings.HasPrefix(s, "***")
394− }
395−
396− for index < len(lines) {
397− s := lines[index]
398− if endSectionConditions(s) {
399− break
400− }
401− index++
402− lastMode := mode
403− line := s
404−
405− if len(line) > 0 {
406− switch line[0] {
407− case '+':
408− mode = "add"
409− case '-':
410− mode = "delete"
411− case ' ':
412− mode = "keep"
413− default:
414− mode = "keep"
415− line = " " + line
416− }
417− } else {
418− mode = "keep"
419− line = " "
420− }
421−
422− line = line[1:]
423− if mode == "keep" && lastMode != mode {
424− if len(insLines) > 0 || len(delLines) > 0 {
425− chunks = append(chunks, Chunk{
426− OrigIndex: len(old) - len(delLines),
427− DelLines: delLines,
428− InsLines: insLines,
429− })
430− }
431− delLines = make([]string, 0, 8)
432− insLines = make([]string, 0, 8)
433− }
434− switch mode {
435− case "delete":
436− delLines = append(delLines, line)
437− old = append(old, line)
438− case "add":
439− insLines = append(insLines, line)
440− default:
441− old = append(old, line)
442− }
443− }
444−
445− if len(insLines) > 0 || len(delLines) > 0 {
446− chunks = append(chunks, Chunk{
447− OrigIndex: len(old) - len(delLines),
448− DelLines: delLines,
449− InsLines: insLines,
450− })
451− }
452−
453− if index < len(lines) && lines[index] == "*** End of File" {
454− index++
455− return old, chunks, index, true
456− }
457− return old, chunks, index, false
458−}
459−
460−func TextToPatch(text string, orig map[string]string) (Patch, int, error) {
461− text = strings.TrimSpace(text)
462− lines := strings.Split(text, "\n")
463− if len(lines) < 2 || !strings.HasPrefix(lines[0], "*** Begin Patch") || lines[len(lines)-1] != "*** End Patch" {
464− return Patch{}, 0, NewDiffError("Invalid patch text")
465− }
466− parser := NewParser(orig, lines)
467− parser.index = 1
468− if err := parser.Parse(); err != nil {
469− return Patch{}, 0, err
470− }
471− return parser.patch, parser.fuzz, nil
472−}
473−
474−func IdentifyFilesNeeded(text string) []string {
475− text = strings.TrimSpace(text)
476− lines := strings.Split(text, "\n")
477− result := make(map[string]bool)
478−
479− for _, line := range lines {
480− if strings.HasPrefix(line, "*** Update File: ") {
481− result[line[len("*** Update File: "):]] = true
482− }
483− if strings.HasPrefix(line, "*** Delete File: ") {
484− result[line[len("*** Delete File: "):]] = true
485− }
486− }
487−
488− files := make([]string, 0, len(result))
489− for file := range result {
490− files = append(files, file)
491− }
492− return files
493−}
494−
495−func IdentifyFilesAdded(text string) []string {
496− text = strings.TrimSpace(text)
497− lines := strings.Split(text, "\n")
498− result := make(map[string]bool)
499−
500− for _, line := range lines {
501− if strings.HasPrefix(line, "*** Add File: ") {
502− result[line[len("*** Add File: "):]] = true
503− }
504− }
505−
506− files := make([]string, 0, len(result))
507− for file := range result {
508− files = append(files, file)
509− }
510− return files
511−}
512−
513−func getUpdatedFile(text string, action PatchAction, path string) (string, error) {
514− if action.Type != ActionUpdate {
515− return "", errors.New("expected UPDATE action")
516− }
517− origLines := strings.Split(text, "\n")
518− destLines := make([]string, 0, len(origLines)) // Preallocate with capacity
519− origIndex := 0
520−
521− for _, chunk := range action.Chunks {
522− if chunk.OrigIndex > len(origLines) {
523− return "", NewDiffError(fmt.Sprintf("%s: chunk.orig_index %d > len(lines) %d", path, chunk.OrigIndex, len(origLines)))
524− }
525− if origIndex > chunk.OrigIndex {
526− return "", NewDiffError(fmt.Sprintf("%s: orig_index %d > chunk.orig_index %d", path, origIndex, chunk.OrigIndex))
527− }
528− destLines = append(destLines, origLines[origIndex:chunk.OrigIndex]...)
529− delta := chunk.OrigIndex - origIndex
530− origIndex += delta
531−
532− if len(chunk.InsLines) > 0 {
533− destLines = append(destLines, chunk.InsLines...)
534− }
535− origIndex += len(chunk.DelLines)
536− }
537−
538− destLines = append(destLines, origLines[origIndex:]...)
539− return strings.Join(destLines, "\n"), nil
540−}
541−
542−func PatchToCommit(patch Patch, orig map[string]string) (Commit, error) {
543− commit := Commit{Changes: make(map[string]FileChange, len(patch.Actions))}
544− for pathKey, action := range patch.Actions {
545− switch action.Type {
546− case ActionDelete:
547− oldContent := orig[pathKey]
548− commit.Changes[pathKey] = FileChange{
549− Type: ActionDelete,
550− OldContent: &oldContent,
551− }
552− case ActionAdd:
553− commit.Changes[pathKey] = FileChange{
554− Type: ActionAdd,
555− NewContent: action.NewFile,
556− }
557− case ActionUpdate:
558− newContent, err := getUpdatedFile(orig[pathKey], action, pathKey)
559− if err != nil {
560− return Commit{}, err
561− }
562− oldContent := orig[pathKey]
563− fileChange := FileChange{
564− Type: ActionUpdate,
565− OldContent: &oldContent,
566− NewContent: &newContent,
567− }
568− if action.MovePath != nil {
569− fileChange.MovePath = action.MovePath
570− }
571− commit.Changes[pathKey] = fileChange
572− }
573− }
574− return commit, nil
575−}
576−
577−func AssembleChanges(orig map[string]string, updatedFiles map[string]string) Commit {
578− commit := Commit{Changes: make(map[string]FileChange, len(updatedFiles))}
579− for p, newContent := range updatedFiles {
580− oldContent, exists := orig[p]
581− if exists && oldContent == newContent {
582− continue
583− }
584−
585− if exists && newContent != "" {
586− commit.Changes[p] = FileChange{
587− Type: ActionUpdate,
588− OldContent: &oldContent,
589− NewContent: &newContent,
590− }
591− } else if newContent != "" {
592− commit.Changes[p] = FileChange{
593− Type: ActionAdd,
594− NewContent: &newContent,
595− }
596− } else if exists {
597− commit.Changes[p] = FileChange{
598− Type: ActionDelete,
599− OldContent: &oldContent,
600− }
601− } else {
602− return commit // Changed from panic to simply return current commit
603− }
604− }
605− return commit
606−}
607−
608−func LoadFiles(paths []string, openFn func(string) (string, error)) (map[string]string, error) {
609− orig := make(map[string]string, len(paths))
610− for _, p := range paths {
611− content, err := openFn(p)
612− if err != nil {
613− return nil, fileError("Open", "File not found", p)
614− }
615− orig[p] = content
616− }
617− return orig, nil
618−}
619−
620−func ApplyCommit(commit Commit, writeFn func(string, string) error, removeFn func(string) error) error {
621− for p, change := range commit.Changes {
622− switch change.Type {
623− case ActionDelete:
624− if err := removeFn(p); err != nil {
625− return err
626− }
627− case ActionAdd:
628− if change.NewContent == nil {
629− return NewDiffError(fmt.Sprintf("Add action for %s has nil new_content", p))
630− }
631− if err := writeFn(p, *change.NewContent); err != nil {
632− return err
633− }
634− case ActionUpdate:
635− if change.NewContent == nil {
636− return NewDiffError(fmt.Sprintf("Update action for %s has nil new_content", p))
637− }
638− if change.MovePath != nil {
639− if err := writeFn(*change.MovePath, *change.NewContent); err != nil {
640− return err
641− }
642− if err := removeFn(p); err != nil {
643− return err
644− }
645− } else {
646− if err := writeFn(p, *change.NewContent); err != nil {
647− return err
648− }
649− }
650− }
651− }
652− return nil
653−}
654−
655−func ProcessPatch(text string, openFn func(string) (string, error), writeFn func(string, string) error, removeFn func(string) error) (string, error) {
656− if !strings.HasPrefix(text, "*** Begin Patch") {
657− return "", NewDiffError("Patch must start with *** Begin Patch")
658− }
659− paths := IdentifyFilesNeeded(text)
660− orig, err := LoadFiles(paths, openFn)
661− if err != nil {
662− return "", err
663− }
664−
665− patch, fuzz, err := TextToPatch(text, orig)
666− if err != nil {
667− return "", err
668− }
669−
670− if fuzz > 0 {
671− return "", NewDiffError(fmt.Sprintf("Patch contains fuzzy matches (fuzz level: %d)", fuzz))
672− }
673−
674− commit, err := PatchToCommit(patch, orig)
675− if err != nil {
676− return "", err
677− }
678−
679− if err := ApplyCommit(commit, writeFn, removeFn); err != nil {
680− return "", err
681− }
682−
683− return "Patch applied successfully", nil
684−}
685−
686−func OpenFile(p string) (string, error) {
687− data, err := os.ReadFile(p)
688− if err != nil {
689− return "", err
690− }
691− return string(data), nil
692−}
693−
694−func WriteFile(p string, content string) error {
695− if filepath.IsAbs(p) {
696− return NewDiffError("We do not support absolute paths.")
697− }
698−
699− dir := filepath.Dir(p)
700− if dir != "." {
701− if err := os.MkdirAll(dir, 0o755); err != nil {
702− return err
703− }
704− }
705−
706− return os.WriteFile(p, []byte(content), 0o644)
707−}
708−
709−func RemoveFile(p string) error {
710− return os.Remove(p)
711−}
712−
713−func ValidatePatch(patchText string, files map[string]string) (bool, string, error) {
714− if !strings.HasPrefix(patchText, "*** Begin Patch") {
715− return false, "Patch must start with *** Begin Patch", nil
716− }
717−
718− neededFiles := IdentifyFilesNeeded(patchText)
719− for _, filePath := range neededFiles {
720− if _, exists := files[filePath]; !exists {
721− return false, fmt.Sprintf("File not found: %s", filePath), nil
722− }
723− }
724−
725− patch, fuzz, err := TextToPatch(patchText, files)
726− if err != nil {
727− return false, err.Error(), nil
728− }
729−
730− if fuzz > 0 {
731− return false, fmt.Sprintf("Patch contains fuzzy matches (fuzz level: %d)", fuzz), nil
732− }
733−
734− _, err = PatchToCommit(patch, files)
735− if err != nil {
736− return false, err.Error(), nil
737− }
738−
739− return true, "Patch is valid", nil
740−}
internal/llm/tools/write.go+6−4
@@ -23,8 +23,9 @@ type WriteParams struct {
23}
23}
24
24
25type WritePermissionsParams struct {
25type WritePermissionsParams struct {
26− FilePath string `json:"file_path"`
26+ FilePath string `json:"file_path"`
27− Diff string `json:"diff"`
27+ OldContent string `json:"old_content,omitempty"`
28+ NewContent string `json:"new_content,omitempty"`
28}
29}
29
30
30type writeTool struct {
31type writeTool struct {
@@ -174,8 +175,9 @@ func (w *writeTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error
174 Action: "write",
175 Action: "write",
175 Description: fmt.Sprintf("Create file %s", filePath),
176 Description: fmt.Sprintf("Create file %s", filePath),
176 Params: WritePermissionsParams{
177 Params: WritePermissionsParams{
177− FilePath: filePath,
178+ FilePath: filePath,
178− Diff: diff,
179+ OldContent: oldContent,
180+ NewContent: params.Content,
179 },
181 },
180 },
182 },
181 )
183 )
internal/tui/components/dialogs/permissions/permissions.go+6−4
@@ -7,7 +7,6 @@ import (
7 "github.com/charmbracelet/bubbles/v2/key"
7 "github.com/charmbracelet/bubbles/v2/key"
8 "github.com/charmbracelet/bubbles/v2/viewport"
8 "github.com/charmbracelet/bubbles/v2/viewport"
9 tea "github.com/charmbracelet/bubbletea/v2"
9 tea "github.com/charmbracelet/bubbletea/v2"
10− "github.com/charmbracelet/crush/internal/diff"
11 "github.com/charmbracelet/crush/internal/fsext"
10 "github.com/charmbracelet/crush/internal/fsext"
12 "github.com/charmbracelet/crush/internal/llm/tools"
11 "github.com/charmbracelet/crush/internal/llm/tools"
13 "github.com/charmbracelet/crush/internal/permission"
12 "github.com/charmbracelet/crush/internal/permission"
@@ -285,10 +284,13 @@ func (p *permissionDialogCmp) renderEditContent() string {
285func (p *permissionDialogCmp) renderWriteContent() string {
284func (p *permissionDialogCmp) renderWriteContent() string {
286 if pr, ok := p.permission.Params.(tools.WritePermissionsParams); ok {
285 if pr, ok := p.permission.Params.(tools.WritePermissionsParams); ok {
287 // Use the cache for diff rendering
286 // Use the cache for diff rendering
288− diff := p.GetOrSetDiff(p.permission.ID, func() (string, error) {
287+ formatter := core.DiffFormatter().
288+ Before(fsext.PrettyPath(pr.FilePath), pr.OldContent).
289+ After(fsext.PrettyPath(pr.FilePath), pr.NewContent).
289− return diff.FormatDiff(pr.Diff, diff.WithTotalWidth(p.contentViewPort.Width()))
290+ Width(p.contentViewPort.Width()).
290− })
291+ Split()
291
292
293+ diff := formatter.String()
292 contentHeight := min(p.height-9, lipgloss.Height(diff))
294 contentHeight := min(p.height-9, lipgloss.Height(diff))
293 p.contentViewPort.SetHeight(contentHeight)
295 p.contentViewPort.SetHeight(contentHeight)
294 p.contentViewPort.SetContent(diff)
296 p.contentViewPort.SetContent(diff)