manage_gitrepo.in 25.4 KB
Newer Older
1 2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2000-2018 University of Utah and the Flux Group.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
#
use English;
use strict;
use Getopt::Std;
use XML::Simple;
use Data::Dumper;
use CGI;
use POSIX ":sys_wait_h";
use Date::Parse;
use File::Basename;

#
# Back-end script to manage GIT Repos
#
sub usage()
{
    print("Usage: manage_gitrepo check url\n");
    exit(-1);
}
my $optlist     = "dt:";
my $debug       = 0;
my $webtask_id;
my $webtask;

#
# Configure variables
#
my $TB		= "@prefix@";
my $TBOPS       = "@TBOPSEMAIL@";
my $OURDOMAIN	= "@OURDOMAIN@";
my $CONTROL     = "@USERNODE@";
54
my $TBADMINGROUP= "@TBADMINGROUP@";
55
my $MAINSITE    = @TBMAINSITE@;
56
my $REPODIR     = "/repos";
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
my $PROXY       = "$TB/libexec/gitrepo.proxy";
my $SSH	        = "$TB/bin/sshtb";
my $GIT         = "/usr/local/bin/git";

#
# Untaint the path
#
$ENV{'PATH'} = "$TB/bin:$TB/sbin:/bin:/usr/bin:/usr/bin:/usr/sbin";
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

#
# Turn off line buffering on output
#
$| = 1;

if ($EUID != 0) {
    # We don't want to run this script unless its the real version.
    die("Must be root! Maybe its a development version?");
}

# This script is setuid, so please do not run it as root. Hard to track
# what has happened.
if ($UID == 0) {
    die("Please do not run this as root! Its already setuid!");
}

#
# Load the Testbed support stuff.
#
use lib "@prefix@/lib";
use emdb;
use emutil;
use User;
use Project;
use EmulabConstants;
use libEmulab;
use libtestbed;
use WebTask;
use APT_Profile;
96
use Blockstore;
97 98 99 100 101 102 103 104 105 106 107 108 109

# Protos
sub fatal($);
sub DoCheckRemote();
sub DoClone();
sub DoUpdate();
sub DoLog();
sub DoHash();
sub DoBranchList();
sub DoTagList();
sub DoCommitList();
sub DoCommitInfo();
sub DoGetSource();
110
sub DoGetRepoSize();
111
sub GetRepoSource($;$);
112
sub GetRepoSize($);
113 114 115 116 117
sub GetBranchList($);
sub GetTagList($);
sub GetCommitList($$);
sub GetCommitField($$$);
sub GetRepoName($);
118
sub GetDefaultBranch($);
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
sub RemoveRepo($);

# Locals
my $SAVEUID  = $UID;

#
# Parse command arguments. Once we return from getopts, all that should be
# left are the required arguments.
#
my %options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (defined($options{"t"})) {
    $webtask_id = $options{"t"};
    $webtask = WebTask->Lookup($webtask_id);
    if (!defined($webtask)) {
	fatal("Could not lookup webtask $webtask_id");
    }
    # Convenient.
    $webtask->AutoStore(1);
}
if (defined($options{"d"})) {
    $debug++;
}
if (@ARGV < 1) {
    usage();
}
my $action = shift(@ARGV);

# For credentials.
my $this_user = User->ThisUser();
if (! defined($this_user)) {
    fatal("You ($UID) do not exist!");
}
154 155 156 157 158 159 160
# We have to add the admin group so we can get into the repositories
my $unix_gid = getgrnam($TBADMINGROUP);
if (!defined($unix_gid)) {
    fatal("No such group $TBADMINGROUP");
}
$GID  = $unix_gid;
$EGID = "$unix_gid $unix_gid";
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
# Run as the user for most of this script.
$EUID = $UID;

if ($action eq "check") {
    DoCheckRemote();
}
elsif ($action eq "clone") {
    DoClone();
}
elsif ($action eq "update") {
    DoUpdate();
}
elsif ($action eq "getsource") {
    DoGetSource();
}
elsif ($action eq "log") {
    DoLog();
}
elsif ($action eq "hash") {
    DoHash();
}
elsif ($action eq "branchlist") {
    DoBranchList();
}
elsif ($action eq "taglist") {
    DoTagList();
}
elsif ($action eq "commitlist") {
    DoCommitList();
}
elsif ($action eq "commitinfo") {
    DoCommitInfo();
}
194 195 196
elsif ($action eq "reposize") {
    DoGetRepoSize();
}
197 198 199 200 201 202
else {
    usage();
}
exit(0);

#
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
# Run with retry, lets see if this helps with the transient NFS/ZFS
# problems. The commands we run through here should generally not fail.
# The only time I see errors is due to transient access problems, which
# is kinda strange.
#
sub runCommandRetry($)
{
    my ($cmd) = @_;

    if ($debug) {
	print STDERR $debug;
    }
    my $output;
    my $count = 3;
    while ($count) {
	$output = emutil::ExecQuiet($cmd);
	last
	    if ($? == 0);

	print STDERR "Failed: '$cmd'\n";
	
224
	system("/usr/bin/fsync $REPODIR");
225 226 227 228 229 230 231 232 233
	$count--;
	sleep(1)
	    if ($count);
    }
    return $output;
}

#
# Check to see if we can access a remote URL.
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
#
sub DoCheckRemote()
{
    usage()
	if (@ARGV != 1);
    
    my $repourl = shift(@ARGV);
    # Taint check.
    if ($repourl =~ /^(.*)$/) {
	$repourl = $1;
    }
    #
    # We can do this here, we are just making sure it can be accessed.
    #
    $ENV{"GIT_ASKPASS"} = "true";
    my $output =
	emutil::ExecQuiet("$GIT ls-remote --exit-code '$repourl' HEAD");
    if ($?) {
252
	UserError($output)
253 254 255 256 257 258 259 260 261 262 263 264
    }
    if (defined($webtask)) {
	$webtask->output("");
	$webtask->code(0);
    }
    exit(0);
}

#
# Clone a repo. This is done on the control node.
# Use -o to write the file to stdout or a file.
# Use -r to remove repo after getting the script/rspec.
265
# Add -u to update if repo is already cloned.
266 267 268
#
sub DoClone()
{
269
    my $optlist = "o:rn:u";
270 271 272
    my $ofile;
    my $remove;
    my $reponame;
273
    my $update;
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292

    my %options = ();
    if (! getopts($optlist, \%options)) {
	usage();
    }
    usage()
	if (@ARGV != 1);
    
    my $repourl = shift(@ARGV);
    # Taint check.
    if ($repourl =~ /^(.*)$/) {
	$repourl = $1;
    }
    if (defined($options{"o"})) {
	$ofile = $options{"o"};
    }
    if (defined($options{"r"})) {
	$remove = 1;
    }
293 294 295 296 297 298
    if (defined($options{"u"})) {
	$update = 1;
	if (!defined($options{"n"})) {
	    fatal("Must provide reponame (-n) with -u option");
	}
    }
299 300 301 302 303 304 305 306 307 308
    if (defined($options{"n"})) {
	$reponame = $options{"n"};
	# Taint check.
	if ($reponame =~ /^(.*)$/) {
	    $reponame = $1;
	}
    }
    else {
	$reponame = NewUUID();
    }
309 310 311 312 313 314 315
    my $cmd = "$SSH -host $CONTROL $PROXY ";
    if ($update && -e "$REPODIR/$reponame") {
	$cmd .= "-n $reponame update";
    }
    else {
	$cmd .= "-n $reponame clone '$repourl'";
    }
316 317 318 319 320 321 322 323 324 325 326 327 328 329
    if ($debug) {
	print "'$cmd'\n";
    }

    $EUID = $UID = 0;
    my $output = emutil::ExecQuiet($cmd);
    $EUID = $UID = $SAVEUID;
    if ($?) {
	print STDERR $output;
	fatal("Could not clone repository")
    }
    if ($debug) {
	print $output;
    }
330 331 332 333 334 335 336 337 338

    #
    # Basic size check. 
    #
    my $size = GetRepoSize($reponame);
    if (!defined($size)) {
	RemoveRepo($reponame);
	fatal("Could not estimate repository size");
    }
339
    if ($size > 500) {
340
	RemoveRepo($reponame);
341
	UserError("Repository is too big: greate then 500MiB");
342 343
    }

344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
    #
    # Now get the geni-lib script or rspec, write it to the file or stdout.
    #
    my $source = GetRepoSource($reponame);
    if (!defined($source)) {
	RemoveRepo($reponame);
	UserError("Could not find profile.py or profile.rspec in repository");
    }
    
    #
    # If we have a web task, lets get some more stuff for it.
    #
    if (defined($webtask)) {
	my $log  = GetCommitField($reponame, undef, "%B");
	my $hash = GetCommitField($reponame, undef, "%H");
	$webtask->log($log);
	$webtask->hash($hash);
361
	$webtask->size("$size MiB");
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
    }
    if (defined($ofile)) {
	if ($ofile eq "-") {
	    print $source;
	}
	else {
	    # Silly taint check.
	    if ($ofile =~ /^(.*)$/) {
		$ofile = $1;
	    }
	    if (open(OF, ">> $ofile")) {
		print OF $source;
		close(OF);
	    }
	    else {
		RemoveRepo($reponame);
		fatal("Could not write source to $ofile");
	    }
	}
    }
    #
    # Use -r option to get the script/rspec, but remove repo afterwards.
    # Used by the web interface.
    #
    if ($remove) {
	RemoveRepo($reponame);
    }
    elsif (!defined($ofile)) {
	print "Cloned $repourl to $reponame\n";
    }
    if (defined($webtask)) {
	$webtask->Exited(0);
    }
    exit(0);
}

#
# Update a repo. This is done on the control node.
# Use -o to write the file to stdout or a file.
#
sub DoUpdate()
{
    my $optlist = "o:n:p:";
    my $ofile;
    my $reponame;
407
    my $repourl;
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438

    my %options = ();
    if (! getopts($optlist, \%options)) {
	usage();
    }
    usage()
	if (@ARGV);

    if (defined($options{"o"})) {
	$ofile = $options{"o"};
    }    

    #
    # We get a reponame or a profile, from which we get the reponame
    #
    if (defined($options{"n"})) {
	$reponame = $options{"n"};
	# Taint check.
	if ($reponame =~ /^(.*)$/) {
	    $reponame = $1;
	}
    }
    elsif (defined($options{"p"})) {
	my $profile = APT_Profile->Lookup($options{"p"});
	if (!defined($profile)) {
	    fatal("No such profile");
	}
	if (!defined($profile->reponame())) {
	    fatal("No such repository associated with profile");
	}
	$reponame = $profile->reponame();
439
	$repourl  = $profile->repourl();
440 441 442 443 444
    }
    else {
	usage();
    }

445 446 447 448 449 450 451 452 453 454 455 456
    #
    # Make sure still accessible.
    #
    if (defined($repourl)) {
	$ENV{"GIT_ASKPASS"} = "true";
	my $output =
	    emutil::ExecQuiet("$GIT ls-remote --exit-code '$repourl' HEAD");
	if ($?) {
	    UserError($output)
	}
    }
    
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
    my $cmd = "$SSH -host $CONTROL $PROXY -n $reponame update";
    if ($debug) {
	print "'$cmd'\n";
    }

    $EUID = $UID = 0;
    my $output = emutil::ExecQuiet($cmd);
    $EUID = $UID = $SAVEUID;
    if ($?) {
	print STDERR $output;
	fatal("Could not update repository")
    }
    if ($debug) {
	print $output;
    }
472 473 474 475 476 477 478 479

    #
    # Basic size check. 
    #
    my $size = GetRepoSize($reponame);
    if (!defined($size)) {
	fatal("Could not estimate repository size");
    }
480 481
    if ($size > 500) {
	UserError("Repository is too big: greater then 500MiB");
482 483
    }
    
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
    #
    # Now get the geni-lib script or rspec write it to the file or stdout.
    #
    my $source = GetRepoSource($reponame);
    if (!defined($source)) {
	UserError("Could not find profile.py or profile.rspec in repository");
    }

    #
    # If we have a web task, lets get some more stuff for it.
    #
    if (defined($webtask)) {
	my $log  = GetCommitField($reponame, undef, "%B");
	my $hash = GetCommitField($reponame, undef, "%H");
	chomp($hash);
	$webtask->log($log);
	$webtask->hash($hash);
501
	$webtask->size("$size MiB");
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
    }
    
    if (defined($ofile)) {
	if ($ofile eq "-") {
	    print $source;
	}
	else {
	    # Silly taint check.
	    if ($ofile =~ /^(.*)$/) {
		$ofile = $1;
	    }
	    if (open(OF, ">> $ofile")) {
		print OF $source;
		close(OF);
	    }
	    else {
		fatal("Could not write source to $ofile");
	    }
	}
    }
    if (defined($webtask)) {
	$webtask->Exited(0);
    }
    exit(0);
}

#
# Get the profile source for a specific branch or tag.
#
sub DoGetSource()
{
    my $optlist = "n:p:o:";
    my $reponame;
    my $ofile;
536
    my $which;
537 538 539 540 541 542 543 544 545 546

    my %options = ();
    if (! getopts($optlist, \%options)) {
	usage();
    }
    if (defined($options{"o"})) {
	$ofile = $options{"o"};	
    }
    $which = shift(@ARGV) if (@ARGV);
    $reponame = GetRepoName(\%options);
547
    $which = GetDefaultBranch($reponame) if (!defined($which));
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592

    # Silly taint check.
    if ($which =~ /^(.*)$/) {
	$which = $1;
    }
    my $source = GetRepoSource($reponame, $which);
    if (!defined($source)) {
	UserError("Could not find profile.py or profile.rspec in repository");
    }
    
    if (defined($ofile)) {
	# Silly taint check.
	if ($ofile =~ /^(.*)$/) {
	    $ofile = $1;
	}
	if (open(OF, ">> $ofile")) {
	    print OF $source;
	    close(OF);
	}
	else {
	    fatal("Could not write source to $ofile");
	}
    }
    else {
	print $source;
    }
    
    if (defined($webtask)) {
	my $hash = GetCommitField($reponame, $which, "%H");
	chomp($hash);
	$webtask->hash($hash);
	$webtask->Exited(0);
    }
    exit(0);
}

#
# Grab a file from the bare repo.
#
sub GetRepoSource($;$)
{
    my ($reponame, $refspec) = @_;
    my $repodir = "$REPODIR/$reponame";
    my $source;

593
    $refspec = GetDefaultBranch($reponame)
594 595
	if (!defined($refspec));

596 597 598 599 600
    # Lets see if this helps. We know there is a source file, but
    # we sometimes get failures cause of NFS/ZFS.
    system("/usr/bin/fsync $repodir");
    sleep(1);

601
    chdir("$repodir") or
602
	fatal("Could not chdir to $repodir: $!");
603

604 605
    if (system("$GIT cat-file -e ".
	       "$refspec:profile.py >/dev/null 2>&1") == 0) {
606 607
	$source = "profile.py";
    }
608 609
    elsif (system("$GIT cat-file -e ".
		  "  $refspec:profile.rspec >/dev/null 2>&1") == 0) {
610 611 612
	$source = "profile.rspec";
    }
    else {
613 614 615 616 617
	print STDERR "$repodir, $refspec\n";
	print STDERR `/usr/bin/id`;
	print STDERR `/bin/ls -la`;
	print STDERR "Could not find source code in repository: $reponame\n";
	
618 619
	return undef;
    }
620 621 622 623 624
    #
    # Do this seemingly odd cat-file, simply cause its the only way
    # --follow-symlinks works. It adds the commit hash as the first
    # line of output, so see below where that first line is killed.
    #
625
    my $stuff =
626 627
      emutil::ExecQuiet("echo '$refspec:$source' | ".
			"  $GIT cat-file --batch --follow-symlinks");
628 629 630 631
    if ($?) {
	print STDERR $stuff;
	return undef;
    }
632 633
    # Kill first line.
    $stuff =~ s/^(?:.*\n){1}//;
634 635 636 637 638 639 640 641 642
    return $stuff;
}

#
# Get commit log for a branch or tag and write it to stdout.
#
sub DoLog()
{
    my $optlist = "n:p:";
643
    my $which;
644 645 646 647 648 649 650

    my %options = ();
    if (! getopts($optlist, \%options)) {
	usage();
    }
    $which = shift(@ARGV) if (@ARGV);
    my $reponame = GetRepoName(\%options);
651
    $which = GetDefaultBranch($reponame) if (!defined($which));
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667

    my $log = GetCommitField($reponame, $which, "%B");
    print $log;
    if (defined($webtask)) {
	$webtask->log($log);
	$webtask->Exited(0);
    }
    exit(0);
}

#
# Get commit hash for branch or tag and send to stdout
#
sub DoHash()
{
    my $optlist = "n:p:";
668
    my $which;
669 670 671 672 673 674 675

    my %options = ();
    if (! getopts($optlist, \%options)) {
	usage();
    }
    $which = shift(@ARGV) if (@ARGV);
    my $reponame = GetRepoName(\%options);
676
    $which = GetDefaultBranch($reponame) if (!defined($which));
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693

    my $hash = GetCommitField($reponame, $which, "%H");
    chomp($hash);
    if (defined($webtask)) {
	$webtask->hash($hash);
	$webtask->Exited(0);
    }
    print "$hash\n";
    exit(0);
}

#
# Internal routine to get something from a commit.
#
sub GetCommitField($$$)
{
    my ($reponame, $refspec, $field) = @_;
694
    $refspec = GetDefaultBranch($reponame)
695 696 697 698 699 700 701 702 703 704 705 706 707 708
	if (!defined($refspec));

    # Silly taint check
    if ($refspec =~ /^(.*)$/) {
	$refspec = $1;
    }

    if (! -e "$REPODIR/$reponame") {
	fatal("Repository does not exist.");
    }
    chdir("$REPODIR/$reponame") or
	fatal("Could not chdir to $REPODIR/$reponame");

    my $cmd = "$GIT log -n 1 --pretty=tformat:$field $refspec";
709
    my $output = runCommandRetry($cmd);
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
    if ($?) {
	print STDERR $output;
	fatal("Could not get $field from repository")
    }
    return $output;
}

#
# Internal routine to remove repo.
#
sub RemoveRepo($)
{
    my ($reponame) = @_;
    my $cmd = "$SSH -host $CONTROL $PROXY -n $reponame delete";
    
    $EUID = $UID = 0;
    my $output = emutil::ExecQuiet($cmd);
    $EUID = $UID = $SAVEUID;
    if ($?) {
	print STDERR $output;
	return -1;
    }
    return 0;
}

#
# Return a branch list.
#
sub DoBranchList()
{
    my $optlist = "n:p:";
    my $reponame;

    my %options = ();
    if (! getopts($optlist, \%options)) {
	usage();
    }
    usage()
	if (@ARGV);
    $reponame = GetRepoName(\%options);

    my $branches = GetBranchList($reponame);
    if (defined($webtask)) {
	$webtask->branchlist($branches);
	$webtask->taglist(GetTagList($reponame));
	$webtask->Exited(0);
    }
    else {
	print Dumper($branches);
    }
    exit(0);
}

sub GetBranchList($)
{
    my ($reponame) = @_;

    if (! -e "$REPODIR/$reponame") {
	fatal("Repository does not exist.");
    }
770 771 772
    # We will mark the default branch.
    my $default_branch = GetDefaultBranch($reponame);

773 774 775 776
    chdir("$REPODIR/$reponame") or
	fatal("Could not chdir to $REPODIR/$reponame");

    #
777 778 779
    # First we need a list of branches and their hash. But notice that
    # multiple branches can point to the same hash, so we have to record
    # the list for the second step below.
780
    #
781
    my $output = runCommandRetry("$GIT show-ref --abbrev --heads");
782 783 784 785 786 787 788 789 790 791 792
    if ($?) {
	print STDERR $output;
	fatal("Could not get branch list from repository")
    }
    my $branches = [];
    my %branches = ();
    
    foreach my $line (split(/\n/, $output)) {
	if ($line =~ /^(\w+)\s+(.*)$/) {
	    my $name = basename($2);
	    
793 794 795 796 797
	    my $blob = {"hash"    => $1,
			"name"    => $name,
			"ref"     => $2,
			"default" => ($2 eq $default_branch ? 1 : 0),   
	    };
798
	    # This is the list we return.
799
	    push(@{ $branches }, $blob);
800 801 802 803 804 805

	    # See comment above, its a many to one relationship.
	    if (!exists($branches{$1})) {
		$branches{$1} = [];
	    }
	    push(@{ $branches{$1} }, $blob);
806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
	}
    }
    #
    # So, now we need to get the commit messages, which is harder.
    #
    open(GIT, "$GIT log '--pretty=format:%h %B %n\@FF\@' ".
	 "   --branches --simplify-by-decoration |") or
	 fatal("Could not get branch list from repository");

    while (<GIT>) {
	my $hash;
	my $comment;
	
	if ($_ =~ /^(\w+)\s+(.*)$/) {
	    my $hash = $1;
	    my $log  = $2;
	    # Scan forward till the terminator.
	    while (<GIT>) {
		last
		    if ($_ =~ /^\@FF\@$/);
		$log .= $_;
	    }
828 829 830 831 832
	    if (exists($branches{$hash})) {
		foreach my $blob (@{ $branches{$hash} }) {
		    $blob->{"log"} = $log;
		}
	    }
833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
	}
    }
    close(GIT);
    return $branches;
}

#
# Return a tag list.
#
sub DoTagList()
{
    my $optlist = "n:p:";
    my $reponame;

    my %options = ();
    if (! getopts($optlist, \%options)) {
	usage();
    }
    usage()
	if (@ARGV);
    $reponame = GetRepoName(\%options);

    my $taglist = GetTagList($reponame);
    if (defined($webtask)) {
	$webtask->taglist($taglist);
	$webtask->Exited(0);
    }
    else {
	print Dumper($taglist);
    }
    exit(0);
}

sub GetTagList($)
{
    my ($reponame) = @_;

    if (! -e "$REPODIR/$reponame") {
	fatal("Repository does not exist.");
    }
    chdir("$REPODIR/$reponame") or
	fatal("Could not chdir to $REPODIR/$reponame");

876
    # See if any tags to list.
877
    my $taglist = runCommandRetry("$GIT tag --list");
878 879 880 881 882 883 884 885
    if ($?) {
	print STDERR $taglist;
	fatal("Could not check for tag list from repository");
    }
    if ($taglist =~/^$/) {
	return [];
    }

886 887 888 889 890
    #
    # First we need a list of tags and their hash. Note dereference option
    # here; we need to dereference annotated tags. This complicates the
    # output though. 
    #
891
    my $output = runCommandRetry("$GIT show-ref --abbrev -d --tags");
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991
    if ($?) {
	print STDERR $output;
	fatal("Could not get tag list from repository")
    }
    my $tags = [];
    my %tags = ();
    my %byref= ();
    
    foreach my $line (split(/\n/, $output)) {
	if ($line =~ /^(\w+)\s+([^^]*)((\^\{\}))?$/) {
	    if (defined($3)) {
		# Need to delete the first one.
		delete($byref{$2});
	    }
	    $byref{$2} = $1;
	}
    }
    foreach my $line (split(/\n/, $output)) {
	if ($line =~ /^(\w+)\s+([^^]*)((\^\{\}))?$/) {
	    my $name = basename($2);
	    next
		if ($byref{$2} ne $1);

	    my $blob = {"hash"  => $1,
			"name"  => $name,
			"ref"   => $2};
	    push(@{ $tags }, $blob);
	    $tags{$1} = $blob;
	}
    }
    #
    # So, now we need to get the commit messages, which is harder.
    #
    open(GIT, "$GIT log '--pretty=format:%h %B %n\@FF\@' ".
	 "   --tags --simplify-by-decoration |") or
	 fatal("Could not get branch list from repository");

    while (<GIT>) {
	my $hash;
	my $comment;
	
	if ($_ =~ /^(\w+)\s+(.*)$/) {
	    my $hash = $1;
	    my $log  = $2;
	    # Scan forward till the terminator.
	    while (<GIT>) {
		last
		    if ($_ =~ /^\@FF\@$/);
		$log .= $_;
	    }
	    $tags{$hash}->{"log"} = $log
		if (exists($tags{$hash}));
	}
    }
    close(GIT);
    return $tags;
}

#
# Return commit list, perhaps on a specific branch
#
sub DoCommitList()
{
    my $optlist = "n:p:";
    my $reponame;
    my $branch;

    my %options = ();
    if (! getopts($optlist, \%options)) {
	usage();
    }
    $reponame = GetRepoName(\%options);
    if (@ARGV) {
	$branch = shift(@ARGV);
	# Silly taint check.
	if ($branch =~ /^(.*)$/) {
	    $branch = $1;
	}
    }
    my $commits = GetCommitList($reponame, $branch);
    if (defined($webtask)) {
	$webtask->commitlist($commits);
	$webtask->Exited(0);
    }
    exit(0);    
}

sub GetCommitList($$)
{
    my ($reponame, $branch) = @_;
    
    if (! -e "$REPODIR/$reponame") {
	fatal("Repository does not exist.");
    }
    chdir("$REPODIR/$reponame") or
	fatal("Could not chdir to $REPODIR/$reponame");

    my $cmd = "$GIT log '--format=%h%x1f%an%x1f%ad%x1f%s%x1e' ";
    $cmd .= $branch if (defined($branch));
    
992
    my $output = runCommandRetry($cmd);
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
    if ($?) {
	print STDERR $output;
	fatal("Could not get branch list from repository")
    }
    my $commits = [];
    
    foreach my $line (split(/\x1e\n/, $output)) {
	my ($hash,$author,$when,$log) = split(/\x1f/, $line);
	next if (!defined($log));

	push(@{ $commits }, {"hash"   => $hash,
			     "author" => $author,
			     "when"   => $when,
			     "log"    => $log});
	print "$hash,$author,$when,$log\n";
    }
    return $commits;
}

#
# Return commit info,
#
sub DoCommitInfo()
{
    my $optlist = "n:p:";
    my $which;

    my %options = ();
    if (! getopts($optlist, \%options)) {
	usage();
    }
    my $reponame = GetRepoName(\%options);
    if (@ARGV) {
	$which = shift(@ARGV);
	# Silly taint check.
	if ($which =~ /^(.*)$/) {
	    $which = $1;
	}
    }
1032 1033 1034
    else {
	$which = GetDefaultBranch($reponame);
    }
1035 1036 1037 1038 1039 1040 1041 1042 1043
    if (! -e "$REPODIR/$reponame") {
	fatal("Repository does not exist.");
    }
    chdir("$REPODIR/$reponame") or
	fatal("Could not chdir to $REPODIR/$reponame");

    my $cmd = "$GIT log -n 1 '--format=%h%x1f%an%x1f%ad%x1f%s%x1e'";
    $cmd .= " $which" if (defined($which));
    
1044
    my $output = runCommandRetry($cmd);
1045 1046 1047 1048 1049 1050
    if ($?) {
	print STDERR $output;
	fatal("Could not get branch list from repository")
    }
    chomp($output);
    my ($hash,$author,$when,$log) = split(/\x1f/, $output);
1051 1052 1053 1054
    my $size = GetRepoSize($reponame);
    if (!defined($size)) {
	$size = "???";
    }
1055 1056 1057 1058 1059
    my $blob = {"hash"      => $hash,
		"author"    => $author,
		"when"      => $when,
		"log"       => $log,
		"reponame"  => $reponame,
1060
		"refspec"   => $which,
1061
		"size"      => "$size MiB"};
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107

    if (defined($webtask)) {
	$webtask->commitinfo($blob);
	$webtask->Exited(0);
    }
    else {
	print Dumper($blob);
    }
    exit(0);    
}

#
# Dig the reponame out of the options list.
#
sub GetRepoName($)
{
    my ($options) = @_;
    my %options   = %{ $options };
    my $reponame;
    
    #
    # We get a reponame or a profile, from which we get the reponame
    #
    if (defined($options{"n"})) {
	$reponame = $options{"n"};
	# Taint check.
	if ($reponame =~ /^(.*)$/) {
	    $reponame = $1;
	}
    }
    elsif (defined($options{"p"})) {
	my $profile = APT_Profile->Lookup($options{"p"});
	if (!defined($profile)) {
	    fatal("No such profile");
	}
	if (!defined($profile->reponame())) {
	    fatal("No such repository associated with profile");
	}
	$reponame = $profile->reponame();
    }
    else {
	usage();
    }
    return $reponame;
}

1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
#
# Estimated Repo size.
#
sub DoGetRepoSize()
{
    my $optlist = "n:p:";
    my $which;

    my %options = ();
    if (! getopts($optlist, \%options)) {
	usage();
    }
    my $reponame = GetRepoName(\%options);
    if (@ARGV) {
	$which = shift(@ARGV);
	# Silly taint check.
	if ($which =~ /^(.*)$/) {
	    $which = $1;
	}
    }
    if (! -e "$REPODIR/$reponame") {
	fatal("Repository does not exist.");
    }
    my $size = GetRepoSize($reponame);
    if (!defined($size)) {
	fatal("Could not determine Repository size");
    }
    if (defined($webtask)) {
	$webtask->reposize("$size Mib");
	$webtask->Exited(0);
    }
    else {
	print "$size Mib\n";
    }
    exit(0);    
}

#
# Get estimated repository size.
#
sub GetRepoSize($)
{
    my ($reponame) = @_;
    
    chdir("$REPODIR/$reponame") or
	fatal("Could not chdir to $REPODIR/$reponame");

    my $gitsize = `$GIT count-objects -v -H | grep size-pack`;
    if ($?) {
	return undef;
    }
    if ($gitsize !~ /^size-pack:\s+([\w\.]+)\s+(\w+)$/) {
	print STDERR "Could not parse object size: '$gitsize'\n";
	return undef;
    }
    my $size = int($1);
    my $unit = $2;
    if ($unit eq "bytes") {
	$unit = "B";
    }
    my $mebi = Blockstore::ConvertToMebi("${size}${unit}");
    if ($mebi < 0) {
	print STDERR "Could not convert size to MiB: ".
	    "${size}${unit}, '$gitsize'\n";
	return undef;
    }
    # Zero is silly.
    $mebi = 1
	if ($mebi == 0);
    return $mebi;
}

1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
#
# Get estimated repository size.
#
sub GetDefaultBranch($)
{
    my ($reponame) = @_;
    
    chdir("$REPODIR/$reponame") or
	fatal("Could not chdir to $REPODIR/$reponame");

    my $branch = `$GIT symbolic-ref --short HEAD`;
    if ($?) {
	fatal("Could not get default branch for $reponame");
    }
    chomp($branch);

    if ($branch =~ /^([-\w]+)$/) {
	$branch = $1;
    }
    else {
	fatal("Illegal default branch name: $branch");
    }
    return "refs/heads/$branch";
}

1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
sub fatal($)
{
    my ($mesg) = @_;

    if (defined($webtask)) {
	$webtask->output($mesg);
	$webtask->Exited(-1);
    }
    print STDERR "*** $0:\n".
	         "    $mesg\n";
    # Exit with negative status so web interface treats it as system error.
    exit(-1);
}

sub UserError($)
{
    my ($mesg) = @_;

    if (defined($webtask)) {
	$webtask->output($mesg);
	$webtask->Exited(1);
    }
    print STDERR "*** $0:\n".
	         "    $mesg\n";
    exit(1);
}