git-gui: fix hunk parsing for corner case changes
[git-gui/bertw.git] / lib / diff.tcl
blob8226d49310c1baa57fc9db150a58cf054cbf66b0
1 # git-gui diff viewer
2 # Copyright (C) 2006, 2007 Shawn Pearce
4 proc clear_diff {} {
5 global ui_diff current_diff_path current_diff_header
6 global ui_index ui_workdir
8 $ui_diff conf -state normal
9 $ui_diff delete 0.0 end
10 $ui_diff conf -state disabled
12 set current_diff_path {}
13 set current_diff_header {}
15 $ui_index tag remove in_diff 0.0 end
16 $ui_workdir tag remove in_diff 0.0 end
19 proc reshow_diff {{after {}}} {
20 global file_states file_lists
21 global current_diff_path current_diff_side
22 global ui_diff
24 set p $current_diff_path
25 if {$p eq {}} {
26 # No diff is being shown.
27 } elseif {$current_diff_side eq {}} {
28 clear_diff
29 } elseif {[catch {set s $file_states($p)}]
30 || [lsearch -sorted -exact $file_lists($current_diff_side) $p] == -1} {
32 if {[find_next_diff $current_diff_side $p {} {[^O]}]} {
33 next_diff $after
34 } else {
35 clear_diff
37 } else {
38 set save_pos [lindex [$ui_diff yview] 0]
39 show_diff $p $current_diff_side {} $save_pos $after
43 proc force_diff_encoding {enc} {
44 global current_diff_path
46 if {$current_diff_path ne {}} {
47 force_path_encoding $current_diff_path $enc
48 reshow_diff
52 proc handle_empty_diff {} {
53 global current_diff_path file_states file_lists
54 global diff_empty_count
56 set path $current_diff_path
57 set s $file_states($path)
58 if {[lindex $s 0] ne {_M} || [has_textconv $path]} return
60 # Prevent infinite rescan loops
61 incr diff_empty_count
62 if {$diff_empty_count > 1} return
64 info_popup [mc "No differences detected.
66 %s has no changes.
68 The modification date of this file was updated by another application, but the content within the file was not changed.
70 A rescan will be automatically started to find other files which may have the same state." [short_path $path]]
72 clear_diff
73 display_file $path __
74 rescan ui_ready 0
77 proc show_diff {path w {lno {}} {scroll_pos {}} {callback {}}} {
78 global file_states file_lists
79 global is_3way_diff is_conflict_diff diff_active repo_config
80 global ui_diff ui_index ui_workdir
81 global current_diff_path current_diff_side current_diff_header
82 global current_diff_queue
84 if {$diff_active || ![lock_index read]} return
86 clear_diff
87 if {$lno == {}} {
88 set lno [lsearch -sorted -exact $file_lists($w) $path]
89 if {$lno >= 0} {
90 incr lno
93 if {$lno >= 1} {
94 $w tag add in_diff $lno.0 [expr {$lno + 1}].0
95 $w see $lno.0
98 set s $file_states($path)
99 set m [lindex $s 0]
100 set is_conflict_diff 0
101 set current_diff_path $path
102 set current_diff_side $w
103 set current_diff_queue {}
104 ui_status [mc "Loading diff of %s..." [escape_path $path]]
106 set cont_info [list $scroll_pos $callback]
108 if {[string first {U} $m] >= 0} {
109 merge_load_stages $path [list show_unmerged_diff $cont_info]
110 } elseif {$m eq {_O}} {
111 show_other_diff $path $w $m $cont_info
112 } else {
113 start_show_diff $cont_info
117 proc show_unmerged_diff {cont_info} {
118 global current_diff_path current_diff_side
119 global merge_stages ui_diff is_conflict_diff
120 global current_diff_queue
122 if {$merge_stages(2) eq {}} {
123 set is_conflict_diff 1
124 lappend current_diff_queue \
125 [list [mc "LOCAL: deleted\nREMOTE:\n"] d= \
126 [list ":1:$current_diff_path" ":3:$current_diff_path"]]
127 } elseif {$merge_stages(3) eq {}} {
128 set is_conflict_diff 1
129 lappend current_diff_queue \
130 [list [mc "REMOTE: deleted\nLOCAL:\n"] d= \
131 [list ":1:$current_diff_path" ":2:$current_diff_path"]]
132 } elseif {[lindex $merge_stages(1) 0] eq {120000}
133 || [lindex $merge_stages(2) 0] eq {120000}
134 || [lindex $merge_stages(3) 0] eq {120000}} {
135 set is_conflict_diff 1
136 lappend current_diff_queue \
137 [list [mc "LOCAL:\n"] d= \
138 [list ":1:$current_diff_path" ":2:$current_diff_path"]]
139 lappend current_diff_queue \
140 [list [mc "REMOTE:\n"] d= \
141 [list ":1:$current_diff_path" ":3:$current_diff_path"]]
142 } else {
143 start_show_diff $cont_info
144 return
147 advance_diff_queue $cont_info
150 proc advance_diff_queue {cont_info} {
151 global current_diff_queue ui_diff
153 set item [lindex $current_diff_queue 0]
154 set current_diff_queue [lrange $current_diff_queue 1 end]
156 $ui_diff conf -state normal
157 $ui_diff insert end [lindex $item 0] [lindex $item 1]
158 $ui_diff conf -state disabled
160 start_show_diff $cont_info [lindex $item 2]
163 proc show_other_diff {path w m cont_info} {
164 global file_states file_lists
165 global is_3way_diff diff_active repo_config
166 global ui_diff ui_index ui_workdir
167 global current_diff_path current_diff_side current_diff_header
169 # - Git won't give us the diff, there's nothing to compare to!
171 if {$m eq {_O}} {
172 set max_sz 100000
173 set type unknown
174 if {[catch {
175 set type [file type $path]
176 switch -- $type {
177 directory {
178 set type submodule
179 set content {}
180 set sz 0
182 link {
183 set content [file readlink $path]
184 set sz [string length $content]
186 file {
187 set fd [open $path r]
188 fconfigure $fd \
189 -eofchar {} \
190 -encoding [get_path_encoding $path]
191 set content [read $fd $max_sz]
192 close $fd
193 set sz [file size $path]
195 default {
196 error "'$type' not supported"
199 } err ]} {
200 set diff_active 0
201 unlock_index
202 ui_status [mc "Unable to display %s" [escape_path $path]]
203 error_popup [strcat [mc "Error loading file:"] "\n\n$err"]
204 return
206 $ui_diff conf -state normal
207 if {$type eq {submodule}} {
208 $ui_diff insert end [append \
209 "* " \
210 [mc "Git Repository (subproject)"] \
211 "\n"] d_info
212 } elseif {![catch {set type [exec file $path]}]} {
213 set n [string length $path]
214 if {[string equal -length $n $path $type]} {
215 set type [string range $type $n end]
216 regsub {^:?\s*} $type {} type
218 $ui_diff insert end "* $type\n" d_info
220 if {[string first "\0" $content] != -1} {
221 $ui_diff insert end \
222 [mc "* Binary file (not showing content)."] \
223 d_info
224 } else {
225 if {$sz > $max_sz} {
226 $ui_diff insert end [mc \
227 "* Untracked file is %d bytes.
228 * Showing only first %d bytes.
229 " $sz $max_sz] d_info
231 $ui_diff insert end $content
232 if {$sz > $max_sz} {
233 $ui_diff insert end [mc "
234 * Untracked file clipped here by %s.
235 * To see the entire file, use an external editor.
236 " [appname]] d_info
239 $ui_diff conf -state disabled
240 set diff_active 0
241 unlock_index
242 set scroll_pos [lindex $cont_info 0]
243 if {$scroll_pos ne {}} {
244 update
245 $ui_diff yview moveto $scroll_pos
247 ui_ready
248 set callback [lindex $cont_info 1]
249 if {$callback ne {}} {
250 eval $callback
252 return
256 proc start_show_diff {cont_info {add_opts {}}} {
257 global file_states file_lists
258 global is_3way_diff is_submodule_diff diff_active repo_config
259 global ui_diff ui_index ui_workdir
260 global current_diff_path current_diff_side current_diff_header
262 set path $current_diff_path
263 set w $current_diff_side
265 set s $file_states($path)
266 set m [lindex $s 0]
267 set is_3way_diff 0
268 set is_submodule_diff 0
269 set diff_active 1
270 set current_diff_header {}
271 set conflict_size [gitattr $path conflict-marker-size 7]
273 set cmd [list]
274 if {$w eq $ui_index} {
275 lappend cmd diff-index
276 lappend cmd --cached
277 } elseif {$w eq $ui_workdir} {
278 if {[string first {U} $m] >= 0} {
279 lappend cmd diff
280 } else {
281 lappend cmd diff-files
284 if {![is_config_false gui.textconv] && [git-version >= 1.6.1]} {
285 lappend cmd --textconv
288 if {[string match {160000 *} [lindex $s 2]]
289 || [string match {160000 *} [lindex $s 3]]} {
290 set is_submodule_diff 1
292 if {[git-version >= "1.6.6"]} {
293 lappend cmd --submodule
297 lappend cmd -p
298 lappend cmd --color
299 set cmd [concat $cmd $repo_config(gui.diffopts)]
300 if {$repo_config(gui.diffcontext) >= 1} {
301 lappend cmd "-U$repo_config(gui.diffcontext)"
303 if {$w eq $ui_index} {
304 lappend cmd [PARENT]
306 if {$add_opts ne {}} {
307 eval lappend cmd $add_opts
308 } else {
309 lappend cmd --
310 lappend cmd $path
313 if {$is_submodule_diff && [git-version < "1.6.6"]} {
314 if {$w eq $ui_index} {
315 set cmd [list submodule summary --cached -- $path]
316 } else {
317 set cmd [list submodule summary --files -- $path]
321 if {[catch {set fd [eval git_read --nice $cmd]} err]} {
322 set diff_active 0
323 unlock_index
324 ui_status [mc "Unable to display %s" [escape_path $path]]
325 error_popup [strcat [mc "Error loading diff:"] "\n\n$err"]
326 return
329 set ::current_diff_inheader 1
330 fconfigure $fd \
331 -blocking 0 \
332 -encoding [get_path_encoding $path] \
333 -translation lf
334 fileevent $fd readable [list read_diff $fd $conflict_size $cont_info]
337 proc parse_color_line {line} {
338 set start 0
339 set result ""
340 set markup [list]
341 set regexp {\033\[((?:\d+;)*\d+)?m}
342 set need_reset 0
343 while {[regexp -indices -start $start $regexp $line match code]} {
344 foreach {begin end} $match break
345 append result [string range $line $start [expr {$begin - 1}]]
346 set pos [string length $result]
347 set col [eval [linsert $code 0 string range $line]]
348 set start [incr end]
349 if {$col eq "0" || $col eq ""} {
350 if {!$need_reset} continue
351 set need_reset 0
352 } else {
353 set need_reset 1
355 lappend markup $pos $col
357 append result [string range $line $start end]
358 if {[llength $markup] < 4} {set markup {}}
359 return [list $result $markup]
362 proc read_diff {fd conflict_size cont_info} {
363 global ui_diff diff_active is_submodule_diff
364 global is_3way_diff is_conflict_diff current_diff_header
365 global current_diff_queue
366 global diff_empty_count
368 $ui_diff conf -state normal
369 while {[gets $fd line] >= 0} {
370 foreach {line markup} [parse_color_line $line] break
371 set line [string map {\033 ^} $line]
373 set tags {}
375 # -- Check for start of diff header.
376 if { [string match {diff --git *} $line]
377 || [string match {diff --cc *} $line]
378 || [string match {diff --combined *} $line]} {
379 set ::current_diff_inheader 1
382 # -- Check for end of diff header (any hunk line will do this).
384 if {[regexp {^@@+ } $line]} {set ::current_diff_inheader 0}
386 # -- Automatically detect if this is a 3 way diff.
388 if {[string match {@@@ *} $line]} {set is_3way_diff 1}
390 if {$::current_diff_inheader} {
392 # -- These two lines stop a diff header and shouldn't be in there
393 if { [string match {Binary files * and * differ} $line]
394 || [regexp {^\* Unmerged path } $line]} {
395 set ::current_diff_inheader 0
396 } else {
397 append current_diff_header $line "\n"
400 # -- Cleanup uninteresting diff header lines.
402 if { [string match {diff --git *} $line]
403 || [string match {diff --cc *} $line]
404 || [string match {diff --combined *} $line]
405 || [string match {--- *} $line]
406 || [string match {+++ *} $line]
407 || [string match {index *} $line]} {
408 continue
411 # -- Name it symlink, not 120000
412 # Note, that the original line is in $current_diff_header
413 regsub {^(deleted|new) file mode 120000} $line {\1 symlink} line
415 } elseif { $line eq {\ No newline at end of file}} {
416 # -- Handle some special lines
417 } elseif {$is_3way_diff} {
418 set op [string range $line 0 1]
419 switch -- $op {
420 { } {set tags {}}
421 {@@} {set tags d_@}
422 { +} {set tags d_s+}
423 { -} {set tags d_s-}
424 {+ } {set tags d_+s}
425 {- } {set tags d_-s}
426 {--} {set tags d_--}
427 {++} {
428 set regexp [string map [list %conflict_size $conflict_size]\
429 {^\+\+([<>=]){%conflict_size}(?: |$)}]
430 if {[regexp $regexp $line _g op]} {
431 set is_conflict_diff 1
432 set line [string replace $line 0 1 { }]
433 set tags d$op
434 } else {
435 set tags d_++
438 default {
439 puts "error: Unhandled 3 way diff marker: {$op}"
440 set tags {}
443 } elseif {$is_submodule_diff} {
444 if {$line == ""} continue
445 if {[regexp {^Submodule } $line]} {
446 set tags d_info
447 } elseif {[regexp {^\* } $line]} {
448 set line [string replace $line 0 1 {Submodule }]
449 set tags d_info
450 } else {
451 set op [string range $line 0 2]
452 switch -- $op {
453 { <} {set tags d_-}
454 { >} {set tags d_+}
455 { W} {set tags {}}
456 default {
457 puts "error: Unhandled submodule diff marker: {$op}"
458 set tags {}
462 } else {
463 set op [string index $line 0]
464 switch -- $op {
465 { } {set tags {}}
466 {@} {set tags d_@}
467 {-} {set tags d_-}
468 {+} {
469 set regexp [string map [list %conflict_size $conflict_size]\
470 {^\+([<>=]){%conflict_size}(?: |$)}]
471 if {[regexp $regexp $line _g op]} {
472 set is_conflict_diff 1
473 set tags d$op
474 } else {
475 set tags d_+
478 default {
479 puts "error: Unhandled 2 way diff marker: {$op}"
480 set tags {}
484 set mark [$ui_diff index "end - 1 line linestart"]
485 $ui_diff insert end $line $tags
486 if {[string index $line end] eq "\r"} {
487 $ui_diff tag add d_cr {end - 2c}
489 $ui_diff insert end "\n" $tags
491 foreach {posbegin colbegin posend colend} $markup {
492 set prefix clr
493 foreach style [lsort -integer [split $colbegin ";"]] {
494 if {$style eq "7"} {append prefix i; continue}
495 if {$style != 4 && ($style < 30 || $style > 47)} {continue}
496 set a "$mark linestart + $posbegin chars"
497 set b "$mark linestart + $posend chars"
498 catch {$ui_diff tag add $prefix$style $a $b}
502 $ui_diff conf -state disabled
504 if {[eof $fd]} {
505 close $fd
507 if {$current_diff_queue ne {}} {
508 advance_diff_queue $cont_info
509 return
512 set diff_active 0
513 unlock_index
514 set scroll_pos [lindex $cont_info 0]
515 if {$scroll_pos ne {}} {
516 update
517 $ui_diff yview moveto $scroll_pos
519 ui_ready
521 if {[$ui_diff index end] eq {2.0}} {
522 handle_empty_diff
523 } else {
524 set diff_empty_count 0
527 set callback [lindex $cont_info 1]
528 if {$callback ne {}} {
529 eval $callback
534 proc apply_hunk {x y} {
535 global current_diff_path current_diff_header current_diff_side
536 global ui_diff ui_index file_states
538 if {$current_diff_path eq {} || $current_diff_header eq {}} return
539 if {![lock_index apply_hunk]} return
541 set apply_cmd {apply --cached --whitespace=nowarn}
542 set mi [lindex $file_states($current_diff_path) 0]
543 if {$current_diff_side eq $ui_index} {
544 set failed_msg [mc "Failed to unstage selected hunk."]
545 lappend apply_cmd --reverse
546 if {[string index $mi 0] ne {M}} {
547 unlock_index
548 return
550 } else {
551 set failed_msg [mc "Failed to stage selected hunk."]
552 if {[string index $mi 1] ne {M}} {
553 unlock_index
554 return
558 set s_lno [lindex [split [$ui_diff index @$x,$y] .] 0]
559 set s_lno [$ui_diff search -backwards -regexp ^@@ $s_lno.0 0.0]
560 if {$s_lno eq {}} {
561 unlock_index
562 return
565 set e_lno [$ui_diff search -forwards -regexp ^@@ "$s_lno + 1 lines" end]
566 if {$e_lno eq {}} {
567 set e_lno end
570 if {[catch {
571 set enc [get_path_encoding $current_diff_path]
572 set p [eval git_write $apply_cmd]
573 fconfigure $p -translation binary -encoding $enc
574 puts -nonewline $p $current_diff_header
575 puts -nonewline $p [$ui_diff get $s_lno $e_lno]
576 close $p} err]} {
577 error_popup [append $failed_msg "\n\n$err"]
578 unlock_index
579 return
582 $ui_diff conf -state normal
583 $ui_diff delete $s_lno $e_lno
584 $ui_diff conf -state disabled
586 if {[$ui_diff get 1.0 end] eq "\n"} {
587 set o _
588 } else {
589 set o ?
592 if {$current_diff_side eq $ui_index} {
593 set mi ${o}M
594 } elseif {[string index $mi 0] eq {_}} {
595 set mi M$o
596 } else {
597 set mi ?$o
599 unlock_index
600 display_file $current_diff_path $mi
601 # This should trigger shift to the next changed file
602 if {$o eq {_}} {
603 reshow_diff
607 proc apply_range_or_line {x y} {
608 global current_diff_path current_diff_header current_diff_side
609 global ui_diff ui_index file_states
611 set selected [$ui_diff tag nextrange sel 0.0]
613 if {$selected == {}} {
614 set first [$ui_diff index "@$x,$y"]
615 set last $first
616 } else {
617 set first [lindex $selected 0]
618 set last [lindex $selected 1]
621 set first_l [$ui_diff index "$first linestart"]
622 set last_l [$ui_diff index "$last lineend"]
624 if {$current_diff_path eq {} || $current_diff_header eq {}} return
625 if {![lock_index apply_hunk]} return
627 set apply_cmd {apply --cached --whitespace=nowarn}
628 set mi [lindex $file_states($current_diff_path) 0]
629 if {$current_diff_side eq $ui_index} {
630 set failed_msg [mc "Failed to unstage selected line."]
631 set to_context {+}
632 lappend apply_cmd --reverse
633 if {[string index $mi 0] ne {M}} {
634 unlock_index
635 return
637 } else {
638 set failed_msg [mc "Failed to stage selected line."]
639 set to_context {-}
640 if {[string index $mi 1] ne {M}} {
641 unlock_index
642 return
646 set wholepatch {}
648 while {$first_l < $last_l} {
649 set i_l [$ui_diff search -backwards -regexp ^@@ $first_l 0.0]
650 if {$i_l eq {}} {
651 # If there's not a @@ above, then the selected range
652 # must have come before the first_l @@
653 set i_l [$ui_diff search -regexp ^@@ $first_l $last_l]
655 if {$i_l eq {}} {
656 unlock_index
657 return
659 # $i_l is now at the beginning of a line
661 # pick start line number from hunk header
662 if {![regexp {^@@ -(\d+)(?:,\d+)? \+(?:\d+)(?:,\d+)? @@(?:\s|$)} \
663 [$ui_diff get $i_l "$i_l + 1 lines"] hh hln]} {
664 unlock_index
665 return
668 # There is a special situation to take care of. Consider this
669 # hunk:
671 # @@ -10,4 +10,4 @@
672 # context before
673 # -old 1
674 # -old 2
675 # +new 1
676 # +new 2
677 # context after
679 # We used to keep the context lines in the order they appear in
680 # the hunk. But then it is not possible to correctly stage only
681 # "-old 1" and "+new 1" - it would result in this staged text:
683 # context before
684 # old 2
685 # new 1
686 # context after
688 # (By symmetry it is not possible to *un*stage "old 2" and "new
689 # 2".)
691 # We resolve the problem by introducing an asymmetry, namely,
692 # when a "+" line is *staged*, it is moved in front of the
693 # context lines that are generated from the "-" lines that are
694 # immediately before the "+" block. That is, we construct this
695 # patch:
697 # @@ -10,4 +10,5 @@
698 # context before
699 # +new 1
700 # old 1
701 # old 2
702 # context after
704 # But we do *not* treat "-" lines that are *un*staged in a
705 # special way.
707 # With this asymmetry it is possible to stage the change "old
708 # 1" -> "new 1" directly, and to stage the change "old 2" ->
709 # "new 2" by first staging the entire hunk and then unstaging
710 # the change "old 1" -> "new 1".
712 # Applying multiple lines adds complexity to the special
713 # situation. The pre_context must be moved after the entire
714 # first block of consecutive staged "+" lines, so that
715 # staging both additions gives the following patch:
717 # @@ -10,4 +10,6 @@
718 # context before
719 # +new 1
720 # +new 2
721 # old 1
722 # old 2
723 # context after
725 # This is non-empty if and only if we are _staging_ changes;
726 # then it accumulates the consecutive "-" lines (after
727 # converting them to context lines) in order to be moved after
728 # "+" change lines.
729 set pre_context {}
731 set n 0
732 set m 0
733 set i_l [$ui_diff index "$i_l + 1 lines"]
734 set patch {}
735 while {[$ui_diff compare $i_l < "end - 1 chars"] &&
736 [$ui_diff get $i_l "$i_l + 2 chars"] ne {@@}} {
737 set next_l [$ui_diff index "$i_l + 1 lines"]
738 set c1 [$ui_diff get $i_l]
739 if {[$ui_diff compare $first_l <= $i_l] &&
740 [$ui_diff compare $i_l < $last_l] &&
741 ($c1 eq {-} || $c1 eq {+})} {
742 # a line to stage/unstage
743 set ln [$ui_diff get $i_l $next_l]
744 if {$c1 eq {-}} {
745 set n [expr $n+1]
746 set patch "$patch$pre_context$ln"
747 set pre_context {}
748 } else {
749 set m [expr $m+1]
750 set patch "$patch$ln"
752 } elseif {$c1 ne {-} && $c1 ne {+}} {
753 # context line
754 set ln [$ui_diff get $i_l $next_l]
755 set patch "$patch$pre_context$ln"
756 # Skip the "\ No newline at end of
757 # file". Depending on the locale setting
758 # we don't know what this line looks
759 # like exactly. The only thing we do
760 # know is that it starts with "\ "
761 if {![string match {\\ *} $ln]} {
762 set n [expr $n+1]
763 set m [expr $m+1]
765 set pre_context {}
766 } elseif {$c1 eq $to_context} {
767 # turn change line into context line
768 set ln [$ui_diff get "$i_l + 1 chars" $next_l]
769 if {$c1 eq {-}} {
770 set pre_context "$pre_context $ln"
771 } else {
772 set patch "$patch $ln"
774 set n [expr $n+1]
775 set m [expr $m+1]
776 } else {
777 # a change in the opposite direction of
778 # to_context which is outside the range of
779 # lines to apply.
780 set patch "$patch$pre_context"
781 set pre_context {}
783 set i_l $next_l
785 set patch "$patch$pre_context"
786 set wholepatch "$wholepatch@@ -$hln,$n +$hln,$m @@\n$patch"
787 set first_l [$ui_diff index "$next_l + 1 lines"]
790 if {[catch {
791 set enc [get_path_encoding $current_diff_path]
792 set p [eval git_write $apply_cmd]
793 fconfigure $p -translation binary -encoding $enc
794 puts -nonewline $p $current_diff_header
795 puts -nonewline $p $wholepatch
796 close $p} err]} {
797 error_popup [append $failed_msg "\n\n$err"]
800 unlock_index