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