3 # Integration between git and Debian-style archives
5 # Copyright (C)2013 Ian Jackson
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.
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.
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/>.
21 $SIG{__WARN__} = sub { die $_[0]; };
26 use Dpkg::Control::Hash;
28 use File::Temp qw(tempdir);
38 our $our_version = 'UNRELEASED'; ###substituted###
40 our $rpushprotovsn = 2;
42 our $isuite = 'unstable';
48 our $dryrun_level = 0;
50 our $buildproductsdir = '..';
56 our $existing_package = 'dpkg';
57 our $cleanmode = 'dpkg-source';
58 our $changes_since_version;
60 our $quilt_modes_re = 'linear|smash|auto|nofix|nocheck';
61 our $we_are_responder;
62 our $initiator_tempdir;
64 our %format_ok = map { $_=>1 } ("1.0","3.0 (native)","3.0 (quilt)");
66 our $suite_re = '[-+.0-9a-z]+';
69 our (@dget) = qw(dget);
70 our (@curl) = qw(curl -f);
71 our (@dput) = qw(dput);
72 our (@debsign) = qw(debsign);
74 our (@sbuild) = qw(sbuild -A);
76 our (@dgit) = qw(dgit);
77 our (@dpkgbuildpackage) = qw(dpkg-buildpackage -i\.git/ -I.git);
78 our (@dpkgsource) = qw(dpkg-source -i\.git/ -I.git);
79 our (@dpkggenchanges) = qw(dpkg-genchanges);
80 our (@mergechanges) = qw(mergechanges -f);
81 our (@changesopts) = ('');
83 our %opts_opt_map = ('dget' => \@dget, # accept for compatibility
86 'debsign' => \@debsign,
91 'dpkg-source' => \@dpkgsource,
92 'dpkg-buildpackage' => \@dpkgbuildpackage,
93 'dpkg-genchanges' => \@dpkggenchanges,
94 'ch' => \@changesopts,
95 'mergechanges' => \@mergechanges);
97 our %opts_opt_cmdonly = ('gpg' => 1);
103 our $remotename = 'dgit';
104 our @ourdscfield = qw(Dgit Vcs-Dgit-Master);
108 sub lbranch () { return "$branchprefix/$csuite"; }
109 my $lbranch_re = '^refs/heads/'.$branchprefix.'/([^/.]+)$';
110 sub lref () { return "refs/heads/".lbranch(); }
111 sub lrref () { return "refs/remotes/$remotename/".server_branch($csuite); }
112 sub rrref () { return server_ref($csuite); }
122 return "${package}_".(stripepoch $vsn).$sfx
127 return srcfn($vsn,".dsc");
136 foreach my $f (@end) {
138 warn "$us: cleanup: $@" if length $@;
142 sub badcfg { print STDERR "$us: invalid configuration: @_\n"; exit 12; }
144 sub no_such_package () {
145 print STDERR "$us: package $package does not exist in suite $isuite\n";
151 return "+".rrref().":".lrref();
156 printdebug "CD $newdir\n";
157 chdir $newdir or die "chdir: $newdir: $!";
160 sub deliberately ($) {
162 return !!grep { $_ eq "--deliberately-$enquiry" } @deliberatelies;
165 #---------- remote protocol support, common ----------
167 # remote push initiator/responder protocol:
168 # < dgit-remote-push-ready [optional extra info ignored by old initiators]
170 # > file parsed-changelog
171 # [indicates that output of dpkg-parsechangelog follows]
172 # > data-block NBYTES
173 # > [NBYTES bytes of data (no newline)]
174 # [maybe some more blocks]
186 # [indicates that signed tag is wanted]
187 # < data-block NBYTES
188 # < [NBYTES bytes of data (no newline)]
189 # [maybe some more blocks]
193 # > want signed-dsc-changes
194 # < data-block NBYTES [transfer of signed dsc]
196 # < data-block NBYTES [transfer of signed changes]
204 sub i_child_report () {
205 # Sees if our child has died, and reap it if so. Returns a string
206 # describing how it died if it failed, or undef otherwise.
207 return undef unless $i_child_pid;
208 my $got = waitpid $i_child_pid, WNOHANG;
209 return undef if $got <= 0;
210 die unless $got == $i_child_pid;
211 $i_child_pid = undef;
212 return undef unless $?;
213 return "build host child ".waitstatusmsg();
218 fail "connection lost: $!" if $fh->error;
219 fail "protocol violation; $m not expected";
222 sub badproto_badread ($$) {
224 fail "connection lost: $!" if $!;
225 my $report = i_child_report();
226 fail $report if defined $report;
227 badproto $fh, "eof (reading $wh)";
230 sub protocol_expect (&$) {
231 my ($match, $fh) = @_;
234 defined && chomp or badproto_badread $fh, "protocol message";
242 badproto $fh, "\`$_'";
245 sub protocol_send_file ($$) {
246 my ($fh, $ourfn) = @_;
247 open PF, "<", $ourfn or die "$ourfn: $!";
250 my $got = read PF, $d, 65536;
251 die "$ourfn: $!" unless defined $got;
253 print $fh "data-block ".length($d)."\n" or die $!;
254 print $fh $d or die $!;
256 PF->error and die "$ourfn $!";
257 print $fh "data-end\n" or die $!;
261 sub protocol_read_bytes ($$) {
262 my ($fh, $nbytes) = @_;
263 $nbytes =~ m/^[1-9]\d{0,5}$/ or badproto \*RO, "bad byte count";
265 my $got = read $fh, $d, $nbytes;
266 $got==$nbytes or badproto_badread $fh, "data block";
270 sub protocol_receive_file ($$) {
271 my ($fh, $ourfn) = @_;
272 printdebug "() $ourfn\n";
273 open PF, ">", $ourfn or die "$ourfn: $!";
275 my ($y,$l) = protocol_expect {
276 m/^data-block (.*)$/ ? (1,$1) :
277 m/^data-end$/ ? (0,) :
281 my $d = protocol_read_bytes $fh, $l;
282 print PF $d or die $!;
287 #---------- remote protocol support, responder ----------
289 sub responder_send_command ($) {
291 return unless $we_are_responder;
292 # called even without $we_are_responder
293 printdebug ">> $command\n";
294 print PO $command, "\n" or die $!;
297 sub responder_send_file ($$) {
298 my ($keyword, $ourfn) = @_;
299 return unless $we_are_responder;
300 printdebug "]] $keyword $ourfn\n";
301 responder_send_command "file $keyword";
302 protocol_send_file \*PO, $ourfn;
305 sub responder_receive_files ($@) {
306 my ($keyword, @ourfns) = @_;
307 die unless $we_are_responder;
308 printdebug "[[ $keyword @ourfns\n";
309 responder_send_command "want $keyword";
310 foreach my $fn (@ourfns) {
311 protocol_receive_file \*PI, $fn;
314 protocol_expect { m/^files-end$/ } \*PI;
317 #---------- remote protocol support, initiator ----------
319 sub initiator_expect (&) {
321 protocol_expect { &$match } \*RO;
324 #---------- end remote code ----------
327 if ($we_are_responder) {
329 responder_send_command "progress ".length($m) or die $!;
330 print PO $m or die $!;
340 $ua = LWP::UserAgent->new();
344 progress "downloading $what...";
345 my $r = $ua->get(@_) or die $!;
346 return undef if $r->code == 404;
347 $r->is_success or fail "failed to fetch $what: ".$r->status_line;
348 return $r->decoded_content(charset => 'none');
351 our ($dscdata,$dscurl,$dsc,$dsc_checked,$skew_warning_vsn);
356 failedcmd @_ if system @_;
359 sub act_local () { return $dryrun_level <= 1; }
360 sub act_scary () { return !$dryrun_level; }
363 if (!$dryrun_level) {
364 progress "dgit ok: @_";
366 progress "would be ok: @_ (but dry run only)";
371 printcmd(\*STDERR,$debugprefix."#",@_);
374 sub runcmd_ordryrun {
382 sub runcmd_ordryrun_local {
391 my ($first_shell, @cmd) = @_;
392 return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
395 our $helpmsg = <<END;
397 dgit [dgit-opts] clone [dgit-opts] package [suite] [./dir|/dir]
398 dgit [dgit-opts] fetch|pull [dgit-opts] [suite]
399 dgit [dgit-opts] build [git-buildpackage-opts|dpkg-buildpackage-opts]
400 dgit [dgit-opts] push [dgit-opts] [suite]
401 dgit [dgit-opts] rpush build-host:build-dir ...
402 important dgit options:
403 -k<keyid> sign tag and package with <keyid> instead of default
404 --dry-run -n do not change anything, but go through the motions
405 --damp-run -L like --dry-run but make local changes, without signing
406 --new -N allow introducing a new package
407 --debug -D increase debug level
408 -c<name>=<value> set git config option (used directly by dgit too)
411 our $later_warning_msg = <<END;
412 Perhaps the upload is stuck in incoming. Using the version from git.
416 print STDERR "$us: @_\n", $helpmsg or die $!;
421 @ARGV or badusage "too few arguments";
422 return scalar shift @ARGV;
426 print $helpmsg or die $!;
430 our $td = $ENV{DGIT_TEST_DUMMY_DIR} || "DGIT_TEST_DUMMY_DIR-unset";
432 our %defcfg = ('dgit.default.distro' => 'debian',
433 'dgit.default.username' => '',
434 'dgit.default.archive-query-default-component' => 'main',
435 'dgit.default.ssh' => 'ssh',
436 'dgit.default.archive-query' => 'madison:',
437 'dgit.default.sshpsql-dbname' => 'service=projectb',
438 'dgit-distro.debian.archive-query' => 'ftpmasterapi:',
439 'dgit-distro.debian.git-host' => 'dgit-git.debian.net',
440 'dgit-distro.debian.git-user-force' => 'dgit',
441 'dgit-distro.debian.git-proto' => 'git+ssh://',
442 'dgit-distro.debian.git-path' => '/dgit/debian/repos',
443 'dgit-distro.debian.git-check' => 'ssh-cmd',
444 'dgit-distro.debian.archive-query-url', 'https://api.ftp-master.debian.org/',
445 'dgit-distro.debian.archive-query-tls-key',
446 '/etc/ssl/certs/%HOST%.pem:/etc/dgit/%HOST%.pem',
447 'dgit-distro.debian.diverts.alioth' => '/alioth',
448 'dgit-distro.debian/alioth.git-host' => 'git.debian.org',
449 'dgit-distro.debian/alioth.git-user-force' => '',
450 'dgit-distro.debian/alioth.git-proto' => 'git+ssh://',
451 'dgit-distro.debian/alioth.git-path' => '/git/dgit-repos/repos',
452 'dgit-distro.debian/alioth.git-create' => 'ssh-cmd',
453 'dgit-distro.debian.upload-host' => 'ftp-master', # for dput
454 'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/',
455 'dgit-distro.debian.backports-quirk' => '(squeeze)-backports*',
456 'dgit-distro.debian-backports.mirror' => 'http://backports.debian.org/debian-backports/',
457 'dgit-distro.ubuntu.git-check' => 'false',
458 'dgit-distro.ubuntu.mirror' => 'http://archive.ubuntu.com/ubuntu',
459 'dgit-distro.test-dummy.ssh' => "$td/ssh",
460 'dgit-distro.test-dummy.username' => "alice",
461 'dgit-distro.test-dummy.git-check' => "ssh-cmd",
462 'dgit-distro.test-dummy.git-create' => "ssh-cmd",
463 'dgit-distro.test-dummy.git-url' => "$td/git",
464 'dgit-distro.test-dummy.git-host' => "git",
465 'dgit-distro.test-dummy.git-path' => "$td/git",
466 'dgit-distro.test-dummy.archive-query' => "ftpmasterapi:",
467 'dgit-distro.test-dummy.archive-query-url' => "file://$td/aq/",
468 'dgit-distro.test-dummy.mirror' => "file://$td/mirror/",
469 'dgit-distro.test-dummy.upload-host' => 'test-dummy',
474 return undef if $c =~ /RETURN-UNDEF/;
475 my @cmd = (@git, qw(config --), $c);
478 local ($debuglevel) = $debuglevel-2;
479 $v = cmdoutput_errok @cmd;
486 my $dv = $defcfg{$c};
487 return $dv if defined $dv;
489 badcfg "need value for one of: @_\n".
490 "$us: distro or suite appears not to be (properly) supported";
493 sub access_basedistro () {
494 if (defined $idistro) {
497 return cfg("dgit-suite.$isuite.distro",
498 "dgit.default.distro");
502 sub access_quirk () {
503 # returns (quirk name, distro to use instead or undef, quirk-specific info)
504 my $basedistro = access_basedistro();
505 my $backports_quirk = cfg("dgit-distro.$basedistro.backports-quirk",
507 if (defined $backports_quirk) {
508 my $re = $backports_quirk;
509 $re =~ s/[^-0-9a-z_\%*()]/\\$&/ig;
511 $re =~ s/\%/([-0-9a-z_]+)/
512 or $re =~ m/[()]/ or badcfg "backports-quirk needs \% or ( )";
513 if ($isuite =~ m/^$re$/) {
514 return ('backports',"$basedistro-backports",$1);
517 return ('none',undef);
520 sub access_distros () {
521 # Returns list of distros to try, in order
524 # 0. `instead of' distro name(s) we have been pointed to
525 # 1. the access_quirk distro, if any
526 # 2a. the user's specified distro, or failing that } basedistro
527 # 2b. the distro calculated from the suite }
528 my @l = access_basedistro();
530 my (undef,$quirkdistro) = access_quirk();
531 unshift @l, $quirkdistro;
532 unshift @l, $instead_distro;
533 return grep { defined } @l;
539 # The nesting of these loops determines the search order. We put
540 # the key loop on the outside so that we search all the distros
541 # for each key, before going on to the next key. That means that
542 # if access_cfg is called with a more specific, and then a less
543 # specific, key, an earlier distro can override the less specific
544 # without necessarily overriding any more specific keys. (If the
545 # distro wants to override the more specific keys it can simply do
546 # so; whereas if we did the loop the other way around, it would be
547 # impossible to for an earlier distro to override a less specific
548 # key but not the more specific ones without restating the unknown
549 # values of the more specific keys.
552 # We have to deal with RETURN-UNDEF specially, so that we don't
553 # terminate the search prematurely.
555 if (m/RETURN-UNDEF/) { push @rundef, $_; last; }
558 foreach my $d (access_distros()) {
559 push @cfgs, map { "dgit-distro.$d.$_" } @realkeys;
561 push @cfgs, map { "dgit.default.$_" } @realkeys;
563 my $value = cfg(@cfgs);
567 sub string_to_ssh ($) {
569 if ($spec =~ m/\s/) {
570 return qw(sh -ec), 'exec '.$spec.' "$@"', 'x';
576 sub access_cfg_ssh () {
577 my $gitssh = access_cfg('ssh', 'RETURN-UNDEF');
578 if (!defined $gitssh) {
581 return string_to_ssh $gitssh;
585 sub access_runeinfo ($) {
587 return ": dgit ".access_basedistro()." $info ;";
590 sub access_someuserhost ($) {
592 my $user = access_cfg("$some-user-force", 'RETURN-UNDEF');
593 defined($user) && length($user) or
594 $user = access_cfg("$some-user",'username');
595 my $host = access_cfg("$some-host");
596 return length($user) ? "$user\@$host" : $host;
599 sub access_gituserhost () {
600 return access_someuserhost('git');
603 sub access_giturl (;$) {
605 my $url = access_cfg('git-url','RETURN-UNDEF');
607 my $proto = access_cfg('git-proto', 'RETURN-UNDEF');
608 return undef unless defined $proto;
611 access_gituserhost().
612 access_cfg('git-path');
614 return "$url/$package.git";
617 sub parsecontrolfh ($$;$) {
618 my ($fh, $desc, $allowsigned) = @_;
619 our $dpkgcontrolhash_noissigned;
622 my %opts = ('name' => $desc);
623 $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
624 $c = Dpkg::Control::Hash->new(%opts);
625 $c->parse($fh,$desc) or die "parsing of $desc failed";
626 last if $allowsigned;
627 last if $dpkgcontrolhash_noissigned;
628 my $issigned= $c->get_option('is_pgp_signed');
629 if (!defined $issigned) {
630 $dpkgcontrolhash_noissigned= 1;
631 seek $fh, 0,0 or die "seek $desc: $!";
632 } elsif ($issigned) {
633 fail "control file $desc is (already) PGP-signed. ".
634 " Note that dgit push needs to modify the .dsc and then".
635 " do the signature itself";
644 my ($file, $desc) = @_;
645 my $fh = new IO::Handle;
646 open $fh, '<', $file or die "$file: $!";
647 my $c = parsecontrolfh($fh,$desc);
648 $fh->error and die $!;
654 my ($dctrl,$field) = @_;
655 my $v = $dctrl->{$field};
656 return $v if defined $v;
657 fail "missing field $field in ".$v->get_option('name');
661 my $c = Dpkg::Control::Hash->new();
662 my $p = new IO::Handle;
663 my @cmd = (qw(dpkg-parsechangelog), @_);
664 open $p, '-|', @cmd or die $!;
666 $?=0; $!=0; close $p or failedcmd @cmd;
672 defined $d or fail "getcwd failed: $!";
678 sub archive_query ($) {
680 my $query = access_cfg('archive-query','RETURN-UNDEF');
681 $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
684 { no strict qw(refs); &{"${method}_${proto}"}($proto,$data); }
687 sub pool_dsc_subpath ($$) {
688 my ($vsn,$component) = @_; # $package is implict arg
689 my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
690 return "/pool/$component/$prefix/$package/".dscfn($vsn);
693 #---------- `ftpmasterapi' archive query method (nascent) ----------
695 sub archive_api_query_cmd ($) {
697 my @cmd = qw(curl -sS);
698 my $url = access_cfg('archive-query-url');
699 if ($url =~ m#^https://([-.0-9a-z]+)/#) {
701 my $keys = access_cfg('archive-query-tls-key','RETURN-UNDEF');
702 foreach my $key (split /\:/, $keys) {
703 $key =~ s/\%HOST\%/$host/g;
705 fail "for $url: stat $key: $!" unless $!==ENOENT;
708 push @cmd, "--ca-certificate=$key", "--ca-directory=/dev/enoent";
712 push @cmd, $url.$subpath;
718 my ($data, $subpath) = @_;
719 badcfg "ftpmasterapi archive query method takes no data part"
721 my @cmd = archive_api_query_cmd($subpath);
722 my $json = cmdoutput @cmd;
723 return decode_json($json);
726 sub canonicalise_suite_ftpmasterapi () {
727 my ($proto,$data) = @_;
728 my $suites = api_query($data, 'suites');
730 foreach my $entry (@$suites) {
732 my $v = $entry->{$_};
733 defined $v && $v eq $isuite;
735 push @matched, $entry;
737 fail "unknown suite $isuite" unless @matched;
740 @matched==1 or die "multiple matches for suite $isuite\n";
741 $cn = "$matched[0]{codename}";
742 defined $cn or die "suite $isuite info has no codename\n";
743 $cn =~ m/^$suite_re$/ or die "suite $isuite maps to bad codename\n";
745 die "bad ftpmaster api response: $@\n".Dumper(\@matched)
750 sub archive_query_ftpmasterapi () {
751 my ($proto,$data) = @_;
752 my $info = api_query($data, "dsc_in_suite/$isuite/$package");
754 my $digester = Digest::SHA->new(256);
755 foreach my $entry (@$info) {
757 my $vsn = "$entry->{version}";
758 my ($ok,$msg) = version_check $vsn;
759 die "bad version: $msg\n" unless $ok;
760 my $component = "$entry->{component}";
761 $component =~ m/^$component_re$/ or die "bad component";
762 my $filename = "$entry->{filename}";
763 $filename && $filename !~ m#[^-+:._~0-9a-zA-Z/]|^[/.]|/[/.]#
764 or die "bad filename";
765 my $sha256sum = "$entry->{sha256sum}";
766 $sha256sum =~ m/^[0-9a-f]+$/ or die "bad sha256sum";
767 push @rows, [ $vsn, "/pool/$component/$filename",
768 $digester, $sha256sum ];
770 die "bad ftpmaster api response: $@\n".Dumper($entry)
773 @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
777 #---------- `madison' archive query method ----------
779 sub archive_query_madison {
780 return map { [ @$_[0..1] ] } madison_get_parse(@_);
783 sub madison_get_parse {
784 my ($proto,$data) = @_;
785 die unless $proto eq 'madison';
787 $data= access_cfg('madison-distro','RETURN-UNDEF');
788 $data //= access_basedistro();
790 $rmad{$proto,$data,$package} ||= cmdoutput
791 qw(rmadison -asource),"-s$isuite","-u$data",$package;
792 my $rmad = $rmad{$proto,$data,$package};
795 foreach my $l (split /\n/, $rmad) {
796 $l =~ m{^ \s*( [^ \t|]+ )\s* \|
797 \s*( [^ \t|]+ )\s* \|
798 \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
799 \s*( [^ \t|]+ )\s* }x or die "$rmad ?";
800 $1 eq $package or die "$rmad $package ?";
807 $component = access_cfg('archive-query-default-component');
809 $5 eq 'source' or die "$rmad ?";
810 push @out, [$vsn,pool_dsc_subpath($vsn,$component),$newsuite];
812 return sort { -version_compare($a->[0],$b->[0]); } @out;
815 sub canonicalise_suite_madison {
816 # madison canonicalises for us
817 my @r = madison_get_parse(@_);
819 "unable to canonicalise suite using package $package".
820 " which does not appear to exist in suite $isuite;".
821 " --existing-package may help";
825 #---------- `sshpsql' archive query method ----------
828 my ($data,$runeinfo,$sql) = @_;
830 $data= access_someuserhost('sshpsql').':'.
831 access_cfg('sshpsql-dbname');
833 $data =~ m/:/ or badcfg "invalid sshpsql method string \`$data'";
834 my ($userhost,$dbname) = ($`,$'); #';
836 my @cmd = (access_cfg_ssh, $userhost,
837 access_runeinfo("ssh-psql $runeinfo").
838 " export LC_MESSAGES=C; export LC_CTYPE=C;".
839 " ".shellquote qw(psql -A), $dbname, qw(-c), $sql);
841 open P, "-|", @cmd or die $!;
844 printdebug("$debugprefix>|$_|\n");
847 $!=0; $?=0; close P or failedcmd @cmd;
849 my $nrows = pop @rows;
850 $nrows =~ s/^\((\d+) rows?\)$/$1/ or die "$nrows ?";
851 @rows == $nrows+1 or die "$nrows ".(scalar @rows)." ?";
852 @rows = map { [ split /\|/, $_ ] } @rows;
853 my $ncols = scalar @{ shift @rows };
854 die if grep { scalar @$_ != $ncols } @rows;
858 sub sql_injection_check {
859 foreach (@_) { die "$_ $& ?" if m{[^-+=:_.,/0-9a-zA-Z]}; }
862 sub archive_query_sshpsql ($$) {
863 my ($proto,$data) = @_;
864 sql_injection_check $isuite, $package;
865 my @rows = sshpsql($data, "archive-query $isuite $package", <<END);
866 SELECT source.version, component.name, files.filename, files.sha256sum
868 JOIN src_associations ON source.id = src_associations.source
869 JOIN suite ON suite.id = src_associations.suite
870 JOIN dsc_files ON dsc_files.source = source.id
871 JOIN files_archive_map ON files_archive_map.file_id = dsc_files.file
872 JOIN component ON component.id = files_archive_map.component_id
873 JOIN files ON files.id = dsc_files.file
874 WHERE ( suite.suite_name='$isuite' OR suite.codename='$isuite' )
875 AND source.source='$package'
876 AND files.filename LIKE '%.dsc';
878 @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
879 my $digester = Digest::SHA->new(256);
881 my ($vsn,$component,$filename,$sha256sum) = @$_;
882 [ $vsn, "/pool/$component/$filename",$digester,$sha256sum ];
887 sub canonicalise_suite_sshpsql ($$) {
888 my ($proto,$data) = @_;
889 sql_injection_check $isuite;
890 my @rows = sshpsql($data, "canonicalise-suite $isuite", <<END);
891 SELECT suite.codename
892 FROM suite where suite_name='$isuite' or codename='$isuite';
894 @rows = map { $_->[0] } @rows;
895 fail "unknown suite $isuite" unless @rows;
896 die "ambiguous $isuite: @rows ?" if @rows>1;
900 #---------- `dummycat' archive query method ----------
902 sub canonicalise_suite_dummycat ($$) {
903 my ($proto,$data) = @_;
904 my $dpath = "$data/suite.$isuite";
905 if (!open C, "<", $dpath) {
906 $!==ENOENT or die "$dpath: $!";
907 printdebug "dummycat canonicalise_suite $isuite $dpath ENOENT\n";
911 chomp or die "$dpath: $!";
913 printdebug "dummycat canonicalise_suite $isuite $dpath = $_\n";
917 sub archive_query_dummycat ($$) {
918 my ($proto,$data) = @_;
919 canonicalise_suite();
920 my $dpath = "$data/package.$csuite.$package";
921 if (!open C, "<", $dpath) {
922 $!==ENOENT or die "$dpath: $!";
923 printdebug "dummycat query $csuite $package $dpath ENOENT\n";
931 printdebug "dummycat query $csuite $package $dpath | $_\n";
932 my @row = split /\s+/, $_;
933 @row==2 or die "$dpath: $_ ?";
936 C->error and die "$dpath: $!";
938 return sort { -version_compare($a->[0],$b->[0]); } @rows;
941 #---------- archive query entrypoints and rest of program ----------
943 sub canonicalise_suite () {
944 return if defined $csuite;
945 fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
946 $csuite = archive_query('canonicalise_suite');
947 if ($isuite ne $csuite) {
948 progress "canonical suite name for $isuite is $csuite";
952 sub get_archive_dsc () {
953 canonicalise_suite();
954 my @vsns = archive_query('archive_query');
955 foreach my $vinfo (@vsns) {
956 my ($vsn,$subpath,$digester,$digest) = @$vinfo;
957 $dscurl = access_cfg('mirror').$subpath;
958 $dscdata = url_get($dscurl);
960 $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
965 $digester->add($dscdata);
966 my $got = $digester->hexdigest();
968 fail "$dscurl has hash $got but".
969 " archive told us to expect $digest";
971 my $dscfh = new IO::File \$dscdata, '<' or die $!;
972 printdebug Dumper($dscdata) if $debuglevel>1;
973 $dsc = parsecontrolfh($dscfh,$dscurl,1);
974 printdebug Dumper($dsc) if $debuglevel>1;
975 my $fmt = getfield $dsc, 'Format';
976 fail "unsupported source format $fmt, sorry" unless $format_ok{$fmt};
977 $dsc_checked = !!$digester;
983 sub check_for_git ();
984 sub check_for_git () {
986 my $how = access_cfg('git-check');
987 if ($how eq 'ssh-cmd') {
989 (access_cfg_ssh, access_gituserhost(),
990 access_runeinfo("git-check $package").
991 " set -e; cd ".access_cfg('git-path').";".
992 " if test -d $package.git; then echo 1; else echo 0; fi");
993 my $r= cmdoutput @cmd;
994 if ($r =~ m/^divert (\w+)$/) {
996 my ($usedistro,) = access_distros();
997 $instead_distro= cfg("dgit-distro.$usedistro.diverts.$divert");
998 $instead_distro =~ s{^/}{ access_basedistro()."/" }e;
999 printdebug "diverting $divert so using distro $instead_distro\n";
1000 return check_for_git();
1002 failedcmd @cmd unless $r =~ m/^[01]$/;
1004 } elsif ($how eq 'true') {
1006 } elsif ($how eq 'false') {
1009 badcfg "unknown git-check \`$how'";
1013 sub create_remote_git_repo () {
1014 my $how = access_cfg('git-create');
1015 if ($how eq 'ssh-cmd') {
1017 (access_cfg_ssh, access_gituserhost(),
1018 access_runeinfo("git-create $package").
1019 "set -e; cd ".access_cfg('git-path').";".
1020 " cp -a _template $package.git");
1021 } elsif ($how eq 'true') {
1024 badcfg "unknown git-create \`$how'";
1028 our ($dsc_hash,$lastpush_hash);
1030 our $ud = '.git/dgit/unpack';
1035 mkdir $ud or die $!;
1038 sub mktree_in_ud_here () {
1039 runcmd qw(git init -q);
1040 rmtree('.git/objects');
1041 symlink '../../../../objects','.git/objects' or die $!;
1044 sub git_write_tree () {
1045 my $tree = cmdoutput @git, qw(write-tree);
1046 $tree =~ m/^\w+$/ or die "$tree ?";
1050 sub mktree_in_ud_from_only_subdir () {
1051 # changes into the subdir
1053 die unless @dirs==1;
1054 $dirs[0] =~ m#^([^/]+)/\.$# or die;
1057 fail "source package contains .git directory" if stat_exists '.git';
1058 mktree_in_ud_here();
1059 my $format=get_source_format();
1060 if (madformat($format)) {
1063 runcmd @git, qw(add -Af);
1064 my $tree=git_write_tree();
1065 return ($tree,$dir);
1068 sub dsc_files_info () {
1069 foreach my $csumi (['Checksums-Sha256','Digest::SHA', 'new(256)'],
1070 ['Checksums-Sha1', 'Digest::SHA', 'new(1)'],
1071 ['Files', 'Digest::MD5', 'new()']) {
1072 my ($fname, $module, $method) = @$csumi;
1073 my $field = $dsc->{$fname};
1074 next unless defined $field;
1075 eval "use $module; 1;" or die $@;
1077 foreach (split /\n/, $field) {
1079 m/^(\w+) (\d+) (\S+)$/ or
1080 fail "could not parse .dsc $fname line \`$_'";
1081 my $digester = eval "$module"."->$method;" or die $@;
1086 Digester => $digester,
1091 fail "missing any supported Checksums-* or Files field in ".
1092 $dsc->get_option('name');
1096 map { $_->{Filename} } dsc_files_info();
1099 sub is_orig_file ($;$) {
1102 m/\.orig(?:-\w+)?\.tar\.\w+$/ or return 0;
1103 defined $base or return 1;
1107 sub make_commit ($) {
1109 return cmdoutput @git, qw(hash-object -w -t commit), $file;
1112 sub clogp_authline ($) {
1114 my $author = getfield $clogp, 'Maintainer';
1115 $author =~ s#,.*##ms;
1116 my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
1117 my $authline = "$author $date";
1118 $authline =~ m/^[^<>]+ \<\S+\> \d+ [-+]\d+$/ or
1119 fail "unexpected commit author line format \`$authline'".
1120 " (was generated from changelog Maintainer field)";
1124 sub generate_commit_from_dsc () {
1128 foreach my $fi (dsc_files_info()) {
1129 my $f = $fi->{Filename};
1130 die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
1132 link "../../../$f", $f
1136 complete_file_from_dsc('.', $fi);
1138 if (is_orig_file($f)) {
1139 link $f, "../../../../$f"
1145 my $dscfn = "$package.dsc";
1147 open D, ">", $dscfn or die "$dscfn: $!";
1148 print D $dscdata or die "$dscfn: $!";
1149 close D or die "$dscfn: $!";
1150 my @cmd = qw(dpkg-source);
1151 push @cmd, '--no-check' if $dsc_checked;
1152 push @cmd, qw(-x --), $dscfn;
1155 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1156 runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
1157 my $clogp = parsecontrol('../changelog.tmp',"commit's changelog");
1158 my $authline = clogp_authline $clogp;
1159 my $changes = getfield $clogp, 'Changes';
1160 open C, ">../commit.tmp" or die $!;
1161 print C <<END or die $!;
1168 # imported from the archive
1171 my $outputhash = make_commit qw(../commit.tmp);
1172 my $cversion = getfield $clogp, 'Version';
1173 progress "synthesised git commit from .dsc $cversion";
1174 if ($lastpush_hash) {
1175 runcmd @git, qw(reset --hard), $lastpush_hash;
1176 runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
1177 my $oldclogp = parsecontrol('../changelogold.tmp','previous changelog');
1178 my $oversion = getfield $oldclogp, 'Version';
1180 version_compare($oversion, $cversion);
1182 # git upload/ is earlier vsn than archive, use archive
1183 open C, ">../commit2.tmp" or die $!;
1184 print C <<END or die $!;
1186 parent $lastpush_hash
1191 Record $package ($cversion) in archive suite $csuite
1193 $outputhash = make_commit qw(../commit2.tmp);
1194 } elsif ($vcmp > 0) {
1195 print STDERR <<END or die $!;
1197 Version actually in archive: $cversion (older)
1198 Last allegedly pushed/uploaded: $oversion (newer or same)
1201 $outputhash = $lastpush_hash;
1203 $outputhash = $lastpush_hash;
1206 changedir '../../../..';
1207 runcmd @git, qw(update-ref -m),"dgit fetch import $cversion",
1208 'DGIT_ARCHIVE', $outputhash;
1209 cmdoutput @git, qw(log -n2), $outputhash;
1210 # ... gives git a chance to complain if our commit is malformed
1215 sub complete_file_from_dsc ($$) {
1216 our ($dstdir, $fi) = @_;
1217 # Ensures that we have, in $dir, the file $fi, with the correct
1218 # contents. (Downloading it from alongside $dscurl if necessary.)
1220 my $f = $fi->{Filename};
1221 my $tf = "$dstdir/$f";
1224 if (stat_exists $tf) {
1225 progress "using existing $f";
1228 $furl =~ s{/[^/]+$}{};
1230 die "$f ?" unless $f =~ m/^${package}_/;
1231 die "$f ?" if $f =~ m#/#;
1232 runcmd_ordryrun_local @curl,qw(-o),$tf,'--',"$furl";
1233 next if !act_local();
1237 open F, "<", "$tf" or die "$tf: $!";
1238 $fi->{Digester}->reset();
1239 $fi->{Digester}->addfile(*F);
1240 F->error and die $!;
1241 my $got = $fi->{Digester}->hexdigest();
1242 $got eq $fi->{Hash} or
1243 fail "file $f has hash $got but .dsc".
1244 " demands hash $fi->{Hash} ".
1245 ($downloaded ? "(got wrong file from archive!)"
1246 : "(perhaps you should delete this file?)");
1249 sub ensure_we_have_orig () {
1250 foreach my $fi (dsc_files_info()) {
1251 my $f = $fi->{Filename};
1252 next unless is_orig_file($f);
1253 complete_file_from_dsc('..', $fi);
1257 sub git_fetch_us () {
1258 runcmd_ordryrun_local @git, qw(fetch),access_giturl(),fetchspec();
1261 sub fetch_from_archive () {
1262 # ensures that lrref() is what is actually in the archive,
1263 # one way or another
1267 foreach my $field (@ourdscfield) {
1268 $dsc_hash = $dsc->{$field};
1269 last if defined $dsc_hash;
1271 if (defined $dsc_hash) {
1272 $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
1274 progress "last upload to archive specified git hash";
1276 progress "last upload to archive has NO git hash";
1279 progress "no version available from the archive";
1282 $lastpush_hash = git_get_ref(lrref());
1283 printdebug "previous reference hash=$lastpush_hash\n";
1285 if (defined $dsc_hash) {
1286 fail "missing remote git history even though dsc has hash -".
1287 " could not find ref ".lrref().
1288 " (should have been fetched from ".access_giturl()."#".rrref().")"
1289 unless $lastpush_hash;
1291 ensure_we_have_orig();
1292 if ($dsc_hash eq $lastpush_hash) {
1293 } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
1294 print STDERR <<END or die $!;
1296 Git commit in archive is behind the last version allegedly pushed/uploaded.
1297 Commit referred to by archive: $dsc_hash
1298 Last allegedly pushed/uploaded: $lastpush_hash
1301 $hash = $lastpush_hash;
1303 fail "git head (".lrref()."=$lastpush_hash) is not a ".
1304 "descendant of archive's .dsc hash ($dsc_hash)";
1307 $hash = generate_commit_from_dsc();
1308 } elsif ($lastpush_hash) {
1309 # only in git, not in the archive yet
1310 $hash = $lastpush_hash;
1311 print STDERR <<END or die $!;
1313 Package not found in the archive, but has allegedly been pushed using dgit.
1317 printdebug "nothing found!\n";
1318 if (defined $skew_warning_vsn) {
1319 print STDERR <<END or die $!;
1321 Warning: relevant archive skew detected.
1322 Archive allegedly contains $skew_warning_vsn
1323 But we were not able to obtain any version from the archive or git.
1329 printdebug "current hash=$hash\n";
1330 if ($lastpush_hash) {
1331 fail "not fast forward on last upload branch!".
1332 " (archive's version left in DGIT_ARCHIVE)"
1333 unless is_fast_fwd($lastpush_hash, $hash);
1335 if (defined $skew_warning_vsn) {
1337 printdebug "SKEW CHECK WANT $skew_warning_vsn\n";
1338 my $clogf = ".git/dgit/changelog.tmp";
1339 runcmd shell_cmd "exec >$clogf",
1340 @git, qw(cat-file blob), "$hash:debian/changelog";
1341 my $gotclogp = parsechangelog("-l$clogf");
1342 my $got_vsn = getfield $gotclogp, 'Version';
1343 printdebug "SKEW CHECK GOT $got_vsn\n";
1344 if (version_compare($got_vsn, $skew_warning_vsn) < 0) {
1345 print STDERR <<END or die $!;
1347 Warning: archive skew detected. Using the available version:
1348 Archive allegedly contains $skew_warning_vsn
1349 We were able to obtain only $got_vsn
1354 if ($lastpush_hash ne $hash) {
1355 my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
1359 dryrun_report @upd_cmd;
1367 canonicalise_suite();
1368 badusage "dry run makes no sense with clone" unless act_local();
1369 my $hasgit = check_for_git();
1370 mkdir $dstdir or die "$dstdir $!";
1372 runcmd @git, qw(init -q);
1373 my $giturl = access_giturl(1);
1374 if (defined $giturl) {
1375 runcmd @git, qw(config), "remote.$remotename.fetch", fetchspec();
1376 open H, "> .git/HEAD" or die $!;
1377 print H "ref: ".lref()."\n" or die $!;
1379 runcmd @git, qw(remote add), 'origin', $giturl;
1382 progress "fetching existing git history";
1384 runcmd_ordryrun_local @git, qw(fetch origin);
1386 progress "starting new git history";
1388 fetch_from_archive() or no_such_package;
1389 my $vcsgiturl = $dsc->{'Vcs-Git'};
1390 if (length $vcsgiturl) {
1391 $vcsgiturl =~ s/\s+-b\s+\S+//g;
1392 runcmd @git, qw(remote add vcs-git), $vcsgiturl;
1394 runcmd @git, qw(reset --hard), lrref();
1395 printdone "ready for work in $dstdir";
1399 if (check_for_git()) {
1402 fetch_from_archive() or no_such_package();
1403 printdone "fetched into ".lrref();
1408 runcmd_ordryrun_local @git, qw(merge -m),"Merge from $csuite [dgit]",
1410 printdone "fetched to ".lrref()." and merged into HEAD";
1413 sub check_not_dirty () {
1414 return if $ignoredirty;
1415 my @cmd = (@git, qw(diff --quiet HEAD));
1417 $!=0; $?=0; system @cmd;
1418 return if !$! && !$?;
1419 if (!$! && $?==256) {
1420 fail "working tree is dirty (does not match HEAD)";
1426 sub commit_admin ($) {
1429 runcmd_ordryrun_local @git, qw(commit -m), $m;
1432 sub commit_quilty_patch () {
1433 my $output = cmdoutput @git, qw(status --porcelain);
1435 foreach my $l (split /\n/, $output) {
1436 next unless $l =~ m/\S/;
1437 if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
1441 delete $adds{'.pc'}; # if there wasn't one before, don't add it
1443 progress "nothing quilty to commit, ok.";
1446 runcmd_ordryrun_local @git, qw(add), sort keys %adds;
1447 commit_admin "Commit Debian 3.0 (quilt) metadata";
1450 sub get_source_format () {
1451 if (!open F, "debian/source/format") {
1452 die $! unless $!==&ENOENT;
1456 F->error and die $!;
1463 return 0 unless $format eq '3.0 (quilt)';
1464 if ($quilt_mode eq 'nocheck') {
1465 progress "Not doing any fixup of \`$format' due to --no-quilt-fixup";
1468 progress "Format \`$format', checking/updating patch stack";
1472 sub push_parse_changelog ($) {
1475 my $clogp = Dpkg::Control::Hash->new();
1476 $clogp->load($clogpfn) or die;
1478 $package = getfield $clogp, 'Source';
1479 my $cversion = getfield $clogp, 'Version';
1480 my $tag = debiantag($cversion);
1481 runcmd @git, qw(check-ref-format), $tag;
1483 my $dscfn = dscfn($cversion);
1485 return ($clogp, $cversion, $tag, $dscfn);
1488 sub push_parse_dsc ($$$) {
1489 my ($dscfn,$dscfnwhat, $cversion) = @_;
1490 $dsc = parsecontrol($dscfn,$dscfnwhat);
1491 my $dversion = getfield $dsc, 'Version';
1492 my $dscpackage = getfield $dsc, 'Source';
1493 ($dscpackage eq $package && $dversion eq $cversion) or
1494 fail "$dscfn is for $dscpackage $dversion".
1495 " but debian/changelog is for $package $cversion";
1498 sub push_mktag ($$$$$$$) {
1499 my ($head,$clogp,$tag,
1501 $changesfile,$changesfilewhat,
1504 $dsc->{$ourdscfield[0]} = $head;
1505 $dsc->save("$dscfn.tmp") or die $!;
1507 my $changes = parsecontrol($changesfile,$changesfilewhat);
1508 foreach my $field (qw(Source Distribution Version)) {
1509 $changes->{$field} eq $clogp->{$field} or
1510 fail "changes field $field \`$changes->{$field}'".
1511 " does not match changelog \`$clogp->{$field}'";
1514 my $cversion = getfield $clogp, 'Version';
1515 my $clogsuite = getfield $clogp, 'Distribution';
1517 # We make the git tag by hand because (a) that makes it easier
1518 # to control the "tagger" (b) we can do remote signing
1519 my $authline = clogp_authline $clogp;
1520 my $delibs = join(" ", "",@deliberatelies);
1521 my $declaredistro = access_basedistro();
1522 open TO, '>', $tfn->('.tmp') or die $!;
1523 print TO <<END or die $!;
1529 $package release $cversion for $clogsuite ($csuite) [dgit]
1530 [dgit distro=$declaredistro$delibs]
1532 foreach my $ref (sort keys %supersedes) {
1533 print TO <<END or die $!;
1534 [dgit supersede:$ref=$supersedes{$ref}]
1540 my $tagobjfn = $tfn->('.tmp');
1542 if (!defined $keyid) {
1543 $keyid = access_cfg('keyid','RETURN-UNDEF');
1545 unlink $tfn->('.tmp.asc') or $!==&ENOENT or die $!;
1546 my @sign_cmd = (@gpg, qw(--detach-sign --armor));
1547 push @sign_cmd, qw(-u),$keyid if defined $keyid;
1548 push @sign_cmd, $tfn->('.tmp');
1549 runcmd_ordryrun @sign_cmd;
1551 $tagobjfn = $tfn->('.signed.tmp');
1552 runcmd shell_cmd "exec >$tagobjfn", qw(cat --),
1553 $tfn->('.tmp'), $tfn->('.tmp.asc');
1560 sub sign_changes ($) {
1561 my ($changesfile) = @_;
1563 my @debsign_cmd = @debsign;
1564 push @debsign_cmd, "-k$keyid" if defined $keyid;
1565 push @debsign_cmd, "-p$gpg[0]" if $gpg[0] ne 'gpg';
1566 push @debsign_cmd, $changesfile;
1567 runcmd_ordryrun @debsign_cmd;
1572 my ($forceflag) = @_;
1573 printdebug "actually entering push\n";
1576 access_giturl(); # check that success is vaguely likely
1578 my $clogpfn = ".git/dgit/changelog.822.tmp";
1579 runcmd shell_cmd "exec >$clogpfn", qw(dpkg-parsechangelog);
1581 responder_send_file('parsed-changelog', $clogpfn);
1583 my ($clogp, $cversion, $tag, $dscfn) =
1584 push_parse_changelog("$clogpfn");
1586 my $dscpath = "$buildproductsdir/$dscfn";
1587 stat_exists $dscpath or
1588 fail "looked for .dsc $dscfn, but $!;".
1589 " maybe you forgot to build";
1591 responder_send_file('dsc', $dscpath);
1593 push_parse_dsc($dscpath, $dscfn, $cversion);
1595 my $format = getfield $dsc, 'Format';
1596 printdebug "format $format\n";
1597 if (madformat($format)) {
1598 commit_quilty_patch();
1602 progress "checking that $dscfn corresponds to HEAD";
1603 runcmd qw(dpkg-source -x --),
1604 $dscpath =~ m#^/# ? $dscpath : "../../../$dscpath";
1605 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1606 changedir '../../../..';
1607 my $diffopt = $debuglevel>0 ? '--exit-code' : '--quiet';
1608 my @diffcmd = (@git, qw(diff), $diffopt, $tree);
1609 debugcmd "+",@diffcmd;
1611 my $r = system @diffcmd;
1614 fail "$dscfn specifies a different tree to your HEAD commit;".
1615 " perhaps you forgot to build".
1616 ($diffopt eq '--exit-code' ? "" :
1617 " (run with -D to see full diff output)");
1623 #do fast forward check and maybe fake merge
1624 # if (!is_fast_fwd(mainbranch
1625 # runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
1626 # map { lref($_).":".rref($_) }
1628 my $head = git_rev_parse('HEAD');
1629 if (!$changesfile) {
1630 my $multi = "$buildproductsdir/".
1631 "${package}_".(stripepoch $cversion)."_multi.changes";
1632 if (stat_exists "$multi") {
1633 $changesfile = $multi;
1635 my $pat = "${package}_".(stripepoch $cversion)."_*.changes";
1636 my @cs = glob "$buildproductsdir/$pat";
1637 fail "failed to find unique changes file".
1638 " (looked for $pat in $buildproductsdir, or $multi);".
1639 " perhaps you need to use dgit -C"
1641 ($changesfile) = @cs;
1644 $changesfile = "$buildproductsdir/$changesfile";
1647 responder_send_file('changes',$changesfile);
1648 responder_send_command("param head $head");
1649 responder_send_command("param csuite $csuite");
1651 if ($forceflag && defined $lastpush_hash) {
1652 git_for_each_tag_referring($lastpush_hash, sub {
1653 my ($tagobjid,$refobjid,$fullrefname,$tagname) = @_;
1654 responder_send_command("supersedes $fullrefname=$tagobjid");
1655 $supersedes{$fullrefname} = $tagobjid;
1659 my $tfn = sub { ".git/dgit/tag$_[0]"; };
1662 if ($we_are_responder) {
1663 $tagobjfn = $tfn->('.signed.tmp');
1664 responder_receive_files('signed-tag', $tagobjfn);
1667 push_mktag($head,$clogp,$tag,
1669 $changesfile,$changesfile,
1673 my $tag_obj_hash = cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
1674 runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
1675 runcmd_ordryrun_local @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
1676 runcmd_ordryrun @git, qw(tag -v --), $tag;
1678 if (!check_for_git()) {
1679 create_remote_git_repo();
1681 runcmd_ordryrun @git, qw(push),access_giturl(),
1682 $forceflag."HEAD:".rrref(), "refs/tags/$tag";
1683 runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), 'HEAD';
1685 if ($we_are_responder) {
1686 my $dryrunsuffix = act_local() ? "" : ".tmp";
1687 responder_receive_files('signed-dsc-changes',
1688 "$dscpath$dryrunsuffix",
1689 "$changesfile$dryrunsuffix");
1692 rename "$dscpath.tmp",$dscpath or die "$dscfn $!";
1694 progress "[new .dsc left in $dscpath.tmp]";
1696 sign_changes $changesfile;
1699 my $host = access_cfg('upload-host','RETURN-UNDEF');
1700 my @hostarg = defined($host) ? ($host,) : ();
1701 runcmd_ordryrun @dput, @hostarg, $changesfile;
1702 printdone "pushed and uploaded $cversion";
1704 responder_send_command("complete");
1710 badusage "-p is not allowed with clone; specify as argument instead"
1711 if defined $package;
1714 } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
1715 ($package,$isuite) = @ARGV;
1716 } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
1717 ($package,$dstdir) = @ARGV;
1718 } elsif (@ARGV==3) {
1719 ($package,$isuite,$dstdir) = @ARGV;
1721 badusage "incorrect arguments to dgit clone";
1723 $dstdir ||= "$package";
1725 if (stat_exists $dstdir) {
1726 fail "$dstdir already exists";
1730 if ($rmonerror && !$dryrun_level) {
1731 $cwd_remove= getcwd();
1733 return unless defined $cwd_remove;
1734 if (!chdir "$cwd_remove") {
1735 return if $!==&ENOENT;
1736 die "chdir $cwd_remove: $!";
1738 rmtree($dstdir) or die "remove $dstdir: $!\n";
1743 $cwd_remove = undef;
1746 sub branchsuite () {
1747 my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
1748 if ($branch =~ m#$lbranch_re#o) {
1755 sub fetchpullargs () {
1756 if (!defined $package) {
1757 my $sourcep = parsecontrol('debian/control','debian/control');
1758 $package = getfield $sourcep, 'Source';
1761 # $isuite = branchsuite(); # this doesn't work because dak hates canons
1763 my $clogp = parsechangelog();
1764 $isuite = getfield $clogp, 'Distribution';
1766 canonicalise_suite();
1767 progress "fetching from suite $csuite";
1768 } elsif (@ARGV==1) {
1770 canonicalise_suite();
1772 badusage "incorrect arguments to dgit fetch or dgit pull";
1790 badusage "-p is not allowed with dgit push" if defined $package;
1792 my $clogp = parsechangelog();
1793 $package = getfield $clogp, 'Source';
1796 } elsif (@ARGV==1) {
1797 ($specsuite) = (@ARGV);
1799 badusage "incorrect arguments to dgit push";
1801 $isuite = getfield $clogp, 'Distribution';
1803 local ($package) = $existing_package; # this is a hack
1804 canonicalise_suite();
1806 if (defined $specsuite && $specsuite ne $isuite) {
1807 canonicalise_suite();
1808 $csuite eq $specsuite or
1809 fail "dgit push: changelog specifies $isuite ($csuite)".
1810 " but command line specifies $specsuite";
1812 if (check_for_git()) {
1816 if (fetch_from_archive()) {
1817 if (is_fast_fwd(lrref(), 'HEAD')) {
1819 } elsif (deliberately('not-fast-forward') ||
1820 deliberately('TEST-not-fast-forward-dgit-only')) {
1823 fail "dgit push: HEAD is not a descendant".
1824 " of the archive's version.\n".
1825 "dgit: To overwrite its contents,".
1826 " use git merge -s ours ".lrref().".\n".
1827 "dgit: To rewind history, if permitted by the archive,".
1828 " use --deliberately-not-fast-forward";
1832 fail "package appears to be new in this suite;".
1833 " if this is intentional, use --new";
1838 #---------- remote commands' implementation ----------
1840 sub cmd_remote_push_build_host {
1841 my ($nrargs) = shift @ARGV;
1842 my (@rargs) = @ARGV[0..$nrargs-1];
1843 @ARGV = @ARGV[$nrargs..$#ARGV];
1845 my ($dir,$vsnwant) = @rargs;
1846 # vsnwant is a comma-separated list; we report which we have
1847 # chosen in our ready response (so other end can tell if they
1850 $we_are_responder = 1;
1851 $us .= " (build host)";
1853 open PI, "<&STDIN" or die $!;
1854 open STDIN, "/dev/null" or die $!;
1855 open PO, ">&STDOUT" or die $!;
1857 open STDOUT, ">&STDERR" or die $!;
1861 fail "build host has dgit rpush protocol version".
1862 " $rpushprotovsn but invocation host has $vsnwant"
1863 unless grep { $rpushprotovsn eq $_ } split /,/, $vsnwant;
1865 responder_send_command("dgit-remote-push-ready $rpushprotovsn");
1871 sub cmd_remote_push_responder { cmd_remote_push_build_host(); }
1872 # ... for compatibility with proto vsn.1 dgit (just so that user gets
1873 # a good error message)
1879 my $report = i_child_report();
1880 if (defined $report) {
1881 printdebug "($report)\n";
1882 } elsif ($i_child_pid) {
1883 printdebug "(killing build host child $i_child_pid)\n";
1884 kill 15, $i_child_pid;
1886 if (defined $i_tmp && !defined $initiator_tempdir) {
1888 eval { rmtree $i_tmp; };
1892 END { i_cleanup(); }
1895 my ($base,$selector,@args) = @_;
1896 $selector =~ s/\-/_/g;
1897 { no strict qw(refs); &{"${base}_${selector}"}(@args); }
1903 if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
1910 my @rargs = ($dir,$rpushprotovsn);
1913 push @rdgit, @ropts;
1914 push @rdgit, qw(remote-push-build-host), (scalar @rargs), @rargs;
1916 my @cmd = (@ssh, $host, shellquote @rdgit);
1919 if (defined $initiator_tempdir) {
1920 rmtree $initiator_tempdir;
1921 mkdir $initiator_tempdir, 0700 or die "$initiator_tempdir: $!";
1922 $i_tmp = $initiator_tempdir;
1926 $i_child_pid = open2(\*RO, \*RI, @cmd);
1928 initiator_expect { m/^dgit-remote-push-ready/ };
1930 my ($icmd,$iargs) = initiator_expect {
1931 m/^(\S+)(?: (.*))?$/;
1934 i_method "i_resp", $icmd, $iargs;
1938 sub i_resp_progress ($) {
1940 my $msg = protocol_read_bytes \*RO, $rhs;
1944 sub i_resp_complete {
1945 my $pid = $i_child_pid;
1946 $i_child_pid = undef; # prevents killing some other process with same pid
1947 printdebug "waiting for build host child $pid...\n";
1948 my $got = waitpid $pid, 0;
1949 die $! unless $got == $pid;
1950 die "build host child failed $?" if $?;
1953 printdebug "all done\n";
1957 sub i_resp_file ($) {
1959 my $localname = i_method "i_localname", $keyword;
1960 my $localpath = "$i_tmp/$localname";
1961 stat_exists $localpath and
1962 badproto \*RO, "file $keyword ($localpath) twice";
1963 protocol_receive_file \*RO, $localpath;
1964 i_method "i_file", $keyword;
1969 sub i_resp_param ($) {
1970 $_[0] =~ m/^(\S+) (.*)$/ or badproto \*RO, "bad param spec";
1974 sub i_resp_supersedes ($) {
1975 $_[0] =~ m#^(refs/tags/\S+)=(\w+)$#
1976 or badproto \*RO, "bad supersedes spec";
1977 my $r = system qw(git check-ref-format), $1;
1978 die "bad supersedes ref spec ($r)" if $r;
1979 $supersedes{$1} = $2;
1984 sub i_resp_want ($) {
1986 die "$keyword ?" if $i_wanted{$keyword}++;
1987 my @localpaths = i_method "i_want", $keyword;
1988 printdebug "[[ $keyword @localpaths\n";
1989 foreach my $localpath (@localpaths) {
1990 protocol_send_file \*RI, $localpath;
1992 print RI "files-end\n" or die $!;
1995 our ($i_clogp, $i_version, $i_tag, $i_dscfn, $i_changesfn);
1997 sub i_localname_parsed_changelog {
1998 return "remote-changelog.822";
2000 sub i_file_parsed_changelog {
2001 ($i_clogp, $i_version, $i_tag, $i_dscfn) =
2002 push_parse_changelog "$i_tmp/remote-changelog.822";
2003 die if $i_dscfn =~ m#/|^\W#;
2006 sub i_localname_dsc {
2007 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
2012 sub i_localname_changes {
2013 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
2014 $i_changesfn = $i_dscfn;
2015 $i_changesfn =~ s/\.dsc$/_dgit.changes/ or die;
2016 return $i_changesfn;
2018 sub i_file_changes { }
2020 sub i_want_signed_tag {
2021 printdebug Dumper(\%i_param, $i_dscfn);
2022 defined $i_param{'head'} && defined $i_dscfn && defined $i_clogp
2023 && defined $i_param{'csuite'}
2024 or badproto \*RO, "premature desire for signed-tag";
2025 my $head = $i_param{'head'};
2026 die if $head =~ m/[^0-9a-f]/ || $head !~ m/^../;
2028 die unless $i_param{'csuite'} =~ m/^$suite_re$/;
2030 push_parse_dsc $i_dscfn, 'remote dsc', $i_version;
2033 push_mktag $head, $i_clogp, $i_tag,
2035 $i_changesfn, 'remote changes',
2036 sub { "tag$_[0]"; };
2041 sub i_want_signed_dsc_changes {
2042 rename "$i_dscfn.tmp","$i_dscfn" or die "$i_dscfn $!";
2043 sign_changes $i_changesfn;
2044 return ($i_dscfn, $i_changesfn);
2047 #---------- building etc. ----------
2053 #----- `3.0 (quilt)' handling -----
2055 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
2057 sub quiltify_dpkg_commit ($$$;$) {
2058 my ($patchname,$author,$msg, $xinfo) = @_;
2062 my $descfn = ".git/dgit/quilt-description.tmp";
2063 open O, '>', $descfn or die "$descfn: $!";
2066 $msg =~ s/^\s+$/ ./mg;
2067 print O <<END or die $!;
2077 local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
2078 local $ENV{'VISUAL'} = $ENV{'EDITOR'};
2079 local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
2080 runcmd_ordryrun_local @dpkgsource, qw(--commit .), $patchname;
2084 sub quiltify_trees_differ ($$) {
2086 # returns 1 iff the two tree objects differ other than in debian/
2088 my @cmd = (@git, qw(diff-tree --name-only -z), $x, $y);
2089 my $diffs= cmdoutput @cmd;
2090 foreach my $f (split /\0/, $diffs) {
2091 next if $f eq 'debian';
2097 sub quiltify_tree_sentinelfiles ($) {
2098 # lists the `sentinel' files present in the tree
2100 my $r = cmdoutput @git, qw(ls-tree --name-only), $x,
2101 qw(-- debian/rules debian/control);
2107 my ($clogp,$target) = @_;
2109 # Quilt patchification algorithm
2111 # We search backwards through the history of the main tree's HEAD
2112 # (T) looking for a start commit S whose tree object is identical
2113 # to to the patch tip tree (ie the tree corresponding to the
2114 # current dpkg-committed patch series). For these purposes
2115 # `identical' disregards anything in debian/ - this wrinkle is
2116 # necessary because dpkg-source treates debian/ specially.
2118 # We can only traverse edges where at most one of the ancestors'
2119 # trees differs (in changes outside in debian/). And we cannot
2120 # handle edges which change .pc/ or debian/patches. To avoid
2121 # going down a rathole we avoid traversing edges which introduce
2122 # debian/rules or debian/control. And we set a limit on the
2123 # number of edges we are willing to look at.
2125 # If we succeed, we walk forwards again. For each traversed edge
2126 # PC (with P parent, C child) (starting with P=S and ending with
2127 # C=T) to we do this:
2129 # - dpkg-source --commit with a patch name and message derived from C
2130 # After traversing PT, we git commit the changes which
2131 # should be contained within debian/patches.
2133 changedir '../fake';
2134 mktree_in_ud_here();
2136 runcmd @git, 'add', '.';
2137 my $oldtiptree=git_write_tree();
2138 changedir '../work';
2140 # The search for the path S..T is breadth-first. We maintain a
2141 # todo list containing search nodes. A search node identifies a
2142 # commit, and looks something like this:
2144 # Commit => $git_commit_id,
2145 # Child => $c, # or undef if P=T
2146 # Whynot => $reason_edge_PC_unsuitable, # in @nots only
2147 # Nontrivial => true iff $p..$c has relevant changes
2154 my %considered; # saves being exponential on some weird graphs
2156 my $t_sentinels = quiltify_tree_sentinelfiles $target;
2159 my ($search,$whynot) = @_;
2160 printdebug " search NOT $search->{Commit} $whynot\n";
2161 $search->{Whynot} = $whynot;
2162 push @nots, $search;
2163 no warnings qw(exiting);
2172 my $c = shift @todo;
2173 next if $considered{$c->{Commit}}++;
2175 $not->($c, "maximum search space exceeded") if --$max_work <= 0;
2177 printdebug "quiltify investigate $c->{Commit}\n";
2180 if (!quiltify_trees_differ $c->{Commit}, $oldtiptree) {
2181 printdebug " search finished hooray!\n";
2186 if ($quilt_mode eq 'nofix') {
2187 fail "quilt fixup required but quilt mode is \`nofix'\n".
2188 "HEAD commit $c->{Commit} differs from tree implied by ".
2189 " debian/patches (tree object $oldtiptree)";
2191 if ($quilt_mode eq 'smash') {
2192 printdebug " search quitting smash\n";
2196 my $c_sentinels = quiltify_tree_sentinelfiles $c->{Commit};
2197 $not->($c, "has $c_sentinels not $t_sentinels")
2198 if $c_sentinels ne $t_sentinels;
2200 my $commitdata = cmdoutput @git, qw(cat-file commit), $c->{Commit};
2201 $commitdata =~ m/\n\n/;
2203 my @parents = ($commitdata =~ m/^parent (\w+)$/gm);
2204 @parents = map { { Commit => $_, Child => $c } } @parents;
2206 $not->($c, "root commit") if !@parents;
2208 foreach my $p (@parents) {
2209 $p->{Nontrivial}= quiltify_trees_differ $p->{Commit},$c->{Commit};
2211 my $ndiffers = grep { $_->{Nontrivial} } @parents;
2212 $not->($c, "merge ($ndiffers nontrivial parents)") if $ndiffers > 1;
2214 foreach my $p (@parents) {
2215 printdebug "considering C=$c->{Commit} P=$p->{Commit}\n";
2217 my @cmd= (@git, qw(diff-tree -r --name-only),
2218 $p->{Commit},$c->{Commit}, qw(-- debian/patches .pc));
2219 my $patchstackchange = cmdoutput @cmd;
2220 if (length $patchstackchange) {
2221 $patchstackchange =~ s/\n/,/g;
2222 $not->($p, "changed $patchstackchange");
2225 printdebug " search queue P=$p->{Commit} ",
2226 ($p->{Nontrivial} ? "NT" : "triv"),"\n";
2232 printdebug "quiltify want to smash\n";
2235 my $x = $_[0]{Commit};
2236 $x =~ s/(.*?[0-9a-z]{8})[0-9a-z]*$/$1/;
2239 my $reportnot = sub {
2241 my $s = $abbrev->($notp);
2242 my $c = $notp->{Child};
2243 $s .= "..".$abbrev->($c) if $c;
2244 $s .= ": ".$c->{Whynot};
2247 if ($quilt_mode eq 'linear') {
2248 print STDERR "$us: quilt fixup cannot be linear. Stopped at:\n";
2249 foreach my $notp (@nots) {
2250 print STDERR "$us: ", $reportnot->($notp), "\n";
2252 fail "quilt fixup naive history linearisation failed.\n".
2253 "Use dpkg-source --commit by hand; or, --quilt=smash for one ugly patch";
2254 } elsif ($quilt_mode eq 'smash') {
2255 } elsif ($quilt_mode eq 'auto') {
2256 progress "quilt fixup cannot be linear, smashing...";
2258 die "$quilt_mode ?";
2263 my $msg = cmdoutput @git, qw(log), "-n$ncommits";
2265 quiltify_dpkg_commit "auto-$version-$target-$time",
2266 (getfield $clogp, 'Maintainer'),
2267 "Automatically generated patch ($clogp->{Version})\n".
2268 "Last (up to) $ncommits git changes, FYI:\n\n". $msg;
2272 progress "quiltify linearisation planning successful, executing...";
2274 for (my $p = $sref_S;
2275 my $c = $p->{Child};
2277 printdebug "quiltify traverse $p->{Commit}..$c->{Commit}\n";
2278 next unless $p->{Nontrivial};
2280 my $cc = $c->{Commit};
2282 my $commitdata = cmdoutput @git, qw(cat-file commit), $cc;
2283 $commitdata =~ m/\n\n/ or die "$c ?";
2286 $commitdata =~ m/^author (.*) \d+ [-+0-9]+$/m or die "$cc ?";
2289 $msg =~ s/^(.*)\n*/$1\n/ or die "$cc $msg ?";
2292 my $patchname = $title;
2293 $patchname =~ s/[.:]$//;
2294 $patchname =~ y/ A-Z/-a-z/;
2295 $patchname =~ y/-a-z0-9_.+=~//cd;
2296 $patchname =~ s/^\W/x-$&/;
2297 $patchname = substr($patchname,0,40);
2300 stat "debian/patches/$patchname$index";
2302 $!==ENOENT or die "$patchname$index $!";
2304 runcmd @git, qw(checkout -q), $cc;
2306 # We use the tip's changelog so that dpkg-source doesn't
2307 # produce complaining messages from dpkg-parsechangelog. None
2308 # of the information dpkg-source gets from the changelog is
2309 # actually relevant - it gets put into the original message
2310 # which dpkg-source provides our stunt editor, and then
2312 runcmd @git, qw(checkout -q), $target, qw(debian/changelog);
2314 quiltify_dpkg_commit "$patchname$index", $author, $msg,
2315 "X-Dgit-Generated: $clogp->{Version} $cc\n";
2317 runcmd @git, qw(checkout -q), $cc, qw(debian/changelog);
2320 runcmd @git, qw(checkout -q master);
2323 sub build_maybe_quilt_fixup () {
2324 my $format=get_source_format;
2325 return unless madformat $format;
2329 # - honour any existing .pc in case it has any strangeness
2330 # - determine the git commit corresponding to the tip of
2331 # the patch stack (if there is one)
2332 # - if there is such a git commit, convert each subsequent
2333 # git commit into a quilt patch with dpkg-source --commit
2334 # - otherwise convert all the differences in the tree into
2335 # a single git commit
2339 # Our git tree doesn't necessarily contain .pc. (Some versions of
2340 # dgit would include the .pc in the git tree.) If there isn't
2341 # one, we need to generate one by unpacking the patches that we
2344 # We first look for a .pc in the git tree. If there is one, we
2345 # will use it. (This is not the normal case.)
2347 # Otherwise need to regenerate .pc so that dpkg-source --commit
2348 # can work. We do this as follows:
2349 # 1. Collect all relevant .orig from parent directory
2350 # 2. Generate a debian.tar.gz out of
2351 # debian/{patches,rules,source/format}
2352 # 3. Generate a fake .dsc containing just these fields:
2353 # Format Source Version Files
2354 # 4. Extract the fake .dsc
2355 # Now the fake .dsc has a .pc directory.
2356 # (In fact we do this in every case, because in future we will
2357 # want to search for a good base commit for generating patches.)
2359 # Then we can actually do the dpkg-source --commit
2360 # 1. Make a new working tree with the same object
2361 # store as our main tree and check out the main
2363 # 2. Copy .pc from the fake's extraction, if necessary
2364 # 3. Run dpkg-source --commit
2365 # 4. If the result has changes to debian/, then
2366 # - git-add them them
2367 # - git-add .pc if we had a .pc in-tree
2369 # 5. If we had a .pc in-tree, delete it, and git-commit
2370 # 6. Back in the main tree, fast forward to the new HEAD
2372 my $clogp = parsechangelog();
2373 my $headref = git_rev_parse('HEAD');
2378 my $upstreamversion=$version;
2379 $upstreamversion =~ s/-[^-]*$//;
2381 my $fakeversion="$upstreamversion-~~DGITFAKE";
2383 my $fakedsc=new IO::File 'fake.dsc', '>' or die $!;
2384 print $fakedsc <<END or die $!;
2387 Version: $fakeversion
2391 my $dscaddfile=sub {
2394 my $md = new Digest::MD5;
2396 my $fh = new IO::File $b, '<' or die "$b $!";
2401 print $fakedsc " ".$md->hexdigest." $size $b\n" or die $!;
2404 foreach my $f (<../../../../*>) { #/){
2405 my $b=$f; $b =~ s{.*/}{};
2406 next unless is_orig_file $b, srcfn $upstreamversion,'';
2407 link $f, $b or die "$b $!";
2411 my @files=qw(debian/source/format debian/rules);
2412 if (stat_exists '../../../debian/patches') {
2413 push @files, 'debian/patches';
2416 my $debtar= srcfn $fakeversion,'.debian.tar.gz';
2417 runcmd qw(env GZIP=-1 tar -zcf), "./$debtar", qw(-C ../../..), @files;
2419 $dscaddfile->($debtar);
2420 close $fakedsc or die $!;
2422 runcmd qw(sh -ec), 'exec dpkg-source --no-check -x fake.dsc >/dev/null';
2424 my $fakexdir= $package.'-'.(stripepoch $upstreamversion);
2425 rename $fakexdir, "fake" or die "$fakexdir $!";
2427 mkdir "work" or die $!;
2429 mktree_in_ud_here();
2430 runcmd @git, qw(reset --hard), $headref;
2433 if (stat_exists ".pc") {
2435 progress "Tree already contains .pc - will use it then delete it.";
2438 rename '../fake/.pc','.pc' or die $!;
2441 quiltify($clogp,$headref);
2443 if (!open P, '>>', ".pc/applied-patches") {
2444 $!==&ENOENT or die $!;
2449 commit_quilty_patch();
2451 if ($mustdeletepc) {
2452 runcmd @git, qw(rm -rq .pc);
2453 commit_admin "Commit removal of .pc (quilt series tracking data)";
2456 changedir '../../../..';
2457 runcmd @git, qw(pull --ff-only -q .git/dgit/unpack/work master);
2460 sub quilt_fixup_editor () {
2461 my $descfn = $ENV{$fakeeditorenv};
2462 my $editing = $ARGV[$#ARGV];
2463 open I1, '<', $descfn or die "$descfn: $!";
2464 open I2, '<', $editing or die "$editing: $!";
2465 unlink $editing or die "$editing: $!";
2466 open O, '>', $editing or die "$editing: $!";
2467 while (<I1>) { print O or die $!; } I1->error and die $!;
2470 $copying ||= m/^\-\-\- /;
2471 next unless $copying;
2474 I2->error and die $!;
2479 #----- other building -----
2482 if ($cleanmode eq 'dpkg-source') {
2483 runcmd_ordryrun_local @dpkgbuildpackage, qw(-T clean);
2484 } elsif ($cleanmode eq 'git') {
2485 runcmd_ordryrun_local @git, qw(clean -xdf);
2486 } elsif ($cleanmode eq 'none') {
2493 badusage "clean takes no additional arguments" if @ARGV;
2498 badusage "-p is not allowed when building" if defined $package;
2501 my $clogp = parsechangelog();
2502 $isuite = getfield $clogp, 'Distribution';
2503 $package = getfield $clogp, 'Source';
2504 $version = getfield $clogp, 'Version';
2505 build_maybe_quilt_fixup();
2508 sub changesopts () {
2509 my @opts =@changesopts[1..$#changesopts];
2510 if (!defined $changes_since_version) {
2511 my @vsns = archive_query('archive_query');
2512 my @quirk = access_quirk();
2513 if ($quirk[0] eq 'backports') {
2514 local $isuite = $quirk[2];
2516 canonicalise_suite();
2517 push @vsns, archive_query('archive_query');
2520 @vsns = map { $_->[0] } @vsns;
2521 @vsns = sort { -version_compare($a, $b) } @vsns;
2522 $changes_since_version = $vsns[0];
2523 progress "changelog will contain changes since $vsns[0]";
2525 $changes_since_version = '_';
2526 progress "package seems new, not specifying -v<version>";
2529 if ($changes_since_version ne '_') {
2530 unshift @opts, "-v$changes_since_version";
2537 runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc), changesopts(), @ARGV;
2538 printdone "build successful\n";
2544 (qw(git-buildpackage -us -uc --git-no-sign-tags),
2545 "--git-builder=@dpkgbuildpackage");
2546 unless (grep { m/^--git-debian-branch|^--git-ignore-branch/ } @ARGV) {
2547 canonicalise_suite();
2548 push @cmd, "--git-debian-branch=".lbranch();
2550 push @cmd, changesopts();
2551 runcmd_ordryrun_local @cmd, @ARGV;
2552 printdone "build successful\n";
2557 $sourcechanges = "${package}_".(stripepoch $version)."_source.changes";
2558 $dscfn = dscfn($version);
2559 if ($cleanmode eq 'dpkg-source') {
2560 runcmd_ordryrun_local (@dpkgbuildpackage, qw(-us -uc -S)),
2563 my $pwd = must_getcwd();
2564 my $leafdir = basename $pwd;
2566 runcmd_ordryrun_local @dpkgsource, qw(-b --), $leafdir;
2568 runcmd_ordryrun_local qw(sh -ec),
2569 'exec >$1; shift; exec "$@"','x',
2570 "../$sourcechanges",
2571 @dpkggenchanges, qw(-S), changesopts();
2575 sub cmd_build_source {
2576 badusage "build-source takes no additional arguments" if @ARGV;
2578 printdone "source built, results in $dscfn and $sourcechanges";
2584 my $pat = "${package}_".(stripepoch $version)."_*.changes";
2586 stat_exist $dscfn or fail "$dscfn (in parent directory): $!";
2587 stat_exists $sourcechanges
2588 or fail "$sourcechanges (in parent directory): $!";
2589 foreach my $cf (glob $pat) {
2590 next if $cf eq $sourcechanges;
2591 unlink $cf or fail "remove $cf: $!";
2594 runcmd_ordryrun_local @sbuild, @ARGV, qw(-d), $isuite, $dscfn;
2595 my @changesfiles = glob $pat;
2596 @changesfiles = sort {
2597 ($b =~ m/_source\.changes$/ <=> $a =~ m/_source\.changes$/)
2600 fail "wrong number of different changes files (@changesfiles)"
2601 unless @changesfiles;
2602 runcmd_ordryrun_local @mergechanges, @changesfiles;
2603 my $multichanges = "${package}_".(stripepoch $version)."_multi.changes";
2605 stat_exists $multichanges or fail "$multichanges: $!";
2607 printdone "build successful, results in $multichanges\n" or die $!;
2610 sub cmd_quilt_fixup {
2611 badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
2612 my $clogp = parsechangelog();
2613 $version = getfield $clogp, 'Version';
2614 $package = getfield $clogp, 'Source';
2615 build_maybe_quilt_fixup();
2618 sub cmd_archive_api_query {
2619 badusage "need only 1 subpath argument" unless @ARGV==1;
2620 my ($subpath) = @ARGV;
2621 my @cmd = archive_api_query_cmd($subpath);
2623 exec @cmd or fail "exec curl: $!\n";
2626 #---------- argument parsing and main program ----------
2629 print "dgit version $our_version\n" or die $!;
2636 if (defined $ENV{'DGIT_SSH'}) {
2637 @ssh = string_to_ssh $ENV{'DGIT_SSH'};
2638 } elsif (defined $ENV{'GIT_SSH'}) {
2639 @ssh = ($ENV{'GIT_SSH'});
2643 last unless $ARGV[0] =~ m/^-/;
2647 if (m/^--dry-run$/) {
2650 } elsif (m/^--damp-run$/) {
2653 } elsif (m/^--no-sign$/) {
2656 } elsif (m/^--help$/) {
2658 } elsif (m/^--version$/) {
2660 } elsif (m/^--new$/) {
2663 } elsif (m/^--since-version=([^_]+|_)$/) {
2665 $changes_since_version = $1;
2666 } elsif (m/^--([-0-9a-z]+)=(.*)/s &&
2667 ($om = $opts_opt_map{$1}) &&
2671 } elsif (m/^--([-0-9a-z]+):(.*)/s &&
2672 !$opts_opt_cmdonly{$1} &&
2673 ($om = $opts_opt_map{$1})) {
2676 } elsif (m/^--existing-package=(.*)/s) {
2678 $existing_package = $1;
2679 } elsif (m/^--initiator-tempdir=(.*)/s) {
2680 $initiator_tempdir = $1;
2681 $initiator_tempdir =~ m#^/# or
2682 badusage "--initiator-tempdir must be used specify an".
2683 " absolute, not relative, directory."
2684 } elsif (m/^--distro=(.*)/s) {
2687 } elsif (m/^--build-products-dir=(.*)/s) {
2689 $buildproductsdir = $1;
2690 } elsif (m/^--clean=(dpkg-source|git|none)$/s) {
2693 } elsif (m/^--clean=(.*)$/s) {
2694 badusage "unknown cleaning mode \`$1'";
2695 } elsif (m/^--quilt=($quilt_modes_re)$/s) {
2698 } elsif (m/^--quilt=(.*)$/s) {
2699 badusage "unknown quilt fixup mode \`$1'";
2700 } elsif (m/^--ignore-dirty$/s) {
2703 } elsif (m/^--no-quilt-fixup$/s) {
2705 $quilt_mode = 'nocheck';
2706 } elsif (m/^--no-rm-on-error$/s) {
2709 } elsif (m/^--deliberately-($deliberately_re)$/s) {
2711 push @deliberatelies, $&;
2713 badusage "unknown long option \`$_'";
2720 } elsif (s/^-L/-/) {
2723 } elsif (s/^-h/-/) {
2725 } elsif (s/^-D/-/) {
2729 } elsif (s/^-N/-/) {
2732 } elsif (s/^-v([^_]+|_)$//s) {
2734 $changes_since_version = $1;
2737 push @changesopts, $_;
2739 } elsif (s/^-c(.*=.*)//s) {
2741 push @git, '-c', $1;
2742 } elsif (s/^-d(.+)//s) {
2745 } elsif (s/^-C(.+)//s) {
2748 if ($changesfile =~ s#^(.*)/##) {
2749 $buildproductsdir = $1;
2751 } elsif (s/^-k(.+)//s) {
2753 } elsif (m/^-[vdCk]$/) {
2755 "option \`$_' requires an argument (and no space before the argument)";
2756 } elsif (s/^-wn$//s) {
2758 $cleanmode = 'none';
2759 } elsif (s/^-wg$//s) {
2762 } elsif (s/^-wd$//s) {
2764 $cleanmode = 'dpkg-source';
2766 badusage "unknown short option \`$_'";
2773 if ($ENV{$fakeeditorenv}) {
2774 quilt_fixup_editor();
2778 print STDERR "DRY RUN ONLY\n" if $dryrun_level > 1;
2779 print STDERR "DAMP RUN - WILL MAKE LOCAL (UNSIGNED) CHANGES\n"
2780 if $dryrun_level == 1;
2782 print STDERR $helpmsg or die $!;
2785 my $cmd = shift @ARGV;
2788 if (!defined $quilt_mode) {
2789 $quilt_mode = cfg('dgit.force.quilt-mode', 'RETURN-UNDEF')
2790 // access_cfg('quilt-mode', 'RETURN-UNDEF')
2792 $quilt_mode =~ m/^($quilt_modes_re)$/
2793 or badcfg "unknown quilt-mode \`$quilt_mode'";
2797 my $fn = ${*::}{"cmd_$cmd"};
2798 $fn or badusage "unknown operation $cmd";