git-guion commit git-gui: Abort on not implemented branch switching. (2171bf4)
   1#!/bin/sh
   2# Tcl ignores the next line -*- tcl -*- \
   3exec wish "$0" -- "$@"
   4
   5set copyright {
   6Copyright © 2006 Shawn Pearce, Paul Mackerras.
   7
   8All rights reserved.
   9
  10This program is free software; it may be used, copied, modified
  11and distributed under the terms of the GNU General Public Licence,
  12either version 2, or (at your option) any later version.}
  13
  14set appname [lindex [file split $argv0] end]
  15set gitdir {}
  16
  17######################################################################
  18##
  19## config
  20
  21proc is_many_config {name} {
  22        switch -glob -- $name {
  23        remote.*.fetch -
  24        remote.*.push
  25                {return 1}
  26        *
  27                {return 0}
  28        }
  29}
  30
  31proc load_config {include_global} {
  32        global repo_config global_config default_config
  33
  34        array unset global_config
  35        if {$include_global} {
  36                catch {
  37                        set fd_rc [open "| git repo-config --global --list" r]
  38                        while {[gets $fd_rc line] >= 0} {
  39                                if {[regexp {^([^=]+)=(.*)$} $line line name value]} {
  40                                        if {[is_many_config $name]} {
  41                                                lappend global_config($name) $value
  42                                        } else {
  43                                                set global_config($name) $value
  44                                        }
  45                                }
  46                        }
  47                        close $fd_rc
  48                }
  49        }
  50
  51        array unset repo_config
  52        catch {
  53                set fd_rc [open "| git repo-config --list" r]
  54                while {[gets $fd_rc line] >= 0} {
  55                        if {[regexp {^([^=]+)=(.*)$} $line line name value]} {
  56                                if {[is_many_config $name]} {
  57                                        lappend repo_config($name) $value
  58                                } else {
  59                                        set repo_config($name) $value
  60                                }
  61                        }
  62                }
  63                close $fd_rc
  64        }
  65
  66        foreach name [array names default_config] {
  67                if {[catch {set v $global_config($name)}]} {
  68                        set global_config($name) $default_config($name)
  69                }
  70                if {[catch {set v $repo_config($name)}]} {
  71                        set repo_config($name) $default_config($name)
  72                }
  73        }
  74}
  75
  76proc save_config {} {
  77        global default_config font_descs
  78        global repo_config global_config
  79        global repo_config_new global_config_new
  80
  81        foreach option $font_descs {
  82                set name [lindex $option 0]
  83                set font [lindex $option 1]
  84                font configure $font \
  85                        -family $global_config_new(gui.$font^^family) \
  86                        -size $global_config_new(gui.$font^^size)
  87                font configure ${font}bold \
  88                        -family $global_config_new(gui.$font^^family) \
  89                        -size $global_config_new(gui.$font^^size)
  90                set global_config_new(gui.$name) [font configure $font]
  91                unset global_config_new(gui.$font^^family)
  92                unset global_config_new(gui.$font^^size)
  93        }
  94
  95        foreach name [array names default_config] {
  96                set value $global_config_new($name)
  97                if {$value ne $global_config($name)} {
  98                        if {$value eq $default_config($name)} {
  99                                catch {exec git repo-config --global --unset $name}
 100                        } else {
 101                                regsub -all "\[{}\]" $value {"} value
 102                                exec git repo-config --global $name $value
 103                        }
 104                        set global_config($name) $value
 105                        if {$value eq $repo_config($name)} {
 106                                catch {exec git repo-config --unset $name}
 107                                set repo_config($name) $value
 108                        }
 109                }
 110        }
 111
 112        foreach name [array names default_config] {
 113                set value $repo_config_new($name)
 114                if {$value ne $repo_config($name)} {
 115                        if {$value eq $global_config($name)} {
 116                                catch {exec git repo-config --unset $name}
 117                        } else {
 118                                regsub -all "\[{}\]" $value {"} value
 119                                exec git repo-config $name $value
 120                        }
 121                        set repo_config($name) $value
 122                }
 123        }
 124}
 125
 126proc error_popup {msg} {
 127        global gitdir appname
 128
 129        set title $appname
 130        if {$gitdir ne {}} {
 131                append title { (}
 132                append title [lindex \
 133                        [file split [file normalize [file dirname $gitdir]]] \
 134                        end]
 135                append title {)}
 136        }
 137        set cmd [list tk_messageBox \
 138                -icon error \
 139                -type ok \
 140                -title "$title: error" \
 141                -message $msg]
 142        if {[winfo ismapped .]} {
 143                lappend cmd -parent .
 144        }
 145        eval $cmd
 146}
 147
 148proc warn_popup {msg} {
 149        global gitdir appname
 150
 151        set title $appname
 152        if {$gitdir ne {}} {
 153                append title { (}
 154                append title [lindex \
 155                        [file split [file normalize [file dirname $gitdir]]] \
 156                        end]
 157                append title {)}
 158        }
 159        set cmd [list tk_messageBox \
 160                -icon warning \
 161                -type ok \
 162                -title "$title: warning" \
 163                -message $msg]
 164        if {[winfo ismapped .]} {
 165                lappend cmd -parent .
 166        }
 167        eval $cmd
 168}
 169
 170proc info_popup {msg} {
 171        global gitdir appname
 172
 173        set title $appname
 174        if {$gitdir ne {}} {
 175                append title { (}
 176                append title [lindex \
 177                        [file split [file normalize [file dirname $gitdir]]] \
 178                        end]
 179                append title {)}
 180        }
 181        tk_messageBox \
 182                -parent . \
 183                -icon info \
 184                -type ok \
 185                -title $title \
 186                -message $msg
 187}
 188
 189######################################################################
 190##
 191## repository setup
 192
 193if {   [catch {set gitdir $env(GIT_DIR)}]
 194        && [catch {set gitdir [exec git rev-parse --git-dir]} err]} {
 195        catch {wm withdraw .}
 196        error_popup "Cannot find the git directory:\n\n$err"
 197        exit 1
 198}
 199if {![file isdirectory $gitdir]} {
 200        catch {wm withdraw .}
 201        error_popup "Git directory not found:\n\n$gitdir"
 202        exit 1
 203}
 204if {[lindex [file split $gitdir] end] ne {.git}} {
 205        catch {wm withdraw .}
 206        error_popup "Cannot use funny .git directory:\n\n$gitdir"
 207        exit 1
 208}
 209if {[catch {cd [file dirname $gitdir]} err]} {
 210        catch {wm withdraw .}
 211        error_popup "No working directory [file dirname $gitdir]:\n\n$err"
 212        exit 1
 213}
 214
 215set single_commit 0
 216if {$appname eq {git-citool}} {
 217        set single_commit 1
 218}
 219
 220######################################################################
 221##
 222## task management
 223
 224set rescan_active 0
 225set diff_active 0
 226set last_clicked {}
 227
 228set disable_on_lock [list]
 229set index_lock_type none
 230
 231proc lock_index {type} {
 232        global index_lock_type disable_on_lock
 233
 234        if {$index_lock_type eq {none}} {
 235                set index_lock_type $type
 236                foreach w $disable_on_lock {
 237                        uplevel #0 $w disabled
 238                }
 239                return 1
 240        } elseif {$index_lock_type eq "begin-$type"} {
 241                set index_lock_type $type
 242                return 1
 243        }
 244        return 0
 245}
 246
 247proc unlock_index {} {
 248        global index_lock_type disable_on_lock
 249
 250        set index_lock_type none
 251        foreach w $disable_on_lock {
 252                uplevel #0 $w normal
 253        }
 254}
 255
 256######################################################################
 257##
 258## status
 259
 260proc repository_state {ctvar hdvar mhvar} {
 261        global gitdir current_branch
 262        upvar $ctvar ct $hdvar hd $mhvar mh
 263
 264        set mh [list]
 265
 266        if {[catch {set current_branch [exec git symbolic-ref HEAD]}]} {
 267                set current_branch {}
 268        } else {
 269                regsub ^refs/((heads|tags|remotes)/)? \
 270                        $current_branch \
 271                        {} \
 272                        current_branch
 273        }
 274
 275        if {[catch {set hd [exec git rev-parse --verify HEAD]}]} {
 276                set hd {}
 277                set ct initial
 278                return
 279        }
 280
 281        set merge_head [file join $gitdir MERGE_HEAD]
 282        if {[file exists $merge_head]} {
 283                set ct merge
 284                set fd_mh [open $merge_head r]
 285                while {[gets $fd_mh line] >= 0} {
 286                        lappend mh $line
 287                }
 288                close $fd_mh
 289                return
 290        }
 291
 292        set ct normal
 293}
 294
 295proc PARENT {} {
 296        global PARENT empty_tree
 297
 298        set p [lindex $PARENT 0]
 299        if {$p ne {}} {
 300                return $p
 301        }
 302        if {$empty_tree eq {}} {
 303                set empty_tree [exec git mktree << {}]
 304        }
 305        return $empty_tree
 306}
 307
 308proc rescan {after} {
 309        global HEAD PARENT MERGE_HEAD commit_type
 310        global ui_index ui_other ui_status_value ui_comm
 311        global rescan_active file_states
 312        global repo_config
 313
 314        if {$rescan_active > 0 || ![lock_index read]} return
 315
 316        repository_state newType newHEAD newMERGE_HEAD
 317        if {[string match amend* $commit_type]
 318                && $newType eq {normal}
 319                && $newHEAD eq $HEAD} {
 320        } else {
 321                set HEAD $newHEAD
 322                set PARENT $newHEAD
 323                set MERGE_HEAD $newMERGE_HEAD
 324                set commit_type $newType
 325        }
 326
 327        array unset file_states
 328
 329        if {![$ui_comm edit modified]
 330                || [string trim [$ui_comm get 0.0 end]] eq {}} {
 331                if {[load_message GITGUI_MSG]} {
 332                } elseif {[load_message MERGE_MSG]} {
 333                } elseif {[load_message SQUASH_MSG]} {
 334                }
 335                $ui_comm edit reset
 336                $ui_comm edit modified false
 337        }
 338
 339        if {$repo_config(gui.trustmtime) eq {true}} {
 340                rescan_stage2 {} $after
 341        } else {
 342                set rescan_active 1
 343                set ui_status_value {Refreshing file status...}
 344                set cmd [list git update-index]
 345                lappend cmd -q
 346                lappend cmd --unmerged
 347                lappend cmd --ignore-missing
 348                lappend cmd --refresh
 349                set fd_rf [open "| $cmd" r]
 350                fconfigure $fd_rf -blocking 0 -translation binary
 351                fileevent $fd_rf readable \
 352                        [list rescan_stage2 $fd_rf $after]
 353        }
 354}
 355
 356proc rescan_stage2 {fd after} {
 357        global gitdir ui_status_value
 358        global rescan_active buf_rdi buf_rdf buf_rlo
 359
 360        if {$fd ne {}} {
 361                read $fd
 362                if {![eof $fd]} return
 363                close $fd
 364        }
 365
 366        set ls_others [list | git ls-files --others -z \
 367                --exclude-per-directory=.gitignore]
 368        set info_exclude [file join $gitdir info exclude]
 369        if {[file readable $info_exclude]} {
 370                lappend ls_others "--exclude-from=$info_exclude"
 371        }
 372
 373        set buf_rdi {}
 374        set buf_rdf {}
 375        set buf_rlo {}
 376
 377        set rescan_active 3
 378        set ui_status_value {Scanning for modified files ...}
 379        set fd_di [open "| git diff-index --cached -z [PARENT]" r]
 380        set fd_df [open "| git diff-files -z" r]
 381        set fd_lo [open $ls_others r]
 382
 383        fconfigure $fd_di -blocking 0 -translation binary
 384        fconfigure $fd_df -blocking 0 -translation binary
 385        fconfigure $fd_lo -blocking 0 -translation binary
 386        fileevent $fd_di readable [list read_diff_index $fd_di $after]
 387        fileevent $fd_df readable [list read_diff_files $fd_df $after]
 388        fileevent $fd_lo readable [list read_ls_others $fd_lo $after]
 389}
 390
 391proc load_message {file} {
 392        global gitdir ui_comm
 393
 394        set f [file join $gitdir $file]
 395        if {[file isfile $f]} {
 396                if {[catch {set fd [open $f r]}]} {
 397                        return 0
 398                }
 399                set content [string trim [read $fd]]
 400                close $fd
 401                $ui_comm delete 0.0 end
 402                $ui_comm insert end $content
 403                return 1
 404        }
 405        return 0
 406}
 407
 408proc read_diff_index {fd after} {
 409        global buf_rdi
 410
 411        append buf_rdi [read $fd]
 412        set c 0
 413        set n [string length $buf_rdi]
 414        while {$c < $n} {
 415                set z1 [string first "\0" $buf_rdi $c]
 416                if {$z1 == -1} break
 417                incr z1
 418                set z2 [string first "\0" $buf_rdi $z1]
 419                if {$z2 == -1} break
 420
 421                incr c
 422                set i [split [string range $buf_rdi $c [expr {$z1 - 2}]] { }]
 423                merge_state \
 424                        [string range $buf_rdi $z1 [expr {$z2 - 1}]] \
 425                        [lindex $i 4]? \
 426                        [list [lindex $i 0] [lindex $i 2]] \
 427                        [list]
 428                set c $z2
 429                incr c
 430        }
 431        if {$c < $n} {
 432                set buf_rdi [string range $buf_rdi $c end]
 433        } else {
 434                set buf_rdi {}
 435        }
 436
 437        rescan_done $fd buf_rdi $after
 438}
 439
 440proc read_diff_files {fd after} {
 441        global buf_rdf
 442
 443        append buf_rdf [read $fd]
 444        set c 0
 445        set n [string length $buf_rdf]
 446        while {$c < $n} {
 447                set z1 [string first "\0" $buf_rdf $c]
 448                if {$z1 == -1} break
 449                incr z1
 450                set z2 [string first "\0" $buf_rdf $z1]
 451                if {$z2 == -1} break
 452
 453                incr c
 454                set i [split [string range $buf_rdf $c [expr {$z1 - 2}]] { }]
 455                merge_state \
 456                        [string range $buf_rdf $z1 [expr {$z2 - 1}]] \
 457                        ?[lindex $i 4] \
 458                        [list] \
 459                        [list [lindex $i 0] [lindex $i 2]]
 460                set c $z2
 461                incr c
 462        }
 463        if {$c < $n} {
 464                set buf_rdf [string range $buf_rdf $c end]
 465        } else {
 466                set buf_rdf {}
 467        }
 468
 469        rescan_done $fd buf_rdf $after
 470}
 471
 472proc read_ls_others {fd after} {
 473        global buf_rlo
 474
 475        append buf_rlo [read $fd]
 476        set pck [split $buf_rlo "\0"]
 477        set buf_rlo [lindex $pck end]
 478        foreach p [lrange $pck 0 end-1] {
 479                merge_state $p ?O
 480        }
 481        rescan_done $fd buf_rlo $after
 482}
 483
 484proc rescan_done {fd buf after} {
 485        global rescan_active
 486        global file_states repo_config
 487        upvar $buf to_clear
 488
 489        if {![eof $fd]} return
 490        set to_clear {}
 491        close $fd
 492        if {[incr rescan_active -1] > 0} return
 493
 494        prune_selection
 495        unlock_index
 496        display_all_files
 497
 498        if {$repo_config(gui.partialinclude) ne {true}} {
 499                set pathList [list]
 500                foreach path [array names file_states] {
 501                        switch -- [lindex $file_states($path) 0] {
 502                        AM -
 503                        MM {lappend pathList $path}
 504                        }
 505                }
 506                if {$pathList ne {}} {
 507                        update_index \
 508                                "Updating included files" \
 509                                $pathList \
 510                                [concat {reshow_diff;} $after]
 511                        return
 512                }
 513        }
 514
 515        reshow_diff
 516        uplevel #0 $after
 517}
 518
 519proc prune_selection {} {
 520        global file_states selected_paths
 521
 522        foreach path [array names selected_paths] {
 523                if {[catch {set still_here $file_states($path)}]} {
 524                        unset selected_paths($path)
 525                }
 526        }
 527}
 528
 529######################################################################
 530##
 531## diff
 532
 533proc clear_diff {} {
 534        global ui_diff current_diff ui_index ui_other
 535
 536        $ui_diff conf -state normal
 537        $ui_diff delete 0.0 end
 538        $ui_diff conf -state disabled
 539
 540        set current_diff {}
 541
 542        $ui_index tag remove in_diff 0.0 end
 543        $ui_other tag remove in_diff 0.0 end
 544}
 545
 546proc reshow_diff {} {
 547        global current_diff ui_status_value file_states
 548
 549        if {$current_diff eq {}
 550                || [catch {set s $file_states($current_diff)}]} {
 551                clear_diff
 552        } else {
 553                show_diff $current_diff
 554        }
 555}
 556
 557proc handle_empty_diff {} {
 558        global current_diff file_states file_lists
 559
 560        set path $current_diff
 561        set s $file_states($path)
 562        if {[lindex $s 0] ne {_M}} return
 563
 564        info_popup "No differences detected.
 565
 566[short_path $path] has no changes.
 567
 568The modification date of this file was updated
 569by another application and you currently have
 570the Trust File Modification Timestamps option
 571enabled, so Git did not automatically detect
 572that there are no content differences in this
 573file.
 574
 575This file will now be removed from the modified
 576files list, to prevent possible confusion.
 577"
 578        if {[catch {exec git update-index -- $path} err]} {
 579                error_popup "Failed to refresh index:\n\n$err"
 580        }
 581
 582        clear_diff
 583        set old_w [mapcol [lindex $file_states($path) 0] $path]
 584        set lno [lsearch -sorted $file_lists($old_w) $path]
 585        if {$lno >= 0} {
 586                set file_lists($old_w) \
 587                        [lreplace $file_lists($old_w) $lno $lno]
 588                incr lno
 589                $old_w conf -state normal
 590                $old_w delete $lno.0 [expr {$lno + 1}].0
 591                $old_w conf -state disabled
 592        }
 593}
 594
 595proc show_diff {path {w {}} {lno {}}} {
 596        global file_states file_lists
 597        global is_3way_diff diff_active repo_config
 598        global ui_diff current_diff ui_status_value
 599
 600        if {$diff_active || ![lock_index read]} return
 601
 602        clear_diff
 603        if {$w eq {} || $lno == {}} {
 604                foreach w [array names file_lists] {
 605                        set lno [lsearch -sorted $file_lists($w) $path]
 606                        if {$lno >= 0} {
 607                                incr lno
 608                                break
 609                        }
 610                }
 611        }
 612        if {$w ne {} && $lno >= 1} {
 613                $w tag add in_diff $lno.0 [expr {$lno + 1}].0
 614        }
 615
 616        set s $file_states($path)
 617        set m [lindex $s 0]
 618        set is_3way_diff 0
 619        set diff_active 1
 620        set current_diff $path
 621        set ui_status_value "Loading diff of [escape_path $path]..."
 622
 623        set cmd [list | git diff-index]
 624        lappend cmd --no-color
 625        if {$repo_config(gui.diffcontext) > 0} {
 626                lappend cmd "-U$repo_config(gui.diffcontext)"
 627        }
 628        lappend cmd -p
 629
 630        switch $m {
 631        MM {
 632                lappend cmd -c
 633        }
 634        _O {
 635                if {[catch {
 636                                set fd [open $path r]
 637                                set content [read $fd]
 638                                close $fd
 639                        } err ]} {
 640                        set diff_active 0
 641                        unlock_index
 642                        set ui_status_value "Unable to display [escape_path $path]"
 643                        error_popup "Error loading file:\n\n$err"
 644                        return
 645                }
 646                $ui_diff conf -state normal
 647                $ui_diff insert end $content
 648                $ui_diff conf -state disabled
 649                set diff_active 0
 650                unlock_index
 651                set ui_status_value {Ready.}
 652                return
 653        }
 654        }
 655
 656        lappend cmd [PARENT]
 657        lappend cmd --
 658        lappend cmd $path
 659
 660        if {[catch {set fd [open $cmd r]} err]} {
 661                set diff_active 0
 662                unlock_index
 663                set ui_status_value "Unable to display [escape_path $path]"
 664                error_popup "Error loading diff:\n\n$err"
 665                return
 666        }
 667
 668        fconfigure $fd -blocking 0 -translation auto
 669        fileevent $fd readable [list read_diff $fd]
 670}
 671
 672proc read_diff {fd} {
 673        global ui_diff ui_status_value is_3way_diff diff_active
 674        global repo_config
 675
 676        $ui_diff conf -state normal
 677        while {[gets $fd line] >= 0} {
 678                # -- Cleanup uninteresting diff header lines.
 679                #
 680                if {[string match {diff --git *}      $line]} continue
 681                if {[string match {diff --combined *} $line]} continue
 682                if {[string match {--- *}             $line]} continue
 683                if {[string match {+++ *}             $line]} continue
 684                if {$line eq {deleted file mode 120000}} {
 685                        set line "deleted symlink"
 686                }
 687
 688                # -- Automatically detect if this is a 3 way diff.
 689                #
 690                if {[string match {@@@ *} $line]} {set is_3way_diff 1}
 691
 692                # -- Reformat a 3 way diff, 'cause its too weird.
 693                #
 694                if {$is_3way_diff} {
 695                        set op [string range $line 0 1]
 696                        switch -- $op {
 697                        {@@} {set tags d_@}
 698                        {++} {set tags d_+ ; set op { +}}
 699                        {--} {set tags d_- ; set op { -}}
 700                        { +} {set tags d_++; set op {++}}
 701                        { -} {set tags d_--; set op {--}}
 702                        {+ } {set tags d_-+; set op {-+}}
 703                        {- } {set tags d_+-; set op {+-}}
 704                        default {set tags {}}
 705                        }
 706                        set line [string replace $line 0 1 $op]
 707                } else {
 708                        switch -- [string index $line 0] {
 709                        @ {set tags d_@}
 710                        + {set tags d_+}
 711                        - {set tags d_-}
 712                        default {set tags {}}
 713                        }
 714                }
 715                $ui_diff insert end $line $tags
 716                $ui_diff insert end "\n" $tags
 717        }
 718        $ui_diff conf -state disabled
 719
 720        if {[eof $fd]} {
 721                close $fd
 722                set diff_active 0
 723                unlock_index
 724                set ui_status_value {Ready.}
 725
 726                if {$repo_config(gui.trustmtime) eq {true}
 727                        && [$ui_diff index end] eq {2.0}} {
 728                        handle_empty_diff
 729                }
 730        }
 731}
 732
 733######################################################################
 734##
 735## commit
 736
 737proc load_last_commit {} {
 738        global HEAD PARENT MERGE_HEAD commit_type ui_comm
 739
 740        if {[llength $PARENT] == 0} {
 741                error_popup {There is nothing to amend.
 742
 743You are about to create the initial commit.
 744There is no commit before this to amend.
 745}
 746                return
 747        }
 748
 749        repository_state curType curHEAD curMERGE_HEAD
 750        if {$curType eq {merge}} {
 751                error_popup {Cannot amend while merging.
 752
 753You are currently in the middle of a merge that
 754has not been fully completed.  You cannot amend
 755the prior commit unless you first abort the
 756current merge activity.
 757}
 758                return
 759        }
 760
 761        set msg {}
 762        set parents [list]
 763        if {[catch {
 764                        set fd [open "| git cat-file commit $curHEAD" r]
 765                        while {[gets $fd line] > 0} {
 766                                if {[string match {parent *} $line]} {
 767                                        lappend parents [string range $line 7 end]
 768                                }
 769                        }
 770                        set msg [string trim [read $fd]]
 771                        close $fd
 772                } err]} {
 773                error_popup "Error loading commit data for amend:\n\n$err"
 774                return
 775        }
 776
 777        set HEAD $curHEAD
 778        set PARENT $parents
 779        set MERGE_HEAD [list]
 780        switch -- [llength $parents] {
 781        0       {set commit_type amend-initial}
 782        1       {set commit_type amend}
 783        default {set commit_type amend-merge}
 784        }
 785
 786        $ui_comm delete 0.0 end
 787        $ui_comm insert end $msg
 788        $ui_comm edit reset
 789        $ui_comm edit modified false
 790        rescan {set ui_status_value {Ready.}}
 791}
 792
 793proc create_new_commit {} {
 794        global commit_type ui_comm
 795
 796        set commit_type normal
 797        $ui_comm delete 0.0 end
 798        $ui_comm edit reset
 799        $ui_comm edit modified false
 800        rescan {set ui_status_value {Ready.}}
 801}
 802
 803set GIT_COMMITTER_IDENT {}
 804
 805proc committer_ident {} {
 806        global GIT_COMMITTER_IDENT
 807
 808        if {$GIT_COMMITTER_IDENT eq {}} {
 809                if {[catch {set me [exec git var GIT_COMMITTER_IDENT]} err]} {
 810                        error_popup "Unable to obtain your identity:\n\n$err"
 811                        return {}
 812                }
 813                if {![regexp {^(.*) [0-9]+ [-+0-9]+$} \
 814                        $me me GIT_COMMITTER_IDENT]} {
 815                        error_popup "Invalid GIT_COMMITTER_IDENT:\n\n$me"
 816                        return {}
 817                }
 818        }
 819
 820        return $GIT_COMMITTER_IDENT
 821}
 822
 823proc commit_tree {} {
 824        global HEAD commit_type file_states ui_comm repo_config
 825
 826        if {![lock_index update]} return
 827        if {[committer_ident] eq {}} return
 828
 829        # -- Our in memory state should match the repository.
 830        #
 831        repository_state curType curHEAD curMERGE_HEAD
 832        if {[string match amend* $commit_type]
 833                && $curType eq {normal}
 834                && $curHEAD eq $HEAD} {
 835        } elseif {$commit_type ne $curType || $HEAD ne $curHEAD} {
 836                info_popup {Last scanned state does not match repository state.
 837
 838Another Git program has modified this repository
 839since the last scan.  A rescan must be performed
 840before another commit can be created.
 841
 842The rescan will be automatically started now.
 843}
 844                unlock_index
 845                rescan {set ui_status_value {Ready.}}
 846                return
 847        }
 848
 849        # -- At least one file should differ in the index.
 850        #
 851        set files_ready 0
 852        foreach path [array names file_states] {
 853                switch -glob -- [lindex $file_states($path) 0] {
 854                _? {continue}
 855                A? -
 856                D? -
 857                M? {set files_ready 1; break}
 858                U? {
 859                        error_popup "Unmerged files cannot be committed.
 860
 861File [short_path $path] has merge conflicts.
 862You must resolve them and include the file before committing.
 863"
 864                        unlock_index
 865                        return
 866                }
 867                default {
 868                        error_popup "Unknown file state [lindex $s 0] detected.
 869
 870File [short_path $path] cannot be committed by this program.
 871"
 872                }
 873                }
 874        }
 875        if {!$files_ready} {
 876                error_popup {No included files to commit.
 877
 878You must include at least 1 file before you can commit.
 879}
 880                unlock_index
 881                return
 882        }
 883
 884        # -- A message is required.
 885        #
 886        set msg [string trim [$ui_comm get 1.0 end]]
 887        if {$msg eq {}} {
 888                error_popup {Please supply a commit message.
 889
 890A good commit message has the following format:
 891
 892- First line: Describe in one sentance what you did.
 893- Second line: Blank
 894- Remaining lines: Describe why this change is good.
 895}
 896                unlock_index
 897                return
 898        }
 899
 900        # -- Update included files if partialincludes are off.
 901        #
 902        if {$repo_config(gui.partialinclude) ne {true}} {
 903                set pathList [list]
 904                foreach path [array names file_states] {
 905                        switch -glob -- [lindex $file_states($path) 0] {
 906                        A? -
 907                        M? {lappend pathList $path}
 908                        }
 909                }
 910                if {$pathList ne {}} {
 911                        unlock_index
 912                        update_index \
 913                                "Updating included files" \
 914                                $pathList \
 915                                [concat {lock_index update;} \
 916                                        [list commit_prehook $curHEAD $msg]]
 917                        return
 918                }
 919        }
 920
 921        commit_prehook $curHEAD $msg
 922}
 923
 924proc commit_prehook {curHEAD msg} {
 925        global gitdir ui_status_value pch_error
 926
 927        set pchook [file join $gitdir hooks pre-commit]
 928
 929        # On Cygwin [file executable] might lie so we need to ask
 930        # the shell if the hook is executable.  Yes that's annoying.
 931        #
 932        if {[is_Windows] && [file isfile $pchook]} {
 933                set pchook [list sh -c [concat \
 934                        "if test -x \"$pchook\";" \
 935                        "then exec \"$pchook\" 2>&1;" \
 936                        "fi"]]
 937        } elseif {[file executable $pchook]} {
 938                set pchook [list $pchook |& cat]
 939        } else {
 940                commit_writetree $curHEAD $msg
 941                return
 942        }
 943
 944        set ui_status_value {Calling pre-commit hook...}
 945        set pch_error {}
 946        set fd_ph [open "| $pchook" r]
 947        fconfigure $fd_ph -blocking 0 -translation binary
 948        fileevent $fd_ph readable \
 949                [list commit_prehook_wait $fd_ph $curHEAD $msg]
 950}
 951
 952proc commit_prehook_wait {fd_ph curHEAD msg} {
 953        global pch_error ui_status_value
 954
 955        append pch_error [read $fd_ph]
 956        fconfigure $fd_ph -blocking 1
 957        if {[eof $fd_ph]} {
 958                if {[catch {close $fd_ph}]} {
 959                        set ui_status_value {Commit declined by pre-commit hook.}
 960                        hook_failed_popup pre-commit $pch_error
 961                        unlock_index
 962                } else {
 963                        commit_writetree $curHEAD $msg
 964                }
 965                set pch_error {}
 966                return
 967        }
 968        fconfigure $fd_ph -blocking 0
 969}
 970
 971proc commit_writetree {curHEAD msg} {
 972        global ui_status_value
 973
 974        set ui_status_value {Committing changes...}
 975        set fd_wt [open "| git write-tree" r]
 976        fileevent $fd_wt readable \
 977                [list commit_committree $fd_wt $curHEAD $msg]
 978}
 979
 980proc commit_committree {fd_wt curHEAD msg} {
 981        global HEAD PARENT MERGE_HEAD commit_type
 982        global single_commit gitdir
 983        global ui_status_value ui_comm selected_commit_type
 984        global file_states selected_paths rescan_active
 985
 986        gets $fd_wt tree_id
 987        if {$tree_id eq {} || [catch {close $fd_wt} err]} {
 988                error_popup "write-tree failed:\n\n$err"
 989                set ui_status_value {Commit failed.}
 990                unlock_index
 991                return
 992        }
 993
 994        # -- Create the commit.
 995        #
 996        set cmd [list git commit-tree $tree_id]
 997        set parents [concat $PARENT $MERGE_HEAD]
 998        if {[llength $parents] > 0} {
 999                foreach p $parents {
1000                        lappend cmd -p $p
1001                }
1002        } else {
1003                # git commit-tree writes to stderr during initial commit.
1004                lappend cmd 2>/dev/null
1005        }
1006        lappend cmd << $msg
1007        if {[catch {set cmt_id [eval exec $cmd]} err]} {
1008                error_popup "commit-tree failed:\n\n$err"
1009                set ui_status_value {Commit failed.}
1010                unlock_index
1011                return
1012        }
1013
1014        # -- Update the HEAD ref.
1015        #
1016        set reflogm commit
1017        if {$commit_type ne {normal}} {
1018                append reflogm " ($commit_type)"
1019        }
1020        set i [string first "\n" $msg]
1021        if {$i >= 0} {
1022                append reflogm {: } [string range $msg 0 [expr {$i - 1}]]
1023        } else {
1024                append reflogm {: } $msg
1025        }
1026        set cmd [list git update-ref -m $reflogm HEAD $cmt_id $curHEAD]
1027        if {[catch {eval exec $cmd} err]} {
1028                error_popup "update-ref failed:\n\n$err"
1029                set ui_status_value {Commit failed.}
1030                unlock_index
1031                return
1032        }
1033
1034        # -- Cleanup after ourselves.
1035        #
1036        catch {file delete [file join $gitdir MERGE_HEAD]}
1037        catch {file delete [file join $gitdir MERGE_MSG]}
1038        catch {file delete [file join $gitdir SQUASH_MSG]}
1039        catch {file delete [file join $gitdir GITGUI_MSG]}
1040
1041        # -- Let rerere do its thing.
1042        #
1043        if {[file isdirectory [file join $gitdir rr-cache]]} {
1044                catch {exec git rerere}
1045        }
1046
1047        # -- Run the post-commit hook.
1048        #
1049        set pchook [file join $gitdir hooks post-commit]
1050        if {[is_Windows] && [file isfile $pchook]} {
1051                set pchook [list sh -c [concat \
1052                        "if test -x \"$pchook\";" \
1053                        "then exec \"$pchook\";" \
1054                        "fi"]]
1055        } elseif {![file executable $pchook]} {
1056                set pchook {}
1057        }
1058        if {$pchook ne {}} {
1059                catch {exec $pchook &}
1060        }
1061
1062        $ui_comm delete 0.0 end
1063        $ui_comm edit reset
1064        $ui_comm edit modified false
1065
1066        if {$single_commit} do_quit
1067
1068        # -- Update in memory status
1069        #
1070        set selected_commit_type new
1071        set commit_type normal
1072        set HEAD $cmt_id
1073        set PARENT $cmt_id
1074        set MERGE_HEAD [list]
1075
1076        foreach path [array names file_states] {
1077                set s $file_states($path)
1078                set m [lindex $s 0]
1079                switch -glob -- $m {
1080                _O -
1081                _M -
1082                _D {continue}
1083                __ -
1084                A_ -
1085                M_ -
1086                DD {
1087                        unset file_states($path)
1088                        catch {unset selected_paths($path)}
1089                }
1090                DO {
1091                        set file_states($path) [list _O [lindex $s 1] {} {}]
1092                }
1093                AM -
1094                AD -
1095                MM -
1096                MD -
1097                DM {
1098                        set file_states($path) [list \
1099                                _[string index $m 1] \
1100                                [lindex $s 1] \
1101                                [lindex $s 3] \
1102                                {}]
1103                }
1104                }
1105        }
1106
1107        display_all_files
1108        unlock_index
1109        reshow_diff
1110        set ui_status_value \
1111                "Changes committed as [string range $cmt_id 0 7]."
1112}
1113
1114######################################################################
1115##
1116## fetch pull push
1117
1118proc fetch_from {remote} {
1119        set w [new_console "fetch $remote" \
1120                "Fetching new changes from $remote"]
1121        set cmd [list git fetch]
1122        lappend cmd $remote
1123        console_exec $w $cmd
1124}
1125
1126proc pull_remote {remote branch} {
1127        global HEAD commit_type file_states repo_config
1128
1129        if {![lock_index update]} return
1130
1131        # -- Our in memory state should match the repository.
1132        #
1133        repository_state curType curHEAD curMERGE_HEAD
1134        if {$commit_type ne $curType || $HEAD ne $curHEAD} {
1135                info_popup {Last scanned state does not match repository state.
1136
1137Another Git program has modified this repository
1138since the last scan.  A rescan must be performed
1139before a pull operation can be started.
1140
1141The rescan will be automatically started now.
1142}
1143                unlock_index
1144                rescan {set ui_status_value {Ready.}}
1145                return
1146        }
1147
1148        # -- No differences should exist before a pull.
1149        #
1150        if {[array size file_states] != 0} {
1151                error_popup {Uncommitted but modified files are present.
1152
1153You should not perform a pull with unmodified
1154files in your working directory as Git will be
1155unable to recover from an incorrect merge.
1156
1157You should commit or revert all changes before
1158starting a pull operation.
1159}
1160                unlock_index
1161                return
1162        }
1163
1164        set w [new_console "pull $remote $branch" \
1165                "Pulling new changes from branch $branch in $remote"]
1166        set cmd [list git pull]
1167        if {$repo_config(gui.pullsummary) eq {false}} {
1168                lappend cmd --no-summary
1169        }
1170        lappend cmd $remote
1171        lappend cmd $branch
1172        console_exec $w $cmd [list post_pull_remote $remote $branch]
1173}
1174
1175proc post_pull_remote {remote branch success} {
1176        global HEAD PARENT MERGE_HEAD commit_type selected_commit_type
1177        global ui_status_value
1178
1179        unlock_index
1180        if {$success} {
1181                repository_state commit_type HEAD MERGE_HEAD
1182                set PARENT $HEAD
1183                set selected_commit_type new
1184                set ui_status_value "Pulling $branch from $remote complete."
1185        } else {
1186                rescan [list set ui_status_value \
1187                        "Conflicts detected while pulling $branch from $remote."]
1188        }
1189}
1190
1191proc push_to {remote} {
1192        set w [new_console "push $remote" \
1193                "Pushing changes to $remote"]
1194        set cmd [list git push]
1195        lappend cmd $remote
1196        console_exec $w $cmd
1197}
1198
1199######################################################################
1200##
1201## ui helpers
1202
1203proc mapcol {state path} {
1204        global all_cols ui_other
1205
1206        if {[catch {set r $all_cols($state)}]} {
1207                puts "error: no column for state={$state} $path"
1208                return $ui_other
1209        }
1210        return $r
1211}
1212
1213proc mapicon {state path} {
1214        global all_icons
1215
1216        if {[catch {set r $all_icons($state)}]} {
1217                puts "error: no icon for state={$state} $path"
1218                return file_plain
1219        }
1220        return $r
1221}
1222
1223proc mapdesc {state path} {
1224        global all_descs
1225
1226        if {[catch {set r $all_descs($state)}]} {
1227                puts "error: no desc for state={$state} $path"
1228                return $state
1229        }
1230        return $r
1231}
1232
1233proc escape_path {path} {
1234        regsub -all "\n" $path "\\n" path
1235        return $path
1236}
1237
1238proc short_path {path} {
1239        return [escape_path [lindex [file split $path] end]]
1240}
1241
1242set next_icon_id 0
1243set null_sha1 [string repeat 0 40]
1244
1245proc merge_state {path new_state {head_info {}} {index_info {}}} {
1246        global file_states next_icon_id null_sha1
1247
1248        set s0 [string index $new_state 0]
1249        set s1 [string index $new_state 1]
1250
1251        if {[catch {set info $file_states($path)}]} {
1252                set state __
1253                set icon n[incr next_icon_id]
1254        } else {
1255                set state [lindex $info 0]
1256                set icon [lindex $info 1]
1257                if {$head_info eq {}}  {set head_info  [lindex $info 2]}
1258                if {$index_info eq {}} {set index_info [lindex $info 3]}
1259        }
1260
1261        if     {$s0 eq {?}} {set s0 [string index $state 0]} \
1262        elseif {$s0 eq {_}} {set s0 _}
1263
1264        if     {$s1 eq {?}} {set s1 [string index $state 1]} \
1265        elseif {$s1 eq {_}} {set s1 _}
1266
1267        if {$s0 eq {A} && $s1 eq {_} && $head_info eq {}} {
1268                set head_info [list 0 $null_sha1]
1269        } elseif {$s0 ne {_} && [string index $state 0] eq {_}
1270                && $head_info eq {}} {
1271                set head_info $index_info
1272        }
1273
1274        set file_states($path) [list $s0$s1 $icon \
1275                $head_info $index_info \
1276                ]
1277        return $state
1278}
1279
1280proc display_file {path state} {
1281        global file_states file_lists selected_paths
1282
1283        set old_m [merge_state $path $state]
1284        set s $file_states($path)
1285        set new_m [lindex $s 0]
1286        set new_w [mapcol $new_m $path] 
1287        set old_w [mapcol $old_m $path]
1288        set new_icon [mapicon $new_m $path]
1289
1290        if {$new_m eq {__}} {
1291                set lno [lsearch -sorted $file_lists($old_w) $path]
1292                if {$lno >= 0} {
1293                        set file_lists($old_w) \
1294                                [lreplace $file_lists($old_w) $lno $lno]
1295                        incr lno
1296                        $old_w conf -state normal
1297                        $old_w delete $lno.0 [expr {$lno + 1}].0
1298                        $old_w conf -state disabled
1299                }
1300                unset file_states($path)
1301                catch {unset selected_paths($path)}
1302                return
1303        }
1304
1305        if {$new_w ne $old_w} {
1306                set lno [lsearch -sorted $file_lists($old_w) $path]
1307                if {$lno >= 0} {
1308                        set file_lists($old_w) \
1309                                [lreplace $file_lists($old_w) $lno $lno]
1310                        incr lno
1311                        $old_w conf -state normal
1312                        $old_w delete $lno.0 [expr {$lno + 1}].0
1313                        $old_w conf -state disabled
1314                }
1315
1316                lappend file_lists($new_w) $path
1317                set file_lists($new_w) [lsort $file_lists($new_w)]
1318                set lno [lsearch -sorted $file_lists($new_w) $path]
1319                incr lno
1320                $new_w conf -state normal
1321                $new_w image create $lno.0 \
1322                        -align center -padx 5 -pady 1 \
1323                        -name [lindex $s 1] \
1324                        -image $new_icon
1325                $new_w insert $lno.1 "[escape_path $path]\n"
1326                if {[catch {set in_sel $selected_paths($path)}]} {
1327                        set in_sel 0
1328                }
1329                if {$in_sel} {
1330                        $new_w tag add in_sel $lno.0 [expr {$lno + 1}].0
1331                }
1332                $new_w conf -state disabled
1333        } elseif {$new_icon ne [mapicon $old_m $path]} {
1334                $new_w conf -state normal
1335                $new_w image conf [lindex $s 1] -image $new_icon
1336                $new_w conf -state disabled
1337        }
1338}
1339
1340proc display_all_files {} {
1341        global ui_index ui_other
1342        global file_states file_lists
1343        global last_clicked selected_paths
1344
1345        $ui_index conf -state normal
1346        $ui_other conf -state normal
1347
1348        $ui_index delete 0.0 end
1349        $ui_other delete 0.0 end
1350        set last_clicked {}
1351
1352        set file_lists($ui_index) [list]
1353        set file_lists($ui_other) [list]
1354
1355        foreach path [lsort [array names file_states]] {
1356                set s $file_states($path)
1357                set m [lindex $s 0]
1358                set w [mapcol $m $path]
1359                lappend file_lists($w) $path
1360                set lno [expr {[lindex [split [$w index end] .] 0] - 1}]
1361                $w image create end \
1362                        -align center -padx 5 -pady 1 \
1363                        -name [lindex $s 1] \
1364                        -image [mapicon $m $path]
1365                $w insert end "[escape_path $path]\n"
1366                if {[catch {set in_sel $selected_paths($path)}]} {
1367                        set in_sel 0
1368                }
1369                if {$in_sel} {
1370                        $w tag add in_sel $lno.0 [expr {$lno + 1}].0
1371                }
1372        }
1373
1374        $ui_index conf -state disabled
1375        $ui_other conf -state disabled
1376}
1377
1378proc update_indexinfo {msg pathList after} {
1379        global update_index_cp ui_status_value
1380
1381        if {![lock_index update]} return
1382
1383        set update_index_cp 0
1384        set pathList [lsort $pathList]
1385        set totalCnt [llength $pathList]
1386        set batch [expr {int($totalCnt * .01) + 1}]
1387        if {$batch > 25} {set batch 25}
1388
1389        set ui_status_value [format \
1390                "$msg... %i/%i files (%.2f%%)" \
1391                $update_index_cp \
1392                $totalCnt \
1393                0.0]
1394        set fd [open "| git update-index -z --index-info" w]
1395        fconfigure $fd \
1396                -blocking 0 \
1397                -buffering full \
1398                -buffersize 512 \
1399                -translation binary
1400        fileevent $fd writable [list \
1401                write_update_indexinfo \
1402                $fd \
1403                $pathList \
1404                $totalCnt \
1405                $batch \
1406                $msg \
1407                $after \
1408                ]
1409}
1410
1411proc write_update_indexinfo {fd pathList totalCnt batch msg after} {
1412        global update_index_cp ui_status_value
1413        global file_states current_diff
1414
1415        if {$update_index_cp >= $totalCnt} {
1416                close $fd
1417                unlock_index
1418                uplevel #0 $after
1419                return
1420        }
1421
1422        for {set i $batch} \
1423                {$update_index_cp < $totalCnt && $i > 0} \
1424                {incr i -1} {
1425                set path [lindex $pathList $update_index_cp]
1426                incr update_index_cp
1427
1428                set s $file_states($path)
1429                switch -glob -- [lindex $s 0] {
1430                A? {set new _O}
1431                M? {set new _M}
1432                D? {set new _?}
1433                ?? {continue}
1434                }
1435                set info [lindex $s 2]
1436                if {$info eq {}} continue
1437
1438                puts -nonewline $fd $info
1439                puts -nonewline $fd "\t"
1440                puts -nonewline $fd $path
1441                puts -nonewline $fd "\0"
1442                display_file $path $new
1443        }
1444
1445        set ui_status_value [format \
1446                "$msg... %i/%i files (%.2f%%)" \
1447                $update_index_cp \
1448                $totalCnt \
1449                [expr {100.0 * $update_index_cp / $totalCnt}]]
1450}
1451
1452proc update_index {msg pathList after} {
1453        global update_index_cp ui_status_value
1454
1455        if {![lock_index update]} return
1456
1457        set update_index_cp 0
1458        set pathList [lsort $pathList]
1459        set totalCnt [llength $pathList]
1460        set batch [expr {int($totalCnt * .01) + 1}]
1461        if {$batch > 25} {set batch 25}
1462
1463        set ui_status_value [format \
1464                "$msg... %i/%i files (%.2f%%)" \
1465                $update_index_cp \
1466                $totalCnt \
1467                0.0]
1468        set fd [open "| git update-index --add --remove -z --stdin" w]
1469        fconfigure $fd \
1470                -blocking 0 \
1471                -buffering full \
1472                -buffersize 512 \
1473                -translation binary
1474        fileevent $fd writable [list \
1475                write_update_index \
1476                $fd \
1477                $pathList \
1478                $totalCnt \
1479                $batch \
1480                $msg \
1481                $after \
1482                ]
1483}
1484
1485proc write_update_index {fd pathList totalCnt batch msg after} {
1486        global update_index_cp ui_status_value
1487        global file_states current_diff
1488
1489        if {$update_index_cp >= $totalCnt} {
1490                close $fd
1491                unlock_index
1492                uplevel #0 $after
1493                return
1494        }
1495
1496        for {set i $batch} \
1497                {$update_index_cp < $totalCnt && $i > 0} \
1498                {incr i -1} {
1499                set path [lindex $pathList $update_index_cp]
1500                incr update_index_cp
1501
1502                switch -glob -- [lindex $file_states($path) 0] {
1503                AD -
1504                MD -
1505                _D {set new DD}
1506
1507                _M -
1508                MM -
1509                M_ {set new M_}
1510
1511                _O -
1512                AM -
1513                A_ {set new A_}
1514
1515                ?? {continue}
1516                }
1517
1518                puts -nonewline $fd $path
1519                puts -nonewline $fd "\0"
1520                display_file $path $new
1521        }
1522
1523        set ui_status_value [format \
1524                "$msg... %i/%i files (%.2f%%)" \
1525                $update_index_cp \
1526                $totalCnt \
1527                [expr {100.0 * $update_index_cp / $totalCnt}]]
1528}
1529
1530proc checkout_index {msg pathList after} {
1531        global update_index_cp ui_status_value
1532
1533        if {![lock_index update]} return
1534
1535        set update_index_cp 0
1536        set pathList [lsort $pathList]
1537        set totalCnt [llength $pathList]
1538        set batch [expr {int($totalCnt * .01) + 1}]
1539        if {$batch > 25} {set batch 25}
1540
1541        set ui_status_value [format \
1542                "$msg... %i/%i files (%.2f%%)" \
1543                $update_index_cp \
1544                $totalCnt \
1545                0.0]
1546        set cmd [list git checkout-index]
1547        lappend cmd --index
1548        lappend cmd --quiet
1549        lappend cmd --force
1550        lappend cmd -z
1551        lappend cmd --stdin
1552        set fd [open "| $cmd " w]
1553        fconfigure $fd \
1554                -blocking 0 \
1555                -buffering full \
1556                -buffersize 512 \
1557                -translation binary
1558        fileevent $fd writable [list \
1559                write_checkout_index \
1560                $fd \
1561                $pathList \
1562                $totalCnt \
1563                $batch \
1564                $msg \
1565                $after \
1566                ]
1567}
1568
1569proc write_checkout_index {fd pathList totalCnt batch msg after} {
1570        global update_index_cp ui_status_value
1571        global file_states current_diff
1572
1573        if {$update_index_cp >= $totalCnt} {
1574                close $fd
1575                unlock_index
1576                uplevel #0 $after
1577                return
1578        }
1579
1580        for {set i $batch} \
1581                {$update_index_cp < $totalCnt && $i > 0} \
1582                {incr i -1} {
1583                set path [lindex $pathList $update_index_cp]
1584                incr update_index_cp
1585
1586                switch -glob -- [lindex $file_states($path) 0] {
1587                AM -
1588                AD {set new A_}
1589                MM -
1590                MD {set new M_}
1591                _M -
1592                _D {set new __}
1593                ?? {continue}
1594                }
1595
1596                puts -nonewline $fd $path
1597                puts -nonewline $fd "\0"
1598                display_file $path $new
1599        }
1600
1601        set ui_status_value [format \
1602                "$msg... %i/%i files (%.2f%%)" \
1603                $update_index_cp \
1604                $totalCnt \
1605                [expr {100.0 * $update_index_cp / $totalCnt}]]
1606}
1607
1608######################################################################
1609##
1610## branch management
1611
1612proc load_all_branches {} {
1613        global all_branches
1614
1615        set all_branches [list]
1616        set cmd [list git for-each-ref]
1617        lappend cmd --format=%(refname)
1618        lappend cmd refs/heads
1619        set fd [open "| $cmd" r]
1620        while {[gets $fd line] > 0} {
1621                if {[regsub ^refs/heads/ $line {} line]} {
1622                        lappend all_branches $line
1623                }
1624        }
1625        close $fd
1626
1627        set all_branches [lsort $all_branches]
1628}
1629
1630proc populate_branch_menu {m} {
1631        global all_branches disable_on_lock
1632
1633        $m add separator
1634        foreach b $all_branches {
1635                $m add radiobutton \
1636                        -label $b \
1637                        -command [list switch_branch $b] \
1638                        -variable current_branch \
1639                        -value $b \
1640                        -font font_ui
1641                lappend disable_on_lock \
1642                        [list $m entryconf [$m index last] -state]
1643        }
1644}
1645
1646proc switch_branch {b} {
1647        error "NOT IMPLEMENTED"
1648}
1649
1650######################################################################
1651##
1652## remote management
1653
1654proc load_all_remotes {} {
1655        global gitdir all_remotes repo_config
1656
1657        set all_remotes [list]
1658        set rm_dir [file join $gitdir remotes]
1659        if {[file isdirectory $rm_dir]} {
1660                set all_remotes [concat $all_remotes [glob \
1661                        -types f \
1662                        -tails \
1663                        -nocomplain \
1664                        -directory $rm_dir *]]
1665        }
1666
1667        foreach line [array names repo_config remote.*.url] {
1668                if {[regexp ^remote\.(.*)\.url\$ $line line name]} {
1669                        lappend all_remotes $name
1670                }
1671        }
1672
1673        set all_remotes [lsort -unique $all_remotes]
1674}
1675
1676proc populate_fetch_menu {m} {
1677        global gitdir all_remotes repo_config
1678
1679        foreach r $all_remotes {
1680                set enable 0
1681                if {![catch {set a $repo_config(remote.$r.url)}]} {
1682                        if {![catch {set a $repo_config(remote.$r.fetch)}]} {
1683                                set enable 1
1684                        }
1685                } else {
1686                        catch {
1687                                set fd [open [file join $gitdir remotes $r] r]
1688                                while {[gets $fd n] >= 0} {
1689                                        if {[regexp {^Pull:[ \t]*([^:]+):} $n]} {
1690                                                set enable 1
1691                                                break
1692                                        }
1693                                }
1694                                close $fd
1695                        }
1696                }
1697
1698                if {$enable} {
1699                        $m add command \
1700                                -label "Fetch from $r..." \
1701                                -command [list fetch_from $r] \
1702                                -font font_ui
1703                }
1704        }
1705}
1706
1707proc populate_push_menu {m} {
1708        global gitdir all_remotes repo_config
1709
1710        foreach r $all_remotes {
1711                set enable 0
1712                if {![catch {set a $repo_config(remote.$r.url)}]} {
1713                        if {![catch {set a $repo_config(remote.$r.push)}]} {
1714                                set enable 1
1715                        }
1716                } else {
1717                        catch {
1718                                set fd [open [file join $gitdir remotes $r] r]
1719                                while {[gets $fd n] >= 0} {
1720                                        if {[regexp {^Push:[ \t]*([^:]+):} $n]} {
1721                                                set enable 1
1722                                                break
1723                                        }
1724                                }
1725                                close $fd
1726                        }
1727                }
1728
1729                if {$enable} {
1730                        $m add command \
1731                                -label "Push to $r..." \
1732                                -command [list push_to $r] \
1733                                -font font_ui
1734                }
1735        }
1736}
1737
1738proc populate_pull_menu {m} {
1739        global gitdir repo_config all_remotes disable_on_lock
1740
1741        foreach remote $all_remotes {
1742                set rb {}
1743                if {[array get repo_config remote.$remote.url] ne {}} {
1744                        if {[array get repo_config remote.$remote.fetch] ne {}} {
1745                                regexp {^([^:]+):} \
1746                                        [lindex $repo_config(remote.$remote.fetch) 0] \
1747                                        line rb
1748                        }
1749                } else {
1750                        catch {
1751                                set fd [open [file join $gitdir remotes $remote] r]
1752                                while {[gets $fd line] >= 0} {
1753                                        if {[regexp {^Pull:[ \t]*([^:]+):} $line line rb]} {
1754                                                break
1755                                        }
1756                                }
1757                                close $fd
1758                        }
1759                }
1760
1761                set rb_short $rb
1762                regsub ^refs/heads/ $rb {} rb_short
1763                if {$rb_short ne {}} {
1764                        $m add command \
1765                                -label "Branch $rb_short from $remote..." \
1766                                -command [list pull_remote $remote $rb] \
1767                                -font font_ui
1768                        lappend disable_on_lock \
1769                                [list $m entryconf [$m index last] -state]
1770                }
1771        }
1772}
1773
1774######################################################################
1775##
1776## icons
1777
1778set filemask {
1779#define mask_width 14
1780#define mask_height 15
1781static unsigned char mask_bits[] = {
1782   0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f,
1783   0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f,
1784   0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f};
1785}
1786
1787image create bitmap file_plain -background white -foreground black -data {
1788#define plain_width 14
1789#define plain_height 15
1790static unsigned char plain_bits[] = {
1791   0xfe, 0x01, 0x02, 0x03, 0x02, 0x05, 0x02, 0x09, 0x02, 0x1f, 0x02, 0x10,
1792   0x02, 0x10, 0x02, 0x10, 0x02, 0x10, 0x02, 0x10, 0x02, 0x10, 0x02, 0x10,
1793   0x02, 0x10, 0x02, 0x10, 0xfe, 0x1f};
1794} -maskdata $filemask
1795
1796image create bitmap file_mod -background white -foreground blue -data {
1797#define mod_width 14
1798#define mod_height 15
1799static unsigned char mod_bits[] = {
1800   0xfe, 0x01, 0x02, 0x03, 0x7a, 0x05, 0x02, 0x09, 0x7a, 0x1f, 0x02, 0x10,
1801   0xfa, 0x17, 0x02, 0x10, 0xfa, 0x17, 0x02, 0x10, 0xfa, 0x17, 0x02, 0x10,
1802   0xfa, 0x17, 0x02, 0x10, 0xfe, 0x1f};
1803} -maskdata $filemask
1804
1805image create bitmap file_fulltick -background white -foreground "#007000" -data {
1806#define file_fulltick_width 14
1807#define file_fulltick_height 15
1808static unsigned char file_fulltick_bits[] = {
1809   0xfe, 0x01, 0x02, 0x1a, 0x02, 0x0c, 0x02, 0x0c, 0x02, 0x16, 0x02, 0x16,
1810   0x02, 0x13, 0x00, 0x13, 0x86, 0x11, 0x8c, 0x11, 0xd8, 0x10, 0xf2, 0x10,
1811   0x62, 0x10, 0x02, 0x10, 0xfe, 0x1f};
1812} -maskdata $filemask
1813
1814image create bitmap file_parttick -background white -foreground "#005050" -data {
1815#define parttick_width 14
1816#define parttick_height 15
1817static unsigned char parttick_bits[] = {
1818   0xfe, 0x01, 0x02, 0x03, 0x7a, 0x05, 0x02, 0x09, 0x7a, 0x1f, 0x02, 0x10,
1819   0x7a, 0x14, 0x02, 0x16, 0x02, 0x13, 0x8a, 0x11, 0xda, 0x10, 0x72, 0x10,
1820   0x22, 0x10, 0x02, 0x10, 0xfe, 0x1f};
1821} -maskdata $filemask
1822
1823image create bitmap file_question -background white -foreground black -data {
1824#define file_question_width 14
1825#define file_question_height 15
1826static unsigned char file_question_bits[] = {
1827   0xfe, 0x01, 0x02, 0x02, 0xe2, 0x04, 0xf2, 0x09, 0x1a, 0x1b, 0x0a, 0x13,
1828   0x82, 0x11, 0xc2, 0x10, 0x62, 0x10, 0x62, 0x10, 0x02, 0x10, 0x62, 0x10,
1829   0x62, 0x10, 0x02, 0x10, 0xfe, 0x1f};
1830} -maskdata $filemask
1831
1832image create bitmap file_removed -background white -foreground red -data {
1833#define file_removed_width 14
1834#define file_removed_height 15
1835static unsigned char file_removed_bits[] = {
1836   0xfe, 0x01, 0x02, 0x03, 0x02, 0x05, 0x02, 0x09, 0x02, 0x1f, 0x02, 0x10,
1837   0x1a, 0x16, 0x32, 0x13, 0xe2, 0x11, 0xc2, 0x10, 0xe2, 0x11, 0x32, 0x13,
1838   0x1a, 0x16, 0x02, 0x10, 0xfe, 0x1f};
1839} -maskdata $filemask
1840
1841image create bitmap file_merge -background white -foreground blue -data {
1842#define file_merge_width 14
1843#define file_merge_height 15
1844static unsigned char file_merge_bits[] = {
1845   0xfe, 0x01, 0x02, 0x03, 0x62, 0x05, 0x62, 0x09, 0x62, 0x1f, 0x62, 0x10,
1846   0xfa, 0x11, 0xf2, 0x10, 0x62, 0x10, 0x02, 0x10, 0xfa, 0x17, 0x02, 0x10,
1847   0xfa, 0x17, 0x02, 0x10, 0xfe, 0x1f};
1848} -maskdata $filemask
1849
1850set ui_index .vpane.files.index.list
1851set ui_other .vpane.files.other.list
1852set max_status_desc 0
1853foreach i {
1854                {__ i plain    "Unmodified"}
1855                {_M i mod      "Modified"}
1856                {M_ i fulltick "Included in commit"}
1857                {MM i parttick "Partially included"}
1858                {MD i question "Included (but gone)"}
1859
1860                {_O o plain    "Untracked"}
1861                {A_ o fulltick "Added by commit"}
1862                {AM o parttick "Partially added"}
1863                {AD o question "Added (but gone)"}
1864
1865                {_D i question "Missing"}
1866                {DD i removed  "Removed by commit"}
1867                {DO i removed  "Removed (still exists)"}
1868                {DM i removed  "Removed (but modified)"}
1869
1870                {UD i merge    "Merge conflicts"}
1871                {UM i merge    "Merge conflicts"}
1872                {U_ i merge    "Merge conflicts"}
1873        } {
1874        if {$max_status_desc < [string length [lindex $i 3]]} {
1875                set max_status_desc [string length [lindex $i 3]]
1876        }
1877        if {[lindex $i 1] eq {i}} {
1878                set all_cols([lindex $i 0]) $ui_index
1879        } else {
1880                set all_cols([lindex $i 0]) $ui_other
1881        }
1882        set all_icons([lindex $i 0]) file_[lindex $i 2]
1883        set all_descs([lindex $i 0]) [lindex $i 3]
1884}
1885unset filemask i
1886
1887######################################################################
1888##
1889## util
1890
1891proc is_MacOSX {} {
1892        global tcl_platform tk_library
1893        if {[tk windowingsystem] eq {aqua}} {
1894                return 1
1895        }
1896        return 0
1897}
1898
1899proc is_Windows {} {
1900        global tcl_platform
1901        if {$tcl_platform(platform) eq {windows}} {
1902                return 1
1903        }
1904        return 0
1905}
1906
1907proc bind_button3 {w cmd} {
1908        bind $w <Any-Button-3> $cmd
1909        if {[is_MacOSX]} {
1910                bind $w <Control-Button-1> $cmd
1911        }
1912}
1913
1914proc incr_font_size {font {amt 1}} {
1915        set sz [font configure $font -size]
1916        incr sz $amt
1917        font configure $font -size $sz
1918        font configure ${font}bold -size $sz
1919}
1920
1921proc hook_failed_popup {hook msg} {
1922        global gitdir appname
1923
1924        set w .hookfail
1925        toplevel $w
1926
1927        frame $w.m
1928        label $w.m.l1 -text "$hook hook failed:" \
1929                -anchor w \
1930                -justify left \
1931                -font font_uibold
1932        text $w.m.t \
1933                -background white -borderwidth 1 \
1934                -relief sunken \
1935                -width 80 -height 10 \
1936                -font font_diff \
1937                -yscrollcommand [list $w.m.sby set]
1938        label $w.m.l2 \
1939                -text {You must correct the above errors before committing.} \
1940                -anchor w \
1941                -justify left \
1942                -font font_uibold
1943        scrollbar $w.m.sby -command [list $w.m.t yview]
1944        pack $w.m.l1 -side top -fill x
1945        pack $w.m.l2 -side bottom -fill x
1946        pack $w.m.sby -side right -fill y
1947        pack $w.m.t -side left -fill both -expand 1
1948        pack $w.m -side top -fill both -expand 1 -padx 5 -pady 10
1949
1950        $w.m.t insert 1.0 $msg
1951        $w.m.t conf -state disabled
1952
1953        button $w.ok -text OK \
1954                -width 15 \
1955                -font font_ui \
1956                -command "destroy $w"
1957        pack $w.ok -side bottom -anchor e -pady 10 -padx 10
1958
1959        bind $w <Visibility> "grab $w; focus $w"
1960        bind $w <Key-Return> "destroy $w"
1961        wm title $w "$appname ([lindex [file split \
1962                [file normalize [file dirname $gitdir]]] \
1963                end]): error"
1964        tkwait window $w
1965}
1966
1967set next_console_id 0
1968
1969proc new_console {short_title long_title} {
1970        global next_console_id console_data
1971        set w .console[incr next_console_id]
1972        set console_data($w) [list $short_title $long_title]
1973        return [console_init $w]
1974}
1975
1976proc console_init {w} {
1977        global console_cr console_data
1978        global gitdir appname M1B
1979
1980        set console_cr($w) 1.0
1981        toplevel $w
1982        frame $w.m
1983        label $w.m.l1 -text "[lindex $console_data($w) 1]:" \
1984                -anchor w \
1985                -justify left \
1986                -font font_uibold
1987        text $w.m.t \
1988                -background white -borderwidth 1 \
1989                -relief sunken \
1990                -width 80 -height 10 \
1991                -font font_diff \
1992                -state disabled \
1993                -yscrollcommand [list $w.m.sby set]
1994        label $w.m.s -text {Working... please wait...} \
1995                -anchor w \
1996                -justify left \
1997                -font font_uibold
1998        scrollbar $w.m.sby -command [list $w.m.t yview]
1999        pack $w.m.l1 -side top -fill x
2000        pack $w.m.s -side bottom -fill x
2001        pack $w.m.sby -side right -fill y
2002        pack $w.m.t -side left -fill both -expand 1
2003        pack $w.m -side top -fill both -expand 1 -padx 5 -pady 10
2004
2005        menu $w.ctxm -tearoff 0
2006        $w.ctxm add command -label "Copy" \
2007                -font font_ui \
2008                -command "tk_textCopy $w.m.t"
2009        $w.ctxm add command -label "Select All" \
2010                -font font_ui \
2011                -command "$w.m.t tag add sel 0.0 end"
2012        $w.ctxm add command -label "Copy All" \
2013                -font font_ui \
2014                -command "
2015                        $w.m.t tag add sel 0.0 end
2016                        tk_textCopy $w.m.t
2017                        $w.m.t tag remove sel 0.0 end
2018                "
2019
2020        button $w.ok -text {Close} \
2021                -font font_ui \
2022                -state disabled \
2023                -command "destroy $w"
2024        pack $w.ok -side bottom -anchor e -pady 10 -padx 10
2025
2026        bind_button3 $w.m.t "tk_popup $w.ctxm %X %Y"
2027        bind $w.m.t <$M1B-Key-a> "$w.m.t tag add sel 0.0 end;break"
2028        bind $w.m.t <$M1B-Key-A> "$w.m.t tag add sel 0.0 end;break"
2029        bind $w <Visibility> "focus $w"
2030        wm title $w "$appname ([lindex [file split \
2031                [file normalize [file dirname $gitdir]]] \
2032                end]): [lindex $console_data($w) 0]"
2033        return $w
2034}
2035
2036proc console_exec {w cmd {after {}}} {
2037        # -- Windows tosses the enviroment when we exec our child.
2038        #    But most users need that so we have to relogin. :-(
2039        #
2040        if {[is_Windows]} {
2041                set cmd [list sh --login -c "cd \"[pwd]\" && [join $cmd { }]"]
2042        }
2043
2044        # -- Tcl won't let us redirect both stdout and stderr to
2045        #    the same pipe.  So pass it through cat...
2046        #
2047        set cmd [concat | $cmd |& cat]
2048
2049        set fd_f [open $cmd r]
2050        fconfigure $fd_f -blocking 0 -translation binary
2051        fileevent $fd_f readable [list console_read $w $fd_f $after]
2052}
2053
2054proc console_read {w fd after} {
2055        global console_cr console_data
2056
2057        set buf [read $fd]
2058        if {$buf ne {}} {
2059                if {![winfo exists $w]} {console_init $w}
2060                $w.m.t conf -state normal
2061                set c 0
2062                set n [string length $buf]
2063                while {$c < $n} {
2064                        set cr [string first "\r" $buf $c]
2065                        set lf [string first "\n" $buf $c]
2066                        if {$cr < 0} {set cr [expr {$n + 1}]}
2067                        if {$lf < 0} {set lf [expr {$n + 1}]}
2068
2069                        if {$lf < $cr} {
2070                                $w.m.t insert end [string range $buf $c $lf]
2071                                set console_cr($w) [$w.m.t index {end -1c}]
2072                                set c $lf
2073                                incr c
2074                        } else {
2075                                $w.m.t delete $console_cr($w) end
2076                                $w.m.t insert end "\n"
2077                                $w.m.t insert end [string range $buf $c $cr]
2078                                set c $cr
2079                                incr c
2080                        }
2081                }
2082                $w.m.t conf -state disabled
2083                $w.m.t see end
2084        }
2085
2086        fconfigure $fd -blocking 1
2087        if {[eof $fd]} {
2088                if {[catch {close $fd}]} {
2089                        if {![winfo exists $w]} {console_init $w}
2090                        $w.m.s conf -background red -text {Error: Command Failed}
2091                        $w.ok conf -state normal
2092                        set ok 0
2093                } elseif {[winfo exists $w]} {
2094                        $w.m.s conf -background green -text {Success}
2095                        $w.ok conf -state normal
2096                        set ok 1
2097                }
2098                array unset console_cr $w
2099                array unset console_data $w
2100                if {$after ne {}} {
2101                        uplevel #0 $after $ok
2102                }
2103                return
2104        }
2105        fconfigure $fd -blocking 0
2106}
2107
2108######################################################################
2109##
2110## ui commands
2111
2112set starting_gitk_msg {Please wait... Starting gitk...}
2113
2114proc do_gitk {revs} {
2115        global ui_status_value starting_gitk_msg
2116
2117        set cmd gitk
2118        if {$revs ne {}} {
2119                append cmd { }
2120                append cmd $revs
2121        }
2122        if {[is_Windows]} {
2123                set cmd "sh -c \"exec $cmd\""
2124        }
2125        append cmd { &}
2126
2127        if {[catch {eval exec $cmd} err]} {
2128                error_popup "Failed to start gitk:\n\n$err"
2129        } else {
2130                set ui_status_value $starting_gitk_msg
2131                after 10000 {
2132                        if {$ui_status_value eq $starting_gitk_msg} {
2133                                set ui_status_value {Ready.}
2134                        }
2135                }
2136        }
2137}
2138
2139proc do_repack {} {
2140        set w [new_console {repack} \
2141                {Repacking the object database}]
2142        set cmd [list git repack]
2143        lappend cmd -a
2144        lappend cmd -d
2145        console_exec $w $cmd
2146}
2147
2148proc do_fsck_objects {} {
2149        set w [new_console {fsck-objects} \
2150                {Verifying the object database with fsck-objects}]
2151        set cmd [list git fsck-objects]
2152        lappend cmd --full
2153        lappend cmd --cache
2154        lappend cmd --strict
2155        console_exec $w $cmd
2156}
2157
2158set is_quitting 0
2159
2160proc do_quit {} {
2161        global gitdir ui_comm is_quitting repo_config commit_type
2162
2163        if {$is_quitting} return
2164        set is_quitting 1
2165
2166        # -- Stash our current commit buffer.
2167        #
2168        set save [file join $gitdir GITGUI_MSG]
2169        set msg [string trim [$ui_comm get 0.0 end]]
2170        if {![string match amend* $commit_type]
2171                && [$ui_comm edit modified]
2172                && $msg ne {}} {
2173                catch {
2174                        set fd [open $save w]
2175                        puts $fd [string trim [$ui_comm get 0.0 end]]
2176                        close $fd
2177                }
2178        } else {
2179                catch {file delete $save}
2180        }
2181
2182        # -- Stash our current window geometry into this repository.
2183        #
2184        set cfg_geometry [list]
2185        lappend cfg_geometry [wm geometry .]
2186        lappend cfg_geometry [lindex [.vpane sash coord 0] 1]
2187        lappend cfg_geometry [lindex [.vpane.files sash coord 0] 0]
2188        if {[catch {set rc_geometry $repo_config(gui.geometry)}]} {
2189                set rc_geometry {}
2190        }
2191        if {$cfg_geometry ne $rc_geometry} {
2192                catch {exec git repo-config gui.geometry $cfg_geometry}
2193        }
2194
2195        destroy .
2196}
2197
2198proc do_rescan {} {
2199        rescan {set ui_status_value {Ready.}}
2200}
2201
2202proc remove_helper {txt paths} {
2203        global file_states current_diff
2204
2205        if {![lock_index begin-update]} return
2206
2207        set pathList [list]
2208        set after {}
2209        foreach path $paths {
2210                switch -glob -- [lindex $file_states($path) 0] {
2211                A? -
2212                M? -
2213                D? {
2214                        lappend pathList $path
2215                        if {$path eq $current_diff} {
2216                                set after {reshow_diff;}
2217                        }
2218                }
2219                }
2220        }
2221        if {$pathList eq {}} {
2222                unlock_index
2223        } else {
2224                update_indexinfo \
2225                        $txt \
2226                        $pathList \
2227                        [concat $after {set ui_status_value {Ready.}}]
2228        }
2229}
2230
2231proc do_remove_selection {} {
2232        global current_diff selected_paths
2233
2234        if {[array size selected_paths] > 0} {
2235                remove_helper \
2236                        {Removing selected files from commit} \
2237                        [array names selected_paths]
2238        } elseif {$current_diff ne {}} {
2239                remove_helper \
2240                        "Removing [short_path $current_diff] from commit" \
2241                        [list $current_diff]
2242        }
2243}
2244
2245proc include_helper {txt paths} {
2246        global file_states current_diff
2247
2248        if {![lock_index begin-update]} return
2249
2250        set pathList [list]
2251        set after {}
2252        foreach path $paths {
2253                switch -glob -- [lindex $file_states($path) 0] {
2254                AM -
2255                AD -
2256                MM -
2257                MD -
2258                U? -
2259                _M -
2260                _D -
2261                _O {
2262                        lappend pathList $path
2263                        if {$path eq $current_diff} {
2264                                set after {reshow_diff;}
2265                        }
2266                }
2267                }
2268        }
2269        if {$pathList eq {}} {
2270                unlock_index
2271        } else {
2272                update_index \
2273                        $txt \
2274                        $pathList \
2275                        [concat $after {set ui_status_value {Ready to commit.}}]
2276        }
2277}
2278
2279proc do_include_selection {} {
2280        global current_diff selected_paths
2281
2282        if {[array size selected_paths] > 0} {
2283                include_helper \
2284                        {Including selected files} \
2285                        [array names selected_paths]
2286        } elseif {$current_diff ne {}} {
2287                include_helper \
2288                        "Including [short_path $current_diff]" \
2289                        [list $current_diff]
2290        }
2291}
2292
2293proc do_include_all {} {
2294        global file_states
2295
2296        set paths [list]
2297        foreach path [array names file_states] {
2298                switch -- [lindex $file_states($path) 0] {
2299                AM -
2300                AD -
2301                MM -
2302                MD -
2303                _M -
2304                _D {lappend paths $path}
2305                }
2306        }
2307        include_helper \
2308                {Including all modified files} \
2309                $paths
2310}
2311
2312proc revert_helper {txt paths} {
2313        global file_states current_diff
2314
2315        if {![lock_index begin-update]} return
2316
2317        set pathList [list]
2318        set after {}
2319        foreach path $paths {
2320                switch -glob -- [lindex $file_states($path) 0] {
2321                AM -
2322                AD -
2323                MM -
2324                MD -
2325                _M -
2326                _D {
2327                        lappend pathList $path
2328                        if {$path eq $current_diff} {
2329                                set after {reshow_diff;}
2330                        }
2331                }
2332                }
2333        }
2334
2335        set n [llength $pathList]
2336        if {$n == 0} {
2337                unlock_index
2338                return
2339        } elseif {$n == 1} {
2340                set s "[short_path [lindex $pathList]]"
2341        } else {
2342                set s "these $n files"
2343        }
2344
2345        set reply [tk_dialog \
2346                .confirm_revert \
2347                "title" \
2348                "Revert unincluded changes in $s?
2349
2350Any unincluded changes will be permanently lost by the revert." \
2351                questhead \
2352                1 \
2353                {Do Nothing} \
2354                {Revert Changes} \
2355                ]
2356        if {$reply == 1} {
2357                checkout_index \
2358                        $txt \
2359                        $pathList \
2360                        [concat $after {set ui_status_value {Ready.}}]
2361        } else {
2362                unlock_index
2363        }
2364}
2365
2366proc do_revert_selection {} {
2367        global current_diff selected_paths
2368
2369        if {[array size selected_paths] > 0} {
2370                revert_helper \
2371                        {Reverting selected files} \
2372                        [array names selected_paths]
2373        } elseif {$current_diff ne {}} {
2374                revert_helper \
2375                        "Reverting [short_path $current_diff]" \
2376                        [list $current_diff]
2377        }
2378}
2379
2380proc do_signoff {} {
2381        global ui_comm
2382
2383        set me [committer_ident]
2384        if {$me eq {}} return
2385
2386        set sob "Signed-off-by: $me"
2387        set last [$ui_comm get {end -1c linestart} {end -1c}]
2388        if {$last ne $sob} {
2389                $ui_comm edit separator
2390                if {$last ne {}
2391                        && ![regexp {^[A-Z][A-Za-z]*-[A-Za-z-]+: *} $last]} {
2392                        $ui_comm insert end "\n"
2393                }
2394                $ui_comm insert end "\n$sob"
2395                $ui_comm edit separator
2396                $ui_comm see end
2397        }
2398}
2399
2400proc do_select_commit_type {} {
2401        global commit_type selected_commit_type
2402
2403        if {$selected_commit_type eq {new}
2404                && [string match amend* $commit_type]} {
2405                create_new_commit
2406        } elseif {$selected_commit_type eq {amend}
2407                && ![string match amend* $commit_type]} {
2408                load_last_commit
2409
2410                # The amend request was rejected...
2411                #
2412                if {![string match amend* $commit_type]} {
2413                        set selected_commit_type new
2414                }
2415        }
2416}
2417
2418proc do_commit {} {
2419        commit_tree
2420}
2421
2422proc do_about {} {
2423        global appname copyright
2424        global tcl_patchLevel tk_patchLevel
2425
2426        set w .about_dialog
2427        toplevel $w
2428        wm geometry $w "+[winfo rootx .]+[winfo rooty .]"
2429
2430        label $w.header -text "About $appname" \
2431                -font font_uibold
2432        pack $w.header -side top -fill x
2433
2434        frame $w.buttons
2435        button $w.buttons.close -text {Close} \
2436                -font font_ui \
2437                -command [list destroy $w]
2438        pack $w.buttons.close -side right
2439        pack $w.buttons -side bottom -fill x -pady 10 -padx 10
2440
2441        label $w.desc \
2442                -text "$appname - a commit creation tool for Git.
2443$copyright" \
2444                -padx 5 -pady 5 \
2445                -justify left \
2446                -anchor w \
2447                -borderwidth 1 \
2448                -relief solid \
2449                -font font_ui
2450        pack $w.desc -side top -fill x -padx 5 -pady 5
2451
2452        set v [exec git --version]
2453        append v "\n\n"
2454        if {$tcl_patchLevel eq $tk_patchLevel} {
2455                append v "Tcl/Tk version $tcl_patchLevel"
2456        } else {
2457                append v "Tcl version $tcl_patchLevel"
2458                append v ", Tk version $tk_patchLevel"
2459        }
2460
2461        label $w.vers \
2462                -text $v \
2463                -padx 5 -pady 5 \
2464                -justify left \
2465                -anchor w \
2466                -borderwidth 1 \
2467                -relief solid \
2468                -font font_ui
2469        pack $w.vers -side top -fill x -padx 5 -pady 5
2470
2471        bind $w <Visibility> "grab $w; focus $w"
2472        bind $w <Key-Escape> "destroy $w"
2473        wm title $w "About $appname"
2474        tkwait window $w
2475}
2476
2477proc do_options {} {
2478        global appname gitdir font_descs
2479        global repo_config global_config
2480        global repo_config_new global_config_new
2481
2482        array unset repo_config_new
2483        array unset global_config_new
2484        foreach name [array names repo_config] {
2485                set repo_config_new($name) $repo_config($name)
2486        }
2487        load_config 1
2488        foreach name [array names repo_config] {
2489                switch -- $name {
2490                gui.diffcontext {continue}
2491                }
2492                set repo_config_new($name) $repo_config($name)
2493        }
2494        foreach name [array names global_config] {
2495                set global_config_new($name) $global_config($name)
2496        }
2497        set reponame [lindex [file split \
2498                [file normalize [file dirname $gitdir]]] \
2499                end]
2500
2501        set w .options_editor
2502        toplevel $w
2503        wm geometry $w "+[winfo rootx .]+[winfo rooty .]"
2504
2505        label $w.header -text "$appname Options" \
2506                -font font_uibold
2507        pack $w.header -side top -fill x
2508
2509        frame $w.buttons
2510        button $w.buttons.restore -text {Restore Defaults} \
2511                -font font_ui \
2512                -command do_restore_defaults
2513        pack $w.buttons.restore -side left
2514        button $w.buttons.save -text Save \
2515                -font font_ui \
2516                -command [list do_save_config $w]
2517        pack $w.buttons.save -side right
2518        button $w.buttons.cancel -text {Cancel} \
2519                -font font_ui \
2520                -command [list destroy $w]
2521        pack $w.buttons.cancel -side right
2522        pack $w.buttons -side bottom -fill x -pady 10 -padx 10
2523
2524        labelframe $w.repo -text "$reponame Repository" \
2525                -font font_ui \
2526                -relief raised -borderwidth 2
2527        labelframe $w.global -text {Global (All Repositories)} \
2528                -font font_ui \
2529                -relief raised -borderwidth 2
2530        pack $w.repo -side left -fill both -expand 1 -pady 5 -padx 5
2531        pack $w.global -side right -fill both -expand 1 -pady 5 -padx 5
2532
2533        foreach option {
2534                {b partialinclude {Allow Partially Included Files}}
2535                {b pullsummary {Show Pull Summary}}
2536                {b trustmtime  {Trust File Modification Timestamps}}
2537                {i diffcontext {Number of Diff Context Lines}}
2538                } {
2539                set type [lindex $option 0]
2540                set name [lindex $option 1]
2541                set text [lindex $option 2]
2542                foreach f {repo global} {
2543                        switch $type {
2544                        b {
2545                                checkbutton $w.$f.$name -text $text \
2546                                        -variable ${f}_config_new(gui.$name) \
2547                                        -onvalue true \
2548                                        -offvalue false \
2549                                        -font font_ui
2550                                pack $w.$f.$name -side top -anchor w
2551                        }
2552                        i {
2553                                frame $w.$f.$name
2554                                label $w.$f.$name.l -text "$text:" -font font_ui
2555                                pack $w.$f.$name.l -side left -anchor w -fill x
2556                                spinbox $w.$f.$name.v \
2557                                        -textvariable ${f}_config_new(gui.$name) \
2558                                        -from 1 -to 99 -increment 1 \
2559                                        -width 3 \
2560                                        -font font_ui
2561                                pack $w.$f.$name.v -side right -anchor e
2562                                pack $w.$f.$name -side top -anchor w -fill x
2563                        }
2564                        }
2565                }
2566        }
2567
2568        set all_fonts [lsort [font families]]
2569        foreach option $font_descs {
2570                set name [lindex $option 0]
2571                set font [lindex $option 1]
2572                set text [lindex $option 2]
2573
2574                set global_config_new(gui.$font^^family) \
2575                        [font configure $font -family]
2576                set global_config_new(gui.$font^^size) \
2577                        [font configure $font -size]
2578
2579                frame $w.global.$name
2580                label $w.global.$name.l -text "$text:" -font font_ui
2581                pack $w.global.$name.l -side left -anchor w -fill x
2582                eval tk_optionMenu $w.global.$name.family \
2583                        global_config_new(gui.$font^^family) \
2584                        $all_fonts
2585                spinbox $w.global.$name.size \
2586                        -textvariable global_config_new(gui.$font^^size) \
2587                        -from 2 -to 80 -increment 1 \
2588                        -width 3 \
2589                        -font font_ui
2590                pack $w.global.$name.size -side right -anchor e
2591                pack $w.global.$name.family -side right -anchor e
2592                pack $w.global.$name -side top -anchor w -fill x
2593        }
2594
2595        bind $w <Visibility> "grab $w; focus $w"
2596        bind $w <Key-Escape> "destroy $w"
2597        wm title $w "$appname ($reponame): Options"
2598        tkwait window $w
2599}
2600
2601proc do_restore_defaults {} {
2602        global font_descs default_config repo_config
2603        global repo_config_new global_config_new
2604
2605        foreach name [array names default_config] {
2606                set repo_config_new($name) $default_config($name)
2607                set global_config_new($name) $default_config($name)
2608        }
2609
2610        foreach option $font_descs {
2611                set name [lindex $option 0]
2612                set repo_config(gui.$name) $default_config(gui.$name)
2613        }
2614        apply_config
2615
2616        foreach option $font_descs {
2617                set name [lindex $option 0]
2618                set font [lindex $option 1]
2619                set global_config_new(gui.$font^^family) \
2620                        [font configure $font -family]
2621                set global_config_new(gui.$font^^size) \
2622                        [font configure $font -size]
2623        }
2624}
2625
2626proc do_save_config {w} {
2627        if {[catch {save_config} err]} {
2628                error_popup "Failed to completely save options:\n\n$err"
2629        }
2630        reshow_diff
2631        destroy $w
2632}
2633
2634proc do_windows_shortcut {} {
2635        global gitdir appname argv0
2636
2637        set reponame [lindex [file split \
2638                [file normalize [file dirname $gitdir]]] \
2639                end]
2640
2641        if {[catch {
2642                set desktop [exec cygpath \
2643                        --windows \
2644                        --absolute \
2645                        --long-name \
2646                        --desktop]
2647                }]} {
2648                        set desktop .
2649        }
2650        set fn [tk_getSaveFile \
2651                -parent . \
2652                -title "$appname ($reponame): Create Desktop Icon" \
2653                -initialdir $desktop \
2654                -initialfile "Git $reponame.bat"]
2655        if {$fn != {}} {
2656                if {[catch {
2657                                set fd [open $fn w]
2658                                set sh [exec cygpath \
2659                                        --windows \
2660                                        --absolute \
2661                                        --long-name \
2662                                        /bin/sh]
2663                                set me [exec cygpath \
2664                                        --unix \
2665                                        --absolute \
2666                                        $argv0]
2667                                set gd [exec cygpath \
2668                                        --unix \
2669                                        --absolute \
2670                                        $gitdir]
2671                                regsub -all ' $me "'\\''" me
2672                                regsub -all ' $gd "'\\''" gd
2673                                puts -nonewline $fd "\"$sh\" --login -c \""
2674                                puts -nonewline $fd "GIT_DIR='$gd'"
2675                                puts -nonewline $fd " '$me'"
2676                                puts $fd "&\""
2677                                close $fd
2678                        } err]} {
2679                        error_popup "Cannot write script:\n\n$err"
2680                }
2681        }
2682}
2683
2684proc do_macosx_app {} {
2685        global gitdir appname argv0 env
2686
2687        set reponame [lindex [file split \
2688                [file normalize [file dirname $gitdir]]] \
2689                end]
2690
2691        set fn [tk_getSaveFile \
2692                -parent . \
2693                -title "$appname ($reponame): Create Desktop Icon" \
2694                -initialdir [file join $env(HOME) Desktop] \
2695                -initialfile "Git $reponame.app"]
2696        if {$fn != {}} {
2697                if {[catch {
2698                                set Contents [file join $fn Contents]
2699                                set MacOS [file join $Contents MacOS]
2700                                set exe [file join $MacOS git-gui]
2701
2702                                file mkdir $MacOS
2703
2704                                set fd [open [file join $Contents Info.plist] w]
2705                                puts $fd {<?xml version="1.0" encoding="UTF-8"?>
2706<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
2707<plist version="1.0">
2708<dict>
2709        <key>CFBundleDevelopmentRegion</key>
2710        <string>English</string>
2711        <key>CFBundleExecutable</key>
2712        <string>git-gui</string>
2713        <key>CFBundleIdentifier</key>
2714        <string>org.spearce.git-gui</string>
2715        <key>CFBundleInfoDictionaryVersion</key>
2716        <string>6.0</string>
2717        <key>CFBundlePackageType</key>
2718        <string>APPL</string>
2719        <key>CFBundleSignature</key>
2720        <string>????</string>
2721        <key>CFBundleVersion</key>
2722        <string>1.0</string>
2723        <key>NSPrincipalClass</key>
2724        <string>NSApplication</string>
2725</dict>
2726</plist>}
2727                                close $fd
2728
2729                                set fd [open $exe w]
2730                                set gd [file normalize $gitdir]
2731                                set ep [file normalize [exec git --exec-path]]
2732                                regsub -all ' $gd "'\\''" gd
2733                                regsub -all ' $ep "'\\''" ep
2734                                puts $fd "#!/bin/sh"
2735                                foreach name [array names env] {
2736                                        if {[string match GIT_* $name]} {
2737                                                regsub -all ' $env($name) "'\\''" v
2738                                                puts $fd "export $name='$v'"
2739                                        }
2740                                }
2741                                puts $fd "export PATH='$ep':\$PATH"
2742                                puts $fd "export GIT_DIR='$gd'"
2743                                puts $fd "exec [file normalize $argv0]"
2744                                close $fd
2745
2746                                file attributes $exe -permissions u+x,g+x,o+x
2747                        } err]} {
2748                        error_popup "Cannot write icon:\n\n$err"
2749                }
2750        }
2751}
2752
2753proc toggle_or_diff {w x y} {
2754        global file_states file_lists current_diff ui_index ui_other
2755        global last_clicked selected_paths
2756
2757        set pos [split [$w index @$x,$y] .]
2758        set lno [lindex $pos 0]
2759        set col [lindex $pos 1]
2760        set path [lindex $file_lists($w) [expr {$lno - 1}]]
2761        if {$path eq {}} {
2762                set last_clicked {}
2763                return
2764        }
2765
2766        set last_clicked [list $w $lno]
2767        array unset selected_paths
2768        $ui_index tag remove in_sel 0.0 end
2769        $ui_other tag remove in_sel 0.0 end
2770
2771        if {$col == 0} {
2772                if {$current_diff eq $path} {
2773                        set after {reshow_diff;}
2774                } else {
2775                        set after {}
2776                }
2777                switch -glob -- [lindex $file_states($path) 0] {
2778                A_ -
2779                M_ -
2780                DD -
2781                DO -
2782                DM {
2783                        update_indexinfo \
2784                                "Removing [short_path $path] from commit" \
2785                                [list $path] \
2786                                [concat $after {set ui_status_value {Ready.}}]
2787                }
2788                ?? {
2789                        update_index \
2790                                "Including [short_path $path]" \
2791                                [list $path] \
2792                                [concat $after {set ui_status_value {Ready.}}]
2793                }
2794                }
2795        } else {
2796                show_diff $path $w $lno
2797        }
2798}
2799
2800proc add_one_to_selection {w x y} {
2801        global file_lists
2802        global last_clicked selected_paths
2803
2804        set pos [split [$w index @$x,$y] .]
2805        set lno [lindex $pos 0]
2806        set col [lindex $pos 1]
2807        set path [lindex $file_lists($w) [expr {$lno - 1}]]
2808        if {$path eq {}} {
2809                set last_clicked {}
2810                return
2811        }
2812
2813        set last_clicked [list $w $lno]
2814        if {[catch {set in_sel $selected_paths($path)}]} {
2815                set in_sel 0
2816        }
2817        if {$in_sel} {
2818                unset selected_paths($path)
2819                $w tag remove in_sel $lno.0 [expr {$lno + 1}].0
2820        } else {
2821                set selected_paths($path) 1
2822                $w tag add in_sel $lno.0 [expr {$lno + 1}].0
2823        }
2824}
2825
2826proc add_range_to_selection {w x y} {
2827        global file_lists
2828        global last_clicked selected_paths
2829
2830        if {[lindex $last_clicked 0] ne $w} {
2831                toggle_or_diff $w $x $y
2832                return
2833        }
2834
2835        set pos [split [$w index @$x,$y] .]
2836        set lno [lindex $pos 0]
2837        set lc [lindex $last_clicked 1]
2838        if {$lc < $lno} {
2839                set begin $lc
2840                set end $lno
2841        } else {
2842                set begin $lno
2843                set end $lc
2844        }
2845
2846        foreach path [lrange $file_lists($w) \
2847                [expr {$begin - 1}] \
2848                [expr {$end - 1}]] {
2849                set selected_paths($path) 1
2850        }
2851        $w tag add in_sel $begin.0 [expr {$end + 1}].0
2852}
2853
2854######################################################################
2855##
2856## config defaults
2857
2858set cursor_ptr arrow
2859font create font_diff -family Courier -size 10
2860font create font_ui
2861catch {
2862        label .dummy
2863        eval font configure font_ui [font actual [.dummy cget -font]]
2864        destroy .dummy
2865}
2866
2867font create font_uibold
2868font create font_diffbold
2869
2870if {[is_Windows]} {
2871        set M1B Control
2872        set M1T Ctrl
2873} elseif {[is_MacOSX]} {
2874        set M1B M1
2875        set M1T Cmd
2876} else {
2877        set M1B M1
2878        set M1T M1
2879}
2880
2881proc apply_config {} {
2882        global repo_config font_descs
2883
2884        foreach option $font_descs {
2885                set name [lindex $option 0]
2886                set font [lindex $option 1]
2887                if {[catch {
2888                        foreach {cn cv} $repo_config(gui.$name) {
2889                                font configure $font $cn $cv
2890                        }
2891                        } err]} {
2892                        error_popup "Invalid font specified in gui.$name:\n\n$err"
2893                }
2894                foreach {cn cv} [font configure $font] {
2895                        font configure ${font}bold $cn $cv
2896                }
2897                font configure ${font}bold -weight bold
2898        }
2899}
2900
2901set default_config(gui.trustmtime) false
2902set default_config(gui.pullsummary) true
2903set default_config(gui.partialinclude) false
2904set default_config(gui.diffcontext) 5
2905set default_config(gui.fontui) [font configure font_ui]
2906set default_config(gui.fontdiff) [font configure font_diff]
2907set font_descs {
2908        {fontui   font_ui   {Main Font}}
2909        {fontdiff font_diff {Diff/Console Font}}
2910}
2911load_config 0
2912apply_config
2913
2914######################################################################
2915##
2916## ui construction
2917
2918# -- Menu Bar
2919#
2920menu .mbar -tearoff 0
2921.mbar add cascade -label Repository -menu .mbar.repository
2922.mbar add cascade -label Edit -menu .mbar.edit
2923if {!$single_commit} {
2924        .mbar add cascade -label Branch -menu .mbar.branch
2925}
2926.mbar add cascade -label Commit -menu .mbar.commit
2927if {!$single_commit} {
2928        .mbar add cascade -label Fetch -menu .mbar.fetch
2929        .mbar add cascade -label Pull -menu .mbar.pull
2930        .mbar add cascade -label Push -menu .mbar.push
2931}
2932. configure -menu .mbar
2933
2934# -- Repository Menu
2935#
2936menu .mbar.repository
2937.mbar.repository add command \
2938        -label {Visualize Current Branch} \
2939        -command {do_gitk {}} \
2940        -font font_ui
2941if {![is_MacOSX]} {
2942        .mbar.repository add command \
2943                -label {Visualize All Branches} \
2944                -command {do_gitk {--all}} \
2945                -font font_ui
2946}
2947.mbar.repository add separator
2948
2949if {!$single_commit} {
2950        .mbar.repository add command -label {Repack Database} \
2951                -command do_repack \
2952                -font font_ui
2953
2954        .mbar.repository add command -label {Verify Database} \
2955                -command do_fsck_objects \
2956                -font font_ui
2957
2958        .mbar.repository add separator
2959
2960        if {[is_Windows]} {
2961                .mbar.repository add command \
2962                        -label {Create Desktop Icon} \
2963                        -command do_windows_shortcut \
2964                        -font font_ui
2965        } elseif {[is_MacOSX]} {
2966                .mbar.repository add command \
2967                        -label {Create Desktop Icon} \
2968                        -command do_macosx_app \
2969                        -font font_ui
2970        }
2971}
2972.mbar.repository add command -label Quit \
2973        -command do_quit \
2974        -accelerator $M1T-Q \
2975        -font font_ui
2976
2977# -- Edit Menu
2978#
2979menu .mbar.edit
2980.mbar.edit add command -label Undo \
2981        -command {catch {[focus] edit undo}} \
2982        -accelerator $M1T-Z \
2983        -font font_ui
2984.mbar.edit add command -label Redo \
2985        -command {catch {[focus] edit redo}} \
2986        -accelerator $M1T-Y \
2987        -font font_ui
2988.mbar.edit add separator
2989.mbar.edit add command -label Cut \
2990        -command {catch {tk_textCut [focus]}} \
2991        -accelerator $M1T-X \
2992        -font font_ui
2993.mbar.edit add command -label Copy \
2994        -command {catch {tk_textCopy [focus]}} \
2995        -accelerator $M1T-C \
2996        -font font_ui
2997.mbar.edit add command -label Paste \
2998        -command {catch {tk_textPaste [focus]; [focus] see insert}} \
2999        -accelerator $M1T-V \
3000        -font font_ui
3001.mbar.edit add command -label Delete \
3002        -command {catch {[focus] delete sel.first sel.last}} \
3003        -accelerator Del \
3004        -font font_ui
3005.mbar.edit add separator
3006.mbar.edit add command -label {Select All} \
3007        -command {catch {[focus] tag add sel 0.0 end}} \
3008        -accelerator $M1T-A \
3009        -font font_ui
3010
3011if {!$single_commit} {
3012        # -- Branch Menu
3013        #
3014        menu .mbar.branch
3015
3016        .mbar.branch add command -label {Create...} \
3017                -command do_create_branch \
3018                -font font_ui
3019        lappend disable_on_lock [list .mbar.branch entryconf \
3020                [.mbar.branch index last] -state]
3021
3022        .mbar.branch add command -label {Delete...} \
3023                -command do_delete_branch \
3024                -font font_ui
3025        lappend disable_on_lock [list .mbar.branch entryconf \
3026                [.mbar.branch index last] -state]
3027}
3028
3029# -- Commit Menu
3030#
3031menu .mbar.commit
3032
3033.mbar.commit add radiobutton \
3034        -label {New Commit} \
3035        -command do_select_commit_type \
3036        -variable selected_commit_type \
3037        -value new \
3038        -font font_ui
3039lappend disable_on_lock \
3040        [list .mbar.commit entryconf [.mbar.commit index last] -state]
3041
3042.mbar.commit add radiobutton \
3043        -label {Amend Last Commit} \
3044        -command do_select_commit_type \
3045        -variable selected_commit_type \
3046        -value amend \
3047        -font font_ui
3048lappend disable_on_lock \
3049        [list .mbar.commit entryconf [.mbar.commit index last] -state]
3050
3051.mbar.commit add separator
3052
3053.mbar.commit add command -label Rescan \
3054        -command do_rescan \
3055        -accelerator F5 \
3056        -font font_ui
3057lappend disable_on_lock \
3058        [list .mbar.commit entryconf [.mbar.commit index last] -state]
3059
3060.mbar.commit add command -label {Include In Commit} \
3061        -command do_include_selection \
3062        -font font_ui
3063lappend disable_on_lock \
3064        [list .mbar.commit entryconf [.mbar.commit index last] -state]
3065
3066.mbar.commit add command -label {Include All In Commit} \
3067        -command do_include_all \
3068        -accelerator $M1T-I \
3069        -font font_ui
3070lappend disable_on_lock \
3071        [list .mbar.commit entryconf [.mbar.commit index last] -state]
3072
3073.mbar.commit add command -label {Remove From Commit} \
3074        -command do_remove_selection \
3075        -font font_ui
3076lappend disable_on_lock \
3077        [list .mbar.commit entryconf [.mbar.commit index last] -state]
3078
3079.mbar.commit add command -label {Revert Changes} \
3080        -command do_revert_selection \
3081        -font font_ui
3082lappend disable_on_lock \
3083        [list .mbar.commit entryconf [.mbar.commit index last] -state]
3084
3085.mbar.commit add separator
3086
3087.mbar.commit add command -label {Sign Off} \
3088        -command do_signoff \
3089        -accelerator $M1T-S \
3090        -font font_ui
3091
3092.mbar.commit add command -label Commit \
3093        -command do_commit \
3094        -accelerator $M1T-Return \
3095        -font font_ui
3096lappend disable_on_lock \
3097        [list .mbar.commit entryconf [.mbar.commit index last] -state]
3098
3099# -- Transport menus
3100#
3101if {!$single_commit} {
3102        menu .mbar.fetch
3103        menu .mbar.pull
3104        menu .mbar.push
3105}
3106
3107if {[is_MacOSX]} {
3108        # -- Apple Menu (Mac OS X only)
3109        #
3110        .mbar add cascade -label Apple -menu .mbar.apple
3111        menu .mbar.apple
3112
3113        .mbar.apple add command -label "About $appname" \
3114                -command do_about \
3115                -font font_ui
3116        .mbar.apple add command -label "$appname Options..." \
3117                -command do_options \
3118                -font font_ui
3119} else {
3120        # -- Edit Menu
3121        #
3122        .mbar.edit add separator
3123        .mbar.edit add command -label {Options...} \
3124                -command do_options \
3125                -font font_ui
3126
3127        # -- Help Menu
3128        #
3129        .mbar add cascade -label Help -menu .mbar.help
3130        menu .mbar.help
3131
3132        .mbar.help add command -label "About $appname" \
3133                -command do_about \
3134                -font font_ui
3135}
3136
3137
3138# -- Branch Control
3139#
3140frame .branch \
3141        -borderwidth 1 \
3142        -relief sunken
3143label .branch.l1 \
3144        -text {Current Branch:} \
3145        -anchor w \
3146        -justify left \
3147        -font font_ui
3148label .branch.cb \
3149        -textvariable current_branch \
3150        -anchor w \
3151        -justify left \
3152        -font font_ui
3153pack .branch.l1 -side left
3154pack .branch.cb -side left -fill x
3155pack .branch -side top -fill x
3156
3157# -- Main Window Layout
3158#
3159panedwindow .vpane -orient vertical
3160panedwindow .vpane.files -orient horizontal
3161.vpane add .vpane.files -sticky nsew -height 100 -width 400
3162pack .vpane -anchor n -side top -fill both -expand 1
3163
3164# -- Index File List
3165#
3166frame .vpane.files.index -height 100 -width 400
3167label .vpane.files.index.title -text {Modified Files} \
3168        -background green \
3169        -font font_ui
3170text $ui_index -background white -borderwidth 0 \
3171        -width 40 -height 10 \
3172        -font font_ui \
3173        -cursor $cursor_ptr \
3174        -yscrollcommand {.vpane.files.index.sb set} \
3175        -state disabled
3176scrollbar .vpane.files.index.sb -command [list $ui_index yview]
3177pack .vpane.files.index.title -side top -fill x
3178pack .vpane.files.index.sb -side right -fill y
3179pack $ui_index -side left -fill both -expand 1
3180.vpane.files add .vpane.files.index -sticky nsew
3181
3182# -- Other (Add) File List
3183#
3184frame .vpane.files.other -height 100 -width 100
3185label .vpane.files.other.title -text {Untracked Files} \
3186        -background red \
3187        -font font_ui
3188text $ui_other -background white -borderwidth 0 \
3189        -width 40 -height 10 \
3190        -font font_ui \
3191        -cursor $cursor_ptr \
3192        -yscrollcommand {.vpane.files.other.sb set} \
3193        -state disabled
3194scrollbar .vpane.files.other.sb -command [list $ui_other yview]
3195pack .vpane.files.other.title -side top -fill x
3196pack .vpane.files.other.sb -side right -fill y
3197pack $ui_other -side left -fill both -expand 1
3198.vpane.files add .vpane.files.other -sticky nsew
3199
3200foreach i [list $ui_index $ui_other] {
3201        $i tag conf in_diff -font font_uibold
3202        $i tag conf in_sel \
3203                -background [$i cget -foreground] \
3204                -foreground [$i cget -background]
3205}
3206unset i
3207
3208# -- Diff and Commit Area
3209#
3210frame .vpane.lower -height 300 -width 400
3211frame .vpane.lower.commarea
3212frame .vpane.lower.diff -relief sunken -borderwidth 1
3213pack .vpane.lower.commarea -side top -fill x
3214pack .vpane.lower.diff -side bottom -fill both -expand 1
3215.vpane add .vpane.lower -stick nsew
3216
3217# -- Commit Area Buttons
3218#
3219frame .vpane.lower.commarea.buttons
3220label .vpane.lower.commarea.buttons.l -text {} \
3221        -anchor w \
3222        -justify left \
3223        -font font_ui
3224pack .vpane.lower.commarea.buttons.l -side top -fill x
3225pack .vpane.lower.commarea.buttons -side left -fill y
3226
3227button .vpane.lower.commarea.buttons.rescan -text {Rescan} \
3228        -command do_rescan \
3229        -font font_ui
3230pack .vpane.lower.commarea.buttons.rescan -side top -fill x
3231lappend disable_on_lock \
3232        {.vpane.lower.commarea.buttons.rescan conf -state}
3233
3234button .vpane.lower.commarea.buttons.incall -text {Include All} \
3235        -command do_include_all \
3236        -font font_ui
3237pack .vpane.lower.commarea.buttons.incall -side top -fill x
3238lappend disable_on_lock \
3239        {.vpane.lower.commarea.buttons.incall conf -state}
3240
3241button .vpane.lower.commarea.buttons.signoff -text {Sign Off} \
3242        -command do_signoff \
3243        -font font_ui
3244pack .vpane.lower.commarea.buttons.signoff -side top -fill x
3245
3246button .vpane.lower.commarea.buttons.commit -text {Commit} \
3247        -command do_commit \
3248        -font font_ui
3249pack .vpane.lower.commarea.buttons.commit -side top -fill x
3250lappend disable_on_lock \
3251        {.vpane.lower.commarea.buttons.commit conf -state}
3252
3253# -- Commit Message Buffer
3254#
3255frame .vpane.lower.commarea.buffer
3256frame .vpane.lower.commarea.buffer.header
3257set ui_comm .vpane.lower.commarea.buffer.t
3258set ui_coml .vpane.lower.commarea.buffer.header.l
3259radiobutton .vpane.lower.commarea.buffer.header.new \
3260        -text {New Commit} \
3261        -command do_select_commit_type \
3262        -variable selected_commit_type \
3263        -value new \
3264        -font font_ui
3265lappend disable_on_lock \
3266        [list .vpane.lower.commarea.buffer.header.new conf -state]
3267radiobutton .vpane.lower.commarea.buffer.header.amend \
3268        -text {Amend Last Commit} \
3269        -command do_select_commit_type \
3270        -variable selected_commit_type \
3271        -value amend \
3272        -font font_ui
3273lappend disable_on_lock \
3274        [list .vpane.lower.commarea.buffer.header.amend conf -state]
3275label $ui_coml \
3276        -anchor w \
3277        -justify left \
3278        -font font_ui
3279proc trace_commit_type {varname args} {
3280        global ui_coml commit_type
3281        switch -glob -- $commit_type {
3282        initial       {set txt {Initial Commit Message:}}
3283        amend         {set txt {Amended Commit Message:}}
3284        amend-initial {set txt {Amended Initial Commit Message:}}
3285        amend-merge   {set txt {Amended Merge Commit Message:}}
3286        merge         {set txt {Merge Commit Message:}}
3287        *             {set txt {Commit Message:}}
3288        }
3289        $ui_coml conf -text $txt
3290}
3291trace add variable commit_type write trace_commit_type
3292pack $ui_coml -side left -fill x
3293pack .vpane.lower.commarea.buffer.header.amend -side right
3294pack .vpane.lower.commarea.buffer.header.new -side right
3295
3296text $ui_comm -background white -borderwidth 1 \
3297        -undo true \
3298        -maxundo 20 \
3299        -autoseparators true \
3300        -relief sunken \
3301        -width 75 -height 9 -wrap none \
3302        -font font_diff \
3303        -yscrollcommand {.vpane.lower.commarea.buffer.sby set}
3304scrollbar .vpane.lower.commarea.buffer.sby \
3305        -command [list $ui_comm yview]
3306pack .vpane.lower.commarea.buffer.header -side top -fill x
3307pack .vpane.lower.commarea.buffer.sby -side right -fill y
3308pack $ui_comm -side left -fill y
3309pack .vpane.lower.commarea.buffer -side left -fill y
3310
3311# -- Commit Message Buffer Context Menu
3312#
3313set ctxm .vpane.lower.commarea.buffer.ctxm
3314menu $ctxm -tearoff 0
3315$ctxm add command \
3316        -label {Cut} \
3317        -font font_ui \
3318        -command {tk_textCut $ui_comm}
3319$ctxm add command \
3320        -label {Copy} \
3321        -font font_ui \
3322        -command {tk_textCopy $ui_comm}
3323$ctxm add command \
3324        -label {Paste} \
3325        -font font_ui \
3326        -command {tk_textPaste $ui_comm}
3327$ctxm add command \
3328        -label {Delete} \
3329        -font font_ui \
3330        -command {$ui_comm delete sel.first sel.last}
3331$ctxm add separator
3332$ctxm add command \
3333        -label {Select All} \
3334        -font font_ui \
3335        -command {$ui_comm tag add sel 0.0 end}
3336$ctxm add command \
3337        -label {Copy All} \
3338        -font font_ui \
3339        -command {
3340                $ui_comm tag add sel 0.0 end
3341                tk_textCopy $ui_comm
3342                $ui_comm tag remove sel 0.0 end
3343        }
3344$ctxm add separator
3345$ctxm add command \
3346        -label {Sign Off} \
3347        -font font_ui \
3348        -command do_signoff
3349bind_button3 $ui_comm "tk_popup $ctxm %X %Y"
3350
3351# -- Diff Header
3352#
3353set current_diff {}
3354set diff_actions [list]
3355proc trace_current_diff {varname args} {
3356        global current_diff diff_actions file_states
3357        if {$current_diff eq {}} {
3358                set s {}
3359                set f {}
3360                set p {}
3361                set o disabled
3362        } else {
3363                set p $current_diff
3364                set s [mapdesc [lindex $file_states($p) 0] $p]
3365                set f {File:}
3366                set p [escape_path $p]
3367                set o normal
3368        }
3369
3370        .vpane.lower.diff.header.status configure -text $s
3371        .vpane.lower.diff.header.file configure -text $f
3372        .vpane.lower.diff.header.path configure -text $p
3373        foreach w $diff_actions {
3374                uplevel #0 $w $o
3375        }
3376}
3377trace add variable current_diff write trace_current_diff
3378
3379frame .vpane.lower.diff.header -background orange
3380label .vpane.lower.diff.header.status \
3381        -background orange \
3382        -width $max_status_desc \
3383        -anchor w \
3384        -justify left \
3385        -font font_ui
3386label .vpane.lower.diff.header.file \
3387        -background orange \
3388        -anchor w \
3389        -justify left \
3390        -font font_ui
3391label .vpane.lower.diff.header.path \
3392        -background orange \
3393        -anchor w \
3394        -justify left \
3395        -font font_ui
3396pack .vpane.lower.diff.header.status -side left
3397pack .vpane.lower.diff.header.file -side left
3398pack .vpane.lower.diff.header.path -fill x
3399set ctxm .vpane.lower.diff.header.ctxm
3400menu $ctxm -tearoff 0
3401$ctxm add command \
3402        -label {Copy} \
3403        -font font_ui \
3404        -command {
3405                clipboard clear
3406                clipboard append \
3407                        -format STRING \
3408                        -type STRING \
3409                        -- $current_diff
3410        }
3411lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3412bind_button3 .vpane.lower.diff.header.path "tk_popup $ctxm %X %Y"
3413
3414# -- Diff Body
3415#
3416frame .vpane.lower.diff.body
3417set ui_diff .vpane.lower.diff.body.t
3418text $ui_diff -background white -borderwidth 0 \
3419        -width 80 -height 15 -wrap none \
3420        -font font_diff \
3421        -xscrollcommand {.vpane.lower.diff.body.sbx set} \
3422        -yscrollcommand {.vpane.lower.diff.body.sby set} \
3423        -state disabled
3424scrollbar .vpane.lower.diff.body.sbx -orient horizontal \
3425        -command [list $ui_diff xview]
3426scrollbar .vpane.lower.diff.body.sby -orient vertical \
3427        -command [list $ui_diff yview]
3428pack .vpane.lower.diff.body.sbx -side bottom -fill x
3429pack .vpane.lower.diff.body.sby -side right -fill y
3430pack $ui_diff -side left -fill both -expand 1
3431pack .vpane.lower.diff.header -side top -fill x
3432pack .vpane.lower.diff.body -side bottom -fill both -expand 1
3433
3434$ui_diff tag conf d_@ -font font_diffbold
3435$ui_diff tag conf d_+  -foreground blue
3436$ui_diff tag conf d_-  -foreground red
3437$ui_diff tag conf d_++ -foreground {#00a000}
3438$ui_diff tag conf d_-- -foreground {#a000a0}
3439$ui_diff tag conf d_+- \
3440        -foreground red \
3441        -background {light goldenrod yellow}
3442$ui_diff tag conf d_-+ \
3443        -foreground blue \
3444        -background azure2
3445
3446# -- Diff Body Context Menu
3447#
3448set ctxm .vpane.lower.diff.body.ctxm
3449menu $ctxm -tearoff 0
3450$ctxm add command \
3451        -label {Copy} \
3452        -font font_ui \
3453        -command {tk_textCopy $ui_diff}
3454lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3455$ctxm add command \
3456        -label {Select All} \
3457        -font font_ui \
3458        -command {$ui_diff tag add sel 0.0 end}
3459lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3460$ctxm add command \
3461        -label {Copy All} \
3462        -font font_ui \
3463        -command {
3464                $ui_diff tag add sel 0.0 end
3465                tk_textCopy $ui_diff
3466                $ui_diff tag remove sel 0.0 end
3467        }
3468lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3469$ctxm add separator
3470$ctxm add command \
3471        -label {Decrease Font Size} \
3472        -font font_ui \
3473        -command {incr_font_size font_diff -1}
3474lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3475$ctxm add command \
3476        -label {Increase Font Size} \
3477        -font font_ui \
3478        -command {incr_font_size font_diff 1}
3479lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3480$ctxm add separator
3481$ctxm add command \
3482        -label {Show Less Context} \
3483        -font font_ui \
3484        -command {if {$repo_config(gui.diffcontext) >= 2} {
3485                incr repo_config(gui.diffcontext) -1
3486                reshow_diff
3487        }}
3488lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3489$ctxm add command \
3490        -label {Show More Context} \
3491        -font font_ui \
3492        -command {
3493                incr repo_config(gui.diffcontext)
3494                reshow_diff
3495        }
3496lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state]
3497$ctxm add separator
3498$ctxm add command -label {Options...} \
3499        -font font_ui \
3500        -command do_options
3501bind_button3 $ui_diff "tk_popup $ctxm %X %Y"
3502
3503# -- Status Bar
3504#
3505set ui_status_value {Initializing...}
3506label .status -textvariable ui_status_value \
3507        -anchor w \
3508        -justify left \
3509        -borderwidth 1 \
3510        -relief sunken \
3511        -font font_ui
3512pack .status -anchor w -side bottom -fill x
3513
3514# -- Load geometry
3515#
3516catch {
3517set gm $repo_config(gui.geometry)
3518wm geometry . [lindex $gm 0]
3519.vpane sash place 0 \
3520        [lindex [.vpane sash coord 0] 0] \
3521        [lindex $gm 1]
3522.vpane.files sash place 0 \
3523        [lindex $gm 2] \
3524        [lindex [.vpane.files sash coord 0] 1]
3525unset gm
3526}
3527
3528# -- Key Bindings
3529#
3530bind $ui_comm <$M1B-Key-Return> {do_commit;break}
3531bind $ui_comm <$M1B-Key-i> {do_include_all;break}
3532bind $ui_comm <$M1B-Key-I> {do_include_all;break}
3533bind $ui_comm <$M1B-Key-x> {tk_textCut %W;break}
3534bind $ui_comm <$M1B-Key-X> {tk_textCut %W;break}
3535bind $ui_comm <$M1B-Key-c> {tk_textCopy %W;break}
3536bind $ui_comm <$M1B-Key-C> {tk_textCopy %W;break}
3537bind $ui_comm <$M1B-Key-v> {tk_textPaste %W; %W see insert; break}
3538bind $ui_comm <$M1B-Key-V> {tk_textPaste %W; %W see insert; break}
3539bind $ui_comm <$M1B-Key-a> {%W tag add sel 0.0 end;break}
3540bind $ui_comm <$M1B-Key-A> {%W tag add sel 0.0 end;break}
3541
3542bind $ui_diff <$M1B-Key-x> {tk_textCopy %W;break}
3543bind $ui_diff <$M1B-Key-X> {tk_textCopy %W;break}
3544bind $ui_diff <$M1B-Key-c> {tk_textCopy %W;break}
3545bind $ui_diff <$M1B-Key-C> {tk_textCopy %W;break}
3546bind $ui_diff <$M1B-Key-v> {break}
3547bind $ui_diff <$M1B-Key-V> {break}
3548bind $ui_diff <$M1B-Key-a> {%W tag add sel 0.0 end;break}
3549bind $ui_diff <$M1B-Key-A> {%W tag add sel 0.0 end;break}
3550bind $ui_diff <Key-Up>     {catch {%W yview scroll -1 units};break}
3551bind $ui_diff <Key-Down>   {catch {%W yview scroll  1 units};break}
3552bind $ui_diff <Key-Left>   {catch {%W xview scroll -1 units};break}
3553bind $ui_diff <Key-Right>  {catch {%W xview scroll  1 units};break}
3554
3555bind .   <Destroy> do_quit
3556bind all <Key-F5> do_rescan
3557bind all <$M1B-Key-r> do_rescan
3558bind all <$M1B-Key-R> do_rescan
3559bind .   <$M1B-Key-s> do_signoff
3560bind .   <$M1B-Key-S> do_signoff
3561bind .   <$M1B-Key-i> do_include_all
3562bind .   <$M1B-Key-I> do_include_all
3563bind .   <$M1B-Key-Return> do_commit
3564bind all <$M1B-Key-q> do_quit
3565bind all <$M1B-Key-Q> do_quit
3566bind all <$M1B-Key-w> {destroy [winfo toplevel %W]}
3567bind all <$M1B-Key-W> {destroy [winfo toplevel %W]}
3568foreach i [list $ui_index $ui_other] {
3569        bind $i <Button-1>       "toggle_or_diff         $i %x %y; break"
3570        bind $i <$M1B-Button-1>  "add_one_to_selection   $i %x %y; break"
3571        bind $i <Shift-Button-1> "add_range_to_selection $i %x %y; break"
3572}
3573unset i
3574
3575set file_lists($ui_index) [list]
3576set file_lists($ui_other) [list]
3577
3578set HEAD {}
3579set PARENT {}
3580set MERGE_HEAD [list]
3581set commit_type {}
3582set empty_tree {}
3583set current_branch {}
3584set current_diff {}
3585set selected_commit_type new
3586
3587wm title . "$appname ([file normalize [file dirname $gitdir]])"
3588focus -force $ui_comm
3589
3590# -- Warn the user about environmental problems.
3591#    Cygwin's Tcl does *not* pass its env array
3592#    onto any processes it spawns.  This means
3593#    that the git processes get none of our
3594#    environment.  That may not work...
3595#
3596if {[is_Windows]} {
3597        set ignored_env 0
3598        set suggest_user {}
3599        set msg "Possible environment issues exist.
3600
3601The following environment variables are probably
3602going to be ignored by any Git subprocess run
3603by $appname:
3604
3605"
3606        foreach name [array names env] {
3607                switch -regexp -- $name {
3608                {^GIT_INDEX_FILE$} -
3609                {^GIT_OBJECT_DIRECTORY$} -
3610                {^GIT_ALTERNATE_OBJECT_DIRECTORIES$} -
3611                {^GIT_DIFF_OPTS$} -
3612                {^GIT_EXTERNAL_DIFF$} -
3613                {^GIT_PAGER$} -
3614                {^GIT_TRACE$} -
3615                {^GIT_CONFIG$} -
3616                {^GIT_CONFIG_LOCAL$} -
3617                {^GIT_(AUTHOR|COMMITTER)_DATE$} {
3618                        append msg " - $name\n"
3619                        incr ignored_env
3620                }
3621                {^GIT_(AUTHOR|COMMITTER)_(NAME|EMAIL)$} {
3622                        append msg " - $name\n"
3623                        incr ignored_env
3624                        set suggest_user $name
3625                }
3626                }
3627        }
3628        if {$ignored_env > 0} {
3629                append msg "
3630This is due to a known issue with the
3631Tcl binary distributed by Cygwin."
3632
3633                if {$suggest_user ne {}} {
3634                        append msg "
3635
3636A good replacement for $suggest_user
3637is placing values for the user.name and
3638user.email settings into your personal
3639~/.gitconfig file.
3640"
3641                }
3642                warn_popup $msg
3643        }
3644        unset ignored_env msg suggest_user name
3645}
3646
3647if {!$single_commit} {
3648        load_all_remotes
3649        load_all_branches
3650        populate_branch_menu .mbar.branch
3651        populate_fetch_menu .mbar.fetch
3652        populate_pull_menu .mbar.pull
3653        populate_push_menu .mbar.push
3654}
3655lock_index begin-read
3656after 1 do_rescan