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