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