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';
73 our $dodep14tag_re = 'want|no|always';
74 our $split_brain_save;
75 our $we_are_responder;
76 our $initiator_tempdir;
77 our $patches_applied_dirtily = 00;
82 our %forceopts = map { $_=>0 }
83 qw(unrepresentable unsupported-source-format
84 dsc-changes-mismatch changes-origs-exactly
85 import-gitapply-absurd
86 import-gitapply-no-absurd
87 import-dsc-with-dgit-field);
89 our %format_ok = map { $_=>1 } ("1.0","3.0 (native)","3.0 (quilt)");
91 our $suite_re = '[-+.0-9a-z]+';
92 our $cleanmode_re = 'dpkg-source(?:-d)?|git|git-ff|check|none';
93 our $orig_f_comp_re = 'orig(?:-[-0-9a-z]+)?';
94 our $orig_f_sig_re = '\\.(?:asc|gpg|pgp)';
95 our $orig_f_tail_re = "$orig_f_comp_re\\.tar(?:\\.\\w+)?(?:$orig_f_sig_re)?";
97 our $git_authline_re = '^([^<>]+) \<(\S+)\> (\d+ [-+]\d+)$';
98 our $splitbraincache = 'dgit-intern/quilt-cache';
100 our (@git) = qw(git);
101 our (@dget) = qw(dget);
102 our (@curl) = qw(curl);
103 our (@dput) = qw(dput);
104 our (@debsign) = qw(debsign);
105 our (@gpg) = qw(gpg);
106 our (@sbuild) = qw(sbuild);
108 our (@dgit) = qw(dgit);
109 our (@aptget) = qw(apt-get);
110 our (@aptcache) = qw(apt-cache);
111 our (@dpkgbuildpackage) = qw(dpkg-buildpackage -i\.git/ -I.git);
112 our (@dpkgsource) = qw(dpkg-source -i\.git/ -I.git);
113 our (@dpkggenchanges) = qw(dpkg-genchanges);
114 our (@mergechanges) = qw(mergechanges -f);
115 our (@gbp_build) = ('');
116 our (@gbp_pq) = ('gbp pq');
117 our (@changesopts) = ('');
119 our %opts_opt_map = ('dget' => \@dget, # accept for compatibility
122 'debsign' => \@debsign,
124 'sbuild' => \@sbuild,
128 'apt-get' => \@aptget,
129 'apt-cache' => \@aptcache,
130 'dpkg-source' => \@dpkgsource,
131 'dpkg-buildpackage' => \@dpkgbuildpackage,
132 'dpkg-genchanges' => \@dpkggenchanges,
133 'gbp-build' => \@gbp_build,
134 'gbp-pq' => \@gbp_pq,
135 'ch' => \@changesopts,
136 'mergechanges' => \@mergechanges);
138 our %opts_opt_cmdonly = ('gpg' => 1, 'git' => 1);
139 our %opts_cfg_insertpos = map {
141 scalar @{ $opts_opt_map{$_} }
142 } keys %opts_opt_map;
144 sub finalise_opts_opts();
150 our $supplementary_message = '';
151 our $need_split_build_invocation = 0;
152 our $split_brain = 0;
156 print STDERR "! $_\n" foreach $supplementary_message =~ m/^.+$/mg;
159 our $remotename = 'dgit';
160 our @ourdscfield = qw(Dgit Vcs-Dgit-Master);
164 if (!defined $absurdity) {
166 $absurdity =~ s{/[^/]+$}{/absurd} or die;
170 my ($v,$distro) = @_;
171 return $tagformatfn->($v, $distro);
174 sub debiantag_maintview ($$) {
175 my ($v,$distro) = @_;
176 return "$distro/".dep14_version_mangle $v;
179 sub madformat ($) { $_[0] eq '3.0 (quilt)' }
181 sub lbranch () { return "$branchprefix/$csuite"; }
182 my $lbranch_re = '^refs/heads/'.$branchprefix.'/([^/.]+)$';
183 sub lref () { return "refs/heads/".lbranch(); }
184 sub lrref () { return "refs/remotes/$remotename/".server_branch($csuite); }
185 sub rrref () { return server_ref($csuite); }
187 sub lrfetchrefs () { return "refs/dgit-fetch/$csuite"; }
188 sub lrfetchref () { return lrfetchrefs.'/'.server_branch($csuite); }
190 # We fetch some parts of lrfetchrefs/*. Ideally we delete these
191 # locally fetched refs because they have unhelpful names and clutter
192 # up gitk etc. So we track whether we have "used up" head ref (ie,
193 # whether we have made another local ref which refers to this object).
195 # (If we deleted them unconditionally, then we might end up
196 # re-fetching the same git objects each time dgit fetch was run.)
198 # So, leach use of lrfetchrefs needs to be accompanied by arrangements
199 # in git_fetch_us to fetch the refs in question, and possibly a call
200 # to lrfetchref_used.
202 our (%lrfetchrefs_f, %lrfetchrefs_d);
203 # $lrfetchrefs_X{lrfetchrefs."/heads/whatever"} = $objid
205 sub lrfetchref_used ($) {
206 my ($fullrefname) = @_;
207 my $objid = $lrfetchrefs_f{$fullrefname};
208 $lrfetchrefs_d{$fullrefname} = $objid if defined $objid;
219 return "${package}_".(stripepoch $vsn).$sfx
224 return srcfn($vsn,".dsc");
227 sub changespat ($;$) {
228 my ($vsn, $arch) = @_;
229 return "${package}_".(stripepoch $vsn)."_".($arch//'*').".changes";
232 sub upstreamversion ($) {
244 foreach my $f (@end) {
246 print STDERR "$us: cleanup: $@" if length $@;
250 sub badcfg { print STDERR "$us: invalid configuration: @_\n"; exit 12; }
252 sub forceable_fail ($$) {
253 my ($forceoptsl, $msg) = @_;
254 fail $msg unless grep { $forceopts{$_} } @$forceoptsl;
255 print STDERR "warning: overriding problem due to --force:\n". $msg;
259 my ($forceoptsl) = @_;
260 my @got = grep { $forceopts{$_} } @$forceoptsl;
261 return 0 unless @got;
263 "warning: skipping checks or functionality due to --force-$got[0]\n";
266 sub no_such_package () {
267 print STDERR "$us: package $package does not exist in suite $isuite\n";
273 printdebug "CD $newdir\n";
274 chdir $newdir or confess "chdir: $newdir: $!";
277 sub deliberately ($) {
279 return !!grep { $_ eq "--deliberately-$enquiry" } @deliberatelies;
282 sub deliberately_not_fast_forward () {
283 foreach (qw(not-fast-forward fresh-repo)) {
284 return 1 if deliberately($_) || deliberately("TEST-dgit-only-$_");
288 sub quiltmode_splitbrain () {
289 $quilt_mode =~ m/gbp|dpm|unapplied/;
292 sub opts_opt_multi_cmd {
294 push @cmd, split /\s+/, shift @_;
300 return opts_opt_multi_cmd @gbp_pq;
303 #---------- remote protocol support, common ----------
305 # remote push initiator/responder protocol:
306 # $ dgit remote-push-build-host <n-rargs> <rargs>... <push-args>...
307 # where <rargs> is <push-host-dir> <supported-proto-vsn>,... ...
308 # < dgit-remote-push-ready <actual-proto-vsn>
315 # > supplementary-message NBYTES # $protovsn >= 3
320 # > file parsed-changelog
321 # [indicates that output of dpkg-parsechangelog follows]
322 # > data-block NBYTES
323 # > [NBYTES bytes of data (no newline)]
324 # [maybe some more blocks]
333 # > param head DGIT-VIEW-HEAD
334 # > param csuite SUITE
335 # > param tagformat old|new
336 # > param maint-view MAINT-VIEW-HEAD
338 # > previously REFNAME=OBJNAME # if --deliberately-not-fast-forward
339 # # goes into tag, for replay prevention
342 # [indicates that signed tag is wanted]
343 # < data-block NBYTES
344 # < [NBYTES bytes of data (no newline)]
345 # [maybe some more blocks]
349 # > want signed-dsc-changes
350 # < data-block NBYTES [transfer of signed dsc]
352 # < data-block NBYTES [transfer of signed changes]
360 sub i_child_report () {
361 # Sees if our child has died, and reap it if so. Returns a string
362 # describing how it died if it failed, or undef otherwise.
363 return undef unless $i_child_pid;
364 my $got = waitpid $i_child_pid, WNOHANG;
365 return undef if $got <= 0;
366 die unless $got == $i_child_pid;
367 $i_child_pid = undef;
368 return undef unless $?;
369 return "build host child ".waitstatusmsg();
374 fail "connection lost: $!" if $fh->error;
375 fail "protocol violation; $m not expected";
378 sub badproto_badread ($$) {
380 fail "connection lost: $!" if $!;
381 my $report = i_child_report();
382 fail $report if defined $report;
383 badproto $fh, "eof (reading $wh)";
386 sub protocol_expect (&$) {
387 my ($match, $fh) = @_;
390 defined && chomp or badproto_badread $fh, "protocol message";
398 badproto $fh, "\`$_'";
401 sub protocol_send_file ($$) {
402 my ($fh, $ourfn) = @_;
403 open PF, "<", $ourfn or die "$ourfn: $!";
406 my $got = read PF, $d, 65536;
407 die "$ourfn: $!" unless defined $got;
409 print $fh "data-block ".length($d)."\n" or die $!;
410 print $fh $d or die $!;
412 PF->error and die "$ourfn $!";
413 print $fh "data-end\n" or die $!;
417 sub protocol_read_bytes ($$) {
418 my ($fh, $nbytes) = @_;
419 $nbytes =~ m/^[1-9]\d{0,5}$|^0$/ or badproto \*RO, "bad byte count";
421 my $got = read $fh, $d, $nbytes;
422 $got==$nbytes or badproto_badread $fh, "data block";
426 sub protocol_receive_file ($$) {
427 my ($fh, $ourfn) = @_;
428 printdebug "() $ourfn\n";
429 open PF, ">", $ourfn or die "$ourfn: $!";
431 my ($y,$l) = protocol_expect {
432 m/^data-block (.*)$/ ? (1,$1) :
433 m/^data-end$/ ? (0,) :
437 my $d = protocol_read_bytes $fh, $l;
438 print PF $d or die $!;
443 #---------- remote protocol support, responder ----------
445 sub responder_send_command ($) {
447 return unless $we_are_responder;
448 # called even without $we_are_responder
449 printdebug ">> $command\n";
450 print PO $command, "\n" or die $!;
453 sub responder_send_file ($$) {
454 my ($keyword, $ourfn) = @_;
455 return unless $we_are_responder;
456 printdebug "]] $keyword $ourfn\n";
457 responder_send_command "file $keyword";
458 protocol_send_file \*PO, $ourfn;
461 sub responder_receive_files ($@) {
462 my ($keyword, @ourfns) = @_;
463 die unless $we_are_responder;
464 printdebug "[[ $keyword @ourfns\n";
465 responder_send_command "want $keyword";
466 foreach my $fn (@ourfns) {
467 protocol_receive_file \*PI, $fn;
470 protocol_expect { m/^files-end$/ } \*PI;
473 #---------- remote protocol support, initiator ----------
475 sub initiator_expect (&) {
477 protocol_expect { &$match } \*RO;
480 #---------- end remote code ----------
483 if ($we_are_responder) {
485 responder_send_command "progress ".length($m) or die $!;
486 print PO $m or die $!;
496 $ua = LWP::UserAgent->new();
500 progress "downloading $what...";
501 my $r = $ua->get(@_) or die $!;
502 return undef if $r->code == 404;
503 $r->is_success or fail "failed to fetch $what: ".$r->status_line;
504 return $r->decoded_content(charset => 'none');
507 our ($dscdata,$dscurl,$dsc,$dsc_checked,$skew_warning_vsn);
512 failedcmd @_ if system @_;
515 sub act_local () { return $dryrun_level <= 1; }
516 sub act_scary () { return !$dryrun_level; }
519 if (!$dryrun_level) {
520 progress "$us ok: @_";
522 progress "would be ok: @_ (but dry run only)";
527 printcmd(\*STDERR,$debugprefix."#",@_);
530 sub runcmd_ordryrun {
538 sub runcmd_ordryrun_local {
547 my ($first_shell, @cmd) = @_;
548 return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
551 our $helpmsg = <<END;
553 dgit [dgit-opts] clone [dgit-opts] package [suite] [./dir|/dir]
554 dgit [dgit-opts] fetch|pull [dgit-opts] [suite]
555 dgit [dgit-opts] build [dpkg-buildpackage-opts]
556 dgit [dgit-opts] sbuild [sbuild-opts]
557 dgit [dgit-opts] push [dgit-opts] [suite]
558 dgit [dgit-opts] rpush build-host:build-dir ...
559 important dgit options:
560 -k<keyid> sign tag and package with <keyid> instead of default
561 --dry-run -n do not change anything, but go through the motions
562 --damp-run -L like --dry-run but make local changes, without signing
563 --new -N allow introducing a new package
564 --debug -D increase debug level
565 -c<name>=<value> set git config option (used directly by dgit too)
568 our $later_warning_msg = <<END;
569 Perhaps the upload is stuck in incoming. Using the version from git.
573 print STDERR "$us: @_\n", $helpmsg or die $!;
578 @ARGV or badusage "too few arguments";
579 return scalar shift @ARGV;
583 print $helpmsg or die $!;
587 our $td = $ENV{DGIT_TEST_DUMMY_DIR} || "DGIT_TEST_DUMMY_DIR-unset";
589 our %defcfg = ('dgit.default.distro' => 'debian',
590 'dgit-suite.*-security.distro' => 'debian-security',
591 'dgit.default.username' => '',
592 'dgit.default.archive-query-default-component' => 'main',
593 'dgit.default.ssh' => 'ssh',
594 'dgit.default.archive-query' => 'madison:',
595 'dgit.default.sshpsql-dbname' => 'service=projectb',
596 'dgit.default.aptget-components' => 'main',
597 'dgit.default.dgit-tag-format' => 'new,old,maint',
598 # old means "repo server accepts pushes with old dgit tags"
599 # new means "repo server accepts pushes with new dgit tags"
600 # maint means "repo server accepts split brain pushes"
601 # hist means "repo server may have old pushes without new tag"
602 # ("hist" is implied by "old")
603 'dgit-distro.debian.archive-query' => 'ftpmasterapi:',
604 'dgit-distro.debian.git-check' => 'url',
605 'dgit-distro.debian.git-check-suffix' => '/info/refs',
606 'dgit-distro.debian.new-private-pushers' => 't',
607 'dgit-distro.debian/push.git-url' => '',
608 'dgit-distro.debian/push.git-host' => 'push.dgit.debian.org',
609 'dgit-distro.debian/push.git-user-force' => 'dgit',
610 'dgit-distro.debian/push.git-proto' => 'git+ssh://',
611 'dgit-distro.debian/push.git-path' => '/dgit/debian/repos',
612 'dgit-distro.debian/push.git-create' => 'true',
613 'dgit-distro.debian/push.git-check' => 'ssh-cmd',
614 'dgit-distro.debian.archive-query-url', 'https://api.ftp-master.debian.org/',
615 # 'dgit-distro.debian.archive-query-tls-key',
616 # '/etc/ssl/certs/%HOST%.pem:/etc/dgit/%HOST%.pem',
617 # ^ this does not work because curl is broken nowadays
618 # Fixing #790093 properly will involve providing providing the key
619 # in some pacagke and maybe updating these paths.
621 # 'dgit-distro.debian.archive-query-tls-curl-args',
622 # '--ca-path=/etc/ssl/ca-debian',
623 # ^ this is a workaround but works (only) on DSA-administered machines
624 'dgit-distro.debian.git-url' => 'https://git.dgit.debian.org',
625 'dgit-distro.debian.git-url-suffix' => '',
626 'dgit-distro.debian.upload-host' => 'ftp-master', # for dput
627 'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/',
628 'dgit-distro.debian-security.archive-query' => 'aptget:',
629 'dgit-distro.debian-security.mirror' => 'http://security.debian.org/debian-security/',
630 'dgit-distro.debian-security.aptget-suite-map' => 's#-security$#/updates#',
631 'dgit-distro.debian-security.aptget-suite-rmap' => 's#$#-security#',
632 'dgit-distro.debian-security.nominal-distro' => 'debian',
633 'dgit-distro.debian.backports-quirk' => '(squeeze)-backports*',
634 'dgit-distro.debian-backports.mirror' => 'http://backports.debian.org/debian-backports/',
635 'dgit-distro.ubuntu.git-check' => 'false',
636 'dgit-distro.ubuntu.mirror' => 'http://archive.ubuntu.com/ubuntu',
637 'dgit-distro.test-dummy.ssh' => "$td/ssh",
638 'dgit-distro.test-dummy.username' => "alice",
639 'dgit-distro.test-dummy.git-check' => "ssh-cmd",
640 'dgit-distro.test-dummy.git-create' => "ssh-cmd",
641 'dgit-distro.test-dummy.git-url' => "$td/git",
642 'dgit-distro.test-dummy.git-host' => "git",
643 'dgit-distro.test-dummy.git-path' => "$td/git",
644 'dgit-distro.test-dummy.archive-query' => "dummycatapi:",
645 'dgit-distro.test-dummy.archive-query-url' => "file://$td/aq/",
646 'dgit-distro.test-dummy.mirror' => "file://$td/mirror/",
647 'dgit-distro.test-dummy.upload-host' => 'test-dummy',
651 our @gitcfgsources = qw(cmdline local global system);
653 sub git_slurp_config () {
654 local ($debuglevel) = $debuglevel-2;
657 # This algoritm is a bit subtle, but this is needed so that for
658 # options which we want to be single-valued, we allow the
659 # different config sources to override properly. See #835858.
660 foreach my $src (@gitcfgsources) {
661 next if $src eq 'cmdline';
662 # we do this ourselves since git doesn't handle it
664 my @cmd = (@git, qw(config -z --get-regexp), "--$src", qw(.*));
667 open GITS, "-|", @cmd or die $!;
670 printdebug "=> ", (messagequote $_), "\n";
672 push @{ $gitcfgs{$src}{$`} }, $'; #';
676 or ($!==0 && $?==256)
681 sub git_get_config ($) {
683 foreach my $src (@gitcfgsources) {
684 my $l = $gitcfgs{$src}{$c};
685 printdebug"C $c ".(defined $l ? messagequote "'$l'" : "undef")."\n"
688 @$l==1 or badcfg "multiple values for $c".
689 " (in $src git config)" if @$l > 1;
697 return undef if $c =~ /RETURN-UNDEF/;
698 my $v = git_get_config($c);
699 return $v if defined $v;
700 my $dv = $defcfg{$c};
701 return $dv if defined $dv;
703 badcfg "need value for one of: @_\n".
704 "$us: distro or suite appears not to be (properly) supported";
707 sub access_basedistro () {
708 if (defined $idistro) {
711 my $def = cfg("dgit-suite.$isuite.distro", 'RETURN-UNDEF');
712 return $def if defined $def;
713 foreach my $src (@gitcfgsources, 'internal') {
714 my $kl = $src eq 'internal' ? \%defcfg : $gitcfgs{$src};
716 foreach my $k (keys %$kl) {
717 next unless $k =~ m#^dgit-suite\.(.*)\.distro$#;
719 next unless match_glob $dpat, $isuite;
723 return cfg("dgit.default.distro");
727 sub access_nomdistro () {
728 my $base = access_basedistro();
729 return cfg("dgit-distro.$base.nominal-distro",'RETURN-UNDEF') // $base;
732 sub access_quirk () {
733 # returns (quirk name, distro to use instead or undef, quirk-specific info)
734 my $basedistro = access_basedistro();
735 my $backports_quirk = cfg("dgit-distro.$basedistro.backports-quirk",
737 if (defined $backports_quirk) {
738 my $re = $backports_quirk;
739 $re =~ s/[^-0-9a-z_\%*()]/\\$&/ig;
741 $re =~ s/\%/([-0-9a-z_]+)/
742 or $re =~ m/[()]/ or badcfg "backports-quirk needs \% or ( )";
743 if ($isuite =~ m/^$re$/) {
744 return ('backports',"$basedistro-backports",$1);
747 return ('none',undef);
752 sub parse_cfg_bool ($$$) {
753 my ($what,$def,$v) = @_;
756 $v =~ m/^[ty1]/ ? 1 :
757 $v =~ m/^[fn0]/ ? 0 :
758 badcfg "$what needs t (true, y, 1) or f (false, n, 0) not \`$v'";
761 sub access_forpush_config () {
762 my $d = access_basedistro();
766 parse_cfg_bool('new-private-pushers', 0,
767 cfg("dgit-distro.$d.new-private-pushers",
770 my $v = cfg("dgit-distro.$d.readonly", 'RETURN-UNDEF');
773 $v =~ m/^[ty1]/ ? 0 : # force readonly, forpush = 0
774 $v =~ m/^[fn0]/ ? 1 : # force nonreadonly, forpush = 1
775 $v =~ m/^[a]/ ? '' : # auto, forpush = ''
776 badcfg "readonly needs t (true, y, 1) or f (false, n, 0) or a (auto)";
779 sub access_forpush () {
780 $access_forpush //= access_forpush_config();
781 return $access_forpush;
785 die "$access_forpush ?" if ($access_forpush // 1) ne 1;
786 badcfg "pushing but distro is configured readonly"
787 if access_forpush_config() eq '0';
789 $supplementary_message = <<'END' unless $we_are_responder;
790 Push failed, before we got started.
791 You can retry the push, after fixing the problem, if you like.
793 finalise_opts_opts();
797 finalise_opts_opts();
800 sub supplementary_message ($) {
802 if (!$we_are_responder) {
803 $supplementary_message = $msg;
805 } elsif ($protovsn >= 3) {
806 responder_send_command "supplementary-message ".length($msg)
808 print PO $msg or die $!;
812 sub access_distros () {
813 # Returns list of distros to try, in order
816 # 0. `instead of' distro name(s) we have been pointed to
817 # 1. the access_quirk distro, if any
818 # 2a. the user's specified distro, or failing that } basedistro
819 # 2b. the distro calculated from the suite }
820 my @l = access_basedistro();
822 my (undef,$quirkdistro) = access_quirk();
823 unshift @l, $quirkdistro;
824 unshift @l, $instead_distro;
825 @l = grep { defined } @l;
827 push @l, access_nomdistro();
829 if (access_forpush()) {
830 @l = map { ("$_/push", $_) } @l;
835 sub access_cfg_cfgs (@) {
838 # The nesting of these loops determines the search order. We put
839 # the key loop on the outside so that we search all the distros
840 # for each key, before going on to the next key. That means that
841 # if access_cfg is called with a more specific, and then a less
842 # specific, key, an earlier distro can override the less specific
843 # without necessarily overriding any more specific keys. (If the
844 # distro wants to override the more specific keys it can simply do
845 # so; whereas if we did the loop the other way around, it would be
846 # impossible to for an earlier distro to override a less specific
847 # key but not the more specific ones without restating the unknown
848 # values of the more specific keys.
851 # We have to deal with RETURN-UNDEF specially, so that we don't
852 # terminate the search prematurely.
854 if (m/RETURN-UNDEF/) { push @rundef, $_; last; }
857 foreach my $d (access_distros()) {
858 push @cfgs, map { "dgit-distro.$d.$_" } @realkeys;
860 push @cfgs, map { "dgit.default.$_" } @realkeys;
867 my (@cfgs) = access_cfg_cfgs(@keys);
868 my $value = cfg(@cfgs);
872 sub access_cfg_bool ($$) {
873 my ($def, @keys) = @_;
874 parse_cfg_bool($keys[0], $def, access_cfg(@keys, 'RETURN-UNDEF'));
877 sub string_to_ssh ($) {
879 if ($spec =~ m/\s/) {
880 return qw(sh -ec), 'exec '.$spec.' "$@"', 'x';
886 sub access_cfg_ssh () {
887 my $gitssh = access_cfg('ssh', 'RETURN-UNDEF');
888 if (!defined $gitssh) {
891 return string_to_ssh $gitssh;
895 sub access_runeinfo ($) {
897 return ": dgit ".access_basedistro()." $info ;";
900 sub access_someuserhost ($) {
902 my $user = access_cfg("$some-user-force", 'RETURN-UNDEF');
903 defined($user) && length($user) or
904 $user = access_cfg("$some-user",'username');
905 my $host = access_cfg("$some-host");
906 return length($user) ? "$user\@$host" : $host;
909 sub access_gituserhost () {
910 return access_someuserhost('git');
913 sub access_giturl (;$) {
915 my $url = access_cfg('git-url','RETURN-UNDEF');
918 my $proto = access_cfg('git-proto', 'RETURN-UNDEF');
919 return undef unless defined $proto;
922 access_gituserhost().
923 access_cfg('git-path');
925 $suffix = access_cfg('git-url-suffix','RETURN-UNDEF');
928 return "$url/$package$suffix";
931 sub parsecontrolfh ($$;$) {
932 my ($fh, $desc, $allowsigned) = @_;
933 our $dpkgcontrolhash_noissigned;
936 my %opts = ('name' => $desc);
937 $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
938 $c = Dpkg::Control::Hash->new(%opts);
939 $c->parse($fh,$desc) or die "parsing of $desc failed";
940 last if $allowsigned;
941 last if $dpkgcontrolhash_noissigned;
942 my $issigned= $c->get_option('is_pgp_signed');
943 if (!defined $issigned) {
944 $dpkgcontrolhash_noissigned= 1;
945 seek $fh, 0,0 or die "seek $desc: $!";
946 } elsif ($issigned) {
947 fail "control file $desc is (already) PGP-signed. ".
948 " Note that dgit push needs to modify the .dsc and then".
949 " do the signature itself";
958 my ($file, $desc, $allowsigned) = @_;
959 my $fh = new IO::Handle;
960 open $fh, '<', $file or die "$file: $!";
961 my $c = parsecontrolfh($fh,$desc,$allowsigned);
962 $fh->error and die $!;
968 my ($dctrl,$field) = @_;
969 my $v = $dctrl->{$field};
970 return $v if defined $v;
971 fail "missing field $field in ".$dctrl->get_option('name');
975 my $c = Dpkg::Control::Hash->new(name => 'parsed changelog');
976 my $p = new IO::Handle;
977 my @cmd = (qw(dpkg-parsechangelog), @_);
978 open $p, '-|', @cmd or die $!;
980 $?=0; $!=0; close $p or failedcmd @cmd;
984 sub commit_getclogp ($) {
985 # Returns the parsed changelog hashref for a particular commit
987 our %commit_getclogp_memo;
988 my $memo = $commit_getclogp_memo{$objid};
989 return $memo if $memo;
991 my $mclog = ".git/dgit/clog-$objid";
992 runcmd shell_cmd "exec >$mclog", @git, qw(cat-file blob),
993 "$objid:debian/changelog";
994 $commit_getclogp_memo{$objid} = parsechangelog("-l$mclog");
999 defined $d or fail "getcwd failed: $!";
1003 sub parse_dscdata () {
1004 my $dscfh = new IO::File \$dscdata, '<' or die $!;
1005 printdebug Dumper($dscdata) if $debuglevel>1;
1006 $dsc = parsecontrolfh($dscfh,$dscurl,1);
1007 printdebug Dumper($dsc) if $debuglevel>1;
1012 sub archive_query ($;@) {
1013 my ($method) = shift @_;
1014 fail "this operation does not support multiple comma-separated suites"
1016 my $query = access_cfg('archive-query','RETURN-UNDEF');
1017 $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
1020 { no strict qw(refs); &{"${method}_${proto}"}($proto,$data,@_); }
1023 sub archive_query_prepend_mirror {
1024 my $m = access_cfg('mirror');
1025 return map { [ $_->[0], $m.$_->[1], @$_[2..$#$_] ] } @_;
1028 sub pool_dsc_subpath ($$) {
1029 my ($vsn,$component) = @_; # $package is implict arg
1030 my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
1031 return "/pool/$component/$prefix/$package/".dscfn($vsn);
1034 sub cfg_apply_map ($$$) {
1035 my ($varref, $what, $mapspec) = @_;
1036 return unless $mapspec;
1038 printdebug "config $what EVAL{ $mapspec; }\n";
1040 eval "package Dgit::Config; $mapspec;";
1045 #---------- `ftpmasterapi' archive query method (nascent) ----------
1047 sub archive_api_query_cmd ($) {
1049 my @cmd = (@curl, qw(-sS));
1050 my $url = access_cfg('archive-query-url');
1051 if ($url =~ m#^https://([-.0-9a-z]+)/#) {
1053 my $keys = access_cfg('archive-query-tls-key','RETURN-UNDEF') //'';
1054 foreach my $key (split /\:/, $keys) {
1055 $key =~ s/\%HOST\%/$host/g;
1057 fail "for $url: stat $key: $!" unless $!==ENOENT;
1060 fail "config requested specific TLS key but do not know".
1061 " how to get curl to use exactly that EE key ($key)";
1062 # push @cmd, "--cacert", $key, "--capath", "/dev/enoent";
1063 # # Sadly the above line does not work because of changes
1064 # # to gnutls. The real fix for #790093 may involve
1065 # # new curl options.
1068 # Fixing #790093 properly will involve providing a value
1069 # for this on clients.
1070 my $kargs = access_cfg('archive-query-tls-curl-ca-args','RETURN-UNDEF');
1071 push @cmd, split / /, $kargs if defined $kargs;
1073 push @cmd, $url.$subpath;
1077 sub api_query ($$;$) {
1079 my ($data, $subpath, $ok404) = @_;
1080 badcfg "ftpmasterapi archive query method takes no data part"
1082 my @cmd = archive_api_query_cmd($subpath);
1083 my $url = $cmd[$#cmd];
1084 push @cmd, qw(-w %{http_code});
1085 my $json = cmdoutput @cmd;
1086 unless ($json =~ s/\d+\d+\d$//) {
1087 failedcmd_report_cmd undef, @cmd;
1088 fail "curl failed to print 3-digit HTTP code";
1091 return undef if $code eq '404' && $ok404;
1092 fail "fetch of $url gave HTTP code $code"
1093 unless $url =~ m#^file://# or $code =~ m/^2/;
1094 return decode_json($json);
1097 sub canonicalise_suite_ftpmasterapi {
1098 my ($proto,$data) = @_;
1099 my $suites = api_query($data, 'suites');
1101 foreach my $entry (@$suites) {
1103 my $v = $entry->{$_};
1104 defined $v && $v eq $isuite;
1105 } qw(codename name);
1106 push @matched, $entry;
1108 fail "unknown suite $isuite" unless @matched;
1111 @matched==1 or die "multiple matches for suite $isuite\n";
1112 $cn = "$matched[0]{codename}";
1113 defined $cn or die "suite $isuite info has no codename\n";
1114 $cn =~ m/^$suite_re$/ or die "suite $isuite maps to bad codename\n";
1116 die "bad ftpmaster api response: $@\n".Dumper(\@matched)
1121 sub archive_query_ftpmasterapi {
1122 my ($proto,$data) = @_;
1123 my $info = api_query($data, "dsc_in_suite/$isuite/$package");
1125 my $digester = Digest::SHA->new(256);
1126 foreach my $entry (@$info) {
1128 my $vsn = "$entry->{version}";
1129 my ($ok,$msg) = version_check $vsn;
1130 die "bad version: $msg\n" unless $ok;
1131 my $component = "$entry->{component}";
1132 $component =~ m/^$component_re$/ or die "bad component";
1133 my $filename = "$entry->{filename}";
1134 $filename && $filename !~ m#[^-+:._~0-9a-zA-Z/]|^[/.]|/[/.]#
1135 or die "bad filename";
1136 my $sha256sum = "$entry->{sha256sum}";
1137 $sha256sum =~ m/^[0-9a-f]+$/ or die "bad sha256sum";
1138 push @rows, [ $vsn, "/pool/$component/$filename",
1139 $digester, $sha256sum ];
1141 die "bad ftpmaster api response: $@\n".Dumper($entry)
1144 @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
1145 return archive_query_prepend_mirror @rows;
1148 sub file_in_archive_ftpmasterapi {
1149 my ($proto,$data,$filename) = @_;
1150 my $pat = $filename;
1153 $pat =~ s#[^-+_.0-9a-z/]# sprintf '%%%02x', ord $& #ge;
1154 my $info = api_query($data, "file_in_archive/$pat", 1);
1157 #---------- `aptget' archive query method ----------
1160 our $aptget_releasefile;
1161 our $aptget_configpath;
1163 sub aptget_aptget () { return @aptget, qw(-c), $aptget_configpath; }
1164 sub aptget_aptcache () { return @aptcache, qw(-c), $aptget_configpath; }
1166 sub aptget_cache_clean {
1167 runcmd_ordryrun_local qw(sh -ec),
1168 'cd "$1"; find -atime +30 -type f -print0 | xargs -0r rm --',
1172 sub aptget_lock_acquire () {
1173 my $lockfile = "$aptget_base/lock";
1174 open APTGET_LOCK, '>', $lockfile or die "open $lockfile: $!";
1175 flock APTGET_LOCK, LOCK_EX or die "lock $lockfile: $!";
1178 sub aptget_prep ($) {
1180 return if defined $aptget_base;
1182 badcfg "aptget archive query method takes no data part"
1185 my $cache = $ENV{XDG_CACHE_DIR} // "$ENV{HOME}/.cache";
1188 ensuredir "$cache/dgit";
1190 access_cfg('aptget-cachekey','RETURN-UNDEF')
1191 // access_nomdistro();
1193 $aptget_base = "$cache/dgit/aptget";
1194 ensuredir $aptget_base;
1196 my $quoted_base = $aptget_base;
1197 die "$quoted_base contains bad chars, cannot continue"
1198 if $quoted_base =~ m/["\\]/; # apt.conf(5) says no escaping :-/
1200 ensuredir $aptget_base;
1202 aptget_lock_acquire();
1204 aptget_cache_clean();
1206 $aptget_configpath = "$aptget_base/apt.conf#$cachekey";
1207 my $sourceslist = "source.list#$cachekey";
1209 my $aptsuites = $isuite;
1210 cfg_apply_map(\$aptsuites, 'suite map',
1211 access_cfg('aptget-suite-map', 'RETURN-UNDEF'));
1213 open SRCS, ">", "$aptget_base/$sourceslist" or die $!;
1214 printf SRCS "deb-src %s %s %s\n",
1215 access_cfg('mirror'),
1217 access_cfg('aptget-components')
1220 ensuredir "$aptget_base/cache";
1221 ensuredir "$aptget_base/lists";
1223 open CONF, ">", $aptget_configpath or die $!;
1225 Debug::NoLocking "true";
1226 APT::Get::List-Cleanup "false";
1227 #clear APT::Update::Post-Invoke-Success;
1228 Dir::Etc::SourceList "$quoted_base/$sourceslist";
1229 Dir::State::Lists "$quoted_base/lists";
1230 Dir::Etc::preferences "$quoted_base/preferences";
1231 Dir::Cache::srcpkgcache "$quoted_base/cache/srcs#$cachekey";
1232 Dir::Cache::pkgcache "$quoted_base/cache/pkgs#$cachekey";
1235 foreach my $key (qw(
1238 Dir::Cache::Archives
1239 Dir::Etc::SourceParts
1240 Dir::Etc::preferencesparts
1242 ensuredir "$aptget_base/$key";
1243 print CONF "$key \"$quoted_base/$key\";\n" or die $!;
1246 my $oldatime = (time // die $!) - 1;
1247 foreach my $oldlist (<$aptget_base/lists/*Release>) {
1248 next unless stat_exists $oldlist;
1249 my ($mtime) = (stat _)[9];
1250 utime $oldatime, $mtime, $oldlist or die "$oldlist $!";
1253 runcmd_ordryrun_local aptget_aptget(), qw(update);
1256 foreach my $oldlist (<$aptget_base/lists/*Release>) {
1257 next unless stat_exists $oldlist;
1258 my ($atime) = (stat _)[8];
1259 next if $atime == $oldatime;
1260 push @releasefiles, $oldlist;
1262 my @inreleasefiles = grep { m#/InRelease$# } @releasefiles;
1263 @releasefiles = @inreleasefiles if @inreleasefiles;
1264 die "apt updated wrong number of Release files (@releasefiles), erk"
1265 unless @releasefiles == 1;
1267 ($aptget_releasefile) = @releasefiles;
1270 sub canonicalise_suite_aptget {
1271 my ($proto,$data) = @_;
1274 my $release = parsecontrol $aptget_releasefile, "Release file", 1;
1276 foreach my $name (qw(Codename Suite)) {
1277 my $val = $release->{$name};
1279 printdebug "release file $name: $val\n";
1280 $val =~ m/^$suite_re$/o or fail
1281 "Release file ($aptget_releasefile) specifies intolerable $name";
1282 cfg_apply_map(\$val, 'suite rmap',
1283 access_cfg('aptget-suite-rmap', 'RETURN-UNDEF'));
1290 sub archive_query_aptget {
1291 my ($proto,$data) = @_;
1294 ensuredir "$aptget_base/source";
1295 foreach my $old (<$aptget_base/source/*.dsc>) {
1296 unlink $old or die "$old: $!";
1299 my $showsrc = cmdoutput aptget_aptcache(), qw(showsrc), $package;
1300 return () unless $showsrc =~ m/^package:\s*\Q$package\E\s*$/mi;
1301 # avoids apt-get source failing with ambiguous error code
1303 runcmd_ordryrun_local
1304 shell_cmd 'cd "$1"/source; shift', $aptget_base,
1305 aptget_aptget(), qw(--download-only --only-source source), $package;
1307 my @dscs = <$aptget_base/source/*.dsc>;
1308 fail "apt-get source did not produce a .dsc" unless @dscs;
1309 fail "apt-get source produced several .dscs (@dscs)" unless @dscs==1;
1311 my $pre_dsc = parsecontrol $dscs[0], $dscs[0], 1;
1314 my $uri = "file://". uri_escape $dscs[0];
1315 $uri =~ s{\%2f}{/}gi;
1316 return [ (getfield $pre_dsc, 'Version'), $uri ];
1319 #---------- `dummyapicat' archive query method ----------
1321 sub archive_query_dummycatapi { archive_query_ftpmasterapi @_; }
1322 sub canonicalise_suite_dummycatapi { canonicalise_suite_ftpmasterapi @_; }
1324 sub file_in_archive_dummycatapi ($$$) {
1325 my ($proto,$data,$filename) = @_;
1326 my $mirror = access_cfg('mirror');
1327 $mirror =~ s#^file://#/# or die "$mirror ?";
1329 my @cmd = (qw(sh -ec), '
1331 find -name "$2" -print0 |
1333 ', qw(x), $mirror, $filename);
1334 debugcmd "-|", @cmd;
1335 open FIA, "-|", @cmd or die $!;
1338 printdebug "| $_\n";
1339 m/^(\w+) (\S+)$/ or die "$_ ?";
1340 push @out, { sha256sum => $1, filename => $2 };
1342 close FIA or die failedcmd @cmd;
1346 #---------- `madison' archive query method ----------
1348 sub archive_query_madison {
1349 return archive_query_prepend_mirror
1350 map { [ @$_[0..1] ] } madison_get_parse(@_);
1353 sub madison_get_parse {
1354 my ($proto,$data) = @_;
1355 die unless $proto eq 'madison';
1356 if (!length $data) {
1357 $data= access_cfg('madison-distro','RETURN-UNDEF');
1358 $data //= access_basedistro();
1360 $rmad{$proto,$data,$package} ||= cmdoutput
1361 qw(rmadison -asource),"-s$isuite","-u$data",$package;
1362 my $rmad = $rmad{$proto,$data,$package};
1365 foreach my $l (split /\n/, $rmad) {
1366 $l =~ m{^ \s*( [^ \t|]+ )\s* \|
1367 \s*( [^ \t|]+ )\s* \|
1368 \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
1369 \s*( [^ \t|]+ )\s* }x or die "$rmad ?";
1370 $1 eq $package or die "$rmad $package ?";
1377 $component = access_cfg('archive-query-default-component');
1379 $5 eq 'source' or die "$rmad ?";
1380 push @out, [$vsn,pool_dsc_subpath($vsn,$component),$newsuite];
1382 return sort { -version_compare($a->[0],$b->[0]); } @out;
1385 sub canonicalise_suite_madison {
1386 # madison canonicalises for us
1387 my @r = madison_get_parse(@_);
1389 "unable to canonicalise suite using package $package".
1390 " which does not appear to exist in suite $isuite;".
1391 " --existing-package may help";
1395 sub file_in_archive_madison { return undef; }
1397 #---------- `sshpsql' archive query method ----------
1400 my ($data,$runeinfo,$sql) = @_;
1401 if (!length $data) {
1402 $data= access_someuserhost('sshpsql').':'.
1403 access_cfg('sshpsql-dbname');
1405 $data =~ m/:/ or badcfg "invalid sshpsql method string \`$data'";
1406 my ($userhost,$dbname) = ($`,$'); #';
1408 my @cmd = (access_cfg_ssh, $userhost,
1409 access_runeinfo("ssh-psql $runeinfo").
1410 " export LC_MESSAGES=C; export LC_CTYPE=C;".
1411 " ".shellquote qw(psql -A), $dbname, qw(-c), $sql);
1413 open P, "-|", @cmd or die $!;
1416 printdebug(">|$_|\n");
1419 $!=0; $?=0; close P or failedcmd @cmd;
1421 my $nrows = pop @rows;
1422 $nrows =~ s/^\((\d+) rows?\)$/$1/ or die "$nrows ?";
1423 @rows == $nrows+1 or die "$nrows ".(scalar @rows)." ?";
1424 @rows = map { [ split /\|/, $_ ] } @rows;
1425 my $ncols = scalar @{ shift @rows };
1426 die if grep { scalar @$_ != $ncols } @rows;
1430 sub sql_injection_check {
1431 foreach (@_) { die "$_ $& ?" if m{[^-+=:_.,/0-9a-zA-Z]}; }
1434 sub archive_query_sshpsql ($$) {
1435 my ($proto,$data) = @_;
1436 sql_injection_check $isuite, $package;
1437 my @rows = sshpsql($data, "archive-query $isuite $package", <<END);
1438 SELECT source.version, component.name, files.filename, files.sha256sum
1440 JOIN src_associations ON source.id = src_associations.source
1441 JOIN suite ON suite.id = src_associations.suite
1442 JOIN dsc_files ON dsc_files.source = source.id
1443 JOIN files_archive_map ON files_archive_map.file_id = dsc_files.file
1444 JOIN component ON component.id = files_archive_map.component_id
1445 JOIN files ON files.id = dsc_files.file
1446 WHERE ( suite.suite_name='$isuite' OR suite.codename='$isuite' )
1447 AND source.source='$package'
1448 AND files.filename LIKE '%.dsc';
1450 @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
1451 my $digester = Digest::SHA->new(256);
1453 my ($vsn,$component,$filename,$sha256sum) = @$_;
1454 [ $vsn, "/pool/$component/$filename",$digester,$sha256sum ];
1456 return archive_query_prepend_mirror @rows;
1459 sub canonicalise_suite_sshpsql ($$) {
1460 my ($proto,$data) = @_;
1461 sql_injection_check $isuite;
1462 my @rows = sshpsql($data, "canonicalise-suite $isuite", <<END);
1463 SELECT suite.codename
1464 FROM suite where suite_name='$isuite' or codename='$isuite';
1466 @rows = map { $_->[0] } @rows;
1467 fail "unknown suite $isuite" unless @rows;
1468 die "ambiguous $isuite: @rows ?" if @rows>1;
1472 sub file_in_archive_sshpsql ($$$) { return undef; }
1474 #---------- `dummycat' archive query method ----------
1476 sub canonicalise_suite_dummycat ($$) {
1477 my ($proto,$data) = @_;
1478 my $dpath = "$data/suite.$isuite";
1479 if (!open C, "<", $dpath) {
1480 $!==ENOENT or die "$dpath: $!";
1481 printdebug "dummycat canonicalise_suite $isuite $dpath ENOENT\n";
1485 chomp or die "$dpath: $!";
1487 printdebug "dummycat canonicalise_suite $isuite $dpath = $_\n";
1491 sub archive_query_dummycat ($$) {
1492 my ($proto,$data) = @_;
1493 canonicalise_suite();
1494 my $dpath = "$data/package.$csuite.$package";
1495 if (!open C, "<", $dpath) {
1496 $!==ENOENT or die "$dpath: $!";
1497 printdebug "dummycat query $csuite $package $dpath ENOENT\n";
1505 printdebug "dummycat query $csuite $package $dpath | $_\n";
1506 my @row = split /\s+/, $_;
1507 @row==2 or die "$dpath: $_ ?";
1510 C->error and die "$dpath: $!";
1512 return archive_query_prepend_mirror
1513 sort { -version_compare($a->[0],$b->[0]); } @rows;
1516 sub file_in_archive_dummycat () { return undef; }
1518 #---------- tag format handling ----------
1520 sub access_cfg_tagformats () {
1521 split /\,/, access_cfg('dgit-tag-format');
1524 sub access_cfg_tagformats_can_splitbrain () {
1525 my %y = map { $_ => 1 } access_cfg_tagformats;
1526 foreach my $needtf (qw(new maint)) {
1527 next if $y{$needtf};
1533 sub need_tagformat ($$) {
1534 my ($fmt, $why) = @_;
1535 fail "need to use tag format $fmt ($why) but also need".
1536 " to use tag format $tagformat_want->[0] ($tagformat_want->[1])".
1537 " - no way to proceed"
1538 if $tagformat_want && $tagformat_want->[0] ne $fmt;
1539 $tagformat_want = [$fmt, $why, $tagformat_want->[2] // 0];
1542 sub select_tagformat () {
1544 return if $tagformatfn && !$tagformat_want;
1545 die 'bug' if $tagformatfn && $tagformat_want;
1546 # ... $tagformat_want assigned after previous select_tagformat
1548 my (@supported) = grep { $_ =~ m/^(?:old|new)$/ } access_cfg_tagformats();
1549 printdebug "select_tagformat supported @supported\n";
1551 $tagformat_want //= [ $supported[0], "distro access configuration", 0 ];
1552 printdebug "select_tagformat specified @$tagformat_want\n";
1554 my ($fmt,$why,$override) = @$tagformat_want;
1556 fail "target distro supports tag formats @supported".
1557 " but have to use $fmt ($why)"
1559 or grep { $_ eq $fmt } @supported;
1561 $tagformat_want = undef;
1563 $tagformatfn = ${*::}{"debiantag_$fmt"};
1565 fail "trying to use unknown tag format \`$fmt' ($why) !"
1566 unless $tagformatfn;
1569 #---------- archive query entrypoints and rest of program ----------
1571 sub canonicalise_suite () {
1572 return if defined $csuite;
1573 fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
1574 $csuite = archive_query('canonicalise_suite');
1575 if ($isuite ne $csuite) {
1576 progress "canonical suite name for $isuite is $csuite";
1578 progress "canonical suite name is $csuite";
1582 sub get_archive_dsc () {
1583 canonicalise_suite();
1584 my @vsns = archive_query('archive_query');
1585 foreach my $vinfo (@vsns) {
1586 my ($vsn,$vsn_dscurl,$digester,$digest) = @$vinfo;
1587 $dscurl = $vsn_dscurl;
1588 $dscdata = url_get($dscurl);
1590 $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
1595 $digester->add($dscdata);
1596 my $got = $digester->hexdigest();
1598 fail "$dscurl has hash $got but".
1599 " archive told us to expect $digest";
1602 my $fmt = getfield $dsc, 'Format';
1603 $format_ok{$fmt} or forceable_fail [qw(unsupported-source-format)],
1604 "unsupported source format $fmt, sorry";
1606 $dsc_checked = !!$digester;
1607 printdebug "get_archive_dsc: Version ".(getfield $dsc, 'Version')."\n";
1611 printdebug "get_archive_dsc: nothing in archive, returning undef\n";
1614 sub check_for_git ();
1615 sub check_for_git () {
1617 my $how = access_cfg('git-check');
1618 if ($how eq 'ssh-cmd') {
1620 (access_cfg_ssh, access_gituserhost(),
1621 access_runeinfo("git-check $package").
1622 " set -e; cd ".access_cfg('git-path').";".
1623 " if test -d $package.git; then echo 1; else echo 0; fi");
1624 my $r= cmdoutput @cmd;
1625 if (defined $r and $r =~ m/^divert (\w+)$/) {
1627 my ($usedistro,) = access_distros();
1628 # NB that if we are pushing, $usedistro will be $distro/push
1629 $instead_distro= cfg("dgit-distro.$usedistro.diverts.$divert");
1630 $instead_distro =~ s{^/}{ access_basedistro()."/" }e;
1631 progress "diverting to $divert (using config for $instead_distro)";
1632 return check_for_git();
1634 failedcmd @cmd unless defined $r and $r =~ m/^[01]$/;
1636 } elsif ($how eq 'url') {
1637 my $prefix = access_cfg('git-check-url','git-url');
1638 my $suffix = access_cfg('git-check-suffix','git-suffix',
1639 'RETURN-UNDEF') // '.git';
1640 my $url = "$prefix/$package$suffix";
1641 my @cmd = (@curl, qw(-sS -I), $url);
1642 my $result = cmdoutput @cmd;
1643 $result =~ s/^\S+ 200 .*\n\r?\n//;
1644 # curl -sS -I with https_proxy prints
1645 # HTTP/1.0 200 Connection established
1646 $result =~ m/^\S+ (404|200) /s or
1647 fail "unexpected results from git check query - ".
1648 Dumper($prefix, $result);
1650 if ($code eq '404') {
1652 } elsif ($code eq '200') {
1657 } elsif ($how eq 'true') {
1659 } elsif ($how eq 'false') {
1662 badcfg "unknown git-check \`$how'";
1666 sub create_remote_git_repo () {
1667 my $how = access_cfg('git-create');
1668 if ($how eq 'ssh-cmd') {
1670 (access_cfg_ssh, access_gituserhost(),
1671 access_runeinfo("git-create $package").
1672 "set -e; cd ".access_cfg('git-path').";".
1673 " cp -a _template $package.git");
1674 } elsif ($how eq 'true') {
1677 badcfg "unknown git-create \`$how'";
1681 our ($dsc_hash,$lastpush_mergeinput);
1683 our $ud = '.git/dgit/unpack';
1693 sub mktree_in_ud_here () {
1694 runcmd qw(git init -q);
1695 runcmd qw(git config gc.auto 0);
1696 rmtree('.git/objects');
1697 symlink '../../../../objects','.git/objects' or die $!;
1700 sub git_write_tree () {
1701 my $tree = cmdoutput @git, qw(write-tree);
1702 $tree =~ m/^\w+$/ or die "$tree ?";
1706 sub git_add_write_tree () {
1707 runcmd @git, qw(add -Af .);
1708 return git_write_tree();
1711 sub remove_stray_gits ($) {
1713 my @gitscmd = qw(find -name .git -prune -print0);
1714 debugcmd "|",@gitscmd;
1715 open GITS, "-|", @gitscmd or die $!;
1720 print STDERR "$us: warning: removing from $what: ",
1721 (messagequote $_), "\n";
1725 $!=0; $?=0; close GITS or failedcmd @gitscmd;
1728 sub mktree_in_ud_from_only_subdir ($;$) {
1729 my ($what,$raw) = @_;
1731 # changes into the subdir
1733 die "expected one subdir but found @dirs ?" unless @dirs==1;
1734 $dirs[0] =~ m#^([^/]+)/\.$# or die;
1738 remove_stray_gits($what);
1739 mktree_in_ud_here();
1741 my ($format, $fopts) = get_source_format();
1742 if (madformat($format)) {
1747 my $tree=git_add_write_tree();
1748 return ($tree,$dir);
1751 our @files_csum_info_fields =
1752 (['Checksums-Sha256','Digest::SHA', 'new(256)', 'sha256sum'],
1753 ['Checksums-Sha1', 'Digest::SHA', 'new(1)', 'sha1sum'],
1754 ['Files', 'Digest::MD5', 'new()', 'md5sum']);
1756 sub dsc_files_info () {
1757 foreach my $csumi (@files_csum_info_fields) {
1758 my ($fname, $module, $method) = @$csumi;
1759 my $field = $dsc->{$fname};
1760 next unless defined $field;
1761 eval "use $module; 1;" or die $@;
1763 foreach (split /\n/, $field) {
1765 m/^(\w+) (\d+) (\S+)$/ or
1766 fail "could not parse .dsc $fname line \`$_'";
1767 my $digester = eval "$module"."->$method;" or die $@;
1772 Digester => $digester,
1777 fail "missing any supported Checksums-* or Files field in ".
1778 $dsc->get_option('name');
1782 map { $_->{Filename} } dsc_files_info();
1785 sub files_compare_inputs (@) {
1790 my $showinputs = sub {
1791 return join "; ", map { $_->get_option('name') } @$inputs;
1794 foreach my $in (@$inputs) {
1796 my $in_name = $in->get_option('name');
1798 printdebug "files_compare_inputs $in_name\n";
1800 foreach my $csumi (@files_csum_info_fields) {
1801 my ($fname) = @$csumi;
1802 printdebug "files_compare_inputs $in_name $fname\n";
1804 my $field = $in->{$fname};
1805 next unless defined $field;
1808 foreach (split /\n/, $field) {
1811 my ($info, $f) = m/^(\w+ \d+) (?:\S+ \S+ )?(\S+)$/ or
1812 fail "could not parse $in_name $fname line \`$_'";
1814 printdebug "files_compare_inputs $in_name $fname $f\n";
1818 my $re = \ $record{$f}{$fname};
1820 $fchecked{$f}{$in_name} = 1;
1822 fail "hash or size of $f varies in $fname fields".
1823 " (between: ".$showinputs->().")";
1828 @files = sort @files;
1829 $expected_files //= \@files;
1830 "@$expected_files" eq "@files" or
1831 fail "file list in $in_name varies between hash fields!";
1834 fail "$in_name has no files list field(s)";
1836 printdebug "files_compare_inputs ".Dumper(\%fchecked, \%record)
1839 grep { keys %$_ == @$inputs-1 } values %fchecked
1840 or fail "no file appears in all file lists".
1841 " (looked in: ".$showinputs->().")";
1844 sub is_orig_file_in_dsc ($$) {
1845 my ($f, $dsc_files_info) = @_;
1846 return 0 if @$dsc_files_info <= 1;
1847 # One file means no origs, and the filename doesn't have a "what
1848 # part of dsc" component. (Consider versions ending `.orig'.)
1849 return 0 unless $f =~ m/\.$orig_f_tail_re$/o;
1853 sub is_orig_file_of_vsn ($$) {
1854 my ($f, $upstreamvsn) = @_;
1855 my $base = srcfn $upstreamvsn, '';
1856 return 0 unless $f =~ m/^\Q$base\E\.$orig_f_tail_re$/;
1860 sub changes_update_origs_from_dsc ($$$$) {
1861 my ($dsc, $changes, $upstreamvsn, $changesfile) = @_;
1863 printdebug "checking origs needed ($upstreamvsn)...\n";
1864 $_ = getfield $changes, 'Files';
1865 m/^\w+ \d+ (\S+ \S+) \S+$/m or
1866 fail "cannot find section/priority from .changes Files field";
1867 my $placementinfo = $1;
1869 printdebug "checking origs needed placement '$placementinfo'...\n";
1870 foreach my $l (split /\n/, getfield $dsc, 'Files') {
1871 $l =~ m/\S+$/ or next;
1873 printdebug "origs $file | $l\n";
1874 next unless is_orig_file_of_vsn $file, $upstreamvsn;
1875 printdebug "origs $file is_orig\n";
1876 my $have = archive_query('file_in_archive', $file);
1877 if (!defined $have) {
1879 archive does not support .orig check; hope you used --ch:--sa/-sd if needed
1885 printdebug "origs $file \$#\$have=$#$have\n";
1886 foreach my $h (@$have) {
1889 foreach my $csumi (@files_csum_info_fields) {
1890 my ($fname, $module, $method, $archivefield) = @$csumi;
1891 next unless defined $h->{$archivefield};
1892 $_ = $dsc->{$fname};
1893 next unless defined;
1894 m/^(\w+) .* \Q$file\E$/m or
1895 fail ".dsc $fname missing entry for $file";
1896 if ($h->{$archivefield} eq $1) {
1900 "$archivefield: $h->{$archivefield} (archive) != $1 (local .dsc)";
1903 die "$file ".Dumper($h)." ?!" if $same && @differ;
1906 push @found_differ, "archive $h->{filename}: ".join "; ", @differ
1909 printdebug "origs $file f.same=$found_same".
1910 " #f._differ=$#found_differ\n";
1911 if (@found_differ && !$found_same) {
1913 "archive contains $file with different checksum",
1916 # Now we edit the changes file to add or remove it
1917 foreach my $csumi (@files_csum_info_fields) {
1918 my ($fname, $module, $method, $archivefield) = @$csumi;
1919 next unless defined $changes->{$fname};
1921 # in archive, delete from .changes if it's there
1922 $changed{$file} = "removed" if
1923 $changes->{$fname} =~ s/^.* \Q$file\E$(?:)\n//m;
1924 } elsif ($changes->{$fname} =~ m/^.* \Q$file\E$(?:)\n/m) {
1925 # not in archive, but it's here in the .changes
1927 my $dsc_data = getfield $dsc, $fname;
1928 $dsc_data =~ m/^(.* \Q$file\E$)\n/m or die "$dsc_data $file ?";
1930 $extra =~ s/ \d+ /$&$placementinfo /
1931 or die "$fname $extra >$dsc_data< ?"
1932 if $fname eq 'Files';
1933 $changes->{$fname} .= "\n". $extra;
1934 $changed{$file} = "added";
1939 foreach my $file (keys %changed) {
1941 "edited .changes for archive .orig contents: %s %s",
1942 $changed{$file}, $file;
1944 my $chtmp = "$changesfile.tmp";
1945 $changes->save($chtmp);
1947 rename $chtmp,$changesfile or die "$changesfile $!";
1949 progress "[new .changes left in $changesfile]";
1952 progress "$changesfile already has appropriate .orig(s) (if any)";
1956 sub make_commit ($) {
1958 return cmdoutput @git, qw(hash-object -w -t commit), $file;
1961 sub make_commit_text ($) {
1964 my @cmd = (@git, qw(hash-object -w -t commit --stdin));
1966 print Dumper($text) if $debuglevel > 1;
1967 my $child = open2($out, $in, @cmd) or die $!;
1970 print $in $text or die $!;
1971 close $in or die $!;
1973 $h =~ m/^\w+$/ or die;
1975 printdebug "=> $h\n";
1978 waitpid $child, 0 == $child or die "$child $!";
1979 $? and failedcmd @cmd;
1983 sub clogp_authline ($) {
1985 my $author = getfield $clogp, 'Maintainer';
1986 $author =~ s#,.*##ms;
1987 my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
1988 my $authline = "$author $date";
1989 $authline =~ m/$git_authline_re/o or
1990 fail "unexpected commit author line format \`$authline'".
1991 " (was generated from changelog Maintainer field)";
1992 return ($1,$2,$3) if wantarray;
1996 sub vendor_patches_distro ($$) {
1997 my ($checkdistro, $what) = @_;
1998 return unless defined $checkdistro;
2000 my $series = "debian/patches/\L$checkdistro\E.series";
2001 printdebug "checking for vendor-specific $series ($what)\n";
2003 if (!open SERIES, "<", $series) {
2004 die "$series $!" unless $!==ENOENT;
2013 Unfortunately, this source package uses a feature of dpkg-source where
2014 the same source package unpacks to different source code on different
2015 distros. dgit cannot safely operate on such packages on affected
2016 distros, because the meaning of source packages is not stable.
2018 Please ask the distro/maintainer to remove the distro-specific series
2019 files and use a different technique (if necessary, uploading actually
2020 different packages, if different distros are supposed to have
2024 fail "Found active distro-specific series file for".
2025 " $checkdistro ($what): $series, cannot continue";
2027 die "$series $!" if SERIES->error;
2031 sub check_for_vendor_patches () {
2032 # This dpkg-source feature doesn't seem to be documented anywhere!
2033 # But it can be found in the changelog (reformatted):
2035 # commit 4fa01b70df1dc4458daee306cfa1f987b69da58c
2036 # Author: Raphael Hertzog <hertzog@debian.org>
2037 # Date: Sun Oct 3 09:36:48 2010 +0200
2039 # dpkg-source: correctly create .pc/.quilt_series with alternate
2042 # If you have debian/patches/ubuntu.series and you were
2043 # unpacking the source package on ubuntu, quilt was still
2044 # directed to debian/patches/series instead of
2045 # debian/patches/ubuntu.series.
2047 # debian/changelog | 3 +++
2048 # scripts/Dpkg/Source/Package/V3/quilt.pm | 4 +++-
2049 # 2 files changed, 6 insertions(+), 1 deletion(-)
2052 vendor_patches_distro($ENV{DEB_VENDOR}, "DEB_VENDOR");
2053 vendor_patches_distro(Dpkg::Vendor::get_current_vendor(),
2054 "Dpkg::Vendor \`current vendor'");
2055 vendor_patches_distro(access_basedistro(),
2056 "(base) distro being accessed");
2057 vendor_patches_distro(access_nomdistro(),
2058 "(nominal) distro being accessed");
2061 sub generate_commits_from_dsc () {
2062 # See big comment in fetch_from_archive, below.
2063 # See also README.dsc-import.
2067 my @dfi = dsc_files_info();
2068 foreach my $fi (@dfi) {
2069 my $f = $fi->{Filename};
2070 die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
2072 printdebug "considering linking $f: ";
2074 link_ltarget "../../../../$f", $f
2075 or ((printdebug "($!) "), 0)
2079 printdebug "linked.\n";
2081 complete_file_from_dsc('.', $fi)
2084 if (is_orig_file_in_dsc($f, \@dfi)) {
2085 link $f, "../../../../$f"
2091 # We unpack and record the orig tarballs first, so that we only
2092 # need disk space for one private copy of the unpacked source.
2093 # But we can't make them into commits until we have the metadata
2094 # from the debian/changelog, so we record the tree objects now and
2095 # make them into commits later.
2097 my $upstreamv = upstreamversion $dsc->{version};
2098 my $orig_f_base = srcfn $upstreamv, '';
2100 foreach my $fi (@dfi) {
2101 # We actually import, and record as a commit, every tarball
2102 # (unless there is only one file, in which case there seems
2105 my $f = $fi->{Filename};
2106 printdebug "import considering $f ";
2107 (printdebug "only one dfi\n"), next if @dfi == 1;
2108 (printdebug "not tar\n"), next unless $f =~ m/\.tar(\.\w+)?$/;
2109 (printdebug "signature\n"), next if $f =~ m/$orig_f_sig_re$/o;
2113 $f =~ m/^\Q$orig_f_base\E\.([^._]+)?\.tar(?:\.\w+)?$/;
2115 printdebug "Y ", (join ' ', map { $_//"(none)" }
2116 $compr_ext, $orig_f_part
2119 my $input = new IO::File $f, '<' or die "$f $!";
2123 if (defined $compr_ext) {
2125 Dpkg::Compression::compression_guess_from_filename $f;
2126 fail "Dpkg::Compression cannot handle file $f in source package"
2127 if defined $compr_ext && !defined $cname;
2129 new Dpkg::Compression::Process compression => $cname;
2130 my @compr_cmd = $compr_proc->get_uncompress_cmdline();
2131 my $compr_fh = new IO::Handle;
2132 my $compr_pid = open $compr_fh, "-|" // die $!;
2134 open STDIN, "<&", $input or die $!;
2136 die "dgit (child): exec $compr_cmd[0]: $!\n";
2141 rmtree "_unpack-tar";
2142 mkdir "_unpack-tar" or die $!;
2143 my @tarcmd = qw(tar -x -f -
2144 --no-same-owner --no-same-permissions
2145 --no-acls --no-xattrs --no-selinux);
2146 my $tar_pid = fork // die $!;
2148 chdir "_unpack-tar" or die $!;
2149 open STDIN, "<&", $input or die $!;
2151 die "dgit (child): exec $tarcmd[0]: $!";
2153 $!=0; (waitpid $tar_pid, 0) == $tar_pid or die $!;
2154 !$? or failedcmd @tarcmd;
2157 (@compr_cmd ? failedcmd @compr_cmd
2159 # finally, we have the results in "tarball", but maybe
2160 # with the wrong permissions
2162 runcmd qw(chmod -R +rwX _unpack-tar);
2163 changedir "_unpack-tar";
2164 remove_stray_gits($f);
2165 mktree_in_ud_here();
2167 my ($tree) = git_add_write_tree();
2168 my $tentries = cmdoutput @git, qw(ls-tree -z), $tree;
2169 if ($tentries =~ m/^\d+ tree (\w+)\t[^\000]+\000$/s) {
2171 printdebug "one subtree $1\n";
2173 printdebug "multiple subtrees\n";
2176 rmtree "_unpack-tar";
2178 my $ent = [ $f, $tree ];
2180 Orig => !!$orig_f_part,
2181 Sort => (!$orig_f_part ? 2 :
2182 $orig_f_part =~ m/-/g ? 1 :
2190 # put any without "_" first (spec is not clear whether files
2191 # are always in the usual order). Tarballs without "_" are
2192 # the main orig or the debian tarball.
2193 $a->{Sort} <=> $b->{Sort} or
2197 my $any_orig = grep { $_->{Orig} } @tartrees;
2199 my $dscfn = "$package.dsc";
2201 my $treeimporthow = 'package';
2203 open D, ">", $dscfn or die "$dscfn: $!";
2204 print D $dscdata or die "$dscfn: $!";
2205 close D or die "$dscfn: $!";
2206 my @cmd = qw(dpkg-source);
2207 push @cmd, '--no-check' if $dsc_checked;
2208 if (madformat $dsc->{format}) {
2209 push @cmd, '--skip-patches';
2210 $treeimporthow = 'unpatched';
2212 push @cmd, qw(-x --), $dscfn;
2215 my ($tree,$dir) = mktree_in_ud_from_only_subdir("source package");
2216 if (madformat $dsc->{format}) {
2217 check_for_vendor_patches();
2221 if (madformat $dsc->{format}) {
2222 my @pcmd = qw(dpkg-source --before-build .);
2223 runcmd shell_cmd 'exec >/dev/null', @pcmd;
2225 $dappliedtree = git_add_write_tree();
2228 my @clogcmd = qw(dpkg-parsechangelog --format rfc822 --all);
2229 debugcmd "|",@clogcmd;
2230 open CLOGS, "-|", @clogcmd or die $!;
2235 printdebug "import clog search...\n";
2238 my $stanzatext = do { local $/=""; <CLOGS>; };
2239 printdebug "import clogp ".Dumper($stanzatext) if $debuglevel>1;
2240 last if !defined $stanzatext;
2242 my $desc = "package changelog, entry no.$.";
2243 open my $stanzafh, "<", \$stanzatext or die;
2244 my $thisstanza = parsecontrolfh $stanzafh, $desc, 1;
2245 $clogp //= $thisstanza;
2247 printdebug "import clog $thisstanza->{version} $desc...\n";
2249 last if !$any_orig; # we don't need $r1clogp
2251 # We look for the first (most recent) changelog entry whose
2252 # version number is lower than the upstream version of this
2253 # package. Then the last (least recent) previous changelog
2254 # entry is treated as the one which introduced this upstream
2255 # version and used for the synthetic commits for the upstream
2258 # One might think that a more sophisticated algorithm would be
2259 # necessary. But: we do not want to scan the whole changelog
2260 # file. Stopping when we see an earlier version, which
2261 # necessarily then is an earlier upstream version, is the only
2262 # realistic way to do that. Then, either the earliest
2263 # changelog entry we have seen so far is indeed the earliest
2264 # upload of this upstream version; or there are only changelog
2265 # entries relating to later upstream versions (which is not
2266 # possible unless the changelog and .dsc disagree about the
2267 # version). Then it remains to choose between the physically
2268 # last entry in the file, and the one with the lowest version
2269 # number. If these are not the same, we guess that the
2270 # versions were created in a non-monotic order rather than
2271 # that the changelog entries have been misordered.
2273 printdebug "import clog $thisstanza->{version} vs $upstreamv...\n";
2275 last if version_compare($thisstanza->{version}, $upstreamv) < 0;
2276 $r1clogp = $thisstanza;
2278 printdebug "import clog $r1clogp->{version} becomes r1\n";
2280 die $! if CLOGS->error;
2281 close CLOGS or $?==SIGPIPE or failedcmd @clogcmd;
2283 $clogp or fail "package changelog has no entries!";
2285 my $authline = clogp_authline $clogp;
2286 my $changes = getfield $clogp, 'Changes';
2287 my $cversion = getfield $clogp, 'Version';
2290 $r1clogp //= $clogp; # maybe there's only one entry;
2291 my $r1authline = clogp_authline $r1clogp;
2292 # Strictly, r1authline might now be wrong if it's going to be
2293 # unused because !$any_orig. Whatever.
2295 printdebug "import tartrees authline $authline\n";
2296 printdebug "import tartrees r1authline $r1authline\n";
2298 foreach my $tt (@tartrees) {
2299 printdebug "import tartree $tt->{F} $tt->{Tree}\n";
2301 $tt->{Commit} = make_commit_text($tt->{Orig} ? <<END_O : <<END_T);
2304 committer $r1authline
2308 [dgit import orig $tt->{F}]
2316 [dgit import tarball $package $cversion $tt->{F}]
2321 printdebug "import main commit\n";
2323 open C, ">../commit.tmp" or die $!;
2324 print C <<END or die $!;
2327 print C <<END or die $! foreach @tartrees;
2330 print C <<END or die $!;
2336 [dgit import $treeimporthow $package $cversion]
2340 my $rawimport_hash = make_commit qw(../commit.tmp);
2342 if (madformat $dsc->{format}) {
2343 printdebug "import apply patches...\n";
2345 # regularise the state of the working tree so that
2346 # the checkout of $rawimport_hash works nicely.
2347 my $dappliedcommit = make_commit_text(<<END);
2354 runcmd @git, qw(checkout -q -b dapplied), $dappliedcommit;
2356 runcmd @git, qw(checkout -q -b unpa), $rawimport_hash;
2358 # We need the answers to be reproducible
2359 my @authline = clogp_authline($clogp);
2360 local $ENV{GIT_COMMITTER_NAME} = $authline[0];
2361 local $ENV{GIT_COMMITTER_EMAIL} = $authline[1];
2362 local $ENV{GIT_COMMITTER_DATE} = $authline[2];
2363 local $ENV{GIT_AUTHOR_NAME} = $authline[0];
2364 local $ENV{GIT_AUTHOR_EMAIL} = $authline[1];
2365 local $ENV{GIT_AUTHOR_DATE} = $authline[2];
2367 my $path = $ENV{PATH} or die;
2369 foreach my $use_absurd (qw(0 1)) {
2370 runcmd @git, qw(checkout -q unpa);
2371 runcmd @git, qw(update-ref -d refs/heads/patch-queue/unpa);
2372 local $ENV{PATH} = $path;
2375 progress "warning: $@";
2376 $path = "$absurdity:$path";
2377 progress "$us: trying slow absurd-git-apply...";
2378 rename "../../gbp-pq-output","../../gbp-pq-output.0"
2383 die "forbid absurd git-apply\n" if $use_absurd
2384 && forceing [qw(import-gitapply-no-absurd)];
2385 die "only absurd git-apply!\n" if !$use_absurd
2386 && forceing [qw(import-gitapply-absurd)];
2388 local $ENV{DGIT_ABSURD_DEBUG} = $debuglevel if $use_absurd;
2389 local $ENV{PATH} = $path if $use_absurd;
2391 my @showcmd = (gbp_pq, qw(import));
2392 my @realcmd = shell_cmd
2393 'exec >/dev/null 2>>../../gbp-pq-output', @showcmd;
2394 debugcmd "+",@realcmd;
2395 if (system @realcmd) {
2396 die +(shellquote @showcmd).
2398 failedcmd_waitstatus()."\n";
2401 my $gapplied = git_rev_parse('HEAD');
2402 my $gappliedtree = cmdoutput @git, qw(rev-parse HEAD:);
2403 $gappliedtree eq $dappliedtree or
2405 gbp-pq import and dpkg-source disagree!
2406 gbp-pq import gave commit $gapplied
2407 gbp-pq import gave tree $gappliedtree
2408 dpkg-source --before-build gave tree $dappliedtree
2410 $rawimport_hash = $gapplied;
2415 { local $@; eval { runcmd qw(cat ../../gbp-pq-output); }; }
2420 progress "synthesised git commit from .dsc $cversion";
2422 my $rawimport_mergeinput = {
2423 Commit => $rawimport_hash,
2424 Info => "Import of source package",
2426 my @output = ($rawimport_mergeinput);
2428 if ($lastpush_mergeinput) {
2429 my $oldclogp = mergeinfo_getclogp($lastpush_mergeinput);
2430 my $oversion = getfield $oldclogp, 'Version';
2432 version_compare($oversion, $cversion);
2434 @output = ($rawimport_mergeinput, $lastpush_mergeinput,
2435 { Message => <<END, ReverseParents => 1 });
2436 Record $package ($cversion) in archive suite $csuite
2438 } elsif ($vcmp > 0) {
2439 print STDERR <<END or die $!;
2441 Version actually in archive: $cversion (older)
2442 Last version pushed with dgit: $oversion (newer or same)
2445 @output = $lastpush_mergeinput;
2447 # Same version. Use what's in the server git branch,
2448 # discarding our own import. (This could happen if the
2449 # server automatically imports all packages into git.)
2450 @output = $lastpush_mergeinput;
2453 changedir '../../../..';
2458 sub complete_file_from_dsc ($$) {
2459 our ($dstdir, $fi) = @_;
2460 # Ensures that we have, in $dir, the file $fi, with the correct
2461 # contents. (Downloading it from alongside $dscurl if necessary.)
2463 my $f = $fi->{Filename};
2464 my $tf = "$dstdir/$f";
2467 if (stat_exists $tf) {
2468 progress "using existing $f";
2470 printdebug "$tf does not exist, need to fetch\n";
2472 $furl =~ s{/[^/]+$}{};
2474 die "$f ?" unless $f =~ m/^\Q${package}\E_/;
2475 die "$f ?" if $f =~ m#/#;
2476 runcmd_ordryrun_local @curl,qw(-f -o),$tf,'--',"$furl";
2477 return 0 if !act_local();
2481 open F, "<", "$tf" or die "$tf: $!";
2482 $fi->{Digester}->reset();
2483 $fi->{Digester}->addfile(*F);
2484 F->error and die $!;
2485 my $got = $fi->{Digester}->hexdigest();
2486 $got eq $fi->{Hash} or
2487 fail "file $f has hash $got but .dsc".
2488 " demands hash $fi->{Hash} ".
2489 ($downloaded ? "(got wrong file from archive!)"
2490 : "(perhaps you should delete this file?)");
2495 sub ensure_we_have_orig () {
2496 my @dfi = dsc_files_info();
2497 foreach my $fi (@dfi) {
2498 my $f = $fi->{Filename};
2499 next unless is_orig_file_in_dsc($f, \@dfi);
2500 complete_file_from_dsc('..', $fi)
2505 sub git_fetch_us () {
2506 # Want to fetch only what we are going to use, unless
2507 # deliberately-not-ff, in which case we must fetch everything.
2509 my @specs = deliberately_not_fast_forward ? qw(tags/*) :
2511 (quiltmode_splitbrain
2512 ? (map { $_->('*',access_nomdistro) }
2513 \&debiantag_new, \&debiantag_maintview)
2514 : debiantags('*',access_nomdistro));
2515 push @specs, server_branch($csuite);
2516 push @specs, qw(heads/*) if deliberately_not_fast_forward;
2518 # This is rather miserable:
2519 # When git fetch --prune is passed a fetchspec ending with a *,
2520 # it does a plausible thing. If there is no * then:
2521 # - it matches subpaths too, even if the supplied refspec
2522 # starts refs, and behaves completely madly if the source
2523 # has refs/refs/something. (See, for example, Debian #NNNN.)
2524 # - if there is no matching remote ref, it bombs out the whole
2526 # We want to fetch a fixed ref, and we don't know in advance
2527 # if it exists, so this is not suitable.
2529 # Our workaround is to use git ls-remote. git ls-remote has its
2530 # own qairks. Notably, it has the absurd multi-tail-matching
2531 # behaviour: git ls-remote R refs/foo can report refs/foo AND
2532 # refs/refs/foo etc.
2534 # Also, we want an idempotent snapshot, but we have to make two
2535 # calls to the remote: one to git ls-remote and to git fetch. The
2536 # solution is use git ls-remote to obtain a target state, and
2537 # git fetch to try to generate it. If we don't manage to generate
2538 # the target state, we try again.
2540 printdebug "git_fetch_us specs @specs\n";
2542 my $specre = join '|', map {
2548 printdebug "git_fetch_us specre=$specre\n";
2549 my $wanted_rref = sub {
2551 return m/^(?:$specre)$/o;
2554 my $fetch_iteration = 0;
2557 printdebug "git_fetch_us iteration $fetch_iteration\n";
2558 if (++$fetch_iteration > 10) {
2559 fail "too many iterations trying to get sane fetch!";
2562 my @look = map { "refs/$_" } @specs;
2563 my @lcmd = (@git, qw(ls-remote -q --refs), access_giturl(), @look);
2567 open GITLS, "-|", @lcmd or die $!;
2569 printdebug "=> ", $_;
2570 m/^(\w+)\s+(\S+)\n/ or die "ls-remote $_ ?";
2571 my ($objid,$rrefname) = ($1,$2);
2572 if (!$wanted_rref->($rrefname)) {
2574 warning: git ls-remote @look reported $rrefname; this is silly, ignoring it.
2578 $wantr{$rrefname} = $objid;
2581 close GITLS or failedcmd @lcmd;
2583 # OK, now %want is exactly what we want for refs in @specs
2585 !m/\*$/ && !exists $wantr{"refs/$_"} ? () :
2586 "+refs/$_:".lrfetchrefs."/$_";
2589 printdebug "git_fetch_us fspecs @fspecs\n";
2591 my @fcmd = (@git, qw(fetch -p -n -q), access_giturl(), @fspecs);
2592 runcmd_ordryrun_local @git, qw(fetch -p -n -q), access_giturl(),
2595 %lrfetchrefs_f = ();
2598 git_for_each_ref(lrfetchrefs, sub {
2599 my ($objid,$objtype,$lrefname,$reftail) = @_;
2600 $lrfetchrefs_f{$lrefname} = $objid;
2601 $objgot{$objid} = 1;
2604 foreach my $lrefname (sort keys %lrfetchrefs_f) {
2605 my $rrefname = 'refs'.substr($lrefname, length lrfetchrefs);
2606 if (!exists $wantr{$rrefname}) {
2607 if ($wanted_rref->($rrefname)) {
2609 git-fetch @fspecs created $lrefname which git ls-remote @look didn't list.
2613 warning: git fetch @fspecs created $lrefname; this is silly, deleting it.
2616 runcmd_ordryrun_local @git, qw(update-ref -d), $lrefname;
2617 delete $lrfetchrefs_f{$lrefname};
2621 foreach my $rrefname (sort keys %wantr) {
2622 my $lrefname = lrfetchrefs.substr($rrefname, 4);
2623 my $got = $lrfetchrefs_f{$lrefname} // '<none>';
2624 my $want = $wantr{$rrefname};
2625 next if $got eq $want;
2626 if (!defined $objgot{$want}) {
2628 warning: git ls-remote suggests we want $lrefname
2629 warning: and it should refer to $want
2630 warning: but git fetch didn't fetch that object to any relevant ref.
2631 warning: This may be due to a race with someone updating the server.
2632 warning: Will try again...
2634 next FETCH_ITERATION;
2637 git-fetch @fspecs made $lrefname=$got but want git ls-remote @look says $want
2639 runcmd_ordryrun_local @git, qw(update-ref -m),
2640 "dgit fetch git fetch fixup", $lrefname, $want;
2641 $lrfetchrefs_f{$lrefname} = $want;
2645 printdebug "git_fetch_us: git fetch --no-insane emulation complete\n",
2646 Dumper(\%lrfetchrefs_f);
2649 my @tagpats = debiantags('*',access_nomdistro);
2651 git_for_each_ref([map { "refs/tags/$_" } @tagpats], sub {
2652 my ($objid,$objtype,$fullrefname,$reftail) = @_;
2653 printdebug "currently $fullrefname=$objid\n";
2654 $here{$fullrefname} = $objid;
2656 git_for_each_ref([map { lrfetchrefs."/tags/".$_ } @tagpats], sub {
2657 my ($objid,$objtype,$fullrefname,$reftail) = @_;
2658 my $lref = "refs".substr($fullrefname, length(lrfetchrefs));
2659 printdebug "offered $lref=$objid\n";
2660 if (!defined $here{$lref}) {
2661 my @upd = (@git, qw(update-ref), $lref, $objid, '');
2662 runcmd_ordryrun_local @upd;
2663 lrfetchref_used $fullrefname;
2664 } elsif ($here{$lref} eq $objid) {
2665 lrfetchref_used $fullrefname;
2668 "Not updateting $lref from $here{$lref} to $objid.\n";
2673 sub mergeinfo_getclogp ($) {
2674 # Ensures thit $mi->{Clogp} exists and returns it
2676 $mi->{Clogp} = commit_getclogp($mi->{Commit});
2679 sub mergeinfo_version ($) {
2680 return getfield( (mergeinfo_getclogp $_[0]), 'Version' );
2683 sub fetch_from_archive_record_1 ($) {
2685 runcmd @git, qw(update-ref -m), "dgit fetch $csuite",
2686 'DGIT_ARCHIVE', $hash;
2687 cmdoutput @git, qw(log -n2), $hash;
2688 # ... gives git a chance to complain if our commit is malformed
2691 sub fetch_from_archive_record_2 ($) {
2693 my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
2697 dryrun_report @upd_cmd;
2701 sub fetch_from_archive () {
2702 ensure_setup_existing_tree();
2704 # Ensures that lrref() is what is actually in the archive, one way
2705 # or another, according to us - ie this client's
2706 # appropritaely-updated archive view. Also returns the commit id.
2707 # If there is nothing in the archive, leaves lrref alone and
2708 # returns undef. git_fetch_us must have already been called.
2712 foreach my $field (@ourdscfield) {
2713 $dsc_hash = $dsc->{$field};
2714 last if defined $dsc_hash;
2716 if (defined $dsc_hash) {
2717 $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
2719 progress "last upload to archive specified git hash";
2721 progress "last upload to archive has NO git hash";
2724 progress "no version available from the archive";
2727 # If the archive's .dsc has a Dgit field, there are three
2728 # relevant git commitids we need to choose between and/or merge
2730 # 1. $dsc_hash: the Dgit field from the archive
2731 # 2. $lastpush_hash: the suite branch on the dgit git server
2732 # 3. $lastfetch_hash: our local tracking brach for the suite
2734 # These may all be distinct and need not be in any fast forward
2737 # If the dsc was pushed to this suite, then the server suite
2738 # branch will have been updated; but it might have been pushed to
2739 # a different suite and copied by the archive. Conversely a more
2740 # recent version may have been pushed with dgit but not appeared
2741 # in the archive (yet).
2743 # $lastfetch_hash may be awkward because archive imports
2744 # (particularly, imports of Dgit-less .dscs) are performed only as
2745 # needed on individual clients, so different clients may perform a
2746 # different subset of them - and these imports are only made
2747 # public during push. So $lastfetch_hash may represent a set of
2748 # imports different to a subsequent upload by a different dgit
2751 # Our approach is as follows:
2753 # As between $dsc_hash and $lastpush_hash: if $lastpush_hash is a
2754 # descendant of $dsc_hash, then it was pushed by a dgit user who
2755 # had based their work on $dsc_hash, so we should prefer it.
2756 # Otherwise, $dsc_hash was installed into this suite in the
2757 # archive other than by a dgit push, and (necessarily) after the
2758 # last dgit push into that suite (since a dgit push would have
2759 # been descended from the dgit server git branch); thus, in that
2760 # case, we prefer the archive's version (and produce a
2761 # pseudo-merge to overwrite the dgit server git branch).
2763 # (If there is no Dgit field in the archive's .dsc then
2764 # generate_commit_from_dsc uses the version numbers to decide
2765 # whether the suite branch or the archive is newer. If the suite
2766 # branch is newer it ignores the archive's .dsc; otherwise it
2767 # generates an import of the .dsc, and produces a pseudo-merge to
2768 # overwrite the suite branch with the archive contents.)
2770 # The outcome of that part of the algorithm is the `public view',
2771 # and is same for all dgit clients: it does not depend on any
2772 # unpublished history in the local tracking branch.
2774 # As between the public view and the local tracking branch: The
2775 # local tracking branch is only updated by dgit fetch, and
2776 # whenever dgit fetch runs it includes the public view in the
2777 # local tracking branch. Therefore if the public view is not
2778 # descended from the local tracking branch, the local tracking
2779 # branch must contain history which was imported from the archive
2780 # but never pushed; and, its tip is now out of date. So, we make
2781 # a pseudo-merge to overwrite the old imports and stitch the old
2784 # Finally: we do not necessarily reify the public view (as
2785 # described above). This is so that we do not end up stacking two
2786 # pseudo-merges. So what we actually do is figure out the inputs
2787 # to any public view pseudo-merge and put them in @mergeinputs.
2790 # $mergeinputs[]{Commit}
2791 # $mergeinputs[]{Info}
2792 # $mergeinputs[0] is the one whose tree we use
2793 # @mergeinputs is in the order we use in the actual commit)
2796 # $mergeinputs[]{Message} is a commit message to use
2797 # $mergeinputs[]{ReverseParents} if def specifies that parent
2798 # list should be in opposite order
2799 # Such an entry has no Commit or Info. It applies only when found
2800 # in the last entry. (This ugliness is to support making
2801 # identical imports to previous dgit versions.)
2803 my $lastpush_hash = git_get_ref(lrfetchref());
2804 printdebug "previous reference hash=$lastpush_hash\n";
2805 $lastpush_mergeinput = $lastpush_hash && {
2806 Commit => $lastpush_hash,
2807 Info => "dgit suite branch on dgit git server",
2810 my $lastfetch_hash = git_get_ref(lrref());
2811 printdebug "fetch_from_archive: lastfetch=$lastfetch_hash\n";
2812 my $lastfetch_mergeinput = $lastfetch_hash && {
2813 Commit => $lastfetch_hash,
2814 Info => "dgit client's archive history view",
2817 my $dsc_mergeinput = $dsc_hash && {
2818 Commit => $dsc_hash,
2819 Info => "Dgit field in .dsc from archive",
2823 my $del_lrfetchrefs = sub {
2826 printdebug "del_lrfetchrefs...\n";
2827 foreach my $fullrefname (sort keys %lrfetchrefs_d) {
2828 my $objid = $lrfetchrefs_d{$fullrefname};
2829 printdebug "del_lrfetchrefs: $objid $fullrefname\n";
2831 $gur ||= new IO::Handle;
2832 open $gur, "|-", qw(git update-ref --stdin) or die $!;
2834 printf $gur "delete %s %s\n", $fullrefname, $objid;
2837 close $gur or failedcmd "git update-ref delete lrfetchrefs";
2841 if (defined $dsc_hash) {
2842 ensure_we_have_orig();
2843 if (!$lastpush_hash || $dsc_hash eq $lastpush_hash) {
2844 @mergeinputs = $dsc_mergeinput
2845 } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
2846 print STDERR <<END or die $!;
2848 Git commit in archive is behind the last version allegedly pushed/uploaded.
2849 Commit referred to by archive: $dsc_hash
2850 Last version pushed with dgit: $lastpush_hash
2853 @mergeinputs = ($lastpush_mergeinput);
2855 # Archive has .dsc which is not a descendant of the last dgit
2856 # push. This can happen if the archive moves .dscs about.
2857 # Just follow its lead.
2858 if (is_fast_fwd($lastpush_hash,$dsc_hash)) {
2859 progress "archive .dsc names newer git commit";
2860 @mergeinputs = ($dsc_mergeinput);
2862 progress "archive .dsc names other git commit, fixing up";
2863 @mergeinputs = ($dsc_mergeinput, $lastpush_mergeinput);
2867 @mergeinputs = generate_commits_from_dsc();
2868 # We have just done an import. Now, our import algorithm might
2869 # have been improved. But even so we do not want to generate
2870 # a new different import of the same package. So if the
2871 # version numbers are the same, just use our existing version.
2872 # If the version numbers are different, the archive has changed
2873 # (perhaps, rewound).
2874 if ($lastfetch_mergeinput &&
2875 !version_compare( (mergeinfo_version $lastfetch_mergeinput),
2876 (mergeinfo_version $mergeinputs[0]) )) {
2877 @mergeinputs = ($lastfetch_mergeinput);
2879 } elsif ($lastpush_hash) {
2880 # only in git, not in the archive yet
2881 @mergeinputs = ($lastpush_mergeinput);
2882 print STDERR <<END or die $!;
2884 Package not found in the archive, but has allegedly been pushed using dgit.
2888 printdebug "nothing found!\n";
2889 if (defined $skew_warning_vsn) {
2890 print STDERR <<END or die $!;
2892 Warning: relevant archive skew detected.
2893 Archive allegedly contains $skew_warning_vsn
2894 But we were not able to obtain any version from the archive or git.
2898 unshift @end, $del_lrfetchrefs;
2902 if ($lastfetch_hash &&
2904 my $h = $_->{Commit};
2905 $h and is_fast_fwd($lastfetch_hash, $h);
2906 # If true, one of the existing parents of this commit
2907 # is a descendant of the $lastfetch_hash, so we'll
2908 # be ff from that automatically.
2912 push @mergeinputs, $lastfetch_mergeinput;
2915 printdebug "fetch mergeinfos:\n";
2916 foreach my $mi (@mergeinputs) {
2918 printdebug " commit $mi->{Commit} $mi->{Info}\n";
2920 printdebug sprintf " ReverseParents=%d Message=%s",
2921 $mi->{ReverseParents}, $mi->{Message};
2925 my $compat_info= pop @mergeinputs
2926 if $mergeinputs[$#mergeinputs]{Message};
2928 @mergeinputs = grep { defined $_->{Commit} } @mergeinputs;
2931 if (@mergeinputs > 1) {
2933 my $tree_commit = $mergeinputs[0]{Commit};
2935 my $tree = cmdoutput @git, qw(cat-file commit), $tree_commit;
2936 $tree =~ m/\n\n/; $tree = $`;
2937 $tree =~ m/^tree (\w+)$/m or die "$dsc_hash tree ?";
2940 # We use the changelog author of the package in question the
2941 # author of this pseudo-merge. This is (roughly) correct if
2942 # this commit is simply representing aa non-dgit upload.
2943 # (Roughly because it does not record sponsorship - but we
2944 # don't have sponsorship info because that's in the .changes,
2945 # which isn't in the archivw.)
2947 # But, it might be that we are representing archive history
2948 # updates (including in-archive copies). These are not really
2949 # the responsibility of the person who created the .dsc, but
2950 # there is no-one whose name we should better use. (The
2951 # author of the .dsc-named commit is clearly worse.)
2953 my $useclogp = mergeinfo_getclogp $mergeinputs[0];
2954 my $author = clogp_authline $useclogp;
2955 my $cversion = getfield $useclogp, 'Version';
2957 my $mcf = ".git/dgit/mergecommit";
2958 open MC, ">", $mcf or die "$mcf $!";
2959 print MC <<END or die $!;
2963 my @parents = grep { $_->{Commit} } @mergeinputs;
2964 @parents = reverse @parents if $compat_info->{ReverseParents};
2965 print MC <<END or die $! foreach @parents;
2969 print MC <<END or die $!;
2975 if (defined $compat_info->{Message}) {
2976 print MC $compat_info->{Message} or die $!;
2978 print MC <<END or die $!;
2979 Record $package ($cversion) in archive suite $csuite
2983 my $message_add_info = sub {
2985 my $mversion = mergeinfo_version $mi;
2986 printf MC " %-20s %s\n", $mversion, $mi->{Info}
2990 $message_add_info->($mergeinputs[0]);
2991 print MC <<END or die $!;
2992 should be treated as descended from
2994 $message_add_info->($_) foreach @mergeinputs[1..$#mergeinputs];
2998 $hash = make_commit $mcf;
3000 $hash = $mergeinputs[0]{Commit};
3002 printdebug "fetch hash=$hash\n";
3005 my ($lasth, $what) = @_;
3006 return unless $lasth;
3007 die "$lasth $hash $what ?" unless is_fast_fwd($lasth, $hash);
3010 $chkff->($lastpush_hash, 'dgit repo server tip (last push)')
3012 $chkff->($lastfetch_hash, 'local tracking tip (last fetch)');
3014 fetch_from_archive_record_1($hash);
3016 if (defined $skew_warning_vsn) {
3018 printdebug "SKEW CHECK WANT $skew_warning_vsn\n";
3019 my $gotclogp = commit_getclogp($hash);
3020 my $got_vsn = getfield $gotclogp, 'Version';
3021 printdebug "SKEW CHECK GOT $got_vsn\n";
3022 if (version_compare($got_vsn, $skew_warning_vsn) < 0) {
3023 print STDERR <<END or die $!;
3025 Warning: archive skew detected. Using the available version:
3026 Archive allegedly contains $skew_warning_vsn
3027 We were able to obtain only $got_vsn
3033 if ($lastfetch_hash ne $hash) {
3034 fetch_from_archive_record_2($hash);
3037 lrfetchref_used lrfetchref();
3039 unshift @end, $del_lrfetchrefs;
3043 sub set_local_git_config ($$) {
3045 runcmd @git, qw(config), $k, $v;
3048 sub setup_mergechangelogs (;$) {
3050 return unless $always || access_cfg_bool(1, 'setup-mergechangelogs');
3052 my $driver = 'dpkg-mergechangelogs';
3053 my $cb = "merge.$driver";
3054 my $attrs = '.git/info/attributes';
3055 ensuredir '.git/info';
3057 open NATTRS, ">", "$attrs.new" or die "$attrs.new $!";
3058 if (!open ATTRS, "<", $attrs) {
3059 $!==ENOENT or die "$attrs: $!";
3063 next if m{^debian/changelog\s};
3064 print NATTRS $_, "\n" or die $!;
3066 ATTRS->error and die $!;
3069 print NATTRS "debian/changelog merge=$driver\n" or die $!;
3072 set_local_git_config "$cb.name", 'debian/changelog merge driver';
3073 set_local_git_config "$cb.driver", 'dpkg-mergechangelogs -m %O %A %B %A';
3075 rename "$attrs.new", "$attrs" or die "$attrs: $!";
3078 sub setup_useremail (;$) {
3080 return unless $always || access_cfg_bool(1, 'setup-useremail');
3083 my ($k, $envvar) = @_;
3084 my $v = access_cfg("user-$k", 'RETURN-UNDEF') // $ENV{$envvar};
3085 return unless defined $v;
3086 set_local_git_config "user.$k", $v;
3089 $setup->('email', 'DEBEMAIL');
3090 $setup->('name', 'DEBFULLNAME');
3093 sub ensure_setup_existing_tree () {
3094 my $k = "remote.$remotename.skipdefaultupdate";
3095 my $c = git_get_config $k;
3096 return if defined $c;
3097 set_local_git_config $k, 'true';
3100 sub setup_new_tree () {
3101 setup_mergechangelogs();
3105 sub multisuite_suite_child ($$$) {
3106 my ($tsuite, $merginputs, $fn) = @_;
3107 # in child, sets things up, calls $fn->(), and returns undef
3108 # in parent, returns canonical suite name for $tsuite
3109 my $canonsuitefh = IO::File::new_tmpfile;
3110 my $pid = fork // die $!;
3113 $us .= " [$isuite]";
3114 $debugprefix .= " ";
3115 progress "fetching $tsuite...";
3116 canonicalise_suite();
3117 print $canonsuitefh $csuite, "\n" or die $!;
3118 close $canonsuitefh or die $!;
3122 waitpid $pid,0 == $pid or die $!;
3123 fail "failed to obtain $tsuite: ".waitstatusmsg() if $? && $?!=256*4;
3124 seek $canonsuitefh,0,0 or die $!;
3125 local $csuite = <$canonsuitefh>;
3126 die $! unless defined $csuite && chomp $csuite;
3128 printdebug "multisuite $tsuite missing\n";
3131 printdebug "multisuite $tsuite ok (canon=$csuite)\n";
3132 push @$merginputs, {
3139 sub fork_for_multisuite ($) {
3140 my ($before_fetch_merge) = @_;
3141 # if nothing unusual, just returns ''
3144 # returns 0 to caller in child, to do first of the specified suites
3145 # in child, $csuite is not yet set
3147 # returns 1 to caller in parent, to finish up anything needed after
3148 # in parent, $csuite is set to canonicalised portmanteau
3150 my $org_isuite = $isuite;
3151 my @suites = split /\,/, $isuite;
3152 return '' unless @suites > 1;
3153 printdebug "fork_for_multisuite: @suites\n";
3157 my $cbasesuite = multisuite_suite_child($suites[0], \@mergeinputs,
3159 return 0 unless defined $cbasesuite;
3161 fail "package $package missing in (base suite) $cbasesuite"
3162 unless @mergeinputs;
3164 my @csuites = ($cbasesuite);
3166 $before_fetch_merge->();
3168 foreach my $tsuite (@suites[1..$#suites]) {
3169 my $csubsuite = multisuite_suite_child($tsuite, \@mergeinputs,
3175 # xxx collecte the ref here
3177 $csubsuite =~ s/^\Q$cbasesuite\E-/-/;
3178 push @csuites, $csubsuite;
3181 foreach my $mi (@mergeinputs) {
3182 my $ref = git_get_ref $mi->{Ref};
3183 die "$mi->{Ref} ?" unless length $ref;
3184 $mi->{Commit} = $ref;
3187 $csuite = join ",", @csuites;
3189 my $previous = git_get_ref lrref;
3191 unshift @mergeinputs, {
3192 Commit => $previous,
3193 Info => "local combined tracking branch",
3195 "archive seems to have rewound: local tracking branch is ahead!",
3199 foreach my $ix (0..$#mergeinputs) {
3200 $mergeinputs[$ix]{Index} = $ix;
3203 @mergeinputs = sort {
3204 -version_compare(mergeinfo_version $a,
3205 mergeinfo_version $b) # highest version first
3207 $a->{Index} <=> $b->{Index}; # earliest in spec first
3213 foreach my $mi (@mergeinputs) {
3214 printdebug "multisuite merge check $mi->{Info}\n";
3215 foreach my $previous (@needed) {
3216 next unless is_fast_fwd $mi->{Commit}, $previous->{Commit};
3217 printdebug "multisuite merge un-needed $previous->{Info}\n";
3221 printdebug "multisuite merge this-needed\n";
3222 $mi->{Character} = '+';
3225 $needed[0]{Character} = '*';
3227 my $output = $needed[0]{Commit};
3230 printdebug "multisuite merge nontrivial\n";
3231 my $tree = cmdoutput qw(git rev-parse), $needed[0]{Commit}.':';
3233 my $commit = "tree $tree\n";
3234 my $msg = "Combine archive branches $csuite [dgit]\n\n".
3235 "Input branches:\n";
3237 foreach my $mi (sort { $a->{Index} <=> $b->{Index} } @mergeinputs) {
3238 printdebug "multisuite merge include $mi->{Info}\n";
3239 $mi->{Character} //= ' ';
3240 $commit .= "parent $mi->{Commit}\n";
3241 $msg .= sprintf " %s %-25s %s\n",
3243 (mergeinfo_version $mi),
3246 my $authline = clogp_authline mergeinfo_getclogp $needed[0];
3248 " * marks the highest version branch, which choose to use\n".
3249 " + marks each branch which was not already an ancestor\n\n".
3250 "[dgit multi-suite $csuite]\n";
3252 "author $authline\n".
3253 "committer $authline\n\n";
3254 $output = make_commit_text $commit.$msg;
3255 printdebug "multisuite merge generated $output\n";
3258 fetch_from_archive_record_1($output);
3259 fetch_from_archive_record_2($output);
3261 progress "calculated combined tracking suite $csuite";
3266 sub clone_set_head () {
3267 open H, "> .git/HEAD" or die $!;
3268 print H "ref: ".lref()."\n" or die $!;
3271 sub clone_finish ($) {
3273 runcmd @git, qw(reset --hard), lrref();
3274 runcmd qw(bash -ec), <<'END';
3276 git ls-tree -r --name-only -z HEAD | \
3277 xargs -0r touch -h -r . --
3279 printdone "ready for work in $dstdir";
3284 badusage "dry run makes no sense with clone" unless act_local();
3286 my $multi_fetched = fork_for_multisuite(sub {
3287 printdebug "multi clone before fetch merge\n";
3290 if ($multi_fetched) {
3291 printdebug "multi clone after fetch merge\n";
3293 clone_finish($dstdir);
3296 printdebug "clone main body\n";
3298 canonicalise_suite();
3299 my $hasgit = check_for_git();
3300 mkdir $dstdir or fail "create \`$dstdir': $!";
3302 runcmd @git, qw(init -q);
3304 my $giturl = access_giturl(1);
3305 if (defined $giturl) {
3306 runcmd @git, qw(remote add), 'origin', $giturl;
3309 progress "fetching existing git history";
3311 runcmd_ordryrun_local @git, qw(fetch origin);
3313 progress "starting new git history";
3315 fetch_from_archive() or no_such_package;
3316 my $vcsgiturl = $dsc->{'Vcs-Git'};
3317 if (length $vcsgiturl) {
3318 $vcsgiturl =~ s/\s+-b\s+\S+//g;
3319 runcmd @git, qw(remote add vcs-git), $vcsgiturl;
3322 clone_finish($dstdir);
3326 canonicalise_suite();
3327 if (check_for_git()) {
3330 fetch_from_archive() or no_such_package();
3331 printdone "fetched into ".lrref();
3335 my $multi_fetched = fork_for_multisuite(sub { });
3336 fetch() unless $multi_fetched; # parent
3337 return if $multi_fetched eq '0'; # child
3338 runcmd_ordryrun_local @git, qw(merge -m),"Merge from $csuite [dgit]",
3340 printdone "fetched to ".lrref()." and merged into HEAD";
3343 sub check_not_dirty () {
3344 foreach my $f (qw(local-options local-patch-header)) {
3345 if (stat_exists "debian/source/$f") {
3346 fail "git tree contains debian/source/$f";
3350 return if $ignoredirty;
3352 my @cmd = (@git, qw(diff --quiet HEAD));
3354 $!=0; $?=-1; system @cmd;
3357 fail "working tree is dirty (does not match HEAD)";
3363 sub commit_admin ($) {
3366 runcmd_ordryrun_local @git, qw(commit -m), $m;
3369 sub commit_quilty_patch () {
3370 my $output = cmdoutput @git, qw(status --porcelain);
3372 foreach my $l (split /\n/, $output) {
3373 next unless $l =~ m/\S/;
3374 if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
3378 delete $adds{'.pc'}; # if there wasn't one before, don't add it
3380 progress "nothing quilty to commit, ok.";
3383 my @adds = map { s/[][*?\\]/\\$&/g; $_; } sort keys %adds;
3384 runcmd_ordryrun_local @git, qw(add -f), @adds;
3386 Commit Debian 3.0 (quilt) metadata
3388 [dgit ($our_version) quilt-fixup]
3392 sub get_source_format () {
3394 if (open F, "debian/source/options") {
3398 s/\s+$//; # ignore missing final newline
3400 my ($k, $v) = ($`, $'); #');
3401 $v =~ s/^"(.*)"$/$1/;
3407 F->error and die $!;
3410 die $! unless $!==&ENOENT;
3413 if (!open F, "debian/source/format") {
3414 die $! unless $!==&ENOENT;
3418 F->error and die $!;
3420 return ($_, \%options);
3423 sub madformat_wantfixup ($) {
3425 return 0 unless $format eq '3.0 (quilt)';
3426 our $quilt_mode_warned;
3427 if ($quilt_mode eq 'nocheck') {
3428 progress "Not doing any fixup of \`$format' due to".
3429 " ----no-quilt-fixup or --quilt=nocheck"
3430 unless $quilt_mode_warned++;
3433 progress "Format \`$format', need to check/update patch stack"
3434 unless $quilt_mode_warned++;
3438 sub maybe_split_brain_save ($$$) {
3439 my ($headref, $dgitview, $msg) = @_;
3440 # => message fragment "$saved" describing disposition of $dgitview
3441 return "commit id $dgitview" unless defined $split_brain_save;
3442 my @cmd = (shell_cmd "cd ../../../..",
3443 @git, qw(update-ref -m),
3444 "dgit --dgit-view-save $msg HEAD=$headref",
3445 $split_brain_save, $dgitview);
3447 return "and left in $split_brain_save";
3450 # An "infopair" is a tuple [ $thing, $what ]
3451 # (often $thing is a commit hash; $what is a description)
3453 sub infopair_cond_equal ($$) {
3455 $x->[0] eq $y->[0] or fail <<END;
3456 $x->[1] ($x->[0]) not equal to $y->[1] ($y->[0])
3460 sub infopair_lrf_tag_lookup ($$) {
3461 my ($tagnames, $what) = @_;
3462 # $tagname may be an array ref
3463 my @tagnames = ref $tagnames ? @$tagnames : ($tagnames);
3464 printdebug "infopair_lrfetchref_tag_lookup $what @tagnames\n";
3465 foreach my $tagname (@tagnames) {
3466 my $lrefname = lrfetchrefs."/tags/$tagname";
3467 my $tagobj = $lrfetchrefs_f{$lrefname};
3468 next unless defined $tagobj;
3469 printdebug "infopair_lrfetchref_tag_lookup $tagobj $tagname $what\n";
3470 return [ git_rev_parse($tagobj), $what ];
3472 fail @tagnames==1 ? <<END : <<END;
3473 Wanted tag $what (@tagnames) on dgit server, but not found
3475 Wanted tag $what (one of: @tagnames) on dgit server, but not found
3479 sub infopair_cond_ff ($$) {
3480 my ($anc,$desc) = @_;
3481 is_fast_fwd($anc->[0], $desc->[0]) or fail <<END;
3482 $anc->[1] ($anc->[0]) .. $desc->[1] ($desc->[0]) is not fast forward
3486 sub pseudomerge_version_check ($$) {
3487 my ($clogp, $archive_hash) = @_;
3489 my $arch_clogp = commit_getclogp $archive_hash;
3490 my $i_arch_v = [ (getfield $arch_clogp, 'Version'),
3491 'version currently in archive' ];
3492 if (defined $overwrite_version) {
3493 if (length $overwrite_version) {
3494 infopair_cond_equal([ $overwrite_version,
3495 '--overwrite= version' ],
3498 my $v = $i_arch_v->[0];
3499 progress "Checking package changelog for archive version $v ...";
3501 my @xa = ("-f$v", "-t$v");
3502 my $vclogp = parsechangelog @xa;
3503 my $cv = [ (getfield $vclogp, 'Version'),
3504 "Version field from dpkg-parsechangelog @xa" ];
3505 infopair_cond_equal($i_arch_v, $cv);
3508 $@ =~ s/^dgit: //gm;
3510 "Perhaps debian/changelog does not mention $v ?";
3515 printdebug "pseudomerge_version_check i_arch_v @$i_arch_v\n";
3519 sub pseudomerge_make_commit ($$$$ $$) {
3520 my ($clogp, $dgitview, $archive_hash, $i_arch_v,
3521 $msg_cmd, $msg_msg) = @_;
3522 progress "Declaring that HEAD inciudes all changes in $i_arch_v->[0]...";
3524 my $tree = cmdoutput qw(git rev-parse), "${dgitview}:";
3525 my $authline = clogp_authline $clogp;
3529 !defined $overwrite_version ? ""
3530 : !length $overwrite_version ? " --overwrite"
3531 : " --overwrite=".$overwrite_version;
3534 my $pmf = ".git/dgit/pseudomerge";
3535 open MC, ">", $pmf or die "$pmf $!";
3536 print MC <<END or die $!;
3539 parent $archive_hash
3549 return make_commit($pmf);
3552 sub splitbrain_pseudomerge ($$$$) {
3553 my ($clogp, $maintview, $dgitview, $archive_hash) = @_;
3554 # => $merged_dgitview
3555 printdebug "splitbrain_pseudomerge...\n";
3557 # We: debian/PREVIOUS HEAD($maintview)
3558 # expect: o ----------------- o
3561 # a/d/PREVIOUS $dgitview
3564 # we do: `------------------ o
3568 return $dgitview unless defined $archive_hash;
3570 printdebug "splitbrain_pseudomerge...\n";
3572 my $i_arch_v = pseudomerge_version_check($clogp, $archive_hash);
3574 if (!defined $overwrite_version) {
3575 progress "Checking that HEAD inciudes all changes in archive...";
3578 return $dgitview if is_fast_fwd $archive_hash, $dgitview;
3580 if (defined $overwrite_version) {
3582 my $t_dep14 = debiantag_maintview $i_arch_v->[0], access_nomdistro;
3583 my $i_dep14 = infopair_lrf_tag_lookup($t_dep14, "maintainer view tag");
3584 my $t_dgit = debiantag_new $i_arch_v->[0], access_nomdistro;
3585 my $i_dgit = infopair_lrf_tag_lookup($t_dgit, "dgit view tag");
3586 my $i_archive = [ $archive_hash, "current archive contents" ];
3588 printdebug "splitbrain_pseudomerge i_archive @$i_archive\n";
3590 infopair_cond_equal($i_dgit, $i_archive);
3591 infopair_cond_ff($i_dep14, $i_dgit);
3592 infopair_cond_ff($i_dep14, [ $maintview, 'HEAD' ]);
3596 $us: check failed (maybe --overwrite is needed, consult documentation)
3601 my $r = pseudomerge_make_commit
3602 $clogp, $dgitview, $archive_hash, $i_arch_v,
3603 "dgit --quilt=$quilt_mode",
3604 (defined $overwrite_version ? <<END_OVERWR : <<END_MAKEFF);
3605 Declare fast forward from $i_arch_v->[0]
3607 Make fast forward from $i_arch_v->[0]
3610 maybe_split_brain_save $maintview, $r, "pseudomerge";
3612 progress "Made pseudo-merge of $i_arch_v->[0] into dgit view.";
3616 sub plain_overwrite_pseudomerge ($$$) {
3617 my ($clogp, $head, $archive_hash) = @_;
3619 printdebug "plain_overwrite_pseudomerge...";
3621 my $i_arch_v = pseudomerge_version_check($clogp, $archive_hash);
3623 return $head if is_fast_fwd $archive_hash, $head;
3625 my $m = "Declare fast forward from $i_arch_v->[0]";
3627 my $r = pseudomerge_make_commit
3628 $clogp, $head, $archive_hash, $i_arch_v,
3631 runcmd @git, qw(update-ref -m), $m, 'HEAD', $r, $head;
3633 progress "Make pseudo-merge of $i_arch_v->[0] into your HEAD.";
3637 sub push_parse_changelog ($) {
3640 my $clogp = Dpkg::Control::Hash->new();
3641 $clogp->load($clogpfn) or die;
3643 my $clogpackage = getfield $clogp, 'Source';
3644 $package //= $clogpackage;
3645 fail "-p specified $package but changelog specified $clogpackage"
3646 unless $package eq $clogpackage;
3647 my $cversion = getfield $clogp, 'Version';
3648 my $tag = debiantag($cversion, access_nomdistro);
3649 runcmd @git, qw(check-ref-format), $tag;
3651 my $dscfn = dscfn($cversion);
3653 return ($clogp, $cversion, $dscfn);
3656 sub push_parse_dsc ($$$) {
3657 my ($dscfn,$dscfnwhat, $cversion) = @_;
3658 $dsc = parsecontrol($dscfn,$dscfnwhat);
3659 my $dversion = getfield $dsc, 'Version';
3660 my $dscpackage = getfield $dsc, 'Source';
3661 ($dscpackage eq $package && $dversion eq $cversion) or
3662 fail "$dscfn is for $dscpackage $dversion".
3663 " but debian/changelog is for $package $cversion";
3666 sub push_tagwants ($$$$) {
3667 my ($cversion, $dgithead, $maintviewhead, $tfbase) = @_;
3670 TagFn => \&debiantag,
3675 if (defined $maintviewhead) {
3677 TagFn => \&debiantag_maintview,
3678 Objid => $maintviewhead,
3679 TfSuffix => '-maintview',
3682 } elsif ($dodep14tag eq 'no' ? 0
3683 : $dodep14tag eq 'want' ? access_cfg_tagformats_can_splitbrain
3684 : $dodep14tag eq 'always'
3685 ? (access_cfg_tagformats_can_splitbrain or fail <<END)
3686 --dep14tag-always (or equivalent in config) means server must support
3687 both "new" and "maint" tag formats, but config says it doesn't.
3689 : die "$dodep14tag ?") {
3691 TagFn => \&debiantag_maintview,
3693 TfSuffix => '-dgit',
3697 foreach my $tw (@tagwants) {
3698 $tw->{Tag} = $tw->{TagFn}($cversion, access_nomdistro);
3699 $tw->{Tfn} = sub { $tfbase.$tw->{TfSuffix}.$_[0]; };
3701 printdebug 'push_tagwants: ', Dumper(\@_, \@tagwants);
3705 sub push_mktags ($$ $$ $) {
3707 $changesfile,$changesfilewhat,
3710 die unless $tagwants->[0]{View} eq 'dgit';
3712 $dsc->{$ourdscfield[0]} = $tagwants->[0]{Objid};
3713 $dsc->save("$dscfn.tmp") or die $!;
3715 my $changes = parsecontrol($changesfile,$changesfilewhat);
3716 foreach my $field (qw(Source Distribution Version)) {
3717 $changes->{$field} eq $clogp->{$field} or
3718 fail "changes field $field \`$changes->{$field}'".
3719 " does not match changelog \`$clogp->{$field}'";
3722 my $cversion = getfield $clogp, 'Version';
3723 my $clogsuite = getfield $clogp, 'Distribution';
3725 # We make the git tag by hand because (a) that makes it easier
3726 # to control the "tagger" (b) we can do remote signing
3727 my $authline = clogp_authline $clogp;
3728 my $delibs = join(" ", "",@deliberatelies);
3729 my $declaredistro = access_nomdistro();
3733 my $tfn = $tw->{Tfn};
3734 my $head = $tw->{Objid};
3735 my $tag = $tw->{Tag};
3737 open TO, '>', $tfn->('.tmp') or die $!;
3738 print TO <<END or die $!;
3745 if ($tw->{View} eq 'dgit') {
3746 print TO <<END or die $!;
3747 $package release $cversion for $clogsuite ($csuite) [dgit]
3748 [dgit distro=$declaredistro$delibs]
3750 foreach my $ref (sort keys %previously) {
3751 print TO <<END or die $!;
3752 [dgit previously:$ref=$previously{$ref}]
3755 } elsif ($tw->{View} eq 'maint') {
3756 print TO <<END or die $!;
3757 $package release $cversion for $clogsuite ($csuite)
3758 (maintainer view tag generated by dgit --quilt=$quilt_mode)
3761 die Dumper($tw)."?";
3766 my $tagobjfn = $tfn->('.tmp');
3768 if (!defined $keyid) {
3769 $keyid = access_cfg('keyid','RETURN-UNDEF');
3771 if (!defined $keyid) {
3772 $keyid = getfield $clogp, 'Maintainer';
3774 unlink $tfn->('.tmp.asc') or $!==&ENOENT or die $!;
3775 my @sign_cmd = (@gpg, qw(--detach-sign --armor));
3776 push @sign_cmd, qw(-u),$keyid if defined $keyid;
3777 push @sign_cmd, $tfn->('.tmp');
3778 runcmd_ordryrun @sign_cmd;
3780 $tagobjfn = $tfn->('.signed.tmp');
3781 runcmd shell_cmd "exec >$tagobjfn", qw(cat --),
3782 $tfn->('.tmp'), $tfn->('.tmp.asc');
3788 my @r = map { $mktag->($_); } @$tagwants;
3792 sub sign_changes ($) {
3793 my ($changesfile) = @_;
3795 my @debsign_cmd = @debsign;
3796 push @debsign_cmd, "-k$keyid" if defined $keyid;
3797 push @debsign_cmd, "-p$gpg[0]" if $gpg[0] ne 'gpg';
3798 push @debsign_cmd, $changesfile;
3799 runcmd_ordryrun @debsign_cmd;
3804 printdebug "actually entering push\n";
3806 supplementary_message(<<'END');
3807 Push failed, while checking state of the archive.
3808 You can retry the push, after fixing the problem, if you like.
3810 if (check_for_git()) {
3813 my $archive_hash = fetch_from_archive();
3814 if (!$archive_hash) {
3816 fail "package appears to be new in this suite;".
3817 " if this is intentional, use --new";
3820 supplementary_message(<<'END');
3821 Push failed, while preparing your push.
3822 You can retry the push, after fixing the problem, if you like.
3825 need_tagformat 'new', "quilt mode $quilt_mode"
3826 if quiltmode_splitbrain;
3830 access_giturl(); # check that success is vaguely likely
3833 my $clogpfn = ".git/dgit/changelog.822.tmp";
3834 runcmd shell_cmd "exec >$clogpfn", qw(dpkg-parsechangelog);
3836 responder_send_file('parsed-changelog', $clogpfn);
3838 my ($clogp, $cversion, $dscfn) =
3839 push_parse_changelog("$clogpfn");
3841 my $dscpath = "$buildproductsdir/$dscfn";
3842 stat_exists $dscpath or
3843 fail "looked for .dsc $dscpath, but $!;".
3844 " maybe you forgot to build";
3846 responder_send_file('dsc', $dscpath);
3848 push_parse_dsc($dscpath, $dscfn, $cversion);
3850 my $format = getfield $dsc, 'Format';
3851 printdebug "format $format\n";
3853 my $actualhead = git_rev_parse('HEAD');
3854 my $dgithead = $actualhead;
3855 my $maintviewhead = undef;
3857 my $upstreamversion = upstreamversion $clogp->{Version};
3859 if (madformat_wantfixup($format)) {
3860 # user might have not used dgit build, so maybe do this now:
3861 if (quiltmode_splitbrain()) {
3863 quilt_make_fake_dsc($upstreamversion);
3865 ($dgithead, $cachekey) =
3866 quilt_check_splitbrain_cache($actualhead, $upstreamversion);
3868 "--quilt=$quilt_mode but no cached dgit view:
3869 perhaps tree changed since dgit build[-source] ?";
3871 $dgithead = splitbrain_pseudomerge($clogp,
3872 $actualhead, $dgithead,
3874 $maintviewhead = $actualhead;
3875 changedir '../../../..';
3876 prep_ud(); # so _only_subdir() works, below
3878 commit_quilty_patch();
3882 if (defined $overwrite_version && !defined $maintviewhead) {
3883 $dgithead = plain_overwrite_pseudomerge($clogp,
3891 if ($archive_hash) {
3892 if (is_fast_fwd($archive_hash, $dgithead)) {
3894 } elsif (deliberately_not_fast_forward) {
3897 fail "dgit push: HEAD is not a descendant".
3898 " of the archive's version.\n".
3899 "To overwrite the archive's contents,".
3900 " pass --overwrite[=VERSION].\n".
3901 "To rewind history, if permitted by the archive,".
3902 " use --deliberately-not-fast-forward.";
3907 progress "checking that $dscfn corresponds to HEAD";
3908 runcmd qw(dpkg-source -x --),
3909 $dscpath =~ m#^/# ? $dscpath : "../../../$dscpath";
3910 my ($tree,$dir) = mktree_in_ud_from_only_subdir("source package");
3911 check_for_vendor_patches() if madformat($dsc->{format});
3912 changedir '../../../..';
3913 my @diffcmd = (@git, qw(diff --quiet), $tree, $dgithead);
3914 debugcmd "+",@diffcmd;
3916 my $r = system @diffcmd;
3919 my $diffs = cmdoutput @git, qw(diff --stat), $tree, $dgithead;
3921 HEAD specifies a different tree to $dscfn:
3923 Perhaps you forgot to build. Or perhaps there is a problem with your
3924 source tree (see dgit(7) for some hints). To see a full diff, run
3931 if (!$changesfile) {
3932 my $pat = changespat $cversion;
3933 my @cs = glob "$buildproductsdir/$pat";
3934 fail "failed to find unique changes file".
3935 " (looked for $pat in $buildproductsdir);".
3936 " perhaps you need to use dgit -C"
3938 ($changesfile) = @cs;
3940 $changesfile = "$buildproductsdir/$changesfile";
3943 # Check that changes and .dsc agree enough
3944 $changesfile =~ m{[^/]*$};
3945 my $changes = parsecontrol($changesfile,$&);
3946 files_compare_inputs($dsc, $changes)
3947 unless forceing [qw(dsc-changes-mismatch)];
3949 # Perhaps adjust .dsc to contain right set of origs
3950 changes_update_origs_from_dsc($dsc, $changes, $upstreamversion,
3952 unless forceing [qw(changes-origs-exactly)];
3954 # Checks complete, we're going to try and go ahead:
3956 responder_send_file('changes',$changesfile);
3957 responder_send_command("param head $dgithead");
3958 responder_send_command("param csuite $csuite");
3959 responder_send_command("param tagformat $tagformat");
3960 if (defined $maintviewhead) {
3961 die unless ($protovsn//4) >= 4;
3962 responder_send_command("param maint-view $maintviewhead");
3965 if (deliberately_not_fast_forward) {
3966 git_for_each_ref(lrfetchrefs, sub {
3967 my ($objid,$objtype,$lrfetchrefname,$reftail) = @_;
3968 my $rrefname= substr($lrfetchrefname, length(lrfetchrefs) + 1);
3969 responder_send_command("previously $rrefname=$objid");
3970 $previously{$rrefname} = $objid;
3974 my @tagwants = push_tagwants($cversion, $dgithead, $maintviewhead,
3978 supplementary_message(<<'END');
3979 Push failed, while signing the tag.
3980 You can retry the push, after fixing the problem, if you like.
3982 # If we manage to sign but fail to record it anywhere, it's fine.
3983 if ($we_are_responder) {
3984 @tagobjfns = map { $_->{Tfn}('.signed-tmp') } @tagwants;
3985 responder_receive_files('signed-tag', @tagobjfns);
3987 @tagobjfns = push_mktags($clogp,$dscpath,
3988 $changesfile,$changesfile,
3991 supplementary_message(<<'END');
3992 Push failed, *after* signing the tag.
3993 If you want to try again, you should use a new version number.
3996 pairwise { $a->{TagObjFn} = $b } @tagwants, @tagobjfns;
3998 foreach my $tw (@tagwants) {
3999 my $tag = $tw->{Tag};
4000 my $tagobjfn = $tw->{TagObjFn};
4002 cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
4003 runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
4004 runcmd_ordryrun_local
4005 @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
4008 supplementary_message(<<'END');
4009 Push failed, while updating the remote git repository - see messages above.
4010 If you want to try again, you should use a new version number.
4012 if (!check_for_git()) {
4013 create_remote_git_repo();
4016 my @pushrefs = $forceflag.$dgithead.":".rrref();
4017 foreach my $tw (@tagwants) {
4018 push @pushrefs, $forceflag."refs/tags/$tw->{Tag}";
4021 runcmd_ordryrun @git,
4022 qw(-c push.followTags=false push), access_giturl(), @pushrefs;
4023 runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), $dgithead;
4025 supplementary_message(<<'END');
4026 Push failed, while obtaining signatures on the .changes and .dsc.
4027 If it was just that the signature failed, you may try again by using
4028 debsign by hand to sign the changes
4030 and then dput to complete the upload.
4031 If you need to change the package, you must use a new version number.
4033 if ($we_are_responder) {
4034 my $dryrunsuffix = act_local() ? "" : ".tmp";
4035 responder_receive_files('signed-dsc-changes',
4036 "$dscpath$dryrunsuffix",
4037 "$changesfile$dryrunsuffix");
4040 rename "$dscpath.tmp",$dscpath or die "$dscfn $!";
4042 progress "[new .dsc left in $dscpath.tmp]";
4044 sign_changes $changesfile;
4047 supplementary_message(<<END);
4048 Push failed, while uploading package(s) to the archive server.
4049 You can retry the upload of exactly these same files with dput of:
4051 If that .changes file is broken, you will need to use a new version
4052 number for your next attempt at the upload.
4054 my $host = access_cfg('upload-host','RETURN-UNDEF');
4055 my @hostarg = defined($host) ? ($host,) : ();
4056 runcmd_ordryrun @dput, @hostarg, $changesfile;
4057 printdone "pushed and uploaded $cversion";
4059 supplementary_message('');
4060 responder_send_command("complete");
4067 badusage "-p is not allowed with clone; specify as argument instead"
4068 if defined $package;
4071 } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
4072 ($package,$isuite) = @ARGV;
4073 } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
4074 ($package,$dstdir) = @ARGV;
4075 } elsif (@ARGV==3) {
4076 ($package,$isuite,$dstdir) = @ARGV;
4078 badusage "incorrect arguments to dgit clone";
4080 $dstdir ||= "$package";
4082 if (stat_exists $dstdir) {
4083 fail "$dstdir already exists";
4087 if ($rmonerror && !$dryrun_level) {
4088 $cwd_remove= getcwd();
4090 return unless defined $cwd_remove;
4091 if (!chdir "$cwd_remove") {
4092 return if $!==&ENOENT;
4093 die "chdir $cwd_remove: $!";
4095 printdebug "clone rmonerror removing $dstdir\n";
4097 rmtree($dstdir) or die "remove $dstdir: $!\n";
4098 } elsif (grep { $! == $_ }
4099 (ENOENT, ENOTDIR, EACCES, EPERM, ELOOP)) {
4101 print STDERR "check whether to remove $dstdir: $!\n";
4107 $cwd_remove = undef;
4110 sub branchsuite () {
4111 my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
4112 if ($branch =~ m#$lbranch_re#o) {
4119 sub fetchpullargs () {
4121 if (!defined $package) {
4122 my $sourcep = parsecontrol('debian/control','debian/control');
4123 $package = getfield $sourcep, 'Source';
4126 $isuite = branchsuite();
4128 my $clogp = parsechangelog();
4129 $isuite = getfield $clogp, 'Distribution';
4131 } elsif (@ARGV==1) {
4134 badusage "incorrect arguments to dgit fetch or dgit pull";
4141 my $multi_fetched = fork_for_multisuite(sub { });
4142 exit 0 if $multi_fetched;
4149 if (quiltmode_splitbrain()) {
4150 my ($format, $fopts) = get_source_format();
4151 madformat($format) and fail <<END
4152 dgit pull not yet supported in split view mode (--quilt=$quilt_mode)
4161 badusage "-p is not allowed with dgit push" if defined $package;
4163 my $clogp = parsechangelog();
4164 $package = getfield $clogp, 'Source';
4167 } elsif (@ARGV==1) {
4168 ($specsuite) = (@ARGV);
4170 badusage "incorrect arguments to dgit push";
4172 $isuite = getfield $clogp, 'Distribution';
4174 local ($package) = $existing_package; # this is a hack
4175 canonicalise_suite();
4177 canonicalise_suite();
4179 if (defined $specsuite &&
4180 $specsuite ne $isuite &&
4181 $specsuite ne $csuite) {
4182 fail "dgit push: changelog specifies $isuite ($csuite)".
4183 " but command line specifies $specsuite";
4188 #---------- remote commands' implementation ----------
4190 sub cmd_remote_push_build_host {
4191 my ($nrargs) = shift @ARGV;
4192 my (@rargs) = @ARGV[0..$nrargs-1];
4193 @ARGV = @ARGV[$nrargs..$#ARGV];
4195 my ($dir,$vsnwant) = @rargs;
4196 # vsnwant is a comma-separated list; we report which we have
4197 # chosen in our ready response (so other end can tell if they
4200 $we_are_responder = 1;
4201 $us .= " (build host)";
4205 open PI, "<&STDIN" or die $!;
4206 open STDIN, "/dev/null" or die $!;
4207 open PO, ">&STDOUT" or die $!;
4209 open STDOUT, ">&STDERR" or die $!;
4213 ($protovsn) = grep {
4214 $vsnwant =~ m{^(?:.*,)?$_(?:,.*)?$}
4215 } @rpushprotovsn_support;
4217 fail "build host has dgit rpush protocol versions ".
4218 (join ",", @rpushprotovsn_support).
4219 " but invocation host has $vsnwant"
4220 unless defined $protovsn;
4222 responder_send_command("dgit-remote-push-ready $protovsn");
4223 rpush_handle_protovsn_bothends();
4228 sub cmd_remote_push_responder { cmd_remote_push_build_host(); }
4229 # ... for compatibility with proto vsn.1 dgit (just so that user gets
4230 # a good error message)
4232 sub rpush_handle_protovsn_bothends () {
4233 if ($protovsn < 4) {
4234 need_tagformat 'old', "rpush negotiated protocol $protovsn";
4243 my $report = i_child_report();
4244 if (defined $report) {
4245 printdebug "($report)\n";
4246 } elsif ($i_child_pid) {
4247 printdebug "(killing build host child $i_child_pid)\n";
4248 kill 15, $i_child_pid;
4250 if (defined $i_tmp && !defined $initiator_tempdir) {
4252 eval { rmtree $i_tmp; };
4256 END { i_cleanup(); }
4259 my ($base,$selector,@args) = @_;
4260 $selector =~ s/\-/_/g;
4261 { no strict qw(refs); &{"${base}_${selector}"}(@args); }
4268 if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
4276 push @rargs, join ",", @rpushprotovsn_support;
4279 push @rdgit, @ropts;
4280 push @rdgit, qw(remote-push-build-host), (scalar @rargs), @rargs;
4282 my @cmd = (@ssh, $host, shellquote @rdgit);
4285 if (defined $initiator_tempdir) {
4286 rmtree $initiator_tempdir;
4287 mkdir $initiator_tempdir, 0700 or die "$initiator_tempdir: $!";
4288 $i_tmp = $initiator_tempdir;
4292 $i_child_pid = open2(\*RO, \*RI, @cmd);
4294 ($protovsn) = initiator_expect { m/^dgit-remote-push-ready (\S+)/ };
4295 die "$protovsn ?" unless grep { $_ eq $protovsn } @rpushprotovsn_support;
4296 $supplementary_message = '' unless $protovsn >= 3;
4298 fail "rpush negotiated protocol version $protovsn".
4299 " which does not support quilt mode $quilt_mode"
4300 if quiltmode_splitbrain;
4302 rpush_handle_protovsn_bothends();
4304 my ($icmd,$iargs) = initiator_expect {
4305 m/^(\S+)(?: (.*))?$/;
4308 i_method "i_resp", $icmd, $iargs;
4312 sub i_resp_progress ($) {
4314 my $msg = protocol_read_bytes \*RO, $rhs;
4318 sub i_resp_supplementary_message ($) {
4320 $supplementary_message = protocol_read_bytes \*RO, $rhs;
4323 sub i_resp_complete {
4324 my $pid = $i_child_pid;
4325 $i_child_pid = undef; # prevents killing some other process with same pid
4326 printdebug "waiting for build host child $pid...\n";
4327 my $got = waitpid $pid, 0;
4328 die $! unless $got == $pid;
4329 die "build host child failed $?" if $?;
4332 printdebug "all done\n";
4336 sub i_resp_file ($) {
4338 my $localname = i_method "i_localname", $keyword;
4339 my $localpath = "$i_tmp/$localname";
4340 stat_exists $localpath and
4341 badproto \*RO, "file $keyword ($localpath) twice";
4342 protocol_receive_file \*RO, $localpath;
4343 i_method "i_file", $keyword;
4348 sub i_resp_param ($) {
4349 $_[0] =~ m/^(\S+) (.*)$/ or badproto \*RO, "bad param spec";
4353 sub i_resp_previously ($) {
4354 $_[0] =~ m#^(refs/tags/\S+)=(\w+)$#
4355 or badproto \*RO, "bad previously spec";
4356 my $r = system qw(git check-ref-format), $1;
4357 die "bad previously ref spec ($r)" if $r;
4358 $previously{$1} = $2;
4363 sub i_resp_want ($) {
4365 die "$keyword ?" if $i_wanted{$keyword}++;
4366 my @localpaths = i_method "i_want", $keyword;
4367 printdebug "[[ $keyword @localpaths\n";
4368 foreach my $localpath (@localpaths) {
4369 protocol_send_file \*RI, $localpath;
4371 print RI "files-end\n" or die $!;
4374 our ($i_clogp, $i_version, $i_dscfn, $i_changesfn);
4376 sub i_localname_parsed_changelog {
4377 return "remote-changelog.822";
4379 sub i_file_parsed_changelog {
4380 ($i_clogp, $i_version, $i_dscfn) =
4381 push_parse_changelog "$i_tmp/remote-changelog.822";
4382 die if $i_dscfn =~ m#/|^\W#;
4385 sub i_localname_dsc {
4386 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
4391 sub i_localname_changes {
4392 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
4393 $i_changesfn = $i_dscfn;
4394 $i_changesfn =~ s/\.dsc$/_dgit.changes/ or die;
4395 return $i_changesfn;
4397 sub i_file_changes { }
4399 sub i_want_signed_tag {
4400 printdebug Dumper(\%i_param, $i_dscfn);
4401 defined $i_param{'head'} && defined $i_dscfn && defined $i_clogp
4402 && defined $i_param{'csuite'}
4403 or badproto \*RO, "premature desire for signed-tag";
4404 my $head = $i_param{'head'};
4405 die if $head =~ m/[^0-9a-f]/ || $head !~ m/^../;
4407 my $maintview = $i_param{'maint-view'};
4408 die if defined $maintview && $maintview =~ m/[^0-9a-f]/;
4411 if ($protovsn >= 4) {
4412 my $p = $i_param{'tagformat'} // '<undef>';
4414 or badproto \*RO, "tag format mismatch: $p vs. $tagformat";
4417 die unless $i_param{'csuite'} =~ m/^$suite_re$/;
4419 push_parse_dsc $i_dscfn, 'remote dsc', $i_version;
4421 my @tagwants = push_tagwants $i_version, $head, $maintview, "tag";
4424 push_mktags $i_clogp, $i_dscfn,
4425 $i_changesfn, 'remote changes',
4429 sub i_want_signed_dsc_changes {
4430 rename "$i_dscfn.tmp","$i_dscfn" or die "$i_dscfn $!";
4431 sign_changes $i_changesfn;
4432 return ($i_dscfn, $i_changesfn);
4435 #---------- building etc. ----------
4441 #----- `3.0 (quilt)' handling -----
4443 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
4445 sub quiltify_dpkg_commit ($$$;$) {
4446 my ($patchname,$author,$msg, $xinfo) = @_;
4450 my $descfn = ".git/dgit/quilt-description.tmp";
4451 open O, '>', $descfn or die "$descfn: $!";
4452 $msg =~ s/\n+/\n\n/;
4453 print O <<END or die $!;
4455 ${xinfo}Subject: $msg
4462 local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
4463 local $ENV{'VISUAL'} = $ENV{'EDITOR'};
4464 local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
4465 runcmd @dpkgsource, qw(--commit --include-removal .), $patchname;
4469 sub quiltify_trees_differ ($$;$$$) {
4470 my ($x,$y,$finegrained,$ignorenamesr,$unrepres) = @_;
4471 # returns true iff the two tree objects differ other than in debian/
4472 # with $finegrained,
4473 # returns bitmask 01 - differ in upstream files except .gitignore
4474 # 02 - differ in .gitignore
4475 # if $ignorenamesr is defined, $ingorenamesr->{$fn}
4476 # is set for each modified .gitignore filename $fn
4477 # if $unrepres is defined, array ref to which is appeneded
4478 # a list of unrepresentable changes (removals of upstream files
4481 my @cmd = (@git, qw(diff-tree -z));
4482 push @cmd, qw(--name-only) unless $unrepres;
4483 push @cmd, qw(-r) if $finegrained || $unrepres;
4485 my $diffs= cmdoutput @cmd;
4488 foreach my $f (split /\0/, $diffs) {
4489 if ($unrepres && !@lmodes) {
4490 @lmodes = $f =~ m/^\:(\w+) (\w+) \w+ \w+ / or die "$_ ?";
4493 my ($oldmode,$newmode) = @lmodes;
4496 next if $f =~ m#^debian(?:/.*)?$#s;
4500 die "not a plain file\n"
4501 unless $newmode =~ m/^10\d{4}$/ ||
4502 $oldmode =~ m/^10\d{4}$/;
4503 if ($oldmode =~ m/[^0]/ &&
4504 $newmode =~ m/[^0]/) {
4505 die "mode changed\n" if $oldmode ne $newmode;
4507 die "non-default mode\n"
4508 unless $newmode =~ m/^100644$/ ||
4509 $oldmode =~ m/^100644$/;
4513 local $/="\n"; chomp $@;
4514 push @$unrepres, [ $f, "$@ ($oldmode->$newmode)" ];
4518 my $isignore = $f =~ m#^(?:.*/)?.gitignore$#s;
4519 $r |= $isignore ? 02 : 01;
4520 $ignorenamesr->{$f}=1 if $ignorenamesr && $isignore;
4522 printdebug "quiltify_trees_differ $x $y => $r\n";
4526 sub quiltify_tree_sentinelfiles ($) {
4527 # lists the `sentinel' files present in the tree
4529 my $r = cmdoutput @git, qw(ls-tree --name-only), $x,
4530 qw(-- debian/rules debian/control);
4535 sub quiltify_splitbrain_needed () {
4536 if (!$split_brain) {
4537 progress "dgit view: changes are required...";
4538 runcmd @git, qw(checkout -q -b dgit-view);
4543 sub quiltify_splitbrain ($$$$$$) {
4544 my ($clogp, $unapplied, $headref, $diffbits,
4545 $editedignores, $cachekey) = @_;
4546 if ($quilt_mode !~ m/gbp|dpm/) {
4547 # treat .gitignore just like any other upstream file
4548 $diffbits = { %$diffbits };
4549 $_ = !!$_ foreach values %$diffbits;
4551 # We would like any commits we generate to be reproducible
4552 my @authline = clogp_authline($clogp);
4553 local $ENV{GIT_COMMITTER_NAME} = $authline[0];
4554 local $ENV{GIT_COMMITTER_EMAIL} = $authline[1];
4555 local $ENV{GIT_COMMITTER_DATE} = $authline[2];
4556 local $ENV{GIT_AUTHOR_NAME} = $authline[0];
4557 local $ENV{GIT_AUTHOR_EMAIL} = $authline[1];
4558 local $ENV{GIT_AUTHOR_DATE} = $authline[2];
4560 if ($quilt_mode =~ m/gbp|unapplied/ &&
4561 ($diffbits->{O2H} & 01)) {
4563 "--quilt=$quilt_mode specified, implying patches-unapplied git tree\n".
4564 " but git tree differs from orig in upstream files.";
4565 if (!stat_exists "debian/patches") {
4567 "\n ... debian/patches is missing; perhaps this is a patch queue branch?";
4571 if ($quilt_mode =~ m/dpm/ &&
4572 ($diffbits->{H2A} & 01)) {
4574 --quilt=$quilt_mode specified, implying patches-applied git tree
4575 but git tree differs from result of applying debian/patches to upstream
4578 if ($quilt_mode =~ m/gbp|unapplied/ &&
4579 ($diffbits->{O2A} & 01)) { # some patches
4580 quiltify_splitbrain_needed();
4581 progress "dgit view: creating patches-applied version using gbp pq";
4582 runcmd shell_cmd 'exec >/dev/null', gbp_pq, qw(import);
4583 # gbp pq import creates a fresh branch; push back to dgit-view
4584 runcmd @git, qw(update-ref refs/heads/dgit-view HEAD);
4585 runcmd @git, qw(checkout -q dgit-view);
4587 if ($quilt_mode =~ m/gbp|dpm/ &&
4588 ($diffbits->{O2A} & 02)) {
4590 --quilt=$quilt_mode specified, implying that HEAD is for use with a
4591 tool which does not create patches for changes to upstream
4592 .gitignores: but, such patches exist in debian/patches.
4595 if (($diffbits->{O2H} & 02) && # user has modified .gitignore
4596 !($diffbits->{O2A} & 02)) { # patches do not change .gitignore
4597 quiltify_splitbrain_needed();
4598 progress "dgit view: creating patch to represent .gitignore changes";
4599 ensuredir "debian/patches";
4600 my $gipatch = "debian/patches/auto-gitignore";
4601 open GIPATCH, ">>", "$gipatch" or die "$gipatch: $!";
4602 stat GIPATCH or die "$gipatch: $!";
4603 fail "$gipatch already exists; but want to create it".
4604 " to record .gitignore changes" if (stat _)[7];
4605 print GIPATCH <<END or die "$gipatch: $!";
4606 Subject: Update .gitignore from Debian packaging branch
4608 The Debian packaging git branch contains these updates to the upstream
4609 .gitignore file(s). This patch is autogenerated, to provide these
4610 updates to users of the official Debian archive view of the package.
4612 [dgit ($our_version) update-gitignore]
4615 close GIPATCH or die "$gipatch: $!";
4616 runcmd shell_cmd "exec >>$gipatch", @git, qw(diff),
4617 $unapplied, $headref, "--", sort keys %$editedignores;
4618 open SERIES, "+>>", "debian/patches/series" or die $!;
4619 defined seek SERIES, -1, 2 or $!==EINVAL or die $!;
4621 defined read SERIES, $newline, 1 or die $!;
4622 print SERIES "\n" or die $! unless $newline eq "\n";
4623 print SERIES "auto-gitignore\n" or die $!;
4624 close SERIES or die $!;
4625 runcmd @git, qw(add -- debian/patches/series), $gipatch;
4627 Commit patch to update .gitignore
4629 [dgit ($our_version) update-gitignore-quilt-fixup]
4633 my $dgitview = git_rev_parse 'HEAD';
4635 changedir '../../../..';
4636 # When we no longer need to support squeeze, use --create-reflog
4638 ensuredir ".git/logs/refs/dgit-intern";
4639 my $makelogfh = new IO::File ".git/logs/refs/$splitbraincache", '>>'
4642 my $oldcache = git_get_ref "refs/$splitbraincache";
4643 if ($oldcache eq $dgitview) {
4644 my $tree = cmdoutput qw(git rev-parse), "$dgitview:";
4645 # git update-ref doesn't always update, in this case. *sigh*
4646 my $dummy = make_commit_text <<END;
4649 author Dgit <dgit\@example.com> 1000000000 +0000
4650 committer Dgit <dgit\@example.com> 1000000000 +0000
4652 Dummy commit - do not use
4654 runcmd @git, qw(update-ref -m), "dgit $our_version - dummy",
4655 "refs/$splitbraincache", $dummy;
4657 runcmd @git, qw(update-ref -m), $cachekey, "refs/$splitbraincache",
4660 changedir '.git/dgit/unpack/work';
4662 my $saved = maybe_split_brain_save $headref, $dgitview, "converted";
4663 progress "dgit view: created ($saved)";
4666 sub quiltify ($$$$) {
4667 my ($clogp,$target,$oldtiptree,$failsuggestion) = @_;
4669 # Quilt patchification algorithm
4671 # We search backwards through the history of the main tree's HEAD
4672 # (T) looking for a start commit S whose tree object is identical
4673 # to to the patch tip tree (ie the tree corresponding to the
4674 # current dpkg-committed patch series). For these purposes
4675 # `identical' disregards anything in debian/ - this wrinkle is
4676 # necessary because dpkg-source treates debian/ specially.
4678 # We can only traverse edges where at most one of the ancestors'
4679 # trees differs (in changes outside in debian/). And we cannot
4680 # handle edges which change .pc/ or debian/patches. To avoid
4681 # going down a rathole we avoid traversing edges which introduce
4682 # debian/rules or debian/control. And we set a limit on the
4683 # number of edges we are willing to look at.
4685 # If we succeed, we walk forwards again. For each traversed edge
4686 # PC (with P parent, C child) (starting with P=S and ending with
4687 # C=T) to we do this:
4689 # - dpkg-source --commit with a patch name and message derived from C
4690 # After traversing PT, we git commit the changes which
4691 # should be contained within debian/patches.
4693 # The search for the path S..T is breadth-first. We maintain a
4694 # todo list containing search nodes. A search node identifies a
4695 # commit, and looks something like this:
4697 # Commit => $git_commit_id,
4698 # Child => $c, # or undef if P=T
4699 # Whynot => $reason_edge_PC_unsuitable, # in @nots only
4700 # Nontrivial => true iff $p..$c has relevant changes
4707 my %considered; # saves being exponential on some weird graphs
4709 my $t_sentinels = quiltify_tree_sentinelfiles $target;
4712 my ($search,$whynot) = @_;
4713 printdebug " search NOT $search->{Commit} $whynot\n";
4714 $search->{Whynot} = $whynot;
4715 push @nots, $search;
4716 no warnings qw(exiting);
4725 my $c = shift @todo;
4726 next if $considered{$c->{Commit}}++;
4728 $not->($c, "maximum search space exceeded") if --$max_work <= 0;
4730 printdebug "quiltify investigate $c->{Commit}\n";
4733 if (!quiltify_trees_differ $c->{Commit}, $oldtiptree) {
4734 printdebug " search finished hooray!\n";
4739 if ($quilt_mode eq 'nofix') {
4740 fail "quilt fixup required but quilt mode is \`nofix'\n".
4741 "HEAD commit $c->{Commit} differs from tree implied by ".
4742 " debian/patches (tree object $oldtiptree)";
4744 if ($quilt_mode eq 'smash') {
4745 printdebug " search quitting smash\n";
4749 my $c_sentinels = quiltify_tree_sentinelfiles $c->{Commit};
4750 $not->($c, "has $c_sentinels not $t_sentinels")
4751 if $c_sentinels ne $t_sentinels;
4753 my $commitdata = cmdoutput @git, qw(cat-file commit), $c->{Commit};
4754 $commitdata =~ m/\n\n/;
4756 my @parents = ($commitdata =~ m/^parent (\w+)$/gm);
4757 @parents = map { { Commit => $_, Child => $c } } @parents;
4759 $not->($c, "root commit") if !@parents;
4761 foreach my $p (@parents) {
4762 $p->{Nontrivial}= quiltify_trees_differ $p->{Commit},$c->{Commit};
4764 my $ndiffers = grep { $_->{Nontrivial} } @parents;
4765 $not->($c, "merge ($ndiffers nontrivial parents)") if $ndiffers > 1;
4767 foreach my $p (@parents) {
4768 printdebug "considering C=$c->{Commit} P=$p->{Commit}\n";
4770 my @cmd= (@git, qw(diff-tree -r --name-only),
4771 $p->{Commit},$c->{Commit}, qw(-- debian/patches .pc));
4772 my $patchstackchange = cmdoutput @cmd;
4773 if (length $patchstackchange) {
4774 $patchstackchange =~ s/\n/,/g;
4775 $not->($p, "changed $patchstackchange");
4778 printdebug " search queue P=$p->{Commit} ",
4779 ($p->{Nontrivial} ? "NT" : "triv"),"\n";
4785 printdebug "quiltify want to smash\n";
4788 my $x = $_[0]{Commit};
4789 $x =~ s/(.*?[0-9a-z]{8})[0-9a-z]*$/$1/;
4792 my $reportnot = sub {
4794 my $s = $abbrev->($notp);
4795 my $c = $notp->{Child};
4796 $s .= "..".$abbrev->($c) if $c;
4797 $s .= ": ".$notp->{Whynot};
4800 if ($quilt_mode eq 'linear') {
4801 print STDERR "$us: quilt fixup cannot be linear. Stopped at:\n";
4802 foreach my $notp (@nots) {
4803 print STDERR "$us: ", $reportnot->($notp), "\n";
4805 print STDERR "$us: $_\n" foreach @$failsuggestion;
4806 fail "quilt fixup naive history linearisation failed.\n".
4807 "Use dpkg-source --commit by hand; or, --quilt=smash for one ugly patch";
4808 } elsif ($quilt_mode eq 'smash') {
4809 } elsif ($quilt_mode eq 'auto') {
4810 progress "quilt fixup cannot be linear, smashing...";
4812 die "$quilt_mode ?";
4815 my $time = $ENV{'GIT_COMMITTER_DATE'} || time;
4816 $time =~ s/\s.*//; # trim timezone from GIT_COMMITTER_DATE
4818 my $msg = cmdoutput @git, qw(log), "-n$ncommits";
4820 quiltify_dpkg_commit "auto-$version-$target-$time",
4821 (getfield $clogp, 'Maintainer'),
4822 "Automatically generated patch ($clogp->{Version})\n".
4823 "Last (up to) $ncommits git changes, FYI:\n\n". $msg;
4827 progress "quiltify linearisation planning successful, executing...";
4829 for (my $p = $sref_S;
4830 my $c = $p->{Child};
4832 printdebug "quiltify traverse $p->{Commit}..$c->{Commit}\n";
4833 next unless $p->{Nontrivial};
4835 my $cc = $c->{Commit};
4837 my $commitdata = cmdoutput @git, qw(cat-file commit), $cc;
4838 $commitdata =~ m/\n\n/ or die "$c ?";
4841 $commitdata =~ m/^author (.*) \d+ [-+0-9]+$/m or die "$cc ?";
4844 my $commitdate = cmdoutput
4845 @git, qw(log -n1 --pretty=format:%aD), $cc;
4847 $msg =~ s/^(.*)\n*/$1\n/ or die "$cc $msg ?";
4849 my $strip_nls = sub { $msg =~ s/\n+$//; $msg .= "\n"; };
4856 my $gbp_check_suitable = sub {
4861 die "contains unexpected slashes\n" if m{//} || m{/$};
4862 die "contains leading punctuation\n" if m{^\W} || m{/\W};
4863 die "contains bad character(s)\n" if m{[^-a-z0-9_.+=~/]}i;
4864 die "too long" if length > 200;
4866 return $_ unless $@;
4867 print STDERR "quiltifying commit $cc:".
4868 " ignoring/dropping Gbp-Pq $what: $@";
4872 if ($msg =~ s/^ (?: gbp(?:-pq)? : \s* name \s+ |
4874 (\S+) \s* \n //ixm) {
4875 $patchname = $gbp_check_suitable->($1, 'Name');
4877 if ($msg =~ s/^ (?: gbp(?:-pq)? : \s* topic \s+ |
4879 (\S+) \s* \n //ixm) {
4880 $patchdir = $gbp_check_suitable->($1, 'Topic');
4885 if (!defined $patchname) {
4886 $patchname = $title;
4887 $patchname =~ s/[.:]$//;
4890 my $converter = new Text::Iconv qw(UTF-8 ASCII//TRANSLIT);
4891 my $translitname = $converter->convert($patchname);
4892 die unless defined $translitname;
4893 $patchname = $translitname;
4896 "dgit: patch title transliteration error: $@"
4898 $patchname =~ y/ A-Z/-a-z/;
4899 $patchname =~ y/-a-z0-9_.+=~//cd;
4900 $patchname =~ s/^\W/x-$&/;
4901 $patchname = substr($patchname,0,40);
4903 if (!defined $patchdir) {
4906 if (length $patchdir) {
4907 $patchname = "$patchdir/$patchname";
4909 if ($patchname =~ m{^(.*)/}) {
4910 mkpath "debian/patches/$1";
4915 stat "debian/patches/$patchname$index";
4917 $!==ENOENT or die "$patchname$index $!";
4919 runcmd @git, qw(checkout -q), $cc;
4921 # We use the tip's changelog so that dpkg-source doesn't
4922 # produce complaining messages from dpkg-parsechangelog. None
4923 # of the information dpkg-source gets from the changelog is
4924 # actually relevant - it gets put into the original message
4925 # which dpkg-source provides our stunt editor, and then
4927 runcmd @git, qw(checkout -q), $target, qw(debian/changelog);
4929 quiltify_dpkg_commit "$patchname$index", $author, $msg,
4930 "Date: $commitdate\n".
4931 "X-Dgit-Generated: $clogp->{Version} $cc\n";
4933 runcmd @git, qw(checkout -q), $cc, qw(debian/changelog);
4936 runcmd @git, qw(checkout -q master);
4939 sub build_maybe_quilt_fixup () {
4940 my ($format,$fopts) = get_source_format;
4941 return unless madformat_wantfixup $format;
4944 check_for_vendor_patches();
4946 if (quiltmode_splitbrain) {
4947 fail <<END unless access_cfg_tagformats_can_splitbrain;
4948 quilt mode $quilt_mode requires split view so server needs to support
4949 both "new" and "maint" tag formats, but config says it doesn't.
4953 my $clogp = parsechangelog();
4954 my $headref = git_rev_parse('HEAD');
4959 my $upstreamversion = upstreamversion $version;
4961 if ($fopts->{'single-debian-patch'}) {
4962 quilt_fixup_singlepatch($clogp, $headref, $upstreamversion);
4964 quilt_fixup_multipatch($clogp, $headref, $upstreamversion);
4967 die 'bug' if $split_brain && !$need_split_build_invocation;
4969 changedir '../../../..';
4970 runcmd_ordryrun_local
4971 @git, qw(pull --ff-only -q .git/dgit/unpack/work master);
4974 sub quilt_fixup_mkwork ($) {
4977 mkdir "work" or die $!;
4979 mktree_in_ud_here();
4980 runcmd @git, qw(reset -q --hard), $headref;
4983 sub quilt_fixup_linkorigs ($$) {
4984 my ($upstreamversion, $fn) = @_;
4985 # calls $fn->($leafname);
4987 foreach my $f (<../../../../*>) { #/){
4988 my $b=$f; $b =~ s{.*/}{};
4990 local ($debuglevel) = $debuglevel-1;
4991 printdebug "QF linkorigs $b, $f ?\n";
4993 next unless is_orig_file_of_vsn $b, $upstreamversion;
4994 printdebug "QF linkorigs $b, $f Y\n";
4995 link_ltarget $f, $b or die "$b $!";
5000 sub quilt_fixup_delete_pc () {
5001 runcmd @git, qw(rm -rqf .pc);
5003 Commit removal of .pc (quilt series tracking data)
5005 [dgit ($our_version) upgrade quilt-remove-pc]
5009 sub quilt_fixup_singlepatch ($$$) {
5010 my ($clogp, $headref, $upstreamversion) = @_;
5012 progress "starting quiltify (single-debian-patch)";
5014 # dpkg-source --commit generates new patches even if
5015 # single-debian-patch is in debian/source/options. In order to
5016 # get it to generate debian/patches/debian-changes, it is
5017 # necessary to build the source package.
5019 quilt_fixup_linkorigs($upstreamversion, sub { });
5020 quilt_fixup_mkwork($headref);
5022 rmtree("debian/patches");
5024 runcmd @dpkgsource, qw(-b .);
5026 runcmd @dpkgsource, qw(-x), (srcfn $version, ".dsc");
5027 rename srcfn("$upstreamversion", "/debian/patches"),
5028 "work/debian/patches";
5031 commit_quilty_patch();
5034 sub quilt_make_fake_dsc ($) {
5035 my ($upstreamversion) = @_;
5037 my $fakeversion="$upstreamversion-~~DGITFAKE";
5039 my $fakedsc=new IO::File 'fake.dsc', '>' or die $!;
5040 print $fakedsc <<END or die $!;
5043 Version: $fakeversion
5047 my $dscaddfile=sub {
5050 my $md = new Digest::MD5;
5052 my $fh = new IO::File $b, '<' or die "$b $!";
5057 print $fakedsc " ".$md->hexdigest." $size $b\n" or die $!;
5060 quilt_fixup_linkorigs($upstreamversion, $dscaddfile);
5062 my @files=qw(debian/source/format debian/rules
5063 debian/control debian/changelog);
5064 foreach my $maybe (qw(debian/patches debian/source/options
5065 debian/tests/control)) {
5066 next unless stat_exists "../../../$maybe";
5067 push @files, $maybe;
5070 my $debtar= srcfn $fakeversion,'.debian.tar.gz';
5071 runcmd qw(env GZIP=-1n tar -zcf), "./$debtar", qw(-C ../../..), @files;
5073 $dscaddfile->($debtar);
5074 close $fakedsc or die $!;
5077 sub quilt_check_splitbrain_cache ($$) {
5078 my ($headref, $upstreamversion) = @_;
5079 # Called only if we are in (potentially) split brain mode.
5081 # Computes the cache key and looks in the cache.
5082 # Returns ($dgit_view_commitid, $cachekey) or (undef, $cachekey)
5084 my $splitbrain_cachekey;
5087 "dgit: split brain (separate dgit view) may be needed (--quilt=$quilt_mode).";
5088 # we look in the reflog of dgit-intern/quilt-cache
5089 # we look for an entry whose message is the key for the cache lookup
5090 my @cachekey = (qw(dgit), $our_version);
5091 push @cachekey, $upstreamversion;
5092 push @cachekey, $quilt_mode;
5093 push @cachekey, $headref;
5095 push @cachekey, hashfile('fake.dsc');
5097 my $srcshash = Digest::SHA->new(256);
5098 my %sfs = ( %INC, '$0(dgit)' => $0 );
5099 foreach my $sfk (sort keys %sfs) {
5100 next unless $sfk =~ m/^\$0\b/ || $sfk =~ m{^Debian/Dgit\b};
5101 $srcshash->add($sfk," ");
5102 $srcshash->add(hashfile($sfs{$sfk}));
5103 $srcshash->add("\n");
5105 push @cachekey, $srcshash->hexdigest();
5106 $splitbrain_cachekey = "@cachekey";
5108 my @cmd = (@git, qw(log -g), '--pretty=format:%H %gs',
5110 printdebug "splitbrain cachekey $splitbrain_cachekey\n";
5111 debugcmd "|(probably)",@cmd;
5112 my $child = open GC, "-|"; defined $child or die $!;
5114 chdir '../../..' or die $!;
5115 if (!stat ".git/logs/refs/$splitbraincache") {
5116 $! == ENOENT or die $!;
5117 printdebug ">(no reflog)\n";
5124 printdebug ">| ", $_, "\n" if $debuglevel > 1;
5125 next unless m/^(\w+) (\S.*\S)$/ && $2 eq $splitbrain_cachekey;
5128 quilt_fixup_mkwork($headref);
5129 my $saved = maybe_split_brain_save $headref, $cachehit, "cache-hit";
5130 if ($cachehit ne $headref) {
5131 progress "dgit view: found cached ($saved)";
5132 runcmd @git, qw(checkout -q -b dgit-view), $cachehit;
5134 return ($cachehit, $splitbrain_cachekey);
5136 progress "dgit view: found cached, no changes required";
5137 return ($headref, $splitbrain_cachekey);
5139 die $! if GC->error;
5140 failedcmd unless close GC;
5142 printdebug "splitbrain cache miss\n";
5143 return (undef, $splitbrain_cachekey);
5146 sub quilt_fixup_multipatch ($$$) {
5147 my ($clogp, $headref, $upstreamversion) = @_;
5149 progress "examining quilt state (multiple patches, $quilt_mode mode)";
5152 # - honour any existing .pc in case it has any strangeness
5153 # - determine the git commit corresponding to the tip of
5154 # the patch stack (if there is one)
5155 # - if there is such a git commit, convert each subsequent
5156 # git commit into a quilt patch with dpkg-source --commit
5157 # - otherwise convert all the differences in the tree into
5158 # a single git commit
5162 # Our git tree doesn't necessarily contain .pc. (Some versions of
5163 # dgit would include the .pc in the git tree.) If there isn't
5164 # one, we need to generate one by unpacking the patches that we
5167 # We first look for a .pc in the git tree. If there is one, we
5168 # will use it. (This is not the normal case.)
5170 # Otherwise need to regenerate .pc so that dpkg-source --commit
5171 # can work. We do this as follows:
5172 # 1. Collect all relevant .orig from parent directory
5173 # 2. Generate a debian.tar.gz out of
5174 # debian/{patches,rules,source/format,source/options}
5175 # 3. Generate a fake .dsc containing just these fields:
5176 # Format Source Version Files
5177 # 4. Extract the fake .dsc
5178 # Now the fake .dsc has a .pc directory.
5179 # (In fact we do this in every case, because in future we will
5180 # want to search for a good base commit for generating patches.)
5182 # Then we can actually do the dpkg-source --commit
5183 # 1. Make a new working tree with the same object
5184 # store as our main tree and check out the main
5186 # 2. Copy .pc from the fake's extraction, if necessary
5187 # 3. Run dpkg-source --commit
5188 # 4. If the result has changes to debian/, then
5189 # - git add them them
5190 # - git add .pc if we had a .pc in-tree
5192 # 5. If we had a .pc in-tree, delete it, and git commit
5193 # 6. Back in the main tree, fast forward to the new HEAD
5195 # Another situation we may have to cope with is gbp-style
5196 # patches-unapplied trees.
5198 # We would want to detect these, so we know to escape into
5199 # quilt_fixup_gbp. However, this is in general not possible.
5200 # Consider a package with a one patch which the dgit user reverts
5201 # (with git revert or the moral equivalent).
5203 # That is indistinguishable in contents from a patches-unapplied
5204 # tree. And looking at the history to distinguish them is not
5205 # useful because the user might have made a confusing-looking git
5206 # history structure (which ought to produce an error if dgit can't
5207 # cope, not a silent reintroduction of an unwanted patch).
5209 # So gbp users will have to pass an option. But we can usually
5210 # detect their failure to do so: if the tree is not a clean
5211 # patches-applied tree, quilt linearisation fails, but the tree
5212 # _is_ a clean patches-unapplied tree, we can suggest that maybe
5213 # they want --quilt=unapplied.
5215 # To help detect this, when we are extracting the fake dsc, we
5216 # first extract it with --skip-patches, and then apply the patches
5217 # afterwards with dpkg-source --before-build. That lets us save a
5218 # tree object corresponding to .origs.
5220 my $splitbrain_cachekey;
5222 quilt_make_fake_dsc($upstreamversion);
5224 if (quiltmode_splitbrain()) {
5226 ($cachehit, $splitbrain_cachekey) =
5227 quilt_check_splitbrain_cache($headref, $upstreamversion);
5228 return if $cachehit;
5232 'exec dpkg-source --no-check --skip-patches -x fake.dsc >/dev/null';
5234 my $fakexdir= $package.'-'.(stripepoch $upstreamversion);
5235 rename $fakexdir, "fake" or die "$fakexdir $!";
5239 remove_stray_gits("source package");
5240 mktree_in_ud_here();
5244 my $unapplied=git_add_write_tree();
5245 printdebug "fake orig tree object $unapplied\n";
5249 my @bbcmd = (qw(sh -ec), 'exec dpkg-source --before-build . >/dev/null');
5251 if (system @bbcmd) {
5252 failedcmd @bbcmd if $? < 0;
5254 failed to apply your git tree's patch stack (from debian/patches/) to
5255 the corresponding upstream tarball(s). Your source tree and .orig
5256 are probably too inconsistent. dgit can only fix up certain kinds of
5257 anomaly (depending on the quilt mode). See --quilt= in dgit(1).
5263 quilt_fixup_mkwork($headref);
5266 if (stat_exists ".pc") {
5268 progress "Tree already contains .pc - will use it then delete it.";
5271 rename '../fake/.pc','.pc' or die $!;
5274 changedir '../fake';
5276 my $oldtiptree=git_add_write_tree();
5277 printdebug "fake o+d/p tree object $unapplied\n";
5278 changedir '../work';
5281 # We calculate some guesswork now about what kind of tree this might
5282 # be. This is mostly for error reporting.
5288 # O = orig, without patches applied
5289 # A = "applied", ie orig with H's debian/patches applied
5290 O2H => quiltify_trees_differ($unapplied,$headref, 1,
5291 \%editedignores, \@unrepres),
5292 H2A => quiltify_trees_differ($headref, $oldtiptree,1),
5293 O2A => quiltify_trees_differ($unapplied,$oldtiptree,1),
5297 foreach my $b (qw(01 02)) {
5298 foreach my $v (qw(O2H O2A H2A)) {
5299 push @dl, ($diffbits->{$v} & $b) ? '##' : '==';
5302 printdebug "differences \@dl @dl.\n";
5305 "$us: base trees orig=%.20s o+d/p=%.20s",
5306 $unapplied, $oldtiptree;
5308 "$us: quilt differences: src: %s orig %s gitignores: %s orig %s\n".
5309 "$us: quilt differences: HEAD %s o+d/p HEAD %s o+d/p",
5310 $dl[0], $dl[1], $dl[3], $dl[4],
5314 print STDERR "dgit: cannot represent change: $_->[1]: $_->[0]\n"
5316 forceable_fail [qw(unrepresentable)], <<END;
5317 HEAD has changes to .orig[s] which are not representable by `3.0 (quilt)'
5322 if (!($diffbits->{O2H} & $diffbits->{O2A})) {
5323 push @failsuggestion, "This might be a patches-unapplied branch.";
5324 } elsif (!($diffbits->{H2A} & $diffbits->{O2A})) {
5325 push @failsuggestion, "This might be a patches-applied branch.";
5327 push @failsuggestion, "Maybe you need to specify one of".
5328 " --[quilt=]gbp --[quilt=]dpm --quilt=unapplied ?";
5330 if (quiltmode_splitbrain()) {
5331 quiltify_splitbrain($clogp, $unapplied, $headref,
5332 $diffbits, \%editedignores,
5333 $splitbrain_cachekey);
5337 progress "starting quiltify (multiple patches, $quilt_mode mode)";
5338 quiltify($clogp,$headref,$oldtiptree,\@failsuggestion);
5340 if (!open P, '>>', ".pc/applied-patches") {
5341 $!==&ENOENT or die $!;
5346 commit_quilty_patch();
5348 if ($mustdeletepc) {
5349 quilt_fixup_delete_pc();
5353 sub quilt_fixup_editor () {
5354 my $descfn = $ENV{$fakeeditorenv};
5355 my $editing = $ARGV[$#ARGV];
5356 open I1, '<', $descfn or die "$descfn: $!";
5357 open I2, '<', $editing or die "$editing: $!";
5358 unlink $editing or die "$editing: $!";
5359 open O, '>', $editing or die "$editing: $!";
5360 while (<I1>) { print O or die $!; } I1->error and die $!;
5363 $copying ||= m/^\-\-\- /;
5364 next unless $copying;
5367 I2->error and die $!;
5372 sub maybe_apply_patches_dirtily () {
5373 return unless $quilt_mode =~ m/gbp|unapplied/;
5374 print STDERR <<END or die $!;
5376 dgit: Building, or cleaning with rules target, in patches-unapplied tree.
5377 dgit: Have to apply the patches - making the tree dirty.
5378 dgit: (Consider specifying --clean=git and (or) using dgit sbuild.)
5381 $patches_applied_dirtily = 01;
5382 $patches_applied_dirtily |= 02 unless stat_exists '.pc';
5383 runcmd qw(dpkg-source --before-build .);
5386 sub maybe_unapply_patches_again () {
5387 progress "dgit: Unapplying patches again to tidy up the tree."
5388 if $patches_applied_dirtily;
5389 runcmd qw(dpkg-source --after-build .)
5390 if $patches_applied_dirtily & 01;
5392 if $patches_applied_dirtily & 02;
5393 $patches_applied_dirtily = 0;
5396 #----- other building -----
5398 our $clean_using_builder;
5399 # ^ tree is to be cleaned by dpkg-source's builtin idea that it should
5400 # clean the tree before building (perhaps invoked indirectly by
5401 # whatever we are using to run the build), rather than separately
5402 # and explicitly by us.
5405 return if $clean_using_builder;
5406 if ($cleanmode eq 'dpkg-source') {
5407 maybe_apply_patches_dirtily();
5408 runcmd_ordryrun_local @dpkgbuildpackage, qw(-T clean);
5409 } elsif ($cleanmode eq 'dpkg-source-d') {
5410 maybe_apply_patches_dirtily();
5411 runcmd_ordryrun_local @dpkgbuildpackage, qw(-d -T clean);
5412 } elsif ($cleanmode eq 'git') {
5413 runcmd_ordryrun_local @git, qw(clean -xdf);
5414 } elsif ($cleanmode eq 'git-ff') {
5415 runcmd_ordryrun_local @git, qw(clean -xdff);
5416 } elsif ($cleanmode eq 'check') {
5417 my $leftovers = cmdoutput @git, qw(clean -xdn);
5418 if (length $leftovers) {
5419 print STDERR $leftovers, "\n" or die $!;
5420 fail "tree contains uncommitted files and --clean=check specified";
5422 } elsif ($cleanmode eq 'none') {
5429 badusage "clean takes no additional arguments" if @ARGV;
5432 maybe_unapply_patches_again();
5435 sub build_prep_early () {
5436 our $build_prep_early_done //= 0;
5437 return if $build_prep_early_done++;
5439 badusage "-p is not allowed when building" if defined $package;
5440 my $clogp = parsechangelog();
5441 $isuite = getfield $clogp, 'Distribution';
5442 $package = getfield $clogp, 'Source';
5443 $version = getfield $clogp, 'Version';
5450 build_maybe_quilt_fixup();
5452 my $pat = changespat $version;
5453 foreach my $f (glob "$buildproductsdir/$pat") {
5455 unlink $f or fail "remove old changes file $f: $!";
5457 progress "would remove $f";
5463 sub changesopts_initial () {
5464 my @opts =@changesopts[1..$#changesopts];
5467 sub changesopts_version () {
5468 if (!defined $changes_since_version) {
5469 my @vsns = archive_query('archive_query');
5470 my @quirk = access_quirk();
5471 if ($quirk[0] eq 'backports') {
5472 local $isuite = $quirk[2];
5474 canonicalise_suite();
5475 push @vsns, archive_query('archive_query');
5478 @vsns = map { $_->[0] } @vsns;
5479 @vsns = sort { -version_compare($a, $b) } @vsns;
5480 $changes_since_version = $vsns[0];
5481 progress "changelog will contain changes since $vsns[0]";
5483 $changes_since_version = '_';
5484 progress "package seems new, not specifying -v<version>";
5487 if ($changes_since_version ne '_') {
5488 return ("-v$changes_since_version");
5494 sub changesopts () {
5495 return (changesopts_initial(), changesopts_version());
5498 sub massage_dbp_args ($;$) {
5499 my ($cmd,$xargs) = @_;
5502 # - if we're going to split the source build out so we can
5503 # do strange things to it, massage the arguments to dpkg-buildpackage
5504 # so that the main build doessn't build source (or add an argument
5505 # to stop it building source by default).
5507 # - add -nc to stop dpkg-source cleaning the source tree,
5508 # unless we're not doing a split build and want dpkg-source
5509 # as cleanmode, in which case we can do nothing
5512 # 0 - source will NOT need to be built separately by caller
5513 # +1 - source will need to be built separately by caller
5514 # +2 - source will need to be built separately by caller AND
5515 # dpkg-buildpackage should not in fact be run at all!
5516 debugcmd '#massaging#', @$cmd if $debuglevel>1;
5517 #print STDERR "MASS0 ",Dumper($cmd, $xargs, $need_split_build_invocation);
5518 if ($cleanmode eq 'dpkg-source' && !$need_split_build_invocation) {
5519 $clean_using_builder = 1;
5522 # -nc has the side effect of specifying -b if nothing else specified
5523 # and some combinations of -S, -b, et al, are errors, rather than
5524 # later simply overriding earlie. So we need to:
5525 # - search the command line for these options
5526 # - pick the last one
5527 # - perhaps add our own as a default
5528 # - perhaps adjust it to the corresponding non-source-building version
5530 foreach my $l ($cmd, $xargs) {
5532 @$l = grep { !(m/^-[SgGFABb]$/s and $dmode=$_) } @$l;
5535 #print STDERR "MASS1 ",Dumper($cmd, $xargs, $dmode);
5537 if ($need_split_build_invocation) {
5538 printdebug "massage split $dmode.\n";
5539 $r = $dmode =~ m/[S]/ ? +2 :
5540 $dmode =~ y/gGF/ABb/ ? +1 :
5541 $dmode =~ m/[ABb]/ ? 0 :
5544 printdebug "massage done $r $dmode.\n";
5546 #print STDERR "MASS2 ",Dumper($cmd, $xargs, $r);
5552 my $wasdir = must_getcwd();
5558 sub postbuild_mergechanges ($) { # must run with CWD=.. (eg in in_parent)
5559 my ($msg_if_onlyone) = @_;
5560 # If there is only one .changes file, fail with $msg_if_onlyone,
5561 # or if that is undef, be a no-op.
5562 # Returns the changes file to report to the user.
5563 my $pat = changespat $version;
5564 my @changesfiles = glob $pat;
5565 @changesfiles = sort {
5566 ($b =~ m/_source\.changes$/ <=> $a =~ m/_source\.changes$/)
5570 if (@changesfiles==1) {
5571 fail <<END.$msg_if_onlyone if defined $msg_if_onlyone;
5572 only one changes file from build (@changesfiles)
5574 $result = $changesfiles[0];
5575 } elsif (@changesfiles==2) {
5576 my $binchanges = parsecontrol($changesfiles[1], "binary changes file");
5577 foreach my $l (split /\n/, getfield $binchanges, 'Files') {
5578 fail "$l found in binaries changes file $binchanges"
5581 runcmd_ordryrun_local @mergechanges, @changesfiles;
5582 my $multichanges = changespat $version,'multi';
5584 stat_exists $multichanges or fail "$multichanges: $!";
5585 foreach my $cf (glob $pat) {
5586 next if $cf eq $multichanges;
5587 rename "$cf", "$cf.inmulti" or fail "$cf\{,.inmulti}: $!";
5590 $result = $multichanges;
5592 fail "wrong number of different changes files (@changesfiles)";
5594 printdone "build successful, results in $result\n" or die $!;
5597 sub midbuild_checkchanges () {
5598 my $pat = changespat $version;
5599 return if $rmchanges;
5600 my @unwanted = map { s#^\.\./##; $_; } glob "../$pat";
5601 @unwanted = grep { $_ ne changespat $version,'source' } @unwanted;
5603 changes files other than source matching $pat already present; building would result in ambiguity about the intended results.
5604 Suggest you delete @unwanted.
5609 sub midbuild_checkchanges_vanilla ($) {
5611 midbuild_checkchanges() if $wantsrc == 1;
5614 sub postbuild_mergechanges_vanilla ($) {
5616 if ($wantsrc == 1) {
5618 postbuild_mergechanges(undef);
5621 printdone "build successful\n";
5626 my @dbp = (@dpkgbuildpackage, qw(-us -uc), changesopts_initial(), @ARGV);
5627 my $wantsrc = massage_dbp_args \@dbp;
5630 midbuild_checkchanges_vanilla $wantsrc;
5635 push @dbp, changesopts_version();
5636 maybe_apply_patches_dirtily();
5637 runcmd_ordryrun_local @dbp;
5639 maybe_unapply_patches_again();
5640 postbuild_mergechanges_vanilla $wantsrc;
5644 $quilt_mode //= 'gbp';
5650 # gbp can make .origs out of thin air. In my tests it does this
5651 # even for a 1.0 format package, with no origs present. So I
5652 # guess it keys off just the version number. We don't know
5653 # exactly what .origs ought to exist, but let's assume that we
5654 # should run gbp if: the version has an upstream part and the main
5656 my $upstreamversion = upstreamversion $version;
5657 my $origfnpat = srcfn $upstreamversion, '.orig.tar.*';
5658 my $gbp_make_orig = $version =~ m/-/ && !(() = glob "../$origfnpat");
5660 if ($gbp_make_orig) {
5662 $cleanmode = 'none'; # don't do it again
5663 $need_split_build_invocation = 1;
5666 my @dbp = @dpkgbuildpackage;
5668 my $wantsrc = massage_dbp_args \@dbp, \@ARGV;
5670 if (!length $gbp_build[0]) {
5671 if (length executable_on_path('git-buildpackage')) {
5672 $gbp_build[0] = qw(git-buildpackage);
5674 $gbp_build[0] = 'gbp buildpackage';
5677 my @cmd = opts_opt_multi_cmd @gbp_build;
5679 push @cmd, (qw(-us -uc --git-no-sign-tags), "--git-builder=@dbp");
5681 if ($gbp_make_orig) {
5682 ensuredir '.git/dgit';
5683 my $ok = '.git/dgit/origs-gen-ok';
5684 unlink $ok or $!==&ENOENT or die $!;
5685 my @origs_cmd = @cmd;
5686 push @origs_cmd, qw(--git-cleaner=true);
5687 push @origs_cmd, "--git-prebuild=touch $ok .git/dgit/no-such-dir/ok";
5688 push @origs_cmd, @ARGV;
5690 debugcmd @origs_cmd;
5692 do { local $!; stat_exists $ok; }
5693 or failedcmd @origs_cmd;
5695 dryrun_report @origs_cmd;
5701 midbuild_checkchanges_vanilla $wantsrc;
5703 if (!$clean_using_builder) {
5704 push @cmd, '--git-cleaner=true';
5708 maybe_unapply_patches_again();
5710 push @cmd, changesopts();
5711 runcmd_ordryrun_local @cmd, @ARGV;
5713 postbuild_mergechanges_vanilla $wantsrc;
5715 sub cmd_git_build { cmd_gbp_build(); } # compatibility with <= 1.0
5718 my $our_cleanmode = $cleanmode;
5719 if ($need_split_build_invocation) {
5720 # Pretend that clean is being done some other way. This
5721 # forces us not to try to use dpkg-buildpackage to clean and
5722 # build source all in one go; and instead we run dpkg-source
5723 # (and build_prep() will do the clean since $clean_using_builder
5725 $our_cleanmode = 'ELSEWHERE';
5727 if ($our_cleanmode =~ m/^dpkg-source/) {
5728 # dpkg-source invocation (below) will clean, so build_prep shouldn't
5729 $clean_using_builder = 1;
5732 $sourcechanges = changespat $version,'source';
5734 unlink "../$sourcechanges" or $!==ENOENT
5735 or fail "remove $sourcechanges: $!";
5737 $dscfn = dscfn($version);
5738 if ($our_cleanmode eq 'dpkg-source') {
5739 maybe_apply_patches_dirtily();
5740 runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc -S),
5742 } elsif ($our_cleanmode eq 'dpkg-source-d') {
5743 maybe_apply_patches_dirtily();
5744 runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc -S -d),
5747 my @cmd = (@dpkgsource, qw(-b --));
5750 runcmd_ordryrun_local @cmd, "work";
5751 my @udfiles = <${package}_*>;
5752 changedir "../../..";
5753 foreach my $f (@udfiles) {
5754 printdebug "source copy, found $f\n";
5757 ($f =~ m/\.debian\.tar(?:\.\w+)$/ &&
5758 $f eq srcfn($version, $&));
5759 printdebug "source copy, found $f - renaming\n";
5760 rename "$ud/$f", "../$f" or $!==ENOENT
5761 or fail "put in place new source file ($f): $!";
5764 my $pwd = must_getcwd();
5765 my $leafdir = basename $pwd;
5767 runcmd_ordryrun_local @cmd, $leafdir;
5770 runcmd_ordryrun_local qw(sh -ec),
5771 'exec >$1; shift; exec "$@"','x',
5772 "../$sourcechanges",
5773 @dpkggenchanges, qw(-S), changesopts();
5777 sub cmd_build_source {
5778 badusage "build-source takes no additional arguments" if @ARGV;
5780 maybe_unapply_patches_again();
5781 printdone "source built, results in $dscfn and $sourcechanges";
5786 midbuild_checkchanges();
5789 stat_exists $dscfn or fail "$dscfn (in parent directory): $!";
5790 stat_exists $sourcechanges
5791 or fail "$sourcechanges (in parent directory): $!";
5793 runcmd_ordryrun_local @sbuild, qw(-d), $isuite, @ARGV, $dscfn;
5795 maybe_unapply_patches_again();
5797 postbuild_mergechanges(<<END);
5798 perhaps you need to pass -A ? (sbuild's default is to build only
5799 arch-specific binaries; dgit 1.4 used to override that.)
5804 sub cmd_quilt_fixup {
5805 badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
5806 my $clogp = parsechangelog();
5807 $version = getfield $clogp, 'Version';
5808 $package = getfield $clogp, 'Source';
5811 build_maybe_quilt_fixup();
5814 sub cmd_import_dsc {
5818 last unless $ARGV[0] =~ m/^-/;
5821 if (m/^--require-valid-signature$/) {
5824 badusage "unknown dgit import-dsc sub-option \`$_'";
5828 badusage "usage: dgit import-dsc .../PATH/TO/.DSC BRANCH" unless @ARGV==2;
5829 my ($dscfn, $dstbranch) = @ARGV;
5831 badusage "dry run makes no sense with import-dsc" unless act_local();
5833 my $force = $dstbranch =~ s/^\+// ? +1 :
5834 $dstbranch =~ s/^\.\.// ? -1 :
5836 my $info = $force ? " $&" : '';
5837 $info = "$dscfn$info";
5839 my $specbranch = $dstbranch;
5840 $dstbranch = "refs/heads/$dstbranch" unless $dstbranch =~ m#^refs/#;
5841 $dstbranch = cmdoutput @git, qw(check-ref-format --normalize), $dstbranch;
5843 my @symcmd = (@git, qw(symbolic-ref -q HEAD));
5844 my $chead = cmdoutput_errok @symcmd;
5845 defined $chead or $?==256 or failedcmd @symcmd;
5847 fail "$dstbranch is checked out - will not update it"
5848 if defined $chead and $chead eq $dstbranch;
5850 my $oldhash = git_get_ref $dstbranch;
5852 open D, "<", $dscfn or fail "open import .dsc ($dscfn): $!";
5853 $dscdata = do { local $/ = undef; <D>; };
5854 D->error and fail "read $dscfn: $!";
5857 # we don't normally need this so import it here
5858 use Dpkg::Source::Package;
5859 my $dp = new Dpkg::Source::Package filename => $dscfn,
5860 require_valid_signature => $needsig;
5862 local $SIG{__WARN__} = sub {
5864 return unless $needsig;
5865 fail "import-dsc signature check failed";
5867 if (!$dp->is_signed()) {
5868 warn "$us: warning: importing unsigned .dsc\n";
5870 my $r = $dp->check_signature();
5871 die "->check_signature => $r" if $needsig && $r;
5877 my $dgit_commit = $dsc->{$ourdscfield[0]};
5878 if (defined $dgit_commit &&
5879 !forceing [qw(import-dsc-with-dgit-field)]) {
5880 $dgit_commit =~ m/\w+/ or fail "invalid hash in .dsc";
5881 progress "dgit: import-dsc of .dsc with Dgit field, using git hash";
5882 my @cmd = (qw(sh -ec),
5883 "echo $dgit_commit | git cat-file --batch-check");
5884 my $objgot = cmdoutput @cmd;
5885 if ($objgot =~ m#^\w+ missing\b#) {
5887 .dsc contains Dgit field referring to object $dgit_commit
5888 Your git tree does not have that object. Try `git fetch' from a
5889 plausible server (browse.dgit.d.o? alioth?), and try the import-dsc again.
5892 if ($oldhash && !is_fast_fwd $oldhash, $dgit_commit) {
5894 progress "Not fast forward, forced update.";
5896 fail "Not fast forward to $dgit_commit";
5899 @cmd = (@git, qw(update-ref -m), "dgit import-dsc (Dgit): $info",
5900 $dstbranch, $dgit_commit);
5902 progress "dgit: import-dsc updated git ref $dstbranch";
5907 Branch $dstbranch already exists
5908 Specify ..$specbranch for a pseudo-merge, binding in existing history
5909 Specify +$specbranch to overwrite, discarding existing history
5911 if $oldhash && !$force;
5913 $package = getfield $dsc, 'Source';
5914 my @dfi = dsc_files_info();
5915 foreach my $fi (@dfi) {
5916 my $f = $fi->{Filename};
5918 next if lstat $here;
5919 fail "stat $here: $!" unless $! == ENOENT;
5921 if ($dscfn =~ m#^(?:\./+)?\.\./+#) {
5923 } elsif ($dscfn =~ m#^/#) {
5926 fail "cannot import $dscfn which seems to be inside working tree!";
5928 $there =~ s#/+[^/]+$## or
5929 fail "cannot import $dscfn which seems to not have a basename";
5931 symlink $there, $here or fail "symlink $there to $here: $!";
5932 progress "made symlink $here -> $there";
5933 # print STDERR Dumper($fi);
5935 my @mergeinputs = generate_commits_from_dsc();
5936 die unless @mergeinputs == 1;
5938 my $newhash = $mergeinputs[0]{Commit};
5942 progress "Import, forced update - synthetic orphan git history.";
5943 } elsif ($force < 0) {
5944 progress "Import, merging.";
5945 my $tree = cmdoutput @git, qw(rev-parse), "$newhash:";
5946 my $version = getfield $dsc, 'Version';
5947 my $clogp = commit_getclogp $newhash;
5948 my $authline = clogp_authline $clogp;
5949 $newhash = make_commit_text <<END;
5956 Merge $package ($version) import into $dstbranch
5959 die; # caught earlier
5963 my @cmd = (@git, qw(update-ref -m), "dgit import-dsc: $info",
5964 $dstbranch, $newhash);
5966 progress "dgit: import-dsc results are in in git ref $dstbranch";
5969 sub cmd_archive_api_query {
5970 badusage "need only 1 subpath argument" unless @ARGV==1;
5971 my ($subpath) = @ARGV;
5972 my @cmd = archive_api_query_cmd($subpath);
5975 exec @cmd or fail "exec curl: $!\n";
5978 sub cmd_clone_dgit_repos_server {
5979 badusage "need destination argument" unless @ARGV==1;
5980 my ($destdir) = @ARGV;
5981 $package = '_dgit-repos-server';
5982 my @cmd = (@git, qw(clone), access_giturl(), $destdir);
5984 exec @cmd or fail "exec git clone: $!\n";
5987 sub cmd_setup_mergechangelogs {
5988 badusage "no arguments allowed to dgit setup-mergechangelogs" if @ARGV;
5989 setup_mergechangelogs(1);
5992 sub cmd_setup_useremail {
5993 badusage "no arguments allowed to dgit setup-mergechangelogs" if @ARGV;
5997 sub cmd_setup_new_tree {
5998 badusage "no arguments allowed to dgit setup-tree" if @ARGV;
6002 #---------- argument parsing and main program ----------
6005 print "dgit version $our_version\n" or die $!;
6009 our (%valopts_long, %valopts_short);
6012 sub defvalopt ($$$$) {
6013 my ($long,$short,$val_re,$how) = @_;
6014 my $oi = { Long => $long, Short => $short, Re => $val_re, How => $how };
6015 $valopts_long{$long} = $oi;
6016 $valopts_short{$short} = $oi;
6017 # $how subref should:
6018 # do whatever assignemnt or thing it likes with $_[0]
6019 # if the option should not be passed on to remote, @rvalopts=()
6020 # or $how can be a scalar ref, meaning simply assign the value
6023 defvalopt '--since-version', '-v', '[^_]+|_', \$changes_since_version;
6024 defvalopt '--distro', '-d', '.+', \$idistro;
6025 defvalopt '', '-k', '.+', \$keyid;
6026 defvalopt '--existing-package','', '.*', \$existing_package;
6027 defvalopt '--build-products-dir','','.*', \$buildproductsdir;
6028 defvalopt '--clean', '', $cleanmode_re, \$cleanmode;
6029 defvalopt '--package', '-p', $package_re, \$package;
6030 defvalopt '--quilt', '', $quilt_modes_re, \$quilt_mode;
6032 defvalopt '', '-C', '.+', sub {
6033 ($changesfile) = (@_);
6034 if ($changesfile =~ s#^(.*)/##) {
6035 $buildproductsdir = $1;
6039 defvalopt '--initiator-tempdir','','.*', sub {
6040 ($initiator_tempdir) = (@_);
6041 $initiator_tempdir =~ m#^/# or
6042 badusage "--initiator-tempdir must be used specify an".
6043 " absolute, not relative, directory."
6049 if (defined $ENV{'DGIT_SSH'}) {
6050 @ssh = string_to_ssh $ENV{'DGIT_SSH'};
6051 } elsif (defined $ENV{'GIT_SSH'}) {
6052 @ssh = ($ENV{'GIT_SSH'});
6060 if (!defined $val) {
6061 badusage "$what needs a value" unless @ARGV;
6063 push @rvalopts, $val;
6065 badusage "bad value \`$val' for $what" unless
6066 $val =~ m/^$oi->{Re}$(?!\n)/s;
6067 my $how = $oi->{How};
6068 if (ref($how) eq 'SCALAR') {
6073 push @ropts, @rvalopts;
6077 last unless $ARGV[0] =~ m/^-/;
6081 if (m/^--dry-run$/) {
6084 } elsif (m/^--damp-run$/) {
6087 } elsif (m/^--no-sign$/) {
6090 } elsif (m/^--help$/) {
6092 } elsif (m/^--version$/) {
6094 } elsif (m/^--new$/) {
6097 } elsif (m/^--([-0-9a-z]+)=(.+)/s &&
6098 ($om = $opts_opt_map{$1}) &&
6102 } elsif (m/^--([-0-9a-z]+):(.*)/s &&
6103 !$opts_opt_cmdonly{$1} &&
6104 ($om = $opts_opt_map{$1})) {
6107 } elsif (m/^--(gbp|dpm)$/s) {
6108 push @ropts, "--quilt=$1";
6110 } elsif (m/^--ignore-dirty$/s) {
6113 } elsif (m/^--no-quilt-fixup$/s) {
6115 $quilt_mode = 'nocheck';
6116 } elsif (m/^--no-rm-on-error$/s) {
6119 } elsif (m/^--overwrite$/s) {
6121 $overwrite_version = '';
6122 } elsif (m/^--overwrite=(.+)$/s) {
6124 $overwrite_version = $1;
6125 } elsif (m/^--dep14tag$/s) {
6127 $dodep14tag= 'want';
6128 } elsif (m/^--no-dep14tag$/s) {
6131 } elsif (m/^--always-dep14tag$/s) {
6133 $dodep14tag= 'always';
6134 } elsif (m/^--delayed=(\d+)$/s) {
6137 } elsif (m/^--dgit-view-save=(.+)$/s) {
6139 $split_brain_save = $1;
6140 $split_brain_save =~ s#^(?!refs/)#refs/heads/#;
6141 } elsif (m/^--(no-)?rm-old-changes$/s) {
6144 } elsif (m/^--deliberately-($deliberately_re)$/s) {
6146 push @deliberatelies, $&;
6147 } elsif (m/^--force-(.*)/ && defined $forceopts{$1}) {
6151 } elsif (m/^--force-/) {
6153 "$us: warning: ignoring unknown force option $_\n";
6155 } elsif (m/^--dgit-tag-format=(old|new)$/s) {
6156 # undocumented, for testing
6158 $tagformat_want = [ $1, 'command line', 1 ];
6159 # 1 menas overrides distro configuration
6160 } elsif (m/^--always-split-source-build$/s) {
6161 # undocumented, for testing
6163 $need_split_build_invocation = 1;
6164 } elsif (m/^(--[-0-9a-z]+)(=|$)/ && ($oi = $valopts_long{$1})) {
6165 $val = $2 ? $' : undef; #';
6166 $valopt->($oi->{Long});
6168 badusage "unknown long option \`$_'";
6175 } elsif (s/^-L/-/) {
6178 } elsif (s/^-h/-/) {
6180 } elsif (s/^-D/-/) {
6184 } elsif (s/^-N/-/) {
6189 push @changesopts, $_;
6191 } elsif (s/^-wn$//s) {
6193 $cleanmode = 'none';
6194 } elsif (s/^-wg$//s) {
6197 } elsif (s/^-wgf$//s) {
6199 $cleanmode = 'git-ff';
6200 } elsif (s/^-wd$//s) {
6202 $cleanmode = 'dpkg-source';
6203 } elsif (s/^-wdd$//s) {
6205 $cleanmode = 'dpkg-source-d';
6206 } elsif (s/^-wc$//s) {
6208 $cleanmode = 'check';
6209 } elsif (s/^-c([^=]*)\=(.*)$//s) {
6210 push @git, '-c', $&;
6211 $gitcfgs{cmdline}{$1} = [ $2 ];
6212 } elsif (s/^-c([^=]+)$//s) {
6213 push @git, '-c', $&;
6214 $gitcfgs{cmdline}{$1} = [ 'true' ];
6215 } elsif (m/^-[a-zA-Z]/ && ($oi = $valopts_short{$&})) {
6217 $val = undef unless length $val;
6218 $valopt->($oi->{Short});
6221 badusage "unknown short option \`$_'";
6228 sub check_env_sanity () {
6229 my $blocked = new POSIX::SigSet;
6230 sigprocmask SIG_UNBLOCK, $blocked, $blocked or die $!;
6233 foreach my $name (qw(PIPE CHLD)) {
6234 my $signame = "SIG$name";
6235 my $signum = eval "POSIX::$signame" // die;
6236 ($SIG{$name} // 'DEFAULT') eq 'DEFAULT' or
6237 die "$signame is set to something other than SIG_DFL\n";
6238 $blocked->ismember($signum) and
6239 die "$signame is blocked\n";
6245 On entry to dgit, $@
6246 This is a bug produced by something in in your execution environment.
6252 sub finalise_opts_opts () {
6253 foreach my $k (keys %opts_opt_map) {
6254 my $om = $opts_opt_map{$k};
6256 my $v = access_cfg("cmd-$k", 'RETURN-UNDEF');
6258 badcfg "cannot set command for $k"
6259 unless length $om->[0];
6263 foreach my $c (access_cfg_cfgs("opts-$k")) {
6265 map { $_ ? @$_ : () }
6266 map { $gitcfgs{$_}{$c} }
6267 reverse @gitcfgsources;
6268 printdebug "CL $c ", (join " ", map { shellquote } @vl),
6269 "\n" if $debuglevel >= 4;
6271 badcfg "cannot configure options for $k"
6272 if $opts_opt_cmdonly{$k};
6273 my $insertpos = $opts_cfg_insertpos{$k};
6274 @$om = ( @$om[0..$insertpos-1],
6276 @$om[$insertpos..$#$om] );
6281 if ($ENV{$fakeeditorenv}) {
6283 quilt_fixup_editor();
6290 print STDERR "DRY RUN ONLY\n" if $dryrun_level > 1;
6291 print STDERR "DAMP RUN - WILL MAKE LOCAL (UNSIGNED) CHANGES\n"
6292 if $dryrun_level == 1;
6294 print STDERR $helpmsg or die $!;
6297 my $cmd = shift @ARGV;
6300 my $pre_fn = ${*::}{"pre_$cmd"};
6301 $pre_fn->() if $pre_fn;
6303 if (!defined $rmchanges) {
6304 local $access_forpush;
6305 $rmchanges = access_cfg_bool(0, 'rm-old-changes');
6308 if (!defined $quilt_mode) {
6309 local $access_forpush;
6310 $quilt_mode = cfg('dgit.force.quilt-mode', 'RETURN-UNDEF')
6311 // access_cfg('quilt-mode', 'RETURN-UNDEF')
6313 $quilt_mode =~ m/^($quilt_modes_re)$/
6314 or badcfg "unknown quilt-mode \`$quilt_mode'";
6318 if (!defined $dodep14tag) {
6319 local $access_forpush;
6320 $dodep14tag = access_cfg('dep14tag', 'RETURN-UNDEF') // 'want';
6321 $dodep14tag =~ m/^($dodep14tag_re)$/
6322 or badcfg "unknown dep14tag setting \`$dodep14tag'";
6326 $need_split_build_invocation ||= quiltmode_splitbrain();
6328 if (!defined $cleanmode) {
6329 local $access_forpush;
6330 $cleanmode = access_cfg('clean-mode', 'RETURN-UNDEF');
6331 $cleanmode //= 'dpkg-source';
6333 badcfg "unknown clean-mode \`$cleanmode'" unless
6334 $cleanmode =~ m/^($cleanmode_re)$(?!\n)/s;
6337 my $fn = ${*::}{"cmd_$cmd"};
6338 $fn or badusage "unknown operation $cmd";