3 # Integration between git and Debian-style archives
5 # Copyright (C)2013-2017 Ian Jackson
6 # Copyright (C)2017 Sean Whitton
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 END { $? = $Debian::Dgit::ExitStatus::desired // -1; };
22 use Debian::Dgit::ExitStatus;
26 use Debian::Dgit qw(:DEFAULT :playground);
32 use Dpkg::Control::Hash;
34 use File::Temp qw(tempdir);
37 use Dpkg::Compression;
38 use Dpkg::Compression::Process;
43 use List::MoreUtils qw(pairwise);
44 use Text::Glob qw(match_glob);
45 use Fcntl qw(:DEFAULT :flock);
50 our $our_version = 'UNRELEASED'; ###substituted###
51 our $absurdity = undef; ###substituted###
53 our @rpushprotovsn_support = qw(4 3 2); # 4 is new tag format
64 our $dryrun_level = 0;
66 our $buildproductsdir = '..';
72 our $existing_package = 'dpkg';
74 our $changes_since_version;
76 our $overwrite_version; # undef: not specified; '': check changelog
78 our $quilt_modes_re = 'linear|smash|auto|nofix|nocheck|gbp|dpm|unapplied';
80 our $split_brain_save;
81 our $we_are_responder;
82 our $we_are_initiator;
83 our $initiator_tempdir;
84 our $patches_applied_dirtily = 00;
88 our $chase_dsc_distro=1;
90 our %forceopts = map { $_=>0 }
91 qw(unrepresentable unsupported-source-format
92 dsc-changes-mismatch changes-origs-exactly
93 import-gitapply-absurd
94 import-gitapply-no-absurd
95 import-dsc-with-dgit-field);
97 our %format_ok = map { $_=>1 } ("1.0","3.0 (native)","3.0 (quilt)");
99 our $suite_re = '[-+.0-9a-z]+';
100 our $cleanmode_re = 'dpkg-source(?:-d)?|git|git-ff|check|none';
101 our $orig_f_comp_re = qr{orig(?:-$extra_orig_namepart_re)?};
102 our $orig_f_sig_re = '\\.(?:asc|gpg|pgp)';
103 our $orig_f_tail_re = "$orig_f_comp_re\\.tar(?:\\.\\w+)?(?:$orig_f_sig_re)?";
105 our $git_authline_re = '^([^<>]+) \<(\S+)\> (\d+ [-+]\d+)$';
106 our $splitbraincache = 'dgit-intern/quilt-cache';
107 our $rewritemap = 'dgit-rewrite/map';
109 our @dpkg_source_ignores = qw(-i(?:^|/)\.git(?:/|$) -I.git);
111 our (@git) = qw(git);
112 our (@dget) = qw(dget);
113 our (@curl) = (qw(curl --proto-redir), '-all,http,https', qw(-L));
114 our (@dput) = qw(dput);
115 our (@debsign) = qw(debsign);
116 our (@gpg) = qw(gpg);
117 our (@sbuild) = qw(sbuild);
119 our (@dgit) = qw(dgit);
120 our (@git_debrebase) = qw(git-debrebase);
121 our (@aptget) = qw(apt-get);
122 our (@aptcache) = qw(apt-cache);
123 our (@dpkgbuildpackage) = (qw(dpkg-buildpackage), @dpkg_source_ignores);
124 our (@dpkgsource) = (qw(dpkg-source), @dpkg_source_ignores);
125 our (@dpkggenchanges) = qw(dpkg-genchanges);
126 our (@mergechanges) = qw(mergechanges -f);
127 our (@gbp_build) = ('');
128 our (@gbp_pq) = ('gbp pq');
129 our (@changesopts) = ('');
131 our %opts_opt_map = ('dget' => \@dget, # accept for compatibility
134 'debsign' => \@debsign,
136 'sbuild' => \@sbuild,
140 'git-debrebase' => \@git_debrebase,
141 'apt-get' => \@aptget,
142 'apt-cache' => \@aptcache,
143 'dpkg-source' => \@dpkgsource,
144 'dpkg-buildpackage' => \@dpkgbuildpackage,
145 'dpkg-genchanges' => \@dpkggenchanges,
146 'gbp-build' => \@gbp_build,
147 'gbp-pq' => \@gbp_pq,
148 'ch' => \@changesopts,
149 'mergechanges' => \@mergechanges);
151 our %opts_opt_cmdonly = ('gpg' => 1, 'git' => 1);
152 our %opts_cfg_insertpos = map {
154 scalar @{ $opts_opt_map{$_} }
155 } keys %opts_opt_map;
157 sub parseopts_late_defaults();
158 sub setup_gitattrs(;$);
159 sub check_gitattrs($$);
166 our $supplementary_message = '';
167 our $need_split_build_invocation = 0;
168 our $split_brain = 0;
172 return unless forkcheck_mainprocess();
173 print STDERR "! $_\n" foreach $supplementary_message =~ m/^.+$/mg;
176 our $remotename = 'dgit';
177 our @ourdscfield = qw(Dgit Vcs-Dgit-Master);
181 if (!defined $absurdity) {
183 $absurdity =~ s{/[^/]+$}{/absurd} or die;
187 my ($v,$distro) = @_;
188 return $tagformatfn->($v, $distro);
191 sub debiantag_maintview ($$) {
192 my ($v,$distro) = @_;
193 return "$distro/".dep14_version_mangle $v;
196 sub madformat ($) { $_[0] eq '3.0 (quilt)' }
198 sub lbranch () { return "$branchprefix/$csuite"; }
199 my $lbranch_re = '^refs/heads/'.$branchprefix.'/([^/.]+)$';
200 sub lref () { return "refs/heads/".lbranch(); }
201 sub lrref () { return "refs/remotes/$remotename/".server_branch($csuite); }
202 sub rrref () { return server_ref($csuite); }
212 return "${package}_".(stripepoch $vsn).$sfx
217 return srcfn($vsn,".dsc");
220 sub changespat ($;$) {
221 my ($vsn, $arch) = @_;
222 return "${package}_".(stripepoch $vsn)."_".($arch//'*').".changes";
225 sub upstreamversion ($) {
237 return unless forkcheck_mainprocess();
238 foreach my $f (@end) {
240 print STDERR "$us: cleanup: $@" if length $@;
244 sub badcfg { print STDERR "$us: invalid configuration: @_\n"; finish 12; }
246 sub forceable_fail ($$) {
247 my ($forceoptsl, $msg) = @_;
248 fail $msg unless grep { $forceopts{$_} } @$forceoptsl;
249 print STDERR "warning: overriding problem due to --force:\n". $msg;
253 my ($forceoptsl) = @_;
254 my @got = grep { $forceopts{$_} } @$forceoptsl;
255 return 0 unless @got;
257 "warning: skipping checks or functionality due to --force-$got[0]\n";
260 sub no_such_package () {
261 print STDERR "$us: package $package does not exist in suite $isuite\n";
265 sub deliberately ($) {
267 return !!grep { $_ eq "--deliberately-$enquiry" } @deliberatelies;
270 sub deliberately_not_fast_forward () {
271 foreach (qw(not-fast-forward fresh-repo)) {
272 return 1 if deliberately($_) || deliberately("TEST-dgit-only-$_");
276 sub quiltmode_splitbrain () {
277 $quilt_mode =~ m/gbp|dpm|unapplied/;
280 sub opts_opt_multi_cmd {
282 push @cmd, split /\s+/, shift @_;
288 return opts_opt_multi_cmd @gbp_pq;
291 sub dgit_privdir () {
292 our $dgit_privdir_made //= ensure_a_playground 'dgit';
295 sub branch_gdr_info ($$) {
296 my ($symref, $head) = @_;
297 my ($status, $msg, $current, $ffq_prev, $gdrlast) =
298 gdr_ffq_prev_branchinfo($symref);
299 return () unless $status eq 'branch';
300 $ffq_prev = git_get_ref $ffq_prev;
301 $gdrlast = git_get_ref $gdrlast;
302 $gdrlast &&= is_fast_fwd $gdrlast, $head;
303 return ($ffq_prev, $gdrlast);
306 sub branch_is_gdr ($$) {
307 my ($symref, $head) = @_;
308 my ($ffq_prev, $gdrlast) = branch_gdr_info($symref, $head);
309 return 0 unless $ffq_prev || $gdrlast;
313 sub branch_is_gdr_unstitched_ff ($$$) {
314 my ($symref, $head, $ancestor) = @_;
315 my ($ffq_prev, $gdrlast) = branch_gdr_info($symref, $head);
316 return 0 unless $ffq_prev;
317 return 0 unless is_fast_fwd $ancestor, $ffq_prev;
321 #---------- remote protocol support, common ----------
323 # remote push initiator/responder protocol:
324 # $ dgit remote-push-build-host <n-rargs> <rargs>... <push-args>...
325 # where <rargs> is <push-host-dir> <supported-proto-vsn>,... ...
326 # < dgit-remote-push-ready <actual-proto-vsn>
333 # > supplementary-message NBYTES # $protovsn >= 3
338 # > file parsed-changelog
339 # [indicates that output of dpkg-parsechangelog follows]
340 # > data-block NBYTES
341 # > [NBYTES bytes of data (no newline)]
342 # [maybe some more blocks]
351 # > param head DGIT-VIEW-HEAD
352 # > param csuite SUITE
353 # > param tagformat old|new
354 # > param maint-view MAINT-VIEW-HEAD
356 # > param buildinfo-filename P_V_X.buildinfo # zero or more times
357 # > file buildinfo # for buildinfos to sign
359 # > previously REFNAME=OBJNAME # if --deliberately-not-fast-forward
360 # # goes into tag, for replay prevention
363 # [indicates that signed tag is wanted]
364 # < data-block NBYTES
365 # < [NBYTES bytes of data (no newline)]
366 # [maybe some more blocks]
370 # > want signed-dsc-changes
371 # < data-block NBYTES [transfer of signed dsc]
373 # < data-block NBYTES [transfer of signed changes]
375 # < data-block NBYTES [transfer of each signed buildinfo
376 # [etc] same number and order as "file buildinfo"]
384 sub i_child_report () {
385 # Sees if our child has died, and reap it if so. Returns a string
386 # describing how it died if it failed, or undef otherwise.
387 return undef unless $i_child_pid;
388 my $got = waitpid $i_child_pid, WNOHANG;
389 return undef if $got <= 0;
390 die unless $got == $i_child_pid;
391 $i_child_pid = undef;
392 return undef unless $?;
393 return "build host child ".waitstatusmsg();
398 fail "connection lost: $!" if $fh->error;
399 fail "protocol violation; $m not expected";
402 sub badproto_badread ($$) {
404 fail "connection lost: $!" if $!;
405 my $report = i_child_report();
406 fail $report if defined $report;
407 badproto $fh, "eof (reading $wh)";
410 sub protocol_expect (&$) {
411 my ($match, $fh) = @_;
414 defined && chomp or badproto_badread $fh, "protocol message";
422 badproto $fh, "\`$_'";
425 sub protocol_send_file ($$) {
426 my ($fh, $ourfn) = @_;
427 open PF, "<", $ourfn or die "$ourfn: $!";
430 my $got = read PF, $d, 65536;
431 die "$ourfn: $!" unless defined $got;
433 print $fh "data-block ".length($d)."\n" or die $!;
434 print $fh $d or die $!;
436 PF->error and die "$ourfn $!";
437 print $fh "data-end\n" or die $!;
441 sub protocol_read_bytes ($$) {
442 my ($fh, $nbytes) = @_;
443 $nbytes =~ m/^[1-9]\d{0,5}$|^0$/ or badproto \*RO, "bad byte count";
445 my $got = read $fh, $d, $nbytes;
446 $got==$nbytes or badproto_badread $fh, "data block";
450 sub protocol_receive_file ($$) {
451 my ($fh, $ourfn) = @_;
452 printdebug "() $ourfn\n";
453 open PF, ">", $ourfn or die "$ourfn: $!";
455 my ($y,$l) = protocol_expect {
456 m/^data-block (.*)$/ ? (1,$1) :
457 m/^data-end$/ ? (0,) :
461 my $d = protocol_read_bytes $fh, $l;
462 print PF $d or die $!;
467 #---------- remote protocol support, responder ----------
469 sub responder_send_command ($) {
471 return unless $we_are_responder;
472 # called even without $we_are_responder
473 printdebug ">> $command\n";
474 print PO $command, "\n" or die $!;
477 sub responder_send_file ($$) {
478 my ($keyword, $ourfn) = @_;
479 return unless $we_are_responder;
480 printdebug "]] $keyword $ourfn\n";
481 responder_send_command "file $keyword";
482 protocol_send_file \*PO, $ourfn;
485 sub responder_receive_files ($@) {
486 my ($keyword, @ourfns) = @_;
487 die unless $we_are_responder;
488 printdebug "[[ $keyword @ourfns\n";
489 responder_send_command "want $keyword";
490 foreach my $fn (@ourfns) {
491 protocol_receive_file \*PI, $fn;
494 protocol_expect { m/^files-end$/ } \*PI;
497 #---------- remote protocol support, initiator ----------
499 sub initiator_expect (&) {
501 protocol_expect { &$match } \*RO;
504 #---------- end remote code ----------
507 if ($we_are_responder) {
509 responder_send_command "progress ".length($m) or die $!;
510 print PO $m or die $!;
520 $ua = LWP::UserAgent->new();
524 progress "downloading $what...";
525 my $r = $ua->get(@_) or die $!;
526 return undef if $r->code == 404;
527 $r->is_success or fail "failed to fetch $what: ".$r->status_line;
528 return $r->decoded_content(charset => 'none');
531 our ($dscdata,$dscurl,$dsc,$dsc_checked,$skew_warning_vsn);
533 sub act_local () { return $dryrun_level <= 1; }
534 sub act_scary () { return !$dryrun_level; }
537 if (!$dryrun_level) {
538 progress "$us ok: @_";
540 progress "would be ok: @_ (but dry run only)";
545 printcmd(\*STDERR,$debugprefix."#",@_);
548 sub runcmd_ordryrun {
556 sub runcmd_ordryrun_local {
564 our $helpmsg = <<END;
566 dgit [dgit-opts] clone [dgit-opts] package [suite] [./dir|/dir]
567 dgit [dgit-opts] fetch|pull [dgit-opts] [suite]
568 dgit [dgit-opts] build [dpkg-buildpackage-opts]
569 dgit [dgit-opts] sbuild [sbuild-opts]
570 dgit [dgit-opts] push [dgit-opts] [suite]
571 dgit [dgit-opts] push-source [dgit-opts] [suite]
572 dgit [dgit-opts] rpush build-host:build-dir ...
573 important dgit options:
574 -k<keyid> sign tag and package with <keyid> instead of default
575 --dry-run -n do not change anything, but go through the motions
576 --damp-run -L like --dry-run but make local changes, without signing
577 --new -N allow introducing a new package
578 --debug -D increase debug level
579 -c<name>=<value> set git config option (used directly by dgit too)
582 our $later_warning_msg = <<END;
583 Perhaps the upload is stuck in incoming. Using the version from git.
587 print STDERR "$us: @_\n", $helpmsg or die $!;
592 @ARGV or badusage "too few arguments";
593 return scalar shift @ARGV;
597 not_necessarily_a_tree();
600 print $helpmsg or die $!;
604 our $td = $ENV{DGIT_TEST_DUMMY_DIR} || "DGIT_TEST_DUMMY_DIR-unset";
606 our %defcfg = ('dgit.default.distro' => 'debian',
607 'dgit.default.default-suite' => 'unstable',
608 'dgit.default.old-dsc-distro' => 'debian',
609 'dgit-suite.*-security.distro' => 'debian-security',
610 'dgit.default.username' => '',
611 'dgit.default.archive-query-default-component' => 'main',
612 'dgit.default.ssh' => 'ssh',
613 'dgit.default.archive-query' => 'madison:',
614 'dgit.default.sshpsql-dbname' => 'service=projectb',
615 'dgit.default.aptget-components' => 'main',
616 'dgit.default.dgit-tag-format' => 'new,old,maint',
617 'dgit.default.source-only-uploads' => 'ok',
618 'dgit.dsc-url-proto-ok.http' => 'true',
619 'dgit.dsc-url-proto-ok.https' => 'true',
620 'dgit.dsc-url-proto-ok.git' => 'true',
621 'dgit.vcs-git.suites', => 'sid', # ;-separated
622 'dgit.default.dsc-url-proto-ok' => 'false',
623 # old means "repo server accepts pushes with old dgit tags"
624 # new means "repo server accepts pushes with new dgit tags"
625 # maint means "repo server accepts split brain pushes"
626 # hist means "repo server may have old pushes without new tag"
627 # ("hist" is implied by "old")
628 'dgit-distro.debian.archive-query' => 'ftpmasterapi:',
629 'dgit-distro.debian.git-check' => 'url',
630 'dgit-distro.debian.git-check-suffix' => '/info/refs',
631 'dgit-distro.debian.new-private-pushers' => 't',
632 'dgit-distro.debian.source-only-uploads' => 'not-wholly-new',
633 'dgit-distro.debian/push.git-url' => '',
634 'dgit-distro.debian/push.git-host' => 'push.dgit.debian.org',
635 'dgit-distro.debian/push.git-user-force' => 'dgit',
636 'dgit-distro.debian/push.git-proto' => 'git+ssh://',
637 'dgit-distro.debian/push.git-path' => '/dgit/debian/repos',
638 'dgit-distro.debian/push.git-create' => 'true',
639 'dgit-distro.debian/push.git-check' => 'ssh-cmd',
640 'dgit-distro.debian.archive-query-url', 'https://api.ftp-master.debian.org/',
641 # 'dgit-distro.debian.archive-query-tls-key',
642 # '/etc/ssl/certs/%HOST%.pem:/etc/dgit/%HOST%.pem',
643 # ^ this does not work because curl is broken nowadays
644 # Fixing #790093 properly will involve providing providing the key
645 # in some pacagke and maybe updating these paths.
647 # 'dgit-distro.debian.archive-query-tls-curl-args',
648 # '--ca-path=/etc/ssl/ca-debian',
649 # ^ this is a workaround but works (only) on DSA-administered machines
650 'dgit-distro.debian.git-url' => 'https://git.dgit.debian.org',
651 'dgit-distro.debian.git-url-suffix' => '',
652 'dgit-distro.debian.upload-host' => 'ftp-master', # for dput
653 'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/',
654 'dgit-distro.debian-security.archive-query' => 'aptget:',
655 'dgit-distro.debian-security.mirror' => 'http://security.debian.org/debian-security/',
656 'dgit-distro.debian-security.aptget-suite-map' => 's#-security$#/updates#',
657 'dgit-distro.debian-security.aptget-suite-rmap' => 's#$#-security#',
658 'dgit-distro.debian-security.nominal-distro' => 'debian',
659 'dgit-distro.debian.backports-quirk' => '(squeeze)-backports*',
660 'dgit-distro.debian-backports.mirror' => 'http://backports.debian.org/debian-backports/',
661 'dgit-distro.ubuntu.git-check' => 'false',
662 'dgit-distro.ubuntu.mirror' => 'http://archive.ubuntu.com/ubuntu',
663 'dgit-distro.test-dummy.ssh' => "$td/ssh",
664 'dgit-distro.test-dummy.username' => "alice",
665 'dgit-distro.test-dummy.git-check' => "ssh-cmd",
666 'dgit-distro.test-dummy.git-create' => "ssh-cmd",
667 'dgit-distro.test-dummy.git-url' => "$td/git",
668 'dgit-distro.test-dummy.git-host' => "git",
669 'dgit-distro.test-dummy.git-path' => "$td/git",
670 'dgit-distro.test-dummy.archive-query' => "dummycatapi:",
671 'dgit-distro.test-dummy.archive-query-url' => "file://$td/aq/",
672 'dgit-distro.test-dummy.mirror' => "file://$td/mirror/",
673 'dgit-distro.test-dummy.upload-host' => 'test-dummy',
677 our @gitcfgsources = qw(cmdline local global system);
678 our $invoked_in_git_tree = 1;
680 sub git_slurp_config () {
681 # This algoritm is a bit subtle, but this is needed so that for
682 # options which we want to be single-valued, we allow the
683 # different config sources to override properly. See #835858.
684 foreach my $src (@gitcfgsources) {
685 next if $src eq 'cmdline';
686 # we do this ourselves since git doesn't handle it
688 $gitcfgs{$src} = git_slurp_config_src $src;
692 sub git_get_config ($) {
694 foreach my $src (@gitcfgsources) {
695 my $l = $gitcfgs{$src}{$c};
696 confess "internal error ($l $c)" if $l && !ref $l;
697 printdebug"C $c ".(defined $l ?
698 join " ", map { messagequote "'$_'" } @$l :
702 @$l==1 or badcfg "multiple values for $c".
703 " (in $src git config)" if @$l > 1;
711 return undef if $c =~ /RETURN-UNDEF/;
712 printdebug "C? $c\n" if $debuglevel >= 5;
713 my $v = git_get_config($c);
714 return $v if defined $v;
715 my $dv = $defcfg{$c};
717 printdebug "CD $c $dv\n" if $debuglevel >= 4;
721 badcfg "need value for one of: @_\n".
722 "$us: distro or suite appears not to be (properly) supported";
725 sub not_necessarily_a_tree () {
726 # needs to be called from pre_*
727 @gitcfgsources = grep { $_ ne 'local' } @gitcfgsources;
728 $invoked_in_git_tree = 0;
731 sub access_basedistro__noalias () {
732 if (defined $idistro) {
735 my $def = cfg("dgit-suite.$isuite.distro", 'RETURN-UNDEF');
736 return $def if defined $def;
737 foreach my $src (@gitcfgsources, 'internal') {
738 my $kl = $src eq 'internal' ? \%defcfg : $gitcfgs{$src};
740 foreach my $k (keys %$kl) {
741 next unless $k =~ m#^dgit-suite\.(.*)\.distro$#;
743 next unless match_glob $dpat, $isuite;
747 return cfg("dgit.default.distro");
751 sub access_basedistro () {
752 my $noalias = access_basedistro__noalias();
753 my $canon = cfg("dgit-distro.$noalias.alias-canon",'RETURN-UNDEF');
754 return $canon // $noalias;
757 sub access_nomdistro () {
758 my $base = access_basedistro();
759 my $r = cfg("dgit-distro.$base.nominal-distro",'RETURN-UNDEF') // $base;
760 $r =~ m/^$distro_re$/ or badcfg
761 "bad syntax for (nominal) distro \`$r' (does not match /^$distro_re$/)";
765 sub access_quirk () {
766 # returns (quirk name, distro to use instead or undef, quirk-specific info)
767 my $basedistro = access_basedistro();
768 my $backports_quirk = cfg("dgit-distro.$basedistro.backports-quirk",
770 if (defined $backports_quirk) {
771 my $re = $backports_quirk;
772 $re =~ s/[^-0-9a-z_\%*()]/\\$&/ig;
774 $re =~ s/\%/([-0-9a-z_]+)/
775 or $re =~ m/[()]/ or badcfg "backports-quirk needs \% or ( )";
776 if ($isuite =~ m/^$re$/) {
777 return ('backports',"$basedistro-backports",$1);
780 return ('none',undef);
785 sub parse_cfg_bool ($$$) {
786 my ($what,$def,$v) = @_;
789 $v =~ m/^[ty1]/ ? 1 :
790 $v =~ m/^[fn0]/ ? 0 :
791 badcfg "$what needs t (true, y, 1) or f (false, n, 0) not \`$v'";
794 sub access_forpush_config () {
795 my $d = access_basedistro();
799 parse_cfg_bool('new-private-pushers', 0,
800 cfg("dgit-distro.$d.new-private-pushers",
803 my $v = cfg("dgit-distro.$d.readonly", 'RETURN-UNDEF');
806 $v =~ m/^[ty1]/ ? 0 : # force readonly, forpush = 0
807 $v =~ m/^[fn0]/ ? 1 : # force nonreadonly, forpush = 1
808 $v =~ m/^[a]/ ? '' : # auto, forpush = ''
809 badcfg "readonly needs t (true, y, 1) or f (false, n, 0) or a (auto)";
812 sub access_forpush () {
813 $access_forpush //= access_forpush_config();
814 return $access_forpush;
818 die "$access_forpush ?" if ($access_forpush // 1) ne 1;
819 badcfg "pushing but distro is configured readonly"
820 if access_forpush_config() eq '0';
822 $supplementary_message = <<'END' unless $we_are_responder;
823 Push failed, before we got started.
824 You can retry the push, after fixing the problem, if you like.
826 parseopts_late_defaults();
830 parseopts_late_defaults();
833 sub supplementary_message ($) {
835 if (!$we_are_responder) {
836 $supplementary_message = $msg;
838 } elsif ($protovsn >= 3) {
839 responder_send_command "supplementary-message ".length($msg)
841 print PO $msg or die $!;
845 sub access_distros () {
846 # Returns list of distros to try, in order
849 # 0. `instead of' distro name(s) we have been pointed to
850 # 1. the access_quirk distro, if any
851 # 2a. the user's specified distro, or failing that } basedistro
852 # 2b. the distro calculated from the suite }
853 my @l = access_basedistro();
855 my (undef,$quirkdistro) = access_quirk();
856 unshift @l, $quirkdistro;
857 unshift @l, $instead_distro;
858 @l = grep { defined } @l;
860 push @l, access_nomdistro();
862 if (access_forpush()) {
863 @l = map { ("$_/push", $_) } @l;
868 sub access_cfg_cfgs (@) {
871 # The nesting of these loops determines the search order. We put
872 # the key loop on the outside so that we search all the distros
873 # for each key, before going on to the next key. That means that
874 # if access_cfg is called with a more specific, and then a less
875 # specific, key, an earlier distro can override the less specific
876 # without necessarily overriding any more specific keys. (If the
877 # distro wants to override the more specific keys it can simply do
878 # so; whereas if we did the loop the other way around, it would be
879 # impossible to for an earlier distro to override a less specific
880 # key but not the more specific ones without restating the unknown
881 # values of the more specific keys.
884 # We have to deal with RETURN-UNDEF specially, so that we don't
885 # terminate the search prematurely.
887 if (m/RETURN-UNDEF/) { push @rundef, $_; last; }
890 foreach my $d (access_distros()) {
891 push @cfgs, map { "dgit-distro.$d.$_" } @realkeys;
893 push @cfgs, map { "dgit.default.$_" } @realkeys;
900 my (@cfgs) = access_cfg_cfgs(@keys);
901 my $value = cfg(@cfgs);
905 sub access_cfg_bool ($$) {
906 my ($def, @keys) = @_;
907 parse_cfg_bool($keys[0], $def, access_cfg(@keys, 'RETURN-UNDEF'));
910 sub string_to_ssh ($) {
912 if ($spec =~ m/\s/) {
913 return qw(sh -ec), 'exec '.$spec.' "$@"', 'x';
919 sub access_cfg_ssh () {
920 my $gitssh = access_cfg('ssh', 'RETURN-UNDEF');
921 if (!defined $gitssh) {
924 return string_to_ssh $gitssh;
928 sub access_runeinfo ($) {
930 return ": dgit ".access_basedistro()." $info ;";
933 sub access_someuserhost ($) {
935 my $user = access_cfg("$some-user-force", 'RETURN-UNDEF');
936 defined($user) && length($user) or
937 $user = access_cfg("$some-user",'username');
938 my $host = access_cfg("$some-host");
939 return length($user) ? "$user\@$host" : $host;
942 sub access_gituserhost () {
943 return access_someuserhost('git');
946 sub access_giturl (;$) {
948 my $url = access_cfg('git-url','RETURN-UNDEF');
951 my $proto = access_cfg('git-proto', 'RETURN-UNDEF');
952 return undef unless defined $proto;
955 access_gituserhost().
956 access_cfg('git-path');
958 $suffix = access_cfg('git-url-suffix','RETURN-UNDEF');
961 return "$url/$package$suffix";
964 sub parsecontrolfh ($$;$) {
965 my ($fh, $desc, $allowsigned) = @_;
966 our $dpkgcontrolhash_noissigned;
969 my %opts = ('name' => $desc);
970 $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
971 $c = Dpkg::Control::Hash->new(%opts);
972 $c->parse($fh,$desc) or die "parsing of $desc failed";
973 last if $allowsigned;
974 last if $dpkgcontrolhash_noissigned;
975 my $issigned= $c->get_option('is_pgp_signed');
976 if (!defined $issigned) {
977 $dpkgcontrolhash_noissigned= 1;
978 seek $fh, 0,0 or die "seek $desc: $!";
979 } elsif ($issigned) {
980 fail "control file $desc is (already) PGP-signed. ".
981 " Note that dgit push needs to modify the .dsc and then".
982 " do the signature itself";
991 my ($file, $desc, $allowsigned) = @_;
992 my $fh = new IO::Handle;
993 open $fh, '<', $file or die "$file: $!";
994 my $c = parsecontrolfh($fh,$desc,$allowsigned);
995 $fh->error and die $!;
1001 my ($dctrl,$field) = @_;
1002 my $v = $dctrl->{$field};
1003 return $v if defined $v;
1004 fail "missing field $field in ".$dctrl->get_option('name');
1007 sub parsechangelog {
1008 my $c = Dpkg::Control::Hash->new(name => 'parsed changelog');
1009 my $p = new IO::Handle;
1010 my @cmd = (qw(dpkg-parsechangelog), @_);
1011 open $p, '-|', @cmd or die $!;
1013 $?=0; $!=0; close $p or failedcmd @cmd;
1017 sub commit_getclogp ($) {
1018 # Returns the parsed changelog hashref for a particular commit
1020 our %commit_getclogp_memo;
1021 my $memo = $commit_getclogp_memo{$objid};
1022 return $memo if $memo;
1024 my $mclog = dgit_privdir()."clog";
1025 runcmd shell_cmd "exec >$mclog", @git, qw(cat-file blob),
1026 "$objid:debian/changelog";
1027 $commit_getclogp_memo{$objid} = parsechangelog("-l$mclog");
1030 sub parse_dscdata () {
1031 my $dscfh = new IO::File \$dscdata, '<' or die $!;
1032 printdebug Dumper($dscdata) if $debuglevel>1;
1033 $dsc = parsecontrolfh($dscfh,$dscurl,1);
1034 printdebug Dumper($dsc) if $debuglevel>1;
1039 sub archive_query ($;@) {
1040 my ($method) = shift @_;
1041 fail "this operation does not support multiple comma-separated suites"
1043 my $query = access_cfg('archive-query','RETURN-UNDEF');
1044 $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
1047 { no strict qw(refs); &{"${method}_${proto}"}($proto,$data,@_); }
1050 sub archive_query_prepend_mirror {
1051 my $m = access_cfg('mirror');
1052 return map { [ $_->[0], $m.$_->[1], @$_[2..$#$_] ] } @_;
1055 sub pool_dsc_subpath ($$) {
1056 my ($vsn,$component) = @_; # $package is implict arg
1057 my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
1058 return "/pool/$component/$prefix/$package/".dscfn($vsn);
1061 sub cfg_apply_map ($$$) {
1062 my ($varref, $what, $mapspec) = @_;
1063 return unless $mapspec;
1065 printdebug "config $what EVAL{ $mapspec; }\n";
1067 eval "package Dgit::Config; $mapspec;";
1072 #---------- `ftpmasterapi' archive query method (nascent) ----------
1074 sub archive_api_query_cmd ($) {
1076 my @cmd = (@curl, qw(-sS));
1077 my $url = access_cfg('archive-query-url');
1078 if ($url =~ m#^https://([-.0-9a-z]+)/#) {
1080 my $keys = access_cfg('archive-query-tls-key','RETURN-UNDEF') //'';
1081 foreach my $key (split /\:/, $keys) {
1082 $key =~ s/\%HOST\%/$host/g;
1084 fail "for $url: stat $key: $!" unless $!==ENOENT;
1087 fail "config requested specific TLS key but do not know".
1088 " how to get curl to use exactly that EE key ($key)";
1089 # push @cmd, "--cacert", $key, "--capath", "/dev/enoent";
1090 # # Sadly the above line does not work because of changes
1091 # # to gnutls. The real fix for #790093 may involve
1092 # # new curl options.
1095 # Fixing #790093 properly will involve providing a value
1096 # for this on clients.
1097 my $kargs = access_cfg('archive-query-tls-curl-ca-args','RETURN-UNDEF');
1098 push @cmd, split / /, $kargs if defined $kargs;
1100 push @cmd, $url.$subpath;
1104 sub api_query ($$;$) {
1106 my ($data, $subpath, $ok404) = @_;
1107 badcfg "ftpmasterapi archive query method takes no data part"
1109 my @cmd = archive_api_query_cmd($subpath);
1110 my $url = $cmd[$#cmd];
1111 push @cmd, qw(-w %{http_code});
1112 my $json = cmdoutput @cmd;
1113 unless ($json =~ s/\d+\d+\d$//) {
1114 failedcmd_report_cmd undef, @cmd;
1115 fail "curl failed to print 3-digit HTTP code";
1118 return undef if $code eq '404' && $ok404;
1119 fail "fetch of $url gave HTTP code $code"
1120 unless $url =~ m#^file://# or $code =~ m/^2/;
1121 return decode_json($json);
1124 sub canonicalise_suite_ftpmasterapi {
1125 my ($proto,$data) = @_;
1126 my $suites = api_query($data, 'suites');
1128 foreach my $entry (@$suites) {
1130 my $v = $entry->{$_};
1131 defined $v && $v eq $isuite;
1132 } qw(codename name);
1133 push @matched, $entry;
1135 fail "unknown suite $isuite" unless @matched;
1138 @matched==1 or die "multiple matches for suite $isuite\n";
1139 $cn = "$matched[0]{codename}";
1140 defined $cn or die "suite $isuite info has no codename\n";
1141 $cn =~ m/^$suite_re$/ or die "suite $isuite maps to bad codename\n";
1143 die "bad ftpmaster api response: $@\n".Dumper(\@matched)
1148 sub archive_query_ftpmasterapi {
1149 my ($proto,$data) = @_;
1150 my $info = api_query($data, "dsc_in_suite/$isuite/$package");
1152 my $digester = Digest::SHA->new(256);
1153 foreach my $entry (@$info) {
1155 my $vsn = "$entry->{version}";
1156 my ($ok,$msg) = version_check $vsn;
1157 die "bad version: $msg\n" unless $ok;
1158 my $component = "$entry->{component}";
1159 $component =~ m/^$component_re$/ or die "bad component";
1160 my $filename = "$entry->{filename}";
1161 $filename && $filename !~ m#[^-+:._~0-9a-zA-Z/]|^[/.]|/[/.]#
1162 or die "bad filename";
1163 my $sha256sum = "$entry->{sha256sum}";
1164 $sha256sum =~ m/^[0-9a-f]+$/ or die "bad sha256sum";
1165 push @rows, [ $vsn, "/pool/$component/$filename",
1166 $digester, $sha256sum ];
1168 die "bad ftpmaster api response: $@\n".Dumper($entry)
1171 @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
1172 return archive_query_prepend_mirror @rows;
1175 sub file_in_archive_ftpmasterapi {
1176 my ($proto,$data,$filename) = @_;
1177 my $pat = $filename;
1180 $pat =~ s#[^-+_.0-9a-z/]# sprintf '%%%02x', ord $& #ge;
1181 my $info = api_query($data, "file_in_archive/$pat", 1);
1184 sub package_not_wholly_new_ftpmasterapi {
1185 my ($proto,$data,$pkg) = @_;
1186 my $info = api_query($data,"madison?package=${pkg}&f=json");
1190 #---------- `aptget' archive query method ----------
1193 our $aptget_releasefile;
1194 our $aptget_configpath;
1196 sub aptget_aptget () { return @aptget, qw(-c), $aptget_configpath; }
1197 sub aptget_aptcache () { return @aptcache, qw(-c), $aptget_configpath; }
1199 sub aptget_cache_clean {
1200 runcmd_ordryrun_local qw(sh -ec),
1201 'cd "$1"; find -atime +30 -type f -print0 | xargs -0r rm --',
1205 sub aptget_lock_acquire () {
1206 my $lockfile = "$aptget_base/lock";
1207 open APTGET_LOCK, '>', $lockfile or die "open $lockfile: $!";
1208 flock APTGET_LOCK, LOCK_EX or die "lock $lockfile: $!";
1211 sub aptget_prep ($) {
1213 return if defined $aptget_base;
1215 badcfg "aptget archive query method takes no data part"
1218 my $cache = $ENV{XDG_CACHE_DIR} // "$ENV{HOME}/.cache";
1221 ensuredir "$cache/dgit";
1223 access_cfg('aptget-cachekey','RETURN-UNDEF')
1224 // access_nomdistro();
1226 $aptget_base = "$cache/dgit/aptget";
1227 ensuredir $aptget_base;
1229 my $quoted_base = $aptget_base;
1230 die "$quoted_base contains bad chars, cannot continue"
1231 if $quoted_base =~ m/["\\]/; # apt.conf(5) says no escaping :-/
1233 ensuredir $aptget_base;
1235 aptget_lock_acquire();
1237 aptget_cache_clean();
1239 $aptget_configpath = "$aptget_base/apt.conf#$cachekey";
1240 my $sourceslist = "source.list#$cachekey";
1242 my $aptsuites = $isuite;
1243 cfg_apply_map(\$aptsuites, 'suite map',
1244 access_cfg('aptget-suite-map', 'RETURN-UNDEF'));
1246 open SRCS, ">", "$aptget_base/$sourceslist" or die $!;
1247 printf SRCS "deb-src %s %s %s\n",
1248 access_cfg('mirror'),
1250 access_cfg('aptget-components')
1253 ensuredir "$aptget_base/cache";
1254 ensuredir "$aptget_base/lists";
1256 open CONF, ">", $aptget_configpath or die $!;
1258 Debug::NoLocking "true";
1259 APT::Get::List-Cleanup "false";
1260 #clear APT::Update::Post-Invoke-Success;
1261 Dir::Etc::SourceList "$quoted_base/$sourceslist";
1262 Dir::State::Lists "$quoted_base/lists";
1263 Dir::Etc::preferences "$quoted_base/preferences";
1264 Dir::Cache::srcpkgcache "$quoted_base/cache/srcs#$cachekey";
1265 Dir::Cache::pkgcache "$quoted_base/cache/pkgs#$cachekey";
1268 foreach my $key (qw(
1271 Dir::Cache::Archives
1272 Dir::Etc::SourceParts
1273 Dir::Etc::preferencesparts
1275 ensuredir "$aptget_base/$key";
1276 print CONF "$key \"$quoted_base/$key\";\n" or die $!;
1279 my $oldatime = (time // die $!) - 1;
1280 foreach my $oldlist (<$aptget_base/lists/*Release>) {
1281 next unless stat_exists $oldlist;
1282 my ($mtime) = (stat _)[9];
1283 utime $oldatime, $mtime, $oldlist or die "$oldlist $!";
1286 runcmd_ordryrun_local aptget_aptget(), qw(update);
1289 foreach my $oldlist (<$aptget_base/lists/*Release>) {
1290 next unless stat_exists $oldlist;
1291 my ($atime) = (stat _)[8];
1292 next if $atime == $oldatime;
1293 push @releasefiles, $oldlist;
1295 my @inreleasefiles = grep { m#/InRelease$# } @releasefiles;
1296 @releasefiles = @inreleasefiles if @inreleasefiles;
1297 die "apt updated wrong number of Release files (@releasefiles), erk"
1298 unless @releasefiles == 1;
1300 ($aptget_releasefile) = @releasefiles;
1303 sub canonicalise_suite_aptget {
1304 my ($proto,$data) = @_;
1307 my $release = parsecontrol $aptget_releasefile, "Release file", 1;
1309 foreach my $name (qw(Codename Suite)) {
1310 my $val = $release->{$name};
1312 printdebug "release file $name: $val\n";
1313 $val =~ m/^$suite_re$/o or fail
1314 "Release file ($aptget_releasefile) specifies intolerable $name";
1315 cfg_apply_map(\$val, 'suite rmap',
1316 access_cfg('aptget-suite-rmap', 'RETURN-UNDEF'));
1323 sub archive_query_aptget {
1324 my ($proto,$data) = @_;
1327 ensuredir "$aptget_base/source";
1328 foreach my $old (<$aptget_base/source/*.dsc>) {
1329 unlink $old or die "$old: $!";
1332 my $showsrc = cmdoutput aptget_aptcache(), qw(showsrc), $package;
1333 return () unless $showsrc =~ m/^package:\s*\Q$package\E\s*$/mi;
1334 # avoids apt-get source failing with ambiguous error code
1336 runcmd_ordryrun_local
1337 shell_cmd 'cd "$1"/source; shift', $aptget_base,
1338 aptget_aptget(), qw(--download-only --only-source source), $package;
1340 my @dscs = <$aptget_base/source/*.dsc>;
1341 fail "apt-get source did not produce a .dsc" unless @dscs;
1342 fail "apt-get source produced several .dscs (@dscs)" unless @dscs==1;
1344 my $pre_dsc = parsecontrol $dscs[0], $dscs[0], 1;
1347 my $uri = "file://". uri_escape $dscs[0];
1348 $uri =~ s{\%2f}{/}gi;
1349 return [ (getfield $pre_dsc, 'Version'), $uri ];
1352 sub file_in_archive_aptget () { return undef; }
1353 sub package_not_wholly_new_aptget () { return undef; }
1355 #---------- `dummyapicat' archive query method ----------
1357 sub archive_query_dummycatapi { archive_query_ftpmasterapi @_; }
1358 sub canonicalise_suite_dummycatapi { canonicalise_suite_ftpmasterapi @_; }
1360 sub dummycatapi_run_in_mirror ($@) {
1361 # runs $fn with FIA open onto rune
1362 my ($rune, $argl, $fn) = @_;
1364 my $mirror = access_cfg('mirror');
1365 $mirror =~ s#^file://#/# or die "$mirror ?";
1366 my @cmd = (qw(sh -ec), 'cd "$1"; shift'."\n".$rune,
1367 qw(x), $mirror, @$argl);
1368 debugcmd "-|", @cmd;
1369 open FIA, "-|", @cmd or die $!;
1371 close FIA or ($!==0 && $?==141) die failedcmd @cmd;
1375 sub file_in_archive_dummycatapi ($$$) {
1376 my ($proto,$data,$filename) = @_;
1378 dummycatapi_run_in_mirror '
1379 find -name "$1" -print0 |
1381 ', [$filename], sub {
1384 printdebug "| $_\n";
1385 m/^(\w+) (\S+)$/ or die "$_ ?";
1386 push @out, { sha256sum => $1, filename => $2 };
1392 sub package_not_wholly_new_dummycatapi {
1393 my ($proto,$data,$pkg) = @_;
1394 dummycatapi_run_in_mirror "
1395 find -name ${pkg}_*.dsc
1402 #---------- `madison' archive query method ----------
1404 sub archive_query_madison {
1405 return archive_query_prepend_mirror
1406 map { [ @$_[0..1] ] } madison_get_parse(@_);
1409 sub madison_get_parse {
1410 my ($proto,$data) = @_;
1411 die unless $proto eq 'madison';
1412 if (!length $data) {
1413 $data= access_cfg('madison-distro','RETURN-UNDEF');
1414 $data //= access_basedistro();
1416 $rmad{$proto,$data,$package} ||= cmdoutput
1417 qw(rmadison -asource),"-s$isuite","-u$data",$package;
1418 my $rmad = $rmad{$proto,$data,$package};
1421 foreach my $l (split /\n/, $rmad) {
1422 $l =~ m{^ \s*( [^ \t|]+ )\s* \|
1423 \s*( [^ \t|]+ )\s* \|
1424 \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
1425 \s*( [^ \t|]+ )\s* }x or die "$rmad ?";
1426 $1 eq $package or die "$rmad $package ?";
1433 $component = access_cfg('archive-query-default-component');
1435 $5 eq 'source' or die "$rmad ?";
1436 push @out, [$vsn,pool_dsc_subpath($vsn,$component),$newsuite];
1438 return sort { -version_compare($a->[0],$b->[0]); } @out;
1441 sub canonicalise_suite_madison {
1442 # madison canonicalises for us
1443 my @r = madison_get_parse(@_);
1445 "unable to canonicalise suite using package $package".
1446 " which does not appear to exist in suite $isuite;".
1447 " --existing-package may help";
1451 sub file_in_archive_madison { return undef; }
1452 sub package_not_wholly_new_madison { return undef; }
1454 #---------- `sshpsql' archive query method ----------
1457 my ($data,$runeinfo,$sql) = @_;
1458 if (!length $data) {
1459 $data= access_someuserhost('sshpsql').':'.
1460 access_cfg('sshpsql-dbname');
1462 $data =~ m/:/ or badcfg "invalid sshpsql method string \`$data'";
1463 my ($userhost,$dbname) = ($`,$'); #';
1465 my @cmd = (access_cfg_ssh, $userhost,
1466 access_runeinfo("ssh-psql $runeinfo").
1467 " export LC_MESSAGES=C; export LC_CTYPE=C;".
1468 " ".shellquote qw(psql -A), $dbname, qw(-c), $sql);
1470 open P, "-|", @cmd or die $!;
1473 printdebug(">|$_|\n");
1476 $!=0; $?=0; close P or failedcmd @cmd;
1478 my $nrows = pop @rows;
1479 $nrows =~ s/^\((\d+) rows?\)$/$1/ or die "$nrows ?";
1480 @rows == $nrows+1 or die "$nrows ".(scalar @rows)." ?";
1481 @rows = map { [ split /\|/, $_ ] } @rows;
1482 my $ncols = scalar @{ shift @rows };
1483 die if grep { scalar @$_ != $ncols } @rows;
1487 sub sql_injection_check {
1488 foreach (@_) { die "$_ $& ?" if m{[^-+=:_.,/0-9a-zA-Z]}; }
1491 sub archive_query_sshpsql ($$) {
1492 my ($proto,$data) = @_;
1493 sql_injection_check $isuite, $package;
1494 my @rows = sshpsql($data, "archive-query $isuite $package", <<END);
1495 SELECT source.version, component.name, files.filename, files.sha256sum
1497 JOIN src_associations ON source.id = src_associations.source
1498 JOIN suite ON suite.id = src_associations.suite
1499 JOIN dsc_files ON dsc_files.source = source.id
1500 JOIN files_archive_map ON files_archive_map.file_id = dsc_files.file
1501 JOIN component ON component.id = files_archive_map.component_id
1502 JOIN files ON files.id = dsc_files.file
1503 WHERE ( suite.suite_name='$isuite' OR suite.codename='$isuite' )
1504 AND source.source='$package'
1505 AND files.filename LIKE '%.dsc';
1507 @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
1508 my $digester = Digest::SHA->new(256);
1510 my ($vsn,$component,$filename,$sha256sum) = @$_;
1511 [ $vsn, "/pool/$component/$filename",$digester,$sha256sum ];
1513 return archive_query_prepend_mirror @rows;
1516 sub canonicalise_suite_sshpsql ($$) {
1517 my ($proto,$data) = @_;
1518 sql_injection_check $isuite;
1519 my @rows = sshpsql($data, "canonicalise-suite $isuite", <<END);
1520 SELECT suite.codename
1521 FROM suite where suite_name='$isuite' or codename='$isuite';
1523 @rows = map { $_->[0] } @rows;
1524 fail "unknown suite $isuite" unless @rows;
1525 die "ambiguous $isuite: @rows ?" if @rows>1;
1529 sub file_in_archive_sshpsql ($$$) { return undef; }
1530 sub package_not_wholly_new_sshpsql ($$$) { return undef; }
1532 #---------- `dummycat' archive query method ----------
1534 sub canonicalise_suite_dummycat ($$) {
1535 my ($proto,$data) = @_;
1536 my $dpath = "$data/suite.$isuite";
1537 if (!open C, "<", $dpath) {
1538 $!==ENOENT or die "$dpath: $!";
1539 printdebug "dummycat canonicalise_suite $isuite $dpath ENOENT\n";
1543 chomp or die "$dpath: $!";
1545 printdebug "dummycat canonicalise_suite $isuite $dpath = $_\n";
1549 sub archive_query_dummycat ($$) {
1550 my ($proto,$data) = @_;
1551 canonicalise_suite();
1552 my $dpath = "$data/package.$csuite.$package";
1553 if (!open C, "<", $dpath) {
1554 $!==ENOENT or die "$dpath: $!";
1555 printdebug "dummycat query $csuite $package $dpath ENOENT\n";
1563 printdebug "dummycat query $csuite $package $dpath | $_\n";
1564 my @row = split /\s+/, $_;
1565 @row==2 or die "$dpath: $_ ?";
1568 C->error and die "$dpath: $!";
1570 return archive_query_prepend_mirror
1571 sort { -version_compare($a->[0],$b->[0]); } @rows;
1574 sub file_in_archive_dummycat () { return undef; }
1575 sub package_not_wholly_new_dummycat () { return undef; }
1577 #---------- tag format handling ----------
1579 sub access_cfg_tagformats () {
1580 split /\,/, access_cfg('dgit-tag-format');
1583 sub access_cfg_tagformats_can_splitbrain () {
1584 my %y = map { $_ => 1 } access_cfg_tagformats;
1585 foreach my $needtf (qw(new maint)) {
1586 next if $y{$needtf};
1592 sub need_tagformat ($$) {
1593 my ($fmt, $why) = @_;
1594 fail "need to use tag format $fmt ($why) but also need".
1595 " to use tag format $tagformat_want->[0] ($tagformat_want->[1])".
1596 " - no way to proceed"
1597 if $tagformat_want && $tagformat_want->[0] ne $fmt;
1598 $tagformat_want = [$fmt, $why, $tagformat_want->[2] // 0];
1601 sub select_tagformat () {
1603 return if $tagformatfn && !$tagformat_want;
1604 die 'bug' if $tagformatfn && $tagformat_want;
1605 # ... $tagformat_want assigned after previous select_tagformat
1607 my (@supported) = grep { $_ =~ m/^(?:old|new)$/ } access_cfg_tagformats();
1608 printdebug "select_tagformat supported @supported\n";
1610 $tagformat_want //= [ $supported[0], "distro access configuration", 0 ];
1611 printdebug "select_tagformat specified @$tagformat_want\n";
1613 my ($fmt,$why,$override) = @$tagformat_want;
1615 fail "target distro supports tag formats @supported".
1616 " but have to use $fmt ($why)"
1618 or grep { $_ eq $fmt } @supported;
1620 $tagformat_want = undef;
1622 $tagformatfn = ${*::}{"debiantag_$fmt"};
1624 fail "trying to use unknown tag format \`$fmt' ($why) !"
1625 unless $tagformatfn;
1628 #---------- archive query entrypoints and rest of program ----------
1630 sub canonicalise_suite () {
1631 return if defined $csuite;
1632 fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
1633 $csuite = archive_query('canonicalise_suite');
1634 if ($isuite ne $csuite) {
1635 progress "canonical suite name for $isuite is $csuite";
1637 progress "canonical suite name is $csuite";
1641 sub get_archive_dsc () {
1642 canonicalise_suite();
1643 my @vsns = archive_query('archive_query');
1644 foreach my $vinfo (@vsns) {
1645 my ($vsn,$vsn_dscurl,$digester,$digest) = @$vinfo;
1646 $dscurl = $vsn_dscurl;
1647 $dscdata = url_get($dscurl);
1649 $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
1654 $digester->add($dscdata);
1655 my $got = $digester->hexdigest();
1657 fail "$dscurl has hash $got but".
1658 " archive told us to expect $digest";
1661 my $fmt = getfield $dsc, 'Format';
1662 $format_ok{$fmt} or forceable_fail [qw(unsupported-source-format)],
1663 "unsupported source format $fmt, sorry";
1665 $dsc_checked = !!$digester;
1666 printdebug "get_archive_dsc: Version ".(getfield $dsc, 'Version')."\n";
1670 printdebug "get_archive_dsc: nothing in archive, returning undef\n";
1673 sub check_for_git ();
1674 sub check_for_git () {
1676 my $how = access_cfg('git-check');
1677 if ($how eq 'ssh-cmd') {
1679 (access_cfg_ssh, access_gituserhost(),
1680 access_runeinfo("git-check $package").
1681 " set -e; cd ".access_cfg('git-path').";".
1682 " if test -d $package.git; then echo 1; else echo 0; fi");
1683 my $r= cmdoutput @cmd;
1684 if (defined $r and $r =~ m/^divert (\w+)$/) {
1686 my ($usedistro,) = access_distros();
1687 # NB that if we are pushing, $usedistro will be $distro/push
1688 $instead_distro= cfg("dgit-distro.$usedistro.diverts.$divert");
1689 $instead_distro =~ s{^/}{ access_basedistro()."/" }e;
1690 progress "diverting to $divert (using config for $instead_distro)";
1691 return check_for_git();
1693 failedcmd @cmd unless defined $r and $r =~ m/^[01]$/;
1695 } elsif ($how eq 'url') {
1696 my $prefix = access_cfg('git-check-url','git-url');
1697 my $suffix = access_cfg('git-check-suffix','git-suffix',
1698 'RETURN-UNDEF') // '.git';
1699 my $url = "$prefix/$package$suffix";
1700 my @cmd = (@curl, qw(-sS -I), $url);
1701 my $result = cmdoutput @cmd;
1702 $result =~ s/^\S+ 200 .*\n\r?\n//;
1703 # curl -sS -I with https_proxy prints
1704 # HTTP/1.0 200 Connection established
1705 $result =~ m/^\S+ (404|200) /s or
1706 fail "unexpected results from git check query - ".
1707 Dumper($prefix, $result);
1709 if ($code eq '404') {
1711 } elsif ($code eq '200') {
1716 } elsif ($how eq 'true') {
1718 } elsif ($how eq 'false') {
1721 badcfg "unknown git-check \`$how'";
1725 sub create_remote_git_repo () {
1726 my $how = access_cfg('git-create');
1727 if ($how eq 'ssh-cmd') {
1729 (access_cfg_ssh, access_gituserhost(),
1730 access_runeinfo("git-create $package").
1731 "set -e; cd ".access_cfg('git-path').";".
1732 " cp -a _template $package.git");
1733 } elsif ($how eq 'true') {
1736 badcfg "unknown git-create \`$how'";
1740 our ($dsc_hash,$lastpush_mergeinput);
1741 our ($dsc_distro, $dsc_hint_tag, $dsc_hint_url);
1745 dgit_privdir(); # ensures that $dgit_privdir_made is based on $maindir
1746 $playground = fresh_playground 'dgit/unpack';
1749 sub mktree_in_ud_here () {
1750 playtree_setup $gitcfgs{local};
1753 sub git_write_tree () {
1754 my $tree = cmdoutput @git, qw(write-tree);
1755 $tree =~ m/^\w+$/ or die "$tree ?";
1759 sub git_add_write_tree () {
1760 runcmd @git, qw(add -Af .);
1761 return git_write_tree();
1764 sub remove_stray_gits ($) {
1766 my @gitscmd = qw(find -name .git -prune -print0);
1767 debugcmd "|",@gitscmd;
1768 open GITS, "-|", @gitscmd or die $!;
1773 print STDERR "$us: warning: removing from $what: ",
1774 (messagequote $_), "\n";
1778 $!=0; $?=0; close GITS or failedcmd @gitscmd;
1781 sub mktree_in_ud_from_only_subdir ($;$) {
1782 my ($what,$raw) = @_;
1783 # changes into the subdir
1786 die "expected one subdir but found @dirs ?" unless @dirs==1;
1787 $dirs[0] =~ m#^([^/]+)/\.$# or die;
1791 remove_stray_gits($what);
1792 mktree_in_ud_here();
1794 my ($format, $fopts) = get_source_format();
1795 if (madformat($format)) {
1800 my $tree=git_add_write_tree();
1801 return ($tree,$dir);
1804 our @files_csum_info_fields =
1805 (['Checksums-Sha256','Digest::SHA', 'new(256)', 'sha256sum'],
1806 ['Checksums-Sha1', 'Digest::SHA', 'new(1)', 'sha1sum'],
1807 ['Files', 'Digest::MD5', 'new()', 'md5sum']);
1809 sub dsc_files_info () {
1810 foreach my $csumi (@files_csum_info_fields) {
1811 my ($fname, $module, $method) = @$csumi;
1812 my $field = $dsc->{$fname};
1813 next unless defined $field;
1814 eval "use $module; 1;" or die $@;
1816 foreach (split /\n/, $field) {
1818 m/^(\w+) (\d+) (\S+)$/ or
1819 fail "could not parse .dsc $fname line \`$_'";
1820 my $digester = eval "$module"."->$method;" or die $@;
1825 Digester => $digester,
1830 fail "missing any supported Checksums-* or Files field in ".
1831 $dsc->get_option('name');
1835 map { $_->{Filename} } dsc_files_info();
1838 sub files_compare_inputs (@) {
1843 my $showinputs = sub {
1844 return join "; ", map { $_->get_option('name') } @$inputs;
1847 foreach my $in (@$inputs) {
1849 my $in_name = $in->get_option('name');
1851 printdebug "files_compare_inputs $in_name\n";
1853 foreach my $csumi (@files_csum_info_fields) {
1854 my ($fname) = @$csumi;
1855 printdebug "files_compare_inputs $in_name $fname\n";
1857 my $field = $in->{$fname};
1858 next unless defined $field;
1861 foreach (split /\n/, $field) {
1864 my ($info, $f) = m/^(\w+ \d+) (?:\S+ \S+ )?(\S+)$/ or
1865 fail "could not parse $in_name $fname line \`$_'";
1867 printdebug "files_compare_inputs $in_name $fname $f\n";
1871 my $re = \ $record{$f}{$fname};
1873 $fchecked{$f}{$in_name} = 1;
1875 fail "hash or size of $f varies in $fname fields".
1876 " (between: ".$showinputs->().")";
1881 @files = sort @files;
1882 $expected_files //= \@files;
1883 "@$expected_files" eq "@files" or
1884 fail "file list in $in_name varies between hash fields!";
1887 fail "$in_name has no files list field(s)";
1889 printdebug "files_compare_inputs ".Dumper(\%fchecked, \%record)
1892 grep { keys %$_ == @$inputs-1 } values %fchecked
1893 or fail "no file appears in all file lists".
1894 " (looked in: ".$showinputs->().")";
1897 sub is_orig_file_in_dsc ($$) {
1898 my ($f, $dsc_files_info) = @_;
1899 return 0 if @$dsc_files_info <= 1;
1900 # One file means no origs, and the filename doesn't have a "what
1901 # part of dsc" component. (Consider versions ending `.orig'.)
1902 return 0 unless $f =~ m/\.$orig_f_tail_re$/o;
1906 sub is_orig_file_of_vsn ($$) {
1907 my ($f, $upstreamvsn) = @_;
1908 my $base = srcfn $upstreamvsn, '';
1909 return 0 unless $f =~ m/^\Q$base\E\.$orig_f_tail_re$/;
1913 # This function determines whether a .changes file is source-only from
1914 # the point of view of dak. Thus, it permits *_source.buildinfo
1917 # It does not, however, permit any other buildinfo files. After a
1918 # source-only upload, the buildds will try to upload files like
1919 # foo_1.2.3_amd64.buildinfo. If the package maintainer included files
1920 # named like this in their (otherwise) source-only upload, the uploads
1921 # of the buildd can be rejected by dak. Fixing the resultant
1922 # situation can require manual intervention. So we block such
1923 # .buildinfo files when the user tells us to perform a source-only
1924 # upload (such as when using the push-source subcommand with the -C
1925 # option, which calls this function).
1927 # Note, though, that when dgit is told to prepare a source-only
1928 # upload, such as when subcommands like build-source and push-source
1929 # without -C are used, dgit has a more restrictive notion of
1930 # source-only .changes than dak: such uploads will never include
1931 # *_source.buildinfo files. This is because there is no use for such
1932 # files when using a tool like dgit to produce the source package, as
1933 # dgit ensures the source is identical to git HEAD.
1934 sub test_source_only_changes ($) {
1936 foreach my $l (split /\n/, getfield $changes, 'Files') {
1937 $l =~ m/\S+$/ or next;
1938 # \.tar\.[a-z0-9]+ covers orig.tar and the tarballs in native packages
1939 unless ($& =~ m/(?:\.dsc|\.diff\.gz|\.tar\.[a-z0-9]+|_source\.buildinfo)$/) {
1940 print "purportedly source-only changes polluted by $&\n";
1947 sub changes_update_origs_from_dsc ($$$$) {
1948 my ($dsc, $changes, $upstreamvsn, $changesfile) = @_;
1950 printdebug "checking origs needed ($upstreamvsn)...\n";
1951 $_ = getfield $changes, 'Files';
1952 m/^\w+ \d+ (\S+ \S+) \S+$/m or
1953 fail "cannot find section/priority from .changes Files field";
1954 my $placementinfo = $1;
1956 printdebug "checking origs needed placement '$placementinfo'...\n";
1957 foreach my $l (split /\n/, getfield $dsc, 'Files') {
1958 $l =~ m/\S+$/ or next;
1960 printdebug "origs $file | $l\n";
1961 next unless is_orig_file_of_vsn $file, $upstreamvsn;
1962 printdebug "origs $file is_orig\n";
1963 my $have = archive_query('file_in_archive', $file);
1964 if (!defined $have) {
1966 archive does not support .orig check; hope you used --ch:--sa/-sd if needed
1972 printdebug "origs $file \$#\$have=$#$have\n";
1973 foreach my $h (@$have) {
1976 foreach my $csumi (@files_csum_info_fields) {
1977 my ($fname, $module, $method, $archivefield) = @$csumi;
1978 next unless defined $h->{$archivefield};
1979 $_ = $dsc->{$fname};
1980 next unless defined;
1981 m/^(\w+) .* \Q$file\E$/m or
1982 fail ".dsc $fname missing entry for $file";
1983 if ($h->{$archivefield} eq $1) {
1987 "$archivefield: $h->{$archivefield} (archive) != $1 (local .dsc)";
1990 die "$file ".Dumper($h)." ?!" if $same && @differ;
1993 push @found_differ, "archive $h->{filename}: ".join "; ", @differ
1996 printdebug "origs $file f.same=$found_same".
1997 " #f._differ=$#found_differ\n";
1998 if (@found_differ && !$found_same) {
2000 "archive contains $file with different checksum",
2003 # Now we edit the changes file to add or remove it
2004 foreach my $csumi (@files_csum_info_fields) {
2005 my ($fname, $module, $method, $archivefield) = @$csumi;
2006 next unless defined $changes->{$fname};
2008 # in archive, delete from .changes if it's there
2009 $changed{$file} = "removed" if
2010 $changes->{$fname} =~ s/\n.* \Q$file\E$(?:)$//m;
2011 } elsif ($changes->{$fname} =~ m/^.* \Q$file\E$(?:)$/m) {
2012 # not in archive, but it's here in the .changes
2014 my $dsc_data = getfield $dsc, $fname;
2015 $dsc_data =~ m/^(.* \Q$file\E$)$/m or die "$dsc_data $file ?";
2017 $extra =~ s/ \d+ /$&$placementinfo /
2018 or die "$fname $extra >$dsc_data< ?"
2019 if $fname eq 'Files';
2020 $changes->{$fname} .= "\n". $extra;
2021 $changed{$file} = "added";
2026 foreach my $file (keys %changed) {
2028 "edited .changes for archive .orig contents: %s %s",
2029 $changed{$file}, $file;
2031 my $chtmp = "$changesfile.tmp";
2032 $changes->save($chtmp);
2034 rename $chtmp,$changesfile or die "$changesfile $!";
2036 progress "[new .changes left in $changesfile]";
2039 progress "$changesfile already has appropriate .orig(s) (if any)";
2043 sub make_commit ($) {
2045 return cmdoutput @git, qw(hash-object -w -t commit), $file;
2048 sub make_commit_text ($) {
2051 my @cmd = (@git, qw(hash-object -w -t commit --stdin));
2053 print Dumper($text) if $debuglevel > 1;
2054 my $child = open2($out, $in, @cmd) or die $!;
2057 print $in $text or die $!;
2058 close $in or die $!;
2060 $h =~ m/^\w+$/ or die;
2062 printdebug "=> $h\n";
2065 waitpid $child, 0 == $child or die "$child $!";
2066 $? and failedcmd @cmd;
2070 sub clogp_authline ($) {
2072 my $author = getfield $clogp, 'Maintainer';
2073 if ($author =~ m/^[^"\@]+\,/) {
2074 # single entry Maintainer field with unquoted comma
2075 $author = ($& =~ y/,//rd).$'; # strip the comma
2077 # git wants a single author; any remaining commas in $author
2078 # are by now preceded by @ (or "). It seems safer to punt on
2079 # "..." for now rather than attempting to dequote or something.
2080 $author =~ s#,.*##ms unless $author =~ m/"/;
2081 my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
2082 my $authline = "$author $date";
2083 $authline =~ m/$git_authline_re/o or
2084 fail "unexpected commit author line format \`$authline'".
2085 " (was generated from changelog Maintainer field)";
2086 return ($1,$2,$3) if wantarray;
2090 sub vendor_patches_distro ($$) {
2091 my ($checkdistro, $what) = @_;
2092 return unless defined $checkdistro;
2094 my $series = "debian/patches/\L$checkdistro\E.series";
2095 printdebug "checking for vendor-specific $series ($what)\n";
2097 if (!open SERIES, "<", $series) {
2098 die "$series $!" unless $!==ENOENT;
2107 Unfortunately, this source package uses a feature of dpkg-source where
2108 the same source package unpacks to different source code on different
2109 distros. dgit cannot safely operate on such packages on affected
2110 distros, because the meaning of source packages is not stable.
2112 Please ask the distro/maintainer to remove the distro-specific series
2113 files and use a different technique (if necessary, uploading actually
2114 different packages, if different distros are supposed to have
2118 fail "Found active distro-specific series file for".
2119 " $checkdistro ($what): $series, cannot continue";
2121 die "$series $!" if SERIES->error;
2125 sub check_for_vendor_patches () {
2126 # This dpkg-source feature doesn't seem to be documented anywhere!
2127 # But it can be found in the changelog (reformatted):
2129 # commit 4fa01b70df1dc4458daee306cfa1f987b69da58c
2130 # Author: Raphael Hertzog <hertzog@debian.org>
2131 # Date: Sun Oct 3 09:36:48 2010 +0200
2133 # dpkg-source: correctly create .pc/.quilt_series with alternate
2136 # If you have debian/patches/ubuntu.series and you were
2137 # unpacking the source package on ubuntu, quilt was still
2138 # directed to debian/patches/series instead of
2139 # debian/patches/ubuntu.series.
2141 # debian/changelog | 3 +++
2142 # scripts/Dpkg/Source/Package/V3/quilt.pm | 4 +++-
2143 # 2 files changed, 6 insertions(+), 1 deletion(-)
2146 vendor_patches_distro($ENV{DEB_VENDOR}, "DEB_VENDOR");
2147 vendor_patches_distro(Dpkg::Vendor::get_current_vendor(),
2148 "Dpkg::Vendor \`current vendor'");
2149 vendor_patches_distro(access_basedistro(),
2150 "(base) distro being accessed");
2151 vendor_patches_distro(access_nomdistro(),
2152 "(nominal) distro being accessed");
2155 sub generate_commits_from_dsc () {
2156 # See big comment in fetch_from_archive, below.
2157 # See also README.dsc-import.
2159 changedir $playground;
2161 my @dfi = dsc_files_info();
2162 foreach my $fi (@dfi) {
2163 my $f = $fi->{Filename};
2164 die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
2165 my $upper_f = "$maindir/../$f";
2167 printdebug "considering reusing $f: ";
2169 if (link_ltarget "$upper_f,fetch", $f) {
2170 printdebug "linked (using ...,fetch).\n";
2171 } elsif ((printdebug "($!) "),
2173 fail "accessing ../$f,fetch: $!";
2174 } elsif (link_ltarget $upper_f, $f) {
2175 printdebug "linked.\n";
2176 } elsif ((printdebug "($!) "),
2178 fail "accessing ../$f: $!";
2180 printdebug "absent.\n";
2184 complete_file_from_dsc('.', $fi, \$refetched)
2187 printdebug "considering saving $f: ";
2189 if (link $f, $upper_f) {
2190 printdebug "linked.\n";
2191 } elsif ((printdebug "($!) "),
2193 fail "saving ../$f: $!";
2194 } elsif (!$refetched) {
2195 printdebug "no need.\n";
2196 } elsif (link $f, "$upper_f,fetch") {
2197 printdebug "linked (using ...,fetch).\n";
2198 } elsif ((printdebug "($!) "),
2200 fail "saving ../$f,fetch: $!";
2202 printdebug "cannot.\n";
2206 # We unpack and record the orig tarballs first, so that we only
2207 # need disk space for one private copy of the unpacked source.
2208 # But we can't make them into commits until we have the metadata
2209 # from the debian/changelog, so we record the tree objects now and
2210 # make them into commits later.
2212 my $upstreamv = upstreamversion $dsc->{version};
2213 my $orig_f_base = srcfn $upstreamv, '';
2215 foreach my $fi (@dfi) {
2216 # We actually import, and record as a commit, every tarball
2217 # (unless there is only one file, in which case there seems
2220 my $f = $fi->{Filename};
2221 printdebug "import considering $f ";
2222 (printdebug "only one dfi\n"), next if @dfi == 1;
2223 (printdebug "not tar\n"), next unless $f =~ m/\.tar(\.\w+)?$/;
2224 (printdebug "signature\n"), next if $f =~ m/$orig_f_sig_re$/o;
2228 $f =~ m/^\Q$orig_f_base\E\.([^._]+)?\.tar(?:\.\w+)?$/;
2230 printdebug "Y ", (join ' ', map { $_//"(none)" }
2231 $compr_ext, $orig_f_part
2234 my $input = new IO::File $f, '<' or die "$f $!";
2238 if (defined $compr_ext) {
2240 Dpkg::Compression::compression_guess_from_filename $f;
2241 fail "Dpkg::Compression cannot handle file $f in source package"
2242 if defined $compr_ext && !defined $cname;
2244 new Dpkg::Compression::Process compression => $cname;
2245 @compr_cmd = $compr_proc->get_uncompress_cmdline();
2246 my $compr_fh = new IO::Handle;
2247 my $compr_pid = open $compr_fh, "-|" // die $!;
2249 open STDIN, "<&", $input or die $!;
2251 die "dgit (child): exec $compr_cmd[0]: $!\n";
2256 rmtree "_unpack-tar";
2257 mkdir "_unpack-tar" or die $!;
2258 my @tarcmd = qw(tar -x -f -
2259 --no-same-owner --no-same-permissions
2260 --no-acls --no-xattrs --no-selinux);
2261 my $tar_pid = fork // die $!;
2263 chdir "_unpack-tar" or die $!;
2264 open STDIN, "<&", $input or die $!;
2266 die "dgit (child): exec $tarcmd[0]: $!";
2268 $!=0; (waitpid $tar_pid, 0) == $tar_pid or die $!;
2269 !$? or failedcmd @tarcmd;
2272 (@compr_cmd ? ($?==SIGPIPE || failedcmd @compr_cmd)
2274 # finally, we have the results in "tarball", but maybe
2275 # with the wrong permissions
2277 runcmd qw(chmod -R +rwX _unpack-tar);
2278 changedir "_unpack-tar";
2279 remove_stray_gits($f);
2280 mktree_in_ud_here();
2282 my ($tree) = git_add_write_tree();
2283 my $tentries = cmdoutput @git, qw(ls-tree -z), $tree;
2284 if ($tentries =~ m/^\d+ tree (\w+)\t[^\000]+\000$/s) {
2286 printdebug "one subtree $1\n";
2288 printdebug "multiple subtrees\n";
2291 rmtree "_unpack-tar";
2293 my $ent = [ $f, $tree ];
2295 Orig => !!$orig_f_part,
2296 Sort => (!$orig_f_part ? 2 :
2297 $orig_f_part =~ m/-/g ? 1 :
2305 # put any without "_" first (spec is not clear whether files
2306 # are always in the usual order). Tarballs without "_" are
2307 # the main orig or the debian tarball.
2308 $a->{Sort} <=> $b->{Sort} or
2312 my $any_orig = grep { $_->{Orig} } @tartrees;
2314 my $dscfn = "$package.dsc";
2316 my $treeimporthow = 'package';
2318 open D, ">", $dscfn or die "$dscfn: $!";
2319 print D $dscdata or die "$dscfn: $!";
2320 close D or die "$dscfn: $!";
2321 my @cmd = qw(dpkg-source);
2322 push @cmd, '--no-check' if $dsc_checked;
2323 if (madformat $dsc->{format}) {
2324 push @cmd, '--skip-patches';
2325 $treeimporthow = 'unpatched';
2327 push @cmd, qw(-x --), $dscfn;
2330 my ($tree,$dir) = mktree_in_ud_from_only_subdir("source package");
2331 if (madformat $dsc->{format}) {
2332 check_for_vendor_patches();
2336 if (madformat $dsc->{format}) {
2337 my @pcmd = qw(dpkg-source --before-build .);
2338 runcmd shell_cmd 'exec >/dev/null', @pcmd;
2340 $dappliedtree = git_add_write_tree();
2343 my @clogcmd = qw(dpkg-parsechangelog --format rfc822 --all);
2344 debugcmd "|",@clogcmd;
2345 open CLOGS, "-|", @clogcmd or die $!;
2350 printdebug "import clog search...\n";
2353 my $stanzatext = do { local $/=""; <CLOGS>; };
2354 printdebug "import clogp ".Dumper($stanzatext) if $debuglevel>1;
2355 last if !defined $stanzatext;
2357 my $desc = "package changelog, entry no.$.";
2358 open my $stanzafh, "<", \$stanzatext or die;
2359 my $thisstanza = parsecontrolfh $stanzafh, $desc, 1;
2360 $clogp //= $thisstanza;
2362 printdebug "import clog $thisstanza->{version} $desc...\n";
2364 last if !$any_orig; # we don't need $r1clogp
2366 # We look for the first (most recent) changelog entry whose
2367 # version number is lower than the upstream version of this
2368 # package. Then the last (least recent) previous changelog
2369 # entry is treated as the one which introduced this upstream
2370 # version and used for the synthetic commits for the upstream
2373 # One might think that a more sophisticated algorithm would be
2374 # necessary. But: we do not want to scan the whole changelog
2375 # file. Stopping when we see an earlier version, which
2376 # necessarily then is an earlier upstream version, is the only
2377 # realistic way to do that. Then, either the earliest
2378 # changelog entry we have seen so far is indeed the earliest
2379 # upload of this upstream version; or there are only changelog
2380 # entries relating to later upstream versions (which is not
2381 # possible unless the changelog and .dsc disagree about the
2382 # version). Then it remains to choose between the physically
2383 # last entry in the file, and the one with the lowest version
2384 # number. If these are not the same, we guess that the
2385 # versions were created in a non-monotic order rather than
2386 # that the changelog entries have been misordered.
2388 printdebug "import clog $thisstanza->{version} vs $upstreamv...\n";
2390 last if version_compare($thisstanza->{version}, $upstreamv) < 0;
2391 $r1clogp = $thisstanza;
2393 printdebug "import clog $r1clogp->{version} becomes r1\n";
2395 die $! if CLOGS->error;
2396 close CLOGS or $?==SIGPIPE or failedcmd @clogcmd;
2398 $clogp or fail "package changelog has no entries!";
2400 my $authline = clogp_authline $clogp;
2401 my $changes = getfield $clogp, 'Changes';
2402 $changes =~ s/^\n//; # Changes: \n
2403 my $cversion = getfield $clogp, 'Version';
2406 $r1clogp //= $clogp; # maybe there's only one entry;
2407 my $r1authline = clogp_authline $r1clogp;
2408 # Strictly, r1authline might now be wrong if it's going to be
2409 # unused because !$any_orig. Whatever.
2411 printdebug "import tartrees authline $authline\n";
2412 printdebug "import tartrees r1authline $r1authline\n";
2414 foreach my $tt (@tartrees) {
2415 printdebug "import tartree $tt->{F} $tt->{Tree}\n";
2417 $tt->{Commit} = make_commit_text($tt->{Orig} ? <<END_O : <<END_T);
2420 committer $r1authline
2424 [dgit import orig $tt->{F}]
2432 [dgit import tarball $package $cversion $tt->{F}]
2437 printdebug "import main commit\n";
2439 open C, ">../commit.tmp" or die $!;
2440 print C <<END or die $!;
2443 print C <<END or die $! foreach @tartrees;
2446 print C <<END or die $!;
2452 [dgit import $treeimporthow $package $cversion]
2456 my $rawimport_hash = make_commit qw(../commit.tmp);
2458 if (madformat $dsc->{format}) {
2459 printdebug "import apply patches...\n";
2461 # regularise the state of the working tree so that
2462 # the checkout of $rawimport_hash works nicely.
2463 my $dappliedcommit = make_commit_text(<<END);
2470 runcmd @git, qw(checkout -q -b dapplied), $dappliedcommit;
2472 runcmd @git, qw(checkout -q -b unpa), $rawimport_hash;
2474 # We need the answers to be reproducible
2475 my @authline = clogp_authline($clogp);
2476 local $ENV{GIT_COMMITTER_NAME} = $authline[0];
2477 local $ENV{GIT_COMMITTER_EMAIL} = $authline[1];
2478 local $ENV{GIT_COMMITTER_DATE} = $authline[2];
2479 local $ENV{GIT_AUTHOR_NAME} = $authline[0];
2480 local $ENV{GIT_AUTHOR_EMAIL} = $authline[1];
2481 local $ENV{GIT_AUTHOR_DATE} = $authline[2];
2483 my $path = $ENV{PATH} or die;
2485 # we use ../../gbp-pq-output, which (given that we are in
2486 # $playground/PLAYTREE, and $playground is .git/dgit/unpack,
2489 foreach my $use_absurd (qw(0 1)) {
2490 runcmd @git, qw(checkout -q unpa);
2491 runcmd @git, qw(update-ref -d refs/heads/patch-queue/unpa);
2492 local $ENV{PATH} = $path;
2495 progress "warning: $@";
2496 $path = "$absurdity:$path";
2497 progress "$us: trying slow absurd-git-apply...";
2498 rename "../../gbp-pq-output","../../gbp-pq-output.0"
2503 die "forbid absurd git-apply\n" if $use_absurd
2504 && forceing [qw(import-gitapply-no-absurd)];
2505 die "only absurd git-apply!\n" if !$use_absurd
2506 && forceing [qw(import-gitapply-absurd)];
2508 local $ENV{DGIT_ABSURD_DEBUG} = $debuglevel if $use_absurd;
2509 local $ENV{PATH} = $path if $use_absurd;
2511 my @showcmd = (gbp_pq, qw(import));
2512 my @realcmd = shell_cmd
2513 'exec >/dev/null 2>>../../gbp-pq-output', @showcmd;
2514 debugcmd "+",@realcmd;
2515 if (system @realcmd) {
2516 die +(shellquote @showcmd).
2518 failedcmd_waitstatus()."\n";
2521 my $gapplied = git_rev_parse('HEAD');
2522 my $gappliedtree = cmdoutput @git, qw(rev-parse HEAD:);
2523 $gappliedtree eq $dappliedtree or
2525 gbp-pq import and dpkg-source disagree!
2526 gbp-pq import gave commit $gapplied
2527 gbp-pq import gave tree $gappliedtree
2528 dpkg-source --before-build gave tree $dappliedtree
2530 $rawimport_hash = $gapplied;
2535 { local $@; eval { runcmd qw(cat ../../gbp-pq-output); }; }
2540 progress "synthesised git commit from .dsc $cversion";
2542 my $rawimport_mergeinput = {
2543 Commit => $rawimport_hash,
2544 Info => "Import of source package",
2546 my @output = ($rawimport_mergeinput);
2548 if ($lastpush_mergeinput) {
2549 my $oldclogp = mergeinfo_getclogp($lastpush_mergeinput);
2550 my $oversion = getfield $oldclogp, 'Version';
2552 version_compare($oversion, $cversion);
2554 @output = ($rawimport_mergeinput, $lastpush_mergeinput,
2555 { Message => <<END, ReverseParents => 1 });
2556 Record $package ($cversion) in archive suite $csuite
2558 } elsif ($vcmp > 0) {
2559 print STDERR <<END or die $!;
2561 Version actually in archive: $cversion (older)
2562 Last version pushed with dgit: $oversion (newer or same)
2565 @output = $lastpush_mergeinput;
2567 # Same version. Use what's in the server git branch,
2568 # discarding our own import. (This could happen if the
2569 # server automatically imports all packages into git.)
2570 @output = $lastpush_mergeinput;
2578 sub complete_file_from_dsc ($$;$) {
2579 our ($dstdir, $fi, $refetched) = @_;
2580 # Ensures that we have, in $dstdir, the file $fi, with the correct
2581 # contents. (Downloading it from alongside $dscurl if necessary.)
2582 # If $refetched is defined, can overwrite "$dstdir/$fi->{Filename}"
2583 # and will set $$refetched=1 if it did so (or tried to).
2585 my $f = $fi->{Filename};
2586 my $tf = "$dstdir/$f";
2590 my $checkhash = sub {
2591 open F, "<", "$tf" or die "$tf: $!";
2592 $fi->{Digester}->reset();
2593 $fi->{Digester}->addfile(*F);
2594 F->error and die $!;
2595 $got = $fi->{Digester}->hexdigest();
2596 return $got eq $fi->{Hash};
2599 if (stat_exists $tf) {
2600 if ($checkhash->()) {
2601 progress "using existing $f";
2605 fail "file $f has hash $got but .dsc".
2606 " demands hash $fi->{Hash} ".
2607 "(perhaps you should delete this file?)";
2609 progress "need to fetch correct version of $f";
2610 unlink $tf or die "$tf $!";
2613 printdebug "$tf does not exist, need to fetch\n";
2617 $furl =~ s{/[^/]+$}{};
2619 die "$f ?" unless $f =~ m/^\Q${package}\E_/;
2620 die "$f ?" if $f =~ m#/#;
2621 runcmd_ordryrun_local @curl,qw(-f -o),$tf,'--',"$furl";
2622 return 0 if !act_local();
2625 fail "file $f has hash $got but .dsc".
2626 " demands hash $fi->{Hash} ".
2627 "(got wrong file from archive!)";
2632 sub ensure_we_have_orig () {
2633 my @dfi = dsc_files_info();
2634 foreach my $fi (@dfi) {
2635 my $f = $fi->{Filename};
2636 next unless is_orig_file_in_dsc($f, \@dfi);
2637 complete_file_from_dsc('..', $fi)
2642 #---------- git fetch ----------
2644 sub lrfetchrefs () { return "refs/dgit-fetch/".access_basedistro(); }
2645 sub lrfetchref () { return lrfetchrefs.'/'.server_branch($csuite); }
2647 # We fetch some parts of lrfetchrefs/*. Ideally we delete these
2648 # locally fetched refs because they have unhelpful names and clutter
2649 # up gitk etc. So we track whether we have "used up" head ref (ie,
2650 # whether we have made another local ref which refers to this object).
2652 # (If we deleted them unconditionally, then we might end up
2653 # re-fetching the same git objects each time dgit fetch was run.)
2655 # So, each use of lrfetchrefs needs to be accompanied by arrangements
2656 # in git_fetch_us to fetch the refs in question, and possibly a call
2657 # to lrfetchref_used.
2659 our (%lrfetchrefs_f, %lrfetchrefs_d);
2660 # $lrfetchrefs_X{lrfetchrefs."/heads/whatever"} = $objid
2662 sub lrfetchref_used ($) {
2663 my ($fullrefname) = @_;
2664 my $objid = $lrfetchrefs_f{$fullrefname};
2665 $lrfetchrefs_d{$fullrefname} = $objid if defined $objid;
2668 sub git_lrfetch_sane {
2669 my ($url, $supplementary, @specs) = @_;
2670 # Make a 'refs/'.lrfetchrefs.'/*' be just like on server,
2671 # at least as regards @specs. Also leave the results in
2672 # %lrfetchrefs_f, and arrange for lrfetchref_used to be
2673 # able to clean these up.
2675 # With $supplementary==1, @specs must not contain wildcards
2676 # and we add to our previous fetches (non-atomically).
2678 # This is rather miserable:
2679 # When git fetch --prune is passed a fetchspec ending with a *,
2680 # it does a plausible thing. If there is no * then:
2681 # - it matches subpaths too, even if the supplied refspec
2682 # starts refs, and behaves completely madly if the source
2683 # has refs/refs/something. (See, for example, Debian #NNNN.)
2684 # - if there is no matching remote ref, it bombs out the whole
2686 # We want to fetch a fixed ref, and we don't know in advance
2687 # if it exists, so this is not suitable.
2689 # Our workaround is to use git ls-remote. git ls-remote has its
2690 # own qairks. Notably, it has the absurd multi-tail-matching
2691 # behaviour: git ls-remote R refs/foo can report refs/foo AND
2692 # refs/refs/foo etc.
2694 # Also, we want an idempotent snapshot, but we have to make two
2695 # calls to the remote: one to git ls-remote and to git fetch. The
2696 # solution is use git ls-remote to obtain a target state, and
2697 # git fetch to try to generate it. If we don't manage to generate
2698 # the target state, we try again.
2700 printdebug "git_lrfetch_sane suppl=$supplementary specs @specs\n";
2702 my $specre = join '|', map {
2705 my $wildcard = $x =~ s/\\\*$/.*/;
2706 die if $wildcard && $supplementary;
2709 printdebug "git_lrfetch_sane specre=$specre\n";
2710 my $wanted_rref = sub {
2712 return m/^(?:$specre)$/;
2715 my $fetch_iteration = 0;
2718 printdebug "git_lrfetch_sane iteration $fetch_iteration\n";
2719 if (++$fetch_iteration > 10) {
2720 fail "too many iterations trying to get sane fetch!";
2723 my @look = map { "refs/$_" } @specs;
2724 my @lcmd = (@git, qw(ls-remote -q --refs), $url, @look);
2728 open GITLS, "-|", @lcmd or die $!;
2730 printdebug "=> ", $_;
2731 m/^(\w+)\s+(\S+)\n/ or die "ls-remote $_ ?";
2732 my ($objid,$rrefname) = ($1,$2);
2733 if (!$wanted_rref->($rrefname)) {
2735 warning: git ls-remote @look reported $rrefname; this is silly, ignoring it.
2739 $wantr{$rrefname} = $objid;
2742 close GITLS or failedcmd @lcmd;
2744 # OK, now %want is exactly what we want for refs in @specs
2746 !m/\*$/ && !exists $wantr{"refs/$_"} ? () :
2747 "+refs/$_:".lrfetchrefs."/$_";
2750 printdebug "git_lrfetch_sane fspecs @fspecs\n";
2752 my @fcmd = (@git, qw(fetch -p -n -q), $url, @fspecs);
2753 runcmd_ordryrun_local @fcmd if @fspecs;
2755 if (!$supplementary) {
2756 %lrfetchrefs_f = ();
2760 git_for_each_ref(lrfetchrefs, sub {
2761 my ($objid,$objtype,$lrefname,$reftail) = @_;
2762 $lrfetchrefs_f{$lrefname} = $objid;
2763 $objgot{$objid} = 1;
2766 if ($supplementary) {
2770 foreach my $lrefname (sort keys %lrfetchrefs_f) {
2771 my $rrefname = 'refs'.substr($lrefname, length lrfetchrefs);
2772 if (!exists $wantr{$rrefname}) {
2773 if ($wanted_rref->($rrefname)) {
2775 git-fetch @fspecs created $lrefname which git ls-remote @look didn't list.
2779 warning: git fetch @fspecs created $lrefname; this is silly, deleting it.
2782 runcmd_ordryrun_local @git, qw(update-ref -d), $lrefname;
2783 delete $lrfetchrefs_f{$lrefname};
2787 foreach my $rrefname (sort keys %wantr) {
2788 my $lrefname = lrfetchrefs.substr($rrefname, 4);
2789 my $got = $lrfetchrefs_f{$lrefname} // '<none>';
2790 my $want = $wantr{$rrefname};
2791 next if $got eq $want;
2792 if (!defined $objgot{$want}) {
2793 fail <<END unless act_local();
2794 --dry-run specified but we actually wanted the results of git fetch,
2795 so this is not going to work. Try running dgit fetch first,
2796 or using --damp-run instead of --dry-run.
2799 warning: git ls-remote suggests we want $lrefname
2800 warning: and it should refer to $want
2801 warning: but git fetch didn't fetch that object to any relevant ref.
2802 warning: This may be due to a race with someone updating the server.
2803 warning: Will try again...
2805 next FETCH_ITERATION;
2808 git-fetch @fspecs made $lrefname=$got but want git ls-remote @look says $want
2810 runcmd_ordryrun_local @git, qw(update-ref -m),
2811 "dgit fetch git fetch fixup", $lrefname, $want;
2812 $lrfetchrefs_f{$lrefname} = $want;
2817 if (defined $csuite) {
2818 printdebug "git_lrfetch_sane: tidying any old suite lrfetchrefs\n";
2819 git_for_each_ref("refs/dgit-fetch/$csuite", sub {
2820 my ($objid,$objtype,$lrefname,$reftail) = @_;
2821 next if $lrfetchrefs_f{$lrefname}; # $csuite eq $distro ?
2822 runcmd_ordryrun_local @git, qw(update-ref -d), $lrefname;
2826 printdebug "git_lrfetch_sane: git fetch --no-insane emulation complete\n",
2827 Dumper(\%lrfetchrefs_f);
2830 sub git_fetch_us () {
2831 # Want to fetch only what we are going to use, unless
2832 # deliberately-not-ff, in which case we must fetch everything.
2834 my @specs = deliberately_not_fast_forward ? qw(tags/*) :
2836 (quiltmode_splitbrain
2837 ? (map { $_->('*',access_nomdistro) }
2838 \&debiantag_new, \&debiantag_maintview)
2839 : debiantags('*',access_nomdistro));
2840 push @specs, server_branch($csuite);
2841 push @specs, $rewritemap;
2842 push @specs, qw(heads/*) if deliberately_not_fast_forward;
2844 my $url = access_giturl();
2845 git_lrfetch_sane $url, 0, @specs;
2848 my @tagpats = debiantags('*',access_nomdistro);
2850 git_for_each_ref([map { "refs/tags/$_" } @tagpats], sub {
2851 my ($objid,$objtype,$fullrefname,$reftail) = @_;
2852 printdebug "currently $fullrefname=$objid\n";
2853 $here{$fullrefname} = $objid;
2855 git_for_each_ref([map { lrfetchrefs."/tags/".$_ } @tagpats], sub {
2856 my ($objid,$objtype,$fullrefname,$reftail) = @_;
2857 my $lref = "refs".substr($fullrefname, length(lrfetchrefs));
2858 printdebug "offered $lref=$objid\n";
2859 if (!defined $here{$lref}) {
2860 my @upd = (@git, qw(update-ref), $lref, $objid, '');
2861 runcmd_ordryrun_local @upd;
2862 lrfetchref_used $fullrefname;
2863 } elsif ($here{$lref} eq $objid) {
2864 lrfetchref_used $fullrefname;
2867 "Not updating $lref from $here{$lref} to $objid.\n";
2872 #---------- dsc and archive handling ----------
2874 sub mergeinfo_getclogp ($) {
2875 # Ensures thit $mi->{Clogp} exists and returns it
2877 $mi->{Clogp} = commit_getclogp($mi->{Commit});
2880 sub mergeinfo_version ($) {
2881 return getfield( (mergeinfo_getclogp $_[0]), 'Version' );
2884 sub fetch_from_archive_record_1 ($) {
2886 runcmd git_update_ref_cmd "dgit fetch $csuite", 'DGIT_ARCHIVE', $hash;
2887 cmdoutput @git, qw(log -n2), $hash;
2888 # ... gives git a chance to complain if our commit is malformed
2891 sub fetch_from_archive_record_2 ($) {
2893 my @upd_cmd = (git_update_ref_cmd 'dgit fetch', lrref(), $hash);
2897 dryrun_report @upd_cmd;
2901 sub parse_dsc_field_def_dsc_distro () {
2902 $dsc_distro //= cfg qw(dgit.default.old-dsc-distro
2903 dgit.default.distro);
2906 sub parse_dsc_field ($$) {
2907 my ($dsc, $what) = @_;
2909 foreach my $field (@ourdscfield) {
2910 $f = $dsc->{$field};
2915 progress "$what: NO git hash";
2916 parse_dsc_field_def_dsc_distro();
2917 } elsif (($dsc_hash, $dsc_distro, $dsc_hint_tag, $dsc_hint_url)
2918 = $f =~ m/^(\w+)\s+($distro_re)\s+($versiontag_re)\s+(\S+)(?:\s|$)/) {
2919 progress "$what: specified git info ($dsc_distro)";
2920 $dsc_hint_tag = [ $dsc_hint_tag ];
2921 } elsif ($f =~ m/^\w+\s*$/) {
2923 parse_dsc_field_def_dsc_distro();
2924 $dsc_hint_tag = [ debiantags +(getfield $dsc, 'Version'),
2926 progress "$what: specified git hash";
2928 fail "$what: invalid Dgit info";
2932 sub resolve_dsc_field_commit ($$) {
2933 my ($already_distro, $already_mapref) = @_;
2935 return unless defined $dsc_hash;
2938 defined $already_mapref &&
2939 ($already_distro eq $dsc_distro || !$chase_dsc_distro)
2940 ? $already_mapref : undef;
2944 my ($what, @fetch) = @_;
2946 local $idistro = $dsc_distro;
2947 my $lrf = lrfetchrefs;
2949 if (!$chase_dsc_distro) {
2951 "not chasing .dsc distro $dsc_distro: not fetching $what";
2956 ".dsc names distro $dsc_distro: fetching $what";
2958 my $url = access_giturl();
2959 if (!defined $url) {
2960 defined $dsc_hint_url or fail <<END;
2961 .dsc Dgit metadata is in context of distro $dsc_distro
2962 for which we have no configured url and .dsc provides no hint
2965 $dsc_hint_url =~ m#^([-+0-9a-zA-Z]+):# ? $1 :
2966 $dsc_hint_url =~ m#^/# ? 'file' : 'bad-syntax';
2967 parse_cfg_bool "dsc-url-proto-ok", 'false',
2968 cfg("dgit.dsc-url-proto-ok.$proto",
2969 "dgit.default.dsc-url-proto-ok")
2971 .dsc Dgit metadata is in context of distro $dsc_distro
2972 for which we have no configured url;
2973 .dsc provides hinted url with protocol $proto which is unsafe.
2974 (can be overridden by config - consult documentation)
2976 $url = $dsc_hint_url;
2979 git_lrfetch_sane $url, 1, @fetch;
2984 my $rewrite_enable = do {
2985 local $idistro = $dsc_distro;
2986 access_cfg('rewrite-map-enable', 'RETURN-UNDEF');
2989 if (parse_cfg_bool 'rewrite-map-enable', 'true', $rewrite_enable) {
2990 if (!defined $mapref) {
2991 my $lrf = $do_fetch->("rewrite map", $rewritemap) or return;
2992 $mapref = $lrf.'/'.$rewritemap;
2994 my $rewritemapdata = git_cat_file $mapref.':map';
2995 if (defined $rewritemapdata
2996 && $rewritemapdata =~ m/^$dsc_hash(?:[ \t](\w+))/m) {
2998 "server's git history rewrite map contains a relevant entry!";
3001 if (defined $dsc_hash) {
3002 progress "using rewritten git hash in place of .dsc value";
3004 progress "server data says .dsc hash is to be disregarded";
3009 if (!defined git_cat_file $dsc_hash) {
3010 my @tags = map { "tags/".$_ } @$dsc_hint_tag;
3011 my $lrf = $do_fetch->("additional commits", @tags) &&
3012 defined git_cat_file $dsc_hash
3014 .dsc Dgit metadata requires commit $dsc_hash
3015 but we could not obtain that object anywhere.
3017 foreach my $t (@tags) {
3018 my $fullrefname = $lrf.'/'.$t;
3019 # print STDERR "CHK $t $fullrefname ".Dumper(\%lrfetchrefs_f);
3020 next unless $lrfetchrefs_f{$fullrefname};
3021 next unless is_fast_fwd "$fullrefname~0", $dsc_hash;
3022 lrfetchref_used $fullrefname;
3027 sub fetch_from_archive () {
3028 ensure_setup_existing_tree();
3030 # Ensures that lrref() is what is actually in the archive, one way
3031 # or another, according to us - ie this client's
3032 # appropritaely-updated archive view. Also returns the commit id.
3033 # If there is nothing in the archive, leaves lrref alone and
3034 # returns undef. git_fetch_us must have already been called.
3038 parse_dsc_field($dsc, 'last upload to archive');
3039 resolve_dsc_field_commit access_basedistro,
3040 lrfetchrefs."/".$rewritemap
3042 progress "no version available from the archive";
3045 # If the archive's .dsc has a Dgit field, there are three
3046 # relevant git commitids we need to choose between and/or merge
3048 # 1. $dsc_hash: the Dgit field from the archive
3049 # 2. $lastpush_hash: the suite branch on the dgit git server
3050 # 3. $lastfetch_hash: our local tracking brach for the suite
3052 # These may all be distinct and need not be in any fast forward
3055 # If the dsc was pushed to this suite, then the server suite
3056 # branch will have been updated; but it might have been pushed to
3057 # a different suite and copied by the archive. Conversely a more
3058 # recent version may have been pushed with dgit but not appeared
3059 # in the archive (yet).
3061 # $lastfetch_hash may be awkward because archive imports
3062 # (particularly, imports of Dgit-less .dscs) are performed only as
3063 # needed on individual clients, so different clients may perform a
3064 # different subset of them - and these imports are only made
3065 # public during push. So $lastfetch_hash may represent a set of
3066 # imports different to a subsequent upload by a different dgit
3069 # Our approach is as follows:
3071 # As between $dsc_hash and $lastpush_hash: if $lastpush_hash is a
3072 # descendant of $dsc_hash, then it was pushed by a dgit user who
3073 # had based their work on $dsc_hash, so we should prefer it.
3074 # Otherwise, $dsc_hash was installed into this suite in the
3075 # archive other than by a dgit push, and (necessarily) after the
3076 # last dgit push into that suite (since a dgit push would have
3077 # been descended from the dgit server git branch); thus, in that
3078 # case, we prefer the archive's version (and produce a
3079 # pseudo-merge to overwrite the dgit server git branch).
3081 # (If there is no Dgit field in the archive's .dsc then
3082 # generate_commit_from_dsc uses the version numbers to decide
3083 # whether the suite branch or the archive is newer. If the suite
3084 # branch is newer it ignores the archive's .dsc; otherwise it
3085 # generates an import of the .dsc, and produces a pseudo-merge to
3086 # overwrite the suite branch with the archive contents.)
3088 # The outcome of that part of the algorithm is the `public view',
3089 # and is same for all dgit clients: it does not depend on any
3090 # unpublished history in the local tracking branch.
3092 # As between the public view and the local tracking branch: The
3093 # local tracking branch is only updated by dgit fetch, and
3094 # whenever dgit fetch runs it includes the public view in the
3095 # local tracking branch. Therefore if the public view is not
3096 # descended from the local tracking branch, the local tracking
3097 # branch must contain history which was imported from the archive
3098 # but never pushed; and, its tip is now out of date. So, we make
3099 # a pseudo-merge to overwrite the old imports and stitch the old
3102 # Finally: we do not necessarily reify the public view (as
3103 # described above). This is so that we do not end up stacking two
3104 # pseudo-merges. So what we actually do is figure out the inputs
3105 # to any public view pseudo-merge and put them in @mergeinputs.
3108 # $mergeinputs[]{Commit}
3109 # $mergeinputs[]{Info}
3110 # $mergeinputs[0] is the one whose tree we use
3111 # @mergeinputs is in the order we use in the actual commit)
3114 # $mergeinputs[]{Message} is a commit message to use
3115 # $mergeinputs[]{ReverseParents} if def specifies that parent
3116 # list should be in opposite order
3117 # Such an entry has no Commit or Info. It applies only when found
3118 # in the last entry. (This ugliness is to support making
3119 # identical imports to previous dgit versions.)
3121 my $lastpush_hash = git_get_ref(lrfetchref());
3122 printdebug "previous reference hash=$lastpush_hash\n";
3123 $lastpush_mergeinput = $lastpush_hash && {
3124 Commit => $lastpush_hash,
3125 Info => "dgit suite branch on dgit git server",
3128 my $lastfetch_hash = git_get_ref(lrref());
3129 printdebug "fetch_from_archive: lastfetch=$lastfetch_hash\n";
3130 my $lastfetch_mergeinput = $lastfetch_hash && {
3131 Commit => $lastfetch_hash,
3132 Info => "dgit client's archive history view",
3135 my $dsc_mergeinput = $dsc_hash && {
3136 Commit => $dsc_hash,
3137 Info => "Dgit field in .dsc from archive",
3141 my $del_lrfetchrefs = sub {
3144 printdebug "del_lrfetchrefs...\n";
3145 foreach my $fullrefname (sort keys %lrfetchrefs_d) {
3146 my $objid = $lrfetchrefs_d{$fullrefname};
3147 printdebug "del_lrfetchrefs: $objid $fullrefname\n";
3149 $gur ||= new IO::Handle;
3150 open $gur, "|-", qw(git update-ref --stdin) or die $!;
3152 printf $gur "delete %s %s\n", $fullrefname, $objid;
3155 close $gur or failedcmd "git update-ref delete lrfetchrefs";
3159 if (defined $dsc_hash) {
3160 ensure_we_have_orig();
3161 if (!$lastpush_hash || $dsc_hash eq $lastpush_hash) {
3162 @mergeinputs = $dsc_mergeinput
3163 } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
3164 print STDERR <<END or die $!;
3166 Git commit in archive is behind the last version allegedly pushed/uploaded.
3167 Commit referred to by archive: $dsc_hash
3168 Last version pushed with dgit: $lastpush_hash
3171 @mergeinputs = ($lastpush_mergeinput);
3173 # Archive has .dsc which is not a descendant of the last dgit
3174 # push. This can happen if the archive moves .dscs about.
3175 # Just follow its lead.
3176 if (is_fast_fwd($lastpush_hash,$dsc_hash)) {
3177 progress "archive .dsc names newer git commit";
3178 @mergeinputs = ($dsc_mergeinput);
3180 progress "archive .dsc names other git commit, fixing up";
3181 @mergeinputs = ($dsc_mergeinput, $lastpush_mergeinput);
3185 @mergeinputs = generate_commits_from_dsc();
3186 # We have just done an import. Now, our import algorithm might
3187 # have been improved. But even so we do not want to generate
3188 # a new different import of the same package. So if the
3189 # version numbers are the same, just use our existing version.
3190 # If the version numbers are different, the archive has changed
3191 # (perhaps, rewound).
3192 if ($lastfetch_mergeinput &&
3193 !version_compare( (mergeinfo_version $lastfetch_mergeinput),
3194 (mergeinfo_version $mergeinputs[0]) )) {
3195 @mergeinputs = ($lastfetch_mergeinput);
3197 } elsif ($lastpush_hash) {
3198 # only in git, not in the archive yet
3199 @mergeinputs = ($lastpush_mergeinput);
3200 print STDERR <<END or die $!;
3202 Package not found in the archive, but has allegedly been pushed using dgit.
3206 printdebug "nothing found!\n";
3207 if (defined $skew_warning_vsn) {
3208 print STDERR <<END or die $!;
3210 Warning: relevant archive skew detected.
3211 Archive allegedly contains $skew_warning_vsn
3212 But we were not able to obtain any version from the archive or git.
3216 unshift @end, $del_lrfetchrefs;
3220 if ($lastfetch_hash &&
3222 my $h = $_->{Commit};
3223 $h and is_fast_fwd($lastfetch_hash, $h);
3224 # If true, one of the existing parents of this commit
3225 # is a descendant of the $lastfetch_hash, so we'll
3226 # be ff from that automatically.
3230 push @mergeinputs, $lastfetch_mergeinput;
3233 printdebug "fetch mergeinfos:\n";
3234 foreach my $mi (@mergeinputs) {
3236 printdebug " commit $mi->{Commit} $mi->{Info}\n";
3238 printdebug sprintf " ReverseParents=%d Message=%s",
3239 $mi->{ReverseParents}, $mi->{Message};
3243 my $compat_info= pop @mergeinputs
3244 if $mergeinputs[$#mergeinputs]{Message};
3246 @mergeinputs = grep { defined $_->{Commit} } @mergeinputs;
3249 if (@mergeinputs > 1) {
3251 my $tree_commit = $mergeinputs[0]{Commit};
3253 my $tree = cmdoutput @git, qw(cat-file commit), $tree_commit;
3254 $tree =~ m/\n\n/; $tree = $`;
3255 $tree =~ m/^tree (\w+)$/m or die "$dsc_hash tree ?";
3258 # We use the changelog author of the package in question the
3259 # author of this pseudo-merge. This is (roughly) correct if
3260 # this commit is simply representing aa non-dgit upload.
3261 # (Roughly because it does not record sponsorship - but we
3262 # don't have sponsorship info because that's in the .changes,
3263 # which isn't in the archivw.)
3265 # But, it might be that we are representing archive history
3266 # updates (including in-archive copies). These are not really
3267 # the responsibility of the person who created the .dsc, but
3268 # there is no-one whose name we should better use. (The
3269 # author of the .dsc-named commit is clearly worse.)
3271 my $useclogp = mergeinfo_getclogp $mergeinputs[0];
3272 my $author = clogp_authline $useclogp;
3273 my $cversion = getfield $useclogp, 'Version';
3275 my $mcf = dgit_privdir()."/mergecommit";
3276 open MC, ">", $mcf or die "$mcf $!";
3277 print MC <<END or die $!;
3281 my @parents = grep { $_->{Commit} } @mergeinputs;
3282 @parents = reverse @parents if $compat_info->{ReverseParents};
3283 print MC <<END or die $! foreach @parents;
3287 print MC <<END or die $!;
3293 if (defined $compat_info->{Message}) {
3294 print MC $compat_info->{Message} or die $!;
3296 print MC <<END or die $!;
3297 Record $package ($cversion) in archive suite $csuite
3301 my $message_add_info = sub {
3303 my $mversion = mergeinfo_version $mi;
3304 printf MC " %-20s %s\n", $mversion, $mi->{Info}
3308 $message_add_info->($mergeinputs[0]);
3309 print MC <<END or die $!;
3310 should be treated as descended from
3312 $message_add_info->($_) foreach @mergeinputs[1..$#mergeinputs];
3316 $hash = make_commit $mcf;
3318 $hash = $mergeinputs[0]{Commit};
3320 printdebug "fetch hash=$hash\n";
3323 my ($lasth, $what) = @_;
3324 return unless $lasth;
3325 die "$lasth $hash $what ?" unless is_fast_fwd($lasth, $hash);
3328 $chkff->($lastpush_hash, 'dgit repo server tip (last push)')
3330 $chkff->($lastfetch_hash, 'local tracking tip (last fetch)');
3332 fetch_from_archive_record_1($hash);
3334 if (defined $skew_warning_vsn) {
3335 printdebug "SKEW CHECK WANT $skew_warning_vsn\n";
3336 my $gotclogp = commit_getclogp($hash);
3337 my $got_vsn = getfield $gotclogp, 'Version';
3338 printdebug "SKEW CHECK GOT $got_vsn\n";
3339 if (version_compare($got_vsn, $skew_warning_vsn) < 0) {
3340 print STDERR <<END or die $!;
3342 Warning: archive skew detected. Using the available version:
3343 Archive allegedly contains $skew_warning_vsn
3344 We were able to obtain only $got_vsn
3350 if ($lastfetch_hash ne $hash) {
3351 fetch_from_archive_record_2($hash);
3354 lrfetchref_used lrfetchref();
3356 check_gitattrs($hash, "fetched source tree");
3358 unshift @end, $del_lrfetchrefs;
3362 sub set_local_git_config ($$) {
3364 runcmd @git, qw(config), $k, $v;
3367 sub setup_mergechangelogs (;$) {
3369 return unless $always || access_cfg_bool(1, 'setup-mergechangelogs');
3371 my $driver = 'dpkg-mergechangelogs';
3372 my $cb = "merge.$driver";
3373 confess unless defined $maindir;
3374 my $attrs = "$maindir_gitcommon/info/attributes";
3375 ensuredir "$maindir_gitcommon/info";
3377 open NATTRS, ">", "$attrs.new" or die "$attrs.new $!";
3378 if (!open ATTRS, "<", $attrs) {
3379 $!==ENOENT or die "$attrs: $!";
3383 next if m{^debian/changelog\s};
3384 print NATTRS $_, "\n" or die $!;
3386 ATTRS->error and die $!;
3389 print NATTRS "debian/changelog merge=$driver\n" or die $!;
3392 set_local_git_config "$cb.name", 'debian/changelog merge driver';
3393 set_local_git_config "$cb.driver", 'dpkg-mergechangelogs -m %O %A %B %A';
3395 rename "$attrs.new", "$attrs" or die "$attrs: $!";
3398 sub setup_useremail (;$) {
3400 return unless $always || access_cfg_bool(1, 'setup-useremail');
3403 my ($k, $envvar) = @_;
3404 my $v = access_cfg("user-$k", 'RETURN-UNDEF') // $ENV{$envvar};
3405 return unless defined $v;
3406 set_local_git_config "user.$k", $v;
3409 $setup->('email', 'DEBEMAIL');
3410 $setup->('name', 'DEBFULLNAME');
3413 sub ensure_setup_existing_tree () {
3414 my $k = "remote.$remotename.skipdefaultupdate";
3415 my $c = git_get_config $k;
3416 return if defined $c;
3417 set_local_git_config $k, 'true';
3420 sub open_main_gitattrs () {
3421 confess 'internal error no maindir' unless defined $maindir;
3422 my $gai = new IO::File "$maindir_gitcommon/info/attributes"
3424 or die "open $maindir_gitcommon/info/attributes: $!";
3428 our $gitattrs_ourmacro_re = qr{^\[attr\]dgit-defuse-attrs\s};
3430 sub is_gitattrs_setup () {
3433 # 1: gitattributes set up and should be left alone
3435 # 0: there is a dgit-defuse-attrs but it needs fixing
3436 # undef: there is none
3437 my $gai = open_main_gitattrs();
3438 return 0 unless $gai;
3440 next unless m{$gitattrs_ourmacro_re};
3441 return 1 if m{\s-working-tree-encoding\s};
3442 printdebug "is_gitattrs_setup: found old macro\n";
3445 $gai->error and die $!;
3446 printdebug "is_gitattrs_setup: found nothing\n";
3450 sub setup_gitattrs (;$) {
3452 return unless $always || access_cfg_bool(1, 'setup-gitattributes');
3454 my $already = is_gitattrs_setup();
3457 [attr]dgit-defuse-attrs already found, and proper, in .git/info/attributes
3458 not doing further gitattributes setup
3462 my $new = "[attr]dgit-defuse-attrs $negate_harmful_gitattrs";
3463 my $af = "$maindir_gitcommon/info/attributes";
3464 ensuredir "$maindir_gitcommon/info";
3466 open GAO, "> $af.new" or die $!;
3467 print GAO <<END or die $! unless defined $already;
3470 # ^ see GITATTRIBUTES in dgit(7) and dgit setup-new-tree in dgit(1)
3472 my $gai = open_main_gitattrs();
3475 if (m{$gitattrs_ourmacro_re}) {
3476 die unless defined $already;
3480 print GAO $_, "\n" or die $!;
3482 $gai->error and die $!;
3484 close GAO or die $!;
3485 rename "$af.new", "$af" or die "install $af: $!";
3488 sub setup_new_tree () {
3489 setup_mergechangelogs();
3494 sub check_gitattrs ($$) {
3495 my ($treeish, $what) = @_;
3497 return if is_gitattrs_setup;
3500 my @cmd = (@git, qw(ls-tree -lrz --), "${treeish}:");
3502 my $gafl = new IO::File;
3503 open $gafl, "-|", @cmd or die $!;
3506 s/^\d+\s+\w+\s+\w+\s+(\d+)\t// or die;
3508 next unless m{(?:^|/)\.gitattributes$};
3510 # oh dear, found one
3512 dgit: warning: $what contains .gitattributes
3513 dgit: .gitattributes not (fully) defused. Recommended: dgit setup-new-tree.
3518 # tree contains no .gitattributes files
3519 $?=0; $!=0; close $gafl or failedcmd @cmd;
3523 sub multisuite_suite_child ($$$) {
3524 my ($tsuite, $merginputs, $fn) = @_;
3525 # in child, sets things up, calls $fn->(), and returns undef
3526 # in parent, returns canonical suite name for $tsuite
3527 my $canonsuitefh = IO::File::new_tmpfile;
3528 my $pid = fork // die $!;
3532 $us .= " [$isuite]";
3533 $debugprefix .= " ";
3534 progress "fetching $tsuite...";
3535 canonicalise_suite();
3536 print $canonsuitefh $csuite, "\n" or die $!;
3537 close $canonsuitefh or die $!;
3541 waitpid $pid,0 == $pid or die $!;
3542 fail "failed to obtain $tsuite: ".waitstatusmsg() if $? && $?!=256*4;
3543 seek $canonsuitefh,0,0 or die $!;
3544 local $csuite = <$canonsuitefh>;
3545 die $! unless defined $csuite && chomp $csuite;
3547 printdebug "multisuite $tsuite missing\n";
3550 printdebug "multisuite $tsuite ok (canon=$csuite)\n";
3551 push @$merginputs, {
3558 sub fork_for_multisuite ($) {
3559 my ($before_fetch_merge) = @_;
3560 # if nothing unusual, just returns ''
3563 # returns 0 to caller in child, to do first of the specified suites
3564 # in child, $csuite is not yet set
3566 # returns 1 to caller in parent, to finish up anything needed after
3567 # in parent, $csuite is set to canonicalised portmanteau
3569 my $org_isuite = $isuite;
3570 my @suites = split /\,/, $isuite;
3571 return '' unless @suites > 1;
3572 printdebug "fork_for_multisuite: @suites\n";
3576 my $cbasesuite = multisuite_suite_child($suites[0], \@mergeinputs,
3578 return 0 unless defined $cbasesuite;
3580 fail "package $package missing in (base suite) $cbasesuite"
3581 unless @mergeinputs;
3583 my @csuites = ($cbasesuite);
3585 $before_fetch_merge->();
3587 foreach my $tsuite (@suites[1..$#suites]) {
3588 $tsuite =~ s/^-/$cbasesuite-/;
3589 my $csubsuite = multisuite_suite_child($tsuite, \@mergeinputs,
3595 # xxx collecte the ref here
3597 $csubsuite =~ s/^\Q$cbasesuite\E-/-/;
3598 push @csuites, $csubsuite;
3601 foreach my $mi (@mergeinputs) {
3602 my $ref = git_get_ref $mi->{Ref};
3603 die "$mi->{Ref} ?" unless length $ref;
3604 $mi->{Commit} = $ref;
3607 $csuite = join ",", @csuites;
3609 my $previous = git_get_ref lrref;
3611 unshift @mergeinputs, {
3612 Commit => $previous,
3613 Info => "local combined tracking branch",
3615 "archive seems to have rewound: local tracking branch is ahead!",
3619 foreach my $ix (0..$#mergeinputs) {
3620 $mergeinputs[$ix]{Index} = $ix;
3623 @mergeinputs = sort {
3624 -version_compare(mergeinfo_version $a,
3625 mergeinfo_version $b) # highest version first
3627 $a->{Index} <=> $b->{Index}; # earliest in spec first
3633 foreach my $mi (@mergeinputs) {
3634 printdebug "multisuite merge check $mi->{Info}\n";
3635 foreach my $previous (@needed) {
3636 next unless is_fast_fwd $mi->{Commit}, $previous->{Commit};
3637 printdebug "multisuite merge un-needed $previous->{Info}\n";
3641 printdebug "multisuite merge this-needed\n";
3642 $mi->{Character} = '+';
3645 $needed[0]{Character} = '*';
3647 my $output = $needed[0]{Commit};
3650 printdebug "multisuite merge nontrivial\n";
3651 my $tree = cmdoutput qw(git rev-parse), $needed[0]{Commit}.':';
3653 my $commit = "tree $tree\n";
3654 my $msg = "Combine archive branches $csuite [dgit]\n\n".
3655 "Input branches:\n";
3657 foreach my $mi (sort { $a->{Index} <=> $b->{Index} } @mergeinputs) {
3658 printdebug "multisuite merge include $mi->{Info}\n";
3659 $mi->{Character} //= ' ';
3660 $commit .= "parent $mi->{Commit}\n";
3661 $msg .= sprintf " %s %-25s %s\n",
3663 (mergeinfo_version $mi),
3666 my $authline = clogp_authline mergeinfo_getclogp $needed[0];
3668 " * marks the highest version branch, which choose to use\n".
3669 " + marks each branch which was not already an ancestor\n\n".
3670 "[dgit multi-suite $csuite]\n";
3672 "author $authline\n".
3673 "committer $authline\n\n";
3674 $output = make_commit_text $commit.$msg;
3675 printdebug "multisuite merge generated $output\n";
3678 fetch_from_archive_record_1($output);
3679 fetch_from_archive_record_2($output);
3681 progress "calculated combined tracking suite $csuite";
3686 sub clone_set_head () {
3687 open H, "> .git/HEAD" or die $!;
3688 print H "ref: ".lref()."\n" or die $!;
3691 sub clone_finish ($) {
3693 runcmd @git, qw(reset --hard), lrref();
3694 runcmd qw(bash -ec), <<'END';
3696 git ls-tree -r --name-only -z HEAD | \
3697 xargs -0r touch -h -r . --
3699 printdone "ready for work in $dstdir";
3703 # in multisuite, returns twice!
3704 # once in parent after first suite fetched,
3705 # and then again in child after everything is finished
3707 badusage "dry run makes no sense with clone" unless act_local();
3709 my $multi_fetched = fork_for_multisuite(sub {
3710 printdebug "multi clone before fetch merge\n";
3714 if ($multi_fetched) {
3715 printdebug "multi clone after fetch merge\n";
3717 clone_finish($dstdir);
3720 printdebug "clone main body\n";
3722 canonicalise_suite();
3723 my $hasgit = check_for_git();
3724 mkdir $dstdir or fail "create \`$dstdir': $!";
3726 runcmd @git, qw(init -q);
3730 my $giturl = access_giturl(1);
3731 if (defined $giturl) {
3732 runcmd @git, qw(remote add), 'origin', $giturl;
3735 progress "fetching existing git history";
3737 runcmd_ordryrun_local @git, qw(fetch origin);
3739 progress "starting new git history";
3741 fetch_from_archive() or no_such_package;
3742 my $vcsgiturl = $dsc->{'Vcs-Git'};
3743 if (length $vcsgiturl) {
3744 $vcsgiturl =~ s/\s+-b\s+\S+//g;
3745 runcmd @git, qw(remote add vcs-git), $vcsgiturl;
3747 clone_finish($dstdir);
3751 canonicalise_suite();
3752 if (check_for_git()) {
3755 fetch_from_archive() or no_such_package();
3757 my $vcsgiturl = $dsc && $dsc->{'Vcs-Git'};
3758 if (length $vcsgiturl and
3759 (grep { $csuite eq $_ }
3761 cfg 'dgit.vcs-git.suites')) {
3762 my $current = cfg 'remote.vcs-git.url', 'RETURN-UNDEF';
3763 if (defined $current && $current ne $vcsgiturl) {
3765 FYI: Vcs-Git in $csuite has different url to your vcs-git remote.
3766 Your vcs-git remote url may be out of date. Use dgit update-vcs-git ?
3770 printdone "fetched into ".lrref();
3774 my $multi_fetched = fork_for_multisuite(sub { });
3775 fetch_one() unless $multi_fetched; # parent
3776 finish 0 if $multi_fetched eq '0'; # child
3781 runcmd_ordryrun_local @git, qw(merge -m),"Merge from $csuite [dgit]",
3783 printdone "fetched to ".lrref()." and merged into HEAD";
3786 sub check_not_dirty () {
3787 foreach my $f (qw(local-options local-patch-header)) {
3788 if (stat_exists "debian/source/$f") {
3789 fail "git tree contains debian/source/$f";
3793 return if $ignoredirty;
3795 git_check_unmodified();
3798 sub commit_admin ($) {
3801 runcmd_ordryrun_local @git, qw(commit -m), $m;
3804 sub quiltify_nofix_bail ($$) {
3805 my ($headinfo, $xinfo) = @_;
3806 if ($quilt_mode eq 'nofix') {
3807 fail "quilt fixup required but quilt mode is \`nofix'\n".
3808 "HEAD commit".$headinfo." differs from tree implied by ".
3809 " debian/patches".$xinfo;
3813 sub commit_quilty_patch () {
3814 my $output = cmdoutput @git, qw(status --porcelain);
3816 foreach my $l (split /\n/, $output) {
3817 next unless $l =~ m/\S/;
3818 if ($l =~ m{^(?:\?\?| [MADRC]) (.pc|debian/patches)}) {
3822 delete $adds{'.pc'}; # if there wasn't one before, don't add it
3824 progress "nothing quilty to commit, ok.";
3827 quiltify_nofix_bail "", " (wanted to commit patch update)";
3828 my @adds = map { s/[][*?\\]/\\$&/g; $_; } sort keys %adds;
3829 runcmd_ordryrun_local @git, qw(add -f), @adds;
3831 Commit Debian 3.0 (quilt) metadata
3833 [dgit ($our_version) quilt-fixup]
3837 sub get_source_format () {
3839 if (open F, "debian/source/options") {
3843 s/\s+$//; # ignore missing final newline
3845 my ($k, $v) = ($`, $'); #');
3846 $v =~ s/^"(.*)"$/$1/;
3852 F->error and die $!;
3855 die $! unless $!==&ENOENT;
3858 if (!open F, "debian/source/format") {
3859 die $! unless $!==&ENOENT;
3863 F->error and die $!;
3865 return ($_, \%options);
3868 sub madformat_wantfixup ($) {
3870 return 0 unless $format eq '3.0 (quilt)';
3871 our $quilt_mode_warned;
3872 if ($quilt_mode eq 'nocheck') {
3873 progress "Not doing any fixup of \`$format' due to".
3874 " ----no-quilt-fixup or --quilt=nocheck"
3875 unless $quilt_mode_warned++;
3878 progress "Format \`$format', need to check/update patch stack"
3879 unless $quilt_mode_warned++;
3883 sub maybe_split_brain_save ($$$) {
3884 my ($headref, $dgitview, $msg) = @_;
3885 # => message fragment "$saved" describing disposition of $dgitview
3886 return "commit id $dgitview" unless defined $split_brain_save;
3887 my @cmd = (shell_cmd 'cd "$1"; shift', $maindir,
3889 "dgit --dgit-view-save $msg HEAD=$headref",
3890 $split_brain_save, $dgitview);
3892 return "and left in $split_brain_save";
3895 # An "infopair" is a tuple [ $thing, $what ]
3896 # (often $thing is a commit hash; $what is a description)
3898 sub infopair_cond_equal ($$) {
3900 $x->[0] eq $y->[0] or fail <<END;
3901 $x->[1] ($x->[0]) not equal to $y->[1] ($y->[0])
3905 sub infopair_lrf_tag_lookup ($$) {
3906 my ($tagnames, $what) = @_;
3907 # $tagname may be an array ref
3908 my @tagnames = ref $tagnames ? @$tagnames : ($tagnames);
3909 printdebug "infopair_lrfetchref_tag_lookup $what @tagnames\n";
3910 foreach my $tagname (@tagnames) {
3911 my $lrefname = lrfetchrefs."/tags/$tagname";
3912 my $tagobj = $lrfetchrefs_f{$lrefname};
3913 next unless defined $tagobj;
3914 printdebug "infopair_lrfetchref_tag_lookup $tagobj $tagname $what\n";
3915 return [ git_rev_parse($tagobj), $what ];
3917 fail @tagnames==1 ? <<END : <<END;
3918 Wanted tag $what (@tagnames) on dgit server, but not found
3920 Wanted tag $what (one of: @tagnames) on dgit server, but not found
3924 sub infopair_cond_ff ($$) {
3925 my ($anc,$desc) = @_;
3926 is_fast_fwd($anc->[0], $desc->[0]) or fail <<END;
3927 $anc->[1] ($anc->[0]) .. $desc->[1] ($desc->[0]) is not fast forward
3931 sub pseudomerge_version_check ($$) {
3932 my ($clogp, $archive_hash) = @_;
3934 my $arch_clogp = commit_getclogp $archive_hash;
3935 my $i_arch_v = [ (getfield $arch_clogp, 'Version'),
3936 'version currently in archive' ];
3937 if (defined $overwrite_version) {
3938 if (length $overwrite_version) {
3939 infopair_cond_equal([ $overwrite_version,
3940 '--overwrite= version' ],
3943 my $v = $i_arch_v->[0];
3944 progress "Checking package changelog for archive version $v ...";
3947 my @xa = ("-f$v", "-t$v");
3948 my $vclogp = parsechangelog @xa;
3951 [ (getfield $vclogp, $fn),
3952 "$fn field from dpkg-parsechangelog @xa" ];
3954 my $cv = $gf->('Version');
3955 infopair_cond_equal($i_arch_v, $cv);
3956 $cd = $gf->('Distribution');
3959 $@ =~ s/^dgit: //gm;
3961 "Perhaps debian/changelog does not mention $v ?";
3963 fail <<END if $cd->[0] =~ m/UNRELEASED/;
3964 $cd->[1] is $cd->[0]
3965 Your tree seems to based on earlier (not uploaded) $v.
3970 printdebug "pseudomerge_version_check i_arch_v @$i_arch_v\n";
3974 sub pseudomerge_make_commit ($$$$ $$) {
3975 my ($clogp, $dgitview, $archive_hash, $i_arch_v,
3976 $msg_cmd, $msg_msg) = @_;
3977 progress "Declaring that HEAD inciudes all changes in $i_arch_v->[0]...";
3979 my $tree = cmdoutput qw(git rev-parse), "${dgitview}:";
3980 my $authline = clogp_authline $clogp;
3984 !defined $overwrite_version ? ""
3985 : !length $overwrite_version ? " --overwrite"
3986 : " --overwrite=".$overwrite_version;
3988 # Contributing parent is the first parent - that makes
3989 # git rev-list --first-parent DTRT.
3990 my $pmf = dgit_privdir()."/pseudomerge";
3991 open MC, ">", $pmf or die "$pmf $!";
3992 print MC <<END or die $!;
3995 parent $archive_hash
4005 return make_commit($pmf);
4008 sub splitbrain_pseudomerge ($$$$) {
4009 my ($clogp, $maintview, $dgitview, $archive_hash) = @_;
4010 # => $merged_dgitview
4011 printdebug "splitbrain_pseudomerge...\n";
4013 # We: debian/PREVIOUS HEAD($maintview)
4014 # expect: o ----------------- o
4017 # a/d/PREVIOUS $dgitview
4020 # we do: `------------------ o
4024 return $dgitview unless defined $archive_hash;
4025 return $dgitview if deliberately_not_fast_forward();
4027 printdebug "splitbrain_pseudomerge...\n";
4029 my $i_arch_v = pseudomerge_version_check($clogp, $archive_hash);
4031 if (!defined $overwrite_version) {
4032 progress "Checking that HEAD inciudes all changes in archive...";
4035 return $dgitview if is_fast_fwd $archive_hash, $dgitview;
4037 if (defined $overwrite_version) {
4039 my $t_dep14 = debiantag_maintview $i_arch_v->[0], access_nomdistro;
4040 my $i_dep14 = infopair_lrf_tag_lookup($t_dep14, "maintainer view tag");
4041 my $t_dgit = debiantag_new $i_arch_v->[0], access_nomdistro;
4042 my $i_dgit = infopair_lrf_tag_lookup($t_dgit, "dgit view tag");
4043 my $i_archive = [ $archive_hash, "current archive contents" ];
4045 printdebug "splitbrain_pseudomerge i_archive @$i_archive\n";
4047 infopair_cond_equal($i_dgit, $i_archive);
4048 infopair_cond_ff($i_dep14, $i_dgit);
4049 infopair_cond_ff($i_dep14, [ $maintview, 'HEAD' ]);
4052 $@ =~ s/^\n//; chomp $@;
4055 | Not fast forward; maybe --overwrite is needed, see dgit(1)
4060 my $r = pseudomerge_make_commit
4061 $clogp, $dgitview, $archive_hash, $i_arch_v,
4062 "dgit --quilt=$quilt_mode",
4063 (defined $overwrite_version ? <<END_OVERWR : <<END_MAKEFF);
4064 Declare fast forward from $i_arch_v->[0]
4066 Make fast forward from $i_arch_v->[0]
4069 maybe_split_brain_save $maintview, $r, "pseudomerge";
4071 progress "Made pseudo-merge of $i_arch_v->[0] into dgit view.";
4075 sub plain_overwrite_pseudomerge ($$$) {
4076 my ($clogp, $head, $archive_hash) = @_;
4078 printdebug "plain_overwrite_pseudomerge...";
4080 my $i_arch_v = pseudomerge_version_check($clogp, $archive_hash);
4082 return $head if is_fast_fwd $archive_hash, $head;
4084 my $m = "Declare fast forward from $i_arch_v->[0]";
4086 my $r = pseudomerge_make_commit
4087 $clogp, $head, $archive_hash, $i_arch_v,
4090 runcmd git_update_ref_cmd $m, 'HEAD', $r, $head;
4092 progress "Make pseudo-merge of $i_arch_v->[0] into your HEAD.";
4096 sub push_parse_changelog ($) {
4099 my $clogp = Dpkg::Control::Hash->new();
4100 $clogp->load($clogpfn) or die;
4102 my $clogpackage = getfield $clogp, 'Source';
4103 $package //= $clogpackage;
4104 fail "-p specified $package but changelog specified $clogpackage"
4105 unless $package eq $clogpackage;
4106 my $cversion = getfield $clogp, 'Version';
4108 if (!$we_are_initiator) {
4109 # rpush initiator can't do this because it doesn't have $isuite yet
4110 my $tag = debiantag($cversion, access_nomdistro);
4111 runcmd @git, qw(check-ref-format), $tag;
4114 my $dscfn = dscfn($cversion);
4116 return ($clogp, $cversion, $dscfn);
4119 sub push_parse_dsc ($$$) {
4120 my ($dscfn,$dscfnwhat, $cversion) = @_;
4121 $dsc = parsecontrol($dscfn,$dscfnwhat);
4122 my $dversion = getfield $dsc, 'Version';
4123 my $dscpackage = getfield $dsc, 'Source';
4124 ($dscpackage eq $package && $dversion eq $cversion) or
4125 fail "$dscfn is for $dscpackage $dversion".
4126 " but debian/changelog is for $package $cversion";
4129 sub push_tagwants ($$$$) {
4130 my ($cversion, $dgithead, $maintviewhead, $tfbase) = @_;
4133 TagFn => \&debiantag,
4138 if (defined $maintviewhead) {
4140 TagFn => \&debiantag_maintview,
4141 Objid => $maintviewhead,
4142 TfSuffix => '-maintview',
4145 } elsif ($dodep14tag eq 'no' ? 0
4146 : $dodep14tag eq 'want' ? access_cfg_tagformats_can_splitbrain
4147 : $dodep14tag eq 'always'
4148 ? (access_cfg_tagformats_can_splitbrain or fail <<END)
4149 --dep14tag-always (or equivalent in config) means server must support
4150 both "new" and "maint" tag formats, but config says it doesn't.
4152 : die "$dodep14tag ?") {
4154 TagFn => \&debiantag_maintview,
4156 TfSuffix => '-dgit',
4160 foreach my $tw (@tagwants) {
4161 $tw->{Tag} = $tw->{TagFn}($cversion, access_nomdistro);
4162 $tw->{Tfn} = sub { $tfbase.$tw->{TfSuffix}.$_[0]; };
4164 printdebug 'push_tagwants: ', Dumper(\@_, \@tagwants);
4168 sub push_mktags ($$ $$ $) {
4170 $changesfile,$changesfilewhat,
4173 die unless $tagwants->[0]{View} eq 'dgit';
4175 my $declaredistro = access_nomdistro();
4176 my $reader_giturl = do { local $access_forpush=0; access_giturl(); };
4177 $dsc->{$ourdscfield[0]} = join " ",
4178 $tagwants->[0]{Objid}, $declaredistro, $tagwants->[0]{Tag},
4180 $dsc->save("$dscfn.tmp") or die $!;
4182 my $changes = parsecontrol($changesfile,$changesfilewhat);
4183 foreach my $field (qw(Source Distribution Version)) {
4184 $changes->{$field} eq $clogp->{$field} or
4185 fail "changes field $field \`$changes->{$field}'".
4186 " does not match changelog \`$clogp->{$field}'";
4189 my $cversion = getfield $clogp, 'Version';
4190 my $clogsuite = getfield $clogp, 'Distribution';
4192 # We make the git tag by hand because (a) that makes it easier
4193 # to control the "tagger" (b) we can do remote signing
4194 my $authline = clogp_authline $clogp;
4195 my $delibs = join(" ", "",@deliberatelies);
4199 my $tfn = $tw->{Tfn};
4200 my $head = $tw->{Objid};
4201 my $tag = $tw->{Tag};
4203 open TO, '>', $tfn->('.tmp') or die $!;
4204 print TO <<END or die $!;
4211 if ($tw->{View} eq 'dgit') {
4212 print TO <<END or die $!;
4213 $package release $cversion for $clogsuite ($csuite) [dgit]
4214 [dgit distro=$declaredistro$delibs]
4216 foreach my $ref (sort keys %previously) {
4217 print TO <<END or die $!;
4218 [dgit previously:$ref=$previously{$ref}]
4221 } elsif ($tw->{View} eq 'maint') {
4222 print TO <<END or die $!;
4223 $package release $cversion for $clogsuite ($csuite)
4224 (maintainer view tag generated by dgit --quilt=$quilt_mode)
4227 die Dumper($tw)."?";
4232 my $tagobjfn = $tfn->('.tmp');
4234 if (!defined $keyid) {
4235 $keyid = access_cfg('keyid','RETURN-UNDEF');
4237 if (!defined $keyid) {
4238 $keyid = getfield $clogp, 'Maintainer';
4240 unlink $tfn->('.tmp.asc') or $!==&ENOENT or die $!;
4241 my @sign_cmd = (@gpg, qw(--detach-sign --armor));
4242 push @sign_cmd, qw(-u),$keyid if defined $keyid;
4243 push @sign_cmd, $tfn->('.tmp');
4244 runcmd_ordryrun @sign_cmd;
4246 $tagobjfn = $tfn->('.signed.tmp');
4247 runcmd shell_cmd "exec >$tagobjfn", qw(cat --),
4248 $tfn->('.tmp'), $tfn->('.tmp.asc');
4254 my @r = map { $mktag->($_); } @$tagwants;
4258 sub sign_changes ($) {
4259 my ($changesfile) = @_;
4261 my @debsign_cmd = @debsign;
4262 push @debsign_cmd, "-k$keyid" if defined $keyid;
4263 push @debsign_cmd, "-p$gpg[0]" if $gpg[0] ne 'gpg';
4264 push @debsign_cmd, $changesfile;
4265 runcmd_ordryrun @debsign_cmd;
4270 printdebug "actually entering push\n";
4272 supplementary_message(<<'END');
4273 Push failed, while checking state of the archive.
4274 You can retry the push, after fixing the problem, if you like.
4276 if (check_for_git()) {
4279 my $archive_hash = fetch_from_archive();
4280 if (!$archive_hash) {
4282 fail "package appears to be new in this suite;".
4283 " if this is intentional, use --new";
4286 supplementary_message(<<'END');
4287 Push failed, while preparing your push.
4288 You can retry the push, after fixing the problem, if you like.
4291 need_tagformat 'new', "quilt mode $quilt_mode"
4292 if quiltmode_splitbrain;
4296 access_giturl(); # check that success is vaguely likely
4297 rpush_handle_protovsn_bothends() if $we_are_initiator;
4300 my $clogpfn = dgit_privdir()."/changelog.822.tmp";
4301 runcmd shell_cmd "exec >$clogpfn", qw(dpkg-parsechangelog);
4303 responder_send_file('parsed-changelog', $clogpfn);
4305 my ($clogp, $cversion, $dscfn) =
4306 push_parse_changelog("$clogpfn");
4308 my $dscpath = "$buildproductsdir/$dscfn";
4309 stat_exists $dscpath or
4310 fail "looked for .dsc $dscpath, but $!;".
4311 " maybe you forgot to build";
4313 responder_send_file('dsc', $dscpath);
4315 push_parse_dsc($dscpath, $dscfn, $cversion);
4317 my $format = getfield $dsc, 'Format';
4318 printdebug "format $format\n";
4320 my $symref = git_get_symref();
4321 my $actualhead = git_rev_parse('HEAD');
4323 if (branch_is_gdr_unstitched_ff($symref, $actualhead, $archive_hash)) {
4324 runcmd_ordryrun_local @git_debrebase, 'stitch';
4325 $actualhead = git_rev_parse('HEAD');
4328 my $dgithead = $actualhead;
4329 my $maintviewhead = undef;
4331 my $upstreamversion = upstreamversion $clogp->{Version};
4333 if (madformat_wantfixup($format)) {
4334 # user might have not used dgit build, so maybe do this now:
4335 if (quiltmode_splitbrain()) {
4336 changedir $playground;
4337 quilt_make_fake_dsc($upstreamversion);
4339 ($dgithead, $cachekey) =
4340 quilt_check_splitbrain_cache($actualhead, $upstreamversion);
4342 "--quilt=$quilt_mode but no cached dgit view:
4343 perhaps HEAD changed since dgit build[-source] ?";
4345 $dgithead = splitbrain_pseudomerge($clogp,
4346 $actualhead, $dgithead,
4348 $maintviewhead = $actualhead;
4350 prep_ud(); # so _only_subdir() works, below
4352 commit_quilty_patch();
4356 if (defined $overwrite_version && !defined $maintviewhead
4358 $dgithead = plain_overwrite_pseudomerge($clogp,
4366 if ($archive_hash) {
4367 if (is_fast_fwd($archive_hash, $dgithead)) {
4369 } elsif (deliberately_not_fast_forward) {
4372 fail "dgit push: HEAD is not a descendant".
4373 " of the archive's version.\n".
4374 "To overwrite the archive's contents,".
4375 " pass --overwrite[=VERSION].\n".
4376 "To rewind history, if permitted by the archive,".
4377 " use --deliberately-not-fast-forward.";
4381 changedir $playground;
4382 progress "checking that $dscfn corresponds to HEAD";
4383 runcmd qw(dpkg-source -x --),
4384 $dscpath =~ m#^/# ? $dscpath : "$maindir/$dscpath";
4385 my ($tree,$dir) = mktree_in_ud_from_only_subdir("source package");
4386 check_for_vendor_patches() if madformat($dsc->{format});
4388 my @diffcmd = (@git, qw(diff --quiet), $tree, $dgithead);
4389 debugcmd "+",@diffcmd;
4391 my $r = system @diffcmd;
4394 my $referent = $split_brain ? $dgithead : 'HEAD';
4395 my $diffs = cmdoutput @git, qw(diff --stat), $tree, $dgithead;
4398 my $raw = cmdoutput @git,
4399 qw(diff --no-renames -z -r --raw), $tree, $dgithead;
4401 foreach (split /\0/, $raw) {
4402 if (defined $changed) {
4403 push @mode_changes, "$changed: $_\n" if $changed;
4406 } elsif (m/^:0+ 0+ /) {
4408 } elsif (m/^:(?:10*)?(\d+) (?:10*)?(\d+) /) {
4409 $changed = "Mode change from $1 to $2"
4414 if (@mode_changes) {
4415 fail <<END.(join '', @mode_changes).<<END;
4416 HEAD specifies a different tree to $dscfn:
4419 There is a problem with your source tree (see dgit(7) for some hints).
4420 To see a full diff, run git diff $tree $referent
4425 HEAD specifies a different tree to $dscfn:
4427 Perhaps you forgot to build. Or perhaps there is a problem with your
4428 source tree (see dgit(7) for some hints). To see a full diff, run
4429 git diff $tree $referent
4435 if (!$changesfile) {
4436 my $pat = changespat $cversion;
4437 my @cs = glob "$buildproductsdir/$pat";
4438 fail "failed to find unique changes file".
4439 " (looked for $pat in $buildproductsdir);".
4440 " perhaps you need to use dgit -C"
4442 ($changesfile) = @cs;
4444 $changesfile = "$buildproductsdir/$changesfile";
4447 # Check that changes and .dsc agree enough
4448 $changesfile =~ m{[^/]*$};
4449 my $changes = parsecontrol($changesfile,$&);
4450 files_compare_inputs($dsc, $changes)
4451 unless forceing [qw(dsc-changes-mismatch)];
4453 # Check whether this is a source only upload
4454 my $hasdebs = $changes->{Files} =~ m{\.deb$}m;
4455 my $sourconlypolicy = access_cfg 'source-only-uploads';
4456 if ($sourconlypolicy eq 'ok') {
4457 } elsif ($sourconlypolicy eq 'always') {
4458 forceable_fail [qw(uploading-binaries)],
4459 "uploading binaries, although distroy policy is source only"
4461 } elsif ($sourconlypolicy eq 'never') {
4462 forceable_fail [qw(uploading-source-only)],
4463 "source-only upload, although distroy policy requires .debs"
4465 } elsif ($sourconlypolicy eq 'not-wholly-new') {
4466 forceable_fail [qw(uploading-source-only)],
4467 "source-only upload, even though package is entirely NEW"
4470 && !archive_query('package_not_wholly_new', $package);
4472 badcfg "unknown source-only-uploads policy \`$sourceonlypolicy'";
4475 # Perhaps adjust .dsc to contain right set of origs
4476 changes_update_origs_from_dsc($dsc, $changes, $upstreamversion,
4478 unless forceing [qw(changes-origs-exactly)];
4480 # Checks complete, we're going to try and go ahead:
4482 responder_send_file('changes',$changesfile);
4483 responder_send_command("param head $dgithead");
4484 responder_send_command("param csuite $csuite");
4485 responder_send_command("param isuite $isuite");
4486 responder_send_command("param tagformat $tagformat");
4487 if (defined $maintviewhead) {
4488 die unless ($protovsn//4) >= 4;
4489 responder_send_command("param maint-view $maintviewhead");
4492 # Perhaps send buildinfo(s) for signing
4493 my $changes_files = getfield $changes, 'Files';
4494 my @buildinfos = ($changes_files =~ m/ .* (\S+\.buildinfo)$/mg);
4495 foreach my $bi (@buildinfos) {
4496 responder_send_command("param buildinfo-filename $bi");
4497 responder_send_file('buildinfo', "$buildproductsdir/$bi");
4500 if (deliberately_not_fast_forward) {
4501 git_for_each_ref(lrfetchrefs, sub {
4502 my ($objid,$objtype,$lrfetchrefname,$reftail) = @_;
4503 my $rrefname= substr($lrfetchrefname, length(lrfetchrefs) + 1);
4504 responder_send_command("previously $rrefname=$objid");
4505 $previously{$rrefname} = $objid;
4509 my @tagwants = push_tagwants($cversion, $dgithead, $maintviewhead,
4510 dgit_privdir()."/tag");
4513 supplementary_message(<<'END');
4514 Push failed, while signing the tag.
4515 You can retry the push, after fixing the problem, if you like.
4517 # If we manage to sign but fail to record it anywhere, it's fine.
4518 if ($we_are_responder) {
4519 @tagobjfns = map { $_->{Tfn}('.signed-tmp') } @tagwants;
4520 responder_receive_files('signed-tag', @tagobjfns);
4522 @tagobjfns = push_mktags($clogp,$dscpath,
4523 $changesfile,$changesfile,
4526 supplementary_message(<<'END');
4527 Push failed, *after* signing the tag.
4528 If you want to try again, you should use a new version number.
4531 pairwise { $a->{TagObjFn} = $b } @tagwants, @tagobjfns;
4533 foreach my $tw (@tagwants) {
4534 my $tag = $tw->{Tag};
4535 my $tagobjfn = $tw->{TagObjFn};
4537 cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
4538 runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
4539 runcmd_ordryrun_local
4540 @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
4543 supplementary_message(<<'END');
4544 Push failed, while updating the remote git repository - see messages above.
4545 If you want to try again, you should use a new version number.
4547 if (!check_for_git()) {
4548 create_remote_git_repo();
4551 my @pushrefs = $forceflag.$dgithead.":".rrref();
4552 foreach my $tw (@tagwants) {
4553 push @pushrefs, $forceflag."refs/tags/$tw->{Tag}";
4556 runcmd_ordryrun @git,
4557 qw(-c push.followTags=false push), access_giturl(), @pushrefs;
4558 runcmd_ordryrun git_update_ref_cmd 'dgit push', lrref(), $dgithead;
4560 supplementary_message(<<'END');
4561 Push failed, while obtaining signatures on the .changes and .dsc.
4562 If it was just that the signature failed, you may try again by using
4563 debsign by hand to sign the changes
4565 and then dput to complete the upload.
4566 If you need to change the package, you must use a new version number.
4568 if ($we_are_responder) {
4569 my $dryrunsuffix = act_local() ? "" : ".tmp";
4570 my @rfiles = ($dscpath, $changesfile);
4571 push @rfiles, map { "$buildproductsdir/$_" } @buildinfos;
4572 responder_receive_files('signed-dsc-changes',
4573 map { "$_$dryrunsuffix" } @rfiles);
4576 rename "$dscpath.tmp",$dscpath or die "$dscfn $!";
4578 progress "[new .dsc left in $dscpath.tmp]";
4580 sign_changes $changesfile;
4583 supplementary_message(<<END);
4584 Push failed, while uploading package(s) to the archive server.
4585 You can retry the upload of exactly these same files with dput of:
4587 If that .changes file is broken, you will need to use a new version
4588 number for your next attempt at the upload.
4590 my $host = access_cfg('upload-host','RETURN-UNDEF');
4591 my @hostarg = defined($host) ? ($host,) : ();
4592 runcmd_ordryrun @dput, @hostarg, $changesfile;
4593 printdone "pushed and uploaded $cversion";
4595 supplementary_message('');
4596 responder_send_command("complete");
4600 not_necessarily_a_tree();
4605 badusage "-p is not allowed with clone; specify as argument instead"
4606 if defined $package;
4609 } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
4610 ($package,$isuite) = @ARGV;
4611 } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
4612 ($package,$dstdir) = @ARGV;
4613 } elsif (@ARGV==3) {
4614 ($package,$isuite,$dstdir) = @ARGV;
4616 badusage "incorrect arguments to dgit clone";
4620 $dstdir ||= "$package";
4621 if (stat_exists $dstdir) {
4622 fail "$dstdir already exists";
4626 if ($rmonerror && !$dryrun_level) {
4627 $cwd_remove= getcwd();
4629 return unless defined $cwd_remove;
4630 if (!chdir "$cwd_remove") {
4631 return if $!==&ENOENT;
4632 die "chdir $cwd_remove: $!";
4634 printdebug "clone rmonerror removing $dstdir\n";
4636 rmtree($dstdir) or die "remove $dstdir: $!\n";
4637 } elsif (grep { $! == $_ }
4638 (ENOENT, ENOTDIR, EACCES, EPERM, ELOOP)) {
4640 print STDERR "check whether to remove $dstdir: $!\n";
4646 $cwd_remove = undef;
4649 sub branchsuite () {
4650 my $branch = git_get_symref();
4651 if (defined $branch && $branch =~ m#$lbranch_re#o) {
4658 sub package_from_d_control () {
4659 if (!defined $package) {
4660 my $sourcep = parsecontrol('debian/control','debian/control');
4661 $package = getfield $sourcep, 'Source';
4665 sub fetchpullargs () {
4666 package_from_d_control();
4668 $isuite = branchsuite();
4670 my $clogp = parsechangelog();
4671 my $clogsuite = getfield $clogp, 'Distribution';
4672 $isuite= $clogsuite if $clogsuite ne 'UNRELEASED';
4674 } elsif (@ARGV==1) {
4677 badusage "incorrect arguments to dgit fetch or dgit pull";
4691 if (quiltmode_splitbrain()) {
4692 my ($format, $fopts) = get_source_format();
4693 madformat($format) and fail <<END
4694 dgit pull not yet supported in split view mode (--quilt=$quilt_mode)
4702 package_from_d_control();
4703 @ARGV==1 or badusage "dgit checkout needs a suite argument";
4707 foreach my $canon (qw(0 1)) {
4712 canonicalise_suite();
4714 if (length git_get_ref lref()) {
4715 # local branch already exists, yay
4718 if (!length git_get_ref lrref()) {
4726 runcmd (@git, qw(update-ref), lref(), lrref(), '');
4729 local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
4730 "dgit checkout $isuite";
4731 runcmd (@git, qw(checkout), lref());
4734 sub cmd_update_vcs_git () {
4736 if (@ARGV==0 || $ARGV[0] =~ m/^-/) {
4737 ($specsuite,) = split /\;/, cfg 'dgit.vcs-git.suites';
4739 ($specsuite) = (@ARGV);
4744 if ($ARGV[0] eq '-') {
4746 } elsif ($ARGV[0] eq '-') {
4751 package_from_d_control();
4753 if ($specsuite eq '.') {
4754 $ctrl = parsecontrol 'debian/control', 'debian/control';
4756 $isuite = $specsuite;
4760 my $url = getfield $ctrl, 'Vcs-Git';
4763 my $orgurl = cfg 'remote.vcs-git.url', 'RETURN-UNDEF';
4764 if (!defined $orgurl) {
4765 print STDERR "setting up vcs-git: $url\n";
4766 @cmd = (@git, qw(remote add vcs-git), $url);
4767 } elsif ($orgurl eq $url) {
4768 print STDERR "vcs git already configured: $url\n";
4770 print STDERR "changing vcs-git url to: $url\n";
4771 @cmd = (@git, qw(remote set-url vcs-git), $url);
4773 runcmd_ordryrun_local @cmd;
4775 print "fetching (@ARGV)\n";
4776 runcmd_ordryrun_local @git, qw(fetch vcs-git), @ARGV;
4782 build_or_push_prep_early();
4787 } elsif (@ARGV==1) {
4788 ($specsuite) = (@ARGV);
4790 badusage "incorrect arguments to dgit $subcommand";
4793 local ($package) = $existing_package; # this is a hack
4794 canonicalise_suite();
4796 canonicalise_suite();
4798 if (defined $specsuite &&
4799 $specsuite ne $isuite &&
4800 $specsuite ne $csuite) {
4801 fail "dgit $subcommand: changelog specifies $isuite ($csuite)".
4802 " but command line specifies $specsuite";
4811 sub cmd_push_source {
4814 my $changes = parsecontrol("$buildproductsdir/$changesfile",
4815 "source changes file");
4816 unless (test_source_only_changes($changes)) {
4817 fail "user-specified changes file is not source-only";
4820 # Building a source package is very fast, so just do it
4821 build_source_for_push();
4826 #---------- remote commands' implementation ----------
4828 sub pre_remote_push_build_host {
4829 my ($nrargs) = shift @ARGV;
4830 my (@rargs) = @ARGV[0..$nrargs-1];
4831 @ARGV = @ARGV[$nrargs..$#ARGV];
4833 my ($dir,$vsnwant) = @rargs;
4834 # vsnwant is a comma-separated list; we report which we have
4835 # chosen in our ready response (so other end can tell if they
4838 $we_are_responder = 1;
4839 $us .= " (build host)";
4841 open PI, "<&STDIN" or die $!;
4842 open STDIN, "/dev/null" or die $!;
4843 open PO, ">&STDOUT" or die $!;
4845 open STDOUT, ">&STDERR" or die $!;
4849 ($protovsn) = grep {
4850 $vsnwant =~ m{^(?:.*,)?$_(?:,.*)?$}
4851 } @rpushprotovsn_support;
4853 fail "build host has dgit rpush protocol versions ".
4854 (join ",", @rpushprotovsn_support).
4855 " but invocation host has $vsnwant"
4856 unless defined $protovsn;
4860 sub cmd_remote_push_build_host {
4861 responder_send_command("dgit-remote-push-ready $protovsn");
4865 sub pre_remote_push_responder { pre_remote_push_build_host(); }
4866 sub cmd_remote_push_responder { cmd_remote_push_build_host(); }
4867 # ... for compatibility with proto vsn.1 dgit (just so that user gets
4868 # a good error message)
4870 sub rpush_handle_protovsn_bothends () {
4871 if ($protovsn < 4) {
4872 need_tagformat 'old', "rpush negotiated protocol $protovsn";
4881 my $report = i_child_report();
4882 if (defined $report) {
4883 printdebug "($report)\n";
4884 } elsif ($i_child_pid) {
4885 printdebug "(killing build host child $i_child_pid)\n";
4886 kill 15, $i_child_pid;
4888 if (defined $i_tmp && !defined $initiator_tempdir) {
4890 eval { rmtree $i_tmp; };
4895 return unless forkcheck_mainprocess();
4900 my ($base,$selector,@args) = @_;
4901 $selector =~ s/\-/_/g;
4902 { no strict qw(refs); &{"${base}_${selector}"}(@args); }
4906 not_necessarily_a_tree();
4911 if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
4919 push @rargs, join ",", @rpushprotovsn_support;
4922 push @rdgit, @ropts;
4923 push @rdgit, qw(remote-push-build-host), (scalar @rargs), @rargs;
4925 my @cmd = (@ssh, $host, shellquote @rdgit);
4928 $we_are_initiator=1;
4930 if (defined $initiator_tempdir) {
4931 rmtree $initiator_tempdir;
4932 mkdir $initiator_tempdir, 0700 or die "$initiator_tempdir: $!";
4933 $i_tmp = $initiator_tempdir;
4937 $i_child_pid = open2(\*RO, \*RI, @cmd);
4939 ($protovsn) = initiator_expect { m/^dgit-remote-push-ready (\S+)/ };
4940 die "$protovsn ?" unless grep { $_ eq $protovsn } @rpushprotovsn_support;
4941 $supplementary_message = '' unless $protovsn >= 3;
4944 my ($icmd,$iargs) = initiator_expect {
4945 m/^(\S+)(?: (.*))?$/;
4948 i_method "i_resp", $icmd, $iargs;
4952 sub i_resp_progress ($) {
4954 my $msg = protocol_read_bytes \*RO, $rhs;
4958 sub i_resp_supplementary_message ($) {
4960 $supplementary_message = protocol_read_bytes \*RO, $rhs;
4963 sub i_resp_complete {
4964 my $pid = $i_child_pid;
4965 $i_child_pid = undef; # prevents killing some other process with same pid
4966 printdebug "waiting for build host child $pid...\n";
4967 my $got = waitpid $pid, 0;
4968 die $! unless $got == $pid;
4969 die "build host child failed $?" if $?;
4972 printdebug "all done\n";
4976 sub i_resp_file ($) {
4978 my $localname = i_method "i_localname", $keyword;
4979 my $localpath = "$i_tmp/$localname";
4980 stat_exists $localpath and
4981 badproto \*RO, "file $keyword ($localpath) twice";
4982 protocol_receive_file \*RO, $localpath;
4983 i_method "i_file", $keyword;
4988 sub i_resp_param ($) {
4989 $_[0] =~ m/^(\S+) (.*)$/ or badproto \*RO, "bad param spec";
4993 sub i_resp_previously ($) {
4994 $_[0] =~ m#^(refs/tags/\S+)=(\w+)$#
4995 or badproto \*RO, "bad previously spec";
4996 my $r = system qw(git check-ref-format), $1;
4997 die "bad previously ref spec ($r)" if $r;
4998 $previously{$1} = $2;
5003 sub i_resp_want ($) {
5005 die "$keyword ?" if $i_wanted{$keyword}++;
5007 defined $i_param{'csuite'} or badproto \*RO, "premature desire, no csuite";
5008 $isuite = $i_param{'isuite'} // $i_param{'csuite'};
5009 die unless $isuite =~ m/^$suite_re$/;
5012 rpush_handle_protovsn_bothends();
5014 fail "rpush negotiated protocol version $protovsn".
5015 " which does not support quilt mode $quilt_mode"
5016 if quiltmode_splitbrain;
5018 my @localpaths = i_method "i_want", $keyword;
5019 printdebug "[[ $keyword @localpaths\n";
5020 foreach my $localpath (@localpaths) {
5021 protocol_send_file \*RI, $localpath;
5023 print RI "files-end\n" or die $!;
5026 our ($i_clogp, $i_version, $i_dscfn, $i_changesfn, @i_buildinfos);
5028 sub i_localname_parsed_changelog {
5029 return "remote-changelog.822";
5031 sub i_file_parsed_changelog {
5032 ($i_clogp, $i_version, $i_dscfn) =
5033 push_parse_changelog "$i_tmp/remote-changelog.822";
5034 die if $i_dscfn =~ m#/|^\W#;
5037 sub i_localname_dsc {
5038 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
5043 sub i_localname_buildinfo ($) {
5044 my $bi = $i_param{'buildinfo-filename'};
5045 defined $bi or badproto \*RO, "buildinfo before filename";
5046 defined $i_changesfn or badproto \*RO, "buildinfo before changes";
5047 $bi =~ m{^\Q$package\E_[!-.0-~]*\.buildinfo$}s
5048 or badproto \*RO, "improper buildinfo filename";
5051 sub i_file_buildinfo {
5052 my $bi = $i_param{'buildinfo-filename'};
5053 my $bd = parsecontrol "$i_tmp/$bi", $bi;
5054 my $ch = parsecontrol "$i_tmp/$i_changesfn", 'changes';
5055 if (!forceing [qw(buildinfo-changes-mismatch)]) {
5056 files_compare_inputs($bd, $ch);
5057 (getfield $bd, $_) eq (getfield $ch, $_) or
5058 fail "buildinfo mismatch $_"
5059 foreach qw(Source Version);
5060 !defined $bd->{$_} or
5061 fail "buildinfo contains $_"
5062 foreach qw(Changes Changed-by Distribution);
5064 push @i_buildinfos, $bi;
5065 delete $i_param{'buildinfo-filename'};
5068 sub i_localname_changes {
5069 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
5070 $i_changesfn = $i_dscfn;
5071 $i_changesfn =~ s/\.dsc$/_dgit.changes/ or die;
5072 return $i_changesfn;
5074 sub i_file_changes { }
5076 sub i_want_signed_tag {
5077 printdebug Dumper(\%i_param, $i_dscfn);
5078 defined $i_param{'head'} && defined $i_dscfn && defined $i_clogp
5079 && defined $i_param{'csuite'}
5080 or badproto \*RO, "premature desire for signed-tag";
5081 my $head = $i_param{'head'};
5082 die if $head =~ m/[^0-9a-f]/ || $head !~ m/^../;
5084 my $maintview = $i_param{'maint-view'};
5085 die if defined $maintview && $maintview =~ m/[^0-9a-f]/;
5088 if ($protovsn >= 4) {
5089 my $p = $i_param{'tagformat'} // '<undef>';
5091 or badproto \*RO, "tag format mismatch: $p vs. $tagformat";
5094 die unless $i_param{'csuite'} =~ m/^$suite_re$/;
5096 push_parse_dsc $i_dscfn, 'remote dsc', $i_version;
5098 my @tagwants = push_tagwants $i_version, $head, $maintview, "tag";
5101 push_mktags $i_clogp, $i_dscfn,
5102 $i_changesfn, 'remote changes',
5106 sub i_want_signed_dsc_changes {
5107 rename "$i_dscfn.tmp","$i_dscfn" or die "$i_dscfn $!";
5108 sign_changes $i_changesfn;
5109 return ($i_dscfn, $i_changesfn, @i_buildinfos);
5112 #---------- building etc. ----------
5118 #----- `3.0 (quilt)' handling -----
5120 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
5122 sub quiltify_dpkg_commit ($$$;$) {
5123 my ($patchname,$author,$msg, $xinfo) = @_;
5126 mkpath '.git/dgit'; # we are in playtree
5127 my $descfn = ".git/dgit/quilt-description.tmp";
5128 open O, '>', $descfn or die "$descfn: $!";
5129 $msg =~ s/\n+/\n\n/;
5130 print O <<END or die $!;
5132 ${xinfo}Subject: $msg
5139 local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
5140 local $ENV{'VISUAL'} = $ENV{'EDITOR'};
5141 local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
5142 runcmd @dpkgsource, qw(--commit --include-removal .), $patchname;
5146 sub quiltify_trees_differ ($$;$$$) {
5147 my ($x,$y,$finegrained,$ignorenamesr,$unrepres) = @_;
5148 # returns true iff the two tree objects differ other than in debian/
5149 # with $finegrained,
5150 # returns bitmask 01 - differ in upstream files except .gitignore
5151 # 02 - differ in .gitignore
5152 # if $ignorenamesr is defined, $ingorenamesr->{$fn}
5153 # is set for each modified .gitignore filename $fn
5154 # if $unrepres is defined, array ref to which is appeneded
5155 # a list of unrepresentable changes (removals of upstream files
5158 my @cmd = (@git, qw(diff-tree -z --no-renames));
5159 push @cmd, qw(--name-only) unless $unrepres;
5160 push @cmd, qw(-r) if $finegrained || $unrepres;
5162 my $diffs= cmdoutput @cmd;
5165 foreach my $f (split /\0/, $diffs) {
5166 if ($unrepres && !@lmodes) {
5167 @lmodes = $f =~ m/^\:(\w+) (\w+) \w+ \w+ / or die "$_ ?";
5170 my ($oldmode,$newmode) = @lmodes;
5173 next if $f =~ m#^debian(?:/.*)?$#s;
5177 die "not a plain file or symlink\n"
5178 unless $newmode =~ m/^(?:10|12)\d{4}$/ ||
5179 $oldmode =~ m/^(?:10|12)\d{4}$/;
5180 if ($oldmode =~ m/[^0]/ &&
5181 $newmode =~ m/[^0]/) {
5182 # both old and new files exist
5183 die "mode or type changed\n" if $oldmode ne $newmode;
5184 die "modified symlink\n" unless $newmode =~ m/^10/;
5185 } elsif ($oldmode =~ m/[^0]/) {
5187 die "deletion of symlink\n"
5188 unless $oldmode =~ m/^10/;
5191 die "creation with non-default mode\n"
5192 unless $newmode =~ m/^100644$/ or
5193 $newmode =~ m/^120000$/;
5197 local $/="\n"; chomp $@;
5198 push @$unrepres, [ $f, "$@ ($oldmode->$newmode)" ];
5202 my $isignore = $f =~ m#^(?:.*/)?.gitignore$#s;
5203 $r |= $isignore ? 02 : 01;
5204 $ignorenamesr->{$f}=1 if $ignorenamesr && $isignore;
5206 printdebug "quiltify_trees_differ $x $y => $r\n";
5210 sub quiltify_tree_sentinelfiles ($) {
5211 # lists the `sentinel' files present in the tree
5213 my $r = cmdoutput @git, qw(ls-tree --name-only), $x,
5214 qw(-- debian/rules debian/control);
5219 sub quiltify_splitbrain_needed () {
5220 if (!$split_brain) {
5221 progress "dgit view: changes are required...";
5222 runcmd @git, qw(checkout -q -b dgit-view);
5227 sub quiltify_splitbrain ($$$$$$$) {
5228 my ($clogp, $unapplied, $headref, $oldtiptree, $diffbits,
5229 $editedignores, $cachekey) = @_;
5230 my $gitignore_special = 1;
5231 if ($quilt_mode !~ m/gbp|dpm/) {
5232 # treat .gitignore just like any other upstream file
5233 $diffbits = { %$diffbits };
5234 $_ = !!$_ foreach values %$diffbits;
5235 $gitignore_special = 0;
5237 # We would like any commits we generate to be reproducible
5238 my @authline = clogp_authline($clogp);
5239 local $ENV{GIT_COMMITTER_NAME} = $authline[0];
5240 local $ENV{GIT_COMMITTER_EMAIL} = $authline[1];
5241 local $ENV{GIT_COMMITTER_DATE} = $authline[2];
5242 local $ENV{GIT_AUTHOR_NAME} = $authline[0];
5243 local $ENV{GIT_AUTHOR_EMAIL} = $authline[1];
5244 local $ENV{GIT_AUTHOR_DATE} = $authline[2];
5246 my $fulldiffhint = sub {
5248 my $cmd = "git diff $x $y -- :/ ':!debian'";
5249 $cmd .= " ':!/.gitignore' ':!*/.gitignore'" if $gitignore_special;
5250 return "\nFor full diff showing the problem(s), type:\n $cmd\n";
5253 if ($quilt_mode =~ m/gbp|unapplied/ &&
5254 ($diffbits->{O2H} & 01)) {
5256 "--quilt=$quilt_mode specified, implying patches-unapplied git tree\n".
5257 " but git tree differs from orig in upstream files.";
5258 $msg .= $fulldiffhint->($unapplied, 'HEAD');
5259 if (!stat_exists "debian/patches") {
5261 "\n ... debian/patches is missing; perhaps this is a patch queue branch?";
5265 if ($quilt_mode =~ m/dpm/ &&
5266 ($diffbits->{H2A} & 01)) {
5267 fail <<END. $fulldiffhint->($oldtiptree,'HEAD');
5268 --quilt=$quilt_mode specified, implying patches-applied git tree
5269 but git tree differs from result of applying debian/patches to upstream
5272 if ($quilt_mode =~ m/gbp|unapplied/ &&
5273 ($diffbits->{O2A} & 01)) { # some patches
5274 quiltify_splitbrain_needed();
5275 progress "dgit view: creating patches-applied version using gbp pq";
5276 runcmd shell_cmd 'exec >/dev/null', gbp_pq, qw(import);
5277 # gbp pq import creates a fresh branch; push back to dgit-view
5278 runcmd @git, qw(update-ref refs/heads/dgit-view HEAD);
5279 runcmd @git, qw(checkout -q dgit-view);
5281 if ($quilt_mode =~ m/gbp|dpm/ &&
5282 ($diffbits->{O2A} & 02)) {
5284 --quilt=$quilt_mode specified, implying that HEAD is for use with a
5285 tool which does not create patches for changes to upstream
5286 .gitignores: but, such patches exist in debian/patches.
5289 if (($diffbits->{O2H} & 02) && # user has modified .gitignore
5290 !($diffbits->{O2A} & 02)) { # patches do not change .gitignore
5291 quiltify_splitbrain_needed();
5292 progress "dgit view: creating patch to represent .gitignore changes";
5293 ensuredir "debian/patches";
5294 my $gipatch = "debian/patches/auto-gitignore";
5295 open GIPATCH, ">>", "$gipatch" or die "$gipatch: $!";
5296 stat GIPATCH or die "$gipatch: $!";
5297 fail "$gipatch already exists; but want to create it".
5298 " to record .gitignore changes" if (stat _)[7];
5299 print GIPATCH <<END or die "$gipatch: $!";
5300 Subject: Update .gitignore from Debian packaging branch
5302 The Debian packaging git branch contains these updates to the upstream
5303 .gitignore file(s). This patch is autogenerated, to provide these
5304 updates to users of the official Debian archive view of the package.
5306 [dgit ($our_version) update-gitignore]
5309 close GIPATCH or die "$gipatch: $!";
5310 runcmd shell_cmd "exec >>$gipatch", @git, qw(diff),
5311 $unapplied, $headref, "--", sort keys %$editedignores;
5312 open SERIES, "+>>", "debian/patches/series" or die $!;
5313 defined seek SERIES, -1, 2 or $!==EINVAL or die $!;
5315 defined read SERIES, $newline, 1 or die $!;
5316 print SERIES "\n" or die $! unless $newline eq "\n";
5317 print SERIES "auto-gitignore\n" or die $!;
5318 close SERIES or die $!;
5319 runcmd @git, qw(add -- debian/patches/series), $gipatch;
5321 Commit patch to update .gitignore
5323 [dgit ($our_version) update-gitignore-quilt-fixup]
5327 my $dgitview = git_rev_parse 'HEAD';
5330 # When we no longer need to support squeeze, use --create-reflog
5332 ensuredir "$maindir_gitcommon/logs/refs/dgit-intern";
5333 my $makelogfh = new IO::File "$maindir_gitcommon/logs/refs/$splitbraincache", '>>'
5336 my $oldcache = git_get_ref "refs/$splitbraincache";
5337 if ($oldcache eq $dgitview) {
5338 my $tree = cmdoutput qw(git rev-parse), "$dgitview:";
5339 # git update-ref doesn't always update, in this case. *sigh*
5340 my $dummy = make_commit_text <<END;
5343 author Dgit <dgit\@example.com> 1000000000 +0000
5344 committer Dgit <dgit\@example.com> 1000000000 +0000
5346 Dummy commit - do not use
5348 runcmd @git, qw(update-ref -m), "dgit $our_version - dummy",
5349 "refs/$splitbraincache", $dummy;
5351 runcmd @git, qw(update-ref -m), $cachekey, "refs/$splitbraincache",
5354 changedir "$playground/work";
5356 my $saved = maybe_split_brain_save $headref, $dgitview, "converted";
5357 progress "dgit view: created ($saved)";
5360 sub quiltify ($$$$) {
5361 my ($clogp,$target,$oldtiptree,$failsuggestion) = @_;
5363 # Quilt patchification algorithm
5365 # We search backwards through the history of the main tree's HEAD
5366 # (T) looking for a start commit S whose tree object is identical
5367 # to to the patch tip tree (ie the tree corresponding to the
5368 # current dpkg-committed patch series). For these purposes
5369 # `identical' disregards anything in debian/ - this wrinkle is
5370 # necessary because dpkg-source treates debian/ specially.
5372 # We can only traverse edges where at most one of the ancestors'
5373 # trees differs (in changes outside in debian/). And we cannot
5374 # handle edges which change .pc/ or debian/patches. To avoid
5375 # going down a rathole we avoid traversing edges which introduce
5376 # debian/rules or debian/control. And we set a limit on the
5377 # number of edges we are willing to look at.
5379 # If we succeed, we walk forwards again. For each traversed edge
5380 # PC (with P parent, C child) (starting with P=S and ending with
5381 # C=T) to we do this:
5383 # - dpkg-source --commit with a patch name and message derived from C
5384 # After traversing PT, we git commit the changes which
5385 # should be contained within debian/patches.
5387 # The search for the path S..T is breadth-first. We maintain a
5388 # todo list containing search nodes. A search node identifies a
5389 # commit, and looks something like this:
5391 # Commit => $git_commit_id,
5392 # Child => $c, # or undef if P=T
5393 # Whynot => $reason_edge_PC_unsuitable, # in @nots only
5394 # Nontrivial => true iff $p..$c has relevant changes
5401 my %considered; # saves being exponential on some weird graphs
5403 my $t_sentinels = quiltify_tree_sentinelfiles $target;
5406 my ($search,$whynot) = @_;
5407 printdebug " search NOT $search->{Commit} $whynot\n";
5408 $search->{Whynot} = $whynot;
5409 push @nots, $search;
5410 no warnings qw(exiting);
5419 my $c = shift @todo;
5420 next if $considered{$c->{Commit}}++;
5422 $not->($c, "maximum search space exceeded") if --$max_work <= 0;
5424 printdebug "quiltify investigate $c->{Commit}\n";
5427 if (!quiltify_trees_differ $c->{Commit}, $oldtiptree) {
5428 printdebug " search finished hooray!\n";
5433 quiltify_nofix_bail " $c->{Commit}", " (tree object $oldtiptree)";
5434 if ($quilt_mode eq 'smash') {
5435 printdebug " search quitting smash\n";
5439 my $c_sentinels = quiltify_tree_sentinelfiles $c->{Commit};
5440 $not->($c, "has $c_sentinels not $t_sentinels")
5441 if $c_sentinels ne $t_sentinels;
5443 my $commitdata = cmdoutput @git, qw(cat-file commit), $c->{Commit};
5444 $commitdata =~ m/\n\n/;
5446 my @parents = ($commitdata =~ m/^parent (\w+)$/gm);
5447 @parents = map { { Commit => $_, Child => $c } } @parents;
5449 $not->($c, "root commit") if !@parents;
5451 foreach my $p (@parents) {
5452 $p->{Nontrivial}= quiltify_trees_differ $p->{Commit},$c->{Commit};
5454 my $ndiffers = grep { $_->{Nontrivial} } @parents;
5455 $not->($c, "merge ($ndiffers nontrivial parents)") if $ndiffers > 1;
5457 foreach my $p (@parents) {
5458 printdebug "considering C=$c->{Commit} P=$p->{Commit}\n";
5460 my @cmd= (@git, qw(diff-tree -r --name-only),
5461 $p->{Commit},$c->{Commit}, qw(-- debian/patches .pc));
5462 my $patchstackchange = cmdoutput @cmd;
5463 if (length $patchstackchange) {
5464 $patchstackchange =~ s/\n/,/g;
5465 $not->($p, "changed $patchstackchange");
5468 printdebug " search queue P=$p->{Commit} ",
5469 ($p->{Nontrivial} ? "NT" : "triv"),"\n";
5475 printdebug "quiltify want to smash\n";
5478 my $x = $_[0]{Commit};
5479 $x =~ s/(.*?[0-9a-z]{8})[0-9a-z]*$/$1/;
5482 my $reportnot = sub {
5484 my $s = $abbrev->($notp);
5485 my $c = $notp->{Child};
5486 $s .= "..".$abbrev->($c) if $c;
5487 $s .= ": ".$notp->{Whynot};
5490 if ($quilt_mode eq 'linear') {
5491 print STDERR "\n$us: error: quilt fixup cannot be linear. Stopped at:\n";
5492 foreach my $notp (@nots) {
5493 print STDERR "$us: ", $reportnot->($notp), "\n";
5495 print STDERR "$us: $_\n" foreach @$failsuggestion;
5497 "quilt history linearisation failed. Search \`quilt fixup' in dgit(7).\n".
5498 "Use dpkg-source --commit by hand; or, --quilt=smash for one ugly patch";
5499 } elsif ($quilt_mode eq 'smash') {
5500 } elsif ($quilt_mode eq 'auto') {
5501 progress "quilt fixup cannot be linear, smashing...";
5503 die "$quilt_mode ?";
5506 my $time = $ENV{'GIT_COMMITTER_DATE'} || time;
5507 $time =~ s/\s.*//; # trim timezone from GIT_COMMITTER_DATE
5509 my $msg = cmdoutput @git, qw(log), "-n$ncommits";
5511 quiltify_dpkg_commit "auto-$version-$target-$time",
5512 (getfield $clogp, 'Maintainer'),
5513 "Automatically generated patch ($clogp->{Version})\n".
5514 "Last (up to) $ncommits git changes, FYI:\n\n". $msg;
5518 progress "quiltify linearisation planning successful, executing...";
5520 for (my $p = $sref_S;
5521 my $c = $p->{Child};
5523 printdebug "quiltify traverse $p->{Commit}..$c->{Commit}\n";
5524 next unless $p->{Nontrivial};
5526 my $cc = $c->{Commit};
5528 my $commitdata = cmdoutput @git, qw(cat-file commit), $cc;
5529 $commitdata =~ m/\n\n/ or die "$c ?";
5532 $commitdata =~ m/^author (.*) \d+ [-+0-9]+$/m or die "$cc ?";
5535 my $commitdate = cmdoutput
5536 @git, qw(log -n1 --pretty=format:%aD), $cc;
5538 $msg =~ s/^(.*)\n*/$1\n/ or die "$cc $msg ?";
5540 my $strip_nls = sub { $msg =~ s/\n+$//; $msg .= "\n"; };
5547 my $gbp_check_suitable = sub {
5552 die "contains unexpected slashes\n" if m{//} || m{/$};
5553 die "contains leading punctuation\n" if m{^\W} || m{/\W};
5554 die "contains bad character(s)\n" if m{[^-a-z0-9_.+=~/]}i;
5555 die "is series file\n" if m{$series_filename_re}o;
5556 die "too long" if length > 200;
5558 return $_ unless $@;
5559 print STDERR "quiltifying commit $cc:".
5560 " ignoring/dropping Gbp-Pq $what: $@";
5564 if ($msg =~ s/^ (?: gbp(?:-pq)? : \s* name \s+ |
5566 (\S+) \s* \n //ixm) {
5567 $patchname = $gbp_check_suitable->($1, 'Name');
5569 if ($msg =~ s/^ (?: gbp(?:-pq)? : \s* topic \s+ |
5571 (\S+) \s* \n //ixm) {
5572 $patchdir = $gbp_check_suitable->($1, 'Topic');
5577 if (!defined $patchname) {
5578 $patchname = $title;
5579 $patchname =~ s/[.:]$//;
5582 my $converter = new Text::Iconv qw(UTF-8 ASCII//TRANSLIT);
5583 my $translitname = $converter->convert($patchname);
5584 die unless defined $translitname;
5585 $patchname = $translitname;
5588 "dgit: patch title transliteration error: $@"
5590 $patchname =~ y/ A-Z/-a-z/;
5591 $patchname =~ y/-a-z0-9_.+=~//cd;
5592 $patchname =~ s/^\W/x-$&/;
5593 $patchname = substr($patchname,0,40);
5594 $patchname .= ".patch";
5596 if (!defined $patchdir) {
5599 if (length $patchdir) {
5600 $patchname = "$patchdir/$patchname";
5602 if ($patchname =~ m{^(.*)/}) {
5603 mkpath "debian/patches/$1";
5608 stat "debian/patches/$patchname$index";
5610 $!==ENOENT or die "$patchname$index $!";
5612 runcmd @git, qw(checkout -q), $cc;
5614 # We use the tip's changelog so that dpkg-source doesn't
5615 # produce complaining messages from dpkg-parsechangelog. None
5616 # of the information dpkg-source gets from the changelog is
5617 # actually relevant - it gets put into the original message
5618 # which dpkg-source provides our stunt editor, and then
5620 runcmd @git, qw(checkout -q), $target, qw(debian/changelog);
5622 quiltify_dpkg_commit "$patchname$index", $author, $msg,
5623 "Date: $commitdate\n".
5624 "X-Dgit-Generated: $clogp->{Version} $cc\n";
5626 runcmd @git, qw(checkout -q), $cc, qw(debian/changelog);
5629 runcmd @git, qw(checkout -q master);
5632 sub build_maybe_quilt_fixup () {
5633 my ($format,$fopts) = get_source_format;
5634 return unless madformat_wantfixup $format;
5637 check_for_vendor_patches();
5639 if (quiltmode_splitbrain) {
5640 fail <<END unless access_cfg_tagformats_can_splitbrain;
5641 quilt mode $quilt_mode requires split view so server needs to support
5642 both "new" and "maint" tag formats, but config says it doesn't.
5646 my $clogp = parsechangelog();
5647 my $headref = git_rev_parse('HEAD');
5648 my $symref = git_get_symref();
5650 if ($quilt_mode eq 'linear'
5651 && !$fopts->{'single-debian-patch'}
5652 && branch_is_gdr($symref, $headref)) {
5653 # This is much faster. It also makes patches that gdr
5654 # likes better for future updates without laundering.
5656 # However, it can fail in some casses where we would
5657 # succeed: if there are existing patches, which correspond
5658 # to a prefix of the branch, but are not in gbp/gdr
5659 # format, gdr will fail (exiting status 7), but we might
5660 # be able to figure out where to start linearising. That
5661 # will be slower so hopefully there's not much to do.
5662 my @cmd = (@git_debrebase,
5663 qw(--noop-ok -funclean-mixed -funclean-ordering
5664 make-patches --quiet-would-amend));
5665 # We tolerate soe snags that gdr wouldn't, by default.
5669 failedcmd @cmd if system @cmd and $?!=7*256;
5673 $headref = git_rev_parse('HEAD');
5677 changedir $playground;
5679 my $upstreamversion = upstreamversion $version;
5681 if ($fopts->{'single-debian-patch'}) {
5682 quilt_fixup_singlepatch($clogp, $headref, $upstreamversion);
5684 quilt_fixup_multipatch($clogp, $headref, $upstreamversion);
5687 die 'bug' if $split_brain && !$need_split_build_invocation;
5690 runcmd_ordryrun_local
5691 @git, qw(pull --ff-only -q), "$playground/work", qw(master);
5694 sub quilt_fixup_mkwork ($) {
5697 mkdir "work" or die $!;
5699 mktree_in_ud_here();
5700 runcmd @git, qw(reset -q --hard), $headref;
5703 sub quilt_fixup_linkorigs ($$) {
5704 my ($upstreamversion, $fn) = @_;
5705 # calls $fn->($leafname);
5707 foreach my $f (<$maindir/../*>) { #/){
5708 my $b=$f; $b =~ s{.*/}{};
5710 local ($debuglevel) = $debuglevel-1;
5711 printdebug "QF linkorigs $b, $f ?\n";
5713 next unless is_orig_file_of_vsn $b, $upstreamversion;
5714 printdebug "QF linkorigs $b, $f Y\n";
5715 link_ltarget $f, $b or die "$b $!";
5720 sub quilt_fixup_delete_pc () {
5721 runcmd @git, qw(rm -rqf .pc);
5723 Commit removal of .pc (quilt series tracking data)
5725 [dgit ($our_version) upgrade quilt-remove-pc]
5729 sub quilt_fixup_singlepatch ($$$) {
5730 my ($clogp, $headref, $upstreamversion) = @_;
5732 progress "starting quiltify (single-debian-patch)";
5734 # dpkg-source --commit generates new patches even if
5735 # single-debian-patch is in debian/source/options. In order to
5736 # get it to generate debian/patches/debian-changes, it is
5737 # necessary to build the source package.
5739 quilt_fixup_linkorigs($upstreamversion, sub { });
5740 quilt_fixup_mkwork($headref);
5742 rmtree("debian/patches");
5744 runcmd @dpkgsource, qw(-b .);
5746 runcmd @dpkgsource, qw(-x), (srcfn $version, ".dsc");
5747 rename srcfn("$upstreamversion", "/debian/patches"),
5748 "work/debian/patches";
5751 commit_quilty_patch();
5754 sub quilt_make_fake_dsc ($) {
5755 my ($upstreamversion) = @_;
5757 my $fakeversion="$upstreamversion-~~DGITFAKE";
5759 my $fakedsc=new IO::File 'fake.dsc', '>' or die $!;
5760 print $fakedsc <<END or die $!;
5763 Version: $fakeversion
5767 my $dscaddfile=sub {
5770 my $md = new Digest::MD5;
5772 my $fh = new IO::File $b, '<' or die "$b $!";
5777 print $fakedsc " ".$md->hexdigest." $size $b\n" or die $!;
5780 quilt_fixup_linkorigs($upstreamversion, $dscaddfile);
5782 my @files=qw(debian/source/format debian/rules
5783 debian/control debian/changelog);
5784 foreach my $maybe (qw(debian/patches debian/source/options
5785 debian/tests/control)) {
5786 next unless stat_exists "$maindir/$maybe";
5787 push @files, $maybe;
5790 my $debtar= srcfn $fakeversion,'.debian.tar.gz';
5791 runcmd qw(env GZIP=-1n tar -zcf), "./$debtar", qw(-C), $maindir, @files;
5793 $dscaddfile->($debtar);
5794 close $fakedsc or die $!;
5797 sub quilt_check_splitbrain_cache ($$) {
5798 my ($headref, $upstreamversion) = @_;
5799 # Called only if we are in (potentially) split brain mode.
5800 # Called in playground.
5801 # Computes the cache key and looks in the cache.
5802 # Returns ($dgit_view_commitid, $cachekey) or (undef, $cachekey)
5804 my $splitbrain_cachekey;
5807 "dgit: split brain (separate dgit view) may be needed (--quilt=$quilt_mode).";
5808 # we look in the reflog of dgit-intern/quilt-cache
5809 # we look for an entry whose message is the key for the cache lookup
5810 my @cachekey = (qw(dgit), $our_version);
5811 push @cachekey, $upstreamversion;
5812 push @cachekey, $quilt_mode;
5813 push @cachekey, $headref;
5815 push @cachekey, hashfile('fake.dsc');
5817 my $srcshash = Digest::SHA->new(256);
5818 my %sfs = ( %INC, '$0(dgit)' => $0 );
5819 foreach my $sfk (sort keys %sfs) {
5820 next unless $sfk =~ m/^\$0\b/ || $sfk =~ m{^Debian/Dgit\b};
5821 $srcshash->add($sfk," ");
5822 $srcshash->add(hashfile($sfs{$sfk}));
5823 $srcshash->add("\n");
5825 push @cachekey, $srcshash->hexdigest();
5826 $splitbrain_cachekey = "@cachekey";
5828 my @cmd = (@git, qw(log -g), '--pretty=format:%H %gs',
5830 printdebug "splitbrain cachekey $splitbrain_cachekey\n";
5831 debugcmd "|(probably)",@cmd;
5832 my $child = open GC, "-|"; defined $child or die $!;
5834 chdir $maindir or die $!;
5835 if (!stat "$maindir_gitcommon/logs/refs/$splitbraincache") {
5836 $! == ENOENT or die $!;
5837 printdebug ">(no reflog)\n";
5844 printdebug ">| ", $_, "\n" if $debuglevel > 1;
5845 next unless m/^(\w+) (\S.*\S)$/ && $2 eq $splitbrain_cachekey;
5848 quilt_fixup_mkwork($headref);
5849 my $saved = maybe_split_brain_save $headref, $cachehit, "cache-hit";
5850 if ($cachehit ne $headref) {
5851 progress "dgit view: found cached ($saved)";
5852 runcmd @git, qw(checkout -q -b dgit-view), $cachehit;
5854 return ($cachehit, $splitbrain_cachekey);
5856 progress "dgit view: found cached, no changes required";
5857 return ($headref, $splitbrain_cachekey);
5859 die $! if GC->error;
5860 failedcmd unless close GC;
5862 printdebug "splitbrain cache miss\n";
5863 return (undef, $splitbrain_cachekey);
5866 sub quilt_fixup_multipatch ($$$) {
5867 my ($clogp, $headref, $upstreamversion) = @_;
5869 progress "examining quilt state (multiple patches, $quilt_mode mode)";
5872 # - honour any existing .pc in case it has any strangeness
5873 # - determine the git commit corresponding to the tip of
5874 # the patch stack (if there is one)
5875 # - if there is such a git commit, convert each subsequent
5876 # git commit into a quilt patch with dpkg-source --commit
5877 # - otherwise convert all the differences in the tree into
5878 # a single git commit
5882 # Our git tree doesn't necessarily contain .pc. (Some versions of
5883 # dgit would include the .pc in the git tree.) If there isn't
5884 # one, we need to generate one by unpacking the patches that we
5887 # We first look for a .pc in the git tree. If there is one, we
5888 # will use it. (This is not the normal case.)
5890 # Otherwise need to regenerate .pc so that dpkg-source --commit
5891 # can work. We do this as follows:
5892 # 1. Collect all relevant .orig from parent directory
5893 # 2. Generate a debian.tar.gz out of
5894 # debian/{patches,rules,source/format,source/options}
5895 # 3. Generate a fake .dsc containing just these fields:
5896 # Format Source Version Files
5897 # 4. Extract the fake .dsc
5898 # Now the fake .dsc has a .pc directory.
5899 # (In fact we do this in every case, because in future we will
5900 # want to search for a good base commit for generating patches.)
5902 # Then we can actually do the dpkg-source --commit
5903 # 1. Make a new working tree with the same object
5904 # store as our main tree and check out the main
5906 # 2. Copy .pc from the fake's extraction, if necessary
5907 # 3. Run dpkg-source --commit
5908 # 4. If the result has changes to debian/, then
5909 # - git add them them
5910 # - git add .pc if we had a .pc in-tree
5912 # 5. If we had a .pc in-tree, delete it, and git commit
5913 # 6. Back in the main tree, fast forward to the new HEAD
5915 # Another situation we may have to cope with is gbp-style
5916 # patches-unapplied trees.
5918 # We would want to detect these, so we know to escape into
5919 # quilt_fixup_gbp. However, this is in general not possible.
5920 # Consider a package with a one patch which the dgit user reverts
5921 # (with git revert or the moral equivalent).
5923 # That is indistinguishable in contents from a patches-unapplied
5924 # tree. And looking at the history to distinguish them is not
5925 # useful because the user might have made a confusing-looking git
5926 # history structure (which ought to produce an error if dgit can't
5927 # cope, not a silent reintroduction of an unwanted patch).
5929 # So gbp users will have to pass an option. But we can usually
5930 # detect their failure to do so: if the tree is not a clean
5931 # patches-applied tree, quilt linearisation fails, but the tree
5932 # _is_ a clean patches-unapplied tree, we can suggest that maybe
5933 # they want --quilt=unapplied.
5935 # To help detect this, when we are extracting the fake dsc, we
5936 # first extract it with --skip-patches, and then apply the patches
5937 # afterwards with dpkg-source --before-build. That lets us save a
5938 # tree object corresponding to .origs.
5940 my $splitbrain_cachekey;
5942 quilt_make_fake_dsc($upstreamversion);
5944 if (quiltmode_splitbrain()) {
5946 ($cachehit, $splitbrain_cachekey) =
5947 quilt_check_splitbrain_cache($headref, $upstreamversion);
5948 return if $cachehit;
5952 'exec dpkg-source --no-check --skip-patches -x fake.dsc >/dev/null';
5954 my $fakexdir= $package.'-'.(stripepoch $upstreamversion);
5955 rename $fakexdir, "fake" or die "$fakexdir $!";
5959 remove_stray_gits("source package");
5960 mktree_in_ud_here();
5964 rmtree 'debian'; # git checkout commitish paths does not delete!
5965 runcmd @git, qw(checkout -f), $headref, qw(-- debian);
5966 my $unapplied=git_add_write_tree();
5967 printdebug "fake orig tree object $unapplied\n";
5971 my @bbcmd = (qw(sh -ec), 'exec dpkg-source --before-build . >/dev/null');
5973 if (system @bbcmd) {
5974 failedcmd @bbcmd if $? < 0;
5976 failed to apply your git tree's patch stack (from debian/patches/) to
5977 the corresponding upstream tarball(s). Your source tree and .orig
5978 are probably too inconsistent. dgit can only fix up certain kinds of
5979 anomaly (depending on the quilt mode). See --quilt= in dgit(1).
5985 quilt_fixup_mkwork($headref);
5988 if (stat_exists ".pc") {
5990 progress "Tree already contains .pc - will use it then delete it.";
5993 rename '../fake/.pc','.pc' or die $!;
5996 changedir '../fake';
5998 my $oldtiptree=git_add_write_tree();
5999 printdebug "fake o+d/p tree object $unapplied\n";
6000 changedir '../work';
6003 # We calculate some guesswork now about what kind of tree this might
6004 # be. This is mostly for error reporting.
6010 # O = orig, without patches applied
6011 # A = "applied", ie orig with H's debian/patches applied
6012 O2H => quiltify_trees_differ($unapplied,$headref, 1,
6013 \%editedignores, \@unrepres),
6014 H2A => quiltify_trees_differ($headref, $oldtiptree,1),
6015 O2A => quiltify_trees_differ($unapplied,$oldtiptree,1),
6019 foreach my $b (qw(01 02)) {
6020 foreach my $v (qw(O2H O2A H2A)) {
6021 push @dl, ($diffbits->{$v} & $b) ? '##' : '==';
6024 printdebug "differences \@dl @dl.\n";
6027 "$us: base trees orig=%.20s o+d/p=%.20s",
6028 $unapplied, $oldtiptree;
6030 "$us: quilt differences: src: %s orig %s gitignores: %s orig %s\n".
6031 "$us: quilt differences: HEAD %s o+d/p HEAD %s o+d/p",
6032 $dl[0], $dl[1], $dl[3], $dl[4],
6036 print STDERR "dgit: cannot represent change: $_->[1]: $_->[0]\n"
6038 forceable_fail [qw(unrepresentable)], <<END;
6039 HEAD has changes to .orig[s] which are not representable by `3.0 (quilt)'
6044 if (!($diffbits->{O2H} & $diffbits->{O2A})) {
6045 push @failsuggestion, "This might be a patches-unapplied branch.";
6046 } elsif (!($diffbits->{H2A} & $diffbits->{O2A})) {
6047 push @failsuggestion, "This might be a patches-applied branch.";
6049 push @failsuggestion, "Maybe you need to specify one of".
6050 " --[quilt=]gbp --[quilt=]dpm --quilt=unapplied ?";
6052 if (quiltmode_splitbrain()) {
6053 quiltify_splitbrain($clogp, $unapplied, $headref, $oldtiptree,
6054 $diffbits, \%editedignores,
6055 $splitbrain_cachekey);
6059 progress "starting quiltify (multiple patches, $quilt_mode mode)";
6060 quiltify($clogp,$headref,$oldtiptree,\@failsuggestion);
6062 if (!open P, '>>', ".pc/applied-patches") {
6063 $!==&ENOENT or die $!;
6068 commit_quilty_patch();
6070 if ($mustdeletepc) {
6071 quilt_fixup_delete_pc();
6075 sub quilt_fixup_editor () {
6076 my $descfn = $ENV{$fakeeditorenv};
6077 my $editing = $ARGV[$#ARGV];
6078 open I1, '<', $descfn or die "$descfn: $!";
6079 open I2, '<', $editing or die "$editing: $!";
6080 unlink $editing or die "$editing: $!";
6081 open O, '>', $editing or die "$editing: $!";
6082 while (<I1>) { print O or die $!; } I1->error and die $!;
6085 $copying ||= m/^\-\-\- /;
6086 next unless $copying;
6089 I2->error and die $!;
6094 sub maybe_apply_patches_dirtily () {
6095 return unless $quilt_mode =~ m/gbp|unapplied/;
6096 print STDERR <<END or die $!;
6098 dgit: Building, or cleaning with rules target, in patches-unapplied tree.
6099 dgit: Have to apply the patches - making the tree dirty.
6100 dgit: (Consider specifying --clean=git and (or) using dgit sbuild.)
6103 $patches_applied_dirtily = 01;
6104 $patches_applied_dirtily |= 02 unless stat_exists '.pc';
6105 runcmd qw(dpkg-source --before-build .);
6108 sub maybe_unapply_patches_again () {
6109 progress "dgit: Unapplying patches again to tidy up the tree."
6110 if $patches_applied_dirtily;
6111 runcmd qw(dpkg-source --after-build .)
6112 if $patches_applied_dirtily & 01;
6114 if $patches_applied_dirtily & 02;
6115 $patches_applied_dirtily = 0;
6118 #----- other building -----
6120 our $clean_using_builder;
6121 # ^ tree is to be cleaned by dpkg-source's builtin idea that it should
6122 # clean the tree before building (perhaps invoked indirectly by
6123 # whatever we are using to run the build), rather than separately
6124 # and explicitly by us.
6127 return if $clean_using_builder;
6128 if ($cleanmode eq 'dpkg-source') {
6129 maybe_apply_patches_dirtily();
6130 runcmd_ordryrun_local @dpkgbuildpackage, qw(-T clean);
6131 } elsif ($cleanmode eq 'dpkg-source-d') {
6132 maybe_apply_patches_dirtily();
6133 runcmd_ordryrun_local @dpkgbuildpackage, qw(-d -T clean);
6134 } elsif ($cleanmode eq 'git') {
6135 runcmd_ordryrun_local @git, qw(clean -xdf);
6136 } elsif ($cleanmode eq 'git-ff') {
6137 runcmd_ordryrun_local @git, qw(clean -xdff);
6138 } elsif ($cleanmode eq 'check') {
6139 my $leftovers = cmdoutput @git, qw(clean -xdn);
6140 if (length $leftovers) {
6141 print STDERR $leftovers, "\n" or die $!;
6142 fail "tree contains uncommitted files and --clean=check specified";
6144 } elsif ($cleanmode eq 'none') {
6151 badusage "clean takes no additional arguments" if @ARGV;
6154 maybe_unapply_patches_again();
6157 sub build_or_push_prep_early () {
6158 our $build_or_push_prep_early_done //= 0;
6159 return if $build_or_push_prep_early_done++;
6160 badusage "-p is not allowed with dgit $subcommand" if defined $package;
6161 my $clogp = parsechangelog();
6162 $isuite = getfield $clogp, 'Distribution';
6163 $package = getfield $clogp, 'Source';
6164 $version = getfield $clogp, 'Version';
6167 sub build_prep_early () {
6168 build_or_push_prep_early();
6176 build_maybe_quilt_fixup();
6178 my $pat = changespat $version;
6179 foreach my $f (glob "$buildproductsdir/$pat") {
6181 unlink $f or fail "remove old changes file $f: $!";
6183 progress "would remove $f";
6189 sub changesopts_initial () {
6190 my @opts =@changesopts[1..$#changesopts];
6193 sub changesopts_version () {
6194 if (!defined $changes_since_version) {
6197 @vsns = archive_query('archive_query');
6198 my @quirk = access_quirk();
6199 if ($quirk[0] eq 'backports') {
6200 local $isuite = $quirk[2];
6202 canonicalise_suite();
6203 push @vsns, archive_query('archive_query');
6209 "archive query failed (queried because --since-version not specified)";
6212 @vsns = map { $_->[0] } @vsns;
6213 @vsns = sort { -version_compare($a, $b) } @vsns;
6214 $changes_since_version = $vsns[0];
6215 progress "changelog will contain changes since $vsns[0]";
6217 $changes_since_version = '_';
6218 progress "package seems new, not specifying -v<version>";
6221 if ($changes_since_version ne '_') {
6222 return ("-v$changes_since_version");
6228 sub changesopts () {
6229 return (changesopts_initial(), changesopts_version());
6232 sub massage_dbp_args ($;$) {
6233 my ($cmd,$xargs) = @_;
6236 # - if we're going to split the source build out so we can
6237 # do strange things to it, massage the arguments to dpkg-buildpackage
6238 # so that the main build doessn't build source (or add an argument
6239 # to stop it building source by default).
6241 # - add -nc to stop dpkg-source cleaning the source tree,
6242 # unless we're not doing a split build and want dpkg-source
6243 # as cleanmode, in which case we can do nothing
6246 # 0 - source will NOT need to be built separately by caller
6247 # +1 - source will need to be built separately by caller
6248 # +2 - source will need to be built separately by caller AND
6249 # dpkg-buildpackage should not in fact be run at all!
6250 debugcmd '#massaging#', @$cmd if $debuglevel>1;
6251 #print STDERR "MASS0 ",Dumper($cmd, $xargs, $need_split_build_invocation);
6252 if ($cleanmode eq 'dpkg-source' && !$need_split_build_invocation) {
6253 $clean_using_builder = 1;
6256 # -nc has the side effect of specifying -b if nothing else specified
6257 # and some combinations of -S, -b, et al, are errors, rather than
6258 # later simply overriding earlie. So we need to:
6259 # - search the command line for these options
6260 # - pick the last one
6261 # - perhaps add our own as a default
6262 # - perhaps adjust it to the corresponding non-source-building version
6264 foreach my $l ($cmd, $xargs) {
6266 @$l = grep { !(m/^-[SgGFABb]$/s and $dmode=$_) } @$l;
6269 #print STDERR "MASS1 ",Dumper($cmd, $xargs, $dmode);
6271 if ($need_split_build_invocation) {
6272 printdebug "massage split $dmode.\n";
6273 $r = $dmode =~ m/[S]/ ? +2 :
6274 $dmode =~ y/gGF/ABb/ ? +1 :
6275 $dmode =~ m/[ABb]/ ? 0 :
6278 printdebug "massage done $r $dmode.\n";
6280 #print STDERR "MASS2 ",Dumper($cmd, $xargs, $r);
6286 my $wasdir = must_getcwd();
6292 sub postbuild_mergechanges ($) { # must run with CWD=.. (eg in in_parent)
6293 my ($msg_if_onlyone) = @_;
6294 # If there is only one .changes file, fail with $msg_if_onlyone,
6295 # or if that is undef, be a no-op.
6296 # Returns the changes file to report to the user.
6297 my $pat = changespat $version;
6298 my @changesfiles = glob $pat;
6299 @changesfiles = sort {
6300 ($b =~ m/_source\.changes$/ <=> $a =~ m/_source\.changes$/)
6304 if (@changesfiles==1) {
6305 fail <<END.$msg_if_onlyone if defined $msg_if_onlyone;
6306 only one changes file from build (@changesfiles)
6308 $result = $changesfiles[0];
6309 } elsif (@changesfiles==2) {
6310 my $binchanges = parsecontrol($changesfiles[1], "binary changes file");
6311 foreach my $l (split /\n/, getfield $binchanges, 'Files') {
6312 fail "$l found in binaries changes file $binchanges"
6315 runcmd_ordryrun_local @mergechanges, @changesfiles;
6316 my $multichanges = changespat $version,'multi';
6318 stat_exists $multichanges or fail "$multichanges: $!";
6319 foreach my $cf (glob $pat) {
6320 next if $cf eq $multichanges;
6321 rename "$cf", "$cf.inmulti" or fail "$cf\{,.inmulti}: $!";
6324 $result = $multichanges;
6326 fail "wrong number of different changes files (@changesfiles)";
6328 printdone "build successful, results in $result\n" or die $!;
6331 sub midbuild_checkchanges () {
6332 my $pat = changespat $version;
6333 return if $rmchanges;
6334 my @unwanted = map { s#^\.\./##; $_; } glob "../$pat";
6335 @unwanted = grep { $_ ne changespat $version,'source' } @unwanted;
6337 changes files other than source matching $pat already present; building would result in ambiguity about the intended results.
6338 Suggest you delete @unwanted.
6343 sub midbuild_checkchanges_vanilla ($) {
6345 midbuild_checkchanges() if $wantsrc == 1;
6348 sub postbuild_mergechanges_vanilla ($) {
6350 if ($wantsrc == 1) {
6352 postbuild_mergechanges(undef);
6355 printdone "build successful\n";
6361 my @dbp = (@dpkgbuildpackage, qw(-us -uc), changesopts_initial(), @ARGV);
6362 my $wantsrc = massage_dbp_args \@dbp;
6365 midbuild_checkchanges_vanilla $wantsrc;
6370 push @dbp, changesopts_version();
6371 maybe_apply_patches_dirtily();
6372 runcmd_ordryrun_local @dbp;
6374 maybe_unapply_patches_again();
6375 postbuild_mergechanges_vanilla $wantsrc;
6379 $quilt_mode //= 'gbp';
6385 # gbp can make .origs out of thin air. In my tests it does this
6386 # even for a 1.0 format package, with no origs present. So I
6387 # guess it keys off just the version number. We don't know
6388 # exactly what .origs ought to exist, but let's assume that we
6389 # should run gbp if: the version has an upstream part and the main
6391 my $upstreamversion = upstreamversion $version;
6392 my $origfnpat = srcfn $upstreamversion, '.orig.tar.*';
6393 my $gbp_make_orig = $version =~ m/-/ && !(() = glob "../$origfnpat");
6395 if ($gbp_make_orig) {
6397 $cleanmode = 'none'; # don't do it again
6398 $need_split_build_invocation = 1;
6401 my @dbp = @dpkgbuildpackage;
6403 my $wantsrc = massage_dbp_args \@dbp, \@ARGV;
6405 if (!length $gbp_build[0]) {
6406 if (length executable_on_path('git-buildpackage')) {
6407 $gbp_build[0] = qw(git-buildpackage);
6409 $gbp_build[0] = 'gbp buildpackage';
6412 my @cmd = opts_opt_multi_cmd @gbp_build;
6414 push @cmd, (qw(-us -uc --git-no-sign-tags),
6415 "--git-builder=".(shellquote @dbp));
6417 if ($gbp_make_orig) {
6418 my $priv = dgit_privdir();
6419 my $ok = "$priv/origs-gen-ok";
6420 unlink $ok or $!==&ENOENT or die $!;
6421 my @origs_cmd = @cmd;
6422 push @origs_cmd, qw(--git-cleaner=true);
6423 push @origs_cmd, "--git-prebuild=".
6424 "touch ".(shellquote $ok)." ".(shellquote "$priv/no-such-dir/ok");
6425 push @origs_cmd, @ARGV;
6427 debugcmd @origs_cmd;
6429 do { local $!; stat_exists $ok; }
6430 or failedcmd @origs_cmd;
6432 dryrun_report @origs_cmd;
6438 midbuild_checkchanges_vanilla $wantsrc;
6440 if (!$clean_using_builder) {
6441 push @cmd, '--git-cleaner=true';
6445 maybe_unapply_patches_again();
6447 push @cmd, changesopts();
6448 runcmd_ordryrun_local @cmd, @ARGV;
6450 postbuild_mergechanges_vanilla $wantsrc;
6452 sub cmd_git_build { cmd_gbp_build(); } # compatibility with <= 1.0
6454 sub build_source_for_push {
6456 maybe_unapply_patches_again();
6457 $changesfile = $sourcechanges;
6463 $sourcechanges = changespat $version,'source';
6465 unlink "../$sourcechanges" or $!==ENOENT
6466 or fail "remove $sourcechanges: $!";
6468 $dscfn = dscfn($version);
6469 my @cmd = (@dpkgsource, qw(-b --));
6471 changedir $playground;
6472 runcmd_ordryrun_local @cmd, "work";
6473 my @udfiles = <${package}_*>;
6475 foreach my $f (@udfiles) {
6476 printdebug "source copy, found $f\n";
6479 ($f =~ m/\.debian\.tar(?:\.\w+)$/ &&
6480 $f eq srcfn($version, $&));
6481 printdebug "source copy, found $f - renaming\n";
6482 rename "$playground/$f", "../$f" or $!==ENOENT
6483 or fail "put in place new source file ($f): $!";
6486 my $pwd = must_getcwd();
6487 my $leafdir = basename $pwd;
6489 runcmd_ordryrun_local @cmd, $leafdir;
6492 runcmd_ordryrun_local qw(sh -ec),
6493 'exec >$1; shift; exec "$@"','x',
6494 "../$sourcechanges",
6495 @dpkggenchanges, qw(-S), changesopts();
6498 sub cmd_build_source {
6500 badusage "build-source takes no additional arguments" if @ARGV;
6502 maybe_unapply_patches_again();
6503 printdone "source built, results in $dscfn and $sourcechanges";
6508 midbuild_checkchanges();
6511 stat_exists $dscfn or fail "$dscfn (in parent directory): $!";
6512 stat_exists $sourcechanges
6513 or fail "$sourcechanges (in parent directory): $!";
6515 runcmd_ordryrun_local @sbuild, qw(-d), $isuite, @ARGV, $dscfn;
6517 maybe_unapply_patches_again();
6519 postbuild_mergechanges(<<END);
6520 perhaps you need to pass -A ? (sbuild's default is to build only
6521 arch-specific binaries; dgit 1.4 used to override that.)
6526 sub cmd_quilt_fixup {
6527 badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
6530 build_maybe_quilt_fixup();
6533 sub import_dsc_result {
6534 my ($dstref, $newhash, $what_log, $what_msg) = @_;
6535 my @cmd = (git_update_ref_cmd $what_log, $dstref, $newhash);
6537 check_gitattrs($newhash, "source tree");
6539 progress "dgit: import-dsc: $what_msg";
6542 sub cmd_import_dsc {
6546 last unless $ARGV[0] =~ m/^-/;
6549 if (m/^--require-valid-signature$/) {
6552 badusage "unknown dgit import-dsc sub-option \`$_'";
6556 badusage "usage: dgit import-dsc .../PATH/TO/.DSC BRANCH" unless @ARGV==2;
6557 my ($dscfn, $dstbranch) = @ARGV;
6559 badusage "dry run makes no sense with import-dsc" unless act_local();
6561 my $force = $dstbranch =~ s/^\+// ? +1 :
6562 $dstbranch =~ s/^\.\.// ? -1 :
6564 my $info = $force ? " $&" : '';
6565 $info = "$dscfn$info";
6567 my $specbranch = $dstbranch;
6568 $dstbranch = "refs/heads/$dstbranch" unless $dstbranch =~ m#^refs/#;
6569 $dstbranch = cmdoutput @git, qw(check-ref-format --normalize), $dstbranch;
6571 my @symcmd = (@git, qw(symbolic-ref -q HEAD));
6572 my $chead = cmdoutput_errok @symcmd;
6573 defined $chead or $?==256 or failedcmd @symcmd;
6575 fail "$dstbranch is checked out - will not update it"
6576 if defined $chead and $chead eq $dstbranch;
6578 my $oldhash = git_get_ref $dstbranch;
6580 open D, "<", $dscfn or fail "open import .dsc ($dscfn): $!";
6581 $dscdata = do { local $/ = undef; <D>; };
6582 D->error and fail "read $dscfn: $!";
6585 # we don't normally need this so import it here
6586 use Dpkg::Source::Package;
6587 my $dp = new Dpkg::Source::Package filename => $dscfn,
6588 require_valid_signature => $needsig;
6590 local $SIG{__WARN__} = sub {
6592 return unless $needsig;
6593 fail "import-dsc signature check failed";
6595 if (!$dp->is_signed()) {
6596 warn "$us: warning: importing unsigned .dsc\n";
6598 my $r = $dp->check_signature();
6599 die "->check_signature => $r" if $needsig && $r;
6605 $package = getfield $dsc, 'Source';
6607 parse_dsc_field($dsc, "Dgit metadata in .dsc")
6608 unless forceing [qw(import-dsc-with-dgit-field)];
6609 parse_dsc_field_def_dsc_distro();
6611 $isuite = 'DGIT-IMPORT-DSC';
6612 $idistro //= $dsc_distro;
6616 if (defined $dsc_hash) {
6617 progress "dgit: import-dsc of .dsc with Dgit field, using git hash";
6618 resolve_dsc_field_commit undef, undef;
6620 if (defined $dsc_hash) {
6621 my @cmd = (qw(sh -ec),
6622 "echo $dsc_hash | git cat-file --batch-check");
6623 my $objgot = cmdoutput @cmd;
6624 if ($objgot =~ m#^\w+ missing\b#) {
6626 .dsc contains Dgit field referring to object $dsc_hash
6627 Your git tree does not have that object. Try `git fetch' from a
6628 plausible server (browse.dgit.d.o? alioth?), and try the import-dsc again.
6631 if ($oldhash && !is_fast_fwd $oldhash, $dsc_hash) {
6633 progress "Not fast forward, forced update.";
6635 fail "Not fast forward to $dsc_hash";
6638 import_dsc_result $dstbranch, $dsc_hash,
6639 "dgit import-dsc (Dgit): $info",
6640 "updated git ref $dstbranch";
6645 Branch $dstbranch already exists
6646 Specify ..$specbranch for a pseudo-merge, binding in existing history
6647 Specify +$specbranch to overwrite, discarding existing history
6649 if $oldhash && !$force;
6651 my @dfi = dsc_files_info();
6652 foreach my $fi (@dfi) {
6653 my $f = $fi->{Filename};
6657 fail "lstat $here works but stat gives $! !";
6659 fail "stat $here: $!" unless $! == ENOENT;
6661 if ($dscfn =~ m#^(?:\./+)?\.\./+#) {
6663 } elsif ($dscfn =~ m#^/#) {
6666 fail "cannot import $dscfn which seems to be inside working tree!";
6668 $there =~ s#/+[^/]+$## or
6669 fail "import $dscfn requires ../$f, but it does not exist";
6671 my $test = $there =~ m{^/} ? $there : "../$there";
6672 stat $test or fail "import $dscfn requires $test, but: $!";
6673 symlink $there, $here or fail "symlink $there to $here: $!";
6674 progress "made symlink $here -> $there";
6675 # print STDERR Dumper($fi);
6677 my @mergeinputs = generate_commits_from_dsc();
6678 die unless @mergeinputs == 1;
6680 my $newhash = $mergeinputs[0]{Commit};
6684 progress "Import, forced update - synthetic orphan git history.";
6685 } elsif ($force < 0) {
6686 progress "Import, merging.";
6687 my $tree = cmdoutput @git, qw(rev-parse), "$newhash:";
6688 my $version = getfield $dsc, 'Version';
6689 my $clogp = commit_getclogp $newhash;
6690 my $authline = clogp_authline $clogp;
6691 $newhash = make_commit_text <<END;
6698 Merge $package ($version) import into $dstbranch
6701 die; # caught earlier
6705 import_dsc_result $dstbranch, $newhash,
6706 "dgit import-dsc: $info",
6707 "results are in in git ref $dstbranch";
6710 sub pre_archive_api_query () {
6711 not_necessarily_a_tree();
6713 sub cmd_archive_api_query {
6714 badusage "need only 1 subpath argument" unless @ARGV==1;
6715 my ($subpath) = @ARGV;
6716 local $isuite = 'DGIT-API-QUERY-CMD';
6717 my @cmd = archive_api_query_cmd($subpath);
6720 exec @cmd or fail "exec curl: $!\n";
6723 sub repos_server_url () {
6724 $package = '_dgit-repos-server';
6725 local $access_forpush = 1;
6726 local $isuite = 'DGIT-REPOS-SERVER';
6727 my $url = access_giturl();
6730 sub pre_clone_dgit_repos_server () {
6731 not_necessarily_a_tree();
6733 sub cmd_clone_dgit_repos_server {
6734 badusage "need destination argument" unless @ARGV==1;
6735 my ($destdir) = @ARGV;
6736 my $url = repos_server_url();
6737 my @cmd = (@git, qw(clone), $url, $destdir);
6739 exec @cmd or fail "exec git clone: $!\n";
6742 sub pre_print_dgit_repos_server_source_url () {
6743 not_necessarily_a_tree();
6745 sub cmd_print_dgit_repos_server_source_url {
6746 badusage "no arguments allowed to dgit print-dgit-repos-server-source-url"
6748 my $url = repos_server_url();
6749 print $url, "\n" or die $!;
6752 sub pre_print_dpkg_source_ignores {
6753 not_necessarily_a_tree();
6755 sub cmd_print_dpkg_source_ignores {
6756 badusage "no arguments allowed to dgit print-dpkg-source-ignores"
6758 print "@dpkg_source_ignores\n" or die $!;
6761 sub cmd_setup_mergechangelogs {
6762 badusage "no arguments allowed to dgit setup-mergechangelogs" if @ARGV;
6763 local $isuite = 'DGIT-SETUP-TREE';
6764 setup_mergechangelogs(1);
6767 sub cmd_setup_useremail {
6768 badusage "no arguments allowed to dgit setup-useremail" if @ARGV;
6769 local $isuite = 'DGIT-SETUP-TREE';
6773 sub cmd_setup_gitattributes {
6774 badusage "no arguments allowed to dgit setup-useremail" if @ARGV;
6775 local $isuite = 'DGIT-SETUP-TREE';
6779 sub cmd_setup_new_tree {
6780 badusage "no arguments allowed to dgit setup-tree" if @ARGV;
6781 local $isuite = 'DGIT-SETUP-TREE';
6785 #---------- argument parsing and main program ----------
6788 print "dgit version $our_version\n" or die $!;
6792 our (%valopts_long, %valopts_short);
6793 our (%funcopts_long);
6795 our (@modeopt_cfgs);
6797 sub defvalopt ($$$$) {
6798 my ($long,$short,$val_re,$how) = @_;
6799 my $oi = { Long => $long, Short => $short, Re => $val_re, How => $how };
6800 $valopts_long{$long} = $oi;
6801 $valopts_short{$short} = $oi;
6802 # $how subref should:
6803 # do whatever assignemnt or thing it likes with $_[0]
6804 # if the option should not be passed on to remote, @rvalopts=()
6805 # or $how can be a scalar ref, meaning simply assign the value
6808 defvalopt '--since-version', '-v', '[^_]+|_', \$changes_since_version;
6809 defvalopt '--distro', '-d', '.+', \$idistro;
6810 defvalopt '', '-k', '.+', \$keyid;
6811 defvalopt '--existing-package','', '.*', \$existing_package;
6812 defvalopt '--build-products-dir','','.*', \$buildproductsdir;
6813 defvalopt '--clean', '', $cleanmode_re, \$cleanmode;
6814 defvalopt '--package', '-p', $package_re, \$package;
6815 defvalopt '--quilt', '', $quilt_modes_re, \$quilt_mode;
6817 defvalopt '', '-C', '.+', sub {
6818 ($changesfile) = (@_);
6819 if ($changesfile =~ s#^(.*)/##) {
6820 $buildproductsdir = $1;
6824 defvalopt '--initiator-tempdir','','.*', sub {
6825 ($initiator_tempdir) = (@_);
6826 $initiator_tempdir =~ m#^/# or
6827 badusage "--initiator-tempdir must be used specify an".
6828 " absolute, not relative, directory."
6831 sub defoptmodes ($@) {
6832 my ($varref, $cfgkey, $default, %optmap) = @_;
6834 while (my ($opt,$val) = each %optmap) {
6835 $funcopts_long{$opt} = sub { $$varref = $val; };
6836 $permit{$val} = $val;
6838 push @modeopt_cfgs, {
6841 Default => $default,
6846 defoptmodes \$dodep14tag, qw( dep14tag want
6849 --always-dep14tag always );
6854 if (defined $ENV{'DGIT_SSH'}) {
6855 @ssh = string_to_ssh $ENV{'DGIT_SSH'};
6856 } elsif (defined $ENV{'GIT_SSH'}) {
6857 @ssh = ($ENV{'GIT_SSH'});
6865 if (!defined $val) {
6866 badusage "$what needs a value" unless @ARGV;
6868 push @rvalopts, $val;
6870 badusage "bad value \`$val' for $what" unless
6871 $val =~ m/^$oi->{Re}$(?!\n)/s;
6872 my $how = $oi->{How};
6873 if (ref($how) eq 'SCALAR') {
6878 push @ropts, @rvalopts;
6882 last unless $ARGV[0] =~ m/^-/;
6886 if (m/^--dry-run$/) {
6889 } elsif (m/^--damp-run$/) {
6892 } elsif (m/^--no-sign$/) {
6895 } elsif (m/^--help$/) {
6897 } elsif (m/^--version$/) {
6899 } elsif (m/^--new$/) {
6902 } elsif (m/^--([-0-9a-z]+)=(.+)/s &&
6903 ($om = $opts_opt_map{$1}) &&
6907 } elsif (m/^--([-0-9a-z]+):(.*)/s &&
6908 !$opts_opt_cmdonly{$1} &&
6909 ($om = $opts_opt_map{$1})) {
6912 } elsif (m/^--(gbp|dpm)$/s) {
6913 push @ropts, "--quilt=$1";
6915 } elsif (m/^--ignore-dirty$/s) {
6918 } elsif (m/^--no-quilt-fixup$/s) {
6920 $quilt_mode = 'nocheck';
6921 } elsif (m/^--no-rm-on-error$/s) {
6924 } elsif (m/^--no-chase-dsc-distro$/s) {
6926 $chase_dsc_distro = 0;
6927 } elsif (m/^--overwrite$/s) {
6929 $overwrite_version = '';
6930 } elsif (m/^--overwrite=(.+)$/s) {
6932 $overwrite_version = $1;
6933 } elsif (m/^--delayed=(\d+)$/s) {
6936 } elsif (m/^--dgit-view-save=(.+)$/s) {
6938 $split_brain_save = $1;
6939 $split_brain_save =~ s#^(?!refs/)#refs/heads/#;
6940 } elsif (m/^--(no-)?rm-old-changes$/s) {
6943 } elsif (m/^--deliberately-($deliberately_re)$/s) {
6945 push @deliberatelies, $&;
6946 } elsif (m/^--force-(.*)/ && defined $forceopts{$1}) {
6950 } elsif (m/^--force-/) {
6952 "$us: warning: ignoring unknown force option $_\n";
6954 } elsif (m/^--dgit-tag-format=(old|new)$/s) {
6955 # undocumented, for testing
6957 $tagformat_want = [ $1, 'command line', 1 ];
6958 # 1 menas overrides distro configuration
6959 } elsif (m/^--always-split-source-build$/s) {
6960 # undocumented, for testing
6962 $need_split_build_invocation = 1;
6963 } elsif (m/^--config-lookup-explode=(.+)$/s) {
6964 # undocumented, for testing
6966 $gitcfgs{cmdline}{$1} = 'CONFIG-LOOKUP-EXPLODE';
6967 # ^ it's supposed to be an array ref
6968 } elsif (m/^(--[-0-9a-z]+)(=|$)/ && ($oi = $valopts_long{$1})) {
6969 $val = $2 ? $' : undef; #';
6970 $valopt->($oi->{Long});
6971 } elsif ($funcopts_long{$_}) {
6973 $funcopts_long{$_}();
6975 badusage "unknown long option \`$_'";
6982 } elsif (s/^-L/-/) {
6985 } elsif (s/^-h/-/) {
6987 } elsif (s/^-D/-/) {
6991 } elsif (s/^-N/-/) {
6996 push @changesopts, $_;
6998 } elsif (s/^-wn$//s) {
7000 $cleanmode = 'none';
7001 } elsif (s/^-wg$//s) {
7004 } elsif (s/^-wgf$//s) {
7006 $cleanmode = 'git-ff';
7007 } elsif (s/^-wd$//s) {
7009 $cleanmode = 'dpkg-source';
7010 } elsif (s/^-wdd$//s) {
7012 $cleanmode = 'dpkg-source-d';
7013 } elsif (s/^-wc$//s) {
7015 $cleanmode = 'check';
7016 } elsif (s/^-c([^=]*)\=(.*)$//s) {
7017 push @git, '-c', $&;
7018 $gitcfgs{cmdline}{$1} = [ $2 ];
7019 } elsif (s/^-c([^=]+)$//s) {
7020 push @git, '-c', $&;
7021 $gitcfgs{cmdline}{$1} = [ 'true' ];
7022 } elsif (m/^-[a-zA-Z]/ && ($oi = $valopts_short{$&})) {
7024 $val = undef unless length $val;
7025 $valopt->($oi->{Short});
7028 badusage "unknown short option \`$_'";
7035 sub check_env_sanity () {
7036 my $blocked = new POSIX::SigSet;
7037 sigprocmask SIG_UNBLOCK, $blocked, $blocked or die $!;
7040 foreach my $name (qw(PIPE CHLD)) {
7041 my $signame = "SIG$name";
7042 my $signum = eval "POSIX::$signame" // die;
7043 ($SIG{$name} // 'DEFAULT') eq 'DEFAULT' or
7044 die "$signame is set to something other than SIG_DFL\n";
7045 $blocked->ismember($signum) and
7046 die "$signame is blocked\n";
7052 On entry to dgit, $@
7053 This is a bug produced by something in in your execution environment.
7059 sub parseopts_late_defaults () {
7060 $isuite //= cfg("dgit-distro.$idistro.default-suite", 'RETURN-UNDEF')
7061 if defined $idistro;
7062 $isuite //= cfg('dgit.default.default-suite');
7064 foreach my $k (keys %opts_opt_map) {
7065 my $om = $opts_opt_map{$k};
7067 my $v = access_cfg("cmd-$k", 'RETURN-UNDEF');
7069 badcfg "cannot set command for $k"
7070 unless length $om->[0];
7074 foreach my $c (access_cfg_cfgs("opts-$k")) {
7076 map { $_ ? @$_ : () }
7077 map { $gitcfgs{$_}{$c} }
7078 reverse @gitcfgsources;
7079 printdebug "CL $c ", (join " ", map { shellquote } @vl),
7080 "\n" if $debuglevel >= 4;
7082 badcfg "cannot configure options for $k"
7083 if $opts_opt_cmdonly{$k};
7084 my $insertpos = $opts_cfg_insertpos{$k};
7085 @$om = ( @$om[0..$insertpos-1],
7087 @$om[$insertpos..$#$om] );
7091 if (!defined $rmchanges) {
7092 local $access_forpush;
7093 $rmchanges = access_cfg_bool(0, 'rm-old-changes');
7096 if (!defined $quilt_mode) {
7097 local $access_forpush;
7098 $quilt_mode = cfg('dgit.force.quilt-mode', 'RETURN-UNDEF')
7099 // access_cfg('quilt-mode', 'RETURN-UNDEF')
7101 $quilt_mode =~ m/^($quilt_modes_re)$/
7102 or badcfg "unknown quilt-mode \`$quilt_mode'";
7106 foreach my $moc (@modeopt_cfgs) {
7107 local $access_forpush;
7108 my $vr = $moc->{Var};
7109 next if defined $$vr;
7110 $$vr = access_cfg($moc->{Key}, 'RETURN-UNDEF') // $moc->{Default};
7111 my $v = $moc->{Vals}{$$vr};
7112 badcfg "unknown $moc->{Key} setting \`$$vr'" unless defined $v;
7116 $need_split_build_invocation ||= quiltmode_splitbrain();
7118 if (!defined $cleanmode) {
7119 local $access_forpush;
7120 $cleanmode = access_cfg('clean-mode', 'RETURN-UNDEF');
7121 $cleanmode //= 'dpkg-source';
7123 badcfg "unknown clean-mode \`$cleanmode'" unless
7124 $cleanmode =~ m/^($cleanmode_re)$(?!\n)/s;
7128 if ($ENV{$fakeeditorenv}) {
7130 quilt_fixup_editor();
7136 print STDERR "DRY RUN ONLY\n" if $dryrun_level > 1;
7137 print STDERR "DAMP RUN - WILL MAKE LOCAL (UNSIGNED) CHANGES\n"
7138 if $dryrun_level == 1;
7140 print STDERR $helpmsg or die $!;
7143 $cmd = $subcommand = shift @ARGV;
7146 my $pre_fn = ${*::}{"pre_$cmd"};
7147 $pre_fn->() if $pre_fn;
7149 record_maindir if $invoked_in_git_tree;
7152 my $fn = ${*::}{"cmd_$cmd"};
7153 $fn or badusage "unknown operation $cmd";