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