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_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_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_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_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_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_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";
4460 } elsif ($sourconlypolicy eq 'never') {
4461 forceable_fail [qw(uploading-source-only)],
4462 "source-only upload, although distroy policy requires .debs";
4463 } elsif ($sourconlypolicy eq 'not-wholly-new') {
4465 my $have = archive_query('package_',
4467 # Perhaps adjust .dsc to contain right set of origs
4468 changes_update_origs_from_dsc($dsc, $changes, $upstreamversion,
4470 unless forceing [qw(changes-origs-exactly)];
4472 # Checks complete, we're going to try and go ahead:
4474 responder_send_file('changes',$changesfile);
4475 responder_send_command("param head $dgithead");
4476 responder_send_command("param csuite $csuite");
4477 responder_send_command("param isuite $isuite");
4478 responder_send_command("param tagformat $tagformat");
4479 if (defined $maintviewhead) {
4480 die unless ($protovsn//4) >= 4;
4481 responder_send_command("param maint-view $maintviewhead");
4484 # Perhaps send buildinfo(s) for signing
4485 my $changes_files = getfield $changes, 'Files';
4486 my @buildinfos = ($changes_files =~ m/ .* (\S+\.buildinfo)$/mg);
4487 foreach my $bi (@buildinfos) {
4488 responder_send_command("param buildinfo-filename $bi");
4489 responder_send_file('buildinfo', "$buildproductsdir/$bi");
4492 if (deliberately_not_fast_forward) {
4493 git_for_each_ref(lrfetchrefs, sub {
4494 my ($objid,$objtype,$lrfetchrefname,$reftail) = @_;
4495 my $rrefname= substr($lrfetchrefname, length(lrfetchrefs) + 1);
4496 responder_send_command("previously $rrefname=$objid");
4497 $previously{$rrefname} = $objid;
4501 my @tagwants = push_tagwants($cversion, $dgithead, $maintviewhead,
4502 dgit_privdir()."/tag");
4505 supplementary_message(<<'END');
4506 Push failed, while signing the tag.
4507 You can retry the push, after fixing the problem, if you like.
4509 # If we manage to sign but fail to record it anywhere, it's fine.
4510 if ($we_are_responder) {
4511 @tagobjfns = map { $_->{Tfn}('.signed-tmp') } @tagwants;
4512 responder_receive_files('signed-tag', @tagobjfns);
4514 @tagobjfns = push_mktags($clogp,$dscpath,
4515 $changesfile,$changesfile,
4518 supplementary_message(<<'END');
4519 Push failed, *after* signing the tag.
4520 If you want to try again, you should use a new version number.
4523 pairwise { $a->{TagObjFn} = $b } @tagwants, @tagobjfns;
4525 foreach my $tw (@tagwants) {
4526 my $tag = $tw->{Tag};
4527 my $tagobjfn = $tw->{TagObjFn};
4529 cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
4530 runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
4531 runcmd_ordryrun_local
4532 @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
4535 supplementary_message(<<'END');
4536 Push failed, while updating the remote git repository - see messages above.
4537 If you want to try again, you should use a new version number.
4539 if (!check_for_git()) {
4540 create_remote_git_repo();
4543 my @pushrefs = $forceflag.$dgithead.":".rrref();
4544 foreach my $tw (@tagwants) {
4545 push @pushrefs, $forceflag."refs/tags/$tw->{Tag}";
4548 runcmd_ordryrun @git,
4549 qw(-c push.followTags=false push), access_giturl(), @pushrefs;
4550 runcmd_ordryrun git_update_ref_cmd 'dgit push', lrref(), $dgithead;
4552 supplementary_message(<<'END');
4553 Push failed, while obtaining signatures on the .changes and .dsc.
4554 If it was just that the signature failed, you may try again by using
4555 debsign by hand to sign the changes
4557 and then dput to complete the upload.
4558 If you need to change the package, you must use a new version number.
4560 if ($we_are_responder) {
4561 my $dryrunsuffix = act_local() ? "" : ".tmp";
4562 my @rfiles = ($dscpath, $changesfile);
4563 push @rfiles, map { "$buildproductsdir/$_" } @buildinfos;
4564 responder_receive_files('signed-dsc-changes',
4565 map { "$_$dryrunsuffix" } @rfiles);
4568 rename "$dscpath.tmp",$dscpath or die "$dscfn $!";
4570 progress "[new .dsc left in $dscpath.tmp]";
4572 sign_changes $changesfile;
4575 supplementary_message(<<END);
4576 Push failed, while uploading package(s) to the archive server.
4577 You can retry the upload of exactly these same files with dput of:
4579 If that .changes file is broken, you will need to use a new version
4580 number for your next attempt at the upload.
4582 my $host = access_cfg('upload-host','RETURN-UNDEF');
4583 my @hostarg = defined($host) ? ($host,) : ();
4584 runcmd_ordryrun @dput, @hostarg, $changesfile;
4585 printdone "pushed and uploaded $cversion";
4587 supplementary_message('');
4588 responder_send_command("complete");
4592 not_necessarily_a_tree();
4597 badusage "-p is not allowed with clone; specify as argument instead"
4598 if defined $package;
4601 } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
4602 ($package,$isuite) = @ARGV;
4603 } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
4604 ($package,$dstdir) = @ARGV;
4605 } elsif (@ARGV==3) {
4606 ($package,$isuite,$dstdir) = @ARGV;
4608 badusage "incorrect arguments to dgit clone";
4612 $dstdir ||= "$package";
4613 if (stat_exists $dstdir) {
4614 fail "$dstdir already exists";
4618 if ($rmonerror && !$dryrun_level) {
4619 $cwd_remove= getcwd();
4621 return unless defined $cwd_remove;
4622 if (!chdir "$cwd_remove") {
4623 return if $!==&ENOENT;
4624 die "chdir $cwd_remove: $!";
4626 printdebug "clone rmonerror removing $dstdir\n";
4628 rmtree($dstdir) or die "remove $dstdir: $!\n";
4629 } elsif (grep { $! == $_ }
4630 (ENOENT, ENOTDIR, EACCES, EPERM, ELOOP)) {
4632 print STDERR "check whether to remove $dstdir: $!\n";
4638 $cwd_remove = undef;
4641 sub branchsuite () {
4642 my $branch = git_get_symref();
4643 if (defined $branch && $branch =~ m#$lbranch_re#o) {
4650 sub package_from_d_control () {
4651 if (!defined $package) {
4652 my $sourcep = parsecontrol('debian/control','debian/control');
4653 $package = getfield $sourcep, 'Source';
4657 sub fetchpullargs () {
4658 package_from_d_control();
4660 $isuite = branchsuite();
4662 my $clogp = parsechangelog();
4663 my $clogsuite = getfield $clogp, 'Distribution';
4664 $isuite= $clogsuite if $clogsuite ne 'UNRELEASED';
4666 } elsif (@ARGV==1) {
4669 badusage "incorrect arguments to dgit fetch or dgit pull";
4683 if (quiltmode_splitbrain()) {
4684 my ($format, $fopts) = get_source_format();
4685 madformat($format) and fail <<END
4686 dgit pull not yet supported in split view mode (--quilt=$quilt_mode)
4694 package_from_d_control();
4695 @ARGV==1 or badusage "dgit checkout needs a suite argument";
4699 foreach my $canon (qw(0 1)) {
4704 canonicalise_suite();
4706 if (length git_get_ref lref()) {
4707 # local branch already exists, yay
4710 if (!length git_get_ref lrref()) {
4718 runcmd (@git, qw(update-ref), lref(), lrref(), '');
4721 local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
4722 "dgit checkout $isuite";
4723 runcmd (@git, qw(checkout), lref());
4726 sub cmd_update_vcs_git () {
4728 if (@ARGV==0 || $ARGV[0] =~ m/^-/) {
4729 ($specsuite,) = split /\;/, cfg 'dgit.vcs-git.suites';
4731 ($specsuite) = (@ARGV);
4736 if ($ARGV[0] eq '-') {
4738 } elsif ($ARGV[0] eq '-') {
4743 package_from_d_control();
4745 if ($specsuite eq '.') {
4746 $ctrl = parsecontrol 'debian/control', 'debian/control';
4748 $isuite = $specsuite;
4752 my $url = getfield $ctrl, 'Vcs-Git';
4755 my $orgurl = cfg 'remote.vcs-git.url', 'RETURN-UNDEF';
4756 if (!defined $orgurl) {
4757 print STDERR "setting up vcs-git: $url\n";
4758 @cmd = (@git, qw(remote add vcs-git), $url);
4759 } elsif ($orgurl eq $url) {
4760 print STDERR "vcs git already configured: $url\n";
4762 print STDERR "changing vcs-git url to: $url\n";
4763 @cmd = (@git, qw(remote set-url vcs-git), $url);
4765 runcmd_ordryrun_local @cmd;
4767 print "fetching (@ARGV)\n";
4768 runcmd_ordryrun_local @git, qw(fetch vcs-git), @ARGV;
4774 build_or_push_prep_early();
4779 } elsif (@ARGV==1) {
4780 ($specsuite) = (@ARGV);
4782 badusage "incorrect arguments to dgit $subcommand";
4785 local ($package) = $existing_package; # this is a hack
4786 canonicalise_suite();
4788 canonicalise_suite();
4790 if (defined $specsuite &&
4791 $specsuite ne $isuite &&
4792 $specsuite ne $csuite) {
4793 fail "dgit $subcommand: changelog specifies $isuite ($csuite)".
4794 " but command line specifies $specsuite";
4803 sub cmd_push_source {
4806 my $changes = parsecontrol("$buildproductsdir/$changesfile",
4807 "source changes file");
4808 unless (test_source_only_changes($changes)) {
4809 fail "user-specified changes file is not source-only";
4812 # Building a source package is very fast, so just do it
4813 build_source_for_push();
4818 #---------- remote commands' implementation ----------
4820 sub pre_remote_push_build_host {
4821 my ($nrargs) = shift @ARGV;
4822 my (@rargs) = @ARGV[0..$nrargs-1];
4823 @ARGV = @ARGV[$nrargs..$#ARGV];
4825 my ($dir,$vsnwant) = @rargs;
4826 # vsnwant is a comma-separated list; we report which we have
4827 # chosen in our ready response (so other end can tell if they
4830 $we_are_responder = 1;
4831 $us .= " (build host)";
4833 open PI, "<&STDIN" or die $!;
4834 open STDIN, "/dev/null" or die $!;
4835 open PO, ">&STDOUT" or die $!;
4837 open STDOUT, ">&STDERR" or die $!;
4841 ($protovsn) = grep {
4842 $vsnwant =~ m{^(?:.*,)?$_(?:,.*)?$}
4843 } @rpushprotovsn_support;
4845 fail "build host has dgit rpush protocol versions ".
4846 (join ",", @rpushprotovsn_support).
4847 " but invocation host has $vsnwant"
4848 unless defined $protovsn;
4852 sub cmd_remote_push_build_host {
4853 responder_send_command("dgit-remote-push-ready $protovsn");
4857 sub pre_remote_push_responder { pre_remote_push_build_host(); }
4858 sub cmd_remote_push_responder { cmd_remote_push_build_host(); }
4859 # ... for compatibility with proto vsn.1 dgit (just so that user gets
4860 # a good error message)
4862 sub rpush_handle_protovsn_bothends () {
4863 if ($protovsn < 4) {
4864 need_tagformat 'old', "rpush negotiated protocol $protovsn";
4873 my $report = i_child_report();
4874 if (defined $report) {
4875 printdebug "($report)\n";
4876 } elsif ($i_child_pid) {
4877 printdebug "(killing build host child $i_child_pid)\n";
4878 kill 15, $i_child_pid;
4880 if (defined $i_tmp && !defined $initiator_tempdir) {
4882 eval { rmtree $i_tmp; };
4887 return unless forkcheck_mainprocess();
4892 my ($base,$selector,@args) = @_;
4893 $selector =~ s/\-/_/g;
4894 { no strict qw(refs); &{"${base}_${selector}"}(@args); }
4898 not_necessarily_a_tree();
4903 if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
4911 push @rargs, join ",", @rpushprotovsn_support;
4914 push @rdgit, @ropts;
4915 push @rdgit, qw(remote-push-build-host), (scalar @rargs), @rargs;
4917 my @cmd = (@ssh, $host, shellquote @rdgit);
4920 $we_are_initiator=1;
4922 if (defined $initiator_tempdir) {
4923 rmtree $initiator_tempdir;
4924 mkdir $initiator_tempdir, 0700 or die "$initiator_tempdir: $!";
4925 $i_tmp = $initiator_tempdir;
4929 $i_child_pid = open2(\*RO, \*RI, @cmd);
4931 ($protovsn) = initiator_expect { m/^dgit-remote-push-ready (\S+)/ };
4932 die "$protovsn ?" unless grep { $_ eq $protovsn } @rpushprotovsn_support;
4933 $supplementary_message = '' unless $protovsn >= 3;
4936 my ($icmd,$iargs) = initiator_expect {
4937 m/^(\S+)(?: (.*))?$/;
4940 i_method "i_resp", $icmd, $iargs;
4944 sub i_resp_progress ($) {
4946 my $msg = protocol_read_bytes \*RO, $rhs;
4950 sub i_resp_supplementary_message ($) {
4952 $supplementary_message = protocol_read_bytes \*RO, $rhs;
4955 sub i_resp_complete {
4956 my $pid = $i_child_pid;
4957 $i_child_pid = undef; # prevents killing some other process with same pid
4958 printdebug "waiting for build host child $pid...\n";
4959 my $got = waitpid $pid, 0;
4960 die $! unless $got == $pid;
4961 die "build host child failed $?" if $?;
4964 printdebug "all done\n";
4968 sub i_resp_file ($) {
4970 my $localname = i_method "i_localname", $keyword;
4971 my $localpath = "$i_tmp/$localname";
4972 stat_exists $localpath and
4973 badproto \*RO, "file $keyword ($localpath) twice";
4974 protocol_receive_file \*RO, $localpath;
4975 i_method "i_file", $keyword;
4980 sub i_resp_param ($) {
4981 $_[0] =~ m/^(\S+) (.*)$/ or badproto \*RO, "bad param spec";
4985 sub i_resp_previously ($) {
4986 $_[0] =~ m#^(refs/tags/\S+)=(\w+)$#
4987 or badproto \*RO, "bad previously spec";
4988 my $r = system qw(git check-ref-format), $1;
4989 die "bad previously ref spec ($r)" if $r;
4990 $previously{$1} = $2;
4995 sub i_resp_want ($) {
4997 die "$keyword ?" if $i_wanted{$keyword}++;
4999 defined $i_param{'csuite'} or badproto \*RO, "premature desire, no csuite";
5000 $isuite = $i_param{'isuite'} // $i_param{'csuite'};
5001 die unless $isuite =~ m/^$suite_re$/;
5004 rpush_handle_protovsn_bothends();
5006 fail "rpush negotiated protocol version $protovsn".
5007 " which does not support quilt mode $quilt_mode"
5008 if quiltmode_splitbrain;
5010 my @localpaths = i_method "i_want", $keyword;
5011 printdebug "[[ $keyword @localpaths\n";
5012 foreach my $localpath (@localpaths) {
5013 protocol_send_file \*RI, $localpath;
5015 print RI "files-end\n" or die $!;
5018 our ($i_clogp, $i_version, $i_dscfn, $i_changesfn, @i_buildinfos);
5020 sub i_localname_parsed_changelog {
5021 return "remote-changelog.822";
5023 sub i_file_parsed_changelog {
5024 ($i_clogp, $i_version, $i_dscfn) =
5025 push_parse_changelog "$i_tmp/remote-changelog.822";
5026 die if $i_dscfn =~ m#/|^\W#;
5029 sub i_localname_dsc {
5030 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
5035 sub i_localname_buildinfo ($) {
5036 my $bi = $i_param{'buildinfo-filename'};
5037 defined $bi or badproto \*RO, "buildinfo before filename";
5038 defined $i_changesfn or badproto \*RO, "buildinfo before changes";
5039 $bi =~ m{^\Q$package\E_[!-.0-~]*\.buildinfo$}s
5040 or badproto \*RO, "improper buildinfo filename";
5043 sub i_file_buildinfo {
5044 my $bi = $i_param{'buildinfo-filename'};
5045 my $bd = parsecontrol "$i_tmp/$bi", $bi;
5046 my $ch = parsecontrol "$i_tmp/$i_changesfn", 'changes';
5047 if (!forceing [qw(buildinfo-changes-mismatch)]) {
5048 files_compare_inputs($bd, $ch);
5049 (getfield $bd, $_) eq (getfield $ch, $_) or
5050 fail "buildinfo mismatch $_"
5051 foreach qw(Source Version);
5052 !defined $bd->{$_} or
5053 fail "buildinfo contains $_"
5054 foreach qw(Changes Changed-by Distribution);
5056 push @i_buildinfos, $bi;
5057 delete $i_param{'buildinfo-filename'};
5060 sub i_localname_changes {
5061 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
5062 $i_changesfn = $i_dscfn;
5063 $i_changesfn =~ s/\.dsc$/_dgit.changes/ or die;
5064 return $i_changesfn;
5066 sub i_file_changes { }
5068 sub i_want_signed_tag {
5069 printdebug Dumper(\%i_param, $i_dscfn);
5070 defined $i_param{'head'} && defined $i_dscfn && defined $i_clogp
5071 && defined $i_param{'csuite'}
5072 or badproto \*RO, "premature desire for signed-tag";
5073 my $head = $i_param{'head'};
5074 die if $head =~ m/[^0-9a-f]/ || $head !~ m/^../;
5076 my $maintview = $i_param{'maint-view'};
5077 die if defined $maintview && $maintview =~ m/[^0-9a-f]/;
5080 if ($protovsn >= 4) {
5081 my $p = $i_param{'tagformat'} // '<undef>';
5083 or badproto \*RO, "tag format mismatch: $p vs. $tagformat";
5086 die unless $i_param{'csuite'} =~ m/^$suite_re$/;
5088 push_parse_dsc $i_dscfn, 'remote dsc', $i_version;
5090 my @tagwants = push_tagwants $i_version, $head, $maintview, "tag";
5093 push_mktags $i_clogp, $i_dscfn,
5094 $i_changesfn, 'remote changes',
5098 sub i_want_signed_dsc_changes {
5099 rename "$i_dscfn.tmp","$i_dscfn" or die "$i_dscfn $!";
5100 sign_changes $i_changesfn;
5101 return ($i_dscfn, $i_changesfn, @i_buildinfos);
5104 #---------- building etc. ----------
5110 #----- `3.0 (quilt)' handling -----
5112 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
5114 sub quiltify_dpkg_commit ($$$;$) {
5115 my ($patchname,$author,$msg, $xinfo) = @_;
5118 mkpath '.git/dgit'; # we are in playtree
5119 my $descfn = ".git/dgit/quilt-description.tmp";
5120 open O, '>', $descfn or die "$descfn: $!";
5121 $msg =~ s/\n+/\n\n/;
5122 print O <<END or die $!;
5124 ${xinfo}Subject: $msg
5131 local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
5132 local $ENV{'VISUAL'} = $ENV{'EDITOR'};
5133 local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
5134 runcmd @dpkgsource, qw(--commit --include-removal .), $patchname;
5138 sub quiltify_trees_differ ($$;$$$) {
5139 my ($x,$y,$finegrained,$ignorenamesr,$unrepres) = @_;
5140 # returns true iff the two tree objects differ other than in debian/
5141 # with $finegrained,
5142 # returns bitmask 01 - differ in upstream files except .gitignore
5143 # 02 - differ in .gitignore
5144 # if $ignorenamesr is defined, $ingorenamesr->{$fn}
5145 # is set for each modified .gitignore filename $fn
5146 # if $unrepres is defined, array ref to which is appeneded
5147 # a list of unrepresentable changes (removals of upstream files
5150 my @cmd = (@git, qw(diff-tree -z --no-renames));
5151 push @cmd, qw(--name-only) unless $unrepres;
5152 push @cmd, qw(-r) if $finegrained || $unrepres;
5154 my $diffs= cmdoutput @cmd;
5157 foreach my $f (split /\0/, $diffs) {
5158 if ($unrepres && !@lmodes) {
5159 @lmodes = $f =~ m/^\:(\w+) (\w+) \w+ \w+ / or die "$_ ?";
5162 my ($oldmode,$newmode) = @lmodes;
5165 next if $f =~ m#^debian(?:/.*)?$#s;
5169 die "not a plain file or symlink\n"
5170 unless $newmode =~ m/^(?:10|12)\d{4}$/ ||
5171 $oldmode =~ m/^(?:10|12)\d{4}$/;
5172 if ($oldmode =~ m/[^0]/ &&
5173 $newmode =~ m/[^0]/) {
5174 # both old and new files exist
5175 die "mode or type changed\n" if $oldmode ne $newmode;
5176 die "modified symlink\n" unless $newmode =~ m/^10/;
5177 } elsif ($oldmode =~ m/[^0]/) {
5179 die "deletion of symlink\n"
5180 unless $oldmode =~ m/^10/;
5183 die "creation with non-default mode\n"
5184 unless $newmode =~ m/^100644$/ or
5185 $newmode =~ m/^120000$/;
5189 local $/="\n"; chomp $@;
5190 push @$unrepres, [ $f, "$@ ($oldmode->$newmode)" ];
5194 my $isignore = $f =~ m#^(?:.*/)?.gitignore$#s;
5195 $r |= $isignore ? 02 : 01;
5196 $ignorenamesr->{$f}=1 if $ignorenamesr && $isignore;
5198 printdebug "quiltify_trees_differ $x $y => $r\n";
5202 sub quiltify_tree_sentinelfiles ($) {
5203 # lists the `sentinel' files present in the tree
5205 my $r = cmdoutput @git, qw(ls-tree --name-only), $x,
5206 qw(-- debian/rules debian/control);
5211 sub quiltify_splitbrain_needed () {
5212 if (!$split_brain) {
5213 progress "dgit view: changes are required...";
5214 runcmd @git, qw(checkout -q -b dgit-view);
5219 sub quiltify_splitbrain ($$$$$$$) {
5220 my ($clogp, $unapplied, $headref, $oldtiptree, $diffbits,
5221 $editedignores, $cachekey) = @_;
5222 my $gitignore_special = 1;
5223 if ($quilt_mode !~ m/gbp|dpm/) {
5224 # treat .gitignore just like any other upstream file
5225 $diffbits = { %$diffbits };
5226 $_ = !!$_ foreach values %$diffbits;
5227 $gitignore_special = 0;
5229 # We would like any commits we generate to be reproducible
5230 my @authline = clogp_authline($clogp);
5231 local $ENV{GIT_COMMITTER_NAME} = $authline[0];
5232 local $ENV{GIT_COMMITTER_EMAIL} = $authline[1];
5233 local $ENV{GIT_COMMITTER_DATE} = $authline[2];
5234 local $ENV{GIT_AUTHOR_NAME} = $authline[0];
5235 local $ENV{GIT_AUTHOR_EMAIL} = $authline[1];
5236 local $ENV{GIT_AUTHOR_DATE} = $authline[2];
5238 my $fulldiffhint = sub {
5240 my $cmd = "git diff $x $y -- :/ ':!debian'";
5241 $cmd .= " ':!/.gitignore' ':!*/.gitignore'" if $gitignore_special;
5242 return "\nFor full diff showing the problem(s), type:\n $cmd\n";
5245 if ($quilt_mode =~ m/gbp|unapplied/ &&
5246 ($diffbits->{O2H} & 01)) {
5248 "--quilt=$quilt_mode specified, implying patches-unapplied git tree\n".
5249 " but git tree differs from orig in upstream files.";
5250 $msg .= $fulldiffhint->($unapplied, 'HEAD');
5251 if (!stat_exists "debian/patches") {
5253 "\n ... debian/patches is missing; perhaps this is a patch queue branch?";
5257 if ($quilt_mode =~ m/dpm/ &&
5258 ($diffbits->{H2A} & 01)) {
5259 fail <<END. $fulldiffhint->($oldtiptree,'HEAD');
5260 --quilt=$quilt_mode specified, implying patches-applied git tree
5261 but git tree differs from result of applying debian/patches to upstream
5264 if ($quilt_mode =~ m/gbp|unapplied/ &&
5265 ($diffbits->{O2A} & 01)) { # some patches
5266 quiltify_splitbrain_needed();
5267 progress "dgit view: creating patches-applied version using gbp pq";
5268 runcmd shell_cmd 'exec >/dev/null', gbp_pq, qw(import);
5269 # gbp pq import creates a fresh branch; push back to dgit-view
5270 runcmd @git, qw(update-ref refs/heads/dgit-view HEAD);
5271 runcmd @git, qw(checkout -q dgit-view);
5273 if ($quilt_mode =~ m/gbp|dpm/ &&
5274 ($diffbits->{O2A} & 02)) {
5276 --quilt=$quilt_mode specified, implying that HEAD is for use with a
5277 tool which does not create patches for changes to upstream
5278 .gitignores: but, such patches exist in debian/patches.
5281 if (($diffbits->{O2H} & 02) && # user has modified .gitignore
5282 !($diffbits->{O2A} & 02)) { # patches do not change .gitignore
5283 quiltify_splitbrain_needed();
5284 progress "dgit view: creating patch to represent .gitignore changes";
5285 ensuredir "debian/patches";
5286 my $gipatch = "debian/patches/auto-gitignore";
5287 open GIPATCH, ">>", "$gipatch" or die "$gipatch: $!";
5288 stat GIPATCH or die "$gipatch: $!";
5289 fail "$gipatch already exists; but want to create it".
5290 " to record .gitignore changes" if (stat _)[7];
5291 print GIPATCH <<END or die "$gipatch: $!";
5292 Subject: Update .gitignore from Debian packaging branch
5294 The Debian packaging git branch contains these updates to the upstream
5295 .gitignore file(s). This patch is autogenerated, to provide these
5296 updates to users of the official Debian archive view of the package.
5298 [dgit ($our_version) update-gitignore]
5301 close GIPATCH or die "$gipatch: $!";
5302 runcmd shell_cmd "exec >>$gipatch", @git, qw(diff),
5303 $unapplied, $headref, "--", sort keys %$editedignores;
5304 open SERIES, "+>>", "debian/patches/series" or die $!;
5305 defined seek SERIES, -1, 2 or $!==EINVAL or die $!;
5307 defined read SERIES, $newline, 1 or die $!;
5308 print SERIES "\n" or die $! unless $newline eq "\n";
5309 print SERIES "auto-gitignore\n" or die $!;
5310 close SERIES or die $!;
5311 runcmd @git, qw(add -- debian/patches/series), $gipatch;
5313 Commit patch to update .gitignore
5315 [dgit ($our_version) update-gitignore-quilt-fixup]
5319 my $dgitview = git_rev_parse 'HEAD';
5322 # When we no longer need to support squeeze, use --create-reflog
5324 ensuredir "$maindir_gitcommon/logs/refs/dgit-intern";
5325 my $makelogfh = new IO::File "$maindir_gitcommon/logs/refs/$splitbraincache", '>>'
5328 my $oldcache = git_get_ref "refs/$splitbraincache";
5329 if ($oldcache eq $dgitview) {
5330 my $tree = cmdoutput qw(git rev-parse), "$dgitview:";
5331 # git update-ref doesn't always update, in this case. *sigh*
5332 my $dummy = make_commit_text <<END;
5335 author Dgit <dgit\@example.com> 1000000000 +0000
5336 committer Dgit <dgit\@example.com> 1000000000 +0000
5338 Dummy commit - do not use
5340 runcmd @git, qw(update-ref -m), "dgit $our_version - dummy",
5341 "refs/$splitbraincache", $dummy;
5343 runcmd @git, qw(update-ref -m), $cachekey, "refs/$splitbraincache",
5346 changedir "$playground/work";
5348 my $saved = maybe_split_brain_save $headref, $dgitview, "converted";
5349 progress "dgit view: created ($saved)";
5352 sub quiltify ($$$$) {
5353 my ($clogp,$target,$oldtiptree,$failsuggestion) = @_;
5355 # Quilt patchification algorithm
5357 # We search backwards through the history of the main tree's HEAD
5358 # (T) looking for a start commit S whose tree object is identical
5359 # to to the patch tip tree (ie the tree corresponding to the
5360 # current dpkg-committed patch series). For these purposes
5361 # `identical' disregards anything in debian/ - this wrinkle is
5362 # necessary because dpkg-source treates debian/ specially.
5364 # We can only traverse edges where at most one of the ancestors'
5365 # trees differs (in changes outside in debian/). And we cannot
5366 # handle edges which change .pc/ or debian/patches. To avoid
5367 # going down a rathole we avoid traversing edges which introduce
5368 # debian/rules or debian/control. And we set a limit on the
5369 # number of edges we are willing to look at.
5371 # If we succeed, we walk forwards again. For each traversed edge
5372 # PC (with P parent, C child) (starting with P=S and ending with
5373 # C=T) to we do this:
5375 # - dpkg-source --commit with a patch name and message derived from C
5376 # After traversing PT, we git commit the changes which
5377 # should be contained within debian/patches.
5379 # The search for the path S..T is breadth-first. We maintain a
5380 # todo list containing search nodes. A search node identifies a
5381 # commit, and looks something like this:
5383 # Commit => $git_commit_id,
5384 # Child => $c, # or undef if P=T
5385 # Whynot => $reason_edge_PC_unsuitable, # in @nots only
5386 # Nontrivial => true iff $p..$c has relevant changes
5393 my %considered; # saves being exponential on some weird graphs
5395 my $t_sentinels = quiltify_tree_sentinelfiles $target;
5398 my ($search,$whynot) = @_;
5399 printdebug " search NOT $search->{Commit} $whynot\n";
5400 $search->{Whynot} = $whynot;
5401 push @nots, $search;
5402 no warnings qw(exiting);
5411 my $c = shift @todo;
5412 next if $considered{$c->{Commit}}++;
5414 $not->($c, "maximum search space exceeded") if --$max_work <= 0;
5416 printdebug "quiltify investigate $c->{Commit}\n";
5419 if (!quiltify_trees_differ $c->{Commit}, $oldtiptree) {
5420 printdebug " search finished hooray!\n";
5425 quiltify_nofix_bail " $c->{Commit}", " (tree object $oldtiptree)";
5426 if ($quilt_mode eq 'smash') {
5427 printdebug " search quitting smash\n";
5431 my $c_sentinels = quiltify_tree_sentinelfiles $c->{Commit};
5432 $not->($c, "has $c_sentinels not $t_sentinels")
5433 if $c_sentinels ne $t_sentinels;
5435 my $commitdata = cmdoutput @git, qw(cat-file commit), $c->{Commit};
5436 $commitdata =~ m/\n\n/;
5438 my @parents = ($commitdata =~ m/^parent (\w+)$/gm);
5439 @parents = map { { Commit => $_, Child => $c } } @parents;
5441 $not->($c, "root commit") if !@parents;
5443 foreach my $p (@parents) {
5444 $p->{Nontrivial}= quiltify_trees_differ $p->{Commit},$c->{Commit};
5446 my $ndiffers = grep { $_->{Nontrivial} } @parents;
5447 $not->($c, "merge ($ndiffers nontrivial parents)") if $ndiffers > 1;
5449 foreach my $p (@parents) {
5450 printdebug "considering C=$c->{Commit} P=$p->{Commit}\n";
5452 my @cmd= (@git, qw(diff-tree -r --name-only),
5453 $p->{Commit},$c->{Commit}, qw(-- debian/patches .pc));
5454 my $patchstackchange = cmdoutput @cmd;
5455 if (length $patchstackchange) {
5456 $patchstackchange =~ s/\n/,/g;
5457 $not->($p, "changed $patchstackchange");
5460 printdebug " search queue P=$p->{Commit} ",
5461 ($p->{Nontrivial} ? "NT" : "triv"),"\n";
5467 printdebug "quiltify want to smash\n";
5470 my $x = $_[0]{Commit};
5471 $x =~ s/(.*?[0-9a-z]{8})[0-9a-z]*$/$1/;
5474 my $reportnot = sub {
5476 my $s = $abbrev->($notp);
5477 my $c = $notp->{Child};
5478 $s .= "..".$abbrev->($c) if $c;
5479 $s .= ": ".$notp->{Whynot};
5482 if ($quilt_mode eq 'linear') {
5483 print STDERR "\n$us: error: quilt fixup cannot be linear. Stopped at:\n";
5484 foreach my $notp (@nots) {
5485 print STDERR "$us: ", $reportnot->($notp), "\n";
5487 print STDERR "$us: $_\n" foreach @$failsuggestion;
5489 "quilt history linearisation failed. Search \`quilt fixup' in dgit(7).\n".
5490 "Use dpkg-source --commit by hand; or, --quilt=smash for one ugly patch";
5491 } elsif ($quilt_mode eq 'smash') {
5492 } elsif ($quilt_mode eq 'auto') {
5493 progress "quilt fixup cannot be linear, smashing...";
5495 die "$quilt_mode ?";
5498 my $time = $ENV{'GIT_COMMITTER_DATE'} || time;
5499 $time =~ s/\s.*//; # trim timezone from GIT_COMMITTER_DATE
5501 my $msg = cmdoutput @git, qw(log), "-n$ncommits";
5503 quiltify_dpkg_commit "auto-$version-$target-$time",
5504 (getfield $clogp, 'Maintainer'),
5505 "Automatically generated patch ($clogp->{Version})\n".
5506 "Last (up to) $ncommits git changes, FYI:\n\n". $msg;
5510 progress "quiltify linearisation planning successful, executing...";
5512 for (my $p = $sref_S;
5513 my $c = $p->{Child};
5515 printdebug "quiltify traverse $p->{Commit}..$c->{Commit}\n";
5516 next unless $p->{Nontrivial};
5518 my $cc = $c->{Commit};
5520 my $commitdata = cmdoutput @git, qw(cat-file commit), $cc;
5521 $commitdata =~ m/\n\n/ or die "$c ?";
5524 $commitdata =~ m/^author (.*) \d+ [-+0-9]+$/m or die "$cc ?";
5527 my $commitdate = cmdoutput
5528 @git, qw(log -n1 --pretty=format:%aD), $cc;
5530 $msg =~ s/^(.*)\n*/$1\n/ or die "$cc $msg ?";
5532 my $strip_nls = sub { $msg =~ s/\n+$//; $msg .= "\n"; };
5539 my $gbp_check_suitable = sub {
5544 die "contains unexpected slashes\n" if m{//} || m{/$};
5545 die "contains leading punctuation\n" if m{^\W} || m{/\W};
5546 die "contains bad character(s)\n" if m{[^-a-z0-9_.+=~/]}i;
5547 die "is series file\n" if m{$series_filename_re}o;
5548 die "too long" if length > 200;
5550 return $_ unless $@;
5551 print STDERR "quiltifying commit $cc:".
5552 " ignoring/dropping Gbp-Pq $what: $@";
5556 if ($msg =~ s/^ (?: gbp(?:-pq)? : \s* name \s+ |
5558 (\S+) \s* \n //ixm) {
5559 $patchname = $gbp_check_suitable->($1, 'Name');
5561 if ($msg =~ s/^ (?: gbp(?:-pq)? : \s* topic \s+ |
5563 (\S+) \s* \n //ixm) {
5564 $patchdir = $gbp_check_suitable->($1, 'Topic');
5569 if (!defined $patchname) {
5570 $patchname = $title;
5571 $patchname =~ s/[.:]$//;
5574 my $converter = new Text::Iconv qw(UTF-8 ASCII//TRANSLIT);
5575 my $translitname = $converter->convert($patchname);
5576 die unless defined $translitname;
5577 $patchname = $translitname;
5580 "dgit: patch title transliteration error: $@"
5582 $patchname =~ y/ A-Z/-a-z/;
5583 $patchname =~ y/-a-z0-9_.+=~//cd;
5584 $patchname =~ s/^\W/x-$&/;
5585 $patchname = substr($patchname,0,40);
5586 $patchname .= ".patch";
5588 if (!defined $patchdir) {
5591 if (length $patchdir) {
5592 $patchname = "$patchdir/$patchname";
5594 if ($patchname =~ m{^(.*)/}) {
5595 mkpath "debian/patches/$1";
5600 stat "debian/patches/$patchname$index";
5602 $!==ENOENT or die "$patchname$index $!";
5604 runcmd @git, qw(checkout -q), $cc;
5606 # We use the tip's changelog so that dpkg-source doesn't
5607 # produce complaining messages from dpkg-parsechangelog. None
5608 # of the information dpkg-source gets from the changelog is
5609 # actually relevant - it gets put into the original message
5610 # which dpkg-source provides our stunt editor, and then
5612 runcmd @git, qw(checkout -q), $target, qw(debian/changelog);
5614 quiltify_dpkg_commit "$patchname$index", $author, $msg,
5615 "Date: $commitdate\n".
5616 "X-Dgit-Generated: $clogp->{Version} $cc\n";
5618 runcmd @git, qw(checkout -q), $cc, qw(debian/changelog);
5621 runcmd @git, qw(checkout -q master);
5624 sub build_maybe_quilt_fixup () {
5625 my ($format,$fopts) = get_source_format;
5626 return unless madformat_wantfixup $format;
5629 check_for_vendor_patches();
5631 if (quiltmode_splitbrain) {
5632 fail <<END unless access_cfg_tagformats_can_splitbrain;
5633 quilt mode $quilt_mode requires split view so server needs to support
5634 both "new" and "maint" tag formats, but config says it doesn't.
5638 my $clogp = parsechangelog();
5639 my $headref = git_rev_parse('HEAD');
5640 my $symref = git_get_symref();
5642 if ($quilt_mode eq 'linear'
5643 && !$fopts->{'single-debian-patch'}
5644 && branch_is_gdr($symref, $headref)) {
5645 # This is much faster. It also makes patches that gdr
5646 # likes better for future updates without laundering.
5648 # However, it can fail in some casses where we would
5649 # succeed: if there are existing patches, which correspond
5650 # to a prefix of the branch, but are not in gbp/gdr
5651 # format, gdr will fail (exiting status 7), but we might
5652 # be able to figure out where to start linearising. That
5653 # will be slower so hopefully there's not much to do.
5654 my @cmd = (@git_debrebase,
5655 qw(--noop-ok -funclean-mixed -funclean-ordering
5656 make-patches --quiet-would-amend));
5657 # We tolerate soe snags that gdr wouldn't, by default.
5661 failedcmd @cmd if system @cmd and $?!=7*256;
5665 $headref = git_rev_parse('HEAD');
5669 changedir $playground;
5671 my $upstreamversion = upstreamversion $version;
5673 if ($fopts->{'single-debian-patch'}) {
5674 quilt_fixup_singlepatch($clogp, $headref, $upstreamversion);
5676 quilt_fixup_multipatch($clogp, $headref, $upstreamversion);
5679 die 'bug' if $split_brain && !$need_split_build_invocation;
5682 runcmd_ordryrun_local
5683 @git, qw(pull --ff-only -q), "$playground/work", qw(master);
5686 sub quilt_fixup_mkwork ($) {
5689 mkdir "work" or die $!;
5691 mktree_in_ud_here();
5692 runcmd @git, qw(reset -q --hard), $headref;
5695 sub quilt_fixup_linkorigs ($$) {
5696 my ($upstreamversion, $fn) = @_;
5697 # calls $fn->($leafname);
5699 foreach my $f (<$maindir/../*>) { #/){
5700 my $b=$f; $b =~ s{.*/}{};
5702 local ($debuglevel) = $debuglevel-1;
5703 printdebug "QF linkorigs $b, $f ?\n";
5705 next unless is_orig_file_of_vsn $b, $upstreamversion;
5706 printdebug "QF linkorigs $b, $f Y\n";
5707 link_ltarget $f, $b or die "$b $!";
5712 sub quilt_fixup_delete_pc () {
5713 runcmd @git, qw(rm -rqf .pc);
5715 Commit removal of .pc (quilt series tracking data)
5717 [dgit ($our_version) upgrade quilt-remove-pc]
5721 sub quilt_fixup_singlepatch ($$$) {
5722 my ($clogp, $headref, $upstreamversion) = @_;
5724 progress "starting quiltify (single-debian-patch)";
5726 # dpkg-source --commit generates new patches even if
5727 # single-debian-patch is in debian/source/options. In order to
5728 # get it to generate debian/patches/debian-changes, it is
5729 # necessary to build the source package.
5731 quilt_fixup_linkorigs($upstreamversion, sub { });
5732 quilt_fixup_mkwork($headref);
5734 rmtree("debian/patches");
5736 runcmd @dpkgsource, qw(-b .);
5738 runcmd @dpkgsource, qw(-x), (srcfn $version, ".dsc");
5739 rename srcfn("$upstreamversion", "/debian/patches"),
5740 "work/debian/patches";
5743 commit_quilty_patch();
5746 sub quilt_make_fake_dsc ($) {
5747 my ($upstreamversion) = @_;
5749 my $fakeversion="$upstreamversion-~~DGITFAKE";
5751 my $fakedsc=new IO::File 'fake.dsc', '>' or die $!;
5752 print $fakedsc <<END or die $!;
5755 Version: $fakeversion
5759 my $dscaddfile=sub {
5762 my $md = new Digest::MD5;
5764 my $fh = new IO::File $b, '<' or die "$b $!";
5769 print $fakedsc " ".$md->hexdigest." $size $b\n" or die $!;
5772 quilt_fixup_linkorigs($upstreamversion, $dscaddfile);
5774 my @files=qw(debian/source/format debian/rules
5775 debian/control debian/changelog);
5776 foreach my $maybe (qw(debian/patches debian/source/options
5777 debian/tests/control)) {
5778 next unless stat_exists "$maindir/$maybe";
5779 push @files, $maybe;
5782 my $debtar= srcfn $fakeversion,'.debian.tar.gz';
5783 runcmd qw(env GZIP=-1n tar -zcf), "./$debtar", qw(-C), $maindir, @files;
5785 $dscaddfile->($debtar);
5786 close $fakedsc or die $!;
5789 sub quilt_check_splitbrain_cache ($$) {
5790 my ($headref, $upstreamversion) = @_;
5791 # Called only if we are in (potentially) split brain mode.
5792 # Called in playground.
5793 # Computes the cache key and looks in the cache.
5794 # Returns ($dgit_view_commitid, $cachekey) or (undef, $cachekey)
5796 my $splitbrain_cachekey;
5799 "dgit: split brain (separate dgit view) may be needed (--quilt=$quilt_mode).";
5800 # we look in the reflog of dgit-intern/quilt-cache
5801 # we look for an entry whose message is the key for the cache lookup
5802 my @cachekey = (qw(dgit), $our_version);
5803 push @cachekey, $upstreamversion;
5804 push @cachekey, $quilt_mode;
5805 push @cachekey, $headref;
5807 push @cachekey, hashfile('fake.dsc');
5809 my $srcshash = Digest::SHA->new(256);
5810 my %sfs = ( %INC, '$0(dgit)' => $0 );
5811 foreach my $sfk (sort keys %sfs) {
5812 next unless $sfk =~ m/^\$0\b/ || $sfk =~ m{^Debian/Dgit\b};
5813 $srcshash->add($sfk," ");
5814 $srcshash->add(hashfile($sfs{$sfk}));
5815 $srcshash->add("\n");
5817 push @cachekey, $srcshash->hexdigest();
5818 $splitbrain_cachekey = "@cachekey";
5820 my @cmd = (@git, qw(log -g), '--pretty=format:%H %gs',
5822 printdebug "splitbrain cachekey $splitbrain_cachekey\n";
5823 debugcmd "|(probably)",@cmd;
5824 my $child = open GC, "-|"; defined $child or die $!;
5826 chdir $maindir or die $!;
5827 if (!stat "$maindir_gitcommon/logs/refs/$splitbraincache") {
5828 $! == ENOENT or die $!;
5829 printdebug ">(no reflog)\n";
5836 printdebug ">| ", $_, "\n" if $debuglevel > 1;
5837 next unless m/^(\w+) (\S.*\S)$/ && $2 eq $splitbrain_cachekey;
5840 quilt_fixup_mkwork($headref);
5841 my $saved = maybe_split_brain_save $headref, $cachehit, "cache-hit";
5842 if ($cachehit ne $headref) {
5843 progress "dgit view: found cached ($saved)";
5844 runcmd @git, qw(checkout -q -b dgit-view), $cachehit;
5846 return ($cachehit, $splitbrain_cachekey);
5848 progress "dgit view: found cached, no changes required";
5849 return ($headref, $splitbrain_cachekey);
5851 die $! if GC->error;
5852 failedcmd unless close GC;
5854 printdebug "splitbrain cache miss\n";
5855 return (undef, $splitbrain_cachekey);
5858 sub quilt_fixup_multipatch ($$$) {
5859 my ($clogp, $headref, $upstreamversion) = @_;
5861 progress "examining quilt state (multiple patches, $quilt_mode mode)";
5864 # - honour any existing .pc in case it has any strangeness
5865 # - determine the git commit corresponding to the tip of
5866 # the patch stack (if there is one)
5867 # - if there is such a git commit, convert each subsequent
5868 # git commit into a quilt patch with dpkg-source --commit
5869 # - otherwise convert all the differences in the tree into
5870 # a single git commit
5874 # Our git tree doesn't necessarily contain .pc. (Some versions of
5875 # dgit would include the .pc in the git tree.) If there isn't
5876 # one, we need to generate one by unpacking the patches that we
5879 # We first look for a .pc in the git tree. If there is one, we
5880 # will use it. (This is not the normal case.)
5882 # Otherwise need to regenerate .pc so that dpkg-source --commit
5883 # can work. We do this as follows:
5884 # 1. Collect all relevant .orig from parent directory
5885 # 2. Generate a debian.tar.gz out of
5886 # debian/{patches,rules,source/format,source/options}
5887 # 3. Generate a fake .dsc containing just these fields:
5888 # Format Source Version Files
5889 # 4. Extract the fake .dsc
5890 # Now the fake .dsc has a .pc directory.
5891 # (In fact we do this in every case, because in future we will
5892 # want to search for a good base commit for generating patches.)
5894 # Then we can actually do the dpkg-source --commit
5895 # 1. Make a new working tree with the same object
5896 # store as our main tree and check out the main
5898 # 2. Copy .pc from the fake's extraction, if necessary
5899 # 3. Run dpkg-source --commit
5900 # 4. If the result has changes to debian/, then
5901 # - git add them them
5902 # - git add .pc if we had a .pc in-tree
5904 # 5. If we had a .pc in-tree, delete it, and git commit
5905 # 6. Back in the main tree, fast forward to the new HEAD
5907 # Another situation we may have to cope with is gbp-style
5908 # patches-unapplied trees.
5910 # We would want to detect these, so we know to escape into
5911 # quilt_fixup_gbp. However, this is in general not possible.
5912 # Consider a package with a one patch which the dgit user reverts
5913 # (with git revert or the moral equivalent).
5915 # That is indistinguishable in contents from a patches-unapplied
5916 # tree. And looking at the history to distinguish them is not
5917 # useful because the user might have made a confusing-looking git
5918 # history structure (which ought to produce an error if dgit can't
5919 # cope, not a silent reintroduction of an unwanted patch).
5921 # So gbp users will have to pass an option. But we can usually
5922 # detect their failure to do so: if the tree is not a clean
5923 # patches-applied tree, quilt linearisation fails, but the tree
5924 # _is_ a clean patches-unapplied tree, we can suggest that maybe
5925 # they want --quilt=unapplied.
5927 # To help detect this, when we are extracting the fake dsc, we
5928 # first extract it with --skip-patches, and then apply the patches
5929 # afterwards with dpkg-source --before-build. That lets us save a
5930 # tree object corresponding to .origs.
5932 my $splitbrain_cachekey;
5934 quilt_make_fake_dsc($upstreamversion);
5936 if (quiltmode_splitbrain()) {
5938 ($cachehit, $splitbrain_cachekey) =
5939 quilt_check_splitbrain_cache($headref, $upstreamversion);
5940 return if $cachehit;
5944 'exec dpkg-source --no-check --skip-patches -x fake.dsc >/dev/null';
5946 my $fakexdir= $package.'-'.(stripepoch $upstreamversion);
5947 rename $fakexdir, "fake" or die "$fakexdir $!";
5951 remove_stray_gits("source package");
5952 mktree_in_ud_here();
5956 rmtree 'debian'; # git checkout commitish paths does not delete!
5957 runcmd @git, qw(checkout -f), $headref, qw(-- debian);
5958 my $unapplied=git_add_write_tree();
5959 printdebug "fake orig tree object $unapplied\n";
5963 my @bbcmd = (qw(sh -ec), 'exec dpkg-source --before-build . >/dev/null');
5965 if (system @bbcmd) {
5966 failedcmd @bbcmd if $? < 0;
5968 failed to apply your git tree's patch stack (from debian/patches/) to
5969 the corresponding upstream tarball(s). Your source tree and .orig
5970 are probably too inconsistent. dgit can only fix up certain kinds of
5971 anomaly (depending on the quilt mode). See --quilt= in dgit(1).
5977 quilt_fixup_mkwork($headref);
5980 if (stat_exists ".pc") {
5982 progress "Tree already contains .pc - will use it then delete it.";
5985 rename '../fake/.pc','.pc' or die $!;
5988 changedir '../fake';
5990 my $oldtiptree=git_add_write_tree();
5991 printdebug "fake o+d/p tree object $unapplied\n";
5992 changedir '../work';
5995 # We calculate some guesswork now about what kind of tree this might
5996 # be. This is mostly for error reporting.
6002 # O = orig, without patches applied
6003 # A = "applied", ie orig with H's debian/patches applied
6004 O2H => quiltify_trees_differ($unapplied,$headref, 1,
6005 \%editedignores, \@unrepres),
6006 H2A => quiltify_trees_differ($headref, $oldtiptree,1),
6007 O2A => quiltify_trees_differ($unapplied,$oldtiptree,1),
6011 foreach my $b (qw(01 02)) {
6012 foreach my $v (qw(O2H O2A H2A)) {
6013 push @dl, ($diffbits->{$v} & $b) ? '##' : '==';
6016 printdebug "differences \@dl @dl.\n";
6019 "$us: base trees orig=%.20s o+d/p=%.20s",
6020 $unapplied, $oldtiptree;
6022 "$us: quilt differences: src: %s orig %s gitignores: %s orig %s\n".
6023 "$us: quilt differences: HEAD %s o+d/p HEAD %s o+d/p",
6024 $dl[0], $dl[1], $dl[3], $dl[4],
6028 print STDERR "dgit: cannot represent change: $_->[1]: $_->[0]\n"
6030 forceable_fail [qw(unrepresentable)], <<END;
6031 HEAD has changes to .orig[s] which are not representable by `3.0 (quilt)'
6036 if (!($diffbits->{O2H} & $diffbits->{O2A})) {
6037 push @failsuggestion, "This might be a patches-unapplied branch.";
6038 } elsif (!($diffbits->{H2A} & $diffbits->{O2A})) {
6039 push @failsuggestion, "This might be a patches-applied branch.";
6041 push @failsuggestion, "Maybe you need to specify one of".
6042 " --[quilt=]gbp --[quilt=]dpm --quilt=unapplied ?";
6044 if (quiltmode_splitbrain()) {
6045 quiltify_splitbrain($clogp, $unapplied, $headref, $oldtiptree,
6046 $diffbits, \%editedignores,
6047 $splitbrain_cachekey);
6051 progress "starting quiltify (multiple patches, $quilt_mode mode)";
6052 quiltify($clogp,$headref,$oldtiptree,\@failsuggestion);
6054 if (!open P, '>>', ".pc/applied-patches") {
6055 $!==&ENOENT or die $!;
6060 commit_quilty_patch();
6062 if ($mustdeletepc) {
6063 quilt_fixup_delete_pc();
6067 sub quilt_fixup_editor () {
6068 my $descfn = $ENV{$fakeeditorenv};
6069 my $editing = $ARGV[$#ARGV];
6070 open I1, '<', $descfn or die "$descfn: $!";
6071 open I2, '<', $editing or die "$editing: $!";
6072 unlink $editing or die "$editing: $!";
6073 open O, '>', $editing or die "$editing: $!";
6074 while (<I1>) { print O or die $!; } I1->error and die $!;
6077 $copying ||= m/^\-\-\- /;
6078 next unless $copying;
6081 I2->error and die $!;
6086 sub maybe_apply_patches_dirtily () {
6087 return unless $quilt_mode =~ m/gbp|unapplied/;
6088 print STDERR <<END or die $!;
6090 dgit: Building, or cleaning with rules target, in patches-unapplied tree.
6091 dgit: Have to apply the patches - making the tree dirty.
6092 dgit: (Consider specifying --clean=git and (or) using dgit sbuild.)
6095 $patches_applied_dirtily = 01;
6096 $patches_applied_dirtily |= 02 unless stat_exists '.pc';
6097 runcmd qw(dpkg-source --before-build .);
6100 sub maybe_unapply_patches_again () {
6101 progress "dgit: Unapplying patches again to tidy up the tree."
6102 if $patches_applied_dirtily;
6103 runcmd qw(dpkg-source --after-build .)
6104 if $patches_applied_dirtily & 01;
6106 if $patches_applied_dirtily & 02;
6107 $patches_applied_dirtily = 0;
6110 #----- other building -----
6112 our $clean_using_builder;
6113 # ^ tree is to be cleaned by dpkg-source's builtin idea that it should
6114 # clean the tree before building (perhaps invoked indirectly by
6115 # whatever we are using to run the build), rather than separately
6116 # and explicitly by us.
6119 return if $clean_using_builder;
6120 if ($cleanmode eq 'dpkg-source') {
6121 maybe_apply_patches_dirtily();
6122 runcmd_ordryrun_local @dpkgbuildpackage, qw(-T clean);
6123 } elsif ($cleanmode eq 'dpkg-source-d') {
6124 maybe_apply_patches_dirtily();
6125 runcmd_ordryrun_local @dpkgbuildpackage, qw(-d -T clean);
6126 } elsif ($cleanmode eq 'git') {
6127 runcmd_ordryrun_local @git, qw(clean -xdf);
6128 } elsif ($cleanmode eq 'git-ff') {
6129 runcmd_ordryrun_local @git, qw(clean -xdff);
6130 } elsif ($cleanmode eq 'check') {
6131 my $leftovers = cmdoutput @git, qw(clean -xdn);
6132 if (length $leftovers) {
6133 print STDERR $leftovers, "\n" or die $!;
6134 fail "tree contains uncommitted files and --clean=check specified";
6136 } elsif ($cleanmode eq 'none') {
6143 badusage "clean takes no additional arguments" if @ARGV;
6146 maybe_unapply_patches_again();
6149 sub build_or_push_prep_early () {
6150 our $build_or_push_prep_early_done //= 0;
6151 return if $build_or_push_prep_early_done++;
6152 badusage "-p is not allowed with dgit $subcommand" if defined $package;
6153 my $clogp = parsechangelog();
6154 $isuite = getfield $clogp, 'Distribution';
6155 $package = getfield $clogp, 'Source';
6156 $version = getfield $clogp, 'Version';
6159 sub build_prep_early () {
6160 build_or_push_prep_early();
6168 build_maybe_quilt_fixup();
6170 my $pat = changespat $version;
6171 foreach my $f (glob "$buildproductsdir/$pat") {
6173 unlink $f or fail "remove old changes file $f: $!";
6175 progress "would remove $f";
6181 sub changesopts_initial () {
6182 my @opts =@changesopts[1..$#changesopts];
6185 sub changesopts_version () {
6186 if (!defined $changes_since_version) {
6189 @vsns = archive_query('archive_query');
6190 my @quirk = access_quirk();
6191 if ($quirk[0] eq 'backports') {
6192 local $isuite = $quirk[2];
6194 canonicalise_suite();
6195 push @vsns, archive_query('archive_query');
6201 "archive query failed (queried because --since-version not specified)";
6204 @vsns = map { $_->[0] } @vsns;
6205 @vsns = sort { -version_compare($a, $b) } @vsns;
6206 $changes_since_version = $vsns[0];
6207 progress "changelog will contain changes since $vsns[0]";
6209 $changes_since_version = '_';
6210 progress "package seems new, not specifying -v<version>";
6213 if ($changes_since_version ne '_') {
6214 return ("-v$changes_since_version");
6220 sub changesopts () {
6221 return (changesopts_initial(), changesopts_version());
6224 sub massage_dbp_args ($;$) {
6225 my ($cmd,$xargs) = @_;
6228 # - if we're going to split the source build out so we can
6229 # do strange things to it, massage the arguments to dpkg-buildpackage
6230 # so that the main build doessn't build source (or add an argument
6231 # to stop it building source by default).
6233 # - add -nc to stop dpkg-source cleaning the source tree,
6234 # unless we're not doing a split build and want dpkg-source
6235 # as cleanmode, in which case we can do nothing
6238 # 0 - source will NOT need to be built separately by caller
6239 # +1 - source will need to be built separately by caller
6240 # +2 - source will need to be built separately by caller AND
6241 # dpkg-buildpackage should not in fact be run at all!
6242 debugcmd '#massaging#', @$cmd if $debuglevel>1;
6243 #print STDERR "MASS0 ",Dumper($cmd, $xargs, $need_split_build_invocation);
6244 if ($cleanmode eq 'dpkg-source' && !$need_split_build_invocation) {
6245 $clean_using_builder = 1;
6248 # -nc has the side effect of specifying -b if nothing else specified
6249 # and some combinations of -S, -b, et al, are errors, rather than
6250 # later simply overriding earlie. So we need to:
6251 # - search the command line for these options
6252 # - pick the last one
6253 # - perhaps add our own as a default
6254 # - perhaps adjust it to the corresponding non-source-building version
6256 foreach my $l ($cmd, $xargs) {
6258 @$l = grep { !(m/^-[SgGFABb]$/s and $dmode=$_) } @$l;
6261 #print STDERR "MASS1 ",Dumper($cmd, $xargs, $dmode);
6263 if ($need_split_build_invocation) {
6264 printdebug "massage split $dmode.\n";
6265 $r = $dmode =~ m/[S]/ ? +2 :
6266 $dmode =~ y/gGF/ABb/ ? +1 :
6267 $dmode =~ m/[ABb]/ ? 0 :
6270 printdebug "massage done $r $dmode.\n";
6272 #print STDERR "MASS2 ",Dumper($cmd, $xargs, $r);
6278 my $wasdir = must_getcwd();
6284 sub postbuild_mergechanges ($) { # must run with CWD=.. (eg in in_parent)
6285 my ($msg_if_onlyone) = @_;
6286 # If there is only one .changes file, fail with $msg_if_onlyone,
6287 # or if that is undef, be a no-op.
6288 # Returns the changes file to report to the user.
6289 my $pat = changespat $version;
6290 my @changesfiles = glob $pat;
6291 @changesfiles = sort {
6292 ($b =~ m/_source\.changes$/ <=> $a =~ m/_source\.changes$/)
6296 if (@changesfiles==1) {
6297 fail <<END.$msg_if_onlyone if defined $msg_if_onlyone;
6298 only one changes file from build (@changesfiles)
6300 $result = $changesfiles[0];
6301 } elsif (@changesfiles==2) {
6302 my $binchanges = parsecontrol($changesfiles[1], "binary changes file");
6303 foreach my $l (split /\n/, getfield $binchanges, 'Files') {
6304 fail "$l found in binaries changes file $binchanges"
6307 runcmd_ordryrun_local @mergechanges, @changesfiles;
6308 my $multichanges = changespat $version,'multi';
6310 stat_exists $multichanges or fail "$multichanges: $!";
6311 foreach my $cf (glob $pat) {
6312 next if $cf eq $multichanges;
6313 rename "$cf", "$cf.inmulti" or fail "$cf\{,.inmulti}: $!";
6316 $result = $multichanges;
6318 fail "wrong number of different changes files (@changesfiles)";
6320 printdone "build successful, results in $result\n" or die $!;
6323 sub midbuild_checkchanges () {
6324 my $pat = changespat $version;
6325 return if $rmchanges;
6326 my @unwanted = map { s#^\.\./##; $_; } glob "../$pat";
6327 @unwanted = grep { $_ ne changespat $version,'source' } @unwanted;
6329 changes files other than source matching $pat already present; building would result in ambiguity about the intended results.
6330 Suggest you delete @unwanted.
6335 sub midbuild_checkchanges_vanilla ($) {
6337 midbuild_checkchanges() if $wantsrc == 1;
6340 sub postbuild_mergechanges_vanilla ($) {
6342 if ($wantsrc == 1) {
6344 postbuild_mergechanges(undef);
6347 printdone "build successful\n";
6353 my @dbp = (@dpkgbuildpackage, qw(-us -uc), changesopts_initial(), @ARGV);
6354 my $wantsrc = massage_dbp_args \@dbp;
6357 midbuild_checkchanges_vanilla $wantsrc;
6362 push @dbp, changesopts_version();
6363 maybe_apply_patches_dirtily();
6364 runcmd_ordryrun_local @dbp;
6366 maybe_unapply_patches_again();
6367 postbuild_mergechanges_vanilla $wantsrc;
6371 $quilt_mode //= 'gbp';
6377 # gbp can make .origs out of thin air. In my tests it does this
6378 # even for a 1.0 format package, with no origs present. So I
6379 # guess it keys off just the version number. We don't know
6380 # exactly what .origs ought to exist, but let's assume that we
6381 # should run gbp if: the version has an upstream part and the main
6383 my $upstreamversion = upstreamversion $version;
6384 my $origfnpat = srcfn $upstreamversion, '.orig.tar.*';
6385 my $gbp_make_orig = $version =~ m/-/ && !(() = glob "../$origfnpat");
6387 if ($gbp_make_orig) {
6389 $cleanmode = 'none'; # don't do it again
6390 $need_split_build_invocation = 1;
6393 my @dbp = @dpkgbuildpackage;
6395 my $wantsrc = massage_dbp_args \@dbp, \@ARGV;
6397 if (!length $gbp_build[0]) {
6398 if (length executable_on_path('git-buildpackage')) {
6399 $gbp_build[0] = qw(git-buildpackage);
6401 $gbp_build[0] = 'gbp buildpackage';
6404 my @cmd = opts_opt_multi_cmd @gbp_build;
6406 push @cmd, (qw(-us -uc --git-no-sign-tags),
6407 "--git-builder=".(shellquote @dbp));
6409 if ($gbp_make_orig) {
6410 my $priv = dgit_privdir();
6411 my $ok = "$priv/origs-gen-ok";
6412 unlink $ok or $!==&ENOENT or die $!;
6413 my @origs_cmd = @cmd;
6414 push @origs_cmd, qw(--git-cleaner=true);
6415 push @origs_cmd, "--git-prebuild=".
6416 "touch ".(shellquote $ok)." ".(shellquote "$priv/no-such-dir/ok");
6417 push @origs_cmd, @ARGV;
6419 debugcmd @origs_cmd;
6421 do { local $!; stat_exists $ok; }
6422 or failedcmd @origs_cmd;
6424 dryrun_report @origs_cmd;
6430 midbuild_checkchanges_vanilla $wantsrc;
6432 if (!$clean_using_builder) {
6433 push @cmd, '--git-cleaner=true';
6437 maybe_unapply_patches_again();
6439 push @cmd, changesopts();
6440 runcmd_ordryrun_local @cmd, @ARGV;
6442 postbuild_mergechanges_vanilla $wantsrc;
6444 sub cmd_git_build { cmd_gbp_build(); } # compatibility with <= 1.0
6446 sub build_source_for_push {
6448 maybe_unapply_patches_again();
6449 $changesfile = $sourcechanges;
6455 $sourcechanges = changespat $version,'source';
6457 unlink "../$sourcechanges" or $!==ENOENT
6458 or fail "remove $sourcechanges: $!";
6460 $dscfn = dscfn($version);
6461 my @cmd = (@dpkgsource, qw(-b --));
6463 changedir $playground;
6464 runcmd_ordryrun_local @cmd, "work";
6465 my @udfiles = <${package}_*>;
6467 foreach my $f (@udfiles) {
6468 printdebug "source copy, found $f\n";
6471 ($f =~ m/\.debian\.tar(?:\.\w+)$/ &&
6472 $f eq srcfn($version, $&));
6473 printdebug "source copy, found $f - renaming\n";
6474 rename "$playground/$f", "../$f" or $!==ENOENT
6475 or fail "put in place new source file ($f): $!";
6478 my $pwd = must_getcwd();
6479 my $leafdir = basename $pwd;
6481 runcmd_ordryrun_local @cmd, $leafdir;
6484 runcmd_ordryrun_local qw(sh -ec),
6485 'exec >$1; shift; exec "$@"','x',
6486 "../$sourcechanges",
6487 @dpkggenchanges, qw(-S), changesopts();
6490 sub cmd_build_source {
6492 badusage "build-source takes no additional arguments" if @ARGV;
6494 maybe_unapply_patches_again();
6495 printdone "source built, results in $dscfn and $sourcechanges";
6500 midbuild_checkchanges();
6503 stat_exists $dscfn or fail "$dscfn (in parent directory): $!";
6504 stat_exists $sourcechanges
6505 or fail "$sourcechanges (in parent directory): $!";
6507 runcmd_ordryrun_local @sbuild, qw(-d), $isuite, @ARGV, $dscfn;
6509 maybe_unapply_patches_again();
6511 postbuild_mergechanges(<<END);
6512 perhaps you need to pass -A ? (sbuild's default is to build only
6513 arch-specific binaries; dgit 1.4 used to override that.)
6518 sub cmd_quilt_fixup {
6519 badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
6522 build_maybe_quilt_fixup();
6525 sub import_dsc_result {
6526 my ($dstref, $newhash, $what_log, $what_msg) = @_;
6527 my @cmd = (git_update_ref_cmd $what_log, $dstref, $newhash);
6529 check_gitattrs($newhash, "source tree");
6531 progress "dgit: import-dsc: $what_msg";
6534 sub cmd_import_dsc {
6538 last unless $ARGV[0] =~ m/^-/;
6541 if (m/^--require-valid-signature$/) {
6544 badusage "unknown dgit import-dsc sub-option \`$_'";
6548 badusage "usage: dgit import-dsc .../PATH/TO/.DSC BRANCH" unless @ARGV==2;
6549 my ($dscfn, $dstbranch) = @ARGV;
6551 badusage "dry run makes no sense with import-dsc" unless act_local();
6553 my $force = $dstbranch =~ s/^\+// ? +1 :
6554 $dstbranch =~ s/^\.\.// ? -1 :
6556 my $info = $force ? " $&" : '';
6557 $info = "$dscfn$info";
6559 my $specbranch = $dstbranch;
6560 $dstbranch = "refs/heads/$dstbranch" unless $dstbranch =~ m#^refs/#;
6561 $dstbranch = cmdoutput @git, qw(check-ref-format --normalize), $dstbranch;
6563 my @symcmd = (@git, qw(symbolic-ref -q HEAD));
6564 my $chead = cmdoutput_errok @symcmd;
6565 defined $chead or $?==256 or failedcmd @symcmd;
6567 fail "$dstbranch is checked out - will not update it"
6568 if defined $chead and $chead eq $dstbranch;
6570 my $oldhash = git_get_ref $dstbranch;
6572 open D, "<", $dscfn or fail "open import .dsc ($dscfn): $!";
6573 $dscdata = do { local $/ = undef; <D>; };
6574 D->error and fail "read $dscfn: $!";
6577 # we don't normally need this so import it here
6578 use Dpkg::Source::Package;
6579 my $dp = new Dpkg::Source::Package filename => $dscfn,
6580 require_valid_signature => $needsig;
6582 local $SIG{__WARN__} = sub {
6584 return unless $needsig;
6585 fail "import-dsc signature check failed";
6587 if (!$dp->is_signed()) {
6588 warn "$us: warning: importing unsigned .dsc\n";
6590 my $r = $dp->check_signature();
6591 die "->check_signature => $r" if $needsig && $r;
6597 $package = getfield $dsc, 'Source';
6599 parse_dsc_field($dsc, "Dgit metadata in .dsc")
6600 unless forceing [qw(import-dsc-with-dgit-field)];
6601 parse_dsc_field_def_dsc_distro();
6603 $isuite = 'DGIT-IMPORT-DSC';
6604 $idistro //= $dsc_distro;
6608 if (defined $dsc_hash) {
6609 progress "dgit: import-dsc of .dsc with Dgit field, using git hash";
6610 resolve_dsc_field_commit undef, undef;
6612 if (defined $dsc_hash) {
6613 my @cmd = (qw(sh -ec),
6614 "echo $dsc_hash | git cat-file --batch-check");
6615 my $objgot = cmdoutput @cmd;
6616 if ($objgot =~ m#^\w+ missing\b#) {
6618 .dsc contains Dgit field referring to object $dsc_hash
6619 Your git tree does not have that object. Try `git fetch' from a
6620 plausible server (browse.dgit.d.o? alioth?), and try the import-dsc again.
6623 if ($oldhash && !is_fast_fwd $oldhash, $dsc_hash) {
6625 progress "Not fast forward, forced update.";
6627 fail "Not fast forward to $dsc_hash";
6630 import_dsc_result $dstbranch, $dsc_hash,
6631 "dgit import-dsc (Dgit): $info",
6632 "updated git ref $dstbranch";
6637 Branch $dstbranch already exists
6638 Specify ..$specbranch for a pseudo-merge, binding in existing history
6639 Specify +$specbranch to overwrite, discarding existing history
6641 if $oldhash && !$force;
6643 my @dfi = dsc_files_info();
6644 foreach my $fi (@dfi) {
6645 my $f = $fi->{Filename};
6649 fail "lstat $here works but stat gives $! !";
6651 fail "stat $here: $!" unless $! == ENOENT;
6653 if ($dscfn =~ m#^(?:\./+)?\.\./+#) {
6655 } elsif ($dscfn =~ m#^/#) {
6658 fail "cannot import $dscfn which seems to be inside working tree!";
6660 $there =~ s#/+[^/]+$## or
6661 fail "import $dscfn requires ../$f, but it does not exist";
6663 my $test = $there =~ m{^/} ? $there : "../$there";
6664 stat $test or fail "import $dscfn requires $test, but: $!";
6665 symlink $there, $here or fail "symlink $there to $here: $!";
6666 progress "made symlink $here -> $there";
6667 # print STDERR Dumper($fi);
6669 my @mergeinputs = generate_commits_from_dsc();
6670 die unless @mergeinputs == 1;
6672 my $newhash = $mergeinputs[0]{Commit};
6676 progress "Import, forced update - synthetic orphan git history.";
6677 } elsif ($force < 0) {
6678 progress "Import, merging.";
6679 my $tree = cmdoutput @git, qw(rev-parse), "$newhash:";
6680 my $version = getfield $dsc, 'Version';
6681 my $clogp = commit_getclogp $newhash;
6682 my $authline = clogp_authline $clogp;
6683 $newhash = make_commit_text <<END;
6690 Merge $package ($version) import into $dstbranch
6693 die; # caught earlier
6697 import_dsc_result $dstbranch, $newhash,
6698 "dgit import-dsc: $info",
6699 "results are in in git ref $dstbranch";
6702 sub pre_archive_api_query () {
6703 not_necessarily_a_tree();
6705 sub cmd_archive_api_query {
6706 badusage "need only 1 subpath argument" unless @ARGV==1;
6707 my ($subpath) = @ARGV;
6708 local $isuite = 'DGIT-API-QUERY-CMD';
6709 my @cmd = archive_api_query_cmd($subpath);
6712 exec @cmd or fail "exec curl: $!\n";
6715 sub repos_server_url () {
6716 $package = '_dgit-repos-server';
6717 local $access_forpush = 1;
6718 local $isuite = 'DGIT-REPOS-SERVER';
6719 my $url = access_giturl();
6722 sub pre_clone_dgit_repos_server () {
6723 not_necessarily_a_tree();
6725 sub cmd_clone_dgit_repos_server {
6726 badusage "need destination argument" unless @ARGV==1;
6727 my ($destdir) = @ARGV;
6728 my $url = repos_server_url();
6729 my @cmd = (@git, qw(clone), $url, $destdir);
6731 exec @cmd or fail "exec git clone: $!\n";
6734 sub pre_print_dgit_repos_server_source_url () {
6735 not_necessarily_a_tree();
6737 sub cmd_print_dgit_repos_server_source_url {
6738 badusage "no arguments allowed to dgit print-dgit-repos-server-source-url"
6740 my $url = repos_server_url();
6741 print $url, "\n" or die $!;
6744 sub pre_print_dpkg_source_ignores {
6745 not_necessarily_a_tree();
6747 sub cmd_print_dpkg_source_ignores {
6748 badusage "no arguments allowed to dgit print-dpkg-source-ignores"
6750 print "@dpkg_source_ignores\n" or die $!;
6753 sub cmd_setup_mergechangelogs {
6754 badusage "no arguments allowed to dgit setup-mergechangelogs" if @ARGV;
6755 local $isuite = 'DGIT-SETUP-TREE';
6756 setup_mergechangelogs(1);
6759 sub cmd_setup_useremail {
6760 badusage "no arguments allowed to dgit setup-useremail" if @ARGV;
6761 local $isuite = 'DGIT-SETUP-TREE';
6765 sub cmd_setup_gitattributes {
6766 badusage "no arguments allowed to dgit setup-useremail" if @ARGV;
6767 local $isuite = 'DGIT-SETUP-TREE';
6771 sub cmd_setup_new_tree {
6772 badusage "no arguments allowed to dgit setup-tree" if @ARGV;
6773 local $isuite = 'DGIT-SETUP-TREE';
6777 #---------- argument parsing and main program ----------
6780 print "dgit version $our_version\n" or die $!;
6784 our (%valopts_long, %valopts_short);
6785 our (%funcopts_long);
6787 our (@modeopt_cfgs);
6789 sub defvalopt ($$$$) {
6790 my ($long,$short,$val_re,$how) = @_;
6791 my $oi = { Long => $long, Short => $short, Re => $val_re, How => $how };
6792 $valopts_long{$long} = $oi;
6793 $valopts_short{$short} = $oi;
6794 # $how subref should:
6795 # do whatever assignemnt or thing it likes with $_[0]
6796 # if the option should not be passed on to remote, @rvalopts=()
6797 # or $how can be a scalar ref, meaning simply assign the value
6800 defvalopt '--since-version', '-v', '[^_]+|_', \$changes_since_version;
6801 defvalopt '--distro', '-d', '.+', \$idistro;
6802 defvalopt '', '-k', '.+', \$keyid;
6803 defvalopt '--existing-package','', '.*', \$existing_package;
6804 defvalopt '--build-products-dir','','.*', \$buildproductsdir;
6805 defvalopt '--clean', '', $cleanmode_re, \$cleanmode;
6806 defvalopt '--package', '-p', $package_re, \$package;
6807 defvalopt '--quilt', '', $quilt_modes_re, \$quilt_mode;
6809 defvalopt '', '-C', '.+', sub {
6810 ($changesfile) = (@_);
6811 if ($changesfile =~ s#^(.*)/##) {
6812 $buildproductsdir = $1;
6816 defvalopt '--initiator-tempdir','','.*', sub {
6817 ($initiator_tempdir) = (@_);
6818 $initiator_tempdir =~ m#^/# or
6819 badusage "--initiator-tempdir must be used specify an".
6820 " absolute, not relative, directory."
6823 sub defoptmodes ($@) {
6824 my ($varref, $cfgkey, $default, %optmap) = @_;
6826 while (my ($opt,$val) = each %optmap) {
6827 $funcopts_long{$opt} = sub { $$varref = $val; };
6828 $permit{$val} = $val;
6830 push @modeopt_cfgs, {
6833 Default => $default,
6838 defoptmodes \$dodep14tag, qw( dep14tag want
6841 --always-dep14tag always );
6846 if (defined $ENV{'DGIT_SSH'}) {
6847 @ssh = string_to_ssh $ENV{'DGIT_SSH'};
6848 } elsif (defined $ENV{'GIT_SSH'}) {
6849 @ssh = ($ENV{'GIT_SSH'});
6857 if (!defined $val) {
6858 badusage "$what needs a value" unless @ARGV;
6860 push @rvalopts, $val;
6862 badusage "bad value \`$val' for $what" unless
6863 $val =~ m/^$oi->{Re}$(?!\n)/s;
6864 my $how = $oi->{How};
6865 if (ref($how) eq 'SCALAR') {
6870 push @ropts, @rvalopts;
6874 last unless $ARGV[0] =~ m/^-/;
6878 if (m/^--dry-run$/) {
6881 } elsif (m/^--damp-run$/) {
6884 } elsif (m/^--no-sign$/) {
6887 } elsif (m/^--help$/) {
6889 } elsif (m/^--version$/) {
6891 } elsif (m/^--new$/) {
6894 } elsif (m/^--([-0-9a-z]+)=(.+)/s &&
6895 ($om = $opts_opt_map{$1}) &&
6899 } elsif (m/^--([-0-9a-z]+):(.*)/s &&
6900 !$opts_opt_cmdonly{$1} &&
6901 ($om = $opts_opt_map{$1})) {
6904 } elsif (m/^--(gbp|dpm)$/s) {
6905 push @ropts, "--quilt=$1";
6907 } elsif (m/^--ignore-dirty$/s) {
6910 } elsif (m/^--no-quilt-fixup$/s) {
6912 $quilt_mode = 'nocheck';
6913 } elsif (m/^--no-rm-on-error$/s) {
6916 } elsif (m/^--no-chase-dsc-distro$/s) {
6918 $chase_dsc_distro = 0;
6919 } elsif (m/^--overwrite$/s) {
6921 $overwrite_version = '';
6922 } elsif (m/^--overwrite=(.+)$/s) {
6924 $overwrite_version = $1;
6925 } elsif (m/^--delayed=(\d+)$/s) {
6928 } elsif (m/^--dgit-view-save=(.+)$/s) {
6930 $split_brain_save = $1;
6931 $split_brain_save =~ s#^(?!refs/)#refs/heads/#;
6932 } elsif (m/^--(no-)?rm-old-changes$/s) {
6935 } elsif (m/^--deliberately-($deliberately_re)$/s) {
6937 push @deliberatelies, $&;
6938 } elsif (m/^--force-(.*)/ && defined $forceopts{$1}) {
6942 } elsif (m/^--force-/) {
6944 "$us: warning: ignoring unknown force option $_\n";
6946 } elsif (m/^--dgit-tag-format=(old|new)$/s) {
6947 # undocumented, for testing
6949 $tagformat_want = [ $1, 'command line', 1 ];
6950 # 1 menas overrides distro configuration
6951 } elsif (m/^--always-split-source-build$/s) {
6952 # undocumented, for testing
6954 $need_split_build_invocation = 1;
6955 } elsif (m/^--config-lookup-explode=(.+)$/s) {
6956 # undocumented, for testing
6958 $gitcfgs{cmdline}{$1} = 'CONFIG-LOOKUP-EXPLODE';
6959 # ^ it's supposed to be an array ref
6960 } elsif (m/^(--[-0-9a-z]+)(=|$)/ && ($oi = $valopts_long{$1})) {
6961 $val = $2 ? $' : undef; #';
6962 $valopt->($oi->{Long});
6963 } elsif ($funcopts_long{$_}) {
6965 $funcopts_long{$_}();
6967 badusage "unknown long option \`$_'";
6974 } elsif (s/^-L/-/) {
6977 } elsif (s/^-h/-/) {
6979 } elsif (s/^-D/-/) {
6983 } elsif (s/^-N/-/) {
6988 push @changesopts, $_;
6990 } elsif (s/^-wn$//s) {
6992 $cleanmode = 'none';
6993 } elsif (s/^-wg$//s) {
6996 } elsif (s/^-wgf$//s) {
6998 $cleanmode = 'git-ff';
6999 } elsif (s/^-wd$//s) {
7001 $cleanmode = 'dpkg-source';
7002 } elsif (s/^-wdd$//s) {
7004 $cleanmode = 'dpkg-source-d';
7005 } elsif (s/^-wc$//s) {
7007 $cleanmode = 'check';
7008 } elsif (s/^-c([^=]*)\=(.*)$//s) {
7009 push @git, '-c', $&;
7010 $gitcfgs{cmdline}{$1} = [ $2 ];
7011 } elsif (s/^-c([^=]+)$//s) {
7012 push @git, '-c', $&;
7013 $gitcfgs{cmdline}{$1} = [ 'true' ];
7014 } elsif (m/^-[a-zA-Z]/ && ($oi = $valopts_short{$&})) {
7016 $val = undef unless length $val;
7017 $valopt->($oi->{Short});
7020 badusage "unknown short option \`$_'";
7027 sub check_env_sanity () {
7028 my $blocked = new POSIX::SigSet;
7029 sigprocmask SIG_UNBLOCK, $blocked, $blocked or die $!;
7032 foreach my $name (qw(PIPE CHLD)) {
7033 my $signame = "SIG$name";
7034 my $signum = eval "POSIX::$signame" // die;
7035 ($SIG{$name} // 'DEFAULT') eq 'DEFAULT' or
7036 die "$signame is set to something other than SIG_DFL\n";
7037 $blocked->ismember($signum) and
7038 die "$signame is blocked\n";
7044 On entry to dgit, $@
7045 This is a bug produced by something in in your execution environment.
7051 sub parseopts_late_defaults () {
7052 $isuite //= cfg("dgit-distro.$idistro.default-suite", 'RETURN-UNDEF')
7053 if defined $idistro;
7054 $isuite //= cfg('dgit.default.default-suite');
7056 foreach my $k (keys %opts_opt_map) {
7057 my $om = $opts_opt_map{$k};
7059 my $v = access_cfg("cmd-$k", 'RETURN-UNDEF');
7061 badcfg "cannot set command for $k"
7062 unless length $om->[0];
7066 foreach my $c (access_cfg_cfgs("opts-$k")) {
7068 map { $_ ? @$_ : () }
7069 map { $gitcfgs{$_}{$c} }
7070 reverse @gitcfgsources;
7071 printdebug "CL $c ", (join " ", map { shellquote } @vl),
7072 "\n" if $debuglevel >= 4;
7074 badcfg "cannot configure options for $k"
7075 if $opts_opt_cmdonly{$k};
7076 my $insertpos = $opts_cfg_insertpos{$k};
7077 @$om = ( @$om[0..$insertpos-1],
7079 @$om[$insertpos..$#$om] );
7083 if (!defined $rmchanges) {
7084 local $access_forpush;
7085 $rmchanges = access_cfg_bool(0, 'rm-old-changes');
7088 if (!defined $quilt_mode) {
7089 local $access_forpush;
7090 $quilt_mode = cfg('dgit.force.quilt-mode', 'RETURN-UNDEF')
7091 // access_cfg('quilt-mode', 'RETURN-UNDEF')
7093 $quilt_mode =~ m/^($quilt_modes_re)$/
7094 or badcfg "unknown quilt-mode \`$quilt_mode'";
7098 foreach my $moc (@modeopt_cfgs) {
7099 local $access_forpush;
7100 my $vr = $moc->{Var};
7101 next if defined $$vr;
7102 $$vr = access_cfg($moc->{Key}, 'RETURN-UNDEF') // $moc->{Default};
7103 my $v = $moc->{Vals}{$$vr};
7104 badcfg "unknown $moc->{Key} setting \`$$vr'" unless defined $v;
7108 $need_split_build_invocation ||= quiltmode_splitbrain();
7110 if (!defined $cleanmode) {
7111 local $access_forpush;
7112 $cleanmode = access_cfg('clean-mode', 'RETURN-UNDEF');
7113 $cleanmode //= 'dpkg-source';
7115 badcfg "unknown clean-mode \`$cleanmode'" unless
7116 $cleanmode =~ m/^($cleanmode_re)$(?!\n)/s;
7120 if ($ENV{$fakeeditorenv}) {
7122 quilt_fixup_editor();
7128 print STDERR "DRY RUN ONLY\n" if $dryrun_level > 1;
7129 print STDERR "DAMP RUN - WILL MAKE LOCAL (UNSIGNED) CHANGES\n"
7130 if $dryrun_level == 1;
7132 print STDERR $helpmsg or die $!;
7135 $cmd = $subcommand = shift @ARGV;
7138 my $pre_fn = ${*::}{"pre_$cmd"};
7139 $pre_fn->() if $pre_fn;
7141 record_maindir if $invoked_in_git_tree;
7144 my $fn = ${*::}{"cmd_$cmd"};
7145 $fn or badusage "unknown operation $cmd";