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);
39 our $our_version = 'UNRELEASED'; ###substituted###
41 our $rpushprotovsn = 2;
43 our $isuite = 'unstable';
49 our $dryrun_level = 0;
51 our $buildproductsdir = '..';
57 our $existing_package = 'dpkg';
58 our $cleanmode = 'dpkg-source';
59 our $changes_since_version;
61 our $quilt_modes_re = 'linear|smash|auto|nofix|nocheck';
62 our $we_are_responder;
63 our $initiator_tempdir;
65 our %format_ok = map { $_=>1 } ("1.0","3.0 (native)","3.0 (quilt)");
67 our $suite_re = '[-+.0-9a-z]+';
70 our (@dget) = qw(dget);
71 our (@curl) = qw(curl -f);
72 our (@dput) = qw(dput);
73 our (@debsign) = qw(debsign);
75 our (@sbuild) = qw(sbuild -A);
77 our (@dgit) = qw(dgit);
78 our (@dpkgbuildpackage) = qw(dpkg-buildpackage -i\.git/ -I.git);
79 our (@dpkgsource) = qw(dpkg-source -i\.git/ -I.git);
80 our (@dpkggenchanges) = qw(dpkg-genchanges);
81 our (@mergechanges) = qw(mergechanges -f);
82 our (@changesopts) = ('');
84 our %opts_opt_map = ('dget' => \@dget, # accept for compatibility
87 'debsign' => \@debsign,
92 'dpkg-source' => \@dpkgsource,
93 'dpkg-buildpackage' => \@dpkgbuildpackage,
94 'dpkg-genchanges' => \@dpkggenchanges,
95 'ch' => \@changesopts,
96 'mergechanges' => \@mergechanges);
98 our %opts_opt_cmdonly = ('gpg' => 1);
104 our $remotename = 'dgit';
105 our @ourdscfield = qw(Dgit Vcs-Dgit-Master);
109 sub lbranch () { return "$branchprefix/$csuite"; }
110 my $lbranch_re = '^refs/heads/'.$branchprefix.'/([^/.]+)$';
111 sub lref () { return "refs/heads/".lbranch(); }
112 sub lrref () { return "refs/remotes/$remotename/".server_branch($csuite); }
113 sub rrref () { return server_ref($csuite); }
123 return "${package}_".(stripepoch $vsn).$sfx
128 return srcfn($vsn,".dsc");
137 foreach my $f (@end) {
139 warn "$us: cleanup: $@" if length $@;
143 our @signames = split / /, $Config{sig_name};
145 sub waitstatusmsg () {
147 return "terminated, reporting successful completion";
148 } elsif (!($? & 255)) {
149 return "failed with error exit status ".WEXITSTATUS($?);
150 } elsif (WIFSIGNALED($?)) {
151 my $signum=WTERMSIG($?);
152 return "died due to fatal signal ".
153 ($signames[$signum] // "number $signum").
154 ($? & 128 ? " (core dumped)" : ""); # POSIX(3pm) has no WCOREDUMP
156 return "failed with unknown wait status ".$?;
162 my $prefix = $us.($we_are_responder ? " (build host)" : "").": ";
163 $s =~ s/^/$prefix/gm;
167 sub badcfg { print STDERR "$us: invalid configuration: @_\n"; exit 12; }
169 sub no_such_package () {
170 print STDERR "$us: package $package does not exist in suite $isuite\n";
176 return "+".rrref().":".lrref();
181 printdebug "CD $newdir\n";
182 chdir $newdir or die "chdir: $newdir: $!";
185 sub deliberately ($) {
187 return !!grep { $_ eq "--deliberately-$enquiry" } @deliberatelies;
190 #---------- remote protocol support, common ----------
192 # remote push initiator/responder protocol:
193 # < dgit-remote-push-ready [optional extra info ignored by old initiators]
195 # > file parsed-changelog
196 # [indicates that output of dpkg-parsechangelog follows]
197 # > data-block NBYTES
198 # > [NBYTES bytes of data (no newline)]
199 # [maybe some more blocks]
211 # [indicates that signed tag is wanted]
212 # < data-block NBYTES
213 # < [NBYTES bytes of data (no newline)]
214 # [maybe some more blocks]
218 # > want signed-dsc-changes
219 # < data-block NBYTES [transfer of signed dsc]
221 # < data-block NBYTES [transfer of signed changes]
229 sub i_child_report () {
230 # Sees if our child has died, and reap it if so. Returns a string
231 # describing how it died if it failed, or undef otherwise.
232 return undef unless $i_child_pid;
233 my $got = waitpid $i_child_pid, WNOHANG;
234 return undef if $got <= 0;
235 die unless $got == $i_child_pid;
236 $i_child_pid = undef;
237 return undef unless $?;
238 return "build host child ".waitstatusmsg();
243 fail "connection lost: $!" if $fh->error;
244 fail "protocol violation; $m not expected";
247 sub badproto_badread ($$) {
249 fail "connection lost: $!" if $!;
250 my $report = i_child_report();
251 fail $report if defined $report;
252 badproto $fh, "eof (reading $wh)";
255 sub protocol_expect (&$) {
256 my ($match, $fh) = @_;
259 defined && chomp or badproto_badread $fh, "protocol message";
267 badproto $fh, "\`$_'";
270 sub protocol_send_file ($$) {
271 my ($fh, $ourfn) = @_;
272 open PF, "<", $ourfn or die "$ourfn: $!";
275 my $got = read PF, $d, 65536;
276 die "$ourfn: $!" unless defined $got;
278 print $fh "data-block ".length($d)."\n" or die $!;
279 print $fh $d or die $!;
281 PF->error and die "$ourfn $!";
282 print $fh "data-end\n" or die $!;
286 sub protocol_read_bytes ($$) {
287 my ($fh, $nbytes) = @_;
288 $nbytes =~ m/^[1-9]\d{0,5}$/ or badproto \*RO, "bad byte count";
290 my $got = read $fh, $d, $nbytes;
291 $got==$nbytes or badproto_badread $fh, "data block";
295 sub protocol_receive_file ($$) {
296 my ($fh, $ourfn) = @_;
297 printdebug "() $ourfn\n";
298 open PF, ">", $ourfn or die "$ourfn: $!";
300 my ($y,$l) = protocol_expect {
301 m/^data-block (.*)$/ ? (1,$1) :
302 m/^data-end$/ ? (0,) :
306 my $d = protocol_read_bytes $fh, $l;
307 print PF $d or die $!;
312 #---------- remote protocol support, responder ----------
314 sub responder_send_command ($) {
316 return unless $we_are_responder;
317 # called even without $we_are_responder
318 printdebug ">> $command\n";
319 print PO $command, "\n" or die $!;
322 sub responder_send_file ($$) {
323 my ($keyword, $ourfn) = @_;
324 return unless $we_are_responder;
325 printdebug "]] $keyword $ourfn\n";
326 responder_send_command "file $keyword";
327 protocol_send_file \*PO, $ourfn;
330 sub responder_receive_files ($@) {
331 my ($keyword, @ourfns) = @_;
332 die unless $we_are_responder;
333 printdebug "[[ $keyword @ourfns\n";
334 responder_send_command "want $keyword";
335 foreach my $fn (@ourfns) {
336 protocol_receive_file \*PI, $fn;
339 protocol_expect { m/^files-end$/ } \*PI;
342 #---------- remote protocol support, initiator ----------
344 sub initiator_expect (&) {
346 protocol_expect { &$match } \*RO;
349 #---------- end remote code ----------
352 if ($we_are_responder) {
354 responder_send_command "progress ".length($m) or die $!;
355 print PO $m or die $!;
365 $ua = LWP::UserAgent->new();
369 progress "downloading $what...";
370 my $r = $ua->get(@_) or die $!;
371 return undef if $r->code == 404;
372 $r->is_success or fail "failed to fetch $what: ".$r->status_line;
373 return $r->decoded_content(charset => 'none');
376 our ($dscdata,$dscurl,$dsc,$dsc_checked,$skew_warning_vsn);
379 { local ($!); printcmd \*STDERR, "$us: failed command:", @_ or die $!; };
381 fail "failed to fork/exec: $!";
383 fail "subprocess ".waitstatusmsg();
385 fail "subprocess produced invalid output";
392 failedcmd @_ if system @_;
395 sub act_local () { return $dryrun_level <= 1; }
396 sub act_scary () { return !$dryrun_level; }
399 if (!$dryrun_level) {
400 progress "dgit ok: @_";
402 progress "would be ok: @_ (but dry run only)";
406 sub cmdoutput_errok {
407 die Dumper(\@_)." ?" if grep { !defined } @_;
409 open P, "-|", @_ or die $!;
412 { local $/ = undef; $d = <P>; }
414 if (!close P) { printdebug "=>!$?\n"; return undef; }
417 printdebug "=> \`$&'",(length $' ? '...' : ''),"\n" if $debuglevel>0; #';
422 my $d = cmdoutput_errok @_;
423 defined $d or failedcmd @_;
428 printcmd(\*STDERR,$debugprefix."#",@_);
431 sub runcmd_ordryrun {
439 sub runcmd_ordryrun_local {
448 my ($first_shell, @cmd) = @_;
449 return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
452 our $helpmsg = <<END;
454 dgit [dgit-opts] clone [dgit-opts] package [suite] [./dir|/dir]
455 dgit [dgit-opts] fetch|pull [dgit-opts] [suite]
456 dgit [dgit-opts] build [git-buildpackage-opts|dpkg-buildpackage-opts]
457 dgit [dgit-opts] push [dgit-opts] [suite]
458 dgit [dgit-opts] rpush build-host:build-dir ...
459 important dgit options:
460 -k<keyid> sign tag and package with <keyid> instead of default
461 --dry-run -n do not change anything, but go through the motions
462 --damp-run -L like --dry-run but make local changes, without signing
463 --new -N allow introducing a new package
464 --debug -D increase debug level
465 -c<name>=<value> set git config option (used directly by dgit too)
468 our $later_warning_msg = <<END;
469 Perhaps the upload is stuck in incoming. Using the version from git.
473 print STDERR "$us: @_\n", $helpmsg or die $!;
478 @ARGV or badusage "too few arguments";
479 return scalar shift @ARGV;
483 print $helpmsg or die $!;
487 our $td = $ENV{DGIT_TEST_DUMMY_DIR} || "DGIT_TEST_DUMMY_DIR-unset";
489 our %defcfg = ('dgit.default.distro' => 'debian',
490 'dgit.default.username' => '',
491 'dgit.default.archive-query-default-component' => 'main',
492 'dgit.default.ssh' => 'ssh',
493 'dgit.default.archive-query' => 'madison:',
494 'dgit.default.sshpsql-dbname' => 'service=projectb',
495 'dgit-distro.debian.archive-query' => 'ftpmasterapi:',
496 'dgit-distro.debian.git-host' => 'dgit-git.debian.net',
497 'dgit-distro.debian.git-user-force' => 'dgit',
498 'dgit-distro.debian.git-proto' => 'git+ssh://',
499 'dgit-distro.debian.git-path' => '/dgit/debian/repos',
500 'dgit-distro.debian.git-check' => 'ssh-cmd',
501 'dgit-distro.debian.archive-query-url', 'https://api.ftp-master.debian.org/',
502 'dgit-distro.debian.archive-query-tls-key',
503 '/etc/ssl/certs/%HOST%.pem:/etc/dgit/%HOST%.pem',
504 'dgit-distro.debian.diverts.alioth' => '/alioth',
505 'dgit-distro.debian/alioth.git-host' => 'git.debian.org',
506 'dgit-distro.debian/alioth.git-user-force' => '',
507 'dgit-distro.debian/alioth.git-proto' => 'git+ssh://',
508 'dgit-distro.debian/alioth.git-path' => '/git/dgit-repos/repos',
509 'dgit-distro.debian/alioth.git-create' => 'ssh-cmd',
510 'dgit-distro.debian.upload-host' => 'ftp-master', # for dput
511 'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/',
512 'dgit-distro.debian.backports-quirk' => '(squeeze)-backports*',
513 'dgit-distro.debian-backports.mirror' => 'http://backports.debian.org/debian-backports/',
514 'dgit-distro.ubuntu.git-check' => 'false',
515 'dgit-distro.ubuntu.mirror' => 'http://archive.ubuntu.com/ubuntu',
516 'dgit-distro.test-dummy.ssh' => "$td/ssh",
517 'dgit-distro.test-dummy.username' => "alice",
518 'dgit-distro.test-dummy.git-check' => "ssh-cmd",
519 'dgit-distro.test-dummy.git-create' => "ssh-cmd",
520 'dgit-distro.test-dummy.git-url' => "$td/git",
521 'dgit-distro.test-dummy.git-host' => "git",
522 'dgit-distro.test-dummy.git-path' => "$td/git",
523 'dgit-distro.test-dummy.archive-query' => "ftpmasterapi:",
524 'dgit-distro.test-dummy.archive-query-url' => "file://$td/aq/",
525 'dgit-distro.test-dummy.mirror' => "file://$td/mirror/",
526 'dgit-distro.test-dummy.upload-host' => 'test-dummy',
531 return undef if $c =~ /RETURN-UNDEF/;
532 my @cmd = (@git, qw(config --), $c);
535 local ($debuglevel) = $debuglevel-2;
536 $v = cmdoutput_errok @cmd;
543 my $dv = $defcfg{$c};
544 return $dv if defined $dv;
546 badcfg "need value for one of: @_\n".
547 "$us: distro or suite appears not to be (properly) supported";
550 sub access_basedistro () {
551 if (defined $idistro) {
554 return cfg("dgit-suite.$isuite.distro",
555 "dgit.default.distro");
559 sub access_quirk () {
560 # returns (quirk name, distro to use instead or undef, quirk-specific info)
561 my $basedistro = access_basedistro();
562 my $backports_quirk = cfg("dgit-distro.$basedistro.backports-quirk",
564 if (defined $backports_quirk) {
565 my $re = $backports_quirk;
566 $re =~ s/[^-0-9a-z_\%*()]/\\$&/ig;
568 $re =~ s/\%/([-0-9a-z_]+)/
569 or $re =~ m/[()]/ or badcfg "backports-quirk needs \% or ( )";
570 if ($isuite =~ m/^$re$/) {
571 return ('backports',"$basedistro-backports",$1);
574 return ('none',undef);
577 sub access_distros () {
578 # Returns list of distros to try, in order
581 # 0. `instead of' distro name(s) we have been pointed to
582 # 1. the access_quirk distro, if any
583 # 2a. the user's specified distro, or failing that } basedistro
584 # 2b. the distro calculated from the suite }
585 my @l = access_basedistro();
587 my (undef,$quirkdistro) = access_quirk();
588 unshift @l, $quirkdistro;
589 unshift @l, $instead_distro;
590 return grep { defined } @l;
596 # The nesting of these loops determines the search order. We put
597 # the key loop on the outside so that we search all the distros
598 # for each key, before going on to the next key. That means that
599 # if access_cfg is called with a more specific, and then a less
600 # specific, key, an earlier distro can override the less specific
601 # without necessarily overriding any more specific keys. (If the
602 # distro wants to override the more specific keys it can simply do
603 # so; whereas if we did the loop the other way around, it would be
604 # impossible to for an earlier distro to override a less specific
605 # key but not the more specific ones without restating the unknown
606 # values of the more specific keys.
609 # We have to deal with RETURN-UNDEF specially, so that we don't
610 # terminate the search prematurely.
612 if (m/RETURN-UNDEF/) { push @rundef, $_; last; }
615 foreach my $d (access_distros()) {
616 push @cfgs, map { "dgit-distro.$d.$_" } @realkeys;
618 push @cfgs, map { "dgit.default.$_" } @realkeys;
620 my $value = cfg(@cfgs);
624 sub string_to_ssh ($) {
626 if ($spec =~ m/\s/) {
627 return qw(sh -ec), 'exec '.$spec.' "$@"', 'x';
633 sub access_cfg_ssh () {
634 my $gitssh = access_cfg('ssh', 'RETURN-UNDEF');
635 if (!defined $gitssh) {
638 return string_to_ssh $gitssh;
642 sub access_runeinfo ($) {
644 return ": dgit ".access_basedistro()." $info ;";
647 sub access_someuserhost ($) {
649 my $user = access_cfg("$some-user-force", 'RETURN-UNDEF');
650 defined($user) && length($user) or
651 $user = access_cfg("$some-user",'username');
652 my $host = access_cfg("$some-host");
653 return length($user) ? "$user\@$host" : $host;
656 sub access_gituserhost () {
657 return access_someuserhost('git');
660 sub access_giturl (;$) {
662 my $url = access_cfg('git-url','RETURN-UNDEF');
664 my $proto = access_cfg('git-proto', 'RETURN-UNDEF');
665 return undef unless defined $proto;
668 access_gituserhost().
669 access_cfg('git-path');
671 return "$url/$package.git";
674 sub parsecontrolfh ($$;$) {
675 my ($fh, $desc, $allowsigned) = @_;
676 our $dpkgcontrolhash_noissigned;
679 my %opts = ('name' => $desc);
680 $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
681 $c = Dpkg::Control::Hash->new(%opts);
682 $c->parse($fh,$desc) or die "parsing of $desc failed";
683 last if $allowsigned;
684 last if $dpkgcontrolhash_noissigned;
685 my $issigned= $c->get_option('is_pgp_signed');
686 if (!defined $issigned) {
687 $dpkgcontrolhash_noissigned= 1;
688 seek $fh, 0,0 or die "seek $desc: $!";
689 } elsif ($issigned) {
690 fail "control file $desc is (already) PGP-signed. ".
691 " Note that dgit push needs to modify the .dsc and then".
692 " do the signature itself";
701 my ($file, $desc) = @_;
702 my $fh = new IO::Handle;
703 open $fh, '<', $file or die "$file: $!";
704 my $c = parsecontrolfh($fh,$desc);
705 $fh->error and die $!;
711 my ($dctrl,$field) = @_;
712 my $v = $dctrl->{$field};
713 return $v if defined $v;
714 fail "missing field $field in ".$v->get_option('name');
718 my $c = Dpkg::Control::Hash->new();
719 my $p = new IO::Handle;
720 my @cmd = (qw(dpkg-parsechangelog), @_);
721 open $p, '-|', @cmd or die $!;
723 $?=0; $!=0; close $p or failedcmd @cmd;
727 sub git_get_ref ($) {
729 my $got = cmdoutput_errok @git, qw(show-ref --), $refname;
731 $?==256 or fail "git show-ref failed (status $?)";
732 printdebug "ref $refname= [show-ref exited 1]\n";
735 if ($got =~ m/^(\w+) \Q$refname\E$/m) {
736 printdebug "ref $refname=$1\n";
739 printdebug "ref $refname= [no match]\n";
746 defined $d or fail "getcwd failed: $!";
752 sub archive_query ($) {
754 my $query = access_cfg('archive-query','RETURN-UNDEF');
755 $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
758 { no strict qw(refs); &{"${method}_${proto}"}($proto,$data); }
761 sub pool_dsc_subpath ($$) {
762 my ($vsn,$component) = @_; # $package is implict arg
763 my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
764 return "/pool/$component/$prefix/$package/".dscfn($vsn);
767 #---------- `ftpmasterapi' archive query method (nascent) ----------
769 sub archive_api_query_cmd ($) {
771 my @cmd = qw(curl -sS);
772 my $url = access_cfg('archive-query-url');
773 if ($url =~ m#^https://([-.0-9a-z]+)/#) {
775 my $keys = access_cfg('archive-query-tls-key','RETURN-UNDEF');
776 foreach my $key (split /\:/, $keys) {
777 $key =~ s/\%HOST\%/$host/g;
779 fail "for $url: stat $key: $!" unless $!==ENOENT;
782 push @cmd, "--ca-certificate=$key", "--ca-directory=/dev/enoent";
786 push @cmd, $url.$subpath;
792 my ($data, $subpath) = @_;
793 badcfg "ftpmasterapi archive query method takes no data part"
795 my @cmd = archive_api_query_cmd($subpath);
796 my $json = cmdoutput @cmd;
797 return decode_json($json);
800 sub canonicalise_suite_ftpmasterapi () {
801 my ($proto,$data) = @_;
802 my $suites = api_query($data, 'suites');
804 foreach my $entry (@$suites) {
806 my $v = $entry->{$_};
807 defined $v && $v eq $isuite;
809 push @matched, $entry;
811 fail "unknown suite $isuite" unless @matched;
814 @matched==1 or die "multiple matches for suite $isuite\n";
815 $cn = "$matched[0]{codename}";
816 defined $cn or die "suite $isuite info has no codename\n";
817 $cn =~ m/^$suite_re$/ or die "suite $isuite maps to bad codename\n";
819 die "bad ftpmaster api response: $@\n".Dumper(\@matched)
824 sub archive_query_ftpmasterapi () {
825 my ($proto,$data) = @_;
826 my $info = api_query($data, "dsc_in_suite/$isuite/$package");
828 my $digester = Digest::SHA->new(256);
829 foreach my $entry (@$info) {
831 my $vsn = "$entry->{version}";
832 my ($ok,$msg) = version_check $vsn;
833 die "bad version: $msg\n" unless $ok;
834 my $component = "$entry->{component}";
835 $component =~ m/^$component_re$/ or die "bad component";
836 my $filename = "$entry->{filename}";
837 $filename && $filename !~ m#[^-+:._~0-9a-zA-Z/]|^[/.]|/[/.]#
838 or die "bad filename";
839 my $sha256sum = "$entry->{sha256sum}";
840 $sha256sum =~ m/^[0-9a-f]+$/ or die "bad sha256sum";
841 push @rows, [ $vsn, "/pool/$component/$filename",
842 $digester, $sha256sum ];
844 die "bad ftpmaster api response: $@\n".Dumper($entry)
847 @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
851 #---------- `madison' archive query method ----------
853 sub archive_query_madison {
854 return map { [ @$_[0..1] ] } madison_get_parse(@_);
857 sub madison_get_parse {
858 my ($proto,$data) = @_;
859 die unless $proto eq 'madison';
861 $data= access_cfg('madison-distro','RETURN-UNDEF');
862 $data //= access_basedistro();
864 $rmad{$proto,$data,$package} ||= cmdoutput
865 qw(rmadison -asource),"-s$isuite","-u$data",$package;
866 my $rmad = $rmad{$proto,$data,$package};
869 foreach my $l (split /\n/, $rmad) {
870 $l =~ m{^ \s*( [^ \t|]+ )\s* \|
871 \s*( [^ \t|]+ )\s* \|
872 \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
873 \s*( [^ \t|]+ )\s* }x or die "$rmad ?";
874 $1 eq $package or die "$rmad $package ?";
881 $component = access_cfg('archive-query-default-component');
883 $5 eq 'source' or die "$rmad ?";
884 push @out, [$vsn,pool_dsc_subpath($vsn,$component),$newsuite];
886 return sort { -version_compare($a->[0],$b->[0]); } @out;
889 sub canonicalise_suite_madison {
890 # madison canonicalises for us
891 my @r = madison_get_parse(@_);
893 "unable to canonicalise suite using package $package".
894 " which does not appear to exist in suite $isuite;".
895 " --existing-package may help";
899 #---------- `sshpsql' archive query method ----------
902 my ($data,$runeinfo,$sql) = @_;
904 $data= access_someuserhost('sshpsql').':'.
905 access_cfg('sshpsql-dbname');
907 $data =~ m/:/ or badcfg "invalid sshpsql method string \`$data'";
908 my ($userhost,$dbname) = ($`,$'); #';
910 my @cmd = (access_cfg_ssh, $userhost,
911 access_runeinfo("ssh-psql $runeinfo").
912 " export LC_MESSAGES=C; export LC_CTYPE=C;".
913 " ".shellquote qw(psql -A), $dbname, qw(-c), $sql);
915 open P, "-|", @cmd or die $!;
918 printdebug("$debugprefix>|$_|\n");
921 $!=0; $?=0; close P or failedcmd @cmd;
923 my $nrows = pop @rows;
924 $nrows =~ s/^\((\d+) rows?\)$/$1/ or die "$nrows ?";
925 @rows == $nrows+1 or die "$nrows ".(scalar @rows)." ?";
926 @rows = map { [ split /\|/, $_ ] } @rows;
927 my $ncols = scalar @{ shift @rows };
928 die if grep { scalar @$_ != $ncols } @rows;
932 sub sql_injection_check {
933 foreach (@_) { die "$_ $& ?" if m{[^-+=:_.,/0-9a-zA-Z]}; }
936 sub archive_query_sshpsql ($$) {
937 my ($proto,$data) = @_;
938 sql_injection_check $isuite, $package;
939 my @rows = sshpsql($data, "archive-query $isuite $package", <<END);
940 SELECT source.version, component.name, files.filename, files.sha256sum
942 JOIN src_associations ON source.id = src_associations.source
943 JOIN suite ON suite.id = src_associations.suite
944 JOIN dsc_files ON dsc_files.source = source.id
945 JOIN files_archive_map ON files_archive_map.file_id = dsc_files.file
946 JOIN component ON component.id = files_archive_map.component_id
947 JOIN files ON files.id = dsc_files.file
948 WHERE ( suite.suite_name='$isuite' OR suite.codename='$isuite' )
949 AND source.source='$package'
950 AND files.filename LIKE '%.dsc';
952 @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
953 my $digester = Digest::SHA->new(256);
955 my ($vsn,$component,$filename,$sha256sum) = @$_;
956 [ $vsn, "/pool/$component/$filename",$digester,$sha256sum ];
961 sub canonicalise_suite_sshpsql ($$) {
962 my ($proto,$data) = @_;
963 sql_injection_check $isuite;
964 my @rows = sshpsql($data, "canonicalise-suite $isuite", <<END);
965 SELECT suite.codename
966 FROM suite where suite_name='$isuite' or codename='$isuite';
968 @rows = map { $_->[0] } @rows;
969 fail "unknown suite $isuite" unless @rows;
970 die "ambiguous $isuite: @rows ?" if @rows>1;
974 #---------- `dummycat' archive query method ----------
976 sub canonicalise_suite_dummycat ($$) {
977 my ($proto,$data) = @_;
978 my $dpath = "$data/suite.$isuite";
979 if (!open C, "<", $dpath) {
980 $!==ENOENT or die "$dpath: $!";
981 printdebug "dummycat canonicalise_suite $isuite $dpath ENOENT\n";
985 chomp or die "$dpath: $!";
987 printdebug "dummycat canonicalise_suite $isuite $dpath = $_\n";
991 sub archive_query_dummycat ($$) {
992 my ($proto,$data) = @_;
993 canonicalise_suite();
994 my $dpath = "$data/package.$csuite.$package";
995 if (!open C, "<", $dpath) {
996 $!==ENOENT or die "$dpath: $!";
997 printdebug "dummycat query $csuite $package $dpath ENOENT\n";
1005 printdebug "dummycat query $csuite $package $dpath | $_\n";
1006 my @row = split /\s+/, $_;
1007 @row==2 or die "$dpath: $_ ?";
1010 C->error and die "$dpath: $!";
1012 return sort { -version_compare($a->[0],$b->[0]); } @rows;
1015 #---------- archive query entrypoints and rest of program ----------
1017 sub canonicalise_suite () {
1018 return if defined $csuite;
1019 fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
1020 $csuite = archive_query('canonicalise_suite');
1021 if ($isuite ne $csuite) {
1022 progress "canonical suite name for $isuite is $csuite";
1026 sub get_archive_dsc () {
1027 canonicalise_suite();
1028 my @vsns = archive_query('archive_query');
1029 foreach my $vinfo (@vsns) {
1030 my ($vsn,$subpath,$digester,$digest) = @$vinfo;
1031 $dscurl = access_cfg('mirror').$subpath;
1032 $dscdata = url_get($dscurl);
1034 $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
1039 $digester->add($dscdata);
1040 my $got = $digester->hexdigest();
1042 fail "$dscurl has hash $got but".
1043 " archive told us to expect $digest";
1045 my $dscfh = new IO::File \$dscdata, '<' or die $!;
1046 printdebug Dumper($dscdata) if $debuglevel>1;
1047 $dsc = parsecontrolfh($dscfh,$dscurl,1);
1048 printdebug Dumper($dsc) if $debuglevel>1;
1049 my $fmt = getfield $dsc, 'Format';
1050 fail "unsupported source format $fmt, sorry" unless $format_ok{$fmt};
1051 $dsc_checked = !!$digester;
1057 sub check_for_git ();
1058 sub check_for_git () {
1060 my $how = access_cfg('git-check');
1061 if ($how eq 'ssh-cmd') {
1063 (access_cfg_ssh, access_gituserhost(),
1064 access_runeinfo("git-check $package").
1065 " set -e; cd ".access_cfg('git-path').";".
1066 " if test -d $package.git; then echo 1; else echo 0; fi");
1067 my $r= cmdoutput @cmd;
1068 if ($r =~ m/^divert (\w+)$/) {
1070 my ($usedistro,) = access_distros();
1071 $instead_distro= cfg("dgit-distro.$usedistro.diverts.$divert");
1072 $instead_distro =~ s{^/}{ access_basedistro()."/" }e;
1073 printdebug "diverting $divert so using distro $instead_distro\n";
1074 return check_for_git();
1076 failedcmd @cmd unless $r =~ m/^[01]$/;
1078 } elsif ($how eq 'true') {
1080 } elsif ($how eq 'false') {
1083 badcfg "unknown git-check \`$how'";
1087 sub create_remote_git_repo () {
1088 my $how = access_cfg('git-create');
1089 if ($how eq 'ssh-cmd') {
1091 (access_cfg_ssh, access_gituserhost(),
1092 access_runeinfo("git-create $package").
1093 "set -e; cd ".access_cfg('git-path').";".
1094 " cp -a _template $package.git");
1095 } elsif ($how eq 'true') {
1098 badcfg "unknown git-create \`$how'";
1102 our ($dsc_hash,$lastpush_hash);
1104 our $ud = '.git/dgit/unpack';
1109 mkdir $ud or die $!;
1112 sub mktree_in_ud_here () {
1113 runcmd qw(git init -q);
1114 rmtree('.git/objects');
1115 symlink '../../../../objects','.git/objects' or die $!;
1118 sub git_write_tree () {
1119 my $tree = cmdoutput @git, qw(write-tree);
1120 $tree =~ m/^\w+$/ or die "$tree ?";
1124 sub mktree_in_ud_from_only_subdir () {
1125 # changes into the subdir
1127 die unless @dirs==1;
1128 $dirs[0] =~ m#^([^/]+)/\.$# or die;
1131 fail "source package contains .git directory" if stat_exists '.git';
1132 mktree_in_ud_here();
1133 my $format=get_source_format();
1134 if (madformat($format)) {
1137 runcmd @git, qw(add -Af);
1138 my $tree=git_write_tree();
1139 return ($tree,$dir);
1142 sub dsc_files_info () {
1143 foreach my $csumi (['Checksums-Sha256','Digest::SHA', 'new(256)'],
1144 ['Checksums-Sha1', 'Digest::SHA', 'new(1)'],
1145 ['Files', 'Digest::MD5', 'new()']) {
1146 my ($fname, $module, $method) = @$csumi;
1147 my $field = $dsc->{$fname};
1148 next unless defined $field;
1149 eval "use $module; 1;" or die $@;
1151 foreach (split /\n/, $field) {
1153 m/^(\w+) (\d+) (\S+)$/ or
1154 fail "could not parse .dsc $fname line \`$_'";
1155 my $digester = eval "$module"."->$method;" or die $@;
1160 Digester => $digester,
1165 fail "missing any supported Checksums-* or Files field in ".
1166 $dsc->get_option('name');
1170 map { $_->{Filename} } dsc_files_info();
1173 sub is_orig_file ($;$) {
1176 m/\.orig(?:-\w+)?\.tar\.\w+$/ or return 0;
1177 defined $base or return 1;
1181 sub make_commit ($) {
1183 return cmdoutput @git, qw(hash-object -w -t commit), $file;
1186 sub clogp_authline ($) {
1188 my $author = getfield $clogp, 'Maintainer';
1189 $author =~ s#,.*##ms;
1190 my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
1191 my $authline = "$author $date";
1192 $authline =~ m/^[^<>]+ \<\S+\> \d+ [-+]\d+$/ or
1193 fail "unexpected commit author line format \`$authline'".
1194 " (was generated from changelog Maintainer field)";
1198 sub generate_commit_from_dsc () {
1202 foreach my $fi (dsc_files_info()) {
1203 my $f = $fi->{Filename};
1204 die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
1206 link "../../../$f", $f
1210 complete_file_from_dsc('.', $fi);
1212 if (is_orig_file($f)) {
1213 link $f, "../../../../$f"
1219 my $dscfn = "$package.dsc";
1221 open D, ">", $dscfn or die "$dscfn: $!";
1222 print D $dscdata or die "$dscfn: $!";
1223 close D or die "$dscfn: $!";
1224 my @cmd = qw(dpkg-source);
1225 push @cmd, '--no-check' if $dsc_checked;
1226 push @cmd, qw(-x --), $dscfn;
1229 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1230 runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
1231 my $clogp = parsecontrol('../changelog.tmp',"commit's changelog");
1232 my $authline = clogp_authline $clogp;
1233 my $changes = getfield $clogp, 'Changes';
1234 open C, ">../commit.tmp" or die $!;
1235 print C <<END or die $!;
1242 # imported from the archive
1245 my $outputhash = make_commit qw(../commit.tmp);
1246 my $cversion = getfield $clogp, 'Version';
1247 progress "synthesised git commit from .dsc $cversion";
1248 if ($lastpush_hash) {
1249 runcmd @git, qw(reset --hard), $lastpush_hash;
1250 runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
1251 my $oldclogp = parsecontrol('../changelogold.tmp','previous changelog');
1252 my $oversion = getfield $oldclogp, 'Version';
1254 version_compare($oversion, $cversion);
1256 # git upload/ is earlier vsn than archive, use archive
1257 open C, ">../commit2.tmp" or die $!;
1258 print C <<END or die $!;
1260 parent $lastpush_hash
1265 Record $package ($cversion) in archive suite $csuite
1267 $outputhash = make_commit qw(../commit2.tmp);
1268 } elsif ($vcmp > 0) {
1269 print STDERR <<END or die $!;
1271 Version actually in archive: $cversion (older)
1272 Last allegedly pushed/uploaded: $oversion (newer or same)
1275 $outputhash = $lastpush_hash;
1277 $outputhash = $lastpush_hash;
1280 changedir '../../../..';
1281 runcmd @git, qw(update-ref -m),"dgit fetch import $cversion",
1282 'DGIT_ARCHIVE', $outputhash;
1283 cmdoutput @git, qw(log -n2), $outputhash;
1284 # ... gives git a chance to complain if our commit is malformed
1289 sub complete_file_from_dsc ($$) {
1290 our ($dstdir, $fi) = @_;
1291 # Ensures that we have, in $dir, the file $fi, with the correct
1292 # contents. (Downloading it from alongside $dscurl if necessary.)
1294 my $f = $fi->{Filename};
1295 my $tf = "$dstdir/$f";
1298 if (stat_exists $tf) {
1299 progress "using existing $f";
1302 $furl =~ s{/[^/]+$}{};
1304 die "$f ?" unless $f =~ m/^${package}_/;
1305 die "$f ?" if $f =~ m#/#;
1306 runcmd_ordryrun_local @curl,qw(-o),$tf,'--',"$furl";
1307 next if !act_local();
1311 open F, "<", "$tf" or die "$tf: $!";
1312 $fi->{Digester}->reset();
1313 $fi->{Digester}->addfile(*F);
1314 F->error and die $!;
1315 my $got = $fi->{Digester}->hexdigest();
1316 $got eq $fi->{Hash} or
1317 fail "file $f has hash $got but .dsc".
1318 " demands hash $fi->{Hash} ".
1319 ($downloaded ? "(got wrong file from archive!)"
1320 : "(perhaps you should delete this file?)");
1323 sub ensure_we_have_orig () {
1324 foreach my $fi (dsc_files_info()) {
1325 my $f = $fi->{Filename};
1326 next unless is_orig_file($f);
1327 complete_file_from_dsc('..', $fi);
1332 return cmdoutput @git, qw(rev-parse), "$_[0]~0";
1335 sub is_fast_fwd ($$) {
1336 my ($ancestor,$child) = @_;
1337 my @cmd = (@git, qw(merge-base), $ancestor, $child);
1338 my $mb = cmdoutput_errok @cmd;
1340 return rev_parse($mb) eq rev_parse($ancestor);
1342 $?==256 or failedcmd @cmd;
1347 sub git_fetch_us () {
1348 runcmd_ordryrun_local @git, qw(fetch),access_giturl(),fetchspec();
1351 sub fetch_from_archive () {
1352 # ensures that lrref() is what is actually in the archive,
1353 # one way or another
1357 foreach my $field (@ourdscfield) {
1358 $dsc_hash = $dsc->{$field};
1359 last if defined $dsc_hash;
1361 if (defined $dsc_hash) {
1362 $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
1364 progress "last upload to archive specified git hash";
1366 progress "last upload to archive has NO git hash";
1369 progress "no version available from the archive";
1372 $lastpush_hash = git_get_ref(lrref());
1373 printdebug "previous reference hash=$lastpush_hash\n";
1375 if (defined $dsc_hash) {
1376 fail "missing remote git history even though dsc has hash -".
1377 " could not find ref ".lrref().
1378 " (should have been fetched from ".access_giturl()."#".rrref().")"
1379 unless $lastpush_hash;
1381 ensure_we_have_orig();
1382 if ($dsc_hash eq $lastpush_hash) {
1383 } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
1384 print STDERR <<END or die $!;
1386 Git commit in archive is behind the last version allegedly pushed/uploaded.
1387 Commit referred to by archive: $dsc_hash
1388 Last allegedly pushed/uploaded: $lastpush_hash
1391 $hash = $lastpush_hash;
1393 fail "git head (".lrref()."=$lastpush_hash) is not a ".
1394 "descendant of archive's .dsc hash ($dsc_hash)";
1397 $hash = generate_commit_from_dsc();
1398 } elsif ($lastpush_hash) {
1399 # only in git, not in the archive yet
1400 $hash = $lastpush_hash;
1401 print STDERR <<END or die $!;
1403 Package not found in the archive, but has allegedly been pushed using dgit.
1407 printdebug "nothing found!\n";
1408 if (defined $skew_warning_vsn) {
1409 print STDERR <<END or die $!;
1411 Warning: relevant archive skew detected.
1412 Archive allegedly contains $skew_warning_vsn
1413 But we were not able to obtain any version from the archive or git.
1419 printdebug "current hash=$hash\n";
1420 if ($lastpush_hash) {
1421 fail "not fast forward on last upload branch!".
1422 " (archive's version left in DGIT_ARCHIVE)"
1423 unless is_fast_fwd($lastpush_hash, $hash);
1425 if (defined $skew_warning_vsn) {
1427 printdebug "SKEW CHECK WANT $skew_warning_vsn\n";
1428 my $clogf = ".git/dgit/changelog.tmp";
1429 runcmd shell_cmd "exec >$clogf",
1430 @git, qw(cat-file blob), "$hash:debian/changelog";
1431 my $gotclogp = parsechangelog("-l$clogf");
1432 my $got_vsn = getfield $gotclogp, 'Version';
1433 printdebug "SKEW CHECK GOT $got_vsn\n";
1434 if (version_compare($got_vsn, $skew_warning_vsn) < 0) {
1435 print STDERR <<END or die $!;
1437 Warning: archive skew detected. Using the available version:
1438 Archive allegedly contains $skew_warning_vsn
1439 We were able to obtain only $got_vsn
1444 if ($lastpush_hash ne $hash) {
1445 my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
1449 dryrun_report @upd_cmd;
1457 canonicalise_suite();
1458 badusage "dry run makes no sense with clone" unless act_local();
1459 my $hasgit = check_for_git();
1460 mkdir $dstdir or die "$dstdir $!";
1462 runcmd @git, qw(init -q);
1463 my $giturl = access_giturl(1);
1464 if (defined $giturl) {
1465 runcmd @git, qw(config), "remote.$remotename.fetch", fetchspec();
1466 open H, "> .git/HEAD" or die $!;
1467 print H "ref: ".lref()."\n" or die $!;
1469 runcmd @git, qw(remote add), 'origin', $giturl;
1472 progress "fetching existing git history";
1474 runcmd_ordryrun_local @git, qw(fetch origin);
1476 progress "starting new git history";
1478 fetch_from_archive() or no_such_package;
1479 my $vcsgiturl = $dsc->{'Vcs-Git'};
1480 if (length $vcsgiturl) {
1481 $vcsgiturl =~ s/\s+-b\s+\S+//g;
1482 runcmd @git, qw(remote add vcs-git), $vcsgiturl;
1484 runcmd @git, qw(reset --hard), lrref();
1485 printdone "ready for work in $dstdir";
1489 if (check_for_git()) {
1492 fetch_from_archive() or no_such_package();
1493 printdone "fetched into ".lrref();
1498 runcmd_ordryrun_local @git, qw(merge -m),"Merge from $csuite [dgit]",
1500 printdone "fetched to ".lrref()." and merged into HEAD";
1503 sub check_not_dirty () {
1504 return if $ignoredirty;
1505 my @cmd = (@git, qw(diff --quiet HEAD));
1507 $!=0; $?=0; system @cmd;
1508 return if !$! && !$?;
1509 if (!$! && $?==256) {
1510 fail "working tree is dirty (does not match HEAD)";
1516 sub commit_admin ($) {
1519 runcmd_ordryrun_local @git, qw(commit -m), $m;
1522 sub commit_quilty_patch () {
1523 my $output = cmdoutput @git, qw(status --porcelain);
1525 foreach my $l (split /\n/, $output) {
1526 next unless $l =~ m/\S/;
1527 if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
1531 delete $adds{'.pc'}; # if there wasn't one before, don't add it
1533 progress "nothing quilty to commit, ok.";
1536 runcmd_ordryrun_local @git, qw(add), sort keys %adds;
1537 commit_admin "Commit Debian 3.0 (quilt) metadata";
1540 sub get_source_format () {
1541 if (!open F, "debian/source/format") {
1542 die $! unless $!==&ENOENT;
1546 F->error and die $!;
1553 return 0 unless $format eq '3.0 (quilt)';
1554 if ($quilt_mode eq 'nocheck') {
1555 progress "Not doing any fixup of \`$format' due to --no-quilt-fixup";
1558 progress "Format \`$format', checking/updating patch stack";
1562 sub push_parse_changelog ($) {
1565 my $clogp = Dpkg::Control::Hash->new();
1566 $clogp->load($clogpfn) or die;
1568 $package = getfield $clogp, 'Source';
1569 my $cversion = getfield $clogp, 'Version';
1570 my $tag = debiantag($cversion);
1571 runcmd @git, qw(check-ref-format), $tag;
1573 my $dscfn = dscfn($cversion);
1575 return ($clogp, $cversion, $tag, $dscfn);
1578 sub push_parse_dsc ($$$) {
1579 my ($dscfn,$dscfnwhat, $cversion) = @_;
1580 $dsc = parsecontrol($dscfn,$dscfnwhat);
1581 my $dversion = getfield $dsc, 'Version';
1582 my $dscpackage = getfield $dsc, 'Source';
1583 ($dscpackage eq $package && $dversion eq $cversion) or
1584 fail "$dscfn is for $dscpackage $dversion".
1585 " but debian/changelog is for $package $cversion";
1588 sub push_mktag ($$$$$$$) {
1589 my ($head,$clogp,$tag,
1591 $changesfile,$changesfilewhat,
1594 $dsc->{$ourdscfield[0]} = $head;
1595 $dsc->save("$dscfn.tmp") or die $!;
1597 my $changes = parsecontrol($changesfile,$changesfilewhat);
1598 foreach my $field (qw(Source Distribution Version)) {
1599 $changes->{$field} eq $clogp->{$field} or
1600 fail "changes field $field \`$changes->{$field}'".
1601 " does not match changelog \`$clogp->{$field}'";
1604 my $cversion = getfield $clogp, 'Version';
1605 my $clogsuite = getfield $clogp, 'Distribution';
1607 # We make the git tag by hand because (a) that makes it easier
1608 # to control the "tagger" (b) we can do remote signing
1609 my $authline = clogp_authline $clogp;
1610 my $delibs = join(" ", "",@deliberatelies);
1611 my $declaredistro = access_basedistro();
1612 open TO, '>', $tfn->('.tmp') or die $!;
1613 print TO <<END or die $!;
1619 $package release $cversion for $clogsuite ($csuite) [dgit]
1620 [dgit distro=$declaredistro$delibs]
1622 foreach my $ref (sort keys %supersedes) {
1623 print TO <<END or die $!;
1624 [dgit supersede:$ref=$supersedes{$ref}]
1630 my $tagobjfn = $tfn->('.tmp');
1632 if (!defined $keyid) {
1633 $keyid = access_cfg('keyid','RETURN-UNDEF');
1635 unlink $tfn->('.tmp.asc') or $!==&ENOENT or die $!;
1636 my @sign_cmd = (@gpg, qw(--detach-sign --armor));
1637 push @sign_cmd, qw(-u),$keyid if defined $keyid;
1638 push @sign_cmd, $tfn->('.tmp');
1639 runcmd_ordryrun @sign_cmd;
1641 $tagobjfn = $tfn->('.signed.tmp');
1642 runcmd shell_cmd "exec >$tagobjfn", qw(cat --),
1643 $tfn->('.tmp'), $tfn->('.tmp.asc');
1650 sub sign_changes ($) {
1651 my ($changesfile) = @_;
1653 my @debsign_cmd = @debsign;
1654 push @debsign_cmd, "-k$keyid" if defined $keyid;
1655 push @debsign_cmd, "-p$gpg[0]" if $gpg[0] ne 'gpg';
1656 push @debsign_cmd, $changesfile;
1657 runcmd_ordryrun @debsign_cmd;
1662 printdebug "actually entering push\n";
1665 access_giturl(); # check that success is vaguely likely
1667 my $clogpfn = ".git/dgit/changelog.822.tmp";
1668 runcmd shell_cmd "exec >$clogpfn", qw(dpkg-parsechangelog);
1670 responder_send_file('parsed-changelog', $clogpfn);
1672 my ($clogp, $cversion, $tag, $dscfn) =
1673 push_parse_changelog("$clogpfn");
1675 my $dscpath = "$buildproductsdir/$dscfn";
1676 stat_exists $dscpath or
1677 fail "looked for .dsc $dscfn, but $!;".
1678 " maybe you forgot to build";
1680 responder_send_file('dsc', $dscpath);
1682 push_parse_dsc($dscpath, $dscfn, $cversion);
1684 my $format = getfield $dsc, 'Format';
1685 printdebug "format $format\n";
1686 if (madformat($format)) {
1687 commit_quilty_patch();
1691 progress "checking that $dscfn corresponds to HEAD";
1692 runcmd qw(dpkg-source -x --),
1693 $dscpath =~ m#^/# ? $dscpath : "../../../$dscpath";
1694 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1695 changedir '../../../..';
1696 my $diffopt = $debuglevel>0 ? '--exit-code' : '--quiet';
1697 my @diffcmd = (@git, qw(diff), $diffopt, $tree);
1698 debugcmd "+",@diffcmd;
1700 my $r = system @diffcmd;
1703 fail "$dscfn specifies a different tree to your HEAD commit;".
1704 " perhaps you forgot to build".
1705 ($diffopt eq '--exit-code' ? "" :
1706 " (run with -D to see full diff output)");
1712 #do fast forward check and maybe fake merge
1713 # if (!is_fast_fwd(mainbranch
1714 # runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
1715 # map { lref($_).":".rref($_) }
1717 my $head = rev_parse('HEAD');
1718 if (!$changesfile) {
1719 my $multi = "$buildproductsdir/".
1720 "${package}_".(stripepoch $cversion)."_multi.changes";
1721 if (stat_exists "$multi") {
1722 $changesfile = $multi;
1724 my $pat = "${package}_".(stripepoch $cversion)."_*.changes";
1725 my @cs = glob "$buildproductsdir/$pat";
1726 fail "failed to find unique changes file".
1727 " (looked for $pat in $buildproductsdir, or $multi);".
1728 " perhaps you need to use dgit -C"
1730 ($changesfile) = @cs;
1733 $changesfile = "$buildproductsdir/$changesfile";
1736 responder_send_file('changes',$changesfile);
1737 responder_send_command("param head $head");
1738 responder_send_command("param csuite $csuite");
1740 my $forceflag = deliberately('not-fast-forward') ? '+' : '';
1741 if ($forceflag && defined $lastpush_hash) {
1742 git_for_each_tag_referring($lastpush_hash, sub {
1743 my ($objid,$fullrefname,$tagname) = @_;
1744 responder_send_command("supersedes $fullrefname=$objid");
1745 $supersedes{$fullrefname} = $objid;
1749 my $tfn = sub { ".git/dgit/tag$_[0]"; };
1752 if ($we_are_responder) {
1753 $tagobjfn = $tfn->('.signed.tmp');
1754 responder_receive_files('signed-tag', $tagobjfn);
1757 push_mktag($head,$clogp,$tag,
1759 $changesfile,$changesfile,
1763 my $tag_obj_hash = cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
1764 runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
1765 runcmd_ordryrun_local @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
1766 runcmd_ordryrun @git, qw(tag -v --), $tag;
1768 if (!check_for_git()) {
1769 create_remote_git_repo();
1771 runcmd_ordryrun @git, qw(push),access_giturl(),
1772 $forceflag."HEAD:".rrref(), "refs/tags/$tag";
1773 runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), 'HEAD';
1775 if ($we_are_responder) {
1776 my $dryrunsuffix = act_local() ? "" : ".tmp";
1777 responder_receive_files('signed-dsc-changes',
1778 "$dscpath$dryrunsuffix",
1779 "$changesfile$dryrunsuffix");
1782 rename "$dscpath.tmp",$dscpath or die "$dscfn $!";
1784 progress "[new .dsc left in $dscpath.tmp]";
1786 sign_changes $changesfile;
1789 my $host = access_cfg('upload-host','RETURN-UNDEF');
1790 my @hostarg = defined($host) ? ($host,) : ();
1791 runcmd_ordryrun @dput, @hostarg, $changesfile;
1792 printdone "pushed and uploaded $cversion";
1794 responder_send_command("complete");
1800 badusage "-p is not allowed with clone; specify as argument instead"
1801 if defined $package;
1804 } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
1805 ($package,$isuite) = @ARGV;
1806 } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
1807 ($package,$dstdir) = @ARGV;
1808 } elsif (@ARGV==3) {
1809 ($package,$isuite,$dstdir) = @ARGV;
1811 badusage "incorrect arguments to dgit clone";
1813 $dstdir ||= "$package";
1815 if (stat_exists $dstdir) {
1816 fail "$dstdir already exists";
1820 if ($rmonerror && !$dryrun_level) {
1821 $cwd_remove= getcwd();
1823 return unless defined $cwd_remove;
1824 if (!chdir "$cwd_remove") {
1825 return if $!==&ENOENT;
1826 die "chdir $cwd_remove: $!";
1828 rmtree($dstdir) or die "remove $dstdir: $!\n";
1833 $cwd_remove = undef;
1836 sub branchsuite () {
1837 my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
1838 if ($branch =~ m#$lbranch_re#o) {
1845 sub fetchpullargs () {
1846 if (!defined $package) {
1847 my $sourcep = parsecontrol('debian/control','debian/control');
1848 $package = getfield $sourcep, 'Source';
1851 # $isuite = branchsuite(); # this doesn't work because dak hates canons
1853 my $clogp = parsechangelog();
1854 $isuite = getfield $clogp, 'Distribution';
1856 canonicalise_suite();
1857 progress "fetching from suite $csuite";
1858 } elsif (@ARGV==1) {
1860 canonicalise_suite();
1862 badusage "incorrect arguments to dgit fetch or dgit pull";
1880 badusage "-p is not allowed with dgit push" if defined $package;
1882 my $clogp = parsechangelog();
1883 $package = getfield $clogp, 'Source';
1886 } elsif (@ARGV==1) {
1887 ($specsuite) = (@ARGV);
1889 badusage "incorrect arguments to dgit push";
1891 $isuite = getfield $clogp, 'Distribution';
1893 local ($package) = $existing_package; # this is a hack
1894 canonicalise_suite();
1896 if (defined $specsuite && $specsuite ne $isuite) {
1897 canonicalise_suite();
1898 $csuite eq $specsuite or
1899 fail "dgit push: changelog specifies $isuite ($csuite)".
1900 " but command line specifies $specsuite";
1902 if (check_for_git()) {
1905 if (fetch_from_archive()) {
1906 is_fast_fwd(lrref(), 'HEAD') or
1907 fail "dgit push: HEAD is not a descendant".
1908 " of the archive's version.\n".
1909 "$us: To overwrite it, use git merge -s ours ".lrref().".";
1912 fail "package appears to be new in this suite;".
1913 " if this is intentional, use --new";
1918 #---------- remote commands' implementation ----------
1920 sub cmd_remote_push_build_host {
1921 my ($nrargs) = shift @ARGV;
1922 my (@rargs) = @ARGV[0..$nrargs-1];
1923 @ARGV = @ARGV[$nrargs..$#ARGV];
1925 my ($dir,$vsnwant) = @rargs;
1926 # vsnwant is a comma-separated list; we report which we have
1927 # chosen in our ready response (so other end can tell if they
1930 $we_are_responder = 1;
1932 open PI, "<&STDIN" or die $!;
1933 open STDIN, "/dev/null" or die $!;
1934 open PO, ">&STDOUT" or die $!;
1936 open STDOUT, ">&STDERR" or die $!;
1940 fail "build host has dgit rpush protocol version".
1941 " $rpushprotovsn but invocation host has $vsnwant"
1942 unless grep { $rpushprotovsn eq $_ } split /,/, $vsnwant;
1944 responder_send_command("dgit-remote-push-ready $rpushprotovsn");
1950 sub cmd_remote_push_responder { cmd_remote_push_build_host(); }
1951 # ... for compatibility with proto vsn.1 dgit (just so that user gets
1952 # a good error message)
1958 my $report = i_child_report();
1959 if (defined $report) {
1960 printdebug "($report)\n";
1961 } elsif ($i_child_pid) {
1962 printdebug "(killing build host child $i_child_pid)\n";
1963 kill 15, $i_child_pid;
1965 if (defined $i_tmp && !defined $initiator_tempdir) {
1967 eval { rmtree $i_tmp; };
1971 END { i_cleanup(); }
1974 my ($base,$selector,@args) = @_;
1975 $selector =~ s/\-/_/g;
1976 { no strict qw(refs); &{"${base}_${selector}"}(@args); }
1982 if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
1989 my @rargs = ($dir,$rpushprotovsn);
1992 push @rdgit, @ropts;
1993 push @rdgit, qw(remote-push-build-host), (scalar @rargs), @rargs;
1995 my @cmd = (@ssh, $host, shellquote @rdgit);
1998 if (defined $initiator_tempdir) {
1999 rmtree $initiator_tempdir;
2000 mkdir $initiator_tempdir, 0700 or die "$initiator_tempdir: $!";
2001 $i_tmp = $initiator_tempdir;
2005 $i_child_pid = open2(\*RO, \*RI, @cmd);
2007 initiator_expect { m/^dgit-remote-push-ready/ };
2009 my ($icmd,$iargs) = initiator_expect {
2010 m/^(\S+)(?: (.*))?$/;
2013 i_method "i_resp", $icmd, $iargs;
2017 sub i_resp_progress ($) {
2019 my $msg = protocol_read_bytes \*RO, $rhs;
2023 sub i_resp_complete {
2024 my $pid = $i_child_pid;
2025 $i_child_pid = undef; # prevents killing some other process with same pid
2026 printdebug "waiting for build host child $pid...\n";
2027 my $got = waitpid $pid, 0;
2028 die $! unless $got == $pid;
2029 die "build host child failed $?" if $?;
2032 printdebug "all done\n";
2036 sub i_resp_file ($) {
2038 my $localname = i_method "i_localname", $keyword;
2039 my $localpath = "$i_tmp/$localname";
2040 stat_exists $localpath and
2041 badproto \*RO, "file $keyword ($localpath) twice";
2042 protocol_receive_file \*RO, $localpath;
2043 i_method "i_file", $keyword;
2048 sub i_resp_param ($) {
2049 $_[0] =~ m/^(\S+) (.*)$/ or badproto \*RO, "bad param spec";
2053 sub i_resp_supersedes ($) {
2054 $_[0] =~ m#^(refs/tags/\S+)=(\w+)$#
2055 or badproto \*RO, "bad supersedes spec";
2056 my $r = system qw(git check-ref-format), $1;
2057 die "bad supersedes ref spec ($r)" if $r;
2058 $supersedes{$1} = $2;
2063 sub i_resp_want ($) {
2065 die "$keyword ?" if $i_wanted{$keyword}++;
2066 my @localpaths = i_method "i_want", $keyword;
2067 printdebug "[[ $keyword @localpaths\n";
2068 foreach my $localpath (@localpaths) {
2069 protocol_send_file \*RI, $localpath;
2071 print RI "files-end\n" or die $!;
2074 our ($i_clogp, $i_version, $i_tag, $i_dscfn, $i_changesfn);
2076 sub i_localname_parsed_changelog {
2077 return "remote-changelog.822";
2079 sub i_file_parsed_changelog {
2080 ($i_clogp, $i_version, $i_tag, $i_dscfn) =
2081 push_parse_changelog "$i_tmp/remote-changelog.822";
2082 die if $i_dscfn =~ m#/|^\W#;
2085 sub i_localname_dsc {
2086 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
2091 sub i_localname_changes {
2092 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
2093 $i_changesfn = $i_dscfn;
2094 $i_changesfn =~ s/\.dsc$/_dgit.changes/ or die;
2095 return $i_changesfn;
2097 sub i_file_changes { }
2099 sub i_want_signed_tag {
2100 printdebug Dumper(\%i_param, $i_dscfn);
2101 defined $i_param{'head'} && defined $i_dscfn && defined $i_clogp
2102 && defined $i_param{'csuite'}
2103 or badproto \*RO, "premature desire for signed-tag";
2104 my $head = $i_param{'head'};
2105 die if $head =~ m/[^0-9a-f]/ || $head !~ m/^../;
2107 die unless $i_param{'csuite'} =~ m/^$suite_re$/;
2109 push_parse_dsc $i_dscfn, 'remote dsc', $i_version;
2112 push_mktag $head, $i_clogp, $i_tag,
2114 $i_changesfn, 'remote changes',
2115 sub { "tag$_[0]"; };
2120 sub i_want_signed_dsc_changes {
2121 rename "$i_dscfn.tmp","$i_dscfn" or die "$i_dscfn $!";
2122 sign_changes $i_changesfn;
2123 return ($i_dscfn, $i_changesfn);
2126 #---------- building etc. ----------
2132 #----- `3.0 (quilt)' handling -----
2134 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
2136 sub quiltify_dpkg_commit ($$$;$) {
2137 my ($patchname,$author,$msg, $xinfo) = @_;
2141 my $descfn = ".git/dgit/quilt-description.tmp";
2142 open O, '>', $descfn or die "$descfn: $!";
2145 $msg =~ s/^\s+$/ ./mg;
2146 print O <<END or die $!;
2156 local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
2157 local $ENV{'VISUAL'} = $ENV{'EDITOR'};
2158 local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
2159 runcmd_ordryrun_local @dpkgsource, qw(--commit .), $patchname;
2163 sub quiltify_trees_differ ($$) {
2165 # returns 1 iff the two tree objects differ other than in debian/
2167 my @cmd = (@git, qw(diff-tree --name-only -z), $x, $y);
2168 my $diffs= cmdoutput @cmd;
2169 foreach my $f (split /\0/, $diffs) {
2170 next if $f eq 'debian';
2176 sub quiltify_tree_sentinelfiles ($) {
2177 # lists the `sentinel' files present in the tree
2179 my $r = cmdoutput @git, qw(ls-tree --name-only), $x,
2180 qw(-- debian/rules debian/control);
2186 my ($clogp,$target) = @_;
2188 # Quilt patchification algorithm
2190 # We search backwards through the history of the main tree's HEAD
2191 # (T) looking for a start commit S whose tree object is identical
2192 # to to the patch tip tree (ie the tree corresponding to the
2193 # current dpkg-committed patch series). For these purposes
2194 # `identical' disregards anything in debian/ - this wrinkle is
2195 # necessary because dpkg-source treates debian/ specially.
2197 # We can only traverse edges where at most one of the ancestors'
2198 # trees differs (in changes outside in debian/). And we cannot
2199 # handle edges which change .pc/ or debian/patches. To avoid
2200 # going down a rathole we avoid traversing edges which introduce
2201 # debian/rules or debian/control. And we set a limit on the
2202 # number of edges we are willing to look at.
2204 # If we succeed, we walk forwards again. For each traversed edge
2205 # PC (with P parent, C child) (starting with P=S and ending with
2206 # C=T) to we do this:
2208 # - dpkg-source --commit with a patch name and message derived from C
2209 # After traversing PT, we git commit the changes which
2210 # should be contained within debian/patches.
2212 changedir '../fake';
2213 mktree_in_ud_here();
2215 runcmd @git, 'add', '.';
2216 my $oldtiptree=git_write_tree();
2217 changedir '../work';
2219 # The search for the path S..T is breadth-first. We maintain a
2220 # todo list containing search nodes. A search node identifies a
2221 # commit, and looks something like this:
2223 # Commit => $git_commit_id,
2224 # Child => $c, # or undef if P=T
2225 # Whynot => $reason_edge_PC_unsuitable, # in @nots only
2226 # Nontrivial => true iff $p..$c has relevant changes
2233 my %considered; # saves being exponential on some weird graphs
2235 my $t_sentinels = quiltify_tree_sentinelfiles $target;
2238 my ($search,$whynot) = @_;
2239 printdebug " search NOT $search->{Commit} $whynot\n";
2240 $search->{Whynot} = $whynot;
2241 push @nots, $search;
2242 no warnings qw(exiting);
2251 my $c = shift @todo;
2252 next if $considered{$c->{Commit}}++;
2254 $not->($c, "maximum search space exceeded") if --$max_work <= 0;
2256 printdebug "quiltify investigate $c->{Commit}\n";
2259 if (!quiltify_trees_differ $c->{Commit}, $oldtiptree) {
2260 printdebug " search finished hooray!\n";
2265 if ($quilt_mode eq 'nofix') {
2266 fail "quilt fixup required but quilt mode is \`nofix'\n".
2267 "HEAD commit $c->{Commit} differs from tree implied by ".
2268 " debian/patches (tree object $oldtiptree)";
2270 if ($quilt_mode eq 'smash') {
2271 printdebug " search quitting smash\n";
2275 my $c_sentinels = quiltify_tree_sentinelfiles $c->{Commit};
2276 $not->($c, "has $c_sentinels not $t_sentinels")
2277 if $c_sentinels ne $t_sentinels;
2279 my $commitdata = cmdoutput @git, qw(cat-file commit), $c->{Commit};
2280 $commitdata =~ m/\n\n/;
2282 my @parents = ($commitdata =~ m/^parent (\w+)$/gm);
2283 @parents = map { { Commit => $_, Child => $c } } @parents;
2285 $not->($c, "root commit") if !@parents;
2287 foreach my $p (@parents) {
2288 $p->{Nontrivial}= quiltify_trees_differ $p->{Commit},$c->{Commit};
2290 my $ndiffers = grep { $_->{Nontrivial} } @parents;
2291 $not->($c, "merge ($ndiffers nontrivial parents)") if $ndiffers > 1;
2293 foreach my $p (@parents) {
2294 printdebug "considering C=$c->{Commit} P=$p->{Commit}\n";
2296 my @cmd= (@git, qw(diff-tree -r --name-only),
2297 $p->{Commit},$c->{Commit}, qw(-- debian/patches .pc));
2298 my $patchstackchange = cmdoutput @cmd;
2299 if (length $patchstackchange) {
2300 $patchstackchange =~ s/\n/,/g;
2301 $not->($p, "changed $patchstackchange");
2304 printdebug " search queue P=$p->{Commit} ",
2305 ($p->{Nontrivial} ? "NT" : "triv"),"\n";
2311 printdebug "quiltify want to smash\n";
2314 my $x = $_[0]{Commit};
2315 $x =~ s/(.*?[0-9a-z]{8})[0-9a-z]*$/$1/;
2318 my $reportnot = sub {
2320 my $s = $abbrev->($notp);
2321 my $c = $notp->{Child};
2322 $s .= "..".$abbrev->($c) if $c;
2323 $s .= ": ".$c->{Whynot};
2326 if ($quilt_mode eq 'linear') {
2327 print STDERR "$us: quilt fixup cannot be linear. Stopped at:\n";
2328 foreach my $notp (@nots) {
2329 print STDERR "$us: ", $reportnot->($notp), "\n";
2331 fail "quilt fixup naive history linearisation failed.\n".
2332 "Use dpkg-source --commit by hand; or, --quilt=smash for one ugly patch";
2333 } elsif ($quilt_mode eq 'smash') {
2334 } elsif ($quilt_mode eq 'auto') {
2335 progress "quilt fixup cannot be linear, smashing...";
2337 die "$quilt_mode ?";
2342 my $msg = cmdoutput @git, qw(log), "-n$ncommits";
2344 quiltify_dpkg_commit "auto-$version-$target-$time",
2345 (getfield $clogp, 'Maintainer'),
2346 "Automatically generated patch ($clogp->{Version})\n".
2347 "Last (up to) $ncommits git changes, FYI:\n\n". $msg;
2351 progress "quiltify linearisation planning successful, executing...";
2353 for (my $p = $sref_S;
2354 my $c = $p->{Child};
2356 printdebug "quiltify traverse $p->{Commit}..$c->{Commit}\n";
2357 next unless $p->{Nontrivial};
2359 my $cc = $c->{Commit};
2361 my $commitdata = cmdoutput @git, qw(cat-file commit), $cc;
2362 $commitdata =~ m/\n\n/ or die "$c ?";
2365 $commitdata =~ m/^author (.*) \d+ [-+0-9]+$/m or die "$cc ?";
2368 $msg =~ s/^(.*)\n*/$1\n/ or die "$cc $msg ?";
2371 my $patchname = $title;
2372 $patchname =~ s/[.:]$//;
2373 $patchname =~ y/ A-Z/-a-z/;
2374 $patchname =~ y/-a-z0-9_.+=~//cd;
2375 $patchname =~ s/^\W/x-$&/;
2376 $patchname = substr($patchname,0,40);
2379 stat "debian/patches/$patchname$index";
2381 $!==ENOENT or die "$patchname$index $!";
2383 runcmd @git, qw(checkout -q), $cc;
2385 # We use the tip's changelog so that dpkg-source doesn't
2386 # produce complaining messages from dpkg-parsechangelog. None
2387 # of the information dpkg-source gets from the changelog is
2388 # actually relevant - it gets put into the original message
2389 # which dpkg-source provides our stunt editor, and then
2391 runcmd @git, qw(checkout -q), $target, qw(debian/changelog);
2393 quiltify_dpkg_commit "$patchname$index", $author, $msg,
2394 "X-Dgit-Generated: $clogp->{Version} $cc\n";
2396 runcmd @git, qw(checkout -q), $cc, qw(debian/changelog);
2399 runcmd @git, qw(checkout -q master);
2402 sub build_maybe_quilt_fixup () {
2403 my $format=get_source_format;
2404 return unless madformat $format;
2408 # - honour any existing .pc in case it has any strangeness
2409 # - determine the git commit corresponding to the tip of
2410 # the patch stack (if there is one)
2411 # - if there is such a git commit, convert each subsequent
2412 # git commit into a quilt patch with dpkg-source --commit
2413 # - otherwise convert all the differences in the tree into
2414 # a single git commit
2418 # Our git tree doesn't necessarily contain .pc. (Some versions of
2419 # dgit would include the .pc in the git tree.) If there isn't
2420 # one, we need to generate one by unpacking the patches that we
2423 # We first look for a .pc in the git tree. If there is one, we
2424 # will use it. (This is not the normal case.)
2426 # Otherwise need to regenerate .pc so that dpkg-source --commit
2427 # can work. We do this as follows:
2428 # 1. Collect all relevant .orig from parent directory
2429 # 2. Generate a debian.tar.gz out of
2430 # debian/{patches,rules,source/format}
2431 # 3. Generate a fake .dsc containing just these fields:
2432 # Format Source Version Files
2433 # 4. Extract the fake .dsc
2434 # Now the fake .dsc has a .pc directory.
2435 # (In fact we do this in every case, because in future we will
2436 # want to search for a good base commit for generating patches.)
2438 # Then we can actually do the dpkg-source --commit
2439 # 1. Make a new working tree with the same object
2440 # store as our main tree and check out the main
2442 # 2. Copy .pc from the fake's extraction, if necessary
2443 # 3. Run dpkg-source --commit
2444 # 4. If the result has changes to debian/, then
2445 # - git-add them them
2446 # - git-add .pc if we had a .pc in-tree
2448 # 5. If we had a .pc in-tree, delete it, and git-commit
2449 # 6. Back in the main tree, fast forward to the new HEAD
2451 my $clogp = parsechangelog();
2452 my $headref = rev_parse('HEAD');
2457 my $upstreamversion=$version;
2458 $upstreamversion =~ s/-[^-]*$//;
2460 my $fakeversion="$upstreamversion-~~DGITFAKE";
2462 my $fakedsc=new IO::File 'fake.dsc', '>' or die $!;
2463 print $fakedsc <<END or die $!;
2466 Version: $fakeversion
2470 my $dscaddfile=sub {
2473 my $md = new Digest::MD5;
2475 my $fh = new IO::File $b, '<' or die "$b $!";
2480 print $fakedsc " ".$md->hexdigest." $size $b\n" or die $!;
2483 foreach my $f (<../../../../*>) { #/){
2484 my $b=$f; $b =~ s{.*/}{};
2485 next unless is_orig_file $b, srcfn $upstreamversion,'';
2486 link $f, $b or die "$b $!";
2490 my @files=qw(debian/source/format debian/rules);
2491 if (stat_exists '../../../debian/patches') {
2492 push @files, 'debian/patches';
2495 my $debtar= srcfn $fakeversion,'.debian.tar.gz';
2496 runcmd qw(env GZIP=-1 tar -zcf), "./$debtar", qw(-C ../../..), @files;
2498 $dscaddfile->($debtar);
2499 close $fakedsc or die $!;
2501 runcmd qw(sh -ec), 'exec dpkg-source --no-check -x fake.dsc >/dev/null';
2503 my $fakexdir= $package.'-'.(stripepoch $upstreamversion);
2504 rename $fakexdir, "fake" or die "$fakexdir $!";
2506 mkdir "work" or die $!;
2508 mktree_in_ud_here();
2509 runcmd @git, qw(reset --hard), $headref;
2512 if (stat_exists ".pc") {
2514 progress "Tree already contains .pc - will use it then delete it.";
2517 rename '../fake/.pc','.pc' or die $!;
2520 quiltify($clogp,$headref);
2522 if (!open P, '>>', ".pc/applied-patches") {
2523 $!==&ENOENT or die $!;
2528 commit_quilty_patch();
2530 if ($mustdeletepc) {
2531 runcmd @git, qw(rm -rq .pc);
2532 commit_admin "Commit removal of .pc (quilt series tracking data)";
2535 changedir '../../../..';
2536 runcmd @git, qw(pull --ff-only -q .git/dgit/unpack/work master);
2539 sub quilt_fixup_editor () {
2540 my $descfn = $ENV{$fakeeditorenv};
2541 my $editing = $ARGV[$#ARGV];
2542 open I1, '<', $descfn or die "$descfn: $!";
2543 open I2, '<', $editing or die "$editing: $!";
2544 unlink $editing or die "$editing: $!";
2545 open O, '>', $editing or die "$editing: $!";
2546 while (<I1>) { print O or die $!; } I1->error and die $!;
2549 $copying ||= m/^\-\-\- /;
2550 next unless $copying;
2553 I2->error and die $!;
2558 #----- other building -----
2561 if ($cleanmode eq 'dpkg-source') {
2562 runcmd_ordryrun_local @dpkgbuildpackage, qw(-T clean);
2563 } elsif ($cleanmode eq 'git') {
2564 runcmd_ordryrun_local @git, qw(clean -xdf);
2565 } elsif ($cleanmode eq 'none') {
2572 badusage "clean takes no additional arguments" if @ARGV;
2577 badusage "-p is not allowed when building" if defined $package;
2580 my $clogp = parsechangelog();
2581 $isuite = getfield $clogp, 'Distribution';
2582 $package = getfield $clogp, 'Source';
2583 $version = getfield $clogp, 'Version';
2584 build_maybe_quilt_fixup();
2587 sub changesopts () {
2588 my @opts =@changesopts[1..$#changesopts];
2589 if (!defined $changes_since_version) {
2590 my @vsns = archive_query('archive_query');
2591 my @quirk = access_quirk();
2592 if ($quirk[0] eq 'backports') {
2593 local $isuite = $quirk[2];
2595 canonicalise_suite();
2596 push @vsns, archive_query('archive_query');
2599 @vsns = map { $_->[0] } @vsns;
2600 @vsns = sort { -version_compare($a, $b) } @vsns;
2601 $changes_since_version = $vsns[0];
2602 progress "changelog will contain changes since $vsns[0]";
2604 $changes_since_version = '_';
2605 progress "package seems new, not specifying -v<version>";
2608 if ($changes_since_version ne '_') {
2609 unshift @opts, "-v$changes_since_version";
2616 runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc), changesopts(), @ARGV;
2617 printdone "build successful\n";
2623 (qw(git-buildpackage -us -uc --git-no-sign-tags),
2624 "--git-builder=@dpkgbuildpackage");
2625 unless (grep { m/^--git-debian-branch|^--git-ignore-branch/ } @ARGV) {
2626 canonicalise_suite();
2627 push @cmd, "--git-debian-branch=".lbranch();
2629 push @cmd, changesopts();
2630 runcmd_ordryrun_local @cmd, @ARGV;
2631 printdone "build successful\n";
2636 $sourcechanges = "${package}_".(stripepoch $version)."_source.changes";
2637 $dscfn = dscfn($version);
2638 if ($cleanmode eq 'dpkg-source') {
2639 runcmd_ordryrun_local (@dpkgbuildpackage, qw(-us -uc -S)),
2642 my $pwd = must_getcwd();
2643 my $leafdir = basename $pwd;
2645 runcmd_ordryrun_local @dpkgsource, qw(-b --), $leafdir;
2647 runcmd_ordryrun_local qw(sh -ec),
2648 'exec >$1; shift; exec "$@"','x',
2649 "../$sourcechanges",
2650 @dpkggenchanges, qw(-S), changesopts();
2654 sub cmd_build_source {
2655 badusage "build-source takes no additional arguments" if @ARGV;
2657 printdone "source built, results in $dscfn and $sourcechanges";
2663 my $pat = "${package}_".(stripepoch $version)."_*.changes";
2665 stat_exist $dscfn or fail "$dscfn (in parent directory): $!";
2666 stat_exists $sourcechanges
2667 or fail "$sourcechanges (in parent directory): $!";
2668 foreach my $cf (glob $pat) {
2669 next if $cf eq $sourcechanges;
2670 unlink $cf or fail "remove $cf: $!";
2673 runcmd_ordryrun_local @sbuild, @ARGV, qw(-d), $isuite, $dscfn;
2674 my @changesfiles = glob $pat;
2675 @changesfiles = sort {
2676 ($b =~ m/_source\.changes$/ <=> $a =~ m/_source\.changes$/)
2679 fail "wrong number of different changes files (@changesfiles)"
2680 unless @changesfiles;
2681 runcmd_ordryrun_local @mergechanges, @changesfiles;
2682 my $multichanges = "${package}_".(stripepoch $version)."_multi.changes";
2684 stat_exists $multichanges or fail "$multichanges: $!";
2686 printdone "build successful, results in $multichanges\n" or die $!;
2689 sub cmd_quilt_fixup {
2690 badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
2691 my $clogp = parsechangelog();
2692 $version = getfield $clogp, 'Version';
2693 $package = getfield $clogp, 'Source';
2694 build_maybe_quilt_fixup();
2697 sub cmd_archive_api_query {
2698 badusage "need only 1 subpath argument" unless @ARGV==1;
2699 my ($subpath) = @ARGV;
2700 my @cmd = archive_api_query_cmd($subpath);
2702 exec @cmd or fail "exec curl: $!\n";
2705 #---------- argument parsing and main program ----------
2708 print "dgit version $our_version\n" or die $!;
2715 if (defined $ENV{'DGIT_SSH'}) {
2716 @ssh = string_to_ssh $ENV{'DGIT_SSH'};
2717 } elsif (defined $ENV{'GIT_SSH'}) {
2718 @ssh = ($ENV{'GIT_SSH'});
2722 last unless $ARGV[0] =~ m/^-/;
2726 if (m/^--dry-run$/) {
2729 } elsif (m/^--damp-run$/) {
2732 } elsif (m/^--no-sign$/) {
2735 } elsif (m/^--help$/) {
2737 } elsif (m/^--version$/) {
2739 } elsif (m/^--new$/) {
2742 } elsif (m/^--since-version=([^_]+|_)$/) {
2744 $changes_since_version = $1;
2745 } elsif (m/^--([-0-9a-z]+)=(.*)/s &&
2746 ($om = $opts_opt_map{$1}) &&
2750 } elsif (m/^--([-0-9a-z]+):(.*)/s &&
2751 !$opts_opt_cmdonly{$1} &&
2752 ($om = $opts_opt_map{$1})) {
2755 } elsif (m/^--existing-package=(.*)/s) {
2757 $existing_package = $1;
2758 } elsif (m/^--initiator-tempdir=(.*)/s) {
2759 $initiator_tempdir = $1;
2760 $initiator_tempdir =~ m#^/# or
2761 badusage "--initiator-tempdir must be used specify an".
2762 " absolute, not relative, directory."
2763 } elsif (m/^--distro=(.*)/s) {
2766 } elsif (m/^--build-products-dir=(.*)/s) {
2768 $buildproductsdir = $1;
2769 } elsif (m/^--clean=(dpkg-source|git|none)$/s) {
2772 } elsif (m/^--clean=(.*)$/s) {
2773 badusage "unknown cleaning mode \`$1'";
2774 } elsif (m/^--quilt=($quilt_modes_re)$/s) {
2777 } elsif (m/^--quilt=(.*)$/s) {
2778 badusage "unknown quilt fixup mode \`$1'";
2779 } elsif (m/^--ignore-dirty$/s) {
2782 } elsif (m/^--no-quilt-fixup$/s) {
2784 $quilt_mode = 'nocheck';
2785 } elsif (m/^--no-rm-on-error$/s) {
2788 } elsif (m/^--deliberately-($deliberately_re)$/s) {
2790 push @deliberatelies, $&;
2792 badusage "unknown long option \`$_'";
2799 } elsif (s/^-L/-/) {
2802 } elsif (s/^-h/-/) {
2804 } elsif (s/^-D/-/) {
2808 } elsif (s/^-N/-/) {
2811 } elsif (s/^-v([^_]+|_)$//s) {
2813 $changes_since_version = $1;
2816 push @changesopts, $_;
2818 } elsif (s/^-c(.*=.*)//s) {
2820 push @git, '-c', $1;
2821 } elsif (s/^-d(.+)//s) {
2824 } elsif (s/^-C(.+)//s) {
2827 if ($changesfile =~ s#^(.*)/##) {
2828 $buildproductsdir = $1;
2830 } elsif (s/^-k(.+)//s) {
2832 } elsif (m/^-[vdCk]$/) {
2834 "option \`$_' requires an argument (and no space before the argument)";
2835 } elsif (s/^-wn$//s) {
2837 $cleanmode = 'none';
2838 } elsif (s/^-wg$//s) {
2841 } elsif (s/^-wd$//s) {
2843 $cleanmode = 'dpkg-source';
2845 badusage "unknown short option \`$_'";
2852 if ($ENV{$fakeeditorenv}) {
2853 quilt_fixup_editor();
2857 print STDERR "DRY RUN ONLY\n" if $dryrun_level > 1;
2858 print STDERR "DAMP RUN - WILL MAKE LOCAL (UNSIGNED) CHANGES\n"
2859 if $dryrun_level == 1;
2861 print STDERR $helpmsg or die $!;
2864 my $cmd = shift @ARGV;
2867 if (!defined $quilt_mode) {
2868 $quilt_mode = cfg('dgit.force.quilt-mode', 'RETURN-UNDEF')
2869 // access_cfg('quilt-mode', 'RETURN-UNDEF')
2871 $quilt_mode =~ m/^($quilt_modes_re)$/
2872 or badcfg "unknown quilt-mode \`$quilt_mode'";
2876 my $fn = ${*::}{"cmd_$cmd"};
2877 $fn or badusage "unknown operation $cmd";