chiark / gitweb /
If $idistro set (ie, distro explicitly specified by user), do not look at anything...
[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::Temp qw(tempdir);
28 use File::Basename;
29 use Dpkg::Version;
30 use POSIX;
31 use IPC::Open2;
32 use Digest::SHA;
33 use Digest::MD5;
34 use Config;
35
36 our $our_version = 'UNRELEASED'; ###substituted###
37
38 our $rpushprotovsn = 2;
39
40 our $isuite = 'unstable';
41 our $idistro;
42 our $package;
43 our @ropts;
44
45 our $sign = 1;
46 our $dryrun_level = 0;
47 our $changesfile;
48 our $buildproductsdir = '..';
49 our $new_package = 0;
50 our $ignoredirty = 0;
51 our $noquilt = 0;
52 our $rmonerror = 1;
53 our $existing_package = 'dpkg';
54 our $cleanmode = 'dpkg-source';
55 our $changes_since_version;
56 our $we_are_responder;
57 our $initiator_tempdir;
58
59 our %format_ok = map { $_=>1 } ("1.0","3.0 (native)","3.0 (quilt)");
60
61 our $suite_re = '[-+.0-9a-z]+';
62
63 our (@git) = qw(git);
64 our (@dget) = qw(dget);
65 our (@curl) = qw(curl -f);
66 our (@dput) = qw(dput);
67 our (@debsign) = qw(debsign);
68 our (@gpg) = qw(gpg);
69 our (@sbuild) = qw(sbuild -A);
70 our (@ssh) = 'ssh';
71 our (@dgit) = qw(dgit);
72 our (@dpkgbuildpackage) = qw(dpkg-buildpackage -i\.git/ -I.git);
73 our (@dpkgsource) = qw(dpkg-source -i\.git/ -I.git);
74 our (@dpkggenchanges) = qw(dpkg-genchanges);
75 our (@mergechanges) = qw(mergechanges -f);
76 our (@changesopts) = ('');
77
78 our %opts_opt_map = ('dget' => \@dget, # accept for compatibility
79                      'curl' => \@curl,
80                      'dput' => \@dput,
81                      'debsign' => \@debsign,
82                      'gpg' => \@gpg,
83                      'sbuild' => \@sbuild,
84                      'ssh' => \@ssh,
85                      'dgit' => \@dgit,
86                      'dpkg-source' => \@dpkgsource,
87                      'dpkg-buildpackage' => \@dpkgbuildpackage,
88                      'dpkg-genchanges' => \@dpkggenchanges,
89                      'ch' => \@changesopts,
90                      'mergechanges' => \@mergechanges);
91
92 our %opts_opt_cmdonly = ('gpg' => 1);
93
94 our $keyid;
95
96 our $debug = 0;
97 open DEBUG, ">/dev/null" or die $!;
98
99 autoflush STDOUT 1;
100
101 our $remotename = 'dgit';
102 our @ourdscfield = qw(Dgit Vcs-Dgit-Master);
103 our $branchprefix = 'dgit';
104 our $csuite;
105
106 sub lbranch () { return "$branchprefix/$csuite"; }
107 my $lbranch_re = '^refs/heads/'.$branchprefix.'/([^/.]+)$';
108 sub lref () { return "refs/heads/".lbranch(); }
109 sub lrref () { return "refs/remotes/$remotename/$branchprefix/$csuite"; }
110 sub rrref () { return "refs/$branchprefix/$csuite"; }
111 sub debiantag ($) { 
112     my ($v) = @_;
113     $v =~ y/~:/_%/;
114     return "debian/$v";
115 }
116
117 sub stripepoch ($) {
118     my ($vsn) = @_;
119     $vsn =~ s/^\d+\://;
120     return $vsn;
121 }
122
123 sub srcfn ($$) {
124     my ($vsn,$sfx) = @_;
125     return "${package}_".(stripepoch $vsn).$sfx
126 }
127
128 sub dscfn ($) {
129     my ($vsn) = @_;
130     return srcfn($vsn,".dsc");
131 }
132
133 our $us = 'dgit';
134 our $debugprefix = '';
135
136 our @end;
137 END { 
138     local ($?);
139     foreach my $f (@end) {
140         eval { $f->(); };
141         warn "$us: cleanup: $@" if length $@;
142     }
143 };
144
145 our @signames = split / /, $Config{sig_name};
146
147 sub waitstatusmsg () {
148     if (!$?) {
149         return "terminated, reporting successful completion";
150     } elsif (!($? & 255)) {
151         return "failed with error exit status ".WEXITSTATUS($?);
152     } elsif (WIFSIGNALED($?)) {
153         my $signum=WTERMSIG($?);
154         return "died due to fatal signal ".
155             ($signames[$signum] // "number $signum").
156             ($? & 128 ? " (core dumped)" : ""); # POSIX(3pm) has no WCOREDUMP
157     } else {
158         return "failed with unknown wait status ".$?;
159     }
160 }
161
162 sub printdebug { print DEBUG $debugprefix, @_ or die $!; }
163
164 sub fail { 
165     die $us.($we_are_responder ? " (build host)" : "").": @_\n";
166 }
167
168 sub badcfg { print STDERR "$us: invalid configuration: @_\n"; exit 12; }
169
170 sub no_such_package () {
171     print STDERR "$us: package $package does not exist in suite $isuite\n";
172     exit 4;
173 }
174
175 sub fetchspec () {
176     local $csuite = '*';
177     return  "+".rrref().":".lrref();
178 }
179
180 sub changedir ($) {
181     my ($newdir) = @_;
182     printdebug "CD $newdir\n";
183     chdir $newdir or die "chdir: $newdir: $!";
184 }
185
186 sub stat_exists ($) {
187     my ($f) = @_;
188     return 1 if stat $f;
189     return 0 if $!==&ENOENT;
190     die "stat $f: $!";
191 }
192
193 #---------- remote protocol support, common ----------
194
195 # remote push initiator/responder protocol:
196 #  < dgit-remote-push-ready [optional extra info ignored by old initiators]
197 #
198 #  > file parsed-changelog
199 #  [indicates that output of dpkg-parsechangelog follows]
200 #  > data-block NBYTES
201 #  > [NBYTES bytes of data (no newline)]
202 #  [maybe some more blocks]
203 #  > data-end
204 #
205 #  > file dsc
206 #  [etc]
207 #
208 #  > file changes
209 #  [etc]
210 #
211 #  > param head HEAD
212 #
213 #  > want signed-tag
214 #  [indicates that signed tag is wanted]
215 #  < data-block NBYTES
216 #  < [NBYTES bytes of data (no newline)]
217 #  [maybe some more blocks]
218 #  < data-end
219 #  < files-end
220 #
221 #  > want signed-dsc-changes
222 #  < data-block NBYTES    [transfer of signed dsc]
223 #  [etc]
224 #  < data-block NBYTES    [transfer of signed changes]
225 #  [etc]
226 #  < files-end
227 #
228 #  > complete
229
230 our $i_child_pid;
231
232 sub i_child_report () {
233     # Sees if our child has died, and reap it if so.  Returns a string
234     # describing how it died if it failed, or undef otherwise.
235     return undef unless $i_child_pid;
236     my $got = waitpid $i_child_pid, WNOHANG;
237     return undef if $got <= 0;
238     die unless $got == $i_child_pid;
239     $i_child_pid = undef;
240     return undef unless $?;
241     return "build host child ".waitstatusmsg();
242 }
243
244 sub badproto ($$) {
245     my ($fh, $m) = @_;
246     fail "connection lost: $!" if $fh->error;
247     fail "protocol violation; $m not expected";
248 }
249
250 sub badproto_badread ($$) {
251     my ($fh, $wh) = @_;
252     fail "connection lost: $!" if $!;
253     my $report = i_child_report();
254     fail $report if defined $report;
255     badproto $fh, "eof (reading $wh)";
256 }
257
258 sub protocol_expect (&$) {
259     my ($match, $fh) = @_;
260     local $_;
261     $_ = <$fh>;
262     defined && chomp or badproto_badread $fh, "protocol message";
263     if (wantarray) {
264         my @r = &$match;
265         return @r if @r;
266     } else {
267         my $r = &$match;
268         return $r if $r;
269     }
270     badproto $fh, "\`$_'";
271 }
272
273 sub protocol_send_file ($$) {
274     my ($fh, $ourfn) = @_;
275     open PF, "<", $ourfn or die "$ourfn: $!";
276     for (;;) {
277         my $d;
278         my $got = read PF, $d, 65536;
279         die "$ourfn: $!" unless defined $got;
280         last if !$got;
281         print $fh "data-block ".length($d)."\n" or die $!;
282         print $fh $d or die $!;
283     }
284     PF->error and die "$ourfn $!";
285     print $fh "data-end\n" or die $!;
286     close PF;
287 }
288
289 sub protocol_read_bytes ($$) {
290     my ($fh, $nbytes) = @_;
291     $nbytes =~ m/^[1-9]\d{0,5}$/ or badproto \*RO, "bad byte count";
292     my $d;
293     my $got = read $fh, $d, $nbytes;
294     $got==$nbytes or badproto_badread $fh, "data block";
295     return $d;
296 }
297
298 sub protocol_receive_file ($$) {
299     my ($fh, $ourfn) = @_;
300     printdebug "() $ourfn\n";
301     open PF, ">", $ourfn or die "$ourfn: $!";
302     for (;;) {
303         my ($y,$l) = protocol_expect {
304             m/^data-block (.*)$/ ? (1,$1) :
305             m/^data-end$/ ? (0,) :
306             ();
307         } $fh;
308         last unless $y;
309         my $d = protocol_read_bytes $fh, $l;
310         print PF $d or die $!;
311     }
312     close PF or die $!;
313 }
314
315 #---------- remote protocol support, responder ----------
316
317 sub responder_send_command ($) {
318     my ($command) = @_;
319     return unless $we_are_responder;
320     # called even without $we_are_responder
321     printdebug ">> $command\n";
322     print PO $command, "\n" or die $!;
323 }    
324
325 sub responder_send_file ($$) {
326     my ($keyword, $ourfn) = @_;
327     return unless $we_are_responder;
328     printdebug "]] $keyword $ourfn\n";
329     responder_send_command "file $keyword";
330     protocol_send_file \*PO, $ourfn;
331 }
332
333 sub responder_receive_files ($@) {
334     my ($keyword, @ourfns) = @_;
335     die unless $we_are_responder;
336     printdebug "[[ $keyword @ourfns\n";
337     responder_send_command "want $keyword";
338     foreach my $fn (@ourfns) {
339         protocol_receive_file \*PI, $fn;
340     }
341     printdebug "[[\$\n";
342     protocol_expect { m/^files-end$/ } \*PI;
343 }
344
345 #---------- remote protocol support, initiator ----------
346
347 sub initiator_expect (&) {
348     my ($match) = @_;
349     protocol_expect { &$match } \*RO;
350 }
351
352 #---------- end remote code ----------
353
354 sub progress {
355     if ($we_are_responder) {
356         my $m = join '', @_;
357         responder_send_command "progress ".length($m) or die $!;
358         print PO $m or die $!;
359     } else {
360         print @_, "\n";
361     }
362 }
363
364 our $ua;
365
366 sub url_get {
367     if (!$ua) {
368         $ua = LWP::UserAgent->new();
369         $ua->env_proxy;
370     }
371     my $what = $_[$#_];
372     progress "downloading $what...";
373     my $r = $ua->get(@_) or die $!;
374     return undef if $r->code == 404;
375     $r->is_success or fail "failed to fetch $what: ".$r->status_line;
376     return $r->decoded_content(charset => 'none');
377 }
378
379 our ($dscdata,$dscurl,$dsc,$dsc_checked,$skew_warning_vsn);
380
381 sub shellquote {
382     my @out;
383     local $_;
384     foreach my $a (@_) {
385         $_ = $a;
386         if (m{[^-=_./0-9a-z]}i) {
387             s{['\\]}{'\\$&'}g;
388             push @out, "'$_'";
389         } else {
390             push @out, $_;
391         }
392     }
393     return join ' ', @out;
394 }
395
396 sub printcmd {
397     my $fh = shift @_;
398     my $intro = shift @_;
399     print $fh $intro," " or die $!;
400     print $fh shellquote @_ or die $!;
401     print $fh "\n" or die $!;
402 }
403
404 sub failedcmd {
405     { local ($!); printcmd \*STDERR, "$us: failed command:", @_ or die $!; };
406     if ($!) {
407         fail "failed to fork/exec: $!";
408     } elsif ($?) {
409         fail "subprocess ".waitstatusmsg();
410     } else {
411         fail "subprocess produced invalid output";
412     }
413 }
414
415 sub runcmd {
416     printcmd(\*DEBUG,$debugprefix."+",@_) if $debug>0;
417     $!=0; $?=0;
418     failedcmd @_ if system @_;
419 }
420
421 sub act_local () { return $dryrun_level <= 1; }
422 sub act_scary () { return !$dryrun_level; }
423
424 sub printdone {
425     if (!$dryrun_level) {
426         progress "dgit ok: @_";
427     } else {
428         progress "would be ok: @_ (but dry run only)";
429     }
430 }
431
432 sub cmdoutput_errok {
433     die Dumper(\@_)." ?" if grep { !defined } @_;
434     printcmd(\*DEBUG,$debugprefix."|",@_) if $debug>0;
435     open P, "-|", @_ or die $!;
436     my $d;
437     $!=0; $?=0;
438     { local $/ = undef; $d = <P>; }
439     die $! if P->error;
440     if (!close P) { printdebug "=>!$?\n" if $debug>0; return undef; }
441     chomp $d;
442     $d =~ m/^.*/;
443     printdebug "=> \`$&'",(length $' ? '...' : ''),"\n" if $debug>0; #';
444     return $d;
445 }
446
447 sub cmdoutput {
448     my $d = cmdoutput_errok @_;
449     defined $d or failedcmd @_;
450     return $d;
451 }
452
453 sub dryrun_report {
454     printcmd(\*STDERR,$debugprefix."#",@_);
455 }
456
457 sub runcmd_ordryrun {
458     if (act_scary()) {
459         runcmd @_;
460     } else {
461         dryrun_report @_;
462     }
463 }
464
465 sub runcmd_ordryrun_local {
466     if (act_local()) {
467         runcmd @_;
468     } else {
469         dryrun_report @_;
470     }
471 }
472
473 sub shell_cmd {
474     my ($first_shell, @cmd) = @_;
475     return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
476 }
477
478 our $helpmsg = <<END;
479 main usages:
480   dgit [dgit-opts] clone [dgit-opts] package [suite] [./dir|/dir]
481   dgit [dgit-opts] fetch|pull [dgit-opts] [suite]
482   dgit [dgit-opts] build [git-buildpackage-opts|dpkg-buildpackage-opts]
483   dgit [dgit-opts] push [dgit-opts] [suite]
484   dgit [dgit-opts] rpush build-host:build-dir ...
485 important dgit options:
486   -k<keyid>           sign tag and package with <keyid> instead of default
487   --dry-run -n        do not change anything, but go through the motions
488   --damp-run -L       like --dry-run but make local changes, without signing
489   --new -N            allow introducing a new package
490   --debug -D          increase debug level
491   -c<name>=<value>    set git config option (used directly by dgit too)
492 END
493
494 our $later_warning_msg = <<END;
495 Perhaps the upload is stuck in incoming.  Using the version from git.
496 END
497
498 sub badusage {
499     print STDERR "$us: @_\n", $helpmsg or die $!;
500     exit 8;
501 }
502
503 sub nextarg {
504     @ARGV or badusage "too few arguments";
505     return scalar shift @ARGV;
506 }
507
508 sub cmd_help () {
509     print $helpmsg or die $!;
510     exit 0;
511 }
512
513 our $td = $ENV{DGIT_TEST_DUMMY_DIR} || "DGIT_TEST_DUMMY_DIR-unset";
514
515 our %defcfg = ('dgit.default.distro' => 'debian',
516                'dgit.default.username' => '',
517                'dgit.default.archive-query-default-component' => 'main',
518                'dgit.default.ssh' => 'ssh',
519                'dgit.default.archive-query' => 'madison:',
520                'dgit.default.sshpsql-dbname' => 'service=projectb',
521                'dgit-distro.debian.archive-query' => 'sshpsql:',
522                'dgit-distro.debian.git-host' => 'git.debian.org',
523                'dgit-distro.debian.git-proto' => 'git+ssh://',
524                'dgit-distro.debian.git-path' => '/git/dgit-repos/repos',
525                'dgit-distro.debian.git-check' => 'ssh-cmd',
526                'dgit-distro.debian.git-create' => 'ssh-cmd',
527                'dgit-distro.debian.sshpsql-host' => 'mirror.ftp-master.debian.org',
528                'dgit-distro.debian.upload-host' => 'ftp-master', # for dput
529                'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/',
530  'dgit-distro.debian.backports-quirk' => '(squeeze)-backports*',
531  'dgit-distro.debian-backports.mirror' => 'http://backports.debian.org/debian-backports/',
532                'dgit-distro.ubuntu.git-check' => 'false',
533  'dgit-distro.ubuntu.mirror' => 'http://archive.ubuntu.com/ubuntu',
534                'dgit-distro.test-dummy.ssh' => "$td/ssh",
535                'dgit-distro.test-dummy.username' => "alice",
536                'dgit-distro.test-dummy.git-check' => "ssh-cmd",
537                'dgit-distro.test-dummy.git-create' => "ssh-cmd",
538                'dgit-distro.test-dummy.git-url' => "$td/git",
539                'dgit-distro.test-dummy.git-host' => "git",
540                'dgit-distro.test-dummy.git-path' => "$td/git",
541                'dgit-distro.test-dummy.archive-query' => "dummycat:$td/aq",
542                'dgit-distro.test-dummy.mirror' => "file://$td/mirror/",
543                'dgit-distro.test-dummy.upload-host' => 'test-dummy',
544                );
545
546 sub cfg {
547     foreach my $c (@_) {
548         return undef if $c =~ /RETURN-UNDEF/;
549         my @cmd = (@git, qw(config --), $c);
550         my $v;
551         {
552             local ($debug) = $debug-1;
553             $v = cmdoutput_errok @cmd;
554         };
555         if ($?==0) {
556             return $v;
557         } elsif ($?!=256) {
558             failedcmd @cmd;
559         }
560         my $dv = $defcfg{$c};
561         return $dv if defined $dv;
562     }
563     badcfg "need value for one of: @_\n".
564         "$us: distro or suite appears not to be (properly) supported";
565 }
566
567 sub access_basedistro () {
568     if (defined $idistro) {
569         return $idistro;
570     } else {    
571         return cfg("dgit-suite.$isuite.distro",
572                    "dgit.default.distro");
573     }
574 }
575
576 sub access_quirk () {
577     # returns (quirk name, distro to use instead, quirk-specific info)
578     my $basedistro = access_basedistro();
579     my $backports_quirk = cfg("dgit-distro.$basedistro.backports-quirk",
580                               'RETURN-UNDEF');
581     if (defined $backports_quirk) {
582         my $re = $backports_quirk;
583         $re =~ s/[^-0-9a-z_\%*()]/\\$&/ig;
584         $re =~ s/\*/.*/g;
585         $re =~ s/\%/([-0-9a-z_]+)/
586             or $re =~ m/[()]/ or badcfg "backports-quirk needs \% or ( )";
587         if ($isuite =~ m/^$re$/) {
588             return ('backports',"$basedistro-backports",$1);
589         }
590     }
591     return ('none',$basedistro);
592 }
593
594 sub access_distro () {
595     return (access_quirk())[1];
596 }
597
598 sub access_cfg (@) {
599     my (@keys) = @_;
600     my $basedistro = access_basedistro();
601     my $distro = $idistro || access_distro();
602     my $value = cfg(map {
603         ("dgit-distro.$distro.$_",
604          "dgit-distro.$basedistro.$_",
605          "dgit.default.$_")
606                     } @keys);
607     return $value;
608 }
609
610 sub string_to_ssh ($) {
611     my ($spec) = @_;
612     if ($spec =~ m/\s/) {
613         return qw(sh -ec), 'exec '.$spec.' "$@"', 'x';
614     } else {
615         return ($spec);
616     }
617 }
618
619 sub access_cfg_ssh () {
620     my $gitssh = access_cfg('ssh', 'RETURN-UNDEF');
621     if (!defined $gitssh) {
622         return @ssh;
623     } else {
624         return string_to_ssh $gitssh;
625     }
626 }
627
628 sub access_someuserhost ($) {
629     my ($some) = @_;
630     my $user = access_cfg("$some-user",'username');
631     my $host = access_cfg("$some-host");
632     return length($user) ? "$user\@$host" : $host;
633 }
634
635 sub access_gituserhost () {
636     return access_someuserhost('git');
637 }
638
639 sub access_giturl (;$) {
640     my ($optional) = @_;
641     my $url = access_cfg('git-url','RETURN-UNDEF');
642     if (!defined $url) {
643         my $proto = access_cfg('git-proto', 'RETURN-UNDEF');
644         return undef unless defined $proto;
645         $url =
646             $proto.
647             access_gituserhost().
648             access_cfg('git-path');
649     }
650     return "$url/$package.git";
651 }              
652
653 sub parsecontrolfh ($$;$) {
654     my ($fh, $desc, $allowsigned) = @_;
655     our $dpkgcontrolhash_noissigned;
656     my $c;
657     for (;;) {
658         my %opts = ('name' => $desc);
659         $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
660         $c = Dpkg::Control::Hash->new(%opts);
661         $c->parse($fh,$desc) or die "parsing of $desc failed";
662         last if $allowsigned;
663         last if $dpkgcontrolhash_noissigned;
664         my $issigned= $c->get_option('is_pgp_signed');
665         if (!defined $issigned) {
666             $dpkgcontrolhash_noissigned= 1;
667             seek $fh, 0,0 or die "seek $desc: $!";
668         } elsif ($issigned) {
669             fail "control file $desc is (already) PGP-signed. ".
670                 " Note that dgit push needs to modify the .dsc and then".
671                 " do the signature itself";
672         } else {
673             last;
674         }
675     }
676     return $c;
677 }
678
679 sub parsecontrol {
680     my ($file, $desc) = @_;
681     my $fh = new IO::Handle;
682     open $fh, '<', $file or die "$file: $!";
683     my $c = parsecontrolfh($fh,$desc);
684     $fh->error and die $!;
685     close $fh;
686     return $c;
687 }
688
689 sub getfield ($$) {
690     my ($dctrl,$field) = @_;
691     my $v = $dctrl->{$field};
692     return $v if defined $v;
693     fail "missing field $field in ".$v->get_option('name');
694 }
695
696 sub parsechangelog {
697     my $c = Dpkg::Control::Hash->new();
698     my $p = new IO::Handle;
699     my @cmd = (qw(dpkg-parsechangelog), @_);
700     open $p, '-|', @cmd or die $!;
701     $c->parse($p);
702     $?=0; $!=0; close $p or failedcmd @cmd;
703     return $c;
704 }
705
706 sub git_get_ref ($) {
707     my ($refname) = @_;
708     my $got = cmdoutput_errok @git, qw(show-ref --), $refname;
709     if (!defined $got) {
710         $?==256 or fail "git show-ref failed (status $?)";
711         printdebug "ref $refname= [show-ref exited 1]\n";
712         return '';
713     }
714     if ($got =~ m/^(\w+) \Q$refname\E$/m) {
715         printdebug "ref $refname=$1\n";
716         return $1;
717     } else {
718         printdebug "ref $refname= [no match]\n";
719         return '';
720     }
721 }
722
723 sub must_getcwd () {
724     my $d = getcwd();
725     defined $d or fail "getcwd failed: $!";
726     return $d;
727 }
728
729 our %rmad;
730
731 sub archive_query ($) {
732     my ($method) = @_;
733     my $query = access_cfg('archive-query','RETURN-UNDEF');
734     $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
735     my $proto = $1;
736     my $data = $'; #';
737     { no strict qw(refs); &{"${method}_${proto}"}($proto,$data); }
738 }
739
740 sub pool_dsc_subpath ($$) {
741     my ($vsn,$component) = @_; # $package is implict arg
742     my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
743     return "/pool/$component/$prefix/$package/".dscfn($vsn);
744 }
745
746 sub archive_query_madison {
747     return map { [ @$_[0..1] ] } madison_get_parse(@_);
748 }
749
750 sub madison_get_parse {
751     my ($proto,$data) = @_;
752     die unless $proto eq 'madison';
753     if (!length $data) {
754         $data= access_cfg('madison-distro','RETURN-UNDEF');
755         $data //= access_basedistro();
756     }
757     $rmad{$proto,$data,$package} ||= cmdoutput
758         qw(rmadison -asource),"-s$isuite","-u$data",$package;
759     my $rmad = $rmad{$proto,$data,$package};
760
761     my @out;
762     foreach my $l (split /\n/, $rmad) {
763         $l =~ m{^ \s*( [^ \t|]+ )\s* \|
764                   \s*( [^ \t|]+ )\s* \|
765                   \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
766                   \s*( [^ \t|]+ )\s* }x or die "$rmad ?";
767         $1 eq $package or die "$rmad $package ?";
768         my $vsn = $2;
769         my $newsuite = $3;
770         my $component;
771         if (defined $4) {
772             $component = $4;
773         } else {
774             $component = access_cfg('archive-query-default-component');
775         }
776         $5 eq 'source' or die "$rmad ?";
777         push @out, [$vsn,pool_dsc_subpath($vsn,$component),$newsuite];
778     }
779     return sort { -version_compare($a->[0],$b->[0]); } @out;
780 }
781
782 sub canonicalise_suite_madison {
783     # madison canonicalises for us
784     my @r = madison_get_parse(@_);
785     @r or fail
786         "unable to canonicalise suite using package $package".
787         " which does not appear to exist in suite $isuite;".
788         " --existing-package may help";
789     return $r[0][2];
790 }
791
792 sub sshpsql ($$) {
793     my ($data,$sql) = @_;
794     if (!length $data) {
795         $data= access_someuserhost('sshpsql').':'.
796             access_cfg('sshpsql-dbname');
797     }
798     $data =~ m/:/ or badcfg "invalid sshpsql method string \`$data'";
799     my ($userhost,$dbname) = ($`,$'); #';
800     my @rows;
801     my @cmd = (access_cfg_ssh, $userhost,
802                "export LANG=C; ".shellquote qw(psql -A), $dbname, qw(-c), $sql);
803     printcmd(\*DEBUG,$debugprefix."|",@cmd) if $debug>0;
804     open P, "-|", @cmd or die $!;
805     while (<P>) {
806         chomp or die;
807         printdebug("$debugprefix>|$_|\n");
808         push @rows, $_;
809     }
810     $!=0; $?=0; close P or failedcmd @cmd;
811     @rows or die;
812     my $nrows = pop @rows;
813     $nrows =~ s/^\((\d+) rows?\)$/$1/ or die "$nrows ?";
814     @rows == $nrows+1 or die "$nrows ".(scalar @rows)." ?";
815     @rows = map { [ split /\|/, $_ ] } @rows;
816     my $ncols = scalar @{ shift @rows };
817     die if grep { scalar @$_ != $ncols } @rows;
818     return @rows;
819 }
820
821 sub sql_injection_check {
822     foreach (@_) { die "$_ $& ?" if m/[']/; }
823 }
824
825 sub archive_query_sshpsql ($$) {
826     my ($proto,$data) = @_;
827     sql_injection_check $isuite, $package;
828     my @rows = sshpsql($data, <<END);
829         SELECT source.version, component.name, files.filename, files.sha256sum
830           FROM source
831           JOIN src_associations ON source.id = src_associations.source
832           JOIN suite ON suite.id = src_associations.suite
833           JOIN dsc_files ON dsc_files.source = source.id
834           JOIN files_archive_map ON files_archive_map.file_id = dsc_files.file
835           JOIN component ON component.id = files_archive_map.component_id
836           JOIN files ON files.id = dsc_files.file
837          WHERE ( suite.suite_name='$isuite' OR suite.codename='$isuite' )
838            AND source.source='$package'
839            AND files.filename LIKE '%.dsc';
840 END
841     @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
842     my $digester = Digest::SHA->new(256);
843     @rows = map {
844         my ($vsn,$component,$filename,$sha256sum) = @$_;
845         [ $vsn, "/pool/$component/$filename",$digester,$sha256sum ];
846     } @rows;
847     return @rows;
848 }
849
850 sub canonicalise_suite_sshpsql ($$) {
851     my ($proto,$data) = @_;
852     sql_injection_check $isuite;
853     my @rows = sshpsql($data, <<END);
854         SELECT suite.codename
855           FROM suite where suite_name='$isuite' or codename='$isuite';
856 END
857     @rows = map { $_->[0] } @rows;
858     fail "unknown suite $isuite" unless @rows;
859     die "ambiguous $isuite: @rows ?" if @rows>1;
860     return $rows[0];
861 }
862
863 sub canonicalise_suite_dummycat ($$) {
864     my ($proto,$data) = @_;
865     my $dpath = "$data/suite.$isuite";
866     if (!open C, "<", $dpath) {
867         $!==ENOENT or die "$dpath: $!";
868         printdebug "dummycat canonicalise_suite $isuite $dpath ENOENT\n";
869         return $isuite;
870     }
871     $!=0; $_ = <C>;
872     chomp or die "$dpath: $!";
873     close C;
874     printdebug "dummycat canonicalise_suite $isuite $dpath = $_\n";
875     return $_;
876 }
877
878 sub archive_query_dummycat ($$) {
879     my ($proto,$data) = @_;
880     canonicalise_suite();
881     my $dpath = "$data/package.$csuite.$package";
882     if (!open C, "<", $dpath) {
883         $!==ENOENT or die "$dpath: $!";
884         printdebug "dummycat query $csuite $package $dpath ENOENT\n";
885         return ();
886     }
887     my @rows;
888     while (<C>) {
889         next if m/^\#/;
890         next unless m/\S/;
891         die unless chomp;
892         printdebug "dummycat query $csuite $package $dpath | $_\n";
893         my @row = split /\s+/, $_;
894         @row==2 or die "$dpath: $_ ?";
895         push @rows, \@row;
896     }
897     C->error and die "$dpath: $!";
898     close C;
899     return sort { -version_compare($a->[0],$b->[0]); } @rows;
900 }
901
902 sub canonicalise_suite () {
903     return if defined $csuite;
904     fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
905     $csuite = archive_query('canonicalise_suite');
906     if ($isuite ne $csuite) {
907         progress "canonical suite name for $isuite is $csuite";
908     }
909 }
910
911 sub get_archive_dsc () {
912     canonicalise_suite();
913     my @vsns = archive_query('archive_query');
914     foreach my $vinfo (@vsns) {
915         my ($vsn,$subpath,$digester,$digest) = @$vinfo;
916         $dscurl = access_cfg('mirror').$subpath;
917         $dscdata = url_get($dscurl);
918         if (!$dscdata) {
919             $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
920             next;
921         }
922         if ($digester) {
923             $digester->reset();
924             $digester->add($dscdata);
925             my $got = $digester->hexdigest();
926             $got eq $digest or
927                 fail "$dscurl has hash $got but".
928                     " archive told us to expect $digest";
929         }
930         my $dscfh = new IO::File \$dscdata, '<' or die $!;
931         printdebug Dumper($dscdata) if $debug>1;
932         $dsc = parsecontrolfh($dscfh,$dscurl,1);
933         printdebug Dumper($dsc) if $debug>1;
934         my $fmt = getfield $dsc, 'Format';
935         fail "unsupported source format $fmt, sorry" unless $format_ok{$fmt};
936         $dsc_checked = !!$digester;
937         return;
938     }
939     $dsc = undef;
940 }
941
942 sub check_for_git () {
943     # returns 0 or 1
944     my $how = access_cfg('git-check');
945     if ($how eq 'ssh-cmd') {
946         my @cmd =
947             (access_cfg_ssh, access_gituserhost(),
948              " set -e; cd ".access_cfg('git-path').";".
949              " if test -d $package.git; then echo 1; else echo 0; fi");
950         my $r= cmdoutput @cmd;
951         failedcmd @cmd unless $r =~ m/^[01]$/;
952         return $r+0;
953     } elsif ($how eq 'true') {
954         return 1;
955     } elsif ($how eq 'false') {
956         return 0;
957     } else {
958         badcfg "unknown git-check \`$how'";
959     }
960 }
961
962 sub create_remote_git_repo () {
963     my $how = access_cfg('git-create');
964     if ($how eq 'ssh-cmd') {
965         runcmd_ordryrun
966             (access_cfg_ssh, access_gituserhost(),
967              "set -e; cd ".access_cfg('git-path').";".
968              " cp -a _template $package.git");
969     } elsif ($how eq 'true') {
970         # nothing to do
971     } else {
972         badcfg "unknown git-create \`$how'";
973     }
974 }
975
976 our ($dsc_hash,$lastpush_hash);
977
978 our $ud = '.git/dgit/unpack';
979
980 sub prep_ud () {
981     rmtree($ud);
982     mkpath '.git/dgit';
983     mkdir $ud or die $!;
984 }
985
986 sub mktree_in_ud_here () {
987     runcmd qw(git init -q);
988     rmtree('.git/objects');
989     symlink '../../../../objects','.git/objects' or die $!;
990 }
991
992 sub mktree_in_ud_from_only_subdir () {
993     # changes into the subdir
994     my (@dirs) = <*/.>;
995     die unless @dirs==1;
996     $dirs[0] =~ m#^([^/]+)/\.$# or die;
997     my $dir = $1;
998     changedir $dir;
999     fail "source package contains .git directory" if stat_exists '.git';
1000     mktree_in_ud_here();
1001     my $format=get_source_format();
1002     if (madformat($format)) {
1003         rmtree '.pc';
1004     }
1005     runcmd @git, qw(add -Af);
1006     my $tree = cmdoutput @git, qw(write-tree);
1007     $tree =~ m/^\w+$/ or die "$tree ?";
1008     return ($tree,$dir);
1009 }
1010
1011 sub dsc_files_info () {
1012     foreach my $csumi (['Checksums-Sha256','Digest::SHA', 'new(256)'],
1013                        ['Checksums-Sha1',  'Digest::SHA', 'new(1)'],
1014                        ['Files',           'Digest::MD5', 'new()']) {
1015         my ($fname, $module, $method) = @$csumi;
1016         my $field = $dsc->{$fname};
1017         next unless defined $field;
1018         eval "use $module; 1;" or die $@;
1019         my @out;
1020         foreach (split /\n/, $field) {
1021             next unless m/\S/;
1022             m/^(\w+) (\d+) (\S+)$/ or
1023                 fail "could not parse .dsc $fname line \`$_'";
1024             my $digester = eval "$module"."->$method;" or die $@;
1025             push @out, {
1026                 Hash => $1,
1027                 Bytes => $2,
1028                 Filename => $3,
1029                 Digester => $digester,
1030             };
1031         }
1032         return @out;
1033     }
1034     fail "missing any supported Checksums-* or Files field in ".
1035         $dsc->get_option('name');
1036 }
1037
1038 sub dsc_files () {
1039     map { $_->{Filename} } dsc_files_info();
1040 }
1041
1042 sub is_orig_file ($;$) {
1043     local ($_) = $_[0];
1044     my $base = $_[1];
1045     m/\.orig(?:-\w+)?\.tar\.\w+$/ or return 0;
1046     defined $base or return 1;
1047     return $` eq $base;
1048 }
1049
1050 sub make_commit ($) {
1051     my ($file) = @_;
1052     return cmdoutput @git, qw(hash-object -w -t commit), $file;
1053 }
1054
1055 sub clogp_authline ($) {
1056     my ($clogp) = @_;
1057     my $author = getfield $clogp, 'Maintainer';
1058     $author =~ s#,.*##ms;
1059     my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
1060     my $authline = "$author $date";
1061     $authline =~ m/^[^<>]+ \<\S+\> \d+ [-+]\d+$/ or
1062         fail "unexpected commit author line format \`$authline'".
1063         " (was generated from changelog Maintainer field)";
1064     return $authline;
1065 }
1066
1067 sub generate_commit_from_dsc () {
1068     prep_ud();
1069     changedir $ud;
1070
1071     foreach my $fi (dsc_files_info()) {
1072         my $f = $fi->{Filename};
1073         die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
1074
1075         link "../../../$f", $f
1076             or $!==&ENOENT
1077             or die "$f $!";
1078
1079         complete_file_from_dsc('.', $fi);
1080
1081         if (is_orig_file($f)) {
1082             link $f, "../../../../$f"
1083                 or $!==&EEXIST
1084                 or die "$f $!";
1085         }
1086     }
1087
1088     my $dscfn = "$package.dsc";
1089
1090     open D, ">", $dscfn or die "$dscfn: $!";
1091     print D $dscdata or die "$dscfn: $!";
1092     close D or die "$dscfn: $!";
1093     my @cmd = qw(dpkg-source);
1094     push @cmd, '--no-check' if $dsc_checked;
1095     push @cmd, qw(-x --), $dscfn;
1096     runcmd @cmd;
1097
1098     my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1099     runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
1100     my $clogp = parsecontrol('../changelog.tmp',"commit's changelog");
1101     my $authline = clogp_authline $clogp;
1102     my $changes = getfield $clogp, 'Changes';
1103     open C, ">../commit.tmp" or die $!;
1104     print C <<END or die $!;
1105 tree $tree
1106 author $authline
1107 committer $authline
1108
1109 $changes
1110
1111 # imported from the archive
1112 END
1113     close C or die $!;
1114     my $outputhash = make_commit qw(../commit.tmp);
1115     my $cversion = getfield $clogp, 'Version';
1116     progress "synthesised git commit from .dsc $cversion";
1117     if ($lastpush_hash) {
1118         runcmd @git, qw(reset --hard), $lastpush_hash;
1119         runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
1120         my $oldclogp = parsecontrol('../changelogold.tmp','previous changelog');
1121         my $oversion = getfield $oldclogp, 'Version';
1122         my $vcmp =
1123             version_compare($oversion, $cversion);
1124         if ($vcmp < 0) {
1125             # git upload/ is earlier vsn than archive, use archive
1126             open C, ">../commit2.tmp" or die $!;
1127             print C <<END or die $!;
1128 tree $tree
1129 parent $lastpush_hash
1130 parent $outputhash
1131 author $authline
1132 committer $authline
1133
1134 Record $package ($cversion) in archive suite $csuite
1135 END
1136             $outputhash = make_commit qw(../commit2.tmp);
1137         } elsif ($vcmp > 0) {
1138             print STDERR <<END or die $!;
1139
1140 Version actually in archive:    $cversion (older)
1141 Last allegedly pushed/uploaded: $oversion (newer or same)
1142 $later_warning_msg
1143 END
1144             $outputhash = $lastpush_hash;
1145         } else {
1146             $outputhash = $lastpush_hash;
1147         }
1148     }
1149     changedir '../../../..';
1150     runcmd @git, qw(update-ref -m),"dgit fetch import $cversion",
1151             'DGIT_ARCHIVE', $outputhash;
1152     cmdoutput @git, qw(log -n2), $outputhash;
1153     # ... gives git a chance to complain if our commit is malformed
1154     rmtree($ud);
1155     return $outputhash;
1156 }
1157
1158 sub complete_file_from_dsc ($$) {
1159     our ($dstdir, $fi) = @_;
1160     # Ensures that we have, in $dir, the file $fi, with the correct
1161     # contents.  (Downloading it from alongside $dscurl if necessary.)
1162
1163     my $f = $fi->{Filename};
1164     my $tf = "$dstdir/$f";
1165     my $downloaded = 0;
1166
1167     if (stat_exists $tf) {
1168         progress "using existing $f";
1169     } else {
1170         my $furl = $dscurl;
1171         $furl =~ s{/[^/]+$}{};
1172         $furl .= "/$f";
1173         die "$f ?" unless $f =~ m/^${package}_/;
1174         die "$f ?" if $f =~ m#/#;
1175         runcmd_ordryrun_local @curl,qw(-o),$tf,'--',"$furl";
1176         next if !act_local();
1177         $downloaded = 1;
1178     }
1179
1180     open F, "<", "$tf" or die "$tf: $!";
1181     $fi->{Digester}->reset();
1182     $fi->{Digester}->addfile(*F);
1183     F->error and die $!;
1184     my $got = $fi->{Digester}->hexdigest();
1185     $got eq $fi->{Hash} or
1186         fail "file $f has hash $got but .dsc".
1187             " demands hash $fi->{Hash} ".
1188             ($downloaded ? "(got wrong file from archive!)"
1189              : "(perhaps you should delete this file?)");
1190 }
1191
1192 sub ensure_we_have_orig () {
1193     foreach my $fi (dsc_files_info()) {
1194         my $f = $fi->{Filename};
1195         next unless is_orig_file($f);
1196         complete_file_from_dsc('..', $fi);
1197     }
1198 }
1199
1200 sub rev_parse ($) {
1201     return cmdoutput @git, qw(rev-parse), "$_[0]~0";
1202 }
1203
1204 sub is_fast_fwd ($$) {
1205     my ($ancestor,$child) = @_;
1206     my @cmd = (@git, qw(merge-base), $ancestor, $child);
1207     my $mb = cmdoutput_errok @cmd;
1208     if (defined $mb) {
1209         return rev_parse($mb) eq rev_parse($ancestor);
1210     } else {
1211         $?==256 or failedcmd @cmd;
1212         return 0;
1213     }
1214 }
1215
1216 sub git_fetch_us () {
1217     runcmd_ordryrun_local @git, qw(fetch),access_giturl(),fetchspec();
1218 }
1219
1220 sub fetch_from_archive () {
1221     # ensures that lrref() is what is actually in the archive,
1222     #  one way or another
1223     get_archive_dsc();
1224
1225     if ($dsc) {
1226         foreach my $field (@ourdscfield) {
1227             $dsc_hash = $dsc->{$field};
1228             last if defined $dsc_hash;
1229         }
1230         if (defined $dsc_hash) {
1231             $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
1232             $dsc_hash = $&;
1233             progress "last upload to archive specified git hash";
1234         } else {
1235             progress "last upload to archive has NO git hash";
1236         }
1237     } else {
1238         progress "no version available from the archive";
1239     }
1240
1241     $lastpush_hash = git_get_ref(lrref());
1242     printdebug "previous reference hash=$lastpush_hash\n";
1243     my $hash;
1244     if (defined $dsc_hash) {
1245         fail "missing remote git history even though dsc has hash -".
1246             " could not find ref ".lrref().
1247             " (should have been fetched from ".access_giturl()."#".rrref().")"
1248             unless $lastpush_hash;
1249         $hash = $dsc_hash;
1250         ensure_we_have_orig();
1251         if ($dsc_hash eq $lastpush_hash) {
1252         } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
1253             print STDERR <<END or die $!;
1254
1255 Git commit in archive is behind the last version allegedly pushed/uploaded.
1256 Commit referred to by archive:  $dsc_hash
1257 Last allegedly pushed/uploaded: $lastpush_hash
1258 $later_warning_msg
1259 END
1260             $hash = $lastpush_hash;
1261         } else {
1262             fail "archive's .dsc refers to ".$dsc_hash.
1263                 " but this is an ancestor of ".$lastpush_hash;
1264         }
1265     } elsif ($dsc) {
1266         $hash = generate_commit_from_dsc();
1267     } elsif ($lastpush_hash) {
1268         # only in git, not in the archive yet
1269         $hash = $lastpush_hash;
1270         print STDERR <<END or die $!;
1271
1272 Package not found in the archive, but has allegedly been pushed using dgit.
1273 $later_warning_msg
1274 END
1275     } else {
1276         printdebug "nothing found!\n";
1277         if (defined $skew_warning_vsn) {
1278             print STDERR <<END or die $!;
1279
1280 Warning: relevant archive skew detected.
1281 Archive allegedly contains $skew_warning_vsn
1282 But we were not able to obtain any version from the archive or git.
1283
1284 END
1285         }
1286         return 0;
1287     }
1288     printdebug "current hash=$hash\n";
1289     if ($lastpush_hash) {
1290         fail "not fast forward on last upload branch!".
1291             " (archive's version left in DGIT_ARCHIVE)"
1292             unless is_fast_fwd($lastpush_hash, $hash);
1293     }
1294     if (defined $skew_warning_vsn) {
1295         mkpath '.git/dgit';
1296         printdebug "SKEW CHECK WANT $skew_warning_vsn\n";
1297         my $clogf = ".git/dgit/changelog.tmp";
1298         runcmd shell_cmd "exec >$clogf",
1299             @git, qw(cat-file blob), "$hash:debian/changelog";
1300         my $gotclogp = parsechangelog("-l$clogf");
1301         my $got_vsn = getfield $gotclogp, 'Version';
1302         printdebug "SKEW CHECK GOT $got_vsn\n";
1303         if (version_compare($got_vsn, $skew_warning_vsn) < 0) {
1304             print STDERR <<END or die $!;
1305
1306 Warning: archive skew detected.  Using the available version:
1307 Archive allegedly contains    $skew_warning_vsn
1308 We were able to obtain only   $got_vsn
1309
1310 END
1311         }
1312     }
1313     if ($lastpush_hash ne $hash) {
1314         my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
1315         if (act_local()) {
1316             cmdoutput @upd_cmd;
1317         } else {
1318             dryrun_report @upd_cmd;
1319         }
1320     }
1321     return 1;
1322 }
1323
1324 sub clone ($) {
1325     my ($dstdir) = @_;
1326     canonicalise_suite();
1327     badusage "dry run makes no sense with clone" unless act_local();
1328     mkdir $dstdir or die "$dstdir $!";
1329     changedir $dstdir;
1330     runcmd @git, qw(init -q);
1331     my $giturl = access_giturl(1);
1332     if (defined $giturl) {
1333         runcmd @git, qw(config), "remote.$remotename.fetch", fetchspec();
1334         open H, "> .git/HEAD" or die $!;
1335         print H "ref: ".lref()."\n" or die $!;
1336         close H or die $!;
1337         runcmd @git, qw(remote add), 'origin', $giturl;
1338     }
1339     if (check_for_git()) {
1340         progress "fetching existing git history";
1341         git_fetch_us();
1342         runcmd_ordryrun_local @git, qw(fetch origin);
1343     } else {
1344         progress "starting new git history";
1345     }
1346     fetch_from_archive() or no_such_package;
1347     my $vcsgiturl = $dsc->{'Vcs-Git'};
1348     if (length $vcsgiturl) {
1349         runcmd @git, qw(remote add vcs-git), $vcsgiturl;
1350     }
1351     runcmd @git, qw(reset --hard), lrref();
1352     printdone "ready for work in $dstdir";
1353 }
1354
1355 sub fetch () {
1356     if (check_for_git()) {
1357         git_fetch_us();
1358     }
1359     fetch_from_archive() or no_such_package();
1360     printdone "fetched into ".lrref();
1361 }
1362
1363 sub pull () {
1364     fetch();
1365     runcmd_ordryrun_local @git, qw(merge -m),"Merge from $csuite [dgit]",
1366         lrref();
1367     printdone "fetched to ".lrref()." and merged into HEAD";
1368 }
1369
1370 sub check_not_dirty () {
1371     return if $ignoredirty;
1372     my @cmd = (@git, qw(diff --quiet HEAD));
1373     printcmd(\*DEBUG,$debugprefix."+",@cmd) if $debug>0;
1374     $!=0; $?=0; system @cmd;
1375     return if !$! && !$?;
1376     if (!$! && $?==256) {
1377         fail "working tree is dirty (does not match HEAD)";
1378     } else {
1379         failedcmd @cmd;
1380     }
1381 }
1382
1383 sub commit_admin ($) {
1384     my ($m) = @_;
1385     progress "$m";
1386     runcmd_ordryrun_local @git, qw(commit -m), $m;
1387 }
1388
1389 sub commit_quilty_patch () {
1390     my $output = cmdoutput @git, qw(status --porcelain);
1391     my %adds;
1392     foreach my $l (split /\n/, $output) {
1393         next unless $l =~ m/\S/;
1394         if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
1395             $adds{$1}++;
1396         }
1397     }
1398     delete $adds{'.pc'}; # if there wasn't one before, don't add it
1399     if (!%adds) {
1400         progress "nothing quilty to commit, ok.";
1401         return;
1402     }
1403     runcmd_ordryrun_local @git, qw(add), sort keys %adds;
1404     commit_admin "Commit Debian 3.0 (quilt) metadata";
1405 }
1406
1407 sub get_source_format () {
1408     if (!open F, "debian/source/format") {
1409         die $! unless $!==&ENOENT;
1410         return '';
1411     }
1412     $_ = <F>;
1413     F->error and die $!;
1414     chomp;
1415     return $_;
1416 }
1417
1418 sub madformat ($) {
1419     my ($format) = @_;
1420     return 0 unless $format eq '3.0 (quilt)';
1421     if ($noquilt) {
1422         progress "Not doing any fixup of \`$format' due to --no-quilt-fixup";
1423         return 0;
1424     }
1425     progress "Format \`$format', checking/updating patch stack";
1426     return 1;
1427 }
1428
1429 sub push_parse_changelog ($) {
1430     my ($clogpfn) = @_;
1431
1432     my $clogp = Dpkg::Control::Hash->new();
1433     $clogp->load($clogpfn) or die;
1434
1435     $package = getfield $clogp, 'Source';
1436     my $cversion = getfield $clogp, 'Version';
1437     my $tag = debiantag($cversion);
1438     runcmd @git, qw(check-ref-format), $tag;
1439
1440     my $dscfn = dscfn($cversion);
1441
1442     return ($clogp, $cversion, $tag, $dscfn);
1443 }
1444
1445 sub push_parse_dsc ($$$) {
1446     my ($dscfn,$dscfnwhat, $cversion) = @_;
1447     $dsc = parsecontrol($dscfn,$dscfnwhat);
1448     my $dversion = getfield $dsc, 'Version';
1449     my $dscpackage = getfield $dsc, 'Source';
1450     ($dscpackage eq $package && $dversion eq $cversion) or
1451         fail "$dscfn is for $dscpackage $dversion".
1452             " but debian/changelog is for $package $cversion";
1453 }
1454
1455 sub push_mktag ($$$$$$$) {
1456     my ($head,$clogp,$tag,
1457         $dscfn,
1458         $changesfile,$changesfilewhat,
1459         $tfn) = @_;
1460
1461     $dsc->{$ourdscfield[0]} = $head;
1462     $dsc->save("$dscfn.tmp") or die $!;
1463
1464     my $changes = parsecontrol($changesfile,$changesfilewhat);
1465     foreach my $field (qw(Source Distribution Version)) {
1466         $changes->{$field} eq $clogp->{$field} or
1467             fail "changes field $field \`$changes->{$field}'".
1468                 " does not match changelog \`$clogp->{$field}'";
1469     }
1470
1471     my $cversion = getfield $clogp, 'Version';
1472     my $clogsuite = getfield $clogp, 'Distribution';
1473
1474     # We make the git tag by hand because (a) that makes it easier
1475     # to control the "tagger" (b) we can do remote signing
1476     my $authline = clogp_authline $clogp;
1477     open TO, '>', $tfn->('.tmp') or die $!;
1478     print TO <<END or die $!;
1479 object $head
1480 type commit
1481 tag $tag
1482 tagger $authline
1483
1484 $package release $cversion for $clogsuite ($csuite) [dgit]
1485 END
1486     close TO or die $!;
1487
1488     my $tagobjfn = $tfn->('.tmp');
1489     if ($sign) {
1490         if (!defined $keyid) {
1491             $keyid = access_cfg('keyid','RETURN-UNDEF');
1492         }
1493         unlink $tfn->('.tmp.asc') or $!==&ENOENT or die $!;
1494         my @sign_cmd = (@gpg, qw(--detach-sign --armor));
1495         push @sign_cmd, qw(-u),$keyid if defined $keyid;
1496         push @sign_cmd, $tfn->('.tmp');
1497         runcmd_ordryrun @sign_cmd;
1498         if (act_scary()) {
1499             $tagobjfn = $tfn->('.signed.tmp');
1500             runcmd shell_cmd "exec >$tagobjfn", qw(cat --),
1501                 $tfn->('.tmp'), $tfn->('.tmp.asc');
1502         }
1503     }
1504
1505     return ($tagobjfn);
1506 }
1507
1508 sub sign_changes ($) {
1509     my ($changesfile) = @_;
1510     if ($sign) {
1511         my @debsign_cmd = @debsign;
1512         push @debsign_cmd, "-k$keyid" if defined $keyid;
1513         push @debsign_cmd, "-p$gpg[0]" if $gpg[0] ne 'gpg';
1514         push @debsign_cmd, $changesfile;
1515         runcmd_ordryrun @debsign_cmd;
1516     }
1517 }
1518
1519 sub dopush () {
1520     printdebug "actually entering push\n";
1521     prep_ud();
1522
1523     access_giturl(); # check that success is vaguely likely
1524
1525     my $clogpfn = ".git/dgit/changelog.822.tmp";
1526     runcmd shell_cmd "exec >$clogpfn", qw(dpkg-parsechangelog);
1527
1528     responder_send_file('parsed-changelog', $clogpfn);
1529
1530     my ($clogp, $cversion, $tag, $dscfn) =
1531         push_parse_changelog("$clogpfn");
1532
1533     my $dscpath = "$buildproductsdir/$dscfn";
1534     stat_exists $dscpath or
1535         fail "looked for .dsc $dscfn, but $!;".
1536             " maybe you forgot to build";
1537
1538     responder_send_file('dsc', $dscpath);
1539
1540     push_parse_dsc($dscpath, $dscfn, $cversion);
1541
1542     my $format = getfield $dsc, 'Format';
1543     printdebug "format $format\n";
1544     if (madformat($format)) {
1545         commit_quilty_patch();
1546     }
1547     check_not_dirty();
1548     changedir $ud;
1549     progress "checking that $dscfn corresponds to HEAD";
1550     runcmd qw(dpkg-source -x --),
1551         $dscpath =~ m#^/# ? $dscpath : "../../../$dscpath";
1552     my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1553     changedir '../../../..';
1554     my $diffopt = $debug>0 ? '--exit-code' : '--quiet';
1555     my @diffcmd = (@git, qw(diff), $diffopt, $tree);
1556     printcmd \*DEBUG,$debugprefix."+",@diffcmd;
1557     $!=0; $?=0;
1558     my $r = system @diffcmd;
1559     if ($r) {
1560         if ($r==256) {
1561             fail "$dscfn specifies a different tree to your HEAD commit;".
1562                 " perhaps you forgot to build".
1563                 ($diffopt eq '--exit-code' ? "" :
1564                  " (run with -D to see full diff output)");
1565         } else {
1566             failedcmd @diffcmd;
1567         }
1568     }
1569 #fetch from alioth
1570 #do fast forward check and maybe fake merge
1571 #    if (!is_fast_fwd(mainbranch
1572 #    runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
1573 #        map { lref($_).":".rref($_) }
1574 #        (uploadbranch());
1575     my $head = rev_parse('HEAD');
1576     if (!$changesfile) {
1577         my $multi = "$buildproductsdir/".
1578             "${package}_".(stripepoch $cversion)."_multi.changes";
1579         if (stat_exists "$multi") {
1580             $changesfile = $multi;
1581         } else {
1582             my $pat = "${package}_".(stripepoch $cversion)."_*.changes";
1583             my @cs = glob "$buildproductsdir/$pat";
1584             fail "failed to find unique changes file".
1585                 " (looked for $pat in $buildproductsdir, or $multi);".
1586                 " perhaps you need to use dgit -C"
1587                 unless @cs==1;
1588             ($changesfile) = @cs;
1589         }
1590     } else {
1591         $changesfile = "$buildproductsdir/$changesfile";
1592     }
1593
1594     responder_send_file('changes',$changesfile);
1595     responder_send_command("param head $head");
1596     responder_send_command("param csuite $csuite");
1597
1598     my $tfn = sub { ".git/dgit/tag$_[0]"; };
1599     my $tagobjfn;
1600
1601     if ($we_are_responder) {
1602         $tagobjfn = $tfn->('.signed.tmp');
1603         responder_receive_files('signed-tag', $tagobjfn);
1604     } else {
1605         $tagobjfn =
1606             push_mktag($head,$clogp,$tag,
1607                        $dscpath,
1608                        $changesfile,$changesfile,
1609                        $tfn);
1610     }
1611
1612     my $tag_obj_hash = cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
1613     runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
1614     runcmd_ordryrun_local @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
1615     runcmd_ordryrun @git, qw(tag -v --), $tag;
1616
1617     if (!check_for_git()) {
1618         create_remote_git_repo();
1619     }
1620     runcmd_ordryrun @git, qw(push),access_giturl(),
1621         "HEAD:".rrref(), "refs/tags/$tag";
1622     runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), 'HEAD';
1623
1624     if ($we_are_responder) {
1625         my $dryrunsuffix = act_local() ? "" : ".tmp";
1626         responder_receive_files('signed-dsc-changes',
1627                                 "$dscpath$dryrunsuffix",
1628                                 "$changesfile$dryrunsuffix");
1629     } else {
1630         if (act_local()) {
1631             rename "$dscpath.tmp",$dscpath or die "$dscfn $!";
1632         } else {
1633             progress "[new .dsc left in $dscpath.tmp]";
1634         }
1635         sign_changes $changesfile;
1636     }
1637
1638     my $host = access_cfg('upload-host','RETURN-UNDEF');
1639     my @hostarg = defined($host) ? ($host,) : ();
1640     runcmd_ordryrun @dput, @hostarg, $changesfile;
1641     printdone "pushed and uploaded $cversion";
1642
1643     responder_send_command("complete");
1644 }
1645
1646 sub cmd_clone {
1647     parseopts();
1648     my $dstdir;
1649     badusage "-p is not allowed with clone; specify as argument instead"
1650         if defined $package;
1651     if (@ARGV==1) {
1652         ($package) = @ARGV;
1653     } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
1654         ($package,$isuite) = @ARGV;
1655     } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
1656         ($package,$dstdir) = @ARGV;
1657     } elsif (@ARGV==3) {
1658         ($package,$isuite,$dstdir) = @ARGV;
1659     } else {
1660         badusage "incorrect arguments to dgit clone";
1661     }
1662     $dstdir ||= "$package";
1663
1664     if (stat_exists $dstdir) {
1665         fail "$dstdir already exists";
1666     }
1667
1668     my $cwd_remove;
1669     if ($rmonerror && !$dryrun_level) {
1670         $cwd_remove= getcwd();
1671         unshift @end, sub { 
1672             return unless defined $cwd_remove;
1673             if (!chdir "$cwd_remove") {
1674                 return if $!==&ENOENT;
1675                 die "chdir $cwd_remove: $!";
1676             }
1677             rmtree($dstdir) or die "remove $dstdir: $!\n";
1678         };
1679     }
1680
1681     clone($dstdir);
1682     $cwd_remove = undef;
1683 }
1684
1685 sub branchsuite () {
1686     my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
1687     if ($branch =~ m#$lbranch_re#o) {
1688         return $1;
1689     } else {
1690         return undef;
1691     }
1692 }
1693
1694 sub fetchpullargs () {
1695     if (!defined $package) {
1696         my $sourcep = parsecontrol('debian/control','debian/control');
1697         $package = getfield $sourcep, 'Source';
1698     }
1699     if (@ARGV==0) {
1700 #       $isuite = branchsuite();  # this doesn't work because dak hates canons
1701         if (!$isuite) {
1702             my $clogp = parsechangelog();
1703             $isuite = getfield $clogp, 'Distribution';
1704         }
1705         canonicalise_suite();
1706         progress "fetching from suite $csuite";
1707     } elsif (@ARGV==1) {
1708         ($isuite) = @ARGV;
1709         canonicalise_suite();
1710     } else {
1711         badusage "incorrect arguments to dgit fetch or dgit pull";
1712     }
1713 }
1714
1715 sub cmd_fetch {
1716     parseopts();
1717     fetchpullargs();
1718     fetch();
1719 }
1720
1721 sub cmd_pull {
1722     parseopts();
1723     fetchpullargs();
1724     pull();
1725 }
1726
1727 sub cmd_push {
1728     parseopts();
1729     badusage "-p is not allowed with dgit push" if defined $package;
1730     check_not_dirty();
1731     my $clogp = parsechangelog();
1732     $package = getfield $clogp, 'Source';
1733     my $specsuite;
1734     if (@ARGV==0) {
1735     } elsif (@ARGV==1) {
1736         ($specsuite) = (@ARGV);
1737     } else {
1738         badusage "incorrect arguments to dgit push";
1739     }
1740     $isuite = getfield $clogp, 'Distribution';
1741     if ($new_package) {
1742         local ($package) = $existing_package; # this is a hack
1743         canonicalise_suite();
1744     }
1745     if (defined $specsuite && $specsuite ne $isuite) {
1746         canonicalise_suite();
1747         $csuite eq $specsuite or
1748             fail "dgit push: changelog specifies $isuite ($csuite)".
1749                 " but command line specifies $specsuite";
1750     }
1751     if (check_for_git()) {
1752         git_fetch_us();
1753     }
1754     if (fetch_from_archive()) {
1755         is_fast_fwd(lrref(), 'HEAD') or
1756             fail "dgit push: HEAD is not a descendant".
1757                 " of the archive's version.\n".
1758                 "$us: To overwrite it, use git merge -s ours ".lrref().".";
1759     } else {
1760         $new_package or
1761             fail "package appears to be new in this suite;".
1762                 " if this is intentional, use --new";
1763     }
1764     dopush();
1765 }
1766
1767 #---------- remote commands' implementation ----------
1768
1769 sub cmd_remote_push_build_host {
1770     my ($nrargs) = shift @ARGV;
1771     my (@rargs) = @ARGV[0..$nrargs-1];
1772     @ARGV = @ARGV[$nrargs..$#ARGV];
1773     die unless @rargs;
1774     my ($dir,$vsnwant) = @rargs;
1775     # vsnwant is a comma-separated list; we report which we have
1776     # chosen in our ready response (so other end can tell if they
1777     # offered several)
1778     $debugprefix = ' ';
1779     $we_are_responder = 1;
1780
1781     open PI, "<&STDIN" or die $!;
1782     open STDIN, "/dev/null" or die $!;
1783     open PO, ">&STDOUT" or die $!;
1784     autoflush PO 1;
1785     open STDOUT, ">&STDERR" or die $!;
1786     autoflush STDOUT 1;
1787
1788     $vsnwant //= 1;
1789     fail "build host has dgit rpush protocol version".
1790         " $rpushprotovsn but invocation host has $vsnwant"
1791         unless grep { $rpushprotovsn eq $_ } split /,/, $vsnwant;
1792
1793     responder_send_command("dgit-remote-push-ready $rpushprotovsn");
1794
1795     changedir $dir;
1796     &cmd_push;
1797 }
1798
1799 sub cmd_remote_push_responder { cmd_remote_push_build_host(); }
1800 # ... for compatibility with proto vsn.1 dgit (just so that user gets
1801 #     a good error message)
1802
1803 our $i_tmp;
1804
1805 sub i_cleanup {
1806     local ($@, $?);
1807     my $report = i_child_report();
1808     if (defined $report) {
1809         printdebug "($report)\n";
1810     } elsif ($i_child_pid) {
1811         printdebug "(killing build host child $i_child_pid)\n";
1812         kill 15, $i_child_pid;
1813     }
1814     if (defined $i_tmp && !defined $initiator_tempdir) {
1815         changedir "/";
1816         eval { rmtree $i_tmp; };
1817     }
1818 }
1819
1820 END { i_cleanup(); }
1821
1822 sub i_method {
1823     my ($base,$selector,@args) = @_;
1824     $selector =~ s/\-/_/g;
1825     { no strict qw(refs); &{"${base}_${selector}"}(@args); }
1826 }
1827
1828 sub cmd_rpush {
1829     my $host = nextarg;
1830     my $dir;
1831     if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
1832         $host = $1;
1833         $dir = $'; #';
1834     } else {
1835         $dir = nextarg;
1836     }
1837     $dir =~ s{^-}{./-};
1838     my @rargs = ($dir,$rpushprotovsn);
1839     my @rdgit;
1840     push @rdgit, @dgit;
1841     push @rdgit, @ropts;
1842     push @rdgit, qw(remote-push-build-host), (scalar @rargs), @rargs;
1843     push @rdgit, @ARGV;
1844     my @cmd = (@ssh, $host, shellquote @rdgit);
1845     printcmd \*DEBUG,$debugprefix."+",@cmd;
1846
1847     if (defined $initiator_tempdir) {
1848         rmtree $initiator_tempdir;
1849         mkdir $initiator_tempdir, 0700 or die "$initiator_tempdir: $!";
1850         $i_tmp = $initiator_tempdir;
1851     } else {
1852         $i_tmp = tempdir();
1853     }
1854     $i_child_pid = open2(\*RO, \*RI, @cmd);
1855     changedir $i_tmp;
1856     initiator_expect { m/^dgit-remote-push-ready/ };
1857     for (;;) {
1858         my ($icmd,$iargs) = initiator_expect {
1859             m/^(\S+)(?: (.*))?$/;
1860             ($1,$2);
1861         };
1862         i_method "i_resp", $icmd, $iargs;
1863     }
1864 }
1865
1866 sub i_resp_progress ($) {
1867     my ($rhs) = @_;
1868     my $msg = protocol_read_bytes \*RO, $rhs;
1869     progress $msg;
1870 }
1871
1872 sub i_resp_complete {
1873     my $pid = $i_child_pid;
1874     $i_child_pid = undef; # prevents killing some other process with same pid
1875     printdebug "waiting for build host child $pid...\n";
1876     my $got = waitpid $pid, 0;
1877     die $! unless $got == $pid;
1878     die "build host child failed $?" if $?;
1879
1880     i_cleanup();
1881     printdebug "all done\n";
1882     exit 0;
1883 }
1884
1885 sub i_resp_file ($) {
1886     my ($keyword) = @_;
1887     my $localname = i_method "i_localname", $keyword;
1888     my $localpath = "$i_tmp/$localname";
1889     stat_exists $localpath and
1890         badproto \*RO, "file $keyword ($localpath) twice";
1891     protocol_receive_file \*RO, $localpath;
1892     i_method "i_file", $keyword;
1893 }
1894
1895 our %i_param;
1896
1897 sub i_resp_param ($) {
1898     $_[0] =~ m/^(\S+) (.*)$/ or badproto \*RO, "bad param spec";
1899     $i_param{$1} = $2;
1900 }
1901
1902 our %i_wanted;
1903
1904 sub i_resp_want ($) {
1905     my ($keyword) = @_;
1906     die "$keyword ?" if $i_wanted{$keyword}++;
1907     my @localpaths = i_method "i_want", $keyword;
1908     printdebug "[[  $keyword @localpaths\n";
1909     foreach my $localpath (@localpaths) {
1910         protocol_send_file \*RI, $localpath;
1911     }
1912     print RI "files-end\n" or die $!;
1913 }
1914
1915 our ($i_clogp, $i_version, $i_tag, $i_dscfn, $i_changesfn);
1916
1917 sub i_localname_parsed_changelog {
1918     return "remote-changelog.822";
1919 }
1920 sub i_file_parsed_changelog {
1921     ($i_clogp, $i_version, $i_tag, $i_dscfn) =
1922         push_parse_changelog "$i_tmp/remote-changelog.822";
1923     die if $i_dscfn =~ m#/|^\W#;
1924 }
1925
1926 sub i_localname_dsc {
1927     defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
1928     return $i_dscfn;
1929 }
1930 sub i_file_dsc { }
1931
1932 sub i_localname_changes {
1933     defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
1934     $i_changesfn = $i_dscfn;
1935     $i_changesfn =~ s/\.dsc$/_dgit.changes/ or die;
1936     return $i_changesfn;
1937 }
1938 sub i_file_changes { }
1939
1940 sub i_want_signed_tag {
1941     printdebug Dumper(\%i_param, $i_dscfn);
1942     defined $i_param{'head'} && defined $i_dscfn && defined $i_clogp
1943         && defined $i_param{'csuite'}
1944         or badproto \*RO, "premature desire for signed-tag";
1945     my $head = $i_param{'head'};
1946     die if $head =~ m/[^0-9a-f]/ || $head !~ m/^../;
1947
1948     die unless $i_param{'csuite'} =~ m/^$suite_re$/;
1949     $csuite = $&;
1950     push_parse_dsc $i_dscfn, 'remote dsc', $i_version;
1951
1952     my $tagobjfn =
1953         push_mktag $head, $i_clogp, $i_tag,
1954             $i_dscfn,
1955             $i_changesfn, 'remote changes',
1956             sub { "tag$_[0]"; };
1957
1958     return $tagobjfn;
1959 }
1960
1961 sub i_want_signed_dsc_changes {
1962     rename "$i_dscfn.tmp","$i_dscfn" or die "$i_dscfn $!";
1963     sign_changes $i_changesfn;
1964     return ($i_dscfn, $i_changesfn);
1965 }
1966
1967 #---------- building etc. ----------
1968
1969 our $version;
1970 our $sourcechanges;
1971 our $dscfn;
1972
1973 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
1974
1975 sub build_maybe_quilt_fixup () {
1976     my $format=get_source_format;
1977     return unless madformat $format;
1978     # sigh
1979
1980     # Our objective is:
1981     #  - honour any existing .pc in case it has any strangeness
1982     #  - determine the git commit corresponding to the tip of
1983     #    the patch stack (if there is one)
1984     #  - if there is such a git commit, convert each subsequent
1985     #    git commit into a quilt patch with dpkg-source --commit
1986     #  - otherwise convert all the differences in the tree into
1987     #    a single git commit
1988     #
1989     # To do this we:
1990
1991     # Our git tree doesn't necessarily contain .pc.  (Some versions of
1992     # dgit would include the .pc in the git tree.)  If there isn't
1993     # one, we need to generate one by unpacking the patches that we
1994     # have.
1995     #
1996     # We first look for a .pc in the git tree.  If there is one, we
1997     # will use it.  (This is not the normal case.)
1998     #
1999     # Otherwise need to regenerate .pc so that dpkg-source --commit
2000     # can work.  We do this as follows:
2001     #     1. Collect all relevant .orig from parent directory
2002     #     2. Generate a debian.tar.gz out of
2003     #         debian/{patches,rules,source/format}
2004     #     3. Generate a fake .dsc containing just these fields:
2005     #          Format Source Version Files
2006     #     4. Extract the fake .dsc
2007     #        Now the fake .dsc has a .pc directory.
2008     # (In fact we do this in every case, because in future we will
2009     # want to search for a good base commit for generating patches.)
2010     #
2011     # Then we can actually do the dpkg-source --commit
2012     #     1. Make a new working tree with the same object
2013     #        store as our main tree and check out the main
2014     #        tree's HEAD.
2015     #     2. Copy .pc from the fake's extraction, if necessary
2016     #     3. Run dpkg-source --commit
2017     #     4. If the result has changes to debian/, then
2018     #          - git-add them them
2019     #          - git-add .pc if we had a .pc in-tree
2020     #          - git-commit
2021     #     5. If we had a .pc in-tree, delete it, and git-commit
2022     #     6. Back in the main tree, fast forward to the new HEAD
2023
2024     my $clogp = parsechangelog();
2025     my $headref = rev_parse('HEAD');
2026
2027     prep_ud();
2028     changedir $ud;
2029
2030     my $upstreamversion=$version;
2031     $upstreamversion =~ s/-[^-]*$//;
2032
2033     my $fakeversion="$upstreamversion-~~DGITFAKE";
2034
2035     my $fakedsc=new IO::File 'fake.dsc', '>' or die $!;
2036     print $fakedsc <<END or die $!;
2037 Format: 3.0 (quilt)
2038 Source: $package
2039 Version: $fakeversion
2040 Files:
2041 END
2042
2043     my $dscaddfile=sub {
2044         my ($b) = @_;
2045         
2046         my $md = new Digest::MD5;
2047
2048         my $fh = new IO::File $b, '<' or die "$b $!";
2049         stat $fh or die $!;
2050         my $size = -s _;
2051
2052         $md->addfile($fh);
2053         print $fakedsc " ".$md->hexdigest." $size $b\n" or die $!;
2054     };
2055
2056     foreach my $f (<../../../../*>) { #/){
2057         my $b=$f; $b =~ s{.*/}{};
2058         next unless is_orig_file $b, srcfn $upstreamversion,'';
2059         link $f, $b or die "$b $!";
2060         $dscaddfile->($b);
2061     }
2062
2063     my @files=qw(debian/source/format debian/rules);
2064     if (stat_exists '../../../debian/patches') {
2065         push @files, 'debian/patches';
2066     }
2067
2068     my $debtar= srcfn $fakeversion,'.debian.tar.gz';
2069     runcmd qw(env GZIP=-1 tar -zcf), "./$debtar", qw(-C ../../..), @files;
2070
2071     $dscaddfile->($debtar);
2072     close $fakedsc or die $!;
2073
2074     runcmd qw(sh -ec), 'exec dpkg-source --no-check -x fake.dsc >/dev/null';
2075
2076     my $fakexdir= $package.'-'.(stripepoch $upstreamversion);
2077     rename $fakexdir, "fake" or die "$fakexdir $!";
2078
2079     mkdir "work" or die $!;
2080     changedir "work";
2081     mktree_in_ud_here();
2082     runcmd @git, qw(reset --hard), $headref;
2083
2084     my $mustdeletepc=0;
2085     if (stat_exists ".pc") {
2086         -d _ or die;
2087         progress "Tree already contains .pc - will use it then delete it.";
2088         $mustdeletepc=1;
2089     } else {
2090         rename '../fake/.pc','.pc' or die $!;
2091     }
2092
2093     my $author = getfield $clogp, 'Maintainer';
2094     my $time = time;
2095     my $ncommits = 3;
2096     my $patchname = "auto-$version-$headref-$time";
2097     my $msg = cmdoutput @git, qw(log), "-n$ncommits";
2098     mkpath '.git/dgit';
2099     my $descfn = ".git/dgit/quilt-description.tmp";
2100     open O, '>', $descfn or die "$descfn: $!";
2101     $msg =~ s/\n/\n /g;
2102     $msg =~ s/^\s+$/ ./mg;
2103     print O <<END or die $!;
2104 Description: Automatically generated patch ($clogp->{Version})
2105  Last (up to) $ncommits git changes, FYI:
2106  .
2107  $msg
2108 Author: $author
2109
2110 ---
2111
2112 END
2113     close O or die $!;
2114     {
2115         local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
2116         local $ENV{'VISUAL'} = $ENV{'EDITOR'};
2117         local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
2118         runcmd_ordryrun_local @dpkgsource, qw(--commit .), $patchname;
2119     }
2120
2121     if (!open P, '>>', ".pc/applied-patches") {
2122         $!==&ENOENT or die $!;
2123     } else {
2124         close P;
2125     }
2126
2127     commit_quilty_patch();
2128
2129     if ($mustdeletepc) {
2130         runcmd @git, qw(rm -rq .pc);
2131         commit_admin "Commit removal of .pc (quilt series tracking data)";
2132     }
2133
2134     changedir '../../../..';
2135     runcmd @git, qw(pull --ff-only -q .git/dgit/unpack/work master);
2136 }
2137
2138 sub quilt_fixup_editor () {
2139     my $descfn = $ENV{$fakeeditorenv};
2140     my $editing = $ARGV[$#ARGV];
2141     open I1, '<', $descfn or die "$descfn: $!";
2142     open I2, '<', $editing or die "$editing: $!";
2143     unlink $editing or die "$editing: $!";
2144     open O, '>', $editing or die "$editing: $!";
2145     while (<I1>) { print O or die $!; } I1->error and die $!;
2146     my $copying = 0;
2147     while (<I2>) {
2148         $copying ||= m/^\-\-\- /;
2149         next unless $copying;
2150         print O or die $!;
2151     }
2152     I2->error and die $!;
2153     close O or die $1;
2154     exit 0;
2155 }
2156
2157 sub clean_tree () {
2158     if ($cleanmode eq 'dpkg-source') {
2159         runcmd_ordryrun_local @dpkgbuildpackage, qw(-T clean);
2160     } elsif ($cleanmode eq 'git') {
2161         runcmd_ordryrun_local @git, qw(clean -xdf);
2162     } elsif ($cleanmode eq 'none') {
2163     } else {
2164         die "$cleanmode ?";
2165     }
2166 }
2167
2168 sub cmd_clean () {
2169     badusage "clean takes no additional arguments" if @ARGV;
2170     clean_tree();
2171 }
2172
2173 sub build_prep () {
2174     badusage "-p is not allowed when building" if defined $package;
2175     check_not_dirty();
2176     clean_tree();
2177     my $clogp = parsechangelog();
2178     $isuite = getfield $clogp, 'Distribution';
2179     $package = getfield $clogp, 'Source';
2180     $version = getfield $clogp, 'Version';
2181     build_maybe_quilt_fixup();
2182 }
2183
2184 sub changesopts () {
2185     my @opts =@changesopts[1..$#changesopts];
2186     if (!defined $changes_since_version) {
2187         my @vsns = archive_query('archive_query');
2188         my @quirk = access_quirk();
2189         if ($quirk[0] eq 'backports') {
2190             local $isuite = $quirk[2];
2191             local $csuite;
2192             canonicalise_suite();
2193             push @vsns, archive_query('archive_query');
2194         }
2195         if (@vsns) {
2196             @vsns = map { $_->[0] } @vsns;
2197             @vsns = sort { -version_compare($a, $b) } @vsns;
2198             $changes_since_version = $vsns[0];
2199             progress "changelog will contain changes since $vsns[0]";
2200         } else {
2201             $changes_since_version = '_';
2202             progress "package seems new, not specifying -v<version>";
2203         }
2204     }
2205     if ($changes_since_version ne '_') {
2206         unshift @opts, "-v$changes_since_version";
2207     }
2208     return @opts;
2209 }
2210
2211 sub cmd_build {
2212     build_prep();
2213     runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc), changesopts(), @ARGV;
2214     printdone "build successful\n";
2215 }
2216
2217 sub cmd_git_build {
2218     build_prep();
2219     my @cmd =
2220         (qw(git-buildpackage -us -uc --git-no-sign-tags),
2221          "--git-builder=@dpkgbuildpackage");
2222     unless (grep { m/^--git-debian-branch|^--git-ignore-branch/ } @ARGV) {
2223         canonicalise_suite();
2224         push @cmd, "--git-debian-branch=".lbranch();
2225     }
2226     push @cmd, changesopts();
2227     runcmd_ordryrun_local @cmd, @ARGV;
2228     printdone "build successful\n";
2229 }
2230
2231 sub build_source {
2232     build_prep();
2233     $sourcechanges = "${package}_".(stripepoch $version)."_source.changes";
2234     $dscfn = dscfn($version);
2235     if ($cleanmode eq 'dpkg-source') {
2236         runcmd_ordryrun_local (@dpkgbuildpackage, qw(-us -uc -S)),
2237             changesopts();
2238     } else {
2239         my $pwd = must_getcwd();
2240         my $leafdir = basename $pwd;
2241         changedir "..";
2242         runcmd_ordryrun_local @dpkgsource, qw(-b --), $leafdir;
2243         changedir $pwd;
2244         runcmd_ordryrun_local qw(sh -ec),
2245             'exec >$1; shift; exec "$@"','x',
2246             "../$sourcechanges",
2247             @dpkggenchanges, qw(-S), changesopts();
2248     }
2249 }
2250
2251 sub cmd_build_source {
2252     badusage "build-source takes no additional arguments" if @ARGV;
2253     build_source();
2254     printdone "source built, results in $dscfn and $sourcechanges";
2255 }
2256
2257 sub cmd_sbuild {
2258     build_source();
2259     changedir "..";
2260     my $pat = "${package}_".(stripepoch $version)."_*.changes";
2261     if (act_local()) {
2262         stat_exist $dscfn or fail "$dscfn (in parent directory): $!";
2263         stat_exists $sourcechanges
2264             or fail "$sourcechanges (in parent directory): $!";
2265         foreach my $cf (glob $pat) {
2266             next if $cf eq $sourcechanges;
2267             unlink $cf or fail "remove $cf: $!";
2268         }
2269     }
2270     runcmd_ordryrun_local @sbuild, @ARGV, qw(-d), $isuite, $dscfn;
2271     my @changesfiles = glob $pat;
2272     @changesfiles = sort {
2273         ($b =~ m/_source\.changes$/ <=> $a =~ m/_source\.changes$/)
2274             or $a cmp $b
2275     } @changesfiles;
2276     fail "wrong number of different changes files (@changesfiles)"
2277         unless @changesfiles;
2278     runcmd_ordryrun_local @mergechanges, @changesfiles;
2279     my $multichanges = "${package}_".(stripepoch $version)."_multi.changes";
2280     if (act_local()) {
2281         stat_exists $multichanges or fail "$multichanges: $!";
2282     }
2283     printdone "build successful, results in $multichanges\n" or die $!;
2284 }    
2285
2286 sub cmd_quilt_fixup {
2287     badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
2288     my $clogp = parsechangelog();
2289     $version = getfield $clogp, 'Version';
2290     $package = getfield $clogp, 'Source';
2291     build_maybe_quilt_fixup();
2292 }
2293
2294 #---------- argument parsing and main program ----------
2295
2296 sub cmd_version {
2297     print "dgit version $our_version\n" or die $!;
2298     exit 0;
2299 }
2300
2301 sub parseopts () {
2302     my $om;
2303
2304     if (defined $ENV{'DGIT_SSH'}) {
2305         @ssh = string_to_ssh $ENV{'DGIT_SSH'};
2306     } elsif (defined $ENV{'GIT_SSH'}) {
2307         @ssh = ($ENV{'GIT_SSH'});
2308     }
2309
2310     while (@ARGV) {
2311         last unless $ARGV[0] =~ m/^-/;
2312         $_ = shift @ARGV;
2313         last if m/^--?$/;
2314         if (m/^--/) {
2315             if (m/^--dry-run$/) {
2316                 push @ropts, $_;
2317                 $dryrun_level=2;
2318             } elsif (m/^--damp-run$/) {
2319                 push @ropts, $_;
2320                 $dryrun_level=1;
2321             } elsif (m/^--no-sign$/) {
2322                 push @ropts, $_;
2323                 $sign=0;
2324             } elsif (m/^--help$/) {
2325                 cmd_help();
2326             } elsif (m/^--version$/) {
2327                 cmd_version();
2328             } elsif (m/^--new$/) {
2329                 push @ropts, $_;
2330                 $new_package=1;
2331             } elsif (m/^--since-version=([^_]+|_)$/) {
2332                 push @ropts, $_;
2333                 $changes_since_version = $1;
2334             } elsif (m/^--([-0-9a-z]+)=(.*)/s &&
2335                      ($om = $opts_opt_map{$1}) &&
2336                      length $om->[0]) {
2337                 push @ropts, $_;
2338                 $om->[0] = $2;
2339             } elsif (m/^--([-0-9a-z]+):(.*)/s &&
2340                      !$opts_opt_cmdonly{$1} &&
2341                      ($om = $opts_opt_map{$1})) {
2342                 push @ropts, $_;
2343                 push @$om, $2;
2344             } elsif (m/^--existing-package=(.*)/s) {
2345                 push @ropts, $_;
2346                 $existing_package = $1;
2347             } elsif (m/^--initiator-tempdir=(.*)/s) {
2348                 $initiator_tempdir = $1;
2349                 $initiator_tempdir =~ m#^/# or
2350                     badusage "--initiator-tempdir must be used specify an".
2351                         " absolute, not relative, directory."
2352             } elsif (m/^--distro=(.*)/s) {
2353                 push @ropts, $_;
2354                 $idistro = $1;
2355             } elsif (m/^--build-products-dir=(.*)/s) {
2356                 push @ropts, $_;
2357                 $buildproductsdir = $1;
2358             } elsif (m/^--clean=(dpkg-source|git|none)$/s) {
2359                 push @ropts, $_;
2360                 $cleanmode = $1;
2361             } elsif (m/^--clean=(.*)$/s) {
2362                 badusage "unknown cleaning mode \`$1'";
2363             } elsif (m/^--ignore-dirty$/s) {
2364                 push @ropts, $_;
2365                 $ignoredirty = 1;
2366             } elsif (m/^--no-quilt-fixup$/s) {
2367                 push @ropts, $_;
2368                 $noquilt = 1;
2369             } elsif (m/^--no-rm-on-error$/s) {
2370                 push @ropts, $_;
2371                 $rmonerror = 0;
2372             } else {
2373                 badusage "unknown long option \`$_'";
2374             }
2375         } else {
2376             while (m/^-./s) {
2377                 if (s/^-n/-/) {
2378                     push @ropts, $&;
2379                     $dryrun_level=2;
2380                 } elsif (s/^-L/-/) {
2381                     push @ropts, $&;
2382                     $dryrun_level=1;
2383                 } elsif (s/^-h/-/) {
2384                     cmd_help();
2385                 } elsif (s/^-D/-/) {
2386                     push @ropts, $&;
2387                     open DEBUG, ">&STDERR" or die $!;
2388                     autoflush DEBUG 1;
2389                     $debug++;
2390                 } elsif (s/^-N/-/) {
2391                     push @ropts, $&;
2392                     $new_package=1;
2393                 } elsif (s/^-v([^_]+|_)$//s) {
2394                     push @ropts, $&;
2395                     $changes_since_version = $1;
2396                 } elsif (m/^-m/) {
2397                     push @ropts, $&;
2398                     push @changesopts, $_;
2399                     $_ = '';
2400                 } elsif (s/^-c(.*=.*)//s) {
2401                     push @ropts, $&;
2402                     push @git, '-c', $1;
2403                 } elsif (s/^-d(.*)//s) {
2404                     push @ropts, $&;
2405                     $idistro = $1;
2406                 } elsif (s/^-C(.*)//s) {
2407                     push @ropts, $&;
2408                     $changesfile = $1;
2409                     if ($changesfile =~ s#^(.*)/##) {
2410                         $buildproductsdir = $1;
2411                     }
2412                 } elsif (s/^-k(.*)//s) {
2413                     $keyid=$1;
2414                 } elsif (s/^-wn//s) {
2415                     push @ropts, $&;
2416                     $cleanmode = 'none';
2417                 } elsif (s/^-wg//s) {
2418                     push @ropts, $&;
2419                     $cleanmode = 'git';
2420                 } elsif (s/^-wd//s) {
2421                     push @ropts, $&;
2422                     $cleanmode = 'dpkg-source';
2423                 } else {
2424                     badusage "unknown short option \`$_'";
2425                 }
2426             }
2427         }
2428     }
2429 }
2430
2431 if ($ENV{$fakeeditorenv}) {
2432     quilt_fixup_editor();
2433 }
2434
2435 parseopts();
2436 print STDERR "DRY RUN ONLY\n" if $dryrun_level > 1;
2437 print STDERR "DAMP RUN - WILL MAKE LOCAL (UNSIGNED) CHANGES\n"
2438     if $dryrun_level == 1;
2439 if (!@ARGV) {
2440     print STDERR $helpmsg or die $!;
2441     exit 8;
2442 }
2443 my $cmd = shift @ARGV;
2444 $cmd =~ y/-/_/;
2445
2446 my $fn = ${*::}{"cmd_$cmd"};
2447 $fn or badusage "unknown operation $cmd";
2448 $fn->();