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