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