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