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