git-gui / lib / choose_repository.tclon commit Merge branch 'ks/recursive-rename-add-identical' (9f0ccb5)
   1# git-gui Git repository chooser
   2# Copyright (C) 2007 Shawn Pearce
   3
   4class choose_repository {
   5
   6field top
   7field w
   8field w_body      ; # Widget holding the center content
   9field w_next      ; # Next button
  10field w_quit      ; # Quit button
  11field o_cons      ; # Console object (if active)
  12field w_types     ; # List of type buttons in clone
  13field w_recentlist ; # Listbox containing recent repositories
  14field w_localpath  ; # Entry widget bound to local_path
  15
  16field done              0 ; # Finished picking the repository?
  17field local_path       {} ; # Where this repository is locally
  18field origin_url       {} ; # Where we are cloning from
  19field origin_name  origin ; # What we shall call 'origin'
  20field clone_type hardlink ; # Type of clone to construct
  21field readtree_err        ; # Error output from read-tree (if any)
  22field sorted_recent       ; # recent repositories (sorted)
  23
  24constructor pick {} {
  25        global M1T M1B use_ttk NS
  26
  27        make_dialog top w
  28        wm title $top [mc "Git Gui"]
  29
  30        if {$top eq {.}} {
  31                menu $w.mbar -tearoff 0
  32                $top configure -menu $w.mbar
  33
  34                set m_repo $w.mbar.repository
  35                $w.mbar add cascade \
  36                        -label [mc Repository] \
  37                        -menu $m_repo
  38                menu $m_repo
  39
  40                if {[is_MacOSX]} {
  41                        $w.mbar add cascade -label Apple -menu .mbar.apple
  42                        menu $w.mbar.apple
  43                        $w.mbar.apple add command \
  44                                -label [mc "About %s" [appname]] \
  45                                -command do_about
  46                        $w.mbar.apple add command \
  47                                -label [mc "Show SSH Key"] \
  48                                -command do_ssh_key
  49                } else {
  50                        $w.mbar add cascade -label [mc Help] -menu $w.mbar.help
  51                        menu $w.mbar.help
  52                        $w.mbar.help add command \
  53                                -label [mc "About %s" [appname]] \
  54                                -command do_about
  55                        $w.mbar.help add command \
  56                                -label [mc "Show SSH Key"] \
  57                                -command do_ssh_key
  58                }
  59
  60                wm protocol $top WM_DELETE_WINDOW exit
  61                bind $top <$M1B-q> exit
  62                bind $top <$M1B-Q> exit
  63                bind $top <Key-Escape> exit
  64        } else {
  65                wm geometry $top "+[winfo rootx .]+[winfo rooty .]"
  66                bind $top <Key-Escape> [list destroy $top]
  67                set m_repo {}
  68        }
  69
  70        pack [git_logo $w.git_logo] -side left -fill y -padx 10 -pady 10
  71
  72        set w_body $w.body
  73        set opts $w_body.options
  74        ${NS}::frame $w_body
  75        text $opts \
  76                -cursor $::cursor_ptr \
  77                -relief flat \
  78                -background [get_bg_color $w_body] \
  79                -wrap none \
  80                -spacing1 5 \
  81                -width 50 \
  82                -height 3
  83        pack $opts -anchor w -fill x
  84
  85        $opts tag conf link_new -foreground blue -underline 1
  86        $opts tag bind link_new <1> [cb _next new]
  87        $opts insert end [mc "Create New Repository"] link_new
  88        $opts insert end "\n"
  89        if {$m_repo ne {}} {
  90                $m_repo add command \
  91                        -command [cb _next new] \
  92                        -accelerator $M1T-N \
  93                        -label [mc "New..."]
  94                bind $top <$M1B-n> [cb _next new]
  95                bind $top <$M1B-N> [cb _next new]
  96        }
  97
  98        $opts tag conf link_clone -foreground blue -underline 1
  99        $opts tag bind link_clone <1> [cb _next clone]
 100        $opts insert end [mc "Clone Existing Repository"] link_clone
 101        $opts insert end "\n"
 102        if {$m_repo ne {}} {
 103                if {[tk windowingsystem] eq "win32"} {
 104                        set key L
 105                } else {
 106                        set key C
 107                }
 108                $m_repo add command \
 109                        -command [cb _next clone] \
 110                        -accelerator $M1T-$key \
 111                        -label [mc "Clone..."]
 112                bind $top <$M1B-[string tolower $key]> [cb _next clone]
 113                bind $top <$M1B-[string toupper $key]> [cb _next clone]
 114        }
 115
 116        $opts tag conf link_open -foreground blue -underline 1
 117        $opts tag bind link_open <1> [cb _next open]
 118        $opts insert end [mc "Open Existing Repository"] link_open
 119        $opts insert end "\n"
 120        if {$m_repo ne {}} {
 121                $m_repo add command \
 122                        -command [cb _next open] \
 123                        -accelerator $M1T-O \
 124                        -label [mc "Open..."]
 125                bind $top <$M1B-o> [cb _next open]
 126                bind $top <$M1B-O> [cb _next open]
 127        }
 128
 129        $opts conf -state disabled
 130
 131        set sorted_recent [_get_recentrepos]
 132        if {[llength $sorted_recent] > 0} {
 133                if {$m_repo ne {}} {
 134                        $m_repo add separator
 135                        $m_repo add command \
 136                                -state disabled \
 137                                -label [mc "Recent Repositories"]
 138                }
 139
 140                ${NS}::label $w_body.space
 141                ${NS}::label $w_body.recentlabel \
 142                        -anchor w \
 143                        -text [mc "Open Recent Repository:"]
 144                set w_recentlist $w_body.recentlist
 145                text $w_recentlist \
 146                        -cursor $::cursor_ptr \
 147                        -relief flat \
 148                        -background [get_bg_color $w_body.recentlabel] \
 149                        -wrap none \
 150                        -width 50 \
 151                        -height 10
 152                $w_recentlist tag conf link \
 153                        -foreground blue \
 154                        -underline 1
 155                set home $::env(HOME)
 156                if {[is_Cygwin]} {
 157                        set home [exec cygpath --windows --absolute $home]
 158                }
 159                set home "[file normalize $home]/"
 160                set hlen [string length $home]
 161                foreach p $sorted_recent {
 162                        set path $p
 163                        if {[string equal -length $hlen $home $p]} {
 164                                set p "~/[string range $p $hlen end]"
 165                        }
 166                        regsub -all "\n" $p "\\n" p
 167                        $w_recentlist insert end $p link
 168                        $w_recentlist insert end "\n"
 169
 170                        if {$m_repo ne {}} {
 171                                $m_repo add command \
 172                                        -command [cb _open_recent_path $path] \
 173                                        -label "    $p"
 174                        }
 175                }
 176                $w_recentlist conf -state disabled
 177                $w_recentlist tag bind link <1> [cb _open_recent %x,%y]
 178                pack $w_body.space -anchor w -fill x
 179                pack $w_body.recentlabel -anchor w -fill x
 180                pack $w_recentlist -anchor w -fill x
 181        }
 182        pack $w_body -fill x -padx 10 -pady 10
 183
 184        ${NS}::frame $w.buttons
 185        set w_next $w.buttons.next
 186        set w_quit $w.buttons.quit
 187        ${NS}::button $w_quit \
 188                -text [mc "Quit"] \
 189                -command exit
 190        pack $w_quit -side right -padx 5
 191        pack $w.buttons -side bottom -fill x -padx 10 -pady 10
 192
 193        if {$m_repo ne {}} {
 194                $m_repo add separator
 195                $m_repo add command \
 196                        -label [mc Quit] \
 197                        -command exit \
 198                        -accelerator $M1T-Q
 199        }
 200
 201        bind $top <Return> [cb _invoke_next]
 202        bind $top <Visibility> "
 203                [cb _center]
 204                grab $top
 205                focus $top
 206                bind $top <Visibility> {}
 207        "
 208        wm deiconify $top
 209        tkwait variable @done
 210
 211        grab release $top
 212        if {$top eq {.}} {
 213                eval destroy [winfo children $top]
 214        }
 215}
 216
 217proc _home {} {
 218        if {[catch {set h $::env(HOME)}]
 219                || ![file isdirectory $h]} {
 220                set h .
 221        }
 222        return $h
 223}
 224
 225method _center {} {
 226        set nx [winfo reqwidth $top]
 227        set ny [winfo reqheight $top]
 228        set rx [expr {([winfo screenwidth  $top] - $nx) / 3}]
 229        set ry [expr {([winfo screenheight $top] - $ny) / 3}]
 230        wm geometry $top [format {+%d+%d} $rx $ry]
 231}
 232
 233method _invoke_next {} {
 234        if {[winfo exists $w_next]} {
 235                uplevel #0 [$w_next cget -command]
 236        }
 237}
 238
 239proc _get_recentrepos {} {
 240        set recent [list]
 241        foreach p [get_config gui.recentrepo] {
 242                if {[_is_git [file join $p .git]]} {
 243                        lappend recent $p
 244                } else {
 245                        _unset_recentrepo $p
 246                }
 247        }
 248        return [lsort $recent]
 249}
 250
 251proc _unset_recentrepo {p} {
 252        regsub -all -- {([()\[\]{}\.^$+*?\\])} $p {\\\1} p
 253        git config --global --unset gui.recentrepo "^$p\$"
 254        load_config 1
 255}
 256
 257proc _append_recentrepos {path} {
 258        set path [file normalize $path]
 259        set recent [get_config gui.recentrepo]
 260
 261        if {[lindex $recent end] eq $path} {
 262                return
 263        }
 264
 265        set i [lsearch $recent $path]
 266        if {$i >= 0} {
 267                _unset_recentrepo $path
 268                set recent [lreplace $recent $i $i]
 269        }
 270
 271        lappend recent $path
 272        git config --global --add gui.recentrepo $path
 273        load_config 1
 274
 275        while {[llength $recent] > 10} {
 276                _unset_recentrepo [lindex $recent 0]
 277                set recent [lrange $recent 1 end]
 278        }
 279}
 280
 281method _open_recent {xy} {
 282        set id [lindex [split [$w_recentlist index @$xy] .] 0]
 283        set local_path [lindex $sorted_recent [expr {$id - 1}]]
 284        _do_open2 $this
 285}
 286
 287method _open_recent_path {p} {
 288        set local_path $p
 289        _do_open2 $this
 290}
 291
 292method _next {action} {
 293        global NS
 294        destroy $w_body
 295        if {![winfo exists $w_next]} {
 296                ${NS}::button $w_next -default active
 297                pack $w_next -side right -padx 5 -before $w_quit
 298        }
 299        _do_$action $this
 300}
 301
 302method _write_local_path {args} {
 303        if {$local_path eq {}} {
 304                $w_next conf -state disabled
 305        } else {
 306                $w_next conf -state normal
 307        }
 308}
 309
 310method _git_init {} {
 311        if {[catch {file mkdir $local_path} err]} {
 312                error_popup [strcat \
 313                        [mc "Failed to create repository %s:" $local_path] \
 314                        "\n\n$err"]
 315                return 0
 316        }
 317
 318        if {[catch {cd $local_path} err]} {
 319                error_popup [strcat \
 320                        [mc "Failed to create repository %s:" $local_path] \
 321                        "\n\n$err"]
 322                return 0
 323        }
 324
 325        if {[catch {git init} err]} {
 326                error_popup [strcat \
 327                        [mc "Failed to create repository %s:" $local_path] \
 328                        "\n\n$err"]
 329                return 0
 330        }
 331
 332        _append_recentrepos [pwd]
 333        set ::_gitdir .git
 334        set ::_prefix {}
 335        return 1
 336}
 337
 338proc _is_git {path} {
 339        if {[file exists [file join $path HEAD]]
 340         && [file exists [file join $path objects]]
 341         && [file exists [file join $path config]]} {
 342                return 1
 343        }
 344        if {[is_Cygwin]} {
 345                if {[file exists [file join $path HEAD]]
 346                 && [file exists [file join $path objects.lnk]]
 347                 && [file exists [file join $path config.lnk]]} {
 348                        return 1
 349                }
 350        }
 351        return 0
 352}
 353
 354proc _objdir {path} {
 355        set objdir [file join $path .git objects]
 356        if {[file isdirectory $objdir]} {
 357                return $objdir
 358        }
 359
 360        set objdir [file join $path objects]
 361        if {[file isdirectory $objdir]} {
 362                return $objdir
 363        }
 364
 365        if {[is_Cygwin]} {
 366                set objdir [file join $path .git objects.lnk]
 367                if {[file isfile $objdir]} {
 368                        return [win32_read_lnk $objdir]
 369                }
 370
 371                set objdir [file join $path objects.lnk]
 372                if {[file isfile $objdir]} {
 373                        return [win32_read_lnk $objdir]
 374                }
 375        }
 376
 377        return {}
 378}
 379
 380######################################################################
 381##
 382## Create New Repository
 383
 384method _do_new {} {
 385        global use_ttk NS
 386        $w_next conf \
 387                -state disabled \
 388                -command [cb _do_new2] \
 389                -text [mc "Create"]
 390
 391        ${NS}::frame $w_body
 392        ${NS}::label $w_body.h \
 393                -font font_uibold -anchor center \
 394                -text [mc "Create New Repository"]
 395        pack $w_body.h -side top -fill x -pady 10
 396        pack $w_body -fill x -padx 10
 397
 398        ${NS}::frame $w_body.where
 399        ${NS}::label $w_body.where.l -text [mc "Directory:"]
 400        ${NS}::entry $w_body.where.t \
 401                -textvariable @local_path \
 402                -width 50
 403        ${NS}::button $w_body.where.b \
 404                -text [mc "Browse"] \
 405                -command [cb _new_local_path]
 406        set w_localpath $w_body.where.t
 407
 408        grid $w_body.where.l $w_body.where.t $w_body.where.b -sticky ew
 409        pack $w_body.where -fill x
 410
 411        grid columnconfigure $w_body.where 1 -weight 1
 412
 413        trace add variable @local_path write [cb _write_local_path]
 414        bind $w_body.h <Destroy> [list trace remove variable @local_path write [cb _write_local_path]]
 415        update
 416        focus $w_body.where.t
 417}
 418
 419method _new_local_path {} {
 420        if {$local_path ne {}} {
 421                set p [file dirname $local_path]
 422        } else {
 423                set p [_home]
 424        }
 425
 426        set p [tk_chooseDirectory \
 427                -initialdir $p \
 428                -parent $top \
 429                -title [mc "Git Repository"] \
 430                -mustexist false]
 431        if {$p eq {}} return
 432
 433        set p [file normalize $p]
 434        if {![_new_ok $p]} {
 435                return
 436        }
 437        set local_path $p
 438        $w_localpath icursor end
 439}
 440
 441method _do_new2 {} {
 442        if {![_new_ok $local_path]} {
 443                return
 444        }
 445        if {![_git_init $this]} {
 446                return
 447        }
 448        set done 1
 449}
 450
 451proc _new_ok {p} {
 452        if {[file isdirectory $p]} {
 453                if {[_is_git [file join $p .git]]} {
 454                        error_popup [mc "Directory %s already exists." $p]
 455                        return 0
 456                }
 457        } elseif {[file exists $p]} {
 458                error_popup [mc "File %s already exists." $p]
 459                return 0
 460        }
 461        return 1
 462}
 463
 464######################################################################
 465##
 466## Clone Existing Repository
 467
 468method _do_clone {} {
 469        global use_ttk NS
 470        $w_next conf \
 471                -state disabled \
 472                -command [cb _do_clone2] \
 473                -text [mc "Clone"]
 474
 475        ${NS}::frame $w_body
 476        ${NS}::label $w_body.h \
 477                -font font_uibold -anchor center \
 478                -text [mc "Clone Existing Repository"]
 479        pack $w_body.h -side top -fill x -pady 10
 480        pack $w_body -fill x -padx 10
 481
 482        set args $w_body.args
 483        ${NS}::frame $w_body.args
 484        pack $args -fill both
 485
 486        ${NS}::label $args.origin_l -text [mc "Source Location:"]
 487        ${NS}::entry $args.origin_t \
 488                -textvariable @origin_url \
 489                -width 50
 490        ${NS}::button $args.origin_b \
 491                -text [mc "Browse"] \
 492                -command [cb _open_origin]
 493        grid $args.origin_l $args.origin_t $args.origin_b -sticky ew
 494
 495        ${NS}::label $args.where_l -text [mc "Target Directory:"]
 496        ${NS}::entry $args.where_t \
 497                -textvariable @local_path \
 498                -width 50
 499        ${NS}::button $args.where_b \
 500                -text [mc "Browse"] \
 501                -command [cb _new_local_path]
 502        grid $args.where_l $args.where_t $args.where_b -sticky ew
 503        set w_localpath $args.where_t
 504
 505        ${NS}::label $args.type_l -text [mc "Clone Type:"]
 506        ${NS}::frame $args.type_f
 507        set w_types [list]
 508        lappend w_types [${NS}::radiobutton $args.type_f.hardlink \
 509                -state disabled \
 510                -text [mc "Standard (Fast, Semi-Redundant, Hardlinks)"] \
 511                -variable @clone_type \
 512                -value hardlink]
 513        lappend w_types [${NS}::radiobutton $args.type_f.full \
 514                -state disabled \
 515                -text [mc "Full Copy (Slower, Redundant Backup)"] \
 516                -variable @clone_type \
 517                -value full]
 518        lappend w_types [${NS}::radiobutton $args.type_f.shared \
 519                -state disabled \
 520                -text [mc "Shared (Fastest, Not Recommended, No Backup)"] \
 521                -variable @clone_type \
 522                -value shared]
 523        foreach r $w_types {
 524                pack $r -anchor w
 525        }
 526        grid $args.type_l $args.type_f -sticky new
 527
 528        grid columnconfigure $args 1 -weight 1
 529
 530        trace add variable @local_path write [cb _update_clone]
 531        trace add variable @origin_url write [cb _update_clone]
 532        bind $w_body.h <Destroy> "
 533                [list trace remove variable @local_path write [cb _update_clone]]
 534                [list trace remove variable @origin_url write [cb _update_clone]]
 535        "
 536        update
 537        focus $args.origin_t
 538}
 539
 540method _open_origin {} {
 541        if {$origin_url ne {} && [file isdirectory $origin_url]} {
 542                set p $origin_url
 543        } else {
 544                set p [_home]
 545        }
 546
 547        set p [tk_chooseDirectory \
 548                -initialdir $p \
 549                -parent $top \
 550                -title [mc "Git Repository"] \
 551                -mustexist true]
 552        if {$p eq {}} return
 553
 554        set p [file normalize $p]
 555        if {![_is_git [file join $p .git]] && ![_is_git $p]} {
 556                error_popup [mc "Not a Git repository: %s" [file tail $p]]
 557                return
 558        }
 559        set origin_url $p
 560}
 561
 562method _update_clone {args} {
 563        if {$local_path ne {} && $origin_url ne {}} {
 564                $w_next conf -state normal
 565        } else {
 566                $w_next conf -state disabled
 567        }
 568
 569        if {$origin_url ne {} &&
 570                (  [_is_git [file join $origin_url .git]]
 571                || [_is_git $origin_url])} {
 572                set e normal
 573                if {[[lindex $w_types 0] cget -state] eq {disabled}} {
 574                        set clone_type hardlink
 575                }
 576        } else {
 577                set e disabled
 578                set clone_type full
 579        }
 580
 581        foreach r $w_types {
 582                $r conf -state $e
 583        }
 584}
 585
 586method _do_clone2 {} {
 587        if {[file isdirectory $origin_url]} {
 588                set origin_url [file normalize $origin_url]
 589        }
 590
 591        if {$clone_type eq {hardlink} && ![file isdirectory $origin_url]} {
 592                error_popup [mc "Standard only available for local repository."]
 593                return
 594        }
 595        if {$clone_type eq {shared} && ![file isdirectory $origin_url]} {
 596                error_popup [mc "Shared only available for local repository."]
 597                return
 598        }
 599
 600        if {$clone_type eq {hardlink} || $clone_type eq {shared}} {
 601                set objdir [_objdir $origin_url]
 602                if {$objdir eq {}} {
 603                        error_popup [mc "Not a Git repository: %s" [file tail $origin_url]]
 604                        return
 605                }
 606        }
 607
 608        set giturl $origin_url
 609        if {[is_Cygwin] && [file isdirectory $giturl]} {
 610                set giturl [exec cygpath --unix --absolute $giturl]
 611                if {$clone_type eq {shared}} {
 612                        set objdir [exec cygpath --unix --absolute $objdir]
 613                }
 614        }
 615
 616        if {[file exists $local_path]} {
 617                error_popup [mc "Location %s already exists." $local_path]
 618                return
 619        }
 620
 621        if {![_git_init $this]} return
 622        set local_path [pwd]
 623
 624        if {[catch {
 625                        git config remote.$origin_name.url $giturl
 626                        git config remote.$origin_name.fetch +refs/heads/*:refs/remotes/$origin_name/*
 627                } err]} {
 628                error_popup [strcat [mc "Failed to configure origin"] "\n\n$err"]
 629                return
 630        }
 631
 632        destroy $w_body $w_next
 633
 634        switch -exact -- $clone_type {
 635        hardlink {
 636                set o_cons [status_bar::two_line $w_body]
 637                pack $w_body -fill x -padx 10 -pady 10
 638
 639                $o_cons start \
 640                        [mc "Counting objects"] \
 641                        [mc "buckets"]
 642                update
 643
 644                if {[file exists [file join $objdir info alternates]]} {
 645                        set pwd [pwd]
 646                        if {[catch {
 647                                file mkdir [gitdir objects info]
 648                                set f_in [open [file join $objdir info alternates] r]
 649                                set f_cp [open [gitdir objects info alternates] w]
 650                                fconfigure $f_in -translation binary -encoding binary
 651                                fconfigure $f_cp -translation binary -encoding binary
 652                                cd $objdir
 653                                while {[gets $f_in line] >= 0} {
 654                                        if {[is_Cygwin]} {
 655                                                puts $f_cp [exec cygpath --unix --absolute $line]
 656                                        } else {
 657                                                puts $f_cp [file normalize $line]
 658                                        }
 659                                }
 660                                close $f_in
 661                                close $f_cp
 662                                cd $pwd
 663                        } err]} {
 664                                catch {cd $pwd}
 665                                _clone_failed $this [mc "Unable to copy objects/info/alternates: %s" $err]
 666                                return
 667                        }
 668                }
 669
 670                set tolink  [list]
 671                set buckets [glob \
 672                        -tails \
 673                        -nocomplain \
 674                        -directory [file join $objdir] ??]
 675                set bcnt [expr {[llength $buckets] + 2}]
 676                set bcur 1
 677                $o_cons update $bcur $bcnt
 678                update
 679
 680                file mkdir [file join .git objects pack]
 681                foreach i [glob -tails -nocomplain \
 682                        -directory [file join $objdir pack] *] {
 683                        lappend tolink [file join pack $i]
 684                }
 685                $o_cons update [incr bcur] $bcnt
 686                update
 687
 688                foreach i $buckets {
 689                        file mkdir [file join .git objects $i]
 690                        foreach j [glob -tails -nocomplain \
 691                                -directory [file join $objdir $i] *] {
 692                                lappend tolink [file join $i $j]
 693                        }
 694                        $o_cons update [incr bcur] $bcnt
 695                        update
 696                }
 697                $o_cons stop
 698
 699                if {$tolink eq {}} {
 700                        info_popup [strcat \
 701                                [mc "Nothing to clone from %s." $origin_url] \
 702                                "\n" \
 703                                [mc "The 'master' branch has not been initialized."] \
 704                                ]
 705                        destroy $w_body
 706                        set done 1
 707                        return
 708                }
 709
 710                set i [lindex $tolink 0]
 711                if {[catch {
 712                                file link -hard \
 713                                        [file join .git objects $i] \
 714                                        [file join $objdir $i]
 715                        } err]} {
 716                        info_popup [mc "Hardlinks are unavailable.  Falling back to copying."]
 717                        set i [_copy_files $this $objdir $tolink]
 718                } else {
 719                        set i [_link_files $this $objdir [lrange $tolink 1 end]]
 720                }
 721                if {!$i} return
 722
 723                destroy $w_body
 724        }
 725        full {
 726                set o_cons [console::embed \
 727                        $w_body \
 728                        [mc "Cloning from %s" $origin_url]]
 729                pack $w_body -fill both -expand 1 -padx 10
 730                $o_cons exec \
 731                        [list git fetch --no-tags -k $origin_name] \
 732                        [cb _do_clone_tags]
 733        }
 734        shared {
 735                set fd [open [gitdir objects info alternates] w]
 736                fconfigure $fd -translation binary
 737                puts $fd $objdir
 738                close $fd
 739        }
 740        }
 741
 742        if {$clone_type eq {hardlink} || $clone_type eq {shared}} {
 743                if {![_clone_refs $this]} return
 744                set pwd [pwd]
 745                if {[catch {
 746                                cd $origin_url
 747                                set HEAD [git rev-parse --verify HEAD^0]
 748                        } err]} {
 749                        _clone_failed $this [mc "Not a Git repository: %s" [file tail $origin_url]]
 750                        return 0
 751                }
 752                cd $pwd
 753                _do_clone_checkout $this $HEAD
 754        }
 755}
 756
 757method _copy_files {objdir tocopy} {
 758        $o_cons start \
 759                [mc "Copying objects"] \
 760                [mc "KiB"]
 761        set tot 0
 762        set cmp 0
 763        foreach p $tocopy {
 764                incr tot [file size [file join $objdir $p]]
 765        }
 766        foreach p $tocopy {
 767                if {[catch {
 768                                set f_in [open [file join $objdir $p] r]
 769                                set f_cp [open [file join .git objects $p] w]
 770                                fconfigure $f_in -translation binary -encoding binary
 771                                fconfigure $f_cp -translation binary -encoding binary
 772
 773                                while {![eof $f_in]} {
 774                                        incr cmp [fcopy $f_in $f_cp -size 16384]
 775                                        $o_cons update \
 776                                                [expr {$cmp / 1024}] \
 777                                                [expr {$tot / 1024}]
 778                                        update
 779                                }
 780
 781                                close $f_in
 782                                close $f_cp
 783                        } err]} {
 784                        _clone_failed $this [mc "Unable to copy object: %s" $err]
 785                        return 0
 786                }
 787        }
 788        return 1
 789}
 790
 791method _link_files {objdir tolink} {
 792        set total [llength $tolink]
 793        $o_cons start \
 794                [mc "Linking objects"] \
 795                [mc "objects"]
 796        for {set i 0} {$i < $total} {} {
 797                set p [lindex $tolink $i]
 798                if {[catch {
 799                                file link -hard \
 800                                        [file join .git objects $p] \
 801                                        [file join $objdir $p]
 802                        } err]} {
 803                        _clone_failed $this [mc "Unable to hardlink object: %s" $err]
 804                        return 0
 805                }
 806
 807                incr i
 808                if {$i % 5 == 0} {
 809                        $o_cons update $i $total
 810                        update
 811                }
 812        }
 813        return 1
 814}
 815
 816method _clone_refs {} {
 817        set pwd [pwd]
 818        if {[catch {cd $origin_url} err]} {
 819                error_popup [mc "Not a Git repository: %s" [file tail $origin_url]]
 820                return 0
 821        }
 822        set fd_in [git_read for-each-ref \
 823                --tcl \
 824                {--format=list %(refname) %(objectname) %(*objectname)}]
 825        cd $pwd
 826
 827        set fd [open [gitdir packed-refs] w]
 828        fconfigure $fd -translation binary
 829        puts $fd "# pack-refs with: peeled"
 830        while {[gets $fd_in line] >= 0} {
 831                set line [eval $line]
 832                set refn [lindex $line 0]
 833                set robj [lindex $line 1]
 834                set tobj [lindex $line 2]
 835
 836                if {[regsub ^refs/heads/ $refn \
 837                        "refs/remotes/$origin_name/" refn]} {
 838                        puts $fd "$robj $refn"
 839                } elseif {[string match refs/tags/* $refn]} {
 840                        puts $fd "$robj $refn"
 841                        if {$tobj ne {}} {
 842                                puts $fd "^$tobj"
 843                        }
 844                }
 845        }
 846        close $fd_in
 847        close $fd
 848        return 1
 849}
 850
 851method _do_clone_tags {ok} {
 852        if {$ok} {
 853                $o_cons exec \
 854                        [list git fetch --tags -k $origin_name] \
 855                        [cb _do_clone_HEAD]
 856        } else {
 857                $o_cons done $ok
 858                _clone_failed $this [mc "Cannot fetch branches and objects.  See console output for details."]
 859        }
 860}
 861
 862method _do_clone_HEAD {ok} {
 863        if {$ok} {
 864                $o_cons exec \
 865                        [list git fetch $origin_name HEAD] \
 866                        [cb _do_clone_full_end]
 867        } else {
 868                $o_cons done $ok
 869                _clone_failed $this [mc "Cannot fetch tags.  See console output for details."]
 870        }
 871}
 872
 873method _do_clone_full_end {ok} {
 874        $o_cons done $ok
 875
 876        if {$ok} {
 877                destroy $w_body
 878
 879                set HEAD {}
 880                if {[file exists [gitdir FETCH_HEAD]]} {
 881                        set fd [open [gitdir FETCH_HEAD] r]
 882                        while {[gets $fd line] >= 0} {
 883                                if {[regexp "^(.{40})\t\t" $line line HEAD]} {
 884                                        break
 885                                }
 886                        }
 887                        close $fd
 888                }
 889
 890                catch {git pack-refs}
 891                _do_clone_checkout $this $HEAD
 892        } else {
 893                _clone_failed $this [mc "Cannot determine HEAD.  See console output for details."]
 894        }
 895}
 896
 897method _clone_failed {{why {}}} {
 898        if {[catch {file delete -force $local_path} err]} {
 899                set why [strcat \
 900                        $why \
 901                        "\n\n" \
 902                        [mc "Unable to cleanup %s" $local_path] \
 903                        "\n\n" \
 904                        $err]
 905        }
 906        if {$why ne {}} {
 907                update
 908                error_popup [strcat [mc "Clone failed."] "\n" $why]
 909        }
 910}
 911
 912method _do_clone_checkout {HEAD} {
 913        if {$HEAD eq {}} {
 914                info_popup [strcat \
 915                        [mc "No default branch obtained."] \
 916                        "\n" \
 917                        [mc "The 'master' branch has not been initialized."] \
 918                        ]
 919                set done 1
 920                return
 921        }
 922        if {[catch {
 923                        git update-ref HEAD $HEAD^0
 924                } err]} {
 925                info_popup [strcat \
 926                        [mc "Cannot resolve %s as a commit." $HEAD^0] \
 927                        "\n  $err" \
 928                        "\n" \
 929                        [mc "The 'master' branch has not been initialized."] \
 930                        ]
 931                set done 1
 932                return
 933        }
 934
 935        set o_cons [status_bar::two_line $w_body]
 936        pack $w_body -fill x -padx 10 -pady 10
 937        $o_cons start \
 938                [mc "Creating working directory"] \
 939                [mc "files"]
 940
 941        set readtree_err {}
 942        set fd [git_read --stderr read-tree \
 943                -m \
 944                -u \
 945                -v \
 946                HEAD \
 947                HEAD \
 948                ]
 949        fconfigure $fd -blocking 0 -translation binary
 950        fileevent $fd readable [cb _readtree_wait $fd]
 951}
 952
 953method _readtree_wait {fd} {
 954        set buf [read $fd]
 955        $o_cons update_meter $buf
 956        append readtree_err $buf
 957
 958        fconfigure $fd -blocking 1
 959        if {![eof $fd]} {
 960                fconfigure $fd -blocking 0
 961                return
 962        }
 963
 964        if {[catch {close $fd}]} {
 965                set err $readtree_err
 966                regsub {^fatal: } $err {} err
 967                error_popup [strcat \
 968                        [mc "Initial file checkout failed."] \
 969                        "\n\n$err"]
 970                return
 971        }
 972
 973        # -- Run the post-checkout hook.
 974        #
 975        set fd_ph [githook_read post-checkout [string repeat 0 40] \
 976                [git rev-parse HEAD] 1]
 977        if {$fd_ph ne {}} {
 978                global pch_error
 979                set pch_error {}
 980                fconfigure $fd_ph -blocking 0 -translation binary -eofchar {}
 981                fileevent $fd_ph readable [cb _postcheckout_wait $fd_ph]
 982        } else {
 983                set done 1
 984        }
 985}
 986
 987method _postcheckout_wait {fd_ph} {
 988        global pch_error
 989
 990        append pch_error [read $fd_ph]
 991        fconfigure $fd_ph -blocking 1
 992        if {[eof $fd_ph]} {
 993                if {[catch {close $fd_ph}]} {
 994                        hook_failed_popup post-checkout $pch_error 0
 995                }
 996                unset pch_error
 997                set done 1
 998                return
 999        }
1000        fconfigure $fd_ph -blocking 0
1001}
1002
1003######################################################################
1004##
1005## Open Existing Repository
1006
1007method _do_open {} {
1008        global NS
1009        $w_next conf \
1010                -state disabled \
1011                -command [cb _do_open2] \
1012                -text [mc "Open"]
1013
1014        ${NS}::frame $w_body
1015        ${NS}::label $w_body.h \
1016                -font font_uibold -anchor center \
1017                -text [mc "Open Existing Repository"]
1018        pack $w_body.h -side top -fill x -pady 10
1019        pack $w_body -fill x -padx 10
1020
1021        ${NS}::frame $w_body.where
1022        ${NS}::label $w_body.where.l -text [mc "Repository:"]
1023        ${NS}::entry $w_body.where.t \
1024                -textvariable @local_path \
1025                -width 50
1026        ${NS}::button $w_body.where.b \
1027                -text [mc "Browse"] \
1028                -command [cb _open_local_path]
1029
1030        grid $w_body.where.l $w_body.where.t $w_body.where.b -sticky ew
1031        pack $w_body.where -fill x
1032
1033        grid columnconfigure $w_body.where 1 -weight 1
1034
1035        trace add variable @local_path write [cb _write_local_path]
1036        bind $w_body.h <Destroy> [list trace remove variable @local_path write [cb _write_local_path]]
1037        update
1038        focus $w_body.where.t
1039}
1040
1041method _open_local_path {} {
1042        if {$local_path ne {}} {
1043                set p $local_path
1044        } else {
1045                set p [_home]
1046        }
1047
1048        set p [tk_chooseDirectory \
1049                -initialdir $p \
1050                -parent $top \
1051                -title [mc "Git Repository"] \
1052                -mustexist true]
1053        if {$p eq {}} return
1054
1055        set p [file normalize $p]
1056        if {![_is_git [file join $p .git]]} {
1057                error_popup [mc "Not a Git repository: %s" [file tail $p]]
1058                return
1059        }
1060        set local_path $p
1061}
1062
1063method _do_open2 {} {
1064        if {![_is_git [file join $local_path .git]]} {
1065                error_popup [mc "Not a Git repository: %s" [file tail $local_path]]
1066                return
1067        }
1068
1069        if {[catch {cd $local_path} err]} {
1070                error_popup [strcat \
1071                        [mc "Failed to open repository %s:" $local_path] \
1072                        "\n\n$err"]
1073                return
1074        }
1075
1076        _append_recentrepos [pwd]
1077        set ::_gitdir .git
1078        set ::_prefix {}
1079        set done 1
1080}
1081
1082}