3 # Integration between git and Debian-style archives
5 # Copyright (C)2013-2016 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/>.
28 use Dpkg::Control::Hash;
30 use File::Temp qw(tempdir);
37 use List::Util qw(any);
38 use List::MoreUtils qw(pairwise);
39 use Text::Glob qw(match_glob);
40 use Fcntl qw(:DEFAULT :flock);
45 our $our_version = 'UNRELEASED'; ###substituted###
46 our $absurdity = undef; ###substituted###
48 our @rpushprotovsn_support = qw(4 3 2); # 4 is new tag format
51 our $isuite = 'unstable';
57 our $dryrun_level = 0;
59 our $buildproductsdir = '..';
65 our $existing_package = 'dpkg';
67 our $changes_since_version;
69 our $overwrite_version; # undef: not specified; '': check changelog
71 our $quilt_modes_re = 'linear|smash|auto|nofix|nocheck|gbp|dpm|unapplied';
72 our $split_brain_save;
73 our $we_are_responder;
74 our $initiator_tempdir;
75 our $patches_applied_dirtily = 00;
80 our %forceopts = map { $_=>0 }
81 qw(unrepresentable unsupported-source-format
82 dsc-changes-mismatch changes-origs-exactly
83 import-gitapply-absurd
84 import-gitapply-no-absurd
85 import-dsc-with-dgit-field);
87 our %format_ok = map { $_=>1 } ("1.0","3.0 (native)","3.0 (quilt)");
89 our $suite_re = '[-+.0-9a-z]+';
90 our $cleanmode_re = 'dpkg-source(?:-d)?|git|git-ff|check|none';
91 our $orig_f_comp_re = 'orig(?:-[-0-9a-z]+)?';
92 our $orig_f_sig_re = '\\.(?:asc|gpg|pgp)';
93 our $orig_f_tail_re = "$orig_f_comp_re\\.tar(?:\\.\\w+)?(?:$orig_f_sig_re)?";
95 our $git_authline_re = '^([^<>]+) \<(\S+)\> (\d+ [-+]\d+)$';
96 our $splitbraincache = 'dgit-intern/quilt-cache';
99 our (@dget) = qw(dget);
100 our (@curl) = qw(curl);
101 our (@dput) = qw(dput);
102 our (@debsign) = qw(debsign);
103 our (@gpg) = qw(gpg);
104 our (@sbuild) = qw(sbuild);
106 our (@dgit) = qw(dgit);
107 our (@aptget) = qw(apt-get);
108 our (@aptcache) = qw(apt-cache);
109 our (@dpkgbuildpackage) = qw(dpkg-buildpackage -i\.git/ -I.git);
110 our (@dpkgsource) = qw(dpkg-source -i\.git/ -I.git);
111 our (@dpkggenchanges) = qw(dpkg-genchanges);
112 our (@mergechanges) = qw(mergechanges -f);
113 our (@gbp_build) = ('');
114 our (@gbp_pq) = ('gbp pq');
115 our (@changesopts) = ('');
117 our %opts_opt_map = ('dget' => \@dget, # accept for compatibility
120 'debsign' => \@debsign,
122 'sbuild' => \@sbuild,
126 'apt-get' => \@aptget,
127 'apt-cache' => \@aptcache,
128 'dpkg-source' => \@dpkgsource,
129 'dpkg-buildpackage' => \@dpkgbuildpackage,
130 'dpkg-genchanges' => \@dpkggenchanges,
131 'gbp-build' => \@gbp_build,
132 'gbp-pq' => \@gbp_pq,
133 'ch' => \@changesopts,
134 'mergechanges' => \@mergechanges);
136 our %opts_opt_cmdonly = ('gpg' => 1, 'git' => 1);
137 our %opts_cfg_insertpos = map {
139 scalar @{ $opts_opt_map{$_} }
140 } keys %opts_opt_map;
142 sub finalise_opts_opts();
148 our $supplementary_message = '';
149 our $need_split_build_invocation = 0;
150 our $split_brain = 0;
154 print STDERR "! $_\n" foreach $supplementary_message =~ m/^.+$/mg;
157 our $remotename = 'dgit';
158 our @ourdscfield = qw(Dgit Vcs-Dgit-Master);
162 if (!defined $absurdity) {
164 $absurdity =~ s{/[^/]+$}{/absurd} or die;
168 my ($v,$distro) = @_;
169 return $tagformatfn->($v, $distro);
172 sub debiantag_maintview ($$) {
173 my ($v,$distro) = @_;
174 return "$distro/".dep14_version_mangle $v;
177 sub madformat ($) { $_[0] eq '3.0 (quilt)' }
179 sub lbranch () { return "$branchprefix/$csuite"; }
180 my $lbranch_re = '^refs/heads/'.$branchprefix.'/([^/.]+)$';
181 sub lref () { return "refs/heads/".lbranch(); }
182 sub lrref () { return "refs/remotes/$remotename/".server_branch($csuite); }
183 sub rrref () { return server_ref($csuite); }
185 sub lrfetchrefs () { return "refs/dgit-fetch/$csuite"; }
186 sub lrfetchref () { return lrfetchrefs.'/'.server_branch($csuite); }
188 # We fetch some parts of lrfetchrefs/*. Ideally we delete these
189 # locally fetched refs because they have unhelpful names and clutter
190 # up gitk etc. So we track whether we have "used up" head ref (ie,
191 # whether we have made another local ref which refers to this object).
193 # (If we deleted them unconditionally, then we might end up
194 # re-fetching the same git objects each time dgit fetch was run.)
196 # So, leach use of lrfetchrefs needs to be accompanied by arrangements
197 # in git_fetch_us to fetch the refs in question, and possibly a call
198 # to lrfetchref_used.
200 our (%lrfetchrefs_f, %lrfetchrefs_d);
201 # $lrfetchrefs_X{lrfetchrefs."/heads/whatever"} = $objid
203 sub lrfetchref_used ($) {
204 my ($fullrefname) = @_;
205 my $objid = $lrfetchrefs_f{$fullrefname};
206 $lrfetchrefs_d{$fullrefname} = $objid if defined $objid;
217 return "${package}_".(stripepoch $vsn).$sfx
222 return srcfn($vsn,".dsc");
225 sub changespat ($;$) {
226 my ($vsn, $arch) = @_;
227 return "${package}_".(stripepoch $vsn)."_".($arch//'*').".changes";
230 sub upstreamversion ($) {
242 foreach my $f (@end) {
244 print STDERR "$us: cleanup: $@" if length $@;
248 sub badcfg { print STDERR "$us: invalid configuration: @_\n"; exit 12; }
250 sub forceable_fail ($$) {
251 my ($forceoptsl, $msg) = @_;
252 fail $msg unless grep { $forceopts{$_} } @$forceoptsl;
253 print STDERR "warning: overriding problem due to --force:\n". $msg;
257 my ($forceoptsl) = @_;
258 my @got = grep { $forceopts{$_} } @$forceoptsl;
259 return 0 unless @got;
261 "warning: skipping checks or functionality due to --force-$got[0]\n";
264 sub no_such_package () {
265 print STDERR "$us: package $package does not exist in suite $isuite\n";
271 printdebug "CD $newdir\n";
272 chdir $newdir or confess "chdir: $newdir: $!";
275 sub deliberately ($) {
277 return !!grep { $_ eq "--deliberately-$enquiry" } @deliberatelies;
280 sub deliberately_not_fast_forward () {
281 foreach (qw(not-fast-forward fresh-repo)) {
282 return 1 if deliberately($_) || deliberately("TEST-dgit-only-$_");
286 sub quiltmode_splitbrain () {
287 $quilt_mode =~ m/gbp|dpm|unapplied/;
290 sub opts_opt_multi_cmd {
292 push @cmd, split /\s+/, shift @_;
298 return opts_opt_multi_cmd @gbp_pq;
301 #---------- remote protocol support, common ----------
303 # remote push initiator/responder protocol:
304 # $ dgit remote-push-build-host <n-rargs> <rargs>... <push-args>...
305 # where <rargs> is <push-host-dir> <supported-proto-vsn>,... ...
306 # < dgit-remote-push-ready <actual-proto-vsn>
313 # > supplementary-message NBYTES # $protovsn >= 3
318 # > file parsed-changelog
319 # [indicates that output of dpkg-parsechangelog follows]
320 # > data-block NBYTES
321 # > [NBYTES bytes of data (no newline)]
322 # [maybe some more blocks]
331 # > param head DGIT-VIEW-HEAD
332 # > param csuite SUITE
333 # > param tagformat old|new
334 # > param maint-view MAINT-VIEW-HEAD
336 # > previously REFNAME=OBJNAME # if --deliberately-not-fast-forward
337 # # goes into tag, for replay prevention
340 # [indicates that signed tag is wanted]
341 # < data-block NBYTES
342 # < [NBYTES bytes of data (no newline)]
343 # [maybe some more blocks]
347 # > want signed-dsc-changes
348 # < data-block NBYTES [transfer of signed dsc]
350 # < data-block NBYTES [transfer of signed changes]
358 sub i_child_report () {
359 # Sees if our child has died, and reap it if so. Returns a string
360 # describing how it died if it failed, or undef otherwise.
361 return undef unless $i_child_pid;
362 my $got = waitpid $i_child_pid, WNOHANG;
363 return undef if $got <= 0;
364 die unless $got == $i_child_pid;
365 $i_child_pid = undef;
366 return undef unless $?;
367 return "build host child ".waitstatusmsg();
372 fail "connection lost: $!" if $fh->error;
373 fail "protocol violation; $m not expected";
376 sub badproto_badread ($$) {
378 fail "connection lost: $!" if $!;
379 my $report = i_child_report();
380 fail $report if defined $report;
381 badproto $fh, "eof (reading $wh)";
384 sub protocol_expect (&$) {
385 my ($match, $fh) = @_;
388 defined && chomp or badproto_badread $fh, "protocol message";
396 badproto $fh, "\`$_'";
399 sub protocol_send_file ($$) {
400 my ($fh, $ourfn) = @_;
401 open PF, "<", $ourfn or die "$ourfn: $!";
404 my $got = read PF, $d, 65536;
405 die "$ourfn: $!" unless defined $got;
407 print $fh "data-block ".length($d)."\n" or die $!;
408 print $fh $d or die $!;
410 PF->error and die "$ourfn $!";
411 print $fh "data-end\n" or die $!;
415 sub protocol_read_bytes ($$) {
416 my ($fh, $nbytes) = @_;
417 $nbytes =~ m/^[1-9]\d{0,5}$|^0$/ or badproto \*RO, "bad byte count";
419 my $got = read $fh, $d, $nbytes;
420 $got==$nbytes or badproto_badread $fh, "data block";
424 sub protocol_receive_file ($$) {
425 my ($fh, $ourfn) = @_;
426 printdebug "() $ourfn\n";
427 open PF, ">", $ourfn or die "$ourfn: $!";
429 my ($y,$l) = protocol_expect {
430 m/^data-block (.*)$/ ? (1,$1) :
431 m/^data-end$/ ? (0,) :
435 my $d = protocol_read_bytes $fh, $l;
436 print PF $d or die $!;
441 #---------- remote protocol support, responder ----------
443 sub responder_send_command ($) {
445 return unless $we_are_responder;
446 # called even without $we_are_responder
447 printdebug ">> $command\n";
448 print PO $command, "\n" or die $!;
451 sub responder_send_file ($$) {
452 my ($keyword, $ourfn) = @_;
453 return unless $we_are_responder;
454 printdebug "]] $keyword $ourfn\n";
455 responder_send_command "file $keyword";
456 protocol_send_file \*PO, $ourfn;
459 sub responder_receive_files ($@) {
460 my ($keyword, @ourfns) = @_;
461 die unless $we_are_responder;
462 printdebug "[[ $keyword @ourfns\n";
463 responder_send_command "want $keyword";
464 foreach my $fn (@ourfns) {
465 protocol_receive_file \*PI, $fn;
468 protocol_expect { m/^files-end$/ } \*PI;
471 #---------- remote protocol support, initiator ----------
473 sub initiator_expect (&) {
475 protocol_expect { &$match } \*RO;
478 #---------- end remote code ----------
481 if ($we_are_responder) {
483 responder_send_command "progress ".length($m) or die $!;
484 print PO $m or die $!;
494 $ua = LWP::UserAgent->new();
498 progress "downloading $what...";
499 my $r = $ua->get(@_) or die $!;
500 return undef if $r->code == 404;
501 $r->is_success or fail "failed to fetch $what: ".$r->status_line;
502 return $r->decoded_content(charset => 'none');
505 our ($dscdata,$dscurl,$dsc,$dsc_checked,$skew_warning_vsn);
510 failedcmd @_ if system @_;
513 sub act_local () { return $dryrun_level <= 1; }
514 sub act_scary () { return !$dryrun_level; }
517 if (!$dryrun_level) {
518 progress "$us ok: @_";
520 progress "would be ok: @_ (but dry run only)";
525 printcmd(\*STDERR,$debugprefix."#",@_);
528 sub runcmd_ordryrun {
536 sub runcmd_ordryrun_local {
545 my ($first_shell, @cmd) = @_;
546 return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
549 our $helpmsg = <<END;
551 dgit [dgit-opts] clone [dgit-opts] package [suite] [./dir|/dir]
552 dgit [dgit-opts] fetch|pull [dgit-opts] [suite]
553 dgit [dgit-opts] build [dpkg-buildpackage-opts]
554 dgit [dgit-opts] sbuild [sbuild-opts]
555 dgit [dgit-opts] push [dgit-opts] [suite]
556 dgit [dgit-opts] rpush build-host:build-dir ...
557 important dgit options:
558 -k<keyid> sign tag and package with <keyid> instead of default
559 --dry-run -n do not change anything, but go through the motions
560 --damp-run -L like --dry-run but make local changes, without signing
561 --new -N allow introducing a new package
562 --debug -D increase debug level
563 -c<name>=<value> set git config option (used directly by dgit too)
566 our $later_warning_msg = <<END;
567 Perhaps the upload is stuck in incoming. Using the version from git.
571 print STDERR "$us: @_\n", $helpmsg or die $!;
576 @ARGV or badusage "too few arguments";
577 return scalar shift @ARGV;
581 print $helpmsg or die $!;
585 our $td = $ENV{DGIT_TEST_DUMMY_DIR} || "DGIT_TEST_DUMMY_DIR-unset";
587 our %defcfg = ('dgit.default.distro' => 'debian',
588 'dgit-suite.*-security.distro' => 'debian-security',
589 'dgit.default.username' => '',
590 'dgit.default.archive-query-default-component' => 'main',
591 'dgit.default.ssh' => 'ssh',
592 'dgit.default.archive-query' => 'madison:',
593 'dgit.default.sshpsql-dbname' => 'service=projectb',
594 'dgit.default.aptget-components' => 'main',
595 'dgit.default.dgit-tag-format' => 'new,old,maint',
596 # old means "repo server accepts pushes with old dgit tags"
597 # new means "repo server accepts pushes with new dgit tags"
598 # maint means "repo server accepts split brain pushes"
599 # hist means "repo server may have old pushes without new tag"
600 # ("hist" is implied by "old")
601 'dgit-distro.debian.archive-query' => 'ftpmasterapi:',
602 'dgit-distro.debian.git-check' => 'url',
603 'dgit-distro.debian.git-check-suffix' => '/info/refs',
604 'dgit-distro.debian.new-private-pushers' => 't',
605 'dgit-distro.debian/push.git-url' => '',
606 'dgit-distro.debian/push.git-host' => 'push.dgit.debian.org',
607 'dgit-distro.debian/push.git-user-force' => 'dgit',
608 'dgit-distro.debian/push.git-proto' => 'git+ssh://',
609 'dgit-distro.debian/push.git-path' => '/dgit/debian/repos',
610 'dgit-distro.debian/push.git-create' => 'true',
611 'dgit-distro.debian/push.git-check' => 'ssh-cmd',
612 'dgit-distro.debian.archive-query-url', 'https://api.ftp-master.debian.org/',
613 # 'dgit-distro.debian.archive-query-tls-key',
614 # '/etc/ssl/certs/%HOST%.pem:/etc/dgit/%HOST%.pem',
615 # ^ this does not work because curl is broken nowadays
616 # Fixing #790093 properly will involve providing providing the key
617 # in some pacagke and maybe updating these paths.
619 # 'dgit-distro.debian.archive-query-tls-curl-args',
620 # '--ca-path=/etc/ssl/ca-debian',
621 # ^ this is a workaround but works (only) on DSA-administered machines
622 'dgit-distro.debian.git-url' => 'https://git.dgit.debian.org',
623 'dgit-distro.debian.git-url-suffix' => '',
624 'dgit-distro.debian.upload-host' => 'ftp-master', # for dput
625 'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/',
626 'dgit-distro.debian-security.archive-query' => 'aptget:',
627 'dgit-distro.debian-security.mirror' => 'http://security.debian.org/debian-security/',
628 'dgit-distro.debian-security.aptget-suite-map' => 's#-security$#/updates#',
629 'dgit-distro.debian-security.aptget-suite-rmap' => 's#$#-security#',
630 'dgit-distro.debian-security.nominal-distro' => 'debian',
631 'dgit-distro.debian.backports-quirk' => '(squeeze)-backports*',
632 'dgit-distro.debian-backports.mirror' => 'http://backports.debian.org/debian-backports/',
633 'dgit-distro.ubuntu.git-check' => 'false',
634 'dgit-distro.ubuntu.mirror' => 'http://archive.ubuntu.com/ubuntu',
635 'dgit-distro.test-dummy.ssh' => "$td/ssh",
636 'dgit-distro.test-dummy.username' => "alice",
637 'dgit-distro.test-dummy.git-check' => "ssh-cmd",
638 'dgit-distro.test-dummy.git-create' => "ssh-cmd",
639 'dgit-distro.test-dummy.git-url' => "$td/git",
640 'dgit-distro.test-dummy.git-host' => "git",
641 'dgit-distro.test-dummy.git-path' => "$td/git",
642 'dgit-distro.test-dummy.archive-query' => "dummycatapi:",
643 'dgit-distro.test-dummy.archive-query-url' => "file://$td/aq/",
644 'dgit-distro.test-dummy.mirror' => "file://$td/mirror/",
645 'dgit-distro.test-dummy.upload-host' => 'test-dummy',
649 our @gitcfgsources = qw(cmdline local global system);
651 sub git_slurp_config () {
652 local ($debuglevel) = $debuglevel-2;
655 # This algoritm is a bit subtle, but this is needed so that for
656 # options which we want to be single-valued, we allow the
657 # different config sources to override properly. See #835858.
658 foreach my $src (@gitcfgsources) {
659 next if $src eq 'cmdline';
660 # we do this ourselves since git doesn't handle it
662 my @cmd = (@git, qw(config -z --get-regexp), "--$src", qw(.*));
665 open GITS, "-|", @cmd or die $!;
668 printdebug "=> ", (messagequote $_), "\n";
670 push @{ $gitcfgs{$src}{$`} }, $'; #';
674 or ($!==0 && $?==256)
679 sub git_get_config ($) {
681 foreach my $src (@gitcfgsources) {
682 my $l = $gitcfgs{$src}{$c};
683 printdebug"C $c ".(defined $l ? messagequote "'$l'" : "undef")."\n"
686 @$l==1 or badcfg "multiple values for $c".
687 " (in $src git config)" if @$l > 1;
695 return undef if $c =~ /RETURN-UNDEF/;
696 my $v = git_get_config($c);
697 return $v if defined $v;
698 my $dv = $defcfg{$c};
699 return $dv if defined $dv;
701 badcfg "need value for one of: @_\n".
702 "$us: distro or suite appears not to be (properly) supported";
705 sub access_basedistro () {
706 if (defined $idistro) {
709 my $def = cfg("dgit-suite.$isuite.distro", 'RETURN-UNDEF');
710 return $def if defined $def;
711 foreach my $src (@gitcfgsources, 'internal') {
712 my $kl = $src eq 'internal' ? \%defcfg : $gitcfgs{$src};
714 foreach my $k (keys %$kl) {
715 next unless $k =~ m#^dgit-suite\.(.*)\.distro$#;
717 next unless match_glob $dpat, $isuite;
721 return cfg("dgit.default.distro");
725 sub access_nomdistro () {
726 my $base = access_basedistro();
727 return cfg("dgit-distro.$base.nominal-distro",'RETURN-UNDEF') // $base;
730 sub access_quirk () {
731 # returns (quirk name, distro to use instead or undef, quirk-specific info)
732 my $basedistro = access_basedistro();
733 my $backports_quirk = cfg("dgit-distro.$basedistro.backports-quirk",
735 if (defined $backports_quirk) {
736 my $re = $backports_quirk;
737 $re =~ s/[^-0-9a-z_\%*()]/\\$&/ig;
739 $re =~ s/\%/([-0-9a-z_]+)/
740 or $re =~ m/[()]/ or badcfg "backports-quirk needs \% or ( )";
741 if ($isuite =~ m/^$re$/) {
742 return ('backports',"$basedistro-backports",$1);
745 return ('none',undef);
750 sub parse_cfg_bool ($$$) {
751 my ($what,$def,$v) = @_;
754 $v =~ m/^[ty1]/ ? 1 :
755 $v =~ m/^[fn0]/ ? 0 :
756 badcfg "$what needs t (true, y, 1) or f (false, n, 0) not \`$v'";
759 sub access_forpush_config () {
760 my $d = access_basedistro();
764 parse_cfg_bool('new-private-pushers', 0,
765 cfg("dgit-distro.$d.new-private-pushers",
768 my $v = cfg("dgit-distro.$d.readonly", 'RETURN-UNDEF');
771 $v =~ m/^[ty1]/ ? 0 : # force readonly, forpush = 0
772 $v =~ m/^[fn0]/ ? 1 : # force nonreadonly, forpush = 1
773 $v =~ m/^[a]/ ? '' : # auto, forpush = ''
774 badcfg "readonly needs t (true, y, 1) or f (false, n, 0) or a (auto)";
777 sub access_forpush () {
778 $access_forpush //= access_forpush_config();
779 return $access_forpush;
783 die "$access_forpush ?" if ($access_forpush // 1) ne 1;
784 badcfg "pushing but distro is configured readonly"
785 if access_forpush_config() eq '0';
787 $supplementary_message = <<'END' unless $we_are_responder;
788 Push failed, before we got started.
789 You can retry the push, after fixing the problem, if you like.
791 finalise_opts_opts();
795 finalise_opts_opts();
798 sub supplementary_message ($) {
800 if (!$we_are_responder) {
801 $supplementary_message = $msg;
803 } elsif ($protovsn >= 3) {
804 responder_send_command "supplementary-message ".length($msg)
806 print PO $msg or die $!;
810 sub access_distros () {
811 # Returns list of distros to try, in order
814 # 0. `instead of' distro name(s) we have been pointed to
815 # 1. the access_quirk distro, if any
816 # 2a. the user's specified distro, or failing that } basedistro
817 # 2b. the distro calculated from the suite }
818 my @l = access_basedistro();
820 my (undef,$quirkdistro) = access_quirk();
821 unshift @l, $quirkdistro;
822 unshift @l, $instead_distro;
823 @l = grep { defined } @l;
825 push @l, access_nomdistro();
827 if (access_forpush()) {
828 @l = map { ("$_/push", $_) } @l;
833 sub access_cfg_cfgs (@) {
836 # The nesting of these loops determines the search order. We put
837 # the key loop on the outside so that we search all the distros
838 # for each key, before going on to the next key. That means that
839 # if access_cfg is called with a more specific, and then a less
840 # specific, key, an earlier distro can override the less specific
841 # without necessarily overriding any more specific keys. (If the
842 # distro wants to override the more specific keys it can simply do
843 # so; whereas if we did the loop the other way around, it would be
844 # impossible to for an earlier distro to override a less specific
845 # key but not the more specific ones without restating the unknown
846 # values of the more specific keys.
849 # We have to deal with RETURN-UNDEF specially, so that we don't
850 # terminate the search prematurely.
852 if (m/RETURN-UNDEF/) { push @rundef, $_; last; }
855 foreach my $d (access_distros()) {
856 push @cfgs, map { "dgit-distro.$d.$_" } @realkeys;
858 push @cfgs, map { "dgit.default.$_" } @realkeys;
865 my (@cfgs) = access_cfg_cfgs(@keys);
866 my $value = cfg(@cfgs);
870 sub access_cfg_bool ($$) {
871 my ($def, @keys) = @_;
872 parse_cfg_bool($keys[0], $def, access_cfg(@keys, 'RETURN-UNDEF'));
875 sub string_to_ssh ($) {
877 if ($spec =~ m/\s/) {
878 return qw(sh -ec), 'exec '.$spec.' "$@"', 'x';
884 sub access_cfg_ssh () {
885 my $gitssh = access_cfg('ssh', 'RETURN-UNDEF');
886 if (!defined $gitssh) {
889 return string_to_ssh $gitssh;
893 sub access_runeinfo ($) {
895 return ": dgit ".access_basedistro()." $info ;";
898 sub access_someuserhost ($) {
900 my $user = access_cfg("$some-user-force", 'RETURN-UNDEF');
901 defined($user) && length($user) or
902 $user = access_cfg("$some-user",'username');
903 my $host = access_cfg("$some-host");
904 return length($user) ? "$user\@$host" : $host;
907 sub access_gituserhost () {
908 return access_someuserhost('git');
911 sub access_giturl (;$) {
913 my $url = access_cfg('git-url','RETURN-UNDEF');
916 my $proto = access_cfg('git-proto', 'RETURN-UNDEF');
917 return undef unless defined $proto;
920 access_gituserhost().
921 access_cfg('git-path');
923 $suffix = access_cfg('git-url-suffix','RETURN-UNDEF');
926 return "$url/$package$suffix";
929 sub parsecontrolfh ($$;$) {
930 my ($fh, $desc, $allowsigned) = @_;
931 our $dpkgcontrolhash_noissigned;
934 my %opts = ('name' => $desc);
935 $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
936 $c = Dpkg::Control::Hash->new(%opts);
937 $c->parse($fh,$desc) or die "parsing of $desc failed";
938 last if $allowsigned;
939 last if $dpkgcontrolhash_noissigned;
940 my $issigned= $c->get_option('is_pgp_signed');
941 if (!defined $issigned) {
942 $dpkgcontrolhash_noissigned= 1;
943 seek $fh, 0,0 or die "seek $desc: $!";
944 } elsif ($issigned) {
945 fail "control file $desc is (already) PGP-signed. ".
946 " Note that dgit push needs to modify the .dsc and then".
947 " do the signature itself";
956 my ($file, $desc, $allowsigned) = @_;
957 my $fh = new IO::Handle;
958 open $fh, '<', $file or die "$file: $!";
959 my $c = parsecontrolfh($fh,$desc,$allowsigned);
960 $fh->error and die $!;
966 my ($dctrl,$field) = @_;
967 my $v = $dctrl->{$field};
968 return $v if defined $v;
969 fail "missing field $field in ".$dctrl->get_option('name');
973 my $c = Dpkg::Control::Hash->new(name => 'parsed changelog');
974 my $p = new IO::Handle;
975 my @cmd = (qw(dpkg-parsechangelog), @_);
976 open $p, '-|', @cmd or die $!;
978 $?=0; $!=0; close $p or failedcmd @cmd;
982 sub commit_getclogp ($) {
983 # Returns the parsed changelog hashref for a particular commit
985 our %commit_getclogp_memo;
986 my $memo = $commit_getclogp_memo{$objid};
987 return $memo if $memo;
989 my $mclog = ".git/dgit/clog-$objid";
990 runcmd shell_cmd "exec >$mclog", @git, qw(cat-file blob),
991 "$objid:debian/changelog";
992 $commit_getclogp_memo{$objid} = parsechangelog("-l$mclog");
997 defined $d or fail "getcwd failed: $!";
1001 sub parse_dscdata () {
1002 my $dscfh = new IO::File \$dscdata, '<' or die $!;
1003 printdebug Dumper($dscdata) if $debuglevel>1;
1004 $dsc = parsecontrolfh($dscfh,$dscurl,1);
1005 printdebug Dumper($dsc) if $debuglevel>1;
1010 sub archive_query ($;@) {
1011 my ($method) = shift @_;
1012 fail "this operation does not support multiple comma-separated suites"
1014 my $query = access_cfg('archive-query','RETURN-UNDEF');
1015 $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
1018 { no strict qw(refs); &{"${method}_${proto}"}($proto,$data,@_); }
1021 sub archive_query_prepend_mirror {
1022 my $m = access_cfg('mirror');
1023 return map { [ $_->[0], $m.$_->[1], @$_[2..$#$_] ] } @_;
1026 sub pool_dsc_subpath ($$) {
1027 my ($vsn,$component) = @_; # $package is implict arg
1028 my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
1029 return "/pool/$component/$prefix/$package/".dscfn($vsn);
1032 sub cfg_apply_map ($$$) {
1033 my ($varref, $what, $mapspec) = @_;
1034 return unless $mapspec;
1036 printdebug "config $what EVAL{ $mapspec; }\n";
1038 eval "package Dgit::Config; $mapspec;";
1043 #---------- `ftpmasterapi' archive query method (nascent) ----------
1045 sub archive_api_query_cmd ($) {
1047 my @cmd = (@curl, qw(-sS));
1048 my $url = access_cfg('archive-query-url');
1049 if ($url =~ m#^https://([-.0-9a-z]+)/#) {
1051 my $keys = access_cfg('archive-query-tls-key','RETURN-UNDEF') //'';
1052 foreach my $key (split /\:/, $keys) {
1053 $key =~ s/\%HOST\%/$host/g;
1055 fail "for $url: stat $key: $!" unless $!==ENOENT;
1058 fail "config requested specific TLS key but do not know".
1059 " how to get curl to use exactly that EE key ($key)";
1060 # push @cmd, "--cacert", $key, "--capath", "/dev/enoent";
1061 # # Sadly the above line does not work because of changes
1062 # # to gnutls. The real fix for #790093 may involve
1063 # # new curl options.
1066 # Fixing #790093 properly will involve providing a value
1067 # for this on clients.
1068 my $kargs = access_cfg('archive-query-tls-curl-ca-args','RETURN-UNDEF');
1069 push @cmd, split / /, $kargs if defined $kargs;
1071 push @cmd, $url.$subpath;
1075 sub api_query ($$;$) {
1077 my ($data, $subpath, $ok404) = @_;
1078 badcfg "ftpmasterapi archive query method takes no data part"
1080 my @cmd = archive_api_query_cmd($subpath);
1081 my $url = $cmd[$#cmd];
1082 push @cmd, qw(-w %{http_code});
1083 my $json = cmdoutput @cmd;
1084 unless ($json =~ s/\d+\d+\d$//) {
1085 failedcmd_report_cmd undef, @cmd;
1086 fail "curl failed to print 3-digit HTTP code";
1089 return undef if $code eq '404' && $ok404;
1090 fail "fetch of $url gave HTTP code $code"
1091 unless $url =~ m#^file://# or $code =~ m/^2/;
1092 return decode_json($json);
1095 sub canonicalise_suite_ftpmasterapi {
1096 my ($proto,$data) = @_;
1097 my $suites = api_query($data, 'suites');
1099 foreach my $entry (@$suites) {
1101 my $v = $entry->{$_};
1102 defined $v && $v eq $isuite;
1103 } qw(codename name);
1104 push @matched, $entry;
1106 fail "unknown suite $isuite" unless @matched;
1109 @matched==1 or die "multiple matches for suite $isuite\n";
1110 $cn = "$matched[0]{codename}";
1111 defined $cn or die "suite $isuite info has no codename\n";
1112 $cn =~ m/^$suite_re$/ or die "suite $isuite maps to bad codename\n";
1114 die "bad ftpmaster api response: $@\n".Dumper(\@matched)
1119 sub archive_query_ftpmasterapi {
1120 my ($proto,$data) = @_;
1121 my $info = api_query($data, "dsc_in_suite/$isuite/$package");
1123 my $digester = Digest::SHA->new(256);
1124 foreach my $entry (@$info) {
1126 my $vsn = "$entry->{version}";
1127 my ($ok,$msg) = version_check $vsn;
1128 die "bad version: $msg\n" unless $ok;
1129 my $component = "$entry->{component}";
1130 $component =~ m/^$component_re$/ or die "bad component";
1131 my $filename = "$entry->{filename}";
1132 $filename && $filename !~ m#[^-+:._~0-9a-zA-Z/]|^[/.]|/[/.]#
1133 or die "bad filename";
1134 my $sha256sum = "$entry->{sha256sum}";
1135 $sha256sum =~ m/^[0-9a-f]+$/ or die "bad sha256sum";
1136 push @rows, [ $vsn, "/pool/$component/$filename",
1137 $digester, $sha256sum ];
1139 die "bad ftpmaster api response: $@\n".Dumper($entry)
1142 @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
1143 return archive_query_prepend_mirror @rows;
1146 sub file_in_archive_ftpmasterapi {
1147 my ($proto,$data,$filename) = @_;
1148 my $pat = $filename;
1151 $pat =~ s#[^-+_.0-9a-z/]# sprintf '%%%02x', ord $& #ge;
1152 my $info = api_query($data, "file_in_archive/$pat", 1);
1155 #---------- `aptget' archive query method ----------
1158 our $aptget_releasefile;
1159 our $aptget_configpath;
1161 sub aptget_aptget () { return @aptget, qw(-c), $aptget_configpath; }
1162 sub aptget_aptcache () { return @aptcache, qw(-c), $aptget_configpath; }
1164 sub aptget_cache_clean {
1165 runcmd_ordryrun_local qw(sh -ec),
1166 'cd "$1"; find -atime +30 -type f -print0 | xargs -0r rm --',
1170 sub aptget_lock_acquire () {
1171 my $lockfile = "$aptget_base/lock";
1172 open APTGET_LOCK, '>', $lockfile or die "open $lockfile: $!";
1173 flock APTGET_LOCK, LOCK_EX or die "lock $lockfile: $!";
1176 sub aptget_prep ($) {
1178 return if defined $aptget_base;
1180 badcfg "aptget archive query method takes no data part"
1183 my $cache = $ENV{XDG_CACHE_DIR} // "$ENV{HOME}/.cache";
1186 ensuredir "$cache/dgit";
1188 access_cfg('aptget-cachekey','RETURN-UNDEF')
1189 // access_nomdistro();
1191 $aptget_base = "$cache/dgit/aptget";
1192 ensuredir $aptget_base;
1194 my $quoted_base = $aptget_base;
1195 die "$quoted_base contains bad chars, cannot continue"
1196 if $quoted_base =~ m/["\\]/; # apt.conf(5) says no escaping :-/
1198 ensuredir $aptget_base;
1200 aptget_lock_acquire();
1202 aptget_cache_clean();
1204 $aptget_configpath = "$aptget_base/apt.conf#$cachekey";
1205 my $sourceslist = "source.list#$cachekey";
1207 my $aptsuites = $isuite;
1208 cfg_apply_map(\$aptsuites, 'suite map',
1209 access_cfg('aptget-suite-map', 'RETURN-UNDEF'));
1211 open SRCS, ">", "$aptget_base/$sourceslist" or die $!;
1212 printf SRCS "deb-src %s %s %s\n",
1213 access_cfg('mirror'),
1215 access_cfg('aptget-components')
1218 ensuredir "$aptget_base/cache";
1219 ensuredir "$aptget_base/lists";
1221 open CONF, ">", $aptget_configpath or die $!;
1223 Debug::NoLocking "true";
1224 APT::Get::List-Cleanup "false";
1225 #clear APT::Update::Post-Invoke-Success;
1226 Dir::Etc::SourceList "$quoted_base/$sourceslist";
1227 Dir::State::Lists "$quoted_base/lists";
1228 Dir::Etc::preferences "$quoted_base/preferences";
1229 Dir::Cache::srcpkgcache "$quoted_base/cache/srcs#$cachekey";
1230 Dir::Cache::pkgcache "$quoted_base/cache/pkgs#$cachekey";
1233 foreach my $key (qw(
1236 Dir::Cache::Archives
1237 Dir::Etc::SourceParts
1238 Dir::Etc::preferencesparts
1240 ensuredir "$aptget_base/$key";
1241 print CONF "$key \"$quoted_base/$key\";\n" or die $!;
1244 my $oldatime = (time // die $!) - 1;
1245 foreach my $oldlist (<$aptget_base/lists/*Release>) {
1246 next unless stat_exists $oldlist;
1247 my ($mtime) = (stat _)[9];
1248 utime $oldatime, $mtime, $oldlist or die "$oldlist $!";
1251 runcmd_ordryrun_local aptget_aptget(), qw(update);
1254 foreach my $oldlist (<$aptget_base/lists/*Release>) {
1255 next unless stat_exists $oldlist;
1256 my ($atime) = (stat _)[8];
1257 next if $atime == $oldatime;
1258 push @releasefiles, $oldlist;
1260 my @inreleasefiles = grep { m#/InRelease$# } @releasefiles;
1261 @releasefiles = @inreleasefiles if @inreleasefiles;
1262 die "apt updated wrong number of Release files (@releasefiles), erk"
1263 unless @releasefiles == 1;
1265 ($aptget_releasefile) = @releasefiles;
1268 sub canonicalise_suite_aptget {
1269 my ($proto,$data) = @_;
1272 my $release = parsecontrol $aptget_releasefile, "Release file", 1;
1274 foreach my $name (qw(Codename Suite)) {
1275 my $val = $release->{$name};
1277 printdebug "release file $name: $val\n";
1278 $val =~ m/^$suite_re$/o or fail
1279 "Release file ($aptget_releasefile) specifies intolerable $name";
1280 cfg_apply_map(\$val, 'suite rmap',
1281 access_cfg('aptget-suite-rmap', 'RETURN-UNDEF'));
1288 sub archive_query_aptget {
1289 my ($proto,$data) = @_;
1292 ensuredir "$aptget_base/source";
1293 foreach my $old (<$aptget_base/source/*.dsc>) {
1294 unlink $old or die "$old: $!";
1297 my $showsrc = cmdoutput aptget_aptcache(), qw(showsrc), $package;
1298 return () unless $showsrc =~ m/^package:\s*\Q$package\E\s*$/mi;
1299 # avoids apt-get source failing with ambiguous error code
1301 runcmd_ordryrun_local
1302 shell_cmd 'cd "$1"/source; shift', $aptget_base,
1303 aptget_aptget(), qw(--download-only --only-source source), $package;
1305 my @dscs = <$aptget_base/source/*.dsc>;
1306 fail "apt-get source did not produce a .dsc" unless @dscs;
1307 fail "apt-get source produced several .dscs (@dscs)" unless @dscs==1;
1309 my $pre_dsc = parsecontrol $dscs[0], $dscs[0], 1;
1312 my $uri = "file://". uri_escape $dscs[0];
1313 $uri =~ s{\%2f}{/}gi;
1314 return [ (getfield $pre_dsc, 'Version'), $uri ];
1317 #---------- `dummyapicat' archive query method ----------
1319 sub archive_query_dummycatapi { archive_query_ftpmasterapi @_; }
1320 sub canonicalise_suite_dummycatapi { canonicalise_suite_ftpmasterapi @_; }
1322 sub file_in_archive_dummycatapi ($$$) {
1323 my ($proto,$data,$filename) = @_;
1324 my $mirror = access_cfg('mirror');
1325 $mirror =~ s#^file://#/# or die "$mirror ?";
1327 my @cmd = (qw(sh -ec), '
1329 find -name "$2" -print0 |
1331 ', qw(x), $mirror, $filename);
1332 debugcmd "-|", @cmd;
1333 open FIA, "-|", @cmd or die $!;
1336 printdebug "| $_\n";
1337 m/^(\w+) (\S+)$/ or die "$_ ?";
1338 push @out, { sha256sum => $1, filename => $2 };
1340 close FIA or die failedcmd @cmd;
1344 #---------- `madison' archive query method ----------
1346 sub archive_query_madison {
1347 return archive_query_prepend_mirror
1348 map { [ @$_[0..1] ] } madison_get_parse(@_);
1351 sub madison_get_parse {
1352 my ($proto,$data) = @_;
1353 die unless $proto eq 'madison';
1354 if (!length $data) {
1355 $data= access_cfg('madison-distro','RETURN-UNDEF');
1356 $data //= access_basedistro();
1358 $rmad{$proto,$data,$package} ||= cmdoutput
1359 qw(rmadison -asource),"-s$isuite","-u$data",$package;
1360 my $rmad = $rmad{$proto,$data,$package};
1363 foreach my $l (split /\n/, $rmad) {
1364 $l =~ m{^ \s*( [^ \t|]+ )\s* \|
1365 \s*( [^ \t|]+ )\s* \|
1366 \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
1367 \s*( [^ \t|]+ )\s* }x or die "$rmad ?";
1368 $1 eq $package or die "$rmad $package ?";
1375 $component = access_cfg('archive-query-default-component');
1377 $5 eq 'source' or die "$rmad ?";
1378 push @out, [$vsn,pool_dsc_subpath($vsn,$component),$newsuite];
1380 return sort { -version_compare($a->[0],$b->[0]); } @out;
1383 sub canonicalise_suite_madison {
1384 # madison canonicalises for us
1385 my @r = madison_get_parse(@_);
1387 "unable to canonicalise suite using package $package".
1388 " which does not appear to exist in suite $isuite;".
1389 " --existing-package may help";
1393 sub file_in_archive_madison { return undef; }
1395 #---------- `sshpsql' archive query method ----------
1398 my ($data,$runeinfo,$sql) = @_;
1399 if (!length $data) {
1400 $data= access_someuserhost('sshpsql').':'.
1401 access_cfg('sshpsql-dbname');
1403 $data =~ m/:/ or badcfg "invalid sshpsql method string \`$data'";
1404 my ($userhost,$dbname) = ($`,$'); #';
1406 my @cmd = (access_cfg_ssh, $userhost,
1407 access_runeinfo("ssh-psql $runeinfo").
1408 " export LC_MESSAGES=C; export LC_CTYPE=C;".
1409 " ".shellquote qw(psql -A), $dbname, qw(-c), $sql);
1411 open P, "-|", @cmd or die $!;
1414 printdebug(">|$_|\n");
1417 $!=0; $?=0; close P or failedcmd @cmd;
1419 my $nrows = pop @rows;
1420 $nrows =~ s/^\((\d+) rows?\)$/$1/ or die "$nrows ?";
1421 @rows == $nrows+1 or die "$nrows ".(scalar @rows)." ?";
1422 @rows = map { [ split /\|/, $_ ] } @rows;
1423 my $ncols = scalar @{ shift @rows };
1424 die if grep { scalar @$_ != $ncols } @rows;
1428 sub sql_injection_check {
1429 foreach (@_) { die "$_ $& ?" if m{[^-+=:_.,/0-9a-zA-Z]}; }
1432 sub archive_query_sshpsql ($$) {
1433 my ($proto,$data) = @_;
1434 sql_injection_check $isuite, $package;
1435 my @rows = sshpsql($data, "archive-query $isuite $package", <<END);
1436 SELECT source.version, component.name, files.filename, files.sha256sum
1438 JOIN src_associations ON source.id = src_associations.source
1439 JOIN suite ON suite.id = src_associations.suite
1440 JOIN dsc_files ON dsc_files.source = source.id
1441 JOIN files_archive_map ON files_archive_map.file_id = dsc_files.file
1442 JOIN component ON component.id = files_archive_map.component_id
1443 JOIN files ON files.id = dsc_files.file
1444 WHERE ( suite.suite_name='$isuite' OR suite.codename='$isuite' )
1445 AND source.source='$package'
1446 AND files.filename LIKE '%.dsc';
1448 @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
1449 my $digester = Digest::SHA->new(256);
1451 my ($vsn,$component,$filename,$sha256sum) = @$_;
1452 [ $vsn, "/pool/$component/$filename",$digester,$sha256sum ];
1454 return archive_query_prepend_mirror @rows;
1457 sub canonicalise_suite_sshpsql ($$) {
1458 my ($proto,$data) = @_;
1459 sql_injection_check $isuite;
1460 my @rows = sshpsql($data, "canonicalise-suite $isuite", <<END);
1461 SELECT suite.codename
1462 FROM suite where suite_name='$isuite' or codename='$isuite';
1464 @rows = map { $_->[0] } @rows;
1465 fail "unknown suite $isuite" unless @rows;
1466 die "ambiguous $isuite: @rows ?" if @rows>1;
1470 sub file_in_archive_sshpsql ($$$) { return undef; }
1472 #---------- `dummycat' archive query method ----------
1474 sub canonicalise_suite_dummycat ($$) {
1475 my ($proto,$data) = @_;
1476 my $dpath = "$data/suite.$isuite";
1477 if (!open C, "<", $dpath) {
1478 $!==ENOENT or die "$dpath: $!";
1479 printdebug "dummycat canonicalise_suite $isuite $dpath ENOENT\n";
1483 chomp or die "$dpath: $!";
1485 printdebug "dummycat canonicalise_suite $isuite $dpath = $_\n";
1489 sub archive_query_dummycat ($$) {
1490 my ($proto,$data) = @_;
1491 canonicalise_suite();
1492 my $dpath = "$data/package.$csuite.$package";
1493 if (!open C, "<", $dpath) {
1494 $!==ENOENT or die "$dpath: $!";
1495 printdebug "dummycat query $csuite $package $dpath ENOENT\n";
1503 printdebug "dummycat query $csuite $package $dpath | $_\n";
1504 my @row = split /\s+/, $_;
1505 @row==2 or die "$dpath: $_ ?";
1508 C->error and die "$dpath: $!";
1510 return archive_query_prepend_mirror
1511 sort { -version_compare($a->[0],$b->[0]); } @rows;
1514 sub file_in_archive_dummycat () { return undef; }
1516 #---------- tag format handling ----------
1518 sub access_cfg_tagformats () {
1519 split /\,/, access_cfg('dgit-tag-format');
1522 sub access_cfg_tagformats_can_splitbrain () {
1523 my %y = map { $_ => 1 } access_cfg_tagformats;
1524 foreach my $needtf (qw(new maint)) {
1525 next if $y{$needtf};
1531 sub need_tagformat ($$) {
1532 my ($fmt, $why) = @_;
1533 fail "need to use tag format $fmt ($why) but also need".
1534 " to use tag format $tagformat_want->[0] ($tagformat_want->[1])".
1535 " - no way to proceed"
1536 if $tagformat_want && $tagformat_want->[0] ne $fmt;
1537 $tagformat_want = [$fmt, $why, $tagformat_want->[2] // 0];
1540 sub select_tagformat () {
1542 return if $tagformatfn && !$tagformat_want;
1543 die 'bug' if $tagformatfn && $tagformat_want;
1544 # ... $tagformat_want assigned after previous select_tagformat
1546 my (@supported) = grep { $_ =~ m/^(?:old|new)$/ } access_cfg_tagformats();
1547 printdebug "select_tagformat supported @supported\n";
1549 $tagformat_want //= [ $supported[0], "distro access configuration", 0 ];
1550 printdebug "select_tagformat specified @$tagformat_want\n";
1552 my ($fmt,$why,$override) = @$tagformat_want;
1554 fail "target distro supports tag formats @supported".
1555 " but have to use $fmt ($why)"
1557 or grep { $_ eq $fmt } @supported;
1559 $tagformat_want = undef;
1561 $tagformatfn = ${*::}{"debiantag_$fmt"};
1563 fail "trying to use unknown tag format \`$fmt' ($why) !"
1564 unless $tagformatfn;
1567 #---------- archive query entrypoints and rest of program ----------
1569 sub canonicalise_suite () {
1570 return if defined $csuite;
1571 fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
1572 $csuite = archive_query('canonicalise_suite');
1573 if ($isuite ne $csuite) {
1574 progress "canonical suite name for $isuite is $csuite";
1576 progress "canonical suite name is $csuite";
1580 sub get_archive_dsc () {
1581 canonicalise_suite();
1582 my @vsns = archive_query('archive_query');
1583 foreach my $vinfo (@vsns) {
1584 my ($vsn,$vsn_dscurl,$digester,$digest) = @$vinfo;
1585 $dscurl = $vsn_dscurl;
1586 $dscdata = url_get($dscurl);
1588 $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
1593 $digester->add($dscdata);
1594 my $got = $digester->hexdigest();
1596 fail "$dscurl has hash $got but".
1597 " archive told us to expect $digest";
1600 my $fmt = getfield $dsc, 'Format';
1601 $format_ok{$fmt} or forceable_fail [qw(unsupported-source-format)],
1602 "unsupported source format $fmt, sorry";
1604 $dsc_checked = !!$digester;
1605 printdebug "get_archive_dsc: Version ".(getfield $dsc, 'Version')."\n";
1609 printdebug "get_archive_dsc: nothing in archive, returning undef\n";
1612 sub check_for_git ();
1613 sub check_for_git () {
1615 my $how = access_cfg('git-check');
1616 if ($how eq 'ssh-cmd') {
1618 (access_cfg_ssh, access_gituserhost(),
1619 access_runeinfo("git-check $package").
1620 " set -e; cd ".access_cfg('git-path').";".
1621 " if test -d $package.git; then echo 1; else echo 0; fi");
1622 my $r= cmdoutput @cmd;
1623 if (defined $r and $r =~ m/^divert (\w+)$/) {
1625 my ($usedistro,) = access_distros();
1626 # NB that if we are pushing, $usedistro will be $distro/push
1627 $instead_distro= cfg("dgit-distro.$usedistro.diverts.$divert");
1628 $instead_distro =~ s{^/}{ access_basedistro()."/" }e;
1629 progress "diverting to $divert (using config for $instead_distro)";
1630 return check_for_git();
1632 failedcmd @cmd unless defined $r and $r =~ m/^[01]$/;
1634 } elsif ($how eq 'url') {
1635 my $prefix = access_cfg('git-check-url','git-url');
1636 my $suffix = access_cfg('git-check-suffix','git-suffix',
1637 'RETURN-UNDEF') // '.git';
1638 my $url = "$prefix/$package$suffix";
1639 my @cmd = (@curl, qw(-sS -I), $url);
1640 my $result = cmdoutput @cmd;
1641 $result =~ s/^\S+ 200 .*\n\r?\n//;
1642 # curl -sS -I with https_proxy prints
1643 # HTTP/1.0 200 Connection established
1644 $result =~ m/^\S+ (404|200) /s or
1645 fail "unexpected results from git check query - ".
1646 Dumper($prefix, $result);
1648 if ($code eq '404') {
1650 } elsif ($code eq '200') {
1655 } elsif ($how eq 'true') {
1657 } elsif ($how eq 'false') {
1660 badcfg "unknown git-check \`$how'";
1664 sub create_remote_git_repo () {
1665 my $how = access_cfg('git-create');
1666 if ($how eq 'ssh-cmd') {
1668 (access_cfg_ssh, access_gituserhost(),
1669 access_runeinfo("git-create $package").
1670 "set -e; cd ".access_cfg('git-path').";".
1671 " cp -a _template $package.git");
1672 } elsif ($how eq 'true') {
1675 badcfg "unknown git-create \`$how'";
1679 our ($dsc_hash,$lastpush_mergeinput);
1681 our $ud = '.git/dgit/unpack';
1691 sub mktree_in_ud_here () {
1692 runcmd qw(git init -q);
1693 runcmd qw(git config gc.auto 0);
1694 rmtree('.git/objects');
1695 symlink '../../../../objects','.git/objects' or die $!;
1698 sub git_write_tree () {
1699 my $tree = cmdoutput @git, qw(write-tree);
1700 $tree =~ m/^\w+$/ or die "$tree ?";
1704 sub git_add_write_tree () {
1705 runcmd @git, qw(add -Af .);
1706 return git_write_tree();
1709 sub remove_stray_gits ($) {
1711 my @gitscmd = qw(find -name .git -prune -print0);
1712 debugcmd "|",@gitscmd;
1713 open GITS, "-|", @gitscmd or die $!;
1718 print STDERR "$us: warning: removing from $what: ",
1719 (messagequote $_), "\n";
1723 $!=0; $?=0; close GITS or failedcmd @gitscmd;
1726 sub mktree_in_ud_from_only_subdir ($;$) {
1727 my ($what,$raw) = @_;
1729 # changes into the subdir
1731 die "expected one subdir but found @dirs ?" unless @dirs==1;
1732 $dirs[0] =~ m#^([^/]+)/\.$# or die;
1736 remove_stray_gits($what);
1737 mktree_in_ud_here();
1739 my ($format, $fopts) = get_source_format();
1740 if (madformat($format)) {
1745 my $tree=git_add_write_tree();
1746 return ($tree,$dir);
1749 our @files_csum_info_fields =
1750 (['Checksums-Sha256','Digest::SHA', 'new(256)', 'sha256sum'],
1751 ['Checksums-Sha1', 'Digest::SHA', 'new(1)', 'sha1sum'],
1752 ['Files', 'Digest::MD5', 'new()', 'md5sum']);
1754 sub dsc_files_info () {
1755 foreach my $csumi (@files_csum_info_fields) {
1756 my ($fname, $module, $method) = @$csumi;
1757 my $field = $dsc->{$fname};
1758 next unless defined $field;
1759 eval "use $module; 1;" or die $@;
1761 foreach (split /\n/, $field) {
1763 m/^(\w+) (\d+) (\S+)$/ or
1764 fail "could not parse .dsc $fname line \`$_'";
1765 my $digester = eval "$module"."->$method;" or die $@;
1770 Digester => $digester,
1775 fail "missing any supported Checksums-* or Files field in ".
1776 $dsc->get_option('name');
1780 map { $_->{Filename} } dsc_files_info();
1783 sub files_compare_inputs (@) {
1788 my $showinputs = sub {
1789 return join "; ", map { $_->get_option('name') } @$inputs;
1792 foreach my $in (@$inputs) {
1794 my $in_name = $in->get_option('name');
1796 printdebug "files_compare_inputs $in_name\n";
1798 foreach my $csumi (@files_csum_info_fields) {
1799 my ($fname) = @$csumi;
1800 printdebug "files_compare_inputs $in_name $fname\n";
1802 my $field = $in->{$fname};
1803 next unless defined $field;
1806 foreach (split /\n/, $field) {
1809 my ($info, $f) = m/^(\w+ \d+) (?:\S+ \S+ )?(\S+)$/ or
1810 fail "could not parse $in_name $fname line \`$_'";
1812 printdebug "files_compare_inputs $in_name $fname $f\n";
1816 my $re = \ $record{$f}{$fname};
1818 $fchecked{$f}{$in_name} = 1;
1820 fail "hash or size of $f varies in $fname fields".
1821 " (between: ".$showinputs->().")";
1826 @files = sort @files;
1827 $expected_files //= \@files;
1828 "@$expected_files" eq "@files" or
1829 fail "file list in $in_name varies between hash fields!";
1832 fail "$in_name has no files list field(s)";
1834 printdebug "files_compare_inputs ".Dumper(\%fchecked, \%record)
1837 grep { keys %$_ == @$inputs-1 } values %fchecked
1838 or fail "no file appears in all file lists".
1839 " (looked in: ".$showinputs->().")";
1842 sub is_orig_file_in_dsc ($$) {
1843 my ($f, $dsc_files_info) = @_;
1844 return 0 if @$dsc_files_info <= 1;
1845 # One file means no origs, and the filename doesn't have a "what
1846 # part of dsc" component. (Consider versions ending `.orig'.)
1847 return 0 unless $f =~ m/\.$orig_f_tail_re$/o;
1851 sub is_orig_file_of_vsn ($$) {
1852 my ($f, $upstreamvsn) = @_;
1853 my $base = srcfn $upstreamvsn, '';
1854 return 0 unless $f =~ m/^\Q$base\E\.$orig_f_tail_re$/;
1858 sub changes_update_origs_from_dsc ($$$$) {
1859 my ($dsc, $changes, $upstreamvsn, $changesfile) = @_;
1861 printdebug "checking origs needed ($upstreamvsn)...\n";
1862 $_ = getfield $changes, 'Files';
1863 m/^\w+ \d+ (\S+ \S+) \S+$/m or
1864 fail "cannot find section/priority from .changes Files field";
1865 my $placementinfo = $1;
1867 printdebug "checking origs needed placement '$placementinfo'...\n";
1868 foreach my $l (split /\n/, getfield $dsc, 'Files') {
1869 $l =~ m/\S+$/ or next;
1871 printdebug "origs $file | $l\n";
1872 next unless is_orig_file_of_vsn $file, $upstreamvsn;
1873 printdebug "origs $file is_orig\n";
1874 my $have = archive_query('file_in_archive', $file);
1875 if (!defined $have) {
1877 archive does not support .orig check; hope you used --ch:--sa/-sd if needed
1883 printdebug "origs $file \$#\$have=$#$have\n";
1884 foreach my $h (@$have) {
1887 foreach my $csumi (@files_csum_info_fields) {
1888 my ($fname, $module, $method, $archivefield) = @$csumi;
1889 next unless defined $h->{$archivefield};
1890 $_ = $dsc->{$fname};
1891 next unless defined;
1892 m/^(\w+) .* \Q$file\E$/m or
1893 fail ".dsc $fname missing entry for $file";
1894 if ($h->{$archivefield} eq $1) {
1898 "$archivefield: $h->{$archivefield} (archive) != $1 (local .dsc)";
1901 die "$file ".Dumper($h)." ?!" if $same && @differ;
1904 push @found_differ, "archive $h->{filename}: ".join "; ", @differ
1907 printdebug "origs $file f.same=$found_same".
1908 " #f._differ=$#found_differ\n";
1909 if (@found_differ && !$found_same) {
1911 "archive contains $file with different checksum",
1914 # Now we edit the changes file to add or remove it
1915 foreach my $csumi (@files_csum_info_fields) {
1916 my ($fname, $module, $method, $archivefield) = @$csumi;
1917 next unless defined $changes->{$fname};
1919 # in archive, delete from .changes if it's there
1920 $changed{$file} = "removed" if
1921 $changes->{$fname} =~ s/^.* \Q$file\E$(?:)\n//m;
1922 } elsif ($changes->{$fname} =~ m/^.* \Q$file\E$(?:)\n/m) {
1923 # not in archive, but it's here in the .changes
1925 my $dsc_data = getfield $dsc, $fname;
1926 $dsc_data =~ m/^(.* \Q$file\E$)\n/m or die "$dsc_data $file ?";
1928 $extra =~ s/ \d+ /$&$placementinfo /
1929 or die "$fname $extra >$dsc_data< ?"
1930 if $fname eq 'Files';
1931 $changes->{$fname} .= "\n". $extra;
1932 $changed{$file} = "added";
1937 foreach my $file (keys %changed) {
1939 "edited .changes for archive .orig contents: %s %s",
1940 $changed{$file}, $file;
1942 my $chtmp = "$changesfile.tmp";
1943 $changes->save($chtmp);
1945 rename $chtmp,$changesfile or die "$changesfile $!";
1947 progress "[new .changes left in $changesfile]";
1950 progress "$changesfile already has appropriate .orig(s) (if any)";
1954 sub make_commit ($) {
1956 return cmdoutput @git, qw(hash-object -w -t commit), $file;
1959 sub make_commit_text ($) {
1962 my @cmd = (@git, qw(hash-object -w -t commit --stdin));
1964 print Dumper($text) if $debuglevel > 1;
1965 my $child = open2($out, $in, @cmd) or die $!;
1968 print $in $text or die $!;
1969 close $in or die $!;
1971 $h =~ m/^\w+$/ or die;
1973 printdebug "=> $h\n";
1976 waitpid $child, 0 == $child or die "$child $!";
1977 $? and failedcmd @cmd;
1981 sub clogp_authline ($) {
1983 my $author = getfield $clogp, 'Maintainer';
1984 $author =~ s#,.*##ms;
1985 my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
1986 my $authline = "$author $date";
1987 $authline =~ m/$git_authline_re/o or
1988 fail "unexpected commit author line format \`$authline'".
1989 " (was generated from changelog Maintainer field)";
1990 return ($1,$2,$3) if wantarray;
1994 sub vendor_patches_distro ($$) {
1995 my ($checkdistro, $what) = @_;
1996 return unless defined $checkdistro;
1998 my $series = "debian/patches/\L$checkdistro\E.series";
1999 printdebug "checking for vendor-specific $series ($what)\n";
2001 if (!open SERIES, "<", $series) {
2002 die "$series $!" unless $!==ENOENT;
2011 Unfortunately, this source package uses a feature of dpkg-source where
2012 the same source package unpacks to different source code on different
2013 distros. dgit cannot safely operate on such packages on affected
2014 distros, because the meaning of source packages is not stable.
2016 Please ask the distro/maintainer to remove the distro-specific series
2017 files and use a different technique (if necessary, uploading actually
2018 different packages, if different distros are supposed to have
2022 fail "Found active distro-specific series file for".
2023 " $checkdistro ($what): $series, cannot continue";
2025 die "$series $!" if SERIES->error;
2029 sub check_for_vendor_patches () {
2030 # This dpkg-source feature doesn't seem to be documented anywhere!
2031 # But it can be found in the changelog (reformatted):
2033 # commit 4fa01b70df1dc4458daee306cfa1f987b69da58c
2034 # Author: Raphael Hertzog <hertzog@debian.org>
2035 # Date: Sun Oct 3 09:36:48 2010 +0200
2037 # dpkg-source: correctly create .pc/.quilt_series with alternate
2040 # If you have debian/patches/ubuntu.series and you were
2041 # unpacking the source package on ubuntu, quilt was still
2042 # directed to debian/patches/series instead of
2043 # debian/patches/ubuntu.series.
2045 # debian/changelog | 3 +++
2046 # scripts/Dpkg/Source/Package/V3/quilt.pm | 4 +++-
2047 # 2 files changed, 6 insertions(+), 1 deletion(-)
2050 vendor_patches_distro($ENV{DEB_VENDOR}, "DEB_VENDOR");
2051 vendor_patches_distro(Dpkg::Vendor::get_current_vendor(),
2052 "Dpkg::Vendor \`current vendor'");
2053 vendor_patches_distro(access_basedistro(),
2054 "(base) distro being accessed");
2055 vendor_patches_distro(access_nomdistro(),
2056 "(nominal) distro being accessed");
2059 sub generate_commits_from_dsc () {
2060 # See big comment in fetch_from_archive, below.
2061 # See also README.dsc-import.
2065 my @dfi = dsc_files_info();
2066 foreach my $fi (@dfi) {
2067 my $f = $fi->{Filename};
2068 die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
2070 printdebug "considering linking $f: ";
2072 link_ltarget "../../../../$f", $f
2073 or ((printdebug "($!) "), 0)
2077 printdebug "linked.\n";
2079 complete_file_from_dsc('.', $fi)
2082 if (is_orig_file_in_dsc($f, \@dfi)) {
2083 link $f, "../../../../$f"
2089 # We unpack and record the orig tarballs first, so that we only
2090 # need disk space for one private copy of the unpacked source.
2091 # But we can't make them into commits until we have the metadata
2092 # from the debian/changelog, so we record the tree objects now and
2093 # make them into commits later.
2095 my $upstreamv = upstreamversion $dsc->{version};
2096 my $orig_f_base = srcfn $upstreamv, '';
2098 foreach my $fi (@dfi) {
2099 # We actually import, and record as a commit, every tarball
2100 # (unless there is only one file, in which case there seems
2103 my $f = $fi->{Filename};
2104 printdebug "import considering $f ";
2105 (printdebug "only one dfi\n"), next if @dfi == 1;
2106 (printdebug "not tar\n"), next unless $f =~ m/\.tar(\.\w+)?$/;
2107 (printdebug "signature\n"), next if $f =~ m/$orig_f_sig_re$/o;
2111 $f =~ m/^\Q$orig_f_base\E\.([^._]+)?\.tar(?:\.\w+)?$/;
2113 printdebug "Y ", (join ' ', map { $_//"(none)" }
2114 $compr_ext, $orig_f_part
2117 my $input = new IO::File $f, '<' or die "$f $!";
2121 if (defined $compr_ext) {
2123 Dpkg::Compression::compression_guess_from_filename $f;
2124 fail "Dpkg::Compression cannot handle file $f in source package"
2125 if defined $compr_ext && !defined $cname;
2127 new Dpkg::Compression::Process compression => $cname;
2128 my @compr_cmd = $compr_proc->get_uncompress_cmdline();
2129 my $compr_fh = new IO::Handle;
2130 my $compr_pid = open $compr_fh, "-|" // die $!;
2132 open STDIN, "<&", $input or die $!;
2134 die "dgit (child): exec $compr_cmd[0]: $!\n";
2139 rmtree "_unpack-tar";
2140 mkdir "_unpack-tar" or die $!;
2141 my @tarcmd = qw(tar -x -f -
2142 --no-same-owner --no-same-permissions
2143 --no-acls --no-xattrs --no-selinux);
2144 my $tar_pid = fork // die $!;
2146 chdir "_unpack-tar" or die $!;
2147 open STDIN, "<&", $input or die $!;
2149 die "dgit (child): exec $tarcmd[0]: $!";
2151 $!=0; (waitpid $tar_pid, 0) == $tar_pid or die $!;
2152 !$? or failedcmd @tarcmd;
2155 (@compr_cmd ? failedcmd @compr_cmd
2157 # finally, we have the results in "tarball", but maybe
2158 # with the wrong permissions
2160 runcmd qw(chmod -R +rwX _unpack-tar);
2161 changedir "_unpack-tar";
2162 remove_stray_gits($f);
2163 mktree_in_ud_here();
2165 my ($tree) = git_add_write_tree();
2166 my $tentries = cmdoutput @git, qw(ls-tree -z), $tree;
2167 if ($tentries =~ m/^\d+ tree (\w+)\t[^\000]+\000$/s) {
2169 printdebug "one subtree $1\n";
2171 printdebug "multiple subtrees\n";
2174 rmtree "_unpack-tar";
2176 my $ent = [ $f, $tree ];
2178 Orig => !!$orig_f_part,
2179 Sort => (!$orig_f_part ? 2 :
2180 $orig_f_part =~ m/-/g ? 1 :
2188 # put any without "_" first (spec is not clear whether files
2189 # are always in the usual order). Tarballs without "_" are
2190 # the main orig or the debian tarball.
2191 $a->{Sort} <=> $b->{Sort} or
2195 my $any_orig = grep { $_->{Orig} } @tartrees;
2197 my $dscfn = "$package.dsc";
2199 my $treeimporthow = 'package';
2201 open D, ">", $dscfn or die "$dscfn: $!";
2202 print D $dscdata or die "$dscfn: $!";
2203 close D or die "$dscfn: $!";
2204 my @cmd = qw(dpkg-source);
2205 push @cmd, '--no-check' if $dsc_checked;
2206 if (madformat $dsc->{format}) {
2207 push @cmd, '--skip-patches';
2208 $treeimporthow = 'unpatched';
2210 push @cmd, qw(-x --), $dscfn;
2213 my ($tree,$dir) = mktree_in_ud_from_only_subdir("source package");
2214 if (madformat $dsc->{format}) {
2215 check_for_vendor_patches();
2219 if (madformat $dsc->{format}) {
2220 my @pcmd = qw(dpkg-source --before-build .);
2221 runcmd shell_cmd 'exec >/dev/null', @pcmd;
2223 $dappliedtree = git_add_write_tree();
2226 my @clogcmd = qw(dpkg-parsechangelog --format rfc822 --all);
2227 debugcmd "|",@clogcmd;
2228 open CLOGS, "-|", @clogcmd or die $!;
2233 printdebug "import clog search...\n";
2236 my $stanzatext = do { local $/=""; <CLOGS>; };
2237 printdebug "import clogp ".Dumper($stanzatext) if $debuglevel>1;
2238 last if !defined $stanzatext;
2240 my $desc = "package changelog, entry no.$.";
2241 open my $stanzafh, "<", \$stanzatext or die;
2242 my $thisstanza = parsecontrolfh $stanzafh, $desc, 1;
2243 $clogp //= $thisstanza;
2245 printdebug "import clog $thisstanza->{version} $desc...\n";
2247 last if !$any_orig; # we don't need $r1clogp
2249 # We look for the first (most recent) changelog entry whose
2250 # version number is lower than the upstream version of this
2251 # package. Then the last (least recent) previous changelog
2252 # entry is treated as the one which introduced this upstream
2253 # version and used for the synthetic commits for the upstream
2256 # One might think that a more sophisticated algorithm would be
2257 # necessary. But: we do not want to scan the whole changelog
2258 # file. Stopping when we see an earlier version, which
2259 # necessarily then is an earlier upstream version, is the only
2260 # realistic way to do that. Then, either the earliest
2261 # changelog entry we have seen so far is indeed the earliest
2262 # upload of this upstream version; or there are only changelog
2263 # entries relating to later upstream versions (which is not
2264 # possible unless the changelog and .dsc disagree about the
2265 # version). Then it remains to choose between the physically
2266 # last entry in the file, and the one with the lowest version
2267 # number. If these are not the same, we guess that the
2268 # versions were created in a non-monotic order rather than
2269 # that the changelog entries have been misordered.
2271 printdebug "import clog $thisstanza->{version} vs $upstreamv...\n";
2273 last if version_compare($thisstanza->{version}, $upstreamv) < 0;
2274 $r1clogp = $thisstanza;
2276 printdebug "import clog $r1clogp->{version} becomes r1\n";
2278 die $! if CLOGS->error;
2279 close CLOGS or $?==SIGPIPE or failedcmd @clogcmd;
2281 $clogp or fail "package changelog has no entries!";
2283 my $authline = clogp_authline $clogp;
2284 my $changes = getfield $clogp, 'Changes';
2285 my $cversion = getfield $clogp, 'Version';
2288 $r1clogp //= $clogp; # maybe there's only one entry;
2289 my $r1authline = clogp_authline $r1clogp;
2290 # Strictly, r1authline might now be wrong if it's going to be
2291 # unused because !$any_orig. Whatever.
2293 printdebug "import tartrees authline $authline\n";
2294 printdebug "import tartrees r1authline $r1authline\n";
2296 foreach my $tt (@tartrees) {
2297 printdebug "import tartree $tt->{F} $tt->{Tree}\n";
2299 $tt->{Commit} = make_commit_text($tt->{Orig} ? <<END_O : <<END_T);
2302 committer $r1authline
2306 [dgit import orig $tt->{F}]
2314 [dgit import tarball $package $cversion $tt->{F}]
2319 printdebug "import main commit\n";
2321 open C, ">../commit.tmp" or die $!;
2322 print C <<END or die $!;
2325 print C <<END or die $! foreach @tartrees;
2328 print C <<END or die $!;
2334 [dgit import $treeimporthow $package $cversion]
2338 my $rawimport_hash = make_commit qw(../commit.tmp);
2340 if (madformat $dsc->{format}) {
2341 printdebug "import apply patches...\n";
2343 # regularise the state of the working tree so that
2344 # the checkout of $rawimport_hash works nicely.
2345 my $dappliedcommit = make_commit_text(<<END);
2352 runcmd @git, qw(checkout -q -b dapplied), $dappliedcommit;
2354 runcmd @git, qw(checkout -q -b unpa), $rawimport_hash;
2356 # We need the answers to be reproducible
2357 my @authline = clogp_authline($clogp);
2358 local $ENV{GIT_COMMITTER_NAME} = $authline[0];
2359 local $ENV{GIT_COMMITTER_EMAIL} = $authline[1];
2360 local $ENV{GIT_COMMITTER_DATE} = $authline[2];
2361 local $ENV{GIT_AUTHOR_NAME} = $authline[0];
2362 local $ENV{GIT_AUTHOR_EMAIL} = $authline[1];
2363 local $ENV{GIT_AUTHOR_DATE} = $authline[2];
2365 my $path = $ENV{PATH} or die;
2367 foreach my $use_absurd (qw(0 1)) {
2368 local $ENV{PATH} = $path;
2371 progress "warning: $@";
2372 $path = "$absurdity:$path";
2373 progress "$us: trying slow absurd-git-apply...";
2374 rename "../../gbp-pq-output","../../gbp-pq-output.0"
2379 die "forbid absurd git-apply\n" if $use_absurd
2380 && forceing [qw(import-gitapply-no-absurd)];
2381 die "only absurd git-apply!\n" if !$use_absurd
2382 && forceing [qw(import-gitapply-absurd)];
2384 local $ENV{PATH} = $path if $use_absurd;
2386 my @showcmd = (gbp_pq, qw(import));
2387 my @realcmd = shell_cmd
2388 'exec >/dev/null 2>../../gbp-pq-output', @showcmd;
2389 debugcmd "+",@realcmd;
2390 if (system @realcmd) {
2391 die +(shellquote @showcmd).
2393 failedcmd_waitstatus()."\n";
2396 my $gapplied = git_rev_parse('HEAD');
2397 my $gappliedtree = cmdoutput @git, qw(rev-parse HEAD:);
2398 $gappliedtree eq $dappliedtree or
2400 gbp-pq import and dpkg-source disagree!
2401 gbp-pq import gave commit $gapplied
2402 gbp-pq import gave tree $gappliedtree
2403 dpkg-source --before-build gave tree $dappliedtree
2405 $rawimport_hash = $gapplied;
2410 { local $@; eval { runcmd qw(cat ../../gbp-pq-output); }; }
2415 progress "synthesised git commit from .dsc $cversion";
2417 my $rawimport_mergeinput = {
2418 Commit => $rawimport_hash,
2419 Info => "Import of source package",
2421 my @output = ($rawimport_mergeinput);
2423 if ($lastpush_mergeinput) {
2424 my $oldclogp = mergeinfo_getclogp($lastpush_mergeinput);
2425 my $oversion = getfield $oldclogp, 'Version';
2427 version_compare($oversion, $cversion);
2429 @output = ($rawimport_mergeinput, $lastpush_mergeinput,
2430 { Message => <<END, ReverseParents => 1 });
2431 Record $package ($cversion) in archive suite $csuite
2433 } elsif ($vcmp > 0) {
2434 print STDERR <<END or die $!;
2436 Version actually in archive: $cversion (older)
2437 Last version pushed with dgit: $oversion (newer or same)
2440 @output = $lastpush_mergeinput;
2442 # Same version. Use what's in the server git branch,
2443 # discarding our own import. (This could happen if the
2444 # server automatically imports all packages into git.)
2445 @output = $lastpush_mergeinput;
2448 changedir '../../../..';
2453 sub complete_file_from_dsc ($$) {
2454 our ($dstdir, $fi) = @_;
2455 # Ensures that we have, in $dir, the file $fi, with the correct
2456 # contents. (Downloading it from alongside $dscurl if necessary.)
2458 my $f = $fi->{Filename};
2459 my $tf = "$dstdir/$f";
2462 if (stat_exists $tf) {
2463 progress "using existing $f";
2465 printdebug "$tf does not exist, need to fetch\n";
2467 $furl =~ s{/[^/]+$}{};
2469 die "$f ?" unless $f =~ m/^\Q${package}\E_/;
2470 die "$f ?" if $f =~ m#/#;
2471 runcmd_ordryrun_local @curl,qw(-f -o),$tf,'--',"$furl";
2472 return 0 if !act_local();
2476 open F, "<", "$tf" or die "$tf: $!";
2477 $fi->{Digester}->reset();
2478 $fi->{Digester}->addfile(*F);
2479 F->error and die $!;
2480 my $got = $fi->{Digester}->hexdigest();
2481 $got eq $fi->{Hash} or
2482 fail "file $f has hash $got but .dsc".
2483 " demands hash $fi->{Hash} ".
2484 ($downloaded ? "(got wrong file from archive!)"
2485 : "(perhaps you should delete this file?)");
2490 sub ensure_we_have_orig () {
2491 my @dfi = dsc_files_info();
2492 foreach my $fi (@dfi) {
2493 my $f = $fi->{Filename};
2494 next unless is_orig_file_in_dsc($f, \@dfi);
2495 complete_file_from_dsc('..', $fi)
2500 sub git_fetch_us () {
2501 # Want to fetch only what we are going to use, unless
2502 # deliberately-not-ff, in which case we must fetch everything.
2504 my @specs = deliberately_not_fast_forward ? qw(tags/*) :
2506 (quiltmode_splitbrain
2507 ? (map { $_->('*',access_nomdistro) }
2508 \&debiantag_new, \&debiantag_maintview)
2509 : debiantags('*',access_nomdistro));
2510 push @specs, server_branch($csuite);
2511 push @specs, qw(heads/*) if deliberately_not_fast_forward;
2513 # This is rather miserable:
2514 # When git fetch --prune is passed a fetchspec ending with a *,
2515 # it does a plausible thing. If there is no * then:
2516 # - it matches subpaths too, even if the supplied refspec
2517 # starts refs, and behaves completely madly if the source
2518 # has refs/refs/something. (See, for example, Debian #NNNN.)
2519 # - if there is no matching remote ref, it bombs out the whole
2521 # We want to fetch a fixed ref, and we don't know in advance
2522 # if it exists, so this is not suitable.
2524 # Our workaround is to use git ls-remote. git ls-remote has its
2525 # own qairks. Notably, it has the absurd multi-tail-matching
2526 # behaviour: git ls-remote R refs/foo can report refs/foo AND
2527 # refs/refs/foo etc.
2529 # Also, we want an idempotent snapshot, but we have to make two
2530 # calls to the remote: one to git ls-remote and to git fetch. The
2531 # solution is use git ls-remote to obtain a target state, and
2532 # git fetch to try to generate it. If we don't manage to generate
2533 # the target state, we try again.
2535 printdebug "git_fetch_us specs @specs\n";
2537 my $specre = join '|', map {
2543 printdebug "git_fetch_us specre=$specre\n";
2544 my $wanted_rref = sub {
2546 return m/^(?:$specre)$/o;
2549 my $fetch_iteration = 0;
2552 printdebug "git_fetch_us iteration $fetch_iteration\n";
2553 if (++$fetch_iteration > 10) {
2554 fail "too many iterations trying to get sane fetch!";
2557 my @look = map { "refs/$_" } @specs;
2558 my @lcmd = (@git, qw(ls-remote -q --refs), access_giturl(), @look);
2562 open GITLS, "-|", @lcmd or die $!;
2564 printdebug "=> ", $_;
2565 m/^(\w+)\s+(\S+)\n/ or die "ls-remote $_ ?";
2566 my ($objid,$rrefname) = ($1,$2);
2567 if (!$wanted_rref->($rrefname)) {
2569 warning: git ls-remote @look reported $rrefname; this is silly, ignoring it.
2573 $wantr{$rrefname} = $objid;
2576 close GITLS or failedcmd @lcmd;
2578 # OK, now %want is exactly what we want for refs in @specs
2580 !m/\*$/ && !exists $wantr{"refs/$_"} ? () :
2581 "+refs/$_:".lrfetchrefs."/$_";
2584 printdebug "git_fetch_us fspecs @fspecs\n";
2586 my @fcmd = (@git, qw(fetch -p -n -q), access_giturl(), @fspecs);
2587 runcmd_ordryrun_local @git, qw(fetch -p -n -q), access_giturl(),
2590 %lrfetchrefs_f = ();
2593 git_for_each_ref(lrfetchrefs, sub {
2594 my ($objid,$objtype,$lrefname,$reftail) = @_;
2595 $lrfetchrefs_f{$lrefname} = $objid;
2596 $objgot{$objid} = 1;
2599 foreach my $lrefname (sort keys %lrfetchrefs_f) {
2600 my $rrefname = 'refs'.substr($lrefname, length lrfetchrefs);
2601 if (!exists $wantr{$rrefname}) {
2602 if ($wanted_rref->($rrefname)) {
2604 git-fetch @fspecs created $lrefname which git ls-remote @look didn't list.
2608 warning: git fetch @fspecs created $lrefname; this is silly, deleting it.
2611 runcmd_ordryrun_local @git, qw(update-ref -d), $lrefname;
2612 delete $lrfetchrefs_f{$lrefname};
2616 foreach my $rrefname (sort keys %wantr) {
2617 my $lrefname = lrfetchrefs.substr($rrefname, 4);
2618 my $got = $lrfetchrefs_f{$lrefname} // '<none>';
2619 my $want = $wantr{$rrefname};
2620 next if $got eq $want;
2621 if (!defined $objgot{$want}) {
2623 warning: git ls-remote suggests we want $lrefname
2624 warning: and it should refer to $want
2625 warning: but git fetch didn't fetch that object to any relevant ref.
2626 warning: This may be due to a race with someone updating the server.
2627 warning: Will try again...
2629 next FETCH_ITERATION;
2632 git-fetch @fspecs made $lrefname=$got but want git ls-remote @look says $want
2634 runcmd_ordryrun_local @git, qw(update-ref -m),
2635 "dgit fetch git fetch fixup", $lrefname, $want;
2636 $lrfetchrefs_f{$lrefname} = $want;
2640 printdebug "git_fetch_us: git fetch --no-insane emulation complete\n",
2641 Dumper(\%lrfetchrefs_f);
2644 my @tagpats = debiantags('*',access_nomdistro);
2646 git_for_each_ref([map { "refs/tags/$_" } @tagpats], sub {
2647 my ($objid,$objtype,$fullrefname,$reftail) = @_;
2648 printdebug "currently $fullrefname=$objid\n";
2649 $here{$fullrefname} = $objid;
2651 git_for_each_ref([map { lrfetchrefs."/tags/".$_ } @tagpats], sub {
2652 my ($objid,$objtype,$fullrefname,$reftail) = @_;
2653 my $lref = "refs".substr($fullrefname, length(lrfetchrefs));
2654 printdebug "offered $lref=$objid\n";
2655 if (!defined $here{$lref}) {
2656 my @upd = (@git, qw(update-ref), $lref, $objid, '');
2657 runcmd_ordryrun_local @upd;
2658 lrfetchref_used $fullrefname;
2659 } elsif ($here{$lref} eq $objid) {
2660 lrfetchref_used $fullrefname;
2663 "Not updateting $lref from $here{$lref} to $objid.\n";
2668 sub mergeinfo_getclogp ($) {
2669 # Ensures thit $mi->{Clogp} exists and returns it
2671 $mi->{Clogp} = commit_getclogp($mi->{Commit});
2674 sub mergeinfo_version ($) {
2675 return getfield( (mergeinfo_getclogp $_[0]), 'Version' );
2678 sub fetch_from_archive_record_1 ($) {
2680 runcmd @git, qw(update-ref -m), "dgit fetch $csuite",
2681 'DGIT_ARCHIVE', $hash;
2682 cmdoutput @git, qw(log -n2), $hash;
2683 # ... gives git a chance to complain if our commit is malformed
2686 sub fetch_from_archive_record_2 ($) {
2688 my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
2692 dryrun_report @upd_cmd;
2696 sub fetch_from_archive () {
2697 ensure_setup_existing_tree();
2699 # Ensures that lrref() is what is actually in the archive, one way
2700 # or another, according to us - ie this client's
2701 # appropritaely-updated archive view. Also returns the commit id.
2702 # If there is nothing in the archive, leaves lrref alone and
2703 # returns undef. git_fetch_us must have already been called.
2707 foreach my $field (@ourdscfield) {
2708 $dsc_hash = $dsc->{$field};
2709 last if defined $dsc_hash;
2711 if (defined $dsc_hash) {
2712 $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
2714 progress "last upload to archive specified git hash";
2716 progress "last upload to archive has NO git hash";
2719 progress "no version available from the archive";
2722 # If the archive's .dsc has a Dgit field, there are three
2723 # relevant git commitids we need to choose between and/or merge
2725 # 1. $dsc_hash: the Dgit field from the archive
2726 # 2. $lastpush_hash: the suite branch on the dgit git server
2727 # 3. $lastfetch_hash: our local tracking brach for the suite
2729 # These may all be distinct and need not be in any fast forward
2732 # If the dsc was pushed to this suite, then the server suite
2733 # branch will have been updated; but it might have been pushed to
2734 # a different suite and copied by the archive. Conversely a more
2735 # recent version may have been pushed with dgit but not appeared
2736 # in the archive (yet).
2738 # $lastfetch_hash may be awkward because archive imports
2739 # (particularly, imports of Dgit-less .dscs) are performed only as
2740 # needed on individual clients, so different clients may perform a
2741 # different subset of them - and these imports are only made
2742 # public during push. So $lastfetch_hash may represent a set of
2743 # imports different to a subsequent upload by a different dgit
2746 # Our approach is as follows:
2748 # As between $dsc_hash and $lastpush_hash: if $lastpush_hash is a
2749 # descendant of $dsc_hash, then it was pushed by a dgit user who
2750 # had based their work on $dsc_hash, so we should prefer it.
2751 # Otherwise, $dsc_hash was installed into this suite in the
2752 # archive other than by a dgit push, and (necessarily) after the
2753 # last dgit push into that suite (since a dgit push would have
2754 # been descended from the dgit server git branch); thus, in that
2755 # case, we prefer the archive's version (and produce a
2756 # pseudo-merge to overwrite the dgit server git branch).
2758 # (If there is no Dgit field in the archive's .dsc then
2759 # generate_commit_from_dsc uses the version numbers to decide
2760 # whether the suite branch or the archive is newer. If the suite
2761 # branch is newer it ignores the archive's .dsc; otherwise it
2762 # generates an import of the .dsc, and produces a pseudo-merge to
2763 # overwrite the suite branch with the archive contents.)
2765 # The outcome of that part of the algorithm is the `public view',
2766 # and is same for all dgit clients: it does not depend on any
2767 # unpublished history in the local tracking branch.
2769 # As between the public view and the local tracking branch: The
2770 # local tracking branch is only updated by dgit fetch, and
2771 # whenever dgit fetch runs it includes the public view in the
2772 # local tracking branch. Therefore if the public view is not
2773 # descended from the local tracking branch, the local tracking
2774 # branch must contain history which was imported from the archive
2775 # but never pushed; and, its tip is now out of date. So, we make
2776 # a pseudo-merge to overwrite the old imports and stitch the old
2779 # Finally: we do not necessarily reify the public view (as
2780 # described above). This is so that we do not end up stacking two
2781 # pseudo-merges. So what we actually do is figure out the inputs
2782 # to any public view pseudo-merge and put them in @mergeinputs.
2785 # $mergeinputs[]{Commit}
2786 # $mergeinputs[]{Info}
2787 # $mergeinputs[0] is the one whose tree we use
2788 # @mergeinputs is in the order we use in the actual commit)
2791 # $mergeinputs[]{Message} is a commit message to use
2792 # $mergeinputs[]{ReverseParents} if def specifies that parent
2793 # list should be in opposite order
2794 # Such an entry has no Commit or Info. It applies only when found
2795 # in the last entry. (This ugliness is to support making
2796 # identical imports to previous dgit versions.)
2798 my $lastpush_hash = git_get_ref(lrfetchref());
2799 printdebug "previous reference hash=$lastpush_hash\n";
2800 $lastpush_mergeinput = $lastpush_hash && {
2801 Commit => $lastpush_hash,
2802 Info => "dgit suite branch on dgit git server",
2805 my $lastfetch_hash = git_get_ref(lrref());
2806 printdebug "fetch_from_archive: lastfetch=$lastfetch_hash\n";
2807 my $lastfetch_mergeinput = $lastfetch_hash && {
2808 Commit => $lastfetch_hash,
2809 Info => "dgit client's archive history view",
2812 my $dsc_mergeinput = $dsc_hash && {
2813 Commit => $dsc_hash,
2814 Info => "Dgit field in .dsc from archive",
2818 my $del_lrfetchrefs = sub {
2821 printdebug "del_lrfetchrefs...\n";
2822 foreach my $fullrefname (sort keys %lrfetchrefs_d) {
2823 my $objid = $lrfetchrefs_d{$fullrefname};
2824 printdebug "del_lrfetchrefs: $objid $fullrefname\n";
2826 $gur ||= new IO::Handle;
2827 open $gur, "|-", qw(git update-ref --stdin) or die $!;
2829 printf $gur "delete %s %s\n", $fullrefname, $objid;
2832 close $gur or failedcmd "git update-ref delete lrfetchrefs";
2836 if (defined $dsc_hash) {
2837 ensure_we_have_orig();
2838 if (!$lastpush_hash || $dsc_hash eq $lastpush_hash) {
2839 @mergeinputs = $dsc_mergeinput
2840 } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
2841 print STDERR <<END or die $!;
2843 Git commit in archive is behind the last version allegedly pushed/uploaded.
2844 Commit referred to by archive: $dsc_hash
2845 Last version pushed with dgit: $lastpush_hash
2848 @mergeinputs = ($lastpush_mergeinput);
2850 # Archive has .dsc which is not a descendant of the last dgit
2851 # push. This can happen if the archive moves .dscs about.
2852 # Just follow its lead.
2853 if (is_fast_fwd($lastpush_hash,$dsc_hash)) {
2854 progress "archive .dsc names newer git commit";
2855 @mergeinputs = ($dsc_mergeinput);
2857 progress "archive .dsc names other git commit, fixing up";
2858 @mergeinputs = ($dsc_mergeinput, $lastpush_mergeinput);
2862 @mergeinputs = generate_commits_from_dsc();
2863 # We have just done an import. Now, our import algorithm might
2864 # have been improved. But even so we do not want to generate
2865 # a new different import of the same package. So if the
2866 # version numbers are the same, just use our existing version.
2867 # If the version numbers are different, the archive has changed
2868 # (perhaps, rewound).
2869 if ($lastfetch_mergeinput &&
2870 !version_compare( (mergeinfo_version $lastfetch_mergeinput),
2871 (mergeinfo_version $mergeinputs[0]) )) {
2872 @mergeinputs = ($lastfetch_mergeinput);
2874 } elsif ($lastpush_hash) {
2875 # only in git, not in the archive yet
2876 @mergeinputs = ($lastpush_mergeinput);
2877 print STDERR <<END or die $!;
2879 Package not found in the archive, but has allegedly been pushed using dgit.
2883 printdebug "nothing found!\n";
2884 if (defined $skew_warning_vsn) {
2885 print STDERR <<END or die $!;
2887 Warning: relevant archive skew detected.
2888 Archive allegedly contains $skew_warning_vsn
2889 But we were not able to obtain any version from the archive or git.
2893 unshift @end, $del_lrfetchrefs;
2897 if ($lastfetch_hash &&
2899 my $h = $_->{Commit};
2900 $h and is_fast_fwd($lastfetch_hash, $h);
2901 # If true, one of the existing parents of this commit
2902 # is a descendant of the $lastfetch_hash, so we'll
2903 # be ff from that automatically.
2907 push @mergeinputs, $lastfetch_mergeinput;
2910 printdebug "fetch mergeinfos:\n";
2911 foreach my $mi (@mergeinputs) {
2913 printdebug " commit $mi->{Commit} $mi->{Info}\n";
2915 printdebug sprintf " ReverseParents=%d Message=%s",
2916 $mi->{ReverseParents}, $mi->{Message};
2920 my $compat_info= pop @mergeinputs
2921 if $mergeinputs[$#mergeinputs]{Message};
2923 @mergeinputs = grep { defined $_->{Commit} } @mergeinputs;
2926 if (@mergeinputs > 1) {
2928 my $tree_commit = $mergeinputs[0]{Commit};
2930 my $tree = cmdoutput @git, qw(cat-file commit), $tree_commit;
2931 $tree =~ m/\n\n/; $tree = $`;
2932 $tree =~ m/^tree (\w+)$/m or die "$dsc_hash tree ?";
2935 # We use the changelog author of the package in question the
2936 # author of this pseudo-merge. This is (roughly) correct if
2937 # this commit is simply representing aa non-dgit upload.
2938 # (Roughly because it does not record sponsorship - but we
2939 # don't have sponsorship info because that's in the .changes,
2940 # which isn't in the archivw.)
2942 # But, it might be that we are representing archive history
2943 # updates (including in-archive copies). These are not really
2944 # the responsibility of the person who created the .dsc, but
2945 # there is no-one whose name we should better use. (The
2946 # author of the .dsc-named commit is clearly worse.)
2948 my $useclogp = mergeinfo_getclogp $mergeinputs[0];
2949 my $author = clogp_authline $useclogp;
2950 my $cversion = getfield $useclogp, 'Version';
2952 my $mcf = ".git/dgit/mergecommit";
2953 open MC, ">", $mcf or die "$mcf $!";
2954 print MC <<END or die $!;
2958 my @parents = grep { $_->{Commit} } @mergeinputs;
2959 @parents = reverse @parents if $compat_info->{ReverseParents};
2960 print MC <<END or die $! foreach @parents;
2964 print MC <<END or die $!;
2970 if (defined $compat_info->{Message}) {
2971 print MC $compat_info->{Message} or die $!;
2973 print MC <<END or die $!;
2974 Record $package ($cversion) in archive suite $csuite
2978 my $message_add_info = sub {
2980 my $mversion = mergeinfo_version $mi;
2981 printf MC " %-20s %s\n", $mversion, $mi->{Info}
2985 $message_add_info->($mergeinputs[0]);
2986 print MC <<END or die $!;
2987 should be treated as descended from
2989 $message_add_info->($_) foreach @mergeinputs[1..$#mergeinputs];
2993 $hash = make_commit $mcf;
2995 $hash = $mergeinputs[0]{Commit};
2997 printdebug "fetch hash=$hash\n";
3000 my ($lasth, $what) = @_;
3001 return unless $lasth;
3002 die "$lasth $hash $what ?" unless is_fast_fwd($lasth, $hash);
3005 $chkff->($lastpush_hash, 'dgit repo server tip (last push)')
3007 $chkff->($lastfetch_hash, 'local tracking tip (last fetch)');
3009 fetch_from_archive_record_1($hash);
3011 if (defined $skew_warning_vsn) {
3013 printdebug "SKEW CHECK WANT $skew_warning_vsn\n";
3014 my $gotclogp = commit_getclogp($hash);
3015 my $got_vsn = getfield $gotclogp, 'Version';
3016 printdebug "SKEW CHECK GOT $got_vsn\n";
3017 if (version_compare($got_vsn, $skew_warning_vsn) < 0) {
3018 print STDERR <<END or die $!;
3020 Warning: archive skew detected. Using the available version:
3021 Archive allegedly contains $skew_warning_vsn
3022 We were able to obtain only $got_vsn
3028 if ($lastfetch_hash ne $hash) {
3029 fetch_from_archive_record_2($hash);
3032 lrfetchref_used lrfetchref();
3034 unshift @end, $del_lrfetchrefs;
3038 sub set_local_git_config ($$) {
3040 runcmd @git, qw(config), $k, $v;
3043 sub setup_mergechangelogs (;$) {
3045 return unless $always || access_cfg_bool(1, 'setup-mergechangelogs');
3047 my $driver = 'dpkg-mergechangelogs';
3048 my $cb = "merge.$driver";
3049 my $attrs = '.git/info/attributes';
3050 ensuredir '.git/info';
3052 open NATTRS, ">", "$attrs.new" or die "$attrs.new $!";
3053 if (!open ATTRS, "<", $attrs) {
3054 $!==ENOENT or die "$attrs: $!";
3058 next if m{^debian/changelog\s};
3059 print NATTRS $_, "\n" or die $!;
3061 ATTRS->error and die $!;
3064 print NATTRS "debian/changelog merge=$driver\n" or die $!;
3067 set_local_git_config "$cb.name", 'debian/changelog merge driver';
3068 set_local_git_config "$cb.driver", 'dpkg-mergechangelogs -m %O %A %B %A';
3070 rename "$attrs.new", "$attrs" or die "$attrs: $!";
3073 sub setup_useremail (;$) {
3075 return unless $always || access_cfg_bool(1, 'setup-useremail');
3078 my ($k, $envvar) = @_;
3079 my $v = access_cfg("user-$k", 'RETURN-UNDEF') // $ENV{$envvar};
3080 return unless defined $v;
3081 set_local_git_config "user.$k", $v;
3084 $setup->('email', 'DEBEMAIL');
3085 $setup->('name', 'DEBFULLNAME');
3088 sub ensure_setup_existing_tree () {
3089 my $k = "remote.$remotename.skipdefaultupdate";
3090 my $c = git_get_config $k;
3091 return if defined $c;
3092 set_local_git_config $k, 'true';
3095 sub setup_new_tree () {
3096 setup_mergechangelogs();
3100 sub multisuite_suite_child ($$$) {
3101 my ($tsuite, $merginputs, $fn) = @_;
3102 # in child, sets things up, calls $fn->(), and returns undef
3103 # in parent, returns canonical suite name for $tsuite
3104 my $canonsuitefh = IO::File::new_tmpfile;
3105 my $pid = fork // die $!;
3108 $us .= " [$isuite]";
3109 $debugprefix .= " ";
3110 progress "fetching $tsuite...";
3111 canonicalise_suite();
3112 print $canonsuitefh $csuite, "\n" or die $!;
3113 close $canonsuitefh or die $!;
3117 waitpid $pid,0 == $pid or die $!;
3118 fail "failed to obtain $tsuite: ".waitstatusmsg() if $? && $?!=256*4;
3119 seek $canonsuitefh,0,0 or die $!;
3120 local $csuite = <$canonsuitefh>;
3121 die $! unless defined $csuite && chomp $csuite;
3123 printdebug "multisuite $tsuite missing\n";
3126 printdebug "multisuite $tsuite ok (canon=$csuite)\n";
3127 push @$merginputs, {
3134 sub fork_for_multisuite ($) {
3135 my ($before_fetch_merge) = @_;
3136 # if nothing unusual, just returns ''
3139 # returns 0 to caller in child, to do first of the specified suites
3140 # in child, $csuite is not yet set
3142 # returns 1 to caller in parent, to finish up anything needed after
3143 # in parent, $csuite is set to canonicalised portmanteau
3145 my $org_isuite = $isuite;
3146 my @suites = split /\,/, $isuite;
3147 return '' unless @suites > 1;
3148 printdebug "fork_for_multisuite: @suites\n";
3152 my $cbasesuite = multisuite_suite_child($suites[0], \@mergeinputs,
3154 return 0 unless defined $cbasesuite;
3156 fail "package $package missing in (base suite) $cbasesuite"
3157 unless @mergeinputs;
3159 my @csuites = ($cbasesuite);
3161 $before_fetch_merge->();
3163 foreach my $tsuite (@suites[1..$#suites]) {
3164 my $csubsuite = multisuite_suite_child($tsuite, \@mergeinputs,
3170 # xxx collecte the ref here
3172 $csubsuite =~ s/^\Q$cbasesuite\E-/-/;
3173 push @csuites, $csubsuite;
3176 foreach my $mi (@mergeinputs) {
3177 my $ref = git_get_ref $mi->{Ref};
3178 die "$mi->{Ref} ?" unless length $ref;
3179 $mi->{Commit} = $ref;
3182 $csuite = join ",", @csuites;
3184 my $previous = git_get_ref lrref;
3186 unshift @mergeinputs, {
3187 Commit => $previous,
3188 Info => "local combined tracking branch",
3190 "archive seems to have rewound: local tracking branch is ahead!",
3194 foreach my $ix (0..$#mergeinputs) {
3195 $mergeinputs[$ix]{Index} = $ix;
3198 @mergeinputs = sort {
3199 -version_compare(mergeinfo_version $a,
3200 mergeinfo_version $b) # highest version first
3202 $a->{Index} <=> $b->{Index}; # earliest in spec first
3208 foreach my $mi (@mergeinputs) {
3209 printdebug "multisuite merge check $mi->{Info}\n";
3210 foreach my $previous (@needed) {
3211 next unless is_fast_fwd $mi->{Commit}, $previous->{Commit};
3212 printdebug "multisuite merge un-needed $previous->{Info}\n";
3216 printdebug "multisuite merge this-needed\n";
3217 $mi->{Character} = '+';
3220 $needed[0]{Character} = '*';
3222 my $output = $needed[0]{Commit};
3225 printdebug "multisuite merge nontrivial\n";
3226 my $tree = cmdoutput qw(git rev-parse), $needed[0]{Commit}.':';
3228 my $commit = "tree $tree\n";
3229 my $msg = "Combine archive branches $csuite [dgit]\n\n".
3230 "Input branches:\n";
3232 foreach my $mi (sort { $a->{Index} <=> $b->{Index} } @mergeinputs) {
3233 printdebug "multisuite merge include $mi->{Info}\n";
3234 $mi->{Character} //= ' ';
3235 $commit .= "parent $mi->{Commit}\n";
3236 $msg .= sprintf " %s %-25s %s\n",
3238 (mergeinfo_version $mi),
3241 my $authline = clogp_authline mergeinfo_getclogp $needed[0];
3243 " * marks the highest version branch, which choose to use\n".
3244 " + marks each branch which was not already an ancestor\n\n".
3245 "[dgit multi-suite $csuite]\n";
3247 "author $authline\n".
3248 "committer $authline\n\n";
3249 $output = make_commit_text $commit.$msg;
3250 printdebug "multisuite merge generated $output\n";
3253 fetch_from_archive_record_1($output);
3254 fetch_from_archive_record_2($output);
3256 progress "calculated combined tracking suite $csuite";
3261 sub clone_set_head () {
3262 open H, "> .git/HEAD" or die $!;
3263 print H "ref: ".lref()."\n" or die $!;
3266 sub clone_finish ($) {
3268 runcmd @git, qw(reset --hard), lrref();
3269 runcmd qw(bash -ec), <<'END';
3271 git ls-tree -r --name-only -z HEAD | \
3272 xargs -0r touch -r . --
3274 printdone "ready for work in $dstdir";
3279 badusage "dry run makes no sense with clone" unless act_local();
3281 my $multi_fetched = fork_for_multisuite(sub {
3282 printdebug "multi clone before fetch merge\n";
3285 if ($multi_fetched) {
3286 printdebug "multi clone after fetch merge\n";
3288 clone_finish($dstdir);
3291 printdebug "clone main body\n";
3293 canonicalise_suite();
3294 my $hasgit = check_for_git();
3295 mkdir $dstdir or fail "create \`$dstdir': $!";
3297 runcmd @git, qw(init -q);
3299 my $giturl = access_giturl(1);
3300 if (defined $giturl) {
3301 runcmd @git, qw(remote add), 'origin', $giturl;
3304 progress "fetching existing git history";
3306 runcmd_ordryrun_local @git, qw(fetch origin);
3308 progress "starting new git history";
3310 fetch_from_archive() or no_such_package;
3311 my $vcsgiturl = $dsc->{'Vcs-Git'};
3312 if (length $vcsgiturl) {
3313 $vcsgiturl =~ s/\s+-b\s+\S+//g;
3314 runcmd @git, qw(remote add vcs-git), $vcsgiturl;
3317 clone_finish($dstdir);
3321 canonicalise_suite();
3322 if (check_for_git()) {
3325 fetch_from_archive() or no_such_package();
3326 printdone "fetched into ".lrref();
3330 my $multi_fetched = fork_for_multisuite(sub { });
3331 fetch() unless $multi_fetched; # parent
3332 return if $multi_fetched eq '0'; # child
3333 runcmd_ordryrun_local @git, qw(merge -m),"Merge from $csuite [dgit]",
3335 printdone "fetched to ".lrref()." and merged into HEAD";
3338 sub check_not_dirty () {
3339 foreach my $f (qw(local-options local-patch-header)) {
3340 if (stat_exists "debian/source/$f") {
3341 fail "git tree contains debian/source/$f";
3345 return if $ignoredirty;
3347 my @cmd = (@git, qw(diff --quiet HEAD));
3349 $!=0; $?=-1; system @cmd;
3352 fail "working tree is dirty (does not match HEAD)";
3358 sub commit_admin ($) {
3361 runcmd_ordryrun_local @git, qw(commit -m), $m;
3364 sub commit_quilty_patch () {
3365 my $output = cmdoutput @git, qw(status --porcelain);
3367 foreach my $l (split /\n/, $output) {
3368 next unless $l =~ m/\S/;
3369 if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
3373 delete $adds{'.pc'}; # if there wasn't one before, don't add it
3375 progress "nothing quilty to commit, ok.";
3378 my @adds = map { s/[][*?\\]/\\$&/g; $_; } sort keys %adds;
3379 runcmd_ordryrun_local @git, qw(add -f), @adds;
3381 Commit Debian 3.0 (quilt) metadata
3383 [dgit ($our_version) quilt-fixup]
3387 sub get_source_format () {
3389 if (open F, "debian/source/options") {
3393 s/\s+$//; # ignore missing final newline
3395 my ($k, $v) = ($`, $'); #');
3396 $v =~ s/^"(.*)"$/$1/;
3402 F->error and die $!;
3405 die $! unless $!==&ENOENT;
3408 if (!open F, "debian/source/format") {
3409 die $! unless $!==&ENOENT;
3413 F->error and die $!;
3415 return ($_, \%options);
3418 sub madformat_wantfixup ($) {
3420 return 0 unless $format eq '3.0 (quilt)';
3421 our $quilt_mode_warned;
3422 if ($quilt_mode eq 'nocheck') {
3423 progress "Not doing any fixup of \`$format' due to".
3424 " ----no-quilt-fixup or --quilt=nocheck"
3425 unless $quilt_mode_warned++;
3428 progress "Format \`$format', need to check/update patch stack"
3429 unless $quilt_mode_warned++;
3433 sub maybe_split_brain_save ($$$) {
3434 my ($headref, $dgitview, $msg) = @_;
3435 # => message fragment "$saved" describing disposition of $dgitview
3436 return "commit id $dgitview" unless defined $split_brain_save;
3437 my @cmd = (shell_cmd "cd ../../../..",
3438 @git, qw(update-ref -m),
3439 "dgit --dgit-view-save $msg HEAD=$headref",
3440 $split_brain_save, $dgitview);
3442 return "and left in $split_brain_save";
3445 # An "infopair" is a tuple [ $thing, $what ]
3446 # (often $thing is a commit hash; $what is a description)
3448 sub infopair_cond_equal ($$) {
3450 $x->[0] eq $y->[0] or fail <<END;
3451 $x->[1] ($x->[0]) not equal to $y->[1] ($y->[0])
3455 sub infopair_lrf_tag_lookup ($$) {
3456 my ($tagnames, $what) = @_;
3457 # $tagname may be an array ref
3458 my @tagnames = ref $tagnames ? @$tagnames : ($tagnames);
3459 printdebug "infopair_lrfetchref_tag_lookup $what @tagnames\n";
3460 foreach my $tagname (@tagnames) {
3461 my $lrefname = lrfetchrefs."/tags/$tagname";
3462 my $tagobj = $lrfetchrefs_f{$lrefname};
3463 next unless defined $tagobj;
3464 printdebug "infopair_lrfetchref_tag_lookup $tagobj $tagname $what\n";
3465 return [ git_rev_parse($tagobj), $what ];
3467 fail @tagnames==1 ? <<END : <<END;
3468 Wanted tag $what (@tagnames) on dgit server, but not found
3470 Wanted tag $what (one of: @tagnames) on dgit server, but not found
3474 sub infopair_cond_ff ($$) {
3475 my ($anc,$desc) = @_;
3476 is_fast_fwd($anc->[0], $desc->[0]) or fail <<END;
3477 $anc->[1] ($anc->[0]) .. $desc->[1] ($desc->[0]) is not fast forward
3481 sub pseudomerge_version_check ($$) {
3482 my ($clogp, $archive_hash) = @_;
3484 my $arch_clogp = commit_getclogp $archive_hash;
3485 my $i_arch_v = [ (getfield $arch_clogp, 'Version'),
3486 'version currently in archive' ];
3487 if (defined $overwrite_version) {
3488 if (length $overwrite_version) {
3489 infopair_cond_equal([ $overwrite_version,
3490 '--overwrite= version' ],
3493 my $v = $i_arch_v->[0];
3494 progress "Checking package changelog for archive version $v ...";
3496 my @xa = ("-f$v", "-t$v");
3497 my $vclogp = parsechangelog @xa;
3498 my $cv = [ (getfield $vclogp, 'Version'),
3499 "Version field from dpkg-parsechangelog @xa" ];
3500 infopair_cond_equal($i_arch_v, $cv);
3503 $@ =~ s/^dgit: //gm;
3505 "Perhaps debian/changelog does not mention $v ?";
3510 printdebug "pseudomerge_version_check i_arch_v @$i_arch_v\n";
3514 sub pseudomerge_make_commit ($$$$ $$) {
3515 my ($clogp, $dgitview, $archive_hash, $i_arch_v,
3516 $msg_cmd, $msg_msg) = @_;
3517 progress "Declaring that HEAD inciudes all changes in $i_arch_v->[0]...";
3519 my $tree = cmdoutput qw(git rev-parse), "${dgitview}:";
3520 my $authline = clogp_authline $clogp;
3524 !defined $overwrite_version ? ""
3525 : !length $overwrite_version ? " --overwrite"
3526 : " --overwrite=".$overwrite_version;
3529 my $pmf = ".git/dgit/pseudomerge";
3530 open MC, ">", $pmf or die "$pmf $!";
3531 print MC <<END or die $!;
3534 parent $archive_hash
3544 return make_commit($pmf);
3547 sub splitbrain_pseudomerge ($$$$) {
3548 my ($clogp, $maintview, $dgitview, $archive_hash) = @_;
3549 # => $merged_dgitview
3550 printdebug "splitbrain_pseudomerge...\n";
3552 # We: debian/PREVIOUS HEAD($maintview)
3553 # expect: o ----------------- o
3556 # a/d/PREVIOUS $dgitview
3559 # we do: `------------------ o
3563 return $dgitview unless defined $archive_hash;
3565 printdebug "splitbrain_pseudomerge...\n";
3567 my $i_arch_v = pseudomerge_version_check($clogp, $archive_hash);
3569 if (!defined $overwrite_version) {
3570 progress "Checking that HEAD inciudes all changes in archive...";
3573 return $dgitview if is_fast_fwd $archive_hash, $dgitview;
3575 if (defined $overwrite_version) {
3577 my $t_dep14 = debiantag_maintview $i_arch_v->[0], access_nomdistro;
3578 my $i_dep14 = infopair_lrf_tag_lookup($t_dep14, "maintainer view tag");
3579 my $t_dgit = debiantag_new $i_arch_v->[0], access_nomdistro;
3580 my $i_dgit = infopair_lrf_tag_lookup($t_dgit, "dgit view tag");
3581 my $i_archive = [ $archive_hash, "current archive contents" ];
3583 printdebug "splitbrain_pseudomerge i_archive @$i_archive\n";
3585 infopair_cond_equal($i_dgit, $i_archive);
3586 infopair_cond_ff($i_dep14, $i_dgit);
3587 infopair_cond_ff($i_dep14, [ $maintview, 'HEAD' ]);
3591 $us: check failed (maybe --overwrite is needed, consult documentation)
3596 my $r = pseudomerge_make_commit
3597 $clogp, $dgitview, $archive_hash, $i_arch_v,
3598 "dgit --quilt=$quilt_mode",
3599 (defined $overwrite_version ? <<END_OVERWR : <<END_MAKEFF);
3600 Declare fast forward from $i_arch_v->[0]
3602 Make fast forward from $i_arch_v->[0]
3605 maybe_split_brain_save $maintview, $r, "pseudomerge";
3607 progress "Made pseudo-merge of $i_arch_v->[0] into dgit view.";
3611 sub plain_overwrite_pseudomerge ($$$) {
3612 my ($clogp, $head, $archive_hash) = @_;
3614 printdebug "plain_overwrite_pseudomerge...";
3616 my $i_arch_v = pseudomerge_version_check($clogp, $archive_hash);
3618 return $head if is_fast_fwd $archive_hash, $head;
3620 my $m = "Declare fast forward from $i_arch_v->[0]";
3622 my $r = pseudomerge_make_commit
3623 $clogp, $head, $archive_hash, $i_arch_v,
3626 runcmd @git, qw(update-ref -m), $m, 'HEAD', $r, $head;
3628 progress "Make pseudo-merge of $i_arch_v->[0] into your HEAD.";
3632 sub push_parse_changelog ($) {
3635 my $clogp = Dpkg::Control::Hash->new();
3636 $clogp->load($clogpfn) or die;
3638 my $clogpackage = getfield $clogp, 'Source';
3639 $package //= $clogpackage;
3640 fail "-p specified $package but changelog specified $clogpackage"
3641 unless $package eq $clogpackage;
3642 my $cversion = getfield $clogp, 'Version';
3643 my $tag = debiantag($cversion, access_nomdistro);
3644 runcmd @git, qw(check-ref-format), $tag;
3646 my $dscfn = dscfn($cversion);
3648 return ($clogp, $cversion, $dscfn);
3651 sub push_parse_dsc ($$$) {
3652 my ($dscfn,$dscfnwhat, $cversion) = @_;
3653 $dsc = parsecontrol($dscfn,$dscfnwhat);
3654 my $dversion = getfield $dsc, 'Version';
3655 my $dscpackage = getfield $dsc, 'Source';
3656 ($dscpackage eq $package && $dversion eq $cversion) or
3657 fail "$dscfn is for $dscpackage $dversion".
3658 " but debian/changelog is for $package $cversion";
3661 sub push_tagwants ($$$$) {
3662 my ($cversion, $dgithead, $maintviewhead, $tfbase) = @_;
3665 TagFn => \&debiantag,
3670 if (defined $maintviewhead) {
3672 TagFn => \&debiantag_maintview,
3673 Objid => $maintviewhead,
3674 TfSuffix => '-maintview',
3678 foreach my $tw (@tagwants) {
3679 $tw->{Tag} = $tw->{TagFn}($cversion, access_nomdistro);
3680 $tw->{Tfn} = sub { $tfbase.$tw->{TfSuffix}.$_[0]; };
3682 printdebug 'push_tagwants: ', Dumper(\@_, \@tagwants);
3686 sub push_mktags ($$ $$ $) {
3688 $changesfile,$changesfilewhat,
3691 die unless $tagwants->[0]{View} eq 'dgit';
3693 $dsc->{$ourdscfield[0]} = $tagwants->[0]{Objid};
3694 $dsc->save("$dscfn.tmp") or die $!;
3696 my $changes = parsecontrol($changesfile,$changesfilewhat);
3697 foreach my $field (qw(Source Distribution Version)) {
3698 $changes->{$field} eq $clogp->{$field} or
3699 fail "changes field $field \`$changes->{$field}'".
3700 " does not match changelog \`$clogp->{$field}'";
3703 my $cversion = getfield $clogp, 'Version';
3704 my $clogsuite = getfield $clogp, 'Distribution';
3706 # We make the git tag by hand because (a) that makes it easier
3707 # to control the "tagger" (b) we can do remote signing
3708 my $authline = clogp_authline $clogp;
3709 my $delibs = join(" ", "",@deliberatelies);
3710 my $declaredistro = access_nomdistro();
3714 my $tfn = $tw->{Tfn};
3715 my $head = $tw->{Objid};
3716 my $tag = $tw->{Tag};
3718 open TO, '>', $tfn->('.tmp') or die $!;
3719 print TO <<END or die $!;
3726 if ($tw->{View} eq 'dgit') {
3727 print TO <<END or die $!;
3728 $package release $cversion for $clogsuite ($csuite) [dgit]
3729 [dgit distro=$declaredistro$delibs]
3731 foreach my $ref (sort keys %previously) {
3732 print TO <<END or die $!;
3733 [dgit previously:$ref=$previously{$ref}]
3736 } elsif ($tw->{View} eq 'maint') {
3737 print TO <<END or die $!;
3738 $package release $cversion for $clogsuite ($csuite)
3739 (maintainer view tag generated by dgit --quilt=$quilt_mode)
3742 die Dumper($tw)."?";
3747 my $tagobjfn = $tfn->('.tmp');
3749 if (!defined $keyid) {
3750 $keyid = access_cfg('keyid','RETURN-UNDEF');
3752 if (!defined $keyid) {
3753 $keyid = getfield $clogp, 'Maintainer';
3755 unlink $tfn->('.tmp.asc') or $!==&ENOENT or die $!;
3756 my @sign_cmd = (@gpg, qw(--detach-sign --armor));
3757 push @sign_cmd, qw(-u),$keyid if defined $keyid;
3758 push @sign_cmd, $tfn->('.tmp');
3759 runcmd_ordryrun @sign_cmd;
3761 $tagobjfn = $tfn->('.signed.tmp');
3762 runcmd shell_cmd "exec >$tagobjfn", qw(cat --),
3763 $tfn->('.tmp'), $tfn->('.tmp.asc');
3769 my @r = map { $mktag->($_); } @$tagwants;
3773 sub sign_changes ($) {
3774 my ($changesfile) = @_;
3776 my @debsign_cmd = @debsign;
3777 push @debsign_cmd, "-k$keyid" if defined $keyid;
3778 push @debsign_cmd, "-p$gpg[0]" if $gpg[0] ne 'gpg';
3779 push @debsign_cmd, $changesfile;
3780 runcmd_ordryrun @debsign_cmd;
3785 printdebug "actually entering push\n";
3787 supplementary_message(<<'END');
3788 Push failed, while checking state of the archive.
3789 You can retry the push, after fixing the problem, if you like.
3791 if (check_for_git()) {
3794 my $archive_hash = fetch_from_archive();
3795 if (!$archive_hash) {
3797 fail "package appears to be new in this suite;".
3798 " if this is intentional, use --new";
3801 supplementary_message(<<'END');
3802 Push failed, while preparing your push.
3803 You can retry the push, after fixing the problem, if you like.
3806 need_tagformat 'new', "quilt mode $quilt_mode"
3807 if quiltmode_splitbrain;
3811 access_giturl(); # check that success is vaguely likely
3814 my $clogpfn = ".git/dgit/changelog.822.tmp";
3815 runcmd shell_cmd "exec >$clogpfn", qw(dpkg-parsechangelog);
3817 responder_send_file('parsed-changelog', $clogpfn);
3819 my ($clogp, $cversion, $dscfn) =
3820 push_parse_changelog("$clogpfn");
3822 my $dscpath = "$buildproductsdir/$dscfn";
3823 stat_exists $dscpath or
3824 fail "looked for .dsc $dscpath, but $!;".
3825 " maybe you forgot to build";
3827 responder_send_file('dsc', $dscpath);
3829 push_parse_dsc($dscpath, $dscfn, $cversion);
3831 my $format = getfield $dsc, 'Format';
3832 printdebug "format $format\n";
3834 my $actualhead = git_rev_parse('HEAD');
3835 my $dgithead = $actualhead;
3836 my $maintviewhead = undef;
3838 my $upstreamversion = upstreamversion $clogp->{Version};
3840 if (madformat_wantfixup($format)) {
3841 # user might have not used dgit build, so maybe do this now:
3842 if (quiltmode_splitbrain()) {
3844 quilt_make_fake_dsc($upstreamversion);
3846 ($dgithead, $cachekey) =
3847 quilt_check_splitbrain_cache($actualhead, $upstreamversion);
3849 "--quilt=$quilt_mode but no cached dgit view:
3850 perhaps tree changed since dgit build[-source] ?";
3852 $dgithead = splitbrain_pseudomerge($clogp,
3853 $actualhead, $dgithead,
3855 $maintviewhead = $actualhead;
3856 changedir '../../../..';
3857 prep_ud(); # so _only_subdir() works, below
3859 commit_quilty_patch();
3863 if (defined $overwrite_version && !defined $maintviewhead) {
3864 $dgithead = plain_overwrite_pseudomerge($clogp,
3872 if ($archive_hash) {
3873 if (is_fast_fwd($archive_hash, $dgithead)) {
3875 } elsif (deliberately_not_fast_forward) {
3878 fail "dgit push: HEAD is not a descendant".
3879 " of the archive's version.\n".
3880 "To overwrite the archive's contents,".
3881 " pass --overwrite[=VERSION].\n".
3882 "To rewind history, if permitted by the archive,".
3883 " use --deliberately-not-fast-forward.";
3888 progress "checking that $dscfn corresponds to HEAD";
3889 runcmd qw(dpkg-source -x --),
3890 $dscpath =~ m#^/# ? $dscpath : "../../../$dscpath";
3891 my ($tree,$dir) = mktree_in_ud_from_only_subdir("source package");
3892 check_for_vendor_patches() if madformat($dsc->{format});
3893 changedir '../../../..';
3894 my @diffcmd = (@git, qw(diff --quiet), $tree, $dgithead);
3895 debugcmd "+",@diffcmd;
3897 my $r = system @diffcmd;
3900 my $diffs = cmdoutput @git, qw(diff --stat), $tree, $dgithead;
3902 HEAD specifies a different tree to $dscfn:
3904 Perhaps you forgot to build. Or perhaps there is a problem with your
3905 source tree (see dgit(7) for some hints). To see a full diff, run
3912 if (!$changesfile) {
3913 my $pat = changespat $cversion;
3914 my @cs = glob "$buildproductsdir/$pat";
3915 fail "failed to find unique changes file".
3916 " (looked for $pat in $buildproductsdir);".
3917 " perhaps you need to use dgit -C"
3919 ($changesfile) = @cs;
3921 $changesfile = "$buildproductsdir/$changesfile";
3924 # Check that changes and .dsc agree enough
3925 $changesfile =~ m{[^/]*$};
3926 my $changes = parsecontrol($changesfile,$&);
3927 files_compare_inputs($dsc, $changes)
3928 unless forceing [qw(dsc-changes-mismatch)];
3930 # Perhaps adjust .dsc to contain right set of origs
3931 changes_update_origs_from_dsc($dsc, $changes, $upstreamversion,
3933 unless forceing [qw(changes-origs-exactly)];
3935 # Checks complete, we're going to try and go ahead:
3937 responder_send_file('changes',$changesfile);
3938 responder_send_command("param head $dgithead");
3939 responder_send_command("param csuite $csuite");
3940 responder_send_command("param tagformat $tagformat");
3941 if (defined $maintviewhead) {
3942 die unless ($protovsn//4) >= 4;
3943 responder_send_command("param maint-view $maintviewhead");
3946 if (deliberately_not_fast_forward) {
3947 git_for_each_ref(lrfetchrefs, sub {
3948 my ($objid,$objtype,$lrfetchrefname,$reftail) = @_;
3949 my $rrefname= substr($lrfetchrefname, length(lrfetchrefs) + 1);
3950 responder_send_command("previously $rrefname=$objid");
3951 $previously{$rrefname} = $objid;
3955 my @tagwants = push_tagwants($cversion, $dgithead, $maintviewhead,
3959 supplementary_message(<<'END');
3960 Push failed, while signing the tag.
3961 You can retry the push, after fixing the problem, if you like.
3963 # If we manage to sign but fail to record it anywhere, it's fine.
3964 if ($we_are_responder) {
3965 @tagobjfns = map { $_->{Tfn}('.signed-tmp') } @tagwants;
3966 responder_receive_files('signed-tag', @tagobjfns);
3968 @tagobjfns = push_mktags($clogp,$dscpath,
3969 $changesfile,$changesfile,
3972 supplementary_message(<<'END');
3973 Push failed, *after* signing the tag.
3974 If you want to try again, you should use a new version number.
3977 pairwise { $a->{TagObjFn} = $b } @tagwants, @tagobjfns;
3979 foreach my $tw (@tagwants) {
3980 my $tag = $tw->{Tag};
3981 my $tagobjfn = $tw->{TagObjFn};
3983 cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
3984 runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
3985 runcmd_ordryrun_local
3986 @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
3989 supplementary_message(<<'END');
3990 Push failed, while updating the remote git repository - see messages above.
3991 If you want to try again, you should use a new version number.
3993 if (!check_for_git()) {
3994 create_remote_git_repo();
3997 my @pushrefs = $forceflag.$dgithead.":".rrref();
3998 foreach my $tw (@tagwants) {
3999 push @pushrefs, $forceflag."refs/tags/$tw->{Tag}";
4002 runcmd_ordryrun @git,
4003 qw(-c push.followTags=false push), access_giturl(), @pushrefs;
4004 runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), $dgithead;
4006 supplementary_message(<<'END');
4007 Push failed, while obtaining signatures on the .changes and .dsc.
4008 If it was just that the signature failed, you may try again by using
4009 debsign by hand to sign the changes
4011 and then dput to complete the upload.
4012 If you need to change the package, you must use a new version number.
4014 if ($we_are_responder) {
4015 my $dryrunsuffix = act_local() ? "" : ".tmp";
4016 responder_receive_files('signed-dsc-changes',
4017 "$dscpath$dryrunsuffix",
4018 "$changesfile$dryrunsuffix");
4021 rename "$dscpath.tmp",$dscpath or die "$dscfn $!";
4023 progress "[new .dsc left in $dscpath.tmp]";
4025 sign_changes $changesfile;
4028 supplementary_message(<<END);
4029 Push failed, while uploading package(s) to the archive server.
4030 You can retry the upload of exactly these same files with dput of:
4032 If that .changes file is broken, you will need to use a new version
4033 number for your next attempt at the upload.
4035 my $host = access_cfg('upload-host','RETURN-UNDEF');
4036 my @hostarg = defined($host) ? ($host,) : ();
4037 runcmd_ordryrun @dput, @hostarg, $changesfile;
4038 printdone "pushed and uploaded $cversion";
4040 supplementary_message('');
4041 responder_send_command("complete");
4048 badusage "-p is not allowed with clone; specify as argument instead"
4049 if defined $package;
4052 } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
4053 ($package,$isuite) = @ARGV;
4054 } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
4055 ($package,$dstdir) = @ARGV;
4056 } elsif (@ARGV==3) {
4057 ($package,$isuite,$dstdir) = @ARGV;
4059 badusage "incorrect arguments to dgit clone";
4061 $dstdir ||= "$package";
4063 if (stat_exists $dstdir) {
4064 fail "$dstdir already exists";
4068 if ($rmonerror && !$dryrun_level) {
4069 $cwd_remove= getcwd();
4071 return unless defined $cwd_remove;
4072 if (!chdir "$cwd_remove") {
4073 return if $!==&ENOENT;
4074 die "chdir $cwd_remove: $!";
4076 printdebug "clone rmonerror removing $dstdir\n";
4078 rmtree($dstdir) or die "remove $dstdir: $!\n";
4079 } elsif (grep { $! == $_ }
4080 (ENOENT, ENOTDIR, EACCES, EPERM, ELOOP)) {
4082 print STDERR "check whether to remove $dstdir: $!\n";
4088 $cwd_remove = undef;
4091 sub branchsuite () {
4092 my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
4093 if ($branch =~ m#$lbranch_re#o) {
4100 sub fetchpullargs () {
4102 if (!defined $package) {
4103 my $sourcep = parsecontrol('debian/control','debian/control');
4104 $package = getfield $sourcep, 'Source';
4107 $isuite = branchsuite();
4109 my $clogp = parsechangelog();
4110 $isuite = getfield $clogp, 'Distribution';
4112 } elsif (@ARGV==1) {
4115 badusage "incorrect arguments to dgit fetch or dgit pull";
4122 my $multi_fetched = fork_for_multisuite(sub { });
4123 exit 0 if $multi_fetched;
4130 if (quiltmode_splitbrain()) {
4131 my ($format, $fopts) = get_source_format();
4132 madformat($format) and fail <<END
4133 dgit pull not yet supported in split view mode (--quilt=$quilt_mode)
4142 badusage "-p is not allowed with dgit push" if defined $package;
4144 my $clogp = parsechangelog();
4145 $package = getfield $clogp, 'Source';
4148 } elsif (@ARGV==1) {
4149 ($specsuite) = (@ARGV);
4151 badusage "incorrect arguments to dgit push";
4153 $isuite = getfield $clogp, 'Distribution';
4155 local ($package) = $existing_package; # this is a hack
4156 canonicalise_suite();
4158 canonicalise_suite();
4160 if (defined $specsuite &&
4161 $specsuite ne $isuite &&
4162 $specsuite ne $csuite) {
4163 fail "dgit push: changelog specifies $isuite ($csuite)".
4164 " but command line specifies $specsuite";
4169 #---------- remote commands' implementation ----------
4171 sub cmd_remote_push_build_host {
4172 my ($nrargs) = shift @ARGV;
4173 my (@rargs) = @ARGV[0..$nrargs-1];
4174 @ARGV = @ARGV[$nrargs..$#ARGV];
4176 my ($dir,$vsnwant) = @rargs;
4177 # vsnwant is a comma-separated list; we report which we have
4178 # chosen in our ready response (so other end can tell if they
4181 $we_are_responder = 1;
4182 $us .= " (build host)";
4186 open PI, "<&STDIN" or die $!;
4187 open STDIN, "/dev/null" or die $!;
4188 open PO, ">&STDOUT" or die $!;
4190 open STDOUT, ">&STDERR" or die $!;
4194 ($protovsn) = grep {
4195 $vsnwant =~ m{^(?:.*,)?$_(?:,.*)?$}
4196 } @rpushprotovsn_support;
4198 fail "build host has dgit rpush protocol versions ".
4199 (join ",", @rpushprotovsn_support).
4200 " but invocation host has $vsnwant"
4201 unless defined $protovsn;
4203 responder_send_command("dgit-remote-push-ready $protovsn");
4204 rpush_handle_protovsn_bothends();
4209 sub cmd_remote_push_responder { cmd_remote_push_build_host(); }
4210 # ... for compatibility with proto vsn.1 dgit (just so that user gets
4211 # a good error message)
4213 sub rpush_handle_protovsn_bothends () {
4214 if ($protovsn < 4) {
4215 need_tagformat 'old', "rpush negotiated protocol $protovsn";
4224 my $report = i_child_report();
4225 if (defined $report) {
4226 printdebug "($report)\n";
4227 } elsif ($i_child_pid) {
4228 printdebug "(killing build host child $i_child_pid)\n";
4229 kill 15, $i_child_pid;
4231 if (defined $i_tmp && !defined $initiator_tempdir) {
4233 eval { rmtree $i_tmp; };
4237 END { i_cleanup(); }
4240 my ($base,$selector,@args) = @_;
4241 $selector =~ s/\-/_/g;
4242 { no strict qw(refs); &{"${base}_${selector}"}(@args); }
4249 if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
4257 push @rargs, join ",", @rpushprotovsn_support;
4260 push @rdgit, @ropts;
4261 push @rdgit, qw(remote-push-build-host), (scalar @rargs), @rargs;
4263 my @cmd = (@ssh, $host, shellquote @rdgit);
4266 if (defined $initiator_tempdir) {
4267 rmtree $initiator_tempdir;
4268 mkdir $initiator_tempdir, 0700 or die "$initiator_tempdir: $!";
4269 $i_tmp = $initiator_tempdir;
4273 $i_child_pid = open2(\*RO, \*RI, @cmd);
4275 ($protovsn) = initiator_expect { m/^dgit-remote-push-ready (\S+)/ };
4276 die "$protovsn ?" unless grep { $_ eq $protovsn } @rpushprotovsn_support;
4277 $supplementary_message = '' unless $protovsn >= 3;
4279 fail "rpush negotiated protocol version $protovsn".
4280 " which does not support quilt mode $quilt_mode"
4281 if quiltmode_splitbrain;
4283 rpush_handle_protovsn_bothends();
4285 my ($icmd,$iargs) = initiator_expect {
4286 m/^(\S+)(?: (.*))?$/;
4289 i_method "i_resp", $icmd, $iargs;
4293 sub i_resp_progress ($) {
4295 my $msg = protocol_read_bytes \*RO, $rhs;
4299 sub i_resp_supplementary_message ($) {
4301 $supplementary_message = protocol_read_bytes \*RO, $rhs;
4304 sub i_resp_complete {
4305 my $pid = $i_child_pid;
4306 $i_child_pid = undef; # prevents killing some other process with same pid
4307 printdebug "waiting for build host child $pid...\n";
4308 my $got = waitpid $pid, 0;
4309 die $! unless $got == $pid;
4310 die "build host child failed $?" if $?;
4313 printdebug "all done\n";
4317 sub i_resp_file ($) {
4319 my $localname = i_method "i_localname", $keyword;
4320 my $localpath = "$i_tmp/$localname";
4321 stat_exists $localpath and
4322 badproto \*RO, "file $keyword ($localpath) twice";
4323 protocol_receive_file \*RO, $localpath;
4324 i_method "i_file", $keyword;
4329 sub i_resp_param ($) {
4330 $_[0] =~ m/^(\S+) (.*)$/ or badproto \*RO, "bad param spec";
4334 sub i_resp_previously ($) {
4335 $_[0] =~ m#^(refs/tags/\S+)=(\w+)$#
4336 or badproto \*RO, "bad previously spec";
4337 my $r = system qw(git check-ref-format), $1;
4338 die "bad previously ref spec ($r)" if $r;
4339 $previously{$1} = $2;
4344 sub i_resp_want ($) {
4346 die "$keyword ?" if $i_wanted{$keyword}++;
4347 my @localpaths = i_method "i_want", $keyword;
4348 printdebug "[[ $keyword @localpaths\n";
4349 foreach my $localpath (@localpaths) {
4350 protocol_send_file \*RI, $localpath;
4352 print RI "files-end\n" or die $!;
4355 our ($i_clogp, $i_version, $i_dscfn, $i_changesfn);
4357 sub i_localname_parsed_changelog {
4358 return "remote-changelog.822";
4360 sub i_file_parsed_changelog {
4361 ($i_clogp, $i_version, $i_dscfn) =
4362 push_parse_changelog "$i_tmp/remote-changelog.822";
4363 die if $i_dscfn =~ m#/|^\W#;
4366 sub i_localname_dsc {
4367 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
4372 sub i_localname_changes {
4373 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
4374 $i_changesfn = $i_dscfn;
4375 $i_changesfn =~ s/\.dsc$/_dgit.changes/ or die;
4376 return $i_changesfn;
4378 sub i_file_changes { }
4380 sub i_want_signed_tag {
4381 printdebug Dumper(\%i_param, $i_dscfn);
4382 defined $i_param{'head'} && defined $i_dscfn && defined $i_clogp
4383 && defined $i_param{'csuite'}
4384 or badproto \*RO, "premature desire for signed-tag";
4385 my $head = $i_param{'head'};
4386 die if $head =~ m/[^0-9a-f]/ || $head !~ m/^../;
4388 my $maintview = $i_param{'maint-view'};
4389 die if defined $maintview && $maintview =~ m/[^0-9a-f]/;
4392 if ($protovsn >= 4) {
4393 my $p = $i_param{'tagformat'} // '<undef>';
4395 or badproto \*RO, "tag format mismatch: $p vs. $tagformat";
4398 die unless $i_param{'csuite'} =~ m/^$suite_re$/;
4400 push_parse_dsc $i_dscfn, 'remote dsc', $i_version;
4402 my @tagwants = push_tagwants $i_version, $head, $maintview, "tag";
4405 push_mktags $i_clogp, $i_dscfn,
4406 $i_changesfn, 'remote changes',
4410 sub i_want_signed_dsc_changes {
4411 rename "$i_dscfn.tmp","$i_dscfn" or die "$i_dscfn $!";
4412 sign_changes $i_changesfn;
4413 return ($i_dscfn, $i_changesfn);
4416 #---------- building etc. ----------
4422 #----- `3.0 (quilt)' handling -----
4424 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
4426 sub quiltify_dpkg_commit ($$$;$) {
4427 my ($patchname,$author,$msg, $xinfo) = @_;
4431 my $descfn = ".git/dgit/quilt-description.tmp";
4432 open O, '>', $descfn or die "$descfn: $!";
4433 $msg =~ s/\n+/\n\n/;
4434 print O <<END or die $!;
4436 ${xinfo}Subject: $msg
4443 local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
4444 local $ENV{'VISUAL'} = $ENV{'EDITOR'};
4445 local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
4446 runcmd @dpkgsource, qw(--commit .), $patchname;
4450 sub quiltify_trees_differ ($$;$$$) {
4451 my ($x,$y,$finegrained,$ignorenamesr,$unrepres) = @_;
4452 # returns true iff the two tree objects differ other than in debian/
4453 # with $finegrained,
4454 # returns bitmask 01 - differ in upstream files except .gitignore
4455 # 02 - differ in .gitignore
4456 # if $ignorenamesr is defined, $ingorenamesr->{$fn}
4457 # is set for each modified .gitignore filename $fn
4458 # if $unrepres is defined, array ref to which is appeneded
4459 # a list of unrepresentable changes (removals of upstream files
4462 my @cmd = (@git, qw(diff-tree -z));
4463 push @cmd, qw(--name-only) unless $unrepres;
4464 push @cmd, qw(-r) if $finegrained || $unrepres;
4466 my $diffs= cmdoutput @cmd;
4469 foreach my $f (split /\0/, $diffs) {
4470 if ($unrepres && !@lmodes) {
4471 @lmodes = $f =~ m/^\:(\w+) (\w+) \w+ \w+ / or die "$_ ?";
4474 my ($oldmode,$newmode) = @lmodes;
4477 next if $f =~ m#^debian(?:/.*)?$#s;
4481 die "deleted\n" unless $newmode =~ m/[^0]/;
4482 die "not a plain file\n" unless $newmode =~ m/^10\d{4}$/;
4483 if ($oldmode =~ m/[^0]/) {
4484 die "mode changed\n" if $oldmode ne $newmode;
4486 die "non-default mode\n" unless $newmode =~ m/^100644$/;
4490 local $/="\n"; chomp $@;
4491 push @$unrepres, [ $f, $@ ];
4495 my $isignore = $f =~ m#^(?:.*/)?.gitignore$#s;
4496 $r |= $isignore ? 02 : 01;
4497 $ignorenamesr->{$f}=1 if $ignorenamesr && $isignore;
4499 printdebug "quiltify_trees_differ $x $y => $r\n";
4503 sub quiltify_tree_sentinelfiles ($) {
4504 # lists the `sentinel' files present in the tree
4506 my $r = cmdoutput @git, qw(ls-tree --name-only), $x,
4507 qw(-- debian/rules debian/control);
4512 sub quiltify_splitbrain_needed () {
4513 if (!$split_brain) {
4514 progress "dgit view: changes are required...";
4515 runcmd @git, qw(checkout -q -b dgit-view);
4520 sub quiltify_splitbrain ($$$$$$) {
4521 my ($clogp, $unapplied, $headref, $diffbits,
4522 $editedignores, $cachekey) = @_;
4523 if ($quilt_mode !~ m/gbp|dpm/) {
4524 # treat .gitignore just like any other upstream file
4525 $diffbits = { %$diffbits };
4526 $_ = !!$_ foreach values %$diffbits;
4528 # We would like any commits we generate to be reproducible
4529 my @authline = clogp_authline($clogp);
4530 local $ENV{GIT_COMMITTER_NAME} = $authline[0];
4531 local $ENV{GIT_COMMITTER_EMAIL} = $authline[1];
4532 local $ENV{GIT_COMMITTER_DATE} = $authline[2];
4533 local $ENV{GIT_AUTHOR_NAME} = $authline[0];
4534 local $ENV{GIT_AUTHOR_EMAIL} = $authline[1];
4535 local $ENV{GIT_AUTHOR_DATE} = $authline[2];
4537 if ($quilt_mode =~ m/gbp|unapplied/ &&
4538 ($diffbits->{O2H} & 01)) {
4540 "--quilt=$quilt_mode specified, implying patches-unapplied git tree\n".
4541 " but git tree differs from orig in upstream files.";
4542 if (!stat_exists "debian/patches") {
4544 "\n ... debian/patches is missing; perhaps this is a patch queue branch?";
4548 if ($quilt_mode =~ m/dpm/ &&
4549 ($diffbits->{H2A} & 01)) {
4551 --quilt=$quilt_mode specified, implying patches-applied git tree
4552 but git tree differs from result of applying debian/patches to upstream
4555 if ($quilt_mode =~ m/gbp|unapplied/ &&
4556 ($diffbits->{O2A} & 01)) { # some patches
4557 quiltify_splitbrain_needed();
4558 progress "dgit view: creating patches-applied version using gbp pq";
4559 runcmd shell_cmd 'exec >/dev/null', gbp_pq, qw(import);
4560 # gbp pq import creates a fresh branch; push back to dgit-view
4561 runcmd @git, qw(update-ref refs/heads/dgit-view HEAD);
4562 runcmd @git, qw(checkout -q dgit-view);
4564 if ($quilt_mode =~ m/gbp|dpm/ &&
4565 ($diffbits->{O2A} & 02)) {
4567 --quilt=$quilt_mode specified, implying that HEAD is for use with a
4568 tool which does not create patches for changes to upstream
4569 .gitignores: but, such patches exist in debian/patches.
4572 if (($diffbits->{O2H} & 02) && # user has modified .gitignore
4573 !($diffbits->{O2A} & 02)) { # patches do not change .gitignore
4574 quiltify_splitbrain_needed();
4575 progress "dgit view: creating patch to represent .gitignore changes";
4576 ensuredir "debian/patches";
4577 my $gipatch = "debian/patches/auto-gitignore";
4578 open GIPATCH, ">>", "$gipatch" or die "$gipatch: $!";
4579 stat GIPATCH or die "$gipatch: $!";
4580 fail "$gipatch already exists; but want to create it".
4581 " to record .gitignore changes" if (stat _)[7];
4582 print GIPATCH <<END or die "$gipatch: $!";
4583 Subject: Update .gitignore from Debian packaging branch
4585 The Debian packaging git branch contains these updates to the upstream
4586 .gitignore file(s). This patch is autogenerated, to provide these
4587 updates to users of the official Debian archive view of the package.
4589 [dgit ($our_version) update-gitignore]
4592 close GIPATCH or die "$gipatch: $!";
4593 runcmd shell_cmd "exec >>$gipatch", @git, qw(diff),
4594 $unapplied, $headref, "--", sort keys %$editedignores;
4595 open SERIES, "+>>", "debian/patches/series" or die $!;
4596 defined seek SERIES, -1, 2 or $!==EINVAL or die $!;
4598 defined read SERIES, $newline, 1 or die $!;
4599 print SERIES "\n" or die $! unless $newline eq "\n";
4600 print SERIES "auto-gitignore\n" or die $!;
4601 close SERIES or die $!;
4602 runcmd @git, qw(add -- debian/patches/series), $gipatch;
4604 Commit patch to update .gitignore
4606 [dgit ($our_version) update-gitignore-quilt-fixup]
4610 my $dgitview = git_rev_parse 'HEAD';
4612 changedir '../../../..';
4613 # When we no longer need to support squeeze, use --create-reflog
4615 ensuredir ".git/logs/refs/dgit-intern";
4616 my $makelogfh = new IO::File ".git/logs/refs/$splitbraincache", '>>'
4619 my $oldcache = git_get_ref "refs/$splitbraincache";
4620 if ($oldcache eq $dgitview) {
4621 my $tree = cmdoutput qw(git rev-parse), "$dgitview:";
4622 # git update-ref doesn't always update, in this case. *sigh*
4623 my $dummy = make_commit_text <<END;
4626 author Dgit <dgit\@example.com> 1000000000 +0000
4627 committer Dgit <dgit\@example.com> 1000000000 +0000
4629 Dummy commit - do not use
4631 runcmd @git, qw(update-ref -m), "dgit $our_version - dummy",
4632 "refs/$splitbraincache", $dummy;
4634 runcmd @git, qw(update-ref -m), $cachekey, "refs/$splitbraincache",
4637 changedir '.git/dgit/unpack/work';
4639 my $saved = maybe_split_brain_save $headref, $dgitview, "converted";
4640 progress "dgit view: created ($saved)";
4643 sub quiltify ($$$$) {
4644 my ($clogp,$target,$oldtiptree,$failsuggestion) = @_;
4646 # Quilt patchification algorithm
4648 # We search backwards through the history of the main tree's HEAD
4649 # (T) looking for a start commit S whose tree object is identical
4650 # to to the patch tip tree (ie the tree corresponding to the
4651 # current dpkg-committed patch series). For these purposes
4652 # `identical' disregards anything in debian/ - this wrinkle is
4653 # necessary because dpkg-source treates debian/ specially.
4655 # We can only traverse edges where at most one of the ancestors'
4656 # trees differs (in changes outside in debian/). And we cannot
4657 # handle edges which change .pc/ or debian/patches. To avoid
4658 # going down a rathole we avoid traversing edges which introduce
4659 # debian/rules or debian/control. And we set a limit on the
4660 # number of edges we are willing to look at.
4662 # If we succeed, we walk forwards again. For each traversed edge
4663 # PC (with P parent, C child) (starting with P=S and ending with
4664 # C=T) to we do this:
4666 # - dpkg-source --commit with a patch name and message derived from C
4667 # After traversing PT, we git commit the changes which
4668 # should be contained within debian/patches.
4670 # The search for the path S..T is breadth-first. We maintain a
4671 # todo list containing search nodes. A search node identifies a
4672 # commit, and looks something like this:
4674 # Commit => $git_commit_id,
4675 # Child => $c, # or undef if P=T
4676 # Whynot => $reason_edge_PC_unsuitable, # in @nots only
4677 # Nontrivial => true iff $p..$c has relevant changes
4684 my %considered; # saves being exponential on some weird graphs
4686 my $t_sentinels = quiltify_tree_sentinelfiles $target;
4689 my ($search,$whynot) = @_;
4690 printdebug " search NOT $search->{Commit} $whynot\n";
4691 $search->{Whynot} = $whynot;
4692 push @nots, $search;
4693 no warnings qw(exiting);
4702 my $c = shift @todo;
4703 next if $considered{$c->{Commit}}++;
4705 $not->($c, "maximum search space exceeded") if --$max_work <= 0;
4707 printdebug "quiltify investigate $c->{Commit}\n";
4710 if (!quiltify_trees_differ $c->{Commit}, $oldtiptree) {
4711 printdebug " search finished hooray!\n";
4716 if ($quilt_mode eq 'nofix') {
4717 fail "quilt fixup required but quilt mode is \`nofix'\n".
4718 "HEAD commit $c->{Commit} differs from tree implied by ".
4719 " debian/patches (tree object $oldtiptree)";
4721 if ($quilt_mode eq 'smash') {
4722 printdebug " search quitting smash\n";
4726 my $c_sentinels = quiltify_tree_sentinelfiles $c->{Commit};
4727 $not->($c, "has $c_sentinels not $t_sentinels")
4728 if $c_sentinels ne $t_sentinels;
4730 my $commitdata = cmdoutput @git, qw(cat-file commit), $c->{Commit};
4731 $commitdata =~ m/\n\n/;
4733 my @parents = ($commitdata =~ m/^parent (\w+)$/gm);
4734 @parents = map { { Commit => $_, Child => $c } } @parents;
4736 $not->($c, "root commit") if !@parents;
4738 foreach my $p (@parents) {
4739 $p->{Nontrivial}= quiltify_trees_differ $p->{Commit},$c->{Commit};
4741 my $ndiffers = grep { $_->{Nontrivial} } @parents;
4742 $not->($c, "merge ($ndiffers nontrivial parents)") if $ndiffers > 1;
4744 foreach my $p (@parents) {
4745 printdebug "considering C=$c->{Commit} P=$p->{Commit}\n";
4747 my @cmd= (@git, qw(diff-tree -r --name-only),
4748 $p->{Commit},$c->{Commit}, qw(-- debian/patches .pc));
4749 my $patchstackchange = cmdoutput @cmd;
4750 if (length $patchstackchange) {
4751 $patchstackchange =~ s/\n/,/g;
4752 $not->($p, "changed $patchstackchange");
4755 printdebug " search queue P=$p->{Commit} ",
4756 ($p->{Nontrivial} ? "NT" : "triv"),"\n";
4762 printdebug "quiltify want to smash\n";
4765 my $x = $_[0]{Commit};
4766 $x =~ s/(.*?[0-9a-z]{8})[0-9a-z]*$/$1/;
4769 my $reportnot = sub {
4771 my $s = $abbrev->($notp);
4772 my $c = $notp->{Child};
4773 $s .= "..".$abbrev->($c) if $c;
4774 $s .= ": ".$notp->{Whynot};
4777 if ($quilt_mode eq 'linear') {
4778 print STDERR "$us: quilt fixup cannot be linear. Stopped at:\n";
4779 foreach my $notp (@nots) {
4780 print STDERR "$us: ", $reportnot->($notp), "\n";
4782 print STDERR "$us: $_\n" foreach @$failsuggestion;
4783 fail "quilt fixup naive history linearisation failed.\n".
4784 "Use dpkg-source --commit by hand; or, --quilt=smash for one ugly patch";
4785 } elsif ($quilt_mode eq 'smash') {
4786 } elsif ($quilt_mode eq 'auto') {
4787 progress "quilt fixup cannot be linear, smashing...";
4789 die "$quilt_mode ?";
4792 my $time = $ENV{'GIT_COMMITTER_DATE'} || time;
4793 $time =~ s/\s.*//; # trim timezone from GIT_COMMITTER_DATE
4795 my $msg = cmdoutput @git, qw(log), "-n$ncommits";
4797 quiltify_dpkg_commit "auto-$version-$target-$time",
4798 (getfield $clogp, 'Maintainer'),
4799 "Automatically generated patch ($clogp->{Version})\n".
4800 "Last (up to) $ncommits git changes, FYI:\n\n". $msg;
4804 progress "quiltify linearisation planning successful, executing...";
4806 for (my $p = $sref_S;
4807 my $c = $p->{Child};
4809 printdebug "quiltify traverse $p->{Commit}..$c->{Commit}\n";
4810 next unless $p->{Nontrivial};
4812 my $cc = $c->{Commit};
4814 my $commitdata = cmdoutput @git, qw(cat-file commit), $cc;
4815 $commitdata =~ m/\n\n/ or die "$c ?";
4818 $commitdata =~ m/^author (.*) \d+ [-+0-9]+$/m or die "$cc ?";
4821 my $commitdate = cmdoutput
4822 @git, qw(log -n1 --pretty=format:%aD), $cc;
4824 $msg =~ s/^(.*)\n*/$1\n/ or die "$cc $msg ?";
4826 my $strip_nls = sub { $msg =~ s/\n+$//; $msg .= "\n"; };
4833 my $gbp_check_suitable = sub {
4838 die "contains unexpected slashes\n" if m{//} || m{/$};
4839 die "contains leading punctuation\n" if m{^\W} || m{/\W};
4840 die "contains bad character(s)\n" if m{[^-a-z0-9_.+=~/]}i;
4841 die "too long" if length > 200;
4843 return $_ unless $@;
4844 print STDERR "quiltifying commit $cc:".
4845 " ignoring/dropping Gbp-Pq $what: $@";
4849 if ($msg =~ s/^ (?: gbp(?:-pq)? : \s* name \s+ |
4851 (\S+) \s* \n //ixm) {
4852 $patchname = $gbp_check_suitable->($1, 'Name');
4854 if ($msg =~ s/^ (?: gbp(?:-pq)? : \s* topic \s+ |
4856 (\S+) \s* \n //ixm) {
4857 $patchdir = $gbp_check_suitable->($1, 'Topic');
4862 if (!defined $patchname) {
4863 $patchname = $title;
4864 $patchname =~ s/[.:]$//;
4867 my $converter = new Text::Iconv qw(UTF-8 ASCII//TRANSLIT);
4868 my $translitname = $converter->convert($patchname);
4869 die unless defined $translitname;
4870 $patchname = $translitname;
4873 "dgit: patch title transliteration error: $@"
4875 $patchname =~ y/ A-Z/-a-z/;
4876 $patchname =~ y/-a-z0-9_.+=~//cd;
4877 $patchname =~ s/^\W/x-$&/;
4878 $patchname = substr($patchname,0,40);
4880 if (!defined $patchdir) {
4883 if (length $patchdir) {
4884 $patchname = "$patchdir/$patchname";
4886 if ($patchname =~ m{^(.*)/}) {
4887 mkpath "debian/patches/$1";
4892 stat "debian/patches/$patchname$index";
4894 $!==ENOENT or die "$patchname$index $!";
4896 runcmd @git, qw(checkout -q), $cc;
4898 # We use the tip's changelog so that dpkg-source doesn't
4899 # produce complaining messages from dpkg-parsechangelog. None
4900 # of the information dpkg-source gets from the changelog is
4901 # actually relevant - it gets put into the original message
4902 # which dpkg-source provides our stunt editor, and then
4904 runcmd @git, qw(checkout -q), $target, qw(debian/changelog);
4906 quiltify_dpkg_commit "$patchname$index", $author, $msg,
4907 "Date: $commitdate\n".
4908 "X-Dgit-Generated: $clogp->{Version} $cc\n";
4910 runcmd @git, qw(checkout -q), $cc, qw(debian/changelog);
4913 runcmd @git, qw(checkout -q master);
4916 sub build_maybe_quilt_fixup () {
4917 my ($format,$fopts) = get_source_format;
4918 return unless madformat_wantfixup $format;
4921 check_for_vendor_patches();
4923 if (quiltmode_splitbrain) {
4924 fail <<END unless access_cfg_tagformats_can_splitbrain;
4925 quilt mode $quilt_mode requires split view so server needs to support
4926 both "new" and "maint" tag formats, but config says it doesn't.
4930 my $clogp = parsechangelog();
4931 my $headref = git_rev_parse('HEAD');
4936 my $upstreamversion = upstreamversion $version;
4938 if ($fopts->{'single-debian-patch'}) {
4939 quilt_fixup_singlepatch($clogp, $headref, $upstreamversion);
4941 quilt_fixup_multipatch($clogp, $headref, $upstreamversion);
4944 die 'bug' if $split_brain && !$need_split_build_invocation;
4946 changedir '../../../..';
4947 runcmd_ordryrun_local
4948 @git, qw(pull --ff-only -q .git/dgit/unpack/work master);
4951 sub quilt_fixup_mkwork ($) {
4954 mkdir "work" or die $!;
4956 mktree_in_ud_here();
4957 runcmd @git, qw(reset -q --hard), $headref;
4960 sub quilt_fixup_linkorigs ($$) {
4961 my ($upstreamversion, $fn) = @_;
4962 # calls $fn->($leafname);
4964 foreach my $f (<../../../../*>) { #/){
4965 my $b=$f; $b =~ s{.*/}{};
4967 local ($debuglevel) = $debuglevel-1;
4968 printdebug "QF linkorigs $b, $f ?\n";
4970 next unless is_orig_file_of_vsn $b, $upstreamversion;
4971 printdebug "QF linkorigs $b, $f Y\n";
4972 link_ltarget $f, $b or die "$b $!";
4977 sub quilt_fixup_delete_pc () {
4978 runcmd @git, qw(rm -rqf .pc);
4980 Commit removal of .pc (quilt series tracking data)
4982 [dgit ($our_version) upgrade quilt-remove-pc]
4986 sub quilt_fixup_singlepatch ($$$) {
4987 my ($clogp, $headref, $upstreamversion) = @_;
4989 progress "starting quiltify (single-debian-patch)";
4991 # dpkg-source --commit generates new patches even if
4992 # single-debian-patch is in debian/source/options. In order to
4993 # get it to generate debian/patches/debian-changes, it is
4994 # necessary to build the source package.
4996 quilt_fixup_linkorigs($upstreamversion, sub { });
4997 quilt_fixup_mkwork($headref);
4999 rmtree("debian/patches");
5001 runcmd @dpkgsource, qw(-b .);
5003 runcmd @dpkgsource, qw(-x), (srcfn $version, ".dsc");
5004 rename srcfn("$upstreamversion", "/debian/patches"),
5005 "work/debian/patches";
5008 commit_quilty_patch();
5011 sub quilt_make_fake_dsc ($) {
5012 my ($upstreamversion) = @_;
5014 my $fakeversion="$upstreamversion-~~DGITFAKE";
5016 my $fakedsc=new IO::File 'fake.dsc', '>' or die $!;
5017 print $fakedsc <<END or die $!;
5020 Version: $fakeversion
5024 my $dscaddfile=sub {
5027 my $md = new Digest::MD5;
5029 my $fh = new IO::File $b, '<' or die "$b $!";
5034 print $fakedsc " ".$md->hexdigest." $size $b\n" or die $!;
5037 quilt_fixup_linkorigs($upstreamversion, $dscaddfile);
5039 my @files=qw(debian/source/format debian/rules
5040 debian/control debian/changelog);
5041 foreach my $maybe (qw(debian/patches debian/source/options
5042 debian/tests/control)) {
5043 next unless stat_exists "../../../$maybe";
5044 push @files, $maybe;
5047 my $debtar= srcfn $fakeversion,'.debian.tar.gz';
5048 runcmd qw(env GZIP=-1n tar -zcf), "./$debtar", qw(-C ../../..), @files;
5050 $dscaddfile->($debtar);
5051 close $fakedsc or die $!;
5054 sub quilt_check_splitbrain_cache ($$) {
5055 my ($headref, $upstreamversion) = @_;
5056 # Called only if we are in (potentially) split brain mode.
5058 # Computes the cache key and looks in the cache.
5059 # Returns ($dgit_view_commitid, $cachekey) or (undef, $cachekey)
5061 my $splitbrain_cachekey;
5064 "dgit: split brain (separate dgit view) may be needed (--quilt=$quilt_mode).";
5065 # we look in the reflog of dgit-intern/quilt-cache
5066 # we look for an entry whose message is the key for the cache lookup
5067 my @cachekey = (qw(dgit), $our_version);
5068 push @cachekey, $upstreamversion;
5069 push @cachekey, $quilt_mode;
5070 push @cachekey, $headref;
5072 push @cachekey, hashfile('fake.dsc');
5074 my $srcshash = Digest::SHA->new(256);
5075 my %sfs = ( %INC, '$0(dgit)' => $0 );
5076 foreach my $sfk (sort keys %sfs) {
5077 next unless $sfk =~ m/^\$0\b/ || $sfk =~ m{^Debian/Dgit\b};
5078 $srcshash->add($sfk," ");
5079 $srcshash->add(hashfile($sfs{$sfk}));
5080 $srcshash->add("\n");
5082 push @cachekey, $srcshash->hexdigest();
5083 $splitbrain_cachekey = "@cachekey";
5085 my @cmd = (@git, qw(log -g), '--pretty=format:%H %gs',
5087 printdebug "splitbrain cachekey $splitbrain_cachekey\n";
5088 debugcmd "|(probably)",@cmd;
5089 my $child = open GC, "-|"; defined $child or die $!;
5091 chdir '../../..' or die $!;
5092 if (!stat ".git/logs/refs/$splitbraincache") {
5093 $! == ENOENT or die $!;
5094 printdebug ">(no reflog)\n";
5101 printdebug ">| ", $_, "\n" if $debuglevel > 1;
5102 next unless m/^(\w+) (\S.*\S)$/ && $2 eq $splitbrain_cachekey;
5105 quilt_fixup_mkwork($headref);
5106 my $saved = maybe_split_brain_save $headref, $cachehit, "cache-hit";
5107 if ($cachehit ne $headref) {
5108 progress "dgit view: found cached ($saved)";
5109 runcmd @git, qw(checkout -q -b dgit-view), $cachehit;
5111 return ($cachehit, $splitbrain_cachekey);
5113 progress "dgit view: found cached, no changes required";
5114 return ($headref, $splitbrain_cachekey);
5116 die $! if GC->error;
5117 failedcmd unless close GC;
5119 printdebug "splitbrain cache miss\n";
5120 return (undef, $splitbrain_cachekey);
5123 sub quilt_fixup_multipatch ($$$) {
5124 my ($clogp, $headref, $upstreamversion) = @_;
5126 progress "examining quilt state (multiple patches, $quilt_mode mode)";
5129 # - honour any existing .pc in case it has any strangeness
5130 # - determine the git commit corresponding to the tip of
5131 # the patch stack (if there is one)
5132 # - if there is such a git commit, convert each subsequent
5133 # git commit into a quilt patch with dpkg-source --commit
5134 # - otherwise convert all the differences in the tree into
5135 # a single git commit
5139 # Our git tree doesn't necessarily contain .pc. (Some versions of
5140 # dgit would include the .pc in the git tree.) If there isn't
5141 # one, we need to generate one by unpacking the patches that we
5144 # We first look for a .pc in the git tree. If there is one, we
5145 # will use it. (This is not the normal case.)
5147 # Otherwise need to regenerate .pc so that dpkg-source --commit
5148 # can work. We do this as follows:
5149 # 1. Collect all relevant .orig from parent directory
5150 # 2. Generate a debian.tar.gz out of
5151 # debian/{patches,rules,source/format,source/options}
5152 # 3. Generate a fake .dsc containing just these fields:
5153 # Format Source Version Files
5154 # 4. Extract the fake .dsc
5155 # Now the fake .dsc has a .pc directory.
5156 # (In fact we do this in every case, because in future we will
5157 # want to search for a good base commit for generating patches.)
5159 # Then we can actually do the dpkg-source --commit
5160 # 1. Make a new working tree with the same object
5161 # store as our main tree and check out the main
5163 # 2. Copy .pc from the fake's extraction, if necessary
5164 # 3. Run dpkg-source --commit
5165 # 4. If the result has changes to debian/, then
5166 # - git add them them
5167 # - git add .pc if we had a .pc in-tree
5169 # 5. If we had a .pc in-tree, delete it, and git commit
5170 # 6. Back in the main tree, fast forward to the new HEAD
5172 # Another situation we may have to cope with is gbp-style
5173 # patches-unapplied trees.
5175 # We would want to detect these, so we know to escape into
5176 # quilt_fixup_gbp. However, this is in general not possible.
5177 # Consider a package with a one patch which the dgit user reverts
5178 # (with git revert or the moral equivalent).
5180 # That is indistinguishable in contents from a patches-unapplied
5181 # tree. And looking at the history to distinguish them is not
5182 # useful because the user might have made a confusing-looking git
5183 # history structure (which ought to produce an error if dgit can't
5184 # cope, not a silent reintroduction of an unwanted patch).
5186 # So gbp users will have to pass an option. But we can usually
5187 # detect their failure to do so: if the tree is not a clean
5188 # patches-applied tree, quilt linearisation fails, but the tree
5189 # _is_ a clean patches-unapplied tree, we can suggest that maybe
5190 # they want --quilt=unapplied.
5192 # To help detect this, when we are extracting the fake dsc, we
5193 # first extract it with --skip-patches, and then apply the patches
5194 # afterwards with dpkg-source --before-build. That lets us save a
5195 # tree object corresponding to .origs.
5197 my $splitbrain_cachekey;
5199 quilt_make_fake_dsc($upstreamversion);
5201 if (quiltmode_splitbrain()) {
5203 ($cachehit, $splitbrain_cachekey) =
5204 quilt_check_splitbrain_cache($headref, $upstreamversion);
5205 return if $cachehit;
5209 'exec dpkg-source --no-check --skip-patches -x fake.dsc >/dev/null';
5211 my $fakexdir= $package.'-'.(stripepoch $upstreamversion);
5212 rename $fakexdir, "fake" or die "$fakexdir $!";
5216 remove_stray_gits("source package");
5217 mktree_in_ud_here();
5221 my $unapplied=git_add_write_tree();
5222 printdebug "fake orig tree object $unapplied\n";
5226 my @bbcmd = (qw(sh -ec), 'exec dpkg-source --before-build . >/dev/null');
5228 if (system @bbcmd) {
5229 failedcmd @bbcmd if $? < 0;
5231 failed to apply your git tree's patch stack (from debian/patches/) to
5232 the corresponding upstream tarball(s). Your source tree and .orig
5233 are probably too inconsistent. dgit can only fix up certain kinds of
5234 anomaly (depending on the quilt mode). See --quilt= in dgit(1).
5240 quilt_fixup_mkwork($headref);
5243 if (stat_exists ".pc") {
5245 progress "Tree already contains .pc - will use it then delete it.";
5248 rename '../fake/.pc','.pc' or die $!;
5251 changedir '../fake';
5253 my $oldtiptree=git_add_write_tree();
5254 printdebug "fake o+d/p tree object $unapplied\n";
5255 changedir '../work';
5258 # We calculate some guesswork now about what kind of tree this might
5259 # be. This is mostly for error reporting.
5265 # O = orig, without patches applied
5266 # A = "applied", ie orig with H's debian/patches applied
5267 O2H => quiltify_trees_differ($unapplied,$headref, 1,
5268 \%editedignores, \@unrepres),
5269 H2A => quiltify_trees_differ($headref, $oldtiptree,1),
5270 O2A => quiltify_trees_differ($unapplied,$oldtiptree,1),
5274 foreach my $b (qw(01 02)) {
5275 foreach my $v (qw(O2H O2A H2A)) {
5276 push @dl, ($diffbits->{$v} & $b) ? '##' : '==';
5279 printdebug "differences \@dl @dl.\n";
5282 "$us: base trees orig=%.20s o+d/p=%.20s",
5283 $unapplied, $oldtiptree;
5285 "$us: quilt differences: src: %s orig %s gitignores: %s orig %s\n".
5286 "$us: quilt differences: HEAD %s o+d/p HEAD %s o+d/p",
5287 $dl[0], $dl[1], $dl[3], $dl[4],
5291 print STDERR "dgit: cannot represent change: $_->[1]: $_->[0]\n"
5293 forceable_fail [qw(unrepresentable)], <<END;
5294 HEAD has changes to .orig[s] which are not representable by `3.0 (quilt)'
5299 if (!($diffbits->{O2H} & $diffbits->{O2A})) {
5300 push @failsuggestion, "This might be a patches-unapplied branch.";
5301 } elsif (!($diffbits->{H2A} & $diffbits->{O2A})) {
5302 push @failsuggestion, "This might be a patches-applied branch.";
5304 push @failsuggestion, "Maybe you need to specify one of".
5305 " --[quilt=]gbp --[quilt=]dpm --quilt=unapplied ?";
5307 if (quiltmode_splitbrain()) {
5308 quiltify_splitbrain($clogp, $unapplied, $headref,
5309 $diffbits, \%editedignores,
5310 $splitbrain_cachekey);
5314 progress "starting quiltify (multiple patches, $quilt_mode mode)";
5315 quiltify($clogp,$headref,$oldtiptree,\@failsuggestion);
5317 if (!open P, '>>', ".pc/applied-patches") {
5318 $!==&ENOENT or die $!;
5323 commit_quilty_patch();
5325 if ($mustdeletepc) {
5326 quilt_fixup_delete_pc();
5330 sub quilt_fixup_editor () {
5331 my $descfn = $ENV{$fakeeditorenv};
5332 my $editing = $ARGV[$#ARGV];
5333 open I1, '<', $descfn or die "$descfn: $!";
5334 open I2, '<', $editing or die "$editing: $!";
5335 unlink $editing or die "$editing: $!";
5336 open O, '>', $editing or die "$editing: $!";
5337 while (<I1>) { print O or die $!; } I1->error and die $!;
5340 $copying ||= m/^\-\-\- /;
5341 next unless $copying;
5344 I2->error and die $!;
5349 sub maybe_apply_patches_dirtily () {
5350 return unless $quilt_mode =~ m/gbp|unapplied/;
5351 print STDERR <<END or die $!;
5353 dgit: Building, or cleaning with rules target, in patches-unapplied tree.
5354 dgit: Have to apply the patches - making the tree dirty.
5355 dgit: (Consider specifying --clean=git and (or) using dgit sbuild.)
5358 $patches_applied_dirtily = 01;
5359 $patches_applied_dirtily |= 02 unless stat_exists '.pc';
5360 runcmd qw(dpkg-source --before-build .);
5363 sub maybe_unapply_patches_again () {
5364 progress "dgit: Unapplying patches again to tidy up the tree."
5365 if $patches_applied_dirtily;
5366 runcmd qw(dpkg-source --after-build .)
5367 if $patches_applied_dirtily & 01;
5369 if $patches_applied_dirtily & 02;
5370 $patches_applied_dirtily = 0;
5373 #----- other building -----
5375 our $clean_using_builder;
5376 # ^ tree is to be cleaned by dpkg-source's builtin idea that it should
5377 # clean the tree before building (perhaps invoked indirectly by
5378 # whatever we are using to run the build), rather than separately
5379 # and explicitly by us.
5382 return if $clean_using_builder;
5383 if ($cleanmode eq 'dpkg-source') {
5384 maybe_apply_patches_dirtily();
5385 runcmd_ordryrun_local @dpkgbuildpackage, qw(-T clean);
5386 } elsif ($cleanmode eq 'dpkg-source-d') {
5387 maybe_apply_patches_dirtily();
5388 runcmd_ordryrun_local @dpkgbuildpackage, qw(-d -T clean);
5389 } elsif ($cleanmode eq 'git') {
5390 runcmd_ordryrun_local @git, qw(clean -xdf);
5391 } elsif ($cleanmode eq 'git-ff') {
5392 runcmd_ordryrun_local @git, qw(clean -xdff);
5393 } elsif ($cleanmode eq 'check') {
5394 my $leftovers = cmdoutput @git, qw(clean -xdn);
5395 if (length $leftovers) {
5396 print STDERR $leftovers, "\n" or die $!;
5397 fail "tree contains uncommitted files and --clean=check specified";
5399 } elsif ($cleanmode eq 'none') {
5406 badusage "clean takes no additional arguments" if @ARGV;
5409 maybe_unapply_patches_again();
5412 sub build_prep_early () {
5413 our $build_prep_early_done //= 0;
5414 return if $build_prep_early_done++;
5416 badusage "-p is not allowed when building" if defined $package;
5417 my $clogp = parsechangelog();
5418 $isuite = getfield $clogp, 'Distribution';
5419 $package = getfield $clogp, 'Source';
5420 $version = getfield $clogp, 'Version';
5427 build_maybe_quilt_fixup();
5429 my $pat = changespat $version;
5430 foreach my $f (glob "$buildproductsdir/$pat") {
5432 unlink $f or fail "remove old changes file $f: $!";
5434 progress "would remove $f";
5440 sub changesopts_initial () {
5441 my @opts =@changesopts[1..$#changesopts];
5444 sub changesopts_version () {
5445 if (!defined $changes_since_version) {
5446 my @vsns = archive_query('archive_query');
5447 my @quirk = access_quirk();
5448 if ($quirk[0] eq 'backports') {
5449 local $isuite = $quirk[2];
5451 canonicalise_suite();
5452 push @vsns, archive_query('archive_query');
5455 @vsns = map { $_->[0] } @vsns;
5456 @vsns = sort { -version_compare($a, $b) } @vsns;
5457 $changes_since_version = $vsns[0];
5458 progress "changelog will contain changes since $vsns[0]";
5460 $changes_since_version = '_';
5461 progress "package seems new, not specifying -v<version>";
5464 if ($changes_since_version ne '_') {
5465 return ("-v$changes_since_version");
5471 sub changesopts () {
5472 return (changesopts_initial(), changesopts_version());
5475 sub massage_dbp_args ($;$) {
5476 my ($cmd,$xargs) = @_;
5479 # - if we're going to split the source build out so we can
5480 # do strange things to it, massage the arguments to dpkg-buildpackage
5481 # so that the main build doessn't build source (or add an argument
5482 # to stop it building source by default).
5484 # - add -nc to stop dpkg-source cleaning the source tree,
5485 # unless we're not doing a split build and want dpkg-source
5486 # as cleanmode, in which case we can do nothing
5489 # 0 - source will NOT need to be built separately by caller
5490 # +1 - source will need to be built separately by caller
5491 # +2 - source will need to be built separately by caller AND
5492 # dpkg-buildpackage should not in fact be run at all!
5493 debugcmd '#massaging#', @$cmd if $debuglevel>1;
5494 #print STDERR "MASS0 ",Dumper($cmd, $xargs, $need_split_build_invocation);
5495 if ($cleanmode eq 'dpkg-source' && !$need_split_build_invocation) {
5496 $clean_using_builder = 1;
5499 # -nc has the side effect of specifying -b if nothing else specified
5500 # and some combinations of -S, -b, et al, are errors, rather than
5501 # later simply overriding earlie. So we need to:
5502 # - search the command line for these options
5503 # - pick the last one
5504 # - perhaps add our own as a default
5505 # - perhaps adjust it to the corresponding non-source-building version
5507 foreach my $l ($cmd, $xargs) {
5509 @$l = grep { !(m/^-[SgGFABb]$/s and $dmode=$_) } @$l;
5512 #print STDERR "MASS1 ",Dumper($cmd, $xargs, $dmode);
5514 if ($need_split_build_invocation) {
5515 printdebug "massage split $dmode.\n";
5516 $r = $dmode =~ m/[S]/ ? +2 :
5517 $dmode =~ y/gGF/ABb/ ? +1 :
5518 $dmode =~ m/[ABb]/ ? 0 :
5521 printdebug "massage done $r $dmode.\n";
5523 #print STDERR "MASS2 ",Dumper($cmd, $xargs, $r);
5529 my $wasdir = must_getcwd();
5535 sub postbuild_mergechanges ($) { # must run with CWD=.. (eg in in_parent)
5536 my ($msg_if_onlyone) = @_;
5537 # If there is only one .changes file, fail with $msg_if_onlyone,
5538 # or if that is undef, be a no-op.
5539 # Returns the changes file to report to the user.
5540 my $pat = changespat $version;
5541 my @changesfiles = glob $pat;
5542 @changesfiles = sort {
5543 ($b =~ m/_source\.changes$/ <=> $a =~ m/_source\.changes$/)
5547 if (@changesfiles==1) {
5548 fail <<END.$msg_if_onlyone if defined $msg_if_onlyone;
5549 only one changes file from build (@changesfiles)
5551 $result = $changesfiles[0];
5552 } elsif (@changesfiles==2) {
5553 my $binchanges = parsecontrol($changesfiles[1], "binary changes file");
5554 foreach my $l (split /\n/, getfield $binchanges, 'Files') {
5555 fail "$l found in binaries changes file $binchanges"
5558 runcmd_ordryrun_local @mergechanges, @changesfiles;
5559 my $multichanges = changespat $version,'multi';
5561 stat_exists $multichanges or fail "$multichanges: $!";
5562 foreach my $cf (glob $pat) {
5563 next if $cf eq $multichanges;
5564 rename "$cf", "$cf.inmulti" or fail "$cf\{,.inmulti}: $!";
5567 $result = $multichanges;
5569 fail "wrong number of different changes files (@changesfiles)";
5571 printdone "build successful, results in $result\n" or die $!;
5574 sub midbuild_checkchanges () {
5575 my $pat = changespat $version;
5576 return if $rmchanges;
5577 my @unwanted = map { s#^\.\./##; $_; } glob "../$pat";
5578 @unwanted = grep { $_ ne changespat $version,'source' } @unwanted;
5580 changes files other than source matching $pat already present; building would result in ambiguity about the intended results.
5581 Suggest you delete @unwanted.
5586 sub midbuild_checkchanges_vanilla ($) {
5588 midbuild_checkchanges() if $wantsrc == 1;
5591 sub postbuild_mergechanges_vanilla ($) {
5593 if ($wantsrc == 1) {
5595 postbuild_mergechanges(undef);
5598 printdone "build successful\n";
5603 my @dbp = (@dpkgbuildpackage, qw(-us -uc), changesopts_initial(), @ARGV);
5604 my $wantsrc = massage_dbp_args \@dbp;
5607 midbuild_checkchanges_vanilla $wantsrc;
5612 push @dbp, changesopts_version();
5613 maybe_apply_patches_dirtily();
5614 runcmd_ordryrun_local @dbp;
5616 maybe_unapply_patches_again();
5617 postbuild_mergechanges_vanilla $wantsrc;
5621 $quilt_mode //= 'gbp';
5627 # gbp can make .origs out of thin air. In my tests it does this
5628 # even for a 1.0 format package, with no origs present. So I
5629 # guess it keys off just the version number. We don't know
5630 # exactly what .origs ought to exist, but let's assume that we
5631 # should run gbp if: the version has an upstream part and the main
5633 my $upstreamversion = upstreamversion $version;
5634 my $origfnpat = srcfn $upstreamversion, '.orig.tar.*';
5635 my $gbp_make_orig = $version =~ m/-/ && !(() = glob "../$origfnpat");
5637 if ($gbp_make_orig) {
5639 $cleanmode = 'none'; # don't do it again
5640 $need_split_build_invocation = 1;
5643 my @dbp = @dpkgbuildpackage;
5645 my $wantsrc = massage_dbp_args \@dbp, \@ARGV;
5647 if (!length $gbp_build[0]) {
5648 if (length executable_on_path('git-buildpackage')) {
5649 $gbp_build[0] = qw(git-buildpackage);
5651 $gbp_build[0] = 'gbp buildpackage';
5654 my @cmd = opts_opt_multi_cmd @gbp_build;
5656 push @cmd, (qw(-us -uc --git-no-sign-tags), "--git-builder=@dbp");
5658 if ($gbp_make_orig) {
5659 ensuredir '.git/dgit';
5660 my $ok = '.git/dgit/origs-gen-ok';
5661 unlink $ok or $!==&ENOENT or die $!;
5662 my @origs_cmd = @cmd;
5663 push @origs_cmd, qw(--git-cleaner=true);
5664 push @origs_cmd, "--git-prebuild=touch $ok .git/dgit/no-such-dir/ok";
5665 push @origs_cmd, @ARGV;
5667 debugcmd @origs_cmd;
5669 do { local $!; stat_exists $ok; }
5670 or failedcmd @origs_cmd;
5672 dryrun_report @origs_cmd;
5678 midbuild_checkchanges_vanilla $wantsrc;
5680 if (!$clean_using_builder) {
5681 push @cmd, '--git-cleaner=true';
5685 maybe_unapply_patches_again();
5687 push @cmd, changesopts();
5688 runcmd_ordryrun_local @cmd, @ARGV;
5690 postbuild_mergechanges_vanilla $wantsrc;
5692 sub cmd_git_build { cmd_gbp_build(); } # compatibility with <= 1.0
5695 my $our_cleanmode = $cleanmode;
5696 if ($need_split_build_invocation) {
5697 # Pretend that clean is being done some other way. This
5698 # forces us not to try to use dpkg-buildpackage to clean and
5699 # build source all in one go; and instead we run dpkg-source
5700 # (and build_prep() will do the clean since $clean_using_builder
5702 $our_cleanmode = 'ELSEWHERE';
5704 if ($our_cleanmode =~ m/^dpkg-source/) {
5705 # dpkg-source invocation (below) will clean, so build_prep shouldn't
5706 $clean_using_builder = 1;
5709 $sourcechanges = changespat $version,'source';
5711 unlink "../$sourcechanges" or $!==ENOENT
5712 or fail "remove $sourcechanges: $!";
5714 $dscfn = dscfn($version);
5715 if ($our_cleanmode eq 'dpkg-source') {
5716 maybe_apply_patches_dirtily();
5717 runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc -S),
5719 } elsif ($our_cleanmode eq 'dpkg-source-d') {
5720 maybe_apply_patches_dirtily();
5721 runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc -S -d),
5724 my @cmd = (@dpkgsource, qw(-b --));
5727 runcmd_ordryrun_local @cmd, "work";
5728 my @udfiles = <${package}_*>;
5729 changedir "../../..";
5730 foreach my $f (@udfiles) {
5731 printdebug "source copy, found $f\n";
5734 ($f =~ m/\.debian\.tar(?:\.\w+)$/ &&
5735 $f eq srcfn($version, $&));
5736 printdebug "source copy, found $f - renaming\n";
5737 rename "$ud/$f", "../$f" or $!==ENOENT
5738 or fail "put in place new source file ($f): $!";
5741 my $pwd = must_getcwd();
5742 my $leafdir = basename $pwd;
5744 runcmd_ordryrun_local @cmd, $leafdir;
5747 runcmd_ordryrun_local qw(sh -ec),
5748 'exec >$1; shift; exec "$@"','x',
5749 "../$sourcechanges",
5750 @dpkggenchanges, qw(-S), changesopts();
5754 sub cmd_build_source {
5755 badusage "build-source takes no additional arguments" if @ARGV;
5757 maybe_unapply_patches_again();
5758 printdone "source built, results in $dscfn and $sourcechanges";
5763 midbuild_checkchanges();
5766 stat_exists $dscfn or fail "$dscfn (in parent directory): $!";
5767 stat_exists $sourcechanges
5768 or fail "$sourcechanges (in parent directory): $!";
5770 runcmd_ordryrun_local @sbuild, qw(-d), $isuite, @ARGV, $dscfn;
5772 maybe_unapply_patches_again();
5774 postbuild_mergechanges(<<END);
5775 perhaps you need to pass -A ? (sbuild's default is to build only
5776 arch-specific binaries; dgit 1.4 used to override that.)
5781 sub cmd_quilt_fixup {
5782 badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
5783 my $clogp = parsechangelog();
5784 $version = getfield $clogp, 'Version';
5785 $package = getfield $clogp, 'Source';
5788 build_maybe_quilt_fixup();
5791 sub cmd_import_dsc {
5795 last unless $ARGV[0] =~ m/^-/;
5798 if (m/^--require-valid-signature$/) {
5801 badusage "unknown dgit import-dsc sub-option \`$_'";
5805 badusage "usage: dgit import-dsc .../PATH/TO/.DSC BRANCH" unless @ARGV==2;
5806 my ($dscfn, $dstbranch) = @ARGV;
5808 badusage "dry run makes no sense with import-dsc" unless act_local();
5810 my $force = $dstbranch =~ s/^\+// ? +1 :
5811 $dstbranch =~ s/^\.\.// ? -1 :
5813 my $info = $force ? " $&" : '';
5814 $info = "$dscfn$info";
5816 my $specbranch = $dstbranch;
5817 $dstbranch = "refs/heads/$dstbranch" unless $dstbranch =~ m#^refs/#;
5818 $dstbranch = cmdoutput @git, qw(check-ref-format --normalize), $dstbranch;
5820 my @symcmd = (@git, qw(symbolic-ref -q HEAD));
5821 my $chead = cmdoutput_errok @symcmd;
5822 defined $chead or $?==256 or failedcmd @symcmd;
5824 fail "$dstbranch is checked out - will not update it"
5825 if defined $chead and $chead eq $dstbranch;
5827 my $oldhash = git_get_ref $dstbranch;
5829 open D, "<", $dscfn or fail "open import .dsc ($dscfn): $!";
5830 $dscdata = do { local $/ = undef; <D>; };
5831 D->error and fail "read $dscfn: $!";
5834 # we don't normally need this so import it here
5835 use Dpkg::Source::Package;
5836 my $dp = new Dpkg::Source::Package filename => $dscfn,
5837 require_valid_signature => $needsig;
5839 local $SIG{__WARN__} = sub {
5841 return unless $needsig;
5842 fail "import-dsc signature check failed";
5844 if (!$dp->is_signed()) {
5845 warn "$us: warning: importing unsigned .dsc\n";
5847 my $r = $dp->check_signature();
5848 die "->check_signature => $r" if $needsig && $r;
5854 my $dgit_commit = $dsc->{$ourdscfield[0]};
5855 if (defined $dgit_commit &&
5856 !forceing [qw(import-dsc-with-dgit-field)]) {
5857 $dgit_commit =~ m/\w+/ or fail "invalid hash in .dsc";
5858 progress "dgit: import-dsc of .dsc with Dgit field, using git hash";
5859 my @cmd = (qw(sh -ec),
5860 "echo $dgit_commit | git cat-file --batch-check");
5861 my $objgot = cmdoutput @cmd;
5862 if ($objgot =~ m#^\w+ missing\b#) {
5864 .dsc contains Dgit field referring to object $dgit_commit
5865 Your git tree does not have that object. Try `git fetch' from a
5866 plausible server (browse.dgit.d.o? alioth?), and try the import-dsc again.
5869 if ($oldhash && !is_fast_fwd $oldhash, $dgit_commit) {
5871 progress "Not fast forward, forced update.";
5873 fail "Not fast forward to $dgit_commit";
5876 @cmd = (@git, qw(update-ref -m), "dgit import-dsc (Dgit): $info",
5877 $dstbranch, $dgit_commit);
5879 progress "dgit: import-dsc updated git ref $dstbranch";
5884 Branch $dstbranch already exists
5885 Specify ..$specbranch for a pseudo-merge, binding in existing history
5886 Specify +$specbranch to overwrite, discarding existing history
5888 if $oldhash && !$force;
5890 $package = getfield $dsc, 'Source';
5891 my @dfi = dsc_files_info();
5892 foreach my $fi (@dfi) {
5893 my $f = $fi->{Filename};
5895 next if lstat $here;
5896 fail "stat $here: $!" unless $! == ENOENT;
5898 if ($dscfn =~ m#^(?:\./+)?\.\./+#) {
5900 } elsif ($dscfn =~ m#^/#) {
5903 fail "cannot import $dscfn which seems to be inside working tree!";
5905 $there =~ s#/+[^/]+$## or
5906 fail "cannot import $dscfn which seems to not have a basename";
5908 symlink $there, $here or fail "symlink $there to $here: $!";
5909 progress "made symlink $here -> $there";
5910 # print STDERR Dumper($fi);
5912 my @mergeinputs = generate_commits_from_dsc();
5913 die unless @mergeinputs == 1;
5915 my $newhash = $mergeinputs[0]{Commit};
5919 progress "Import, forced update - synthetic orphan git history.";
5920 } elsif ($force < 0) {
5921 progress "Import, merging.";
5922 my $tree = cmdoutput @git, qw(rev-parse), "$newhash:";
5923 my $version = getfield $dsc, 'Version';
5924 $newhash = make_commit_text <<END;
5929 Merge $package ($version) import into $dstbranch
5932 die; # caught earlier
5936 my @cmd = (@git, qw(update-ref -m), "dgit import-dsc: $info",
5937 $dstbranch, $newhash);
5939 progress "dgit: import-dsc results are in in git ref $dstbranch";
5942 sub cmd_archive_api_query {
5943 badusage "need only 1 subpath argument" unless @ARGV==1;
5944 my ($subpath) = @ARGV;
5945 my @cmd = archive_api_query_cmd($subpath);
5948 exec @cmd or fail "exec curl: $!\n";
5951 sub cmd_clone_dgit_repos_server {
5952 badusage "need destination argument" unless @ARGV==1;
5953 my ($destdir) = @ARGV;
5954 $package = '_dgit-repos-server';
5955 my @cmd = (@git, qw(clone), access_giturl(), $destdir);
5957 exec @cmd or fail "exec git clone: $!\n";
5960 sub cmd_setup_mergechangelogs {
5961 badusage "no arguments allowed to dgit setup-mergechangelogs" if @ARGV;
5962 setup_mergechangelogs(1);
5965 sub cmd_setup_useremail {
5966 badusage "no arguments allowed to dgit setup-mergechangelogs" if @ARGV;
5970 sub cmd_setup_new_tree {
5971 badusage "no arguments allowed to dgit setup-tree" if @ARGV;
5975 #---------- argument parsing and main program ----------
5978 print "dgit version $our_version\n" or die $!;
5982 our (%valopts_long, %valopts_short);
5985 sub defvalopt ($$$$) {
5986 my ($long,$short,$val_re,$how) = @_;
5987 my $oi = { Long => $long, Short => $short, Re => $val_re, How => $how };
5988 $valopts_long{$long} = $oi;
5989 $valopts_short{$short} = $oi;
5990 # $how subref should:
5991 # do whatever assignemnt or thing it likes with $_[0]
5992 # if the option should not be passed on to remote, @rvalopts=()
5993 # or $how can be a scalar ref, meaning simply assign the value
5996 defvalopt '--since-version', '-v', '[^_]+|_', \$changes_since_version;
5997 defvalopt '--distro', '-d', '.+', \$idistro;
5998 defvalopt '', '-k', '.+', \$keyid;
5999 defvalopt '--existing-package','', '.*', \$existing_package;
6000 defvalopt '--build-products-dir','','.*', \$buildproductsdir;
6001 defvalopt '--clean', '', $cleanmode_re, \$cleanmode;
6002 defvalopt '--package', '-p', $package_re, \$package;
6003 defvalopt '--quilt', '', $quilt_modes_re, \$quilt_mode;
6005 defvalopt '', '-C', '.+', sub {
6006 ($changesfile) = (@_);
6007 if ($changesfile =~ s#^(.*)/##) {
6008 $buildproductsdir = $1;
6012 defvalopt '--initiator-tempdir','','.*', sub {
6013 ($initiator_tempdir) = (@_);
6014 $initiator_tempdir =~ m#^/# or
6015 badusage "--initiator-tempdir must be used specify an".
6016 " absolute, not relative, directory."
6022 if (defined $ENV{'DGIT_SSH'}) {
6023 @ssh = string_to_ssh $ENV{'DGIT_SSH'};
6024 } elsif (defined $ENV{'GIT_SSH'}) {
6025 @ssh = ($ENV{'GIT_SSH'});
6033 if (!defined $val) {
6034 badusage "$what needs a value" unless @ARGV;
6036 push @rvalopts, $val;
6038 badusage "bad value \`$val' for $what" unless
6039 $val =~ m/^$oi->{Re}$(?!\n)/s;
6040 my $how = $oi->{How};
6041 if (ref($how) eq 'SCALAR') {
6046 push @ropts, @rvalopts;
6050 last unless $ARGV[0] =~ m/^-/;
6054 if (m/^--dry-run$/) {
6057 } elsif (m/^--damp-run$/) {
6060 } elsif (m/^--no-sign$/) {
6063 } elsif (m/^--help$/) {
6065 } elsif (m/^--version$/) {
6067 } elsif (m/^--new$/) {
6070 } elsif (m/^--([-0-9a-z]+)=(.+)/s &&
6071 ($om = $opts_opt_map{$1}) &&
6075 } elsif (m/^--([-0-9a-z]+):(.*)/s &&
6076 !$opts_opt_cmdonly{$1} &&
6077 ($om = $opts_opt_map{$1})) {
6080 } elsif (m/^--(gbp|dpm)$/s) {
6081 push @ropts, "--quilt=$1";
6083 } elsif (m/^--ignore-dirty$/s) {
6086 } elsif (m/^--no-quilt-fixup$/s) {
6088 $quilt_mode = 'nocheck';
6089 } elsif (m/^--no-rm-on-error$/s) {
6092 } elsif (m/^--overwrite$/s) {
6094 $overwrite_version = '';
6095 } elsif (m/^--overwrite=(.+)$/s) {
6097 $overwrite_version = $1;
6098 } elsif (m/^--delayed=(\d+)$/s) {
6101 } elsif (m/^--dgit-view-save=(.+)$/s) {
6103 $split_brain_save = $1;
6104 $split_brain_save =~ s#^(?!refs/)#refs/heads/#;
6105 } elsif (m/^--(no-)?rm-old-changes$/s) {
6108 } elsif (m/^--deliberately-($deliberately_re)$/s) {
6110 push @deliberatelies, $&;
6111 } elsif (m/^--force-(.*)/ && defined $forceopts{$1}) {
6115 } elsif (m/^--force-/) {
6117 "$us: warning: ignoring unknown force option $_\n";
6119 } elsif (m/^--dgit-tag-format=(old|new)$/s) {
6120 # undocumented, for testing
6122 $tagformat_want = [ $1, 'command line', 1 ];
6123 # 1 menas overrides distro configuration
6124 } elsif (m/^--always-split-source-build$/s) {
6125 # undocumented, for testing
6127 $need_split_build_invocation = 1;
6128 } elsif (m/^(--[-0-9a-z]+)(=|$)/ && ($oi = $valopts_long{$1})) {
6129 $val = $2 ? $' : undef; #';
6130 $valopt->($oi->{Long});
6132 badusage "unknown long option \`$_'";
6139 } elsif (s/^-L/-/) {
6142 } elsif (s/^-h/-/) {
6144 } elsif (s/^-D/-/) {
6148 } elsif (s/^-N/-/) {
6153 push @changesopts, $_;
6155 } elsif (s/^-wn$//s) {
6157 $cleanmode = 'none';
6158 } elsif (s/^-wg$//s) {
6161 } elsif (s/^-wgf$//s) {
6163 $cleanmode = 'git-ff';
6164 } elsif (s/^-wd$//s) {
6166 $cleanmode = 'dpkg-source';
6167 } elsif (s/^-wdd$//s) {
6169 $cleanmode = 'dpkg-source-d';
6170 } elsif (s/^-wc$//s) {
6172 $cleanmode = 'check';
6173 } elsif (s/^-c([^=]*)\=(.*)$//s) {
6174 push @git, '-c', $&;
6175 $gitcfgs{cmdline}{$1} = [ $2 ];
6176 } elsif (s/^-c([^=]+)$//s) {
6177 push @git, '-c', $&;
6178 $gitcfgs{cmdline}{$1} = [ 'true' ];
6179 } elsif (m/^-[a-zA-Z]/ && ($oi = $valopts_short{$&})) {
6181 $val = undef unless length $val;
6182 $valopt->($oi->{Short});
6185 badusage "unknown short option \`$_'";
6192 sub check_env_sanity () {
6193 my $blocked = new POSIX::SigSet;
6194 sigprocmask SIG_UNBLOCK, $blocked, $blocked or die $!;
6197 foreach my $name (qw(PIPE CHLD)) {
6198 my $signame = "SIG$name";
6199 my $signum = eval "POSIX::$signame" // die;
6200 ($SIG{$name} // 'DEFAULT') eq 'DEFAULT' or
6201 die "$signame is set to something other than SIG_DFL\n";
6202 $blocked->ismember($signum) and
6203 die "$signame is blocked\n";
6209 On entry to dgit, $@
6210 This is a bug produced by something in in your execution environment.
6216 sub finalise_opts_opts () {
6217 foreach my $k (keys %opts_opt_map) {
6218 my $om = $opts_opt_map{$k};
6220 my $v = access_cfg("cmd-$k", 'RETURN-UNDEF');
6222 badcfg "cannot set command for $k"
6223 unless length $om->[0];
6227 foreach my $c (access_cfg_cfgs("opts-$k")) {
6229 map { $_ ? @$_ : () }
6230 map { $gitcfgs{$_}{$c} }
6231 reverse @gitcfgsources;
6232 printdebug "CL $c ", (join " ", map { shellquote } @vl),
6233 "\n" if $debuglevel >= 4;
6235 badcfg "cannot configure options for $k"
6236 if $opts_opt_cmdonly{$k};
6237 my $insertpos = $opts_cfg_insertpos{$k};
6238 @$om = ( @$om[0..$insertpos-1],
6240 @$om[$insertpos..$#$om] );
6245 if ($ENV{$fakeeditorenv}) {
6247 quilt_fixup_editor();
6254 print STDERR "DRY RUN ONLY\n" if $dryrun_level > 1;
6255 print STDERR "DAMP RUN - WILL MAKE LOCAL (UNSIGNED) CHANGES\n"
6256 if $dryrun_level == 1;
6258 print STDERR $helpmsg or die $!;
6261 my $cmd = shift @ARGV;
6264 my $pre_fn = ${*::}{"pre_$cmd"};
6265 $pre_fn->() if $pre_fn;
6267 if (!defined $rmchanges) {
6268 local $access_forpush;
6269 $rmchanges = access_cfg_bool(0, 'rm-old-changes');
6272 if (!defined $quilt_mode) {
6273 local $access_forpush;
6274 $quilt_mode = cfg('dgit.force.quilt-mode', 'RETURN-UNDEF')
6275 // access_cfg('quilt-mode', 'RETURN-UNDEF')
6277 $quilt_mode =~ m/^($quilt_modes_re)$/
6278 or badcfg "unknown quilt-mode \`$quilt_mode'";
6282 $need_split_build_invocation ||= quiltmode_splitbrain();
6284 if (!defined $cleanmode) {
6285 local $access_forpush;
6286 $cleanmode = access_cfg('clean-mode', 'RETURN-UNDEF');
6287 $cleanmode //= 'dpkg-source';
6289 badcfg "unknown clean-mode \`$cleanmode'" unless
6290 $cleanmode =~ m/^($cleanmode_re)$(?!\n)/s;
6293 my $fn = ${*::}{"cmd_$cmd"};
6294 $fn or badusage "unknown operation $cmd";