chiark / gitweb /
Fix comparison of archive's .dsc's hash and git branch head to DTRT.
[dgit.git] / dgit
1 #!/usr/bin/perl -w
2 # dgit
3 # Integration between git and Debian-style archives
4 #
5 # Copyright (C)2013 Ian Jackson
6 #
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
20 use strict;
21
22 use IO::Handle;
23 use Data::Dumper;
24 use LWP::UserAgent;
25 use Dpkg::Control::Hash;
26 use File::Path;
27 use Dpkg::Version;
28 use POSIX;
29
30 our $isuite = 'unstable';
31 our $idistro;
32 our $package;
33
34 our $sign = 1;
35 our $dryrun = 0;
36 our $changesfile;
37 our $new_package = 0;
38 our $existing_package = 'dpkg';
39
40 our %format_ok = map { $_=>1 } ("1.0","3.0 (native)","3.0 (quilt)");
41
42 our (@git) = qw(git);
43 our (@dget) = qw(dget);
44 our (@dput) = qw(dput);
45 our (@debsign) = qw(debsign);
46 our (@sbuild) = qw(sbuild -A);
47 our (@dpkgbuildpackage) = qw(dpkg-buildpackage -i\.git/ -I.git);
48 our (@mergechanges) = qw(mergechanges -f);
49
50
51 our %opts_opt_map = ('dget' => \@dget,
52                      'dput' => \@dput,
53                      'debsign' => \@debsign,
54                      'sbuild' => \@sbuild,
55                      'dpkg-buildpackage' => \@dpkgbuildpackage,
56                      'mergechanges' => \@mergechanges);
57
58 our $keyid;
59
60 our $debug = 0;
61 open DEBUG, ">/dev/null" or die $!;
62
63 our $remotename = 'dgit';
64 our $ourdscfield = 'Vcs-Dgit-Master';
65 our $branchprefix = 'dgit';
66 our $csuite;
67
68 sub lbranch () { return "$branchprefix/$csuite"; }
69 my $lbranch_re = '^refs/heads/'.$branchprefix.'/([^/.]+)$';
70 sub lref () { return "refs/heads/".lbranch(); }
71 sub lrref () { return "refs/remotes/$remotename/$branchprefix/$csuite"; }
72 sub rrref () { return "refs/$branchprefix/$csuite"; }
73 sub debiantag ($) { 
74     my ($v) = @_;
75     $v =~ y/~:/_%/;
76     return "debian/$v";
77 }
78
79 sub dscfn ($) { return "${package}_$_[0].dsc"; }
80
81 our $us = 'dgit';
82
83 sub fail { die "$us: @_\n"; }
84
85 sub badcfg { print STDERR "$us: invalid configuration: @_\n"; exit 12; }
86
87 sub no_such_package () {
88     print STDERR "$us: package $package does not exist in suite $isuite\n";
89     exit 4;
90 }
91
92 sub fetchspec () {
93     local $csuite = '*';
94     return  "+".rrref().":".lrref();
95 }
96
97 our $ua;
98
99 sub url_get {
100     if (!$ua) {
101         $ua = LWP::UserAgent->new();
102         $ua->env_proxy;
103     }
104     my $what = $_[$#_];
105     print "downloading $what...\n";
106     my $r = $ua->get(@_) or die $!;
107     return undef if $r->code == 404;
108     $r->is_success or fail "failed to fetch $what: ".$r->status_line;
109     return $r->decoded_content();
110 }
111
112 our ($dscdata,$dscurl,$dsc);
113
114 sub printcmd {
115     my $fh = shift @_;
116     my $intro = shift @_;
117     print $fh $intro or die $!;
118     local $_;
119     foreach my $a (@_) {
120         $_ = $a;
121         if (s{['\\]}{\\$&}g || m{\s} || m{[^-_./0-9a-z]}i) {
122             print $fh " '$_'" or die $!;
123         } else {
124             print $fh " $_" or die $!;
125         }
126     }
127     print $fh "\n" or die $!;
128 }
129
130 sub failedcmd {
131     { local ($!); printcmd \*STDERR, "$_[0]: failed command:", @_ or die $!; };
132     if ($!) {
133         fail "failed to fork/exec: $!";
134     } elsif (!($? & 0xff)) {
135         fail "subprocess failed with error exit status ".($?>>8);
136     } elsif ($?) {
137         fail "subprocess crashed (wait status $?)";
138     } else {
139         fail "subprocess produced invalid output";
140     }
141 }
142
143 sub runcmd {
144     printcmd(\*DEBUG,"+",@_) if $debug>0;
145     $!=0; $?=0;
146     failedcmd @_ if system @_;
147 }
148
149 sub printdone {
150     if (!$dryrun) {
151         print "dgit ok: @_\n";
152     } else {
153         print "would be ok: @_ (but dry run only)\n";
154     }
155 }
156
157 sub cmdoutput_errok {
158     die Dumper(\@_)." ?" if grep { !defined } @_;
159     printcmd(\*DEBUG,"|",@_) if $debug>0;
160     open P, "-|", @_ or die $!;
161     my $d;
162     $!=0; $?=0;
163     { local $/ = undef; $d = <P>; }
164     die $! if P->error;
165     if (!close P) { print DEBUG "=>!$?\n" if $debug>0; return undef; }
166     chomp $d;
167     $d =~ m/^.*/;
168     print DEBUG "=> \`$&'",(length $' ? '...' : ''),"\n" if $debug>0; #';
169     return $d;
170 }
171
172 sub cmdoutput {
173     my $d = cmdoutput_errok @_;
174     defined $d or failedcmd @_;
175     return $d;
176 }
177
178 sub dryrun_report {
179     printcmd(\*STDOUT,"#",@_);
180 }
181
182 sub runcmd_ordryrun {
183     if (!$dryrun) {
184         runcmd @_;
185     } else {
186         dryrun_report @_;
187     }
188 }
189
190 our $helpmsg = <<END;
191 main usages:
192   dgit [dgit-opts] clone [dgit-opts] package [suite] [./dir|/dir]
193   dgit [dgit-opts] fetch|pull [dgit-opts] [suite]
194   dgit [dgit-opts] build [git-buildpackage-opts|dpkg-buildpackage-opts]
195   dgit [dgit-opts] push [dgit-opts] [suite]
196 important dgit options:
197   -k<keyid>           sign tag and package with <keyid> instead of default
198   --dry-run -n        do not change anything, but go through the motions
199   --new -N            allow introducing a new package
200   --debug -D          increase debug level
201   -c<name>=<value>    set git config option (used directly by dgit too)
202 END
203
204 our $later_warning_msg = <<END;
205 Perhaps the upload is stuck in incoming.  Using the version from git.
206 END
207
208 sub badusage {
209     print STDERR "$us: @_\n", $helpmsg or die $!;
210     exit 8;
211 }
212
213 sub helponly () {
214     print $helpmsg or die $!;
215     exit 0;
216 }
217
218 our %defcfg = ('dgit.default.distro' => 'debian',
219                'dgit.default.username' => '',
220                'dgit.default.archive-query-default-component' => 'main',
221                'dgit.default.ssh' => 'ssh',
222                'dgit-distro.debian.git-host' => 'git.debian.org',
223                'dgit-distro.debian.git-proto' => 'git+ssh://',
224                'dgit-distro.debian.git-path' => '/git/dgit-repos',
225                'dgit-distro.debian.git-check' => 'ssh-cmd',
226                'dgit-distro.debian.git-create' => 'ssh-cmd',
227                'dgit-distro.debian.sshdakls-host' => 'coccia.debian.org',
228                'dgit-distro.debian.sshdakls-dir' =>
229                    '/srv/ftp-master.debian.org/ftp/dists',
230                'dgit-distro.debian.mirror' => 'http://http.debian.net/debian/');
231
232 sub cfg {
233     foreach my $c (@_) {
234         return undef if $c =~ /RETURN-UNDEF/;
235         my @cmd = (@git, qw(config --), $c);
236         my $v;
237         {
238             local ($debug) = $debug-1;
239             $v = cmdoutput_errok @cmd;
240         };
241         if ($?==0) {
242             return $v;
243         } elsif ($?!=256) {
244             failedcmd @cmd;
245         }
246         my $dv = $defcfg{$c};
247         return $dv if defined $dv;
248     }
249     badcfg "need value for one of: @_";
250 }
251
252 sub access_distro () {
253     return cfg("dgit-suite.$isuite.distro",
254                "dgit.default.distro");
255 }
256
257 sub access_cfg (@) {
258     my (@keys) = @_;
259     my $distro = $idistro || access_distro();
260     my $value = cfg(map { ("dgit-distro.$distro.$_",
261                            "dgit.default.$_") } @keys);
262     return $value;
263 }
264
265 sub access_someuserhost ($) {
266     my ($some) = @_;
267     my $user = access_cfg("$some-user",'username');
268     my $host = access_cfg("$some-host");
269     return length($user) ? "$user\@$host" : $host;
270 }
271
272 sub access_gituserhost () {
273     return access_someuserhost('git');
274 }
275
276 sub access_giturl () {
277     my $url = access_cfg('git-url','RETURN-UNDEF');
278     if (!defined $url) {
279         $url =
280             access_cfg('git-proto').
281             access_gituserhost().
282             access_cfg('git-path');
283     }
284     return "$url/$package.git";
285 }              
286
287 sub parsecontrolfh ($$@) {
288     my ($fh, $desc, @opts) = @_;
289     my %opts = ('name' => $desc, @opts);
290     my $c = Dpkg::Control::Hash->new(%opts);
291     $c->parse($fh) or die "parsing of $desc failed";
292     return $c;
293 }
294
295 sub parsecontrol {
296     my ($file, $desc) = @_;
297     my $fh = new IO::Handle;
298     open $fh, '<', $file or die "$file: $!";
299     my $c = parsecontrolfh($fh,$desc);
300     $fh->error and die $!;
301     close $fh;
302     return $c;
303 }
304
305 sub getfield ($$) {
306     my ($dctrl,$field) = @_;
307     my $v = $dctrl->{$field};
308     return $v if defined $v;
309     fail "missing field $field in ".$v->get_option('name');
310 }
311
312 sub parsechangelog {
313     my $c = Dpkg::Control::Hash->new();
314     my $p = new IO::Handle;
315     my @cmd = (qw(dpkg-parsechangelog));
316     open $p, '-|', @cmd or die $!;
317     $c->parse($p);
318     $?=0; $!=0; close $p or failedcmd @cmd;
319     return $c;
320 }
321
322 our %rmad;
323
324 sub archive_query ($) {
325     my ($method) = @_;
326     my $query = access_cfg('archive-query','RETURN-UNDEF');
327     if (!defined $query) {
328         my $distro = access_distro();
329         if ($distro eq 'debian') {
330             $query = "sshdakls:".
331                 access_someuserhost('sshdakls').':'.
332                 access_cfg('sshdakls-dir');
333         } else {
334             $query = "madison:$distro";
335         }
336     }
337     $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
338     my $proto = $1;
339     my $data = $'; #';
340     { no strict qw(refs); &{"${method}_${proto}"}($proto,$data); }
341 }
342
343 sub archive_query_madison ($$) {
344     my ($proto,$data) = @_;
345     die unless $proto eq 'madison';
346     $rmad{$package} ||= cmdoutput
347         qw(rmadison -asource),"-s$isuite","-u$data",$package;
348     my $rmad = $rmad{$package};
349     return madison_parse($rmad);
350 }
351
352 sub archive_query_sshdakls ($$) {
353     my ($proto,$data) = @_;
354     $data =~ s/:.*// or badcfg "invalid sshdakls method string \`$data'";
355     my $dakls = cmdoutput
356         access_cfg('ssh'), $data, qw(dak ls -asource),"-s$isuite",$package;
357     return madison_parse($dakls);
358 }
359
360 sub canonicalise_suite_sshdakls ($$) {
361     my ($proto,$data) = @_;
362     $data =~ m/:/ or badcfg "invalid sshdakls method string \`$data'";
363     my @cmd =
364         (access_cfg('ssh'), $`,
365          "set -e; cd $';".
366          " if test -h $isuite; then readlink $isuite; exit 0; fi;".
367          " if test -d $isuite; then echo $isuite; exit 0; fi;".
368          " exit 1");
369     my $dakls = cmdoutput @cmd;
370     failedcmd @cmd unless $dakls =~ m/^\w/;
371     return $dakls;
372 }
373
374 sub madison_parse ($) {
375     my ($rmad) = @_;
376     my @out;
377     foreach my $l (split /\n/, $rmad) {
378         $l =~ m{^ \s*( [^ \t|]+ )\s* \|
379                   \s*( [^ \t|]+ )\s* \|
380                   \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
381                   \s*( [^ \t|]+ )\s* }x or die "$rmad $?";
382         $1 eq $package or die "$rmad $package ?";
383         my $vsn = $2;
384         my $newsuite = $3;
385         my $component;
386         if (defined $4) {
387             $component = $4;
388         } else {
389             $component = access_cfg('archive-query-default-component');
390         }
391         $5 eq 'source' or die "$rmad ?";
392         my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
393         my $subpath = "/pool/$component/$prefix/$package/${package}_$vsn.dsc";
394         push @out, [$vsn,$subpath,$newsuite];
395     }
396     return sort { -version_compare_string($a->[0],$b->[0]); } @out;
397 }
398
399 sub canonicalise_suite_madison ($$) {
400     my @r = archive_query_madison($_[0],$_[1]);
401     @r or fail
402         "unable to canonicalise suite using package $package".
403         " which does not appear to exist in suite $isuite;".
404         " --existing-package may help";
405     return $r[0][2];
406 }
407
408 sub canonicalise_suite () {
409     $csuite = archive_query('canonicalise_suite');
410     if ($isuite ne $csuite) {
411         # madison canonicalises for us
412         print "canonical suite name for $isuite is $csuite\n";
413     }
414 }
415
416 sub get_archive_dsc () {
417     canonicalise_suite();
418     my @vsns = archive_query('archive_query');
419     foreach my $vinfo (@vsns) {
420         my ($vsn,$subpath) = @$vinfo;
421         $dscurl = access_cfg('mirror').$subpath;
422         $dscdata = url_get($dscurl);
423         next unless defined $dscdata;
424         $dscurl = access_cfg('mirror').$subpath;
425         $dscdata = url_get($dscurl);
426         my $dscfh = new IO::File \$dscdata, '<' or die $!;
427         print DEBUG Dumper($dscdata) if $debug>1;
428         $dsc = parsecontrolfh($dscfh,$dscurl, allow_pgp=>1);
429         print DEBUG Dumper($dsc) if $debug>1;
430         my $fmt = getfield $dsc, 'Format';
431         fail "unsupported source format $fmt, sorry" unless $format_ok{$fmt};
432         return $dsc;
433     }
434     return undef;
435 }
436
437 sub check_for_git () {
438     # returns 0 or 1
439     my $how = access_cfg('git-check');
440     if ($how eq 'ssh-cmd') {
441         my @cmd =
442             (access_cfg('ssh'),access_gituserhost(),
443              " set -e; cd ".access_cfg('git-path').";".
444              " if test -d $package.git; then echo 1; else echo 0; fi");
445         my $r= cmdoutput @cmd;
446         failedcmd @cmd unless $r =~ m/^[01]$/;
447         return $r+0;
448     } else {
449         badcfg "unknown git-check \`$how'";
450     }
451 }
452
453 sub create_remote_git_repo () {
454     my $how = access_cfg('git-create');
455     if ($how eq 'ssh-cmd') {
456         runcmd_ordryrun
457             (access_cfg('ssh'),access_gituserhost(),
458              "set -e; cd ".access_cfg('git-path').";".
459              " cp -a _template $package.git");
460     } else {
461         badcfg "unknown git-create \`$how'";
462     }
463 }
464
465 our ($dsc_hash,$upload_hash);
466
467 our $ud = '.git/dgit/unpack';
468
469 sub prep_ud () {
470     rmtree($ud);
471     mkpath '.git/dgit';
472     mkdir $ud or die $!;
473 }
474
475 sub mktree_in_ud_from_only_subdir () {
476     # changes into the subdir
477     my (@dirs) = <*/.>;
478     die unless @dirs==1;
479     $dirs[0] =~ m#^([^/]+)/\.$# or die;
480     my $dir = $1;
481     chdir $dir or die "$dir $!";
482     die if stat '.git';
483     die $! unless $!==&ENOENT;
484     runcmd qw(git init -q);
485     rmtree('.git/objects');
486     symlink '../../../../objects','.git/objects' or die $!;
487     runcmd @git, qw(add -Af);
488     my $tree = cmdoutput @git, qw(write-tree);
489     $tree =~ m/^\w+$/ or die "$tree ?";
490     return ($tree,$dir);
491 }
492
493 sub dsc_files () {
494     my $field = $dsc->{'Checksums-Sha256'} || $dsc->{Files};
495     defined $field or
496         fail "missing both Checksums-Sha256 and Files in ".
497         $dsc->get_option('name');
498     map {
499         m/^\w+ \d+ (\S+)$/ or
500             fail "could not parse .dsc Files/Checksums line \`$_'";
501         $1;
502     } grep m/\S/, split /\n/, $field;
503 }
504
505 sub is_orig_file ($) {
506     local ($_) = @_;
507     m/\.orig(?:-\w+)?\.tar\.\w+$/;
508 }
509
510 sub make_commit ($) {
511     my ($file) = @_;
512     return cmdoutput @git, qw(hash-object -w -t commit), $file;
513 }
514
515 sub generate_commit_from_dsc () {
516     prep_ud();
517     chdir $ud or die $!;
518     my @files;
519     foreach my $f (dsc_files()) {
520         die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
521         push @files, $f;
522         link "../../../$f", $f
523             or $!==&ENOENT
524             or die "$f $!";
525     }
526     runcmd @dget, qw(--), $dscurl;
527     foreach my $f (grep { is_orig_file($_) } @files) {
528         link $f, "../../../../$f"
529             or $!==&EEXIST
530             or die "$f $!";
531     }
532     my ($tree,$dir) = mktree_in_ud_from_only_subdir();
533     runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
534     my $clogp = parsecontrol('../changelog.tmp',"commit's changelog");
535     my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
536     my $author = getfield $clogp, 'Maintainer';
537     $author =~ s#,.*##ms;
538     my $authline = "$author $date";
539     $authline =~ m/^[^<>]+ \<\S+\> \d+ [-+]\d+$/ or
540         fail "unexpected commit author line format \`$authline'".
541             " (was generated from changelog Maintainer field)";
542     my $changes = getfield $clogp, 'Changes';
543     open C, ">../commit.tmp" or die $!;
544     print C <<END or die $!;
545 tree $tree
546 author $authline
547 committer $authline
548
549 $changes
550
551 # imported from the archive
552 END
553     close C or die $!;
554     my $outputhash = make_commit qw(../commit.tmp);
555     my $cversion = getfield $clogp, 'Version';
556     print "synthesised git commit from .dsc $cversion\n";
557     if ($upload_hash) {
558         runcmd @git, qw(reset --hard), $upload_hash;
559         runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
560         my $oldclogp = parsecontrol('../changelogold.tmp','previous changelog');
561         my $oversion = getfield $oldclogp, 'Version';
562         my $vcmp =
563             version_compare_string($oversion, $cversion);
564         if ($vcmp < 0) {
565             # git upload/ is earlier vsn than archive, use archive
566             open C, ">../commit2.tmp" or die $!;
567             print C <<END or die $!;
568 tree $tree
569 parent $upload_hash
570 parent $outputhash
571 author $authline
572 committer $authline
573
574 Record $package ($cversion) in archive suite $csuite
575 END
576             $outputhash = make_commit qw(../commit2.tmp);
577         } elsif ($vcmp > 0) {
578             print STDERR <<END or die $!;
579
580 Version actually in archive:    $cversion (older)
581 Last allegedly pushed/uploaded: $oversion (newer or same)
582 $later_warning_msg
583 END
584             $outputhash = $upload_hash;
585         } elsif ($outputhash ne $upload_hash) {
586             fail "version in archive ($cversion)".
587                 " is same as version in git".
588                 " to-be-uploaded (upload/) branch ($oversion)".
589                 " but archive version hash no commit hash?!";
590         }
591     }
592     chdir '../../../..' or die $!;
593     runcmd @git, qw(update-ref -m),"dgit fetch import $cversion",
594             'DGIT_ARCHIVE', $outputhash;
595     cmdoutput @git, qw(log -n2), $outputhash;
596     # ... gives git a chance to complain if our commit is malformed
597     rmtree($ud);
598     return $outputhash;
599 }
600
601 sub ensure_we_have_orig () {
602     foreach my $f (dsc_files()) {
603         next unless is_orig_file($f);
604         if (stat "../$f") {
605             die "$f ?" unless -f _;
606         } else {
607             die "$f $!" unless $!==&ENOENT;
608         }
609         my $origurl = $dscurl;
610         $origurl =~ s{/[^/]+$}{};
611         $origurl .= "/$f";
612         die "$f ?" unless $f =~ m/^${package}_/;
613         die "$f ?" if $f =~ m#/#;
614         runcmd_ordryrun qw(sh -ec),'cd ..; exec "$@"','x',
615             @dget,'--',$origurl;
616     }
617 }
618
619 sub rev_parse ($) {
620     return cmdoutput @git, qw(rev-parse), "$_[0]~0";
621 }
622
623 sub is_fast_fwd ($$) {
624     my ($ancestor,$child) = @_;
625     my $mb = cmdoutput @git, qw(merge-base), $ancestor, $child;
626     return rev_parse($mb) eq rev_parse($ancestor);
627 }
628
629 sub git_fetch_us () {
630     badusage "cannot dry run with fetch" if $dryrun;
631     runcmd @git, qw(fetch),access_giturl(),fetchspec();
632 }
633
634 sub fetch_from_archive () {
635     # ensures that lrref() is what is actually in the archive,
636     #  one way or another
637     get_archive_dsc() or return 0;
638     $dsc_hash = $dsc->{$ourdscfield};
639     if (defined $dsc_hash) {
640         $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
641         $dsc_hash = $&;
642         print "last upload to archive specified git hash\n";
643     } else {
644         print "last upload to archive has NO git hash\n";
645     }
646
647     my $lrref_fn = ".git/".lrref();
648     if (open H, $lrref_fn) {
649         $upload_hash = <H>;
650         chomp $upload_hash;
651         die "$lrref_fn $upload_hash ?" unless $upload_hash =~ m/^\w+$/;
652     } elsif ($! == &ENOENT) {
653         $upload_hash = '';
654     } else {
655         die "$lrref_fn $!";
656     }
657     print DEBUG "previous reference hash=$upload_hash\n";
658     my $hash;
659     if (defined $dsc_hash) {
660         fail "missing git history even though dsc has hash -".
661             " could not find commit $dsc_hash".
662             " (should be in ".access_giturl()."#".rrref().")"
663             unless $upload_hash;
664         $hash = $dsc_hash;
665         ensure_we_have_orig();
666         if ($dsc_hash eq $upload_hash) {
667         } elsif (is_fast_fwd($dsc_hash,$upload_hash)) {
668             print STDERR <<END or die $!;
669
670 Git commit in archive is behind the last version allegedly pushed/uploaded.
671 Commit referred to by archive:  $dsc_hash
672 Last allegedly pushed/uploaded: $upload_hash
673 $later_warning_msg
674 END
675             $hash = $upload_hash;
676         } else {
677             fail "archive's .dsc refers to ".$dsc_hash.
678                 " but this is an ancestor of ".$upload_hash;
679         }
680     } else {
681         $hash = generate_commit_from_dsc();
682     }
683     print DEBUG "current hash=$hash\n";
684     if ($upload_hash) {
685         fail "not fast forward on last upload branch!".
686             " (archive's version left in DGIT_ARCHIVE)"
687             unless is_fast_fwd($upload_hash, $hash);
688     }
689     if ($upload_hash ne $hash) {
690         my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
691         if (!$dryrun) {
692             cmdoutput @upd_cmd;
693         } else {
694             dryrun_report @upd_cmd;
695         }
696     }
697     return 1;
698 }
699
700 sub clone ($) {
701     my ($dstdir) = @_;
702     canonicalise_suite();
703     badusage "dry run makes no sense with clone" if $dryrun;
704     mkdir $dstdir or die "$dstdir $!";
705     chdir "$dstdir" or die "$dstdir $!";
706     runcmd @git, qw(init -q);
707     runcmd @git, qw(config), "remote.$remotename.fetch", fetchspec();
708     open H, "> .git/HEAD" or die $!;
709     print H "ref: ".lref()."\n" or die $!;
710     close H or die $!;
711     runcmd @git, qw(remote add), 'origin', access_giturl();
712     if (check_for_git()) {
713         print "fetching existing git history\n";
714         git_fetch_us();
715         runcmd @git, qw(fetch origin);
716     } else {
717         print "starting new git history\n";
718     }
719     fetch_from_archive() or no_such_package;
720     runcmd @git, qw(reset --hard), lrref();
721     printdone "ready for work in $dstdir";
722 }
723
724 sub fetch () {
725     if (check_for_git()) {
726         git_fetch_us();
727     }
728     fetch_from_archive() or no_such_package();
729     printdone "fetched into ".lrref();
730 }
731
732 sub pull () {
733     fetch();
734     runcmd_ordryrun @git, qw(merge -m),"Merge from $csuite [dgit]",
735         lrref();
736     printdone "fetched to ".lrref()." and merged into HEAD";
737 }
738
739 sub check_not_dirty () {
740     my @cmd = (@git, qw(diff --quiet HEAD));
741     printcmd(\*DEBUG,"+",@cmd) if $debug>0;
742     $!=0; $?=0; system @cmd;
743     return if !$! && !$?;
744     if (!$! && $?==256) {
745         fail "working tree is dirty (does not match HEAD)";
746     } else {
747         failedcmd @cmd;
748     }
749 }
750
751 sub commit_quilty_patch ($) {
752     my ($vsn) = @_;
753     my $output = cmdoutput @git, qw(status --porcelain);
754     my %fixups = map {$_=>1}
755         (".pc/debian-changes-$vsn/","debian/patches/debian-changes-$vsn");
756     my @files;
757     foreach my $l (split /\n/, $output) {
758         next unless $l =~ s/^\?\? //;
759         next unless $fixups{$l};
760         push @files, $l;
761     }
762     print DEBUG "checking for quilty\n", Dumper(\@files);
763     if (@files == 2) {
764         my $m = "Commit Debian 3.0 (quilt) metadata";
765         print "$m\n";
766         runcmd_ordryrun @git, qw(add), @files;
767         runcmd_ordryrun @git, qw(commit -m), $m;
768     }
769 }
770
771 sub dopush () {
772     print DEBUG "actually entering push\n";
773     my $clogp = parsechangelog();
774     $package = getfield $clogp, 'Source';
775     my $cversion = getfield $clogp, 'Version';
776     my $dscfn = dscfn($cversion);
777     stat "../$dscfn" or
778         fail "looked for .dsc $dscfn, but $!;".
779             " maybe you forgot to build";
780     $dsc = parsecontrol("../$dscfn","$dscfn");
781     my $dscpackage = getfield $dsc, 'Source';
782     my $format = getfield $dsc, 'Format';
783     my $dversion = getfield $dsc, 'Version';
784     ($dscpackage eq $package && $dversion eq $cversion) or
785         fail "$dsc is for $dscpackage $dversion".
786             " but debian/changelog is for $package $cversion";
787     print DEBUG "format $format\n";
788     if ($format eq '3.0 (quilt)') {
789         print "Format \`$format', urgh\n";
790         commit_quilty_patch($dversion);
791     }
792     check_not_dirty();
793     prep_ud();
794     chdir $ud or die $!;
795     print "checking that $dscfn corresponds to HEAD\n";
796     runcmd qw(dpkg-source -x --), "../../../../$dscfn";
797     my ($tree,$dir) = mktree_in_ud_from_only_subdir();
798     chdir '../../../..' or die $!;
799     printcmd \*DEBUG,"+",@_;
800     my @diffcmd = (@git, qw(diff --exit-code), $tree);
801     $!=0; $?=0;
802     if (system @diffcmd) {
803         if ($! && $?==256) {
804             fail "$dscfn specifies a different tree to your HEAD commit;".
805                 " perhaps you forgot to build";
806         } else {
807             failedcmd @diffcmd;
808         }
809     }
810 #fetch from alioth
811 #do fast forward check and maybe fake merge
812 #    if (!is_fast_fwd(mainbranch
813 #    runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
814 #        map { lref($_).":".rref($_) }
815 #        (uploadbranch());
816     $dsc->{$ourdscfield} = rev_parse('HEAD');
817     $dsc->save("../$dscfn.tmp") or die $!;
818     if (!$changesfile) {
819         my $multi = "../${package}_${cversion}_multi.changes";
820         if (stat "$multi") {
821             $changesfile = $multi;
822         } else {
823             $!==&ENOENT or die "$multi: $!";
824             my $pat = "${package}_${cversion}_*.changes";
825             my @cs = glob "../$pat";
826             fail "failed to find unique changes file".
827                 " (looked for $pat in .., or $multi);".
828                 " perhaps you need to use dgit -C"
829                 unless @cs==1;
830             ($changesfile) = @cs;
831         }
832     }
833     my $tag = debiantag($dversion);
834     if (!check_for_git()) {
835         create_remote_git_repo();
836     }
837     runcmd_ordryrun @git, qw(push),access_giturl(),"HEAD:".rrref();
838     if (!$dryrun) {
839         rename "../$dscfn.tmp","../$dscfn" or die "$dscfn $!";
840     } else {
841         print "[new .dsc left in $dscfn.tmp]\n";
842     }
843     if ($sign) {
844         if (!defined $keyid) {
845             $keyid = access_cfg('keyid','RETURN-UNDEF');
846         }
847         my @tag_cmd = (@git, qw(tag -s -m),
848                        "Release $dversion for $csuite [dgit]");
849         push @tag_cmd, qw(-u),$keyid if defined $keyid;
850         push @tag_cmd, $tag;
851         runcmd_ordryrun @tag_cmd;
852         my @debsign_cmd = @debsign;
853         push @debsign_cmd, "-k$keyid" if defined $keyid;
854         push @debsign_cmd, $changesfile;
855         runcmd_ordryrun @debsign_cmd;
856     }
857     runcmd_ordryrun @git, qw(push),access_giturl(),"refs/tags/$tag";
858     my $host = access_cfg('upload-host','RETURN-UNDEF');
859     my @hostarg = defined($host) ? ($host,) : ();
860     runcmd_ordryrun @dput, @hostarg, $changesfile;
861     printdone "pushed and uploaded $dversion";
862 }
863
864 sub cmd_clone {
865     parseopts();
866     my $dstdir;
867     badusage "-p is not allowed with clone; specify as argument instead"
868         if defined $package;
869     if (@ARGV==1) {
870         ($package) = @ARGV;
871     } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
872         ($package,$isuite) = @ARGV;
873     } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
874         ($package,$dstdir) = @ARGV;
875     } elsif (@ARGV==3) {
876         ($package,$isuite,$dstdir) = @ARGV;
877     } else {
878         badusage "incorrect arguments to dgit clone";
879     }
880     $dstdir ||= "$package";
881     clone($dstdir);
882 }
883
884 sub branchsuite () {
885     my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
886     if ($branch =~ m#$lbranch_re#o) {
887         return $1;
888     } else {
889         return undef;
890     }
891 }
892
893 sub fetchpullargs () {
894     if (!defined $package) {
895         my $sourcep = parsecontrol('debian/control','debian/control');
896         $package = getfield $sourcep, 'Source';
897     }
898     if (@ARGV==0) {
899 #       $isuite = branchsuite();  # this doesn't work because dak hates canons
900         if (!$isuite) {
901             my $clogp = parsechangelog();
902             $isuite = getfield $clogp, 'Distribution';
903         }
904         canonicalise_suite();
905         print "fetching from suite $csuite\n";
906     } elsif (@ARGV==1) {
907         ($isuite) = @ARGV;
908         canonicalise_suite();
909     } else {
910         badusage "incorrect arguments to dgit fetch or dgit pull";
911     }
912 }
913
914 sub cmd_fetch {
915     parseopts();
916     fetchpullargs();
917     fetch();
918 }
919
920 sub cmd_pull {
921     parseopts();
922     fetchpullargs();
923     pull();
924 }
925
926 sub cmd_push {
927     parseopts();
928     badusage "-p is not allowed with dgit push" if defined $package;
929     runcmd @git, qw(diff --quiet HEAD);
930     my $clogp = parsechangelog();
931     $package = getfield $clogp, 'Source';
932     if (@ARGV==0) {
933         $isuite = getfield $clogp, 'Distribution';
934         if ($new_package) {
935             local ($package) = $existing_package; # this is a hack
936             canonicalise_suite();
937         }
938     } else {
939         badusage "incorrect arguments to dgit push";
940     }
941     if (fetch_from_archive()) {
942         is_fast_fwd(lrref(), 'HEAD') or die;
943     } else {
944         $new_package or
945             fail "package appears to be new in this suite;".
946                 " if this is intentional, use --new";
947     }
948     dopush();
949 }
950
951 sub cmd_build {
952     # we pass further options and args to git-buildpackage
953     badusage "-p is not allowed with dgit build" if defined $package;
954     my $clogp = parsechangelog();
955     $isuite = getfield $clogp, 'Distribution';
956     $package = getfield $clogp, 'Source';
957     my @cmd =
958         (qw(git-buildpackage -us -uc --git-no-sign-tags),
959          "--git-builder=@dpkgbuildpackage");
960     unless (grep { m/^--git-debian-branch/ } @ARGV) {
961         canonicalise_suite();
962         push @cmd, "--git-debian-branch=".lbranch();
963     }
964     runcmd_ordryrun @cmd, @ARGV;
965     printdone "build successful\n";
966 }
967
968 sub cmd_sbuild {
969     check_not_dirty();
970     badusage "-p is not allowed with dgit sbuild" if defined $package;
971     my $clogp = parsechangelog();
972     $package = getfield $clogp, 'Source';
973     my $isuite = getfield $clogp, 'Distribution';
974     my $version = getfield $clogp, 'Version';
975     runcmd_ordryrun (@dpkgbuildpackage, qw(-us -uc -S));
976     chdir ".." or die $!;
977     my $sourcechanges = "${package}_${version}_source.changes";
978     my $dscfn = dscfn($version);
979     my $pat = "${package}_${version}_*.changes";
980     if (!$dryrun) {
981         stat $dscfn or fail "$dscfn (in parent directory): $!";
982         stat $sourcechanges or fail "$sourcechanges (in parent directory): $!";
983         foreach my $cf (glob $pat) {
984             next if $cf eq $sourcechanges;
985             unlink $cf or fail "remove $cf: $!";
986         }
987     }
988     runcmd_ordryrun @sbuild, @ARGV, qw(-d), $isuite, $dscfn;
989     runcmd_ordryrun @mergechanges, glob $pat;
990     my $multichanges = "${package}_${version}_multi.changes";
991     if (!$dryrun) {
992         stat $multichanges or fail "$multichanges: $!";
993     }
994     printdone "build successful, results in $multichanges\n" or die $!;
995 }    
996
997 sub cmd_quilt_fixup {
998     badusage "incorrect arguments to dgit quilt-fixup";
999     my $clogp = parsechangelog();
1000     commit_quilty_patch((getfield $clogp, 'Version'));
1001 }
1002
1003 sub parseopts () {
1004     my $om;
1005     while (@ARGV) {
1006         last unless $ARGV[0] =~ m/^-/;
1007         $_ = shift @ARGV;
1008         last if m/^--?$/;
1009         if (m/^--/) {
1010             if (m/^--dry-run$/) {
1011                 $dryrun=1;
1012             } elsif (m/^--no-sign$/) {
1013                 $sign=0;
1014             } elsif (m/^--help$/) {
1015                 helponly();
1016             } elsif (m/^--new$/) {
1017                 $new_package=1;
1018             } elsif (m/^--(\w+)=(.*)/s && ($om = $opts_opt_map{$1})) {
1019                 $om->[0] = $2;
1020             } elsif (m/^--(\w+):(.*)/s && ($om = $opts_opt_map{$1})) {
1021                 push @$om, $2;
1022             } elsif (m/^--existing-package=(.*)/s) {
1023                 $existing_package = $1;
1024             } elsif (m/^--distro=(.*)/s) {
1025                 $idistro = $1;
1026             } else {
1027                 badusage "unknown long option \`$_'";
1028             }
1029         } else {
1030             while (m/^-./s) {
1031                 if (s/^-n/-/) {
1032                     $dryrun=1;
1033                 } elsif (s/^-h/-/) {
1034                     helponly();
1035                 } elsif (s/^-D/-/) {
1036                     open DEBUG, ">&STDERR" or die $!;
1037                     $debug++;
1038                 } elsif (s/^-N/-/) {
1039                     $new_package=1;
1040                 } elsif (s/^-c(.*=.*)//s) {
1041                     push @git, '-c', $1;
1042                 } elsif (s/^-d(.*)//s) {
1043                     $idistro = $1;
1044                 } elsif (s/^-C(.*)//s) {
1045                     $changesfile = $1;
1046                 } elsif (s/^-k(.*)//s) {
1047                     $keyid=$1;
1048                 } else {
1049                     badusage "unknown short option \`$_'";
1050                 }
1051             }
1052         }
1053     }
1054 }
1055
1056 parseopts();
1057 print STDERR "DRY RUN ONLY\n" if $dryrun;
1058 if (!@ARGV) {
1059     print STDERR $helpmsg or die $!;
1060     exit 8;
1061 }
1062 my $cmd = shift @ARGV;
1063 $cmd =~ y/-/_/;
1064 { no strict qw(refs); &{"cmd_$cmd"}(); }