3 # Integration between git and Debian-style archives
5 # Copyright (C)2013-2018 Ian Jackson
6 # Copyright (C)2017-2018 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;
23 use Debian::Dgit::I18n;
27 use Debian::Dgit qw(:DEFAULT :playground);
33 use Dpkg::Control::Hash;
35 use File::Temp qw(tempdir);
38 use Dpkg::Compression;
39 use Dpkg::Compression::Process;
45 use List::MoreUtils qw(pairwise);
46 use Text::Glob qw(match_glob);
47 use Fcntl qw(:DEFAULT :flock);
52 our $our_version = 'UNRELEASED'; ###substituted###
53 our $absurdity = undef; ###substituted###
55 our @rpushprotovsn_support = qw(4 3 2); # 4 is new tag format
66 our $dryrun_level = 0;
68 our $buildproductsdir;
71 our $includedirty = 0;
75 our $existing_package = 'dpkg';
77 our $changes_since_version;
79 our $overwrite_version; # undef: not specified; '': check changelog
81 our $quilt_modes_re = 'linear|smash|auto|nofix|nocheck|gbp|dpm|unapplied';
83 our %internal_object_save;
84 our $we_are_responder;
85 our $we_are_initiator;
86 our $initiator_tempdir;
87 our $patches_applied_dirtily = 00;
91 our $chase_dsc_distro=1;
93 our %forceopts = map { $_=>0 }
94 qw(unrepresentable unsupported-source-format
95 dsc-changes-mismatch changes-origs-exactly
96 uploading-binaries uploading-source-only
97 import-gitapply-absurd
98 import-gitapply-no-absurd
99 import-dsc-with-dgit-field);
101 our %format_ok = map { $_=>1 } ("1.0","3.0 (native)","3.0 (quilt)");
103 our $suite_re = '[-+.0-9a-z]+';
104 our $cleanmode_re = 'dpkg-source(?:-d)?|git|git-ff|check|none';
106 our $git_authline_re = '^([^<>]+) \<(\S+)\> (\d+ [-+]\d+)$';
107 our $splitbraincache = 'dgit-intern/quilt-cache';
108 our $rewritemap = 'dgit-rewrite/map';
110 our @dpkg_source_ignores = qw(-i(?:^|/)\.git(?:/|$) -I.git);
112 our (@git) = qw(git);
113 our (@dget) = qw(dget);
114 our (@curl) = (qw(curl --proto-redir), '-all,http,https', qw(-L));
115 our (@dput) = qw(dput);
116 our (@debsign) = qw(debsign);
117 our (@gpg) = qw(gpg);
118 our (@sbuild) = (qw(sbuild --no-source));
120 our (@dgit) = qw(dgit);
121 our (@git_debrebase) = qw(git-debrebase);
122 our (@aptget) = qw(apt-get);
123 our (@aptcache) = qw(apt-cache);
124 our (@dpkgbuildpackage) = (qw(dpkg-buildpackage), @dpkg_source_ignores);
125 our (@dpkgsource) = (qw(dpkg-source), @dpkg_source_ignores);
126 our (@dpkggenchanges) = qw(dpkg-genchanges);
127 our (@mergechanges) = qw(mergechanges -f);
128 our (@gbp_build) = ('');
129 our (@gbp_pq) = ('gbp pq');
130 our (@changesopts) = ('');
131 our (@pbuilder) = ("sudo -E pbuilder");
132 our (@cowbuilder) = ("sudo -E cowbuilder");
134 our %opts_opt_map = ('dget' => \@dget, # accept for compatibility
137 'debsign' => \@debsign,
139 'sbuild' => \@sbuild,
143 'git-debrebase' => \@git_debrebase,
144 'apt-get' => \@aptget,
145 'apt-cache' => \@aptcache,
146 'dpkg-source' => \@dpkgsource,
147 'dpkg-buildpackage' => \@dpkgbuildpackage,
148 'dpkg-genchanges' => \@dpkggenchanges,
149 'gbp-build' => \@gbp_build,
150 'gbp-pq' => \@gbp_pq,
151 'ch' => \@changesopts,
152 'mergechanges' => \@mergechanges,
153 'pbuilder' => \@pbuilder,
154 'cowbuilder' => \@cowbuilder);
156 our %opts_opt_cmdonly = ('gpg' => 1, 'git' => 1);
157 our %opts_cfg_insertpos = map {
159 scalar @{ $opts_opt_map{$_} }
160 } keys %opts_opt_map;
162 sub parseopts_late_defaults();
163 sub setup_gitattrs(;$);
164 sub check_gitattrs($$);
171 our $supplementary_message = '';
172 our $split_brain = 0;
176 return unless forkcheck_mainprocess();
177 print STDERR "! $_\n" foreach $supplementary_message =~ m/^.+$/mg;
180 our $remotename = 'dgit';
181 our @ourdscfield = qw(Dgit Vcs-Dgit-Master);
185 if (!defined $absurdity) {
187 $absurdity =~ s{/[^/]+$}{/absurd} or die;
191 my ($v,$distro) = @_;
192 return $tagformatfn->($v, $distro);
195 sub madformat ($) { $_[0] eq '3.0 (quilt)' }
197 sub lbranch () { return "$branchprefix/$csuite"; }
198 my $lbranch_re = '^refs/heads/'.$branchprefix.'/([^/.]+)$';
199 sub lref () { return "refs/heads/".lbranch(); }
200 sub lrref () { return "refs/remotes/$remotename/".server_branch($csuite); }
201 sub rrref () { return server_ref($csuite); }
204 my ($vsn, $sfx) = @_;
205 return &source_file_leafname($package, $vsn, $sfx);
207 sub is_orig_file_of_vsn ($$) {
208 my ($f, $upstreamvsn) = @_;
209 return is_orig_file_of_p_v($f, $package, $upstreamvsn);
214 return srcfn($vsn,".dsc");
217 sub changespat ($;$) {
218 my ($vsn, $arch) = @_;
219 return "${package}_".(stripepoch $vsn)."_".($arch//'*').".changes";
228 return unless forkcheck_mainprocess();
229 foreach my $f (@end) {
231 print STDERR "$us: cleanup: $@" if length $@;
236 print STDERR f_ "%s: invalid configuration: %s\n", $us, "@_";
240 sub forceable_fail ($$) {
241 my ($forceoptsl, $msg) = @_;
242 fail $msg unless grep { $forceopts{$_} } @$forceoptsl;
243 print STDERR +(__ "warning: overriding problem due to --force:\n"). $msg;
247 my ($forceoptsl) = @_;
248 my @got = grep { $forceopts{$_} } @$forceoptsl;
249 return 0 unless @got;
251 "warning: skipping checks or functionality due to --force-%s\n",
255 sub no_such_package () {
256 print STDERR f_ "%s: package %s does not exist in suite %s\n",
257 $us, $package, $isuite;
261 sub deliberately ($) {
263 return !!grep { $_ eq "--deliberately-$enquiry" } @deliberatelies;
266 sub deliberately_not_fast_forward () {
267 foreach (qw(not-fast-forward fresh-repo)) {
268 return 1 if deliberately($_) || deliberately("TEST-dgit-only-$_");
272 sub quiltmode_splitbrain () {
273 $quilt_mode =~ m/gbp|dpm|unapplied/;
276 sub opts_opt_multi_cmd {
279 push @cmd, split /\s+/, shift @_;
286 return opts_opt_multi_cmd [], @gbp_pq;
289 sub dgit_privdir () {
290 our $dgit_privdir_made //= ensure_a_playground 'dgit';
294 my $r = $buildproductsdir;
295 $r = "$maindir/$r" unless $r =~ m{^/};
299 sub get_tree_of_commit ($) {
300 my ($commitish) = @_;
301 my $cdata = cmdoutput @git, qw(cat-file commit), $commitish;
302 $cdata =~ m/\n\n/; $cdata = $`;
303 $cdata =~ m/^tree (\w+)$/m or confess "cdata $cdata ?";
307 sub branch_gdr_info ($$) {
308 my ($symref, $head) = @_;
309 my ($status, $msg, $current, $ffq_prev, $gdrlast) =
310 gdr_ffq_prev_branchinfo($symref);
311 return () unless $status eq 'branch';
312 $ffq_prev = git_get_ref $ffq_prev;
313 $gdrlast = git_get_ref $gdrlast;
314 $gdrlast &&= is_fast_fwd $gdrlast, $head;
315 return ($ffq_prev, $gdrlast);
318 sub branch_is_gdr_unstitched_ff ($$$) {
319 my ($symref, $head, $ancestor) = @_;
320 my ($ffq_prev, $gdrlast) = branch_gdr_info($symref, $head);
321 return 0 unless $ffq_prev;
322 return 0 unless !defined $ancestor or is_fast_fwd $ancestor, $ffq_prev;
326 sub branch_is_gdr ($) {
328 # This is quite like git-debrebase's keycommits.
329 # We have our own implementation because:
330 # - our algorighm can do fewer tests so is faster
331 # - it saves testing to see if gdr is installed
333 # NB we use this jsut for deciding whether to run gdr make-patches
334 # Before reusing this algorithm for somthing else, its
335 # suitability should be reconsidered.
338 local $Debian::Dgit::debugcmd_when_debuglevel = 3;
339 printdebug "branch_is_gdr $head...\n";
340 my $get_patches = sub {
341 my $t = git_cat_file "$_[0]:debian/patches", [qw(missing tree)];
344 my $tip_patches = $get_patches->($head);
347 my $cdata = git_cat_file $walk, 'commit';
348 my ($hdrs,$msg) = $cdata =~ m{\n\n} ? ($`,$') : ($cdata,'');
349 if ($msg =~ m{^\[git-debrebase\ (
350 anchor | changelog | make-patches |
351 merged-breakwater | pseudomerge
353 # no need to analyse this - it's sufficient
354 # (gdr classifications: Anchor, MergedBreakwaters)
355 # (made by gdr: Pseudomerge, Changelog)
356 printdebug "branch_is_gdr $walk gdr $1 YES\n";
359 my @parents = ($hdrs =~ m/^parent (\w+)$/gm);
361 my $walk_tree = get_tree_of_commit $walk;
362 foreach my $p (@parents) {
363 my $p_tree = get_tree_of_commit $p;
364 if ($p_tree eq $walk_tree) { # pseudomerge contriburor
365 # (gdr classification: Pseudomerge; not made by gdr)
366 printdebug "branch_is_gdr $walk unmarked pseudomerge\n"
372 # some other non-gdr merge
373 # (gdr classification: VanillaMerge, DgitImportUnpatched, ?)
374 printdebug "branch_is_gdr $walk ?-2-merge NO\n";
378 # (gdr classification: ?)
379 printdebug "branch_is_gdr $walk ?-octopus NO\n";
383 printdebug "branch_is_gdr $walk origin\n";
386 if ($get_patches->($walk) ne $tip_patches) {
387 # Our parent added, removed, or edited patches, and wasn't
388 # a gdr make-patches commit. gdr make-patches probably
389 # won't do that well, then.
390 # (gdr classification of parent: AddPatches or ?)
391 printdebug "branch_is_gdr $walk ?-patches NO\n";
394 if ($tip_patches eq '' and
395 !defined git_cat_file "$walk:debian") {
396 # (gdr classification of parent: BreakwaterStart
397 printdebug "branch_is_gdr $walk unmarked BreakwaterStart YES\n";
400 # (gdr classification: Upstream Packaging Mixed Changelog)
401 printdebug "branch_is_gdr $walk plain\n"
407 #---------- remote protocol support, common ----------
409 # remote push initiator/responder protocol:
410 # $ dgit remote-push-build-host <n-rargs> <rargs>... <push-args>...
411 # where <rargs> is <push-host-dir> <supported-proto-vsn>,... ...
412 # < dgit-remote-push-ready <actual-proto-vsn>
419 # > supplementary-message NBYTES # $protovsn >= 3
424 # > file parsed-changelog
425 # [indicates that output of dpkg-parsechangelog follows]
426 # > data-block NBYTES
427 # > [NBYTES bytes of data (no newline)]
428 # [maybe some more blocks]
437 # > param head DGIT-VIEW-HEAD
438 # > param csuite SUITE
439 # > param tagformat old|new
440 # > param maint-view MAINT-VIEW-HEAD
442 # > param buildinfo-filename P_V_X.buildinfo # zero or more times
443 # > file buildinfo # for buildinfos to sign
445 # > previously REFNAME=OBJNAME # if --deliberately-not-fast-forward
446 # # goes into tag, for replay prevention
449 # [indicates that signed tag is wanted]
450 # < data-block NBYTES
451 # < [NBYTES bytes of data (no newline)]
452 # [maybe some more blocks]
456 # > want signed-dsc-changes
457 # < data-block NBYTES [transfer of signed dsc]
459 # < data-block NBYTES [transfer of signed changes]
461 # < data-block NBYTES [transfer of each signed buildinfo
462 # [etc] same number and order as "file buildinfo"]
470 sub i_child_report () {
471 # Sees if our child has died, and reap it if so. Returns a string
472 # describing how it died if it failed, or undef otherwise.
473 return undef unless $i_child_pid;
474 my $got = waitpid $i_child_pid, WNOHANG;
475 return undef if $got <= 0;
476 die unless $got == $i_child_pid;
477 $i_child_pid = undef;
478 return undef unless $?;
479 return f_ "build host child %s", waitstatusmsg();
484 fail f_ "connection lost: %s", $! if $fh->error;
485 fail f_ "protocol violation; %s not expected", $m;
488 sub badproto_badread ($$) {
490 fail f_ "connection lost: %s", $! if $!;
491 my $report = i_child_report();
492 fail $report if defined $report;
493 badproto $fh, f_ "eof (reading %s)", $wh;
496 sub protocol_expect (&$) {
497 my ($match, $fh) = @_;
500 defined && chomp or badproto_badread $fh, __ "protocol message";
508 badproto $fh, f_ "\`%s'", $_;
511 sub protocol_send_file ($$) {
512 my ($fh, $ourfn) = @_;
513 open PF, "<", $ourfn or die "$ourfn: $!";
516 my $got = read PF, $d, 65536;
517 die "$ourfn: $!" unless defined $got;
519 print $fh "data-block ".length($d)."\n" or confess $!;
520 print $fh $d or confess $!;
522 PF->error and die "$ourfn $!";
523 print $fh "data-end\n" or confess $!;
527 sub protocol_read_bytes ($$) {
528 my ($fh, $nbytes) = @_;
529 $nbytes =~ m/^[1-9]\d{0,5}$|^0$/ or badproto \*RO, __ "bad byte count";
531 my $got = read $fh, $d, $nbytes;
532 $got==$nbytes or badproto_badread $fh, __ "data block";
536 sub protocol_receive_file ($$) {
537 my ($fh, $ourfn) = @_;
538 printdebug "() $ourfn\n";
539 open PF, ">", $ourfn or die "$ourfn: $!";
541 my ($y,$l) = protocol_expect {
542 m/^data-block (.*)$/ ? (1,$1) :
543 m/^data-end$/ ? (0,) :
547 my $d = protocol_read_bytes $fh, $l;
548 print PF $d or confess $!;
550 close PF or confess $!;
553 #---------- remote protocol support, responder ----------
555 sub responder_send_command ($) {
557 return unless $we_are_responder;
558 # called even without $we_are_responder
559 printdebug ">> $command\n";
560 print PO $command, "\n" or confess $!;
563 sub responder_send_file ($$) {
564 my ($keyword, $ourfn) = @_;
565 return unless $we_are_responder;
566 printdebug "]] $keyword $ourfn\n";
567 responder_send_command "file $keyword";
568 protocol_send_file \*PO, $ourfn;
571 sub responder_receive_files ($@) {
572 my ($keyword, @ourfns) = @_;
573 die unless $we_are_responder;
574 printdebug "[[ $keyword @ourfns\n";
575 responder_send_command "want $keyword";
576 foreach my $fn (@ourfns) {
577 protocol_receive_file \*PI, $fn;
580 protocol_expect { m/^files-end$/ } \*PI;
583 #---------- remote protocol support, initiator ----------
585 sub initiator_expect (&) {
587 protocol_expect { &$match } \*RO;
590 #---------- end remote code ----------
593 if ($we_are_responder) {
595 responder_send_command "progress ".length($m) or confess $!;
596 print PO $m or confess $!;
606 $ua = LWP::UserAgent->new();
610 progress "downloading $what...";
611 my $r = $ua->get(@_) or confess $!;
612 return undef if $r->code == 404;
613 $r->is_success or fail f_ "failed to fetch %s: %s",
614 $what, $r->status_line;
615 return $r->decoded_content(charset => 'none');
618 our ($dscdata,$dscurl,$dsc,$dsc_checked,$skew_warning_vsn);
620 sub act_local () { return $dryrun_level <= 1; }
621 sub act_scary () { return !$dryrun_level; }
624 if (!$dryrun_level) {
625 progress f_ "%s ok: %s", $us, "@_";
627 progress f_ "would be ok: %s (but dry run only)", "@_";
632 printcmd(\*STDERR,$debugprefix."#",@_);
635 sub runcmd_ordryrun {
643 sub runcmd_ordryrun_local {
651 our $helpmsg = i_ <<END;
653 dgit [dgit-opts] clone [dgit-opts] package [suite] [./dir|/dir]
654 dgit [dgit-opts] fetch|pull [dgit-opts] [suite]
655 dgit [dgit-opts] build [dpkg-buildpackage-opts]
656 dgit [dgit-opts] sbuild [sbuild-opts]
657 dgit [dgit-opts] pbuilder|cowbuilder [debbuildopts]
658 dgit [dgit-opts] push [dgit-opts] [suite]
659 dgit [dgit-opts] push-source [dgit-opts] [suite]
660 dgit [dgit-opts] rpush build-host:build-dir ...
661 important dgit options:
662 -k<keyid> sign tag and package with <keyid> instead of default
663 --dry-run -n do not change anything, but go through the motions
664 --damp-run -L like --dry-run but make local changes, without signing
665 --new -N allow introducing a new package
666 --debug -D increase debug level
667 -c<name>=<value> set git config option (used directly by dgit too)
670 our $later_warning_msg = i_ <<END;
671 Perhaps the upload is stuck in incoming. Using the version from git.
675 print STDERR f_ "%s: %s\n%s", $us, "@_", __ $helpmsg or confess $!;
680 @ARGV or badusage __ "too few arguments";
681 return scalar shift @ARGV;
685 not_necessarily_a_tree();
688 print __ $helpmsg or confess $!;
692 our $td = $ENV{DGIT_TEST_DUMMY_DIR} || "DGIT_TEST_DUMMY_DIR-unset";
694 our %defcfg = ('dgit.default.distro' => 'debian',
695 'dgit.default.default-suite' => 'unstable',
696 'dgit.default.old-dsc-distro' => 'debian',
697 'dgit-suite.*-security.distro' => 'debian-security',
698 'dgit.default.username' => '',
699 'dgit.default.archive-query-default-component' => 'main',
700 'dgit.default.ssh' => 'ssh',
701 'dgit.default.archive-query' => 'madison:',
702 'dgit.default.sshpsql-dbname' => 'service=projectb',
703 'dgit.default.aptget-components' => 'main',
704 'dgit.default.dgit-tag-format' => 'new,old,maint',
705 'dgit.default.source-only-uploads' => 'ok',
706 'dgit.dsc-url-proto-ok.http' => 'true',
707 'dgit.dsc-url-proto-ok.https' => 'true',
708 'dgit.dsc-url-proto-ok.git' => 'true',
709 'dgit.vcs-git.suites', => 'sid', # ;-separated
710 'dgit.default.dsc-url-proto-ok' => 'false',
711 # old means "repo server accepts pushes with old dgit tags"
712 # new means "repo server accepts pushes with new dgit tags"
713 # maint means "repo server accepts split brain pushes"
714 # hist means "repo server may have old pushes without new tag"
715 # ("hist" is implied by "old")
716 'dgit-distro.debian.archive-query' => 'ftpmasterapi:',
717 'dgit-distro.debian.git-check' => 'url',
718 'dgit-distro.debian.git-check-suffix' => '/info/refs',
719 'dgit-distro.debian.new-private-pushers' => 't',
720 'dgit-distro.debian.source-only-uploads' => 'not-wholly-new',
721 'dgit-distro.debian/push.git-url' => '',
722 'dgit-distro.debian/push.git-host' => 'push.dgit.debian.org',
723 'dgit-distro.debian/push.git-user-force' => 'dgit',
724 'dgit-distro.debian/push.git-proto' => 'git+ssh://',
725 'dgit-distro.debian/push.git-path' => '/dgit/debian/repos',
726 'dgit-distro.debian/push.git-create' => 'true',
727 'dgit-distro.debian/push.git-check' => 'ssh-cmd',
728 'dgit-distro.debian.archive-query-url', 'https://api.ftp-master.debian.org/',
729 # 'dgit-distro.debian.archive-query-tls-key',
730 # '/etc/ssl/certs/%HOST%.pem:/etc/dgit/%HOST%.pem',
731 # ^ this does not work because curl is broken nowadays
732 # Fixing #790093 properly will involve providing providing the key
733 # in some pacagke and maybe updating these paths.
735 # 'dgit-distro.debian.archive-query-tls-curl-args',
736 # '--ca-path=/etc/ssl/ca-debian',
737 # ^ this is a workaround but works (only) on DSA-administered machines
738 'dgit-distro.debian.git-url' => 'https://git.dgit.debian.org',
739 'dgit-distro.debian.git-url-suffix' => '',
740 'dgit-distro.debian.upload-host' => 'ftp-master', # for dput
741 'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/',
742 'dgit-distro.debian-security.archive-query' => 'aptget:',
743 'dgit-distro.debian-security.mirror' => 'http://security.debian.org/debian-security/',
744 'dgit-distro.debian-security.aptget-suite-map' => 's#-security$#/updates#',
745 'dgit-distro.debian-security.aptget-suite-rmap' => 's#$#-security#',
746 'dgit-distro.debian-security.nominal-distro' => 'debian',
747 'dgit-distro.debian.backports-quirk' => '(squeeze)-backports*',
748 'dgit-distro.debian-backports.mirror' => 'http://backports.debian.org/debian-backports/',
749 'dgit-distro.ubuntu.git-check' => 'false',
750 'dgit-distro.ubuntu.mirror' => 'http://archive.ubuntu.com/ubuntu',
751 'dgit-distro.test-dummy.ssh' => "$td/ssh",
752 'dgit-distro.test-dummy.username' => "alice",
753 'dgit-distro.test-dummy.git-check' => "ssh-cmd",
754 'dgit-distro.test-dummy.git-create' => "ssh-cmd",
755 'dgit-distro.test-dummy.git-url' => "$td/git",
756 'dgit-distro.test-dummy.git-host' => "git",
757 'dgit-distro.test-dummy.git-path' => "$td/git",
758 'dgit-distro.test-dummy.archive-query' => "dummycatapi:",
759 'dgit-distro.test-dummy.archive-query-url' => "file://$td/aq/",
760 'dgit-distro.test-dummy.mirror' => "file://$td/mirror/",
761 'dgit-distro.test-dummy.upload-host' => 'test-dummy',
765 our @gitcfgsources = qw(cmdline local global system);
766 our $invoked_in_git_tree = 1;
768 sub git_slurp_config () {
769 # This algoritm is a bit subtle, but this is needed so that for
770 # options which we want to be single-valued, we allow the
771 # different config sources to override properly. See #835858.
772 foreach my $src (@gitcfgsources) {
773 next if $src eq 'cmdline';
774 # we do this ourselves since git doesn't handle it
776 $gitcfgs{$src} = git_slurp_config_src $src;
780 sub git_get_config ($) {
782 foreach my $src (@gitcfgsources) {
783 my $l = $gitcfgs{$src}{$c};
784 confess "internal error ($l $c)" if $l && !ref $l;
785 printdebug"C $c ".(defined $l ?
786 join " ", map { messagequote "'$_'" } @$l :
791 f_ "multiple values for %s (in %s git config)", $c, $src
800 return undef if $c =~ /RETURN-UNDEF/;
801 printdebug "C? $c\n" if $debuglevel >= 5;
802 my $v = git_get_config($c);
803 return $v if defined $v;
804 my $dv = $defcfg{$c};
806 printdebug "CD $c $dv\n" if $debuglevel >= 4;
811 "need value for one of: %s\n".
812 "%s: distro or suite appears not to be (properly) supported",
816 sub not_necessarily_a_tree () {
817 # needs to be called from pre_*
818 @gitcfgsources = grep { $_ ne 'local' } @gitcfgsources;
819 $invoked_in_git_tree = 0;
822 sub access_basedistro__noalias () {
823 if (defined $idistro) {
826 my $def = cfg("dgit-suite.$isuite.distro", 'RETURN-UNDEF');
827 return $def if defined $def;
828 foreach my $src (@gitcfgsources, 'internal') {
829 my $kl = $src eq 'internal' ? \%defcfg : $gitcfgs{$src};
831 foreach my $k (keys %$kl) {
832 next unless $k =~ m#^dgit-suite\.(.*)\.distro$#;
834 next unless match_glob $dpat, $isuite;
838 return cfg("dgit.default.distro");
842 sub access_basedistro () {
843 my $noalias = access_basedistro__noalias();
844 my $canon = cfg("dgit-distro.$noalias.alias-canon",'RETURN-UNDEF');
845 return $canon // $noalias;
848 sub access_nomdistro () {
849 my $base = access_basedistro();
850 my $r = cfg("dgit-distro.$base.nominal-distro",'RETURN-UNDEF') // $base;
851 $r =~ m/^$distro_re$/ or badcfg
852 f_ "bad syntax for (nominal) distro \`%s' (does not match %s)",
853 $r, "/^$distro_re$/";
857 sub access_quirk () {
858 # returns (quirk name, distro to use instead or undef, quirk-specific info)
859 my $basedistro = access_basedistro();
860 my $backports_quirk = cfg("dgit-distro.$basedistro.backports-quirk",
862 if (defined $backports_quirk) {
863 my $re = $backports_quirk;
864 $re =~ s/[^-0-9a-z_\%*()]/\\$&/ig;
866 $re =~ s/\%/([-0-9a-z_]+)/
867 or $re =~ m/[()]/ or badcfg __ "backports-quirk needs \% or ( )";
868 if ($isuite =~ m/^$re$/) {
869 return ('backports',"$basedistro-backports",$1);
872 return ('none',undef);
877 sub parse_cfg_bool ($$$) {
878 my ($what,$def,$v) = @_;
881 $v =~ m/^[ty1]/ ? 1 :
882 $v =~ m/^[fn0]/ ? 0 :
883 badcfg f_ "%s needs t (true, y, 1) or f (false, n, 0) not \`%s'",
887 sub access_forpush_config () {
888 my $d = access_basedistro();
892 parse_cfg_bool('new-private-pushers', 0,
893 cfg("dgit-distro.$d.new-private-pushers",
896 my $v = cfg("dgit-distro.$d.readonly", 'RETURN-UNDEF');
899 $v =~ m/^[ty1]/ ? 0 : # force readonly, forpush = 0
900 $v =~ m/^[fn0]/ ? 1 : # force nonreadonly, forpush = 1
901 $v =~ m/^[a]/ ? '' : # auto, forpush = ''
903 "readonly needs t (true, y, 1) or f (false, n, 0) or a (auto)";
906 sub access_forpush () {
907 $access_forpush //= access_forpush_config();
908 return $access_forpush;
912 confess +(__ 'internal error').' '.Dumper($access_forpush)," ?" if
913 defined $access_forpush and !$access_forpush;
914 badcfg __ "pushing but distro is configured readonly"
915 if access_forpush_config() eq '0';
917 $supplementary_message = __ <<'END' unless $we_are_responder;
918 Push failed, before we got started.
919 You can retry the push, after fixing the problem, if you like.
921 parseopts_late_defaults();
925 parseopts_late_defaults();
928 sub supplementary_message ($) {
930 if (!$we_are_responder) {
931 $supplementary_message = $msg;
933 } elsif ($protovsn >= 3) {
934 responder_send_command "supplementary-message ".length($msg)
936 print PO $msg or confess $!;
940 sub access_distros () {
941 # Returns list of distros to try, in order
944 # 0. `instead of' distro name(s) we have been pointed to
945 # 1. the access_quirk distro, if any
946 # 2a. the user's specified distro, or failing that } basedistro
947 # 2b. the distro calculated from the suite }
948 my @l = access_basedistro();
950 my (undef,$quirkdistro) = access_quirk();
951 unshift @l, $quirkdistro;
952 unshift @l, $instead_distro;
953 @l = grep { defined } @l;
955 push @l, access_nomdistro();
957 if (access_forpush()) {
958 @l = map { ("$_/push", $_) } @l;
963 sub access_cfg_cfgs (@) {
966 # The nesting of these loops determines the search order. We put
967 # the key loop on the outside so that we search all the distros
968 # for each key, before going on to the next key. That means that
969 # if access_cfg is called with a more specific, and then a less
970 # specific, key, an earlier distro can override the less specific
971 # without necessarily overriding any more specific keys. (If the
972 # distro wants to override the more specific keys it can simply do
973 # so; whereas if we did the loop the other way around, it would be
974 # impossible to for an earlier distro to override a less specific
975 # key but not the more specific ones without restating the unknown
976 # values of the more specific keys.
979 # We have to deal with RETURN-UNDEF specially, so that we don't
980 # terminate the search prematurely.
982 if (m/RETURN-UNDEF/) { push @rundef, $_; last; }
985 foreach my $d (access_distros()) {
986 push @cfgs, map { "dgit-distro.$d.$_" } @realkeys;
988 push @cfgs, map { "dgit.default.$_" } @realkeys;
995 my (@cfgs) = access_cfg_cfgs(@keys);
996 my $value = cfg(@cfgs);
1000 sub access_cfg_bool ($$) {
1001 my ($def, @keys) = @_;
1002 parse_cfg_bool($keys[0], $def, access_cfg(@keys, 'RETURN-UNDEF'));
1005 sub string_to_ssh ($) {
1007 if ($spec =~ m/\s/) {
1008 return qw(sh -ec), 'exec '.$spec.' "$@"', 'x';
1014 sub access_cfg_ssh () {
1015 my $gitssh = access_cfg('ssh', 'RETURN-UNDEF');
1016 if (!defined $gitssh) {
1019 return string_to_ssh $gitssh;
1023 sub access_runeinfo ($) {
1025 return ": dgit ".access_basedistro()." $info ;";
1028 sub access_someuserhost ($) {
1030 my $user = access_cfg("$some-user-force", 'RETURN-UNDEF');
1031 defined($user) && length($user) or
1032 $user = access_cfg("$some-user",'username');
1033 my $host = access_cfg("$some-host");
1034 return length($user) ? "$user\@$host" : $host;
1037 sub access_gituserhost () {
1038 return access_someuserhost('git');
1041 sub access_giturl (;$) {
1042 my ($optional) = @_;
1043 my $url = access_cfg('git-url','RETURN-UNDEF');
1046 my $proto = access_cfg('git-proto', 'RETURN-UNDEF');
1047 return undef unless defined $proto;
1050 access_gituserhost().
1051 access_cfg('git-path');
1053 $suffix = access_cfg('git-url-suffix','RETURN-UNDEF');
1056 return "$url/$package$suffix";
1059 sub commit_getclogp ($) {
1060 # Returns the parsed changelog hashref for a particular commit
1062 our %commit_getclogp_memo;
1063 my $memo = $commit_getclogp_memo{$objid};
1064 return $memo if $memo;
1066 my $mclog = dgit_privdir()."clog";
1067 runcmd shell_cmd "exec >$mclog", @git, qw(cat-file blob),
1068 "$objid:debian/changelog";
1069 $commit_getclogp_memo{$objid} = parsechangelog("-l$mclog");
1072 sub parse_dscdata () {
1073 my $dscfh = new IO::File \$dscdata, '<' or confess $!;
1074 printdebug Dumper($dscdata) if $debuglevel>1;
1075 $dsc = parsecontrolfh($dscfh,$dscurl,1);
1076 printdebug Dumper($dsc) if $debuglevel>1;
1081 sub archive_query ($;@) {
1082 my ($method) = shift @_;
1083 fail __ "this operation does not support multiple comma-separated suites"
1085 my $query = access_cfg('archive-query','RETURN-UNDEF');
1086 $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
1089 { no strict qw(refs); &{"${method}_${proto}"}($proto,$data,@_); }
1092 sub archive_query_prepend_mirror {
1093 my $m = access_cfg('mirror');
1094 return map { [ $_->[0], $m.$_->[1], @$_[2..$#$_] ] } @_;
1097 sub pool_dsc_subpath ($$) {
1098 my ($vsn,$component) = @_; # $package is implict arg
1099 my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
1100 return "/pool/$component/$prefix/$package/".dscfn($vsn);
1103 sub cfg_apply_map ($$$) {
1104 my ($varref, $what, $mapspec) = @_;
1105 return unless $mapspec;
1107 printdebug "config $what EVAL{ $mapspec; }\n";
1109 eval "package Dgit::Config; $mapspec;";
1114 #---------- `ftpmasterapi' archive query method (nascent) ----------
1116 sub archive_api_query_cmd ($) {
1118 my @cmd = (@curl, qw(-sS));
1119 my $url = access_cfg('archive-query-url');
1120 if ($url =~ m#^https://([-.0-9a-z]+)/#) {
1122 my $keys = access_cfg('archive-query-tls-key','RETURN-UNDEF') //'';
1123 foreach my $key (split /\:/, $keys) {
1124 $key =~ s/\%HOST\%/$host/g;
1126 fail "for $url: stat $key: $!" unless $!==ENOENT;
1129 fail f_ "config requested specific TLS key but do not know".
1130 " how to get curl to use exactly that EE key (%s)",
1132 # push @cmd, "--cacert", $key, "--capath", "/dev/enoent";
1133 # # Sadly the above line does not work because of changes
1134 # # to gnutls. The real fix for #790093 may involve
1135 # # new curl options.
1138 # Fixing #790093 properly will involve providing a value
1139 # for this on clients.
1140 my $kargs = access_cfg('archive-query-tls-curl-ca-args','RETURN-UNDEF');
1141 push @cmd, split / /, $kargs if defined $kargs;
1143 push @cmd, $url.$subpath;
1147 sub api_query ($$;$) {
1149 my ($data, $subpath, $ok404) = @_;
1150 badcfg __ "ftpmasterapi archive query method takes no data part"
1152 my @cmd = archive_api_query_cmd($subpath);
1153 my $url = $cmd[$#cmd];
1154 push @cmd, qw(-w %{http_code});
1155 my $json = cmdoutput @cmd;
1156 unless ($json =~ s/\d+\d+\d$//) {
1157 failedcmd_report_cmd undef, @cmd;
1158 fail __ "curl failed to print 3-digit HTTP code";
1161 return undef if $code eq '404' && $ok404;
1162 fail f_ "fetch of %s gave HTTP code %s", $url, $code
1163 unless $url =~ m#^file://# or $code =~ m/^2/;
1164 return decode_json($json);
1167 sub canonicalise_suite_ftpmasterapi {
1168 my ($proto,$data) = @_;
1169 my $suites = api_query($data, 'suites');
1171 foreach my $entry (@$suites) {
1173 my $v = $entry->{$_};
1174 defined $v && $v eq $isuite;
1175 } qw(codename name);
1176 push @matched, $entry;
1178 fail f_ "unknown suite %s, maybe -d would help", $isuite
1182 @matched==1 or die f_ "multiple matches for suite %s\n", $isuite;
1183 $cn = "$matched[0]{codename}";
1184 defined $cn or die f_ "suite %s info has no codename\n", $isuite;
1185 $cn =~ m/^$suite_re$/
1186 or die f_ "suite %s maps to bad codename\n", $isuite;
1188 die +(__ "bad ftpmaster api response: ")."$@\n".Dumper(\@matched)
1193 sub archive_query_ftpmasterapi {
1194 my ($proto,$data) = @_;
1195 my $info = api_query($data, "dsc_in_suite/$isuite/$package");
1197 my $digester = Digest::SHA->new(256);
1198 foreach my $entry (@$info) {
1200 my $vsn = "$entry->{version}";
1201 my ($ok,$msg) = version_check $vsn;
1202 die f_ "bad version: %s\n", $msg unless $ok;
1203 my $component = "$entry->{component}";
1204 $component =~ m/^$component_re$/ or die __ "bad component";
1205 my $filename = "$entry->{filename}";
1206 $filename && $filename !~ m#[^-+:._~0-9a-zA-Z/]|^[/.]|/[/.]#
1207 or die __ "bad filename";
1208 my $sha256sum = "$entry->{sha256sum}";
1209 $sha256sum =~ m/^[0-9a-f]+$/ or die __ "bad sha256sum";
1210 push @rows, [ $vsn, "/pool/$component/$filename",
1211 $digester, $sha256sum ];
1213 die +(__ "bad ftpmaster api response: ")."$@\n".Dumper($entry)
1216 @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
1217 return archive_query_prepend_mirror @rows;
1220 sub file_in_archive_ftpmasterapi {
1221 my ($proto,$data,$filename) = @_;
1222 my $pat = $filename;
1225 $pat =~ s#[^-+_.0-9a-z/]# sprintf '%%%02x', ord $& #ge;
1226 my $info = api_query($data, "file_in_archive/$pat", 1);
1229 sub package_not_wholly_new_ftpmasterapi {
1230 my ($proto,$data,$pkg) = @_;
1231 my $info = api_query($data,"madison?package=${pkg}&f=json");
1235 #---------- `aptget' archive query method ----------
1238 our $aptget_releasefile;
1239 our $aptget_configpath;
1241 sub aptget_aptget () { return @aptget, qw(-c), $aptget_configpath; }
1242 sub aptget_aptcache () { return @aptcache, qw(-c), $aptget_configpath; }
1244 sub aptget_cache_clean {
1245 runcmd_ordryrun_local qw(sh -ec),
1246 'cd "$1"; find -atime +30 -type f -print0 | xargs -0r rm --',
1250 sub aptget_lock_acquire () {
1251 my $lockfile = "$aptget_base/lock";
1252 open APTGET_LOCK, '>', $lockfile or confess "open $lockfile: $!";
1253 flock APTGET_LOCK, LOCK_EX or confess "lock $lockfile: $!";
1256 sub aptget_prep ($) {
1258 return if defined $aptget_base;
1260 badcfg __ "aptget archive query method takes no data part"
1263 my $cache = $ENV{XDG_CACHE_DIR} // "$ENV{HOME}/.cache";
1266 ensuredir "$cache/dgit";
1268 access_cfg('aptget-cachekey','RETURN-UNDEF')
1269 // access_nomdistro();
1271 $aptget_base = "$cache/dgit/aptget";
1272 ensuredir $aptget_base;
1274 my $quoted_base = $aptget_base;
1275 confess "$quoted_base contains bad chars, cannot continue"
1276 if $quoted_base =~ m/["\\]/; # apt.conf(5) says no escaping :-/
1278 ensuredir $aptget_base;
1280 aptget_lock_acquire();
1282 aptget_cache_clean();
1284 $aptget_configpath = "$aptget_base/apt.conf#$cachekey";
1285 my $sourceslist = "source.list#$cachekey";
1287 my $aptsuites = $isuite;
1288 cfg_apply_map(\$aptsuites, 'suite map',
1289 access_cfg('aptget-suite-map', 'RETURN-UNDEF'));
1291 open SRCS, ">", "$aptget_base/$sourceslist" or confess $!;
1292 printf SRCS "deb-src %s %s %s\n",
1293 access_cfg('mirror'),
1295 access_cfg('aptget-components')
1298 ensuredir "$aptget_base/cache";
1299 ensuredir "$aptget_base/lists";
1301 open CONF, ">", $aptget_configpath or confess $!;
1303 Debug::NoLocking "true";
1304 APT::Get::List-Cleanup "false";
1305 #clear APT::Update::Post-Invoke-Success;
1306 Dir::Etc::SourceList "$quoted_base/$sourceslist";
1307 Dir::State::Lists "$quoted_base/lists";
1308 Dir::Etc::preferences "$quoted_base/preferences";
1309 Dir::Cache::srcpkgcache "$quoted_base/cache/srcs#$cachekey";
1310 Dir::Cache::pkgcache "$quoted_base/cache/pkgs#$cachekey";
1313 foreach my $key (qw(
1316 Dir::Cache::Archives
1317 Dir::Etc::SourceParts
1318 Dir::Etc::preferencesparts
1320 ensuredir "$aptget_base/$key";
1321 print CONF "$key \"$quoted_base/$key\";\n" or confess $!;
1324 my $oldatime = (time // confess $!) - 1;
1325 foreach my $oldlist (<$aptget_base/lists/*Release>) {
1326 next unless stat_exists $oldlist;
1327 my ($mtime) = (stat _)[9];
1328 utime $oldatime, $mtime, $oldlist or die "$oldlist $!";
1331 runcmd_ordryrun_local aptget_aptget(), qw(update);
1334 foreach my $oldlist (<$aptget_base/lists/*Release>) {
1335 next unless stat_exists $oldlist;
1336 my ($atime) = (stat _)[8];
1337 next if $atime == $oldatime;
1338 push @releasefiles, $oldlist;
1340 my @inreleasefiles = grep { m#/InRelease$# } @releasefiles;
1341 @releasefiles = @inreleasefiles if @inreleasefiles;
1342 if (!@releasefiles) {
1343 fail f_ <<END, $isuite, $cache;
1344 apt seemed to not to update dgit's cached Release files for %s.
1346 is on a filesystem mounted `noatime'; if so, please use `relatime'.)
1349 confess "apt updated too many Release files (@releasefiles), erk"
1350 unless @releasefiles == 1;
1352 ($aptget_releasefile) = @releasefiles;
1355 sub canonicalise_suite_aptget {
1356 my ($proto,$data) = @_;
1359 my $release = parsecontrol $aptget_releasefile, "Release file", 1;
1361 foreach my $name (qw(Codename Suite)) {
1362 my $val = $release->{$name};
1364 printdebug "release file $name: $val\n";
1365 $val =~ m/^$suite_re$/o or fail f_
1366 "Release file (%s) specifies intolerable %s",
1367 $aptget_releasefile, $name;
1368 cfg_apply_map(\$val, 'suite rmap',
1369 access_cfg('aptget-suite-rmap', 'RETURN-UNDEF'));
1376 sub archive_query_aptget {
1377 my ($proto,$data) = @_;
1380 ensuredir "$aptget_base/source";
1381 foreach my $old (<$aptget_base/source/*.dsc>) {
1382 unlink $old or die "$old: $!";
1385 my $showsrc = cmdoutput aptget_aptcache(), qw(showsrc), $package;
1386 return () unless $showsrc =~ m/^package:\s*\Q$package\E\s*$/mi;
1387 # avoids apt-get source failing with ambiguous error code
1389 runcmd_ordryrun_local
1390 shell_cmd 'cd "$1"/source; shift', $aptget_base,
1391 aptget_aptget(), qw(--download-only --only-source source), $package;
1393 my @dscs = <$aptget_base/source/*.dsc>;
1394 fail __ "apt-get source did not produce a .dsc" unless @dscs;
1395 fail f_ "apt-get source produced several .dscs (%s)", "@dscs"
1398 my $pre_dsc = parsecontrol $dscs[0], $dscs[0], 1;
1401 my $uri = "file://". uri_escape $dscs[0];
1402 $uri =~ s{\%2f}{/}gi;
1403 return [ (getfield $pre_dsc, 'Version'), $uri ];
1406 sub file_in_archive_aptget () { return undef; }
1407 sub package_not_wholly_new_aptget () { return undef; }
1409 #---------- `dummyapicat' archive query method ----------
1410 # (untranslated, because this is for testing purposes etc.)
1412 sub archive_query_dummycatapi { archive_query_ftpmasterapi @_; }
1413 sub canonicalise_suite_dummycatapi { canonicalise_suite_ftpmasterapi @_; }
1415 sub dummycatapi_run_in_mirror ($@) {
1416 # runs $fn with FIA open onto rune
1417 my ($rune, $argl, $fn) = @_;
1419 my $mirror = access_cfg('mirror');
1420 $mirror =~ s#^file://#/# or die "$mirror ?";
1421 my @cmd = (qw(sh -ec), 'cd "$1"; shift'."\n".$rune,
1422 qw(x), $mirror, @$argl);
1423 debugcmd "-|", @cmd;
1424 open FIA, "-|", @cmd or confess $!;
1426 close FIA or ($!==0 && $?==141) or die failedcmd @cmd;
1430 sub file_in_archive_dummycatapi ($$$) {
1431 my ($proto,$data,$filename) = @_;
1433 dummycatapi_run_in_mirror '
1434 find -name "$1" -print0 |
1436 ', [$filename], sub {
1439 printdebug "| $_\n";
1440 m/^(\w+) (\S+)$/ or die "$_ ?";
1441 push @out, { sha256sum => $1, filename => $2 };
1447 sub package_not_wholly_new_dummycatapi {
1448 my ($proto,$data,$pkg) = @_;
1449 dummycatapi_run_in_mirror "
1450 find -name ${pkg}_*.dsc
1457 #---------- `madison' archive query method ----------
1459 sub archive_query_madison {
1460 return archive_query_prepend_mirror
1461 map { [ @$_[0..1] ] } madison_get_parse(@_);
1464 sub madison_get_parse {
1465 my ($proto,$data) = @_;
1466 die unless $proto eq 'madison';
1467 if (!length $data) {
1468 $data= access_cfg('madison-distro','RETURN-UNDEF');
1469 $data //= access_basedistro();
1471 $rmad{$proto,$data,$package} ||= cmdoutput
1472 qw(rmadison -asource),"-s$isuite","-u$data",$package;
1473 my $rmad = $rmad{$proto,$data,$package};
1476 foreach my $l (split /\n/, $rmad) {
1477 $l =~ m{^ \s*( [^ \t|]+ )\s* \|
1478 \s*( [^ \t|]+ )\s* \|
1479 \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
1480 \s*( [^ \t|]+ )\s* }x or die "$rmad ?";
1481 $1 eq $package or die "$rmad $package ?";
1488 $component = access_cfg('archive-query-default-component');
1490 $5 eq 'source' or die "$rmad ?";
1491 push @out, [$vsn,pool_dsc_subpath($vsn,$component),$newsuite];
1493 return sort { -version_compare($a->[0],$b->[0]); } @out;
1496 sub canonicalise_suite_madison {
1497 # madison canonicalises for us
1498 my @r = madison_get_parse(@_);
1500 "unable to canonicalise suite using package %s".
1501 " which does not appear to exist in suite %s;".
1502 " --existing-package may help",
1507 sub file_in_archive_madison { return undef; }
1508 sub package_not_wholly_new_madison { return undef; }
1510 #---------- `sshpsql' archive query method ----------
1511 # (untranslated, because this is obsolete)
1514 my ($data,$runeinfo,$sql) = @_;
1515 if (!length $data) {
1516 $data= access_someuserhost('sshpsql').':'.
1517 access_cfg('sshpsql-dbname');
1519 $data =~ m/:/ or badcfg "invalid sshpsql method string \`$data'";
1520 my ($userhost,$dbname) = ($`,$'); #';
1522 my @cmd = (access_cfg_ssh, $userhost,
1523 access_runeinfo("ssh-psql $runeinfo").
1524 " export LC_MESSAGES=C; export LC_CTYPE=C;".
1525 " ".shellquote qw(psql -A), $dbname, qw(-c), $sql);
1527 open P, "-|", @cmd or confess $!;
1530 printdebug(">|$_|\n");
1533 $!=0; $?=0; close P or failedcmd @cmd;
1535 my $nrows = pop @rows;
1536 $nrows =~ s/^\((\d+) rows?\)$/$1/ or die "$nrows ?";
1537 @rows == $nrows+1 or die "$nrows ".(scalar @rows)." ?";
1538 @rows = map { [ split /\|/, $_ ] } @rows;
1539 my $ncols = scalar @{ shift @rows };
1540 die if grep { scalar @$_ != $ncols } @rows;
1544 sub sql_injection_check {
1545 foreach (@_) { die "$_ $& ?" if m{[^-+=:_.,/0-9a-zA-Z]}; }
1548 sub archive_query_sshpsql ($$) {
1549 my ($proto,$data) = @_;
1550 sql_injection_check $isuite, $package;
1551 my @rows = sshpsql($data, "archive-query $isuite $package", <<END);
1552 SELECT source.version, component.name, files.filename, files.sha256sum
1554 JOIN src_associations ON source.id = src_associations.source
1555 JOIN suite ON suite.id = src_associations.suite
1556 JOIN dsc_files ON dsc_files.source = source.id
1557 JOIN files_archive_map ON files_archive_map.file_id = dsc_files.file
1558 JOIN component ON component.id = files_archive_map.component_id
1559 JOIN files ON files.id = dsc_files.file
1560 WHERE ( suite.suite_name='$isuite' OR suite.codename='$isuite' )
1561 AND source.source='$package'
1562 AND files.filename LIKE '%.dsc';
1564 @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
1565 my $digester = Digest::SHA->new(256);
1567 my ($vsn,$component,$filename,$sha256sum) = @$_;
1568 [ $vsn, "/pool/$component/$filename",$digester,$sha256sum ];
1570 return archive_query_prepend_mirror @rows;
1573 sub canonicalise_suite_sshpsql ($$) {
1574 my ($proto,$data) = @_;
1575 sql_injection_check $isuite;
1576 my @rows = sshpsql($data, "canonicalise-suite $isuite", <<END);
1577 SELECT suite.codename
1578 FROM suite where suite_name='$isuite' or codename='$isuite';
1580 @rows = map { $_->[0] } @rows;
1581 fail "unknown suite $isuite" unless @rows;
1582 die "ambiguous $isuite: @rows ?" if @rows>1;
1586 sub file_in_archive_sshpsql ($$$) { return undef; }
1587 sub package_not_wholly_new_sshpsql ($$$) { return undef; }
1589 #---------- `dummycat' archive query method ----------
1590 # (untranslated, because this is for testing purposes etc.)
1592 sub canonicalise_suite_dummycat ($$) {
1593 my ($proto,$data) = @_;
1594 my $dpath = "$data/suite.$isuite";
1595 if (!open C, "<", $dpath) {
1596 $!==ENOENT or die "$dpath: $!";
1597 printdebug "dummycat canonicalise_suite $isuite $dpath ENOENT\n";
1601 chomp or die "$dpath: $!";
1603 printdebug "dummycat canonicalise_suite $isuite $dpath = $_\n";
1607 sub archive_query_dummycat ($$) {
1608 my ($proto,$data) = @_;
1609 canonicalise_suite();
1610 my $dpath = "$data/package.$csuite.$package";
1611 if (!open C, "<", $dpath) {
1612 $!==ENOENT or die "$dpath: $!";
1613 printdebug "dummycat query $csuite $package $dpath ENOENT\n";
1621 printdebug "dummycat query $csuite $package $dpath | $_\n";
1622 my @row = split /\s+/, $_;
1623 @row==2 or die "$dpath: $_ ?";
1626 C->error and die "$dpath: $!";
1628 return archive_query_prepend_mirror
1629 sort { -version_compare($a->[0],$b->[0]); } @rows;
1632 sub file_in_archive_dummycat () { return undef; }
1633 sub package_not_wholly_new_dummycat () { return undef; }
1635 #---------- tag format handling ----------
1636 # (untranslated, because everything should be new tag format by now)
1638 sub access_cfg_tagformats () {
1639 split /\,/, access_cfg('dgit-tag-format');
1642 sub access_cfg_tagformats_can_splitbrain () {
1643 my %y = map { $_ => 1 } access_cfg_tagformats;
1644 foreach my $needtf (qw(new maint)) {
1645 next if $y{$needtf};
1651 sub need_tagformat ($$) {
1652 my ($fmt, $why) = @_;
1653 fail "need to use tag format $fmt ($why) but also need".
1654 " to use tag format $tagformat_want->[0] ($tagformat_want->[1])".
1655 " - no way to proceed"
1656 if $tagformat_want && $tagformat_want->[0] ne $fmt;
1657 $tagformat_want = [$fmt, $why, $tagformat_want->[2] // 0];
1660 sub select_tagformat () {
1662 return if $tagformatfn && !$tagformat_want;
1663 die 'bug' if $tagformatfn && $tagformat_want;
1664 # ... $tagformat_want assigned after previous select_tagformat
1666 my (@supported) = grep { $_ =~ m/^(?:old|new)$/ } access_cfg_tagformats();
1667 printdebug "select_tagformat supported @supported\n";
1669 $tagformat_want //= [ $supported[0], "distro access configuration", 0 ];
1670 printdebug "select_tagformat specified @$tagformat_want\n";
1672 my ($fmt,$why,$override) = @$tagformat_want;
1674 fail "target distro supports tag formats @supported".
1675 " but have to use $fmt ($why)"
1677 or grep { $_ eq $fmt } @supported;
1679 $tagformat_want = undef;
1681 $tagformatfn = ${*::}{"debiantag_$fmt"};
1683 fail "trying to use unknown tag format \`$fmt' ($why) !"
1684 unless $tagformatfn;
1687 #---------- archive query entrypoints and rest of program ----------
1689 sub canonicalise_suite () {
1690 return if defined $csuite;
1691 fail f_ "cannot operate on %s suite", $isuite if $isuite eq 'UNRELEASED';
1692 $csuite = archive_query('canonicalise_suite');
1693 if ($isuite ne $csuite) {
1694 progress f_ "canonical suite name for %s is %s", $isuite, $csuite;
1696 progress f_ "canonical suite name is %s", $csuite;
1700 sub get_archive_dsc () {
1701 canonicalise_suite();
1702 my @vsns = archive_query('archive_query');
1703 foreach my $vinfo (@vsns) {
1704 my ($vsn,$vsn_dscurl,$digester,$digest) = @$vinfo;
1705 $dscurl = $vsn_dscurl;
1706 $dscdata = url_get($dscurl);
1708 $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
1713 $digester->add($dscdata);
1714 my $got = $digester->hexdigest();
1716 fail f_ "%s has hash %s but archive told us to expect %s",
1717 $dscurl, $got, $digest;
1720 my $fmt = getfield $dsc, 'Format';
1721 $format_ok{$fmt} or forceable_fail [qw(unsupported-source-format)],
1722 f_ "unsupported source format %s, sorry", $fmt;
1724 $dsc_checked = !!$digester;
1725 printdebug "get_archive_dsc: Version ".(getfield $dsc, 'Version')."\n";
1729 printdebug "get_archive_dsc: nothing in archive, returning undef\n";
1732 sub check_for_git ();
1733 sub check_for_git () {
1735 my $how = access_cfg('git-check');
1736 if ($how eq 'ssh-cmd') {
1738 (access_cfg_ssh, access_gituserhost(),
1739 access_runeinfo("git-check $package").
1740 " set -e; cd ".access_cfg('git-path').";".
1741 " if test -d $package.git; then echo 1; else echo 0; fi");
1742 my $r= cmdoutput @cmd;
1743 if (defined $r and $r =~ m/^divert (\w+)$/) {
1745 my ($usedistro,) = access_distros();
1746 # NB that if we are pushing, $usedistro will be $distro/push
1747 $instead_distro= cfg("dgit-distro.$usedistro.diverts.$divert");
1748 $instead_distro =~ s{^/}{ access_basedistro()."/" }e;
1749 progress f_ "diverting to %s (using config for %s)",
1750 $divert, $instead_distro;
1751 return check_for_git();
1753 failedcmd @cmd unless defined $r and $r =~ m/^[01]$/;
1755 } elsif ($how eq 'url') {
1756 my $prefix = access_cfg('git-check-url','git-url');
1757 my $suffix = access_cfg('git-check-suffix','git-suffix',
1758 'RETURN-UNDEF') // '.git';
1759 my $url = "$prefix/$package$suffix";
1760 my @cmd = (@curl, qw(-sS -I), $url);
1761 my $result = cmdoutput @cmd;
1762 $result =~ s/^\S+ 200 .*\n\r?\n//;
1763 # curl -sS -I with https_proxy prints
1764 # HTTP/1.0 200 Connection established
1765 $result =~ m/^\S+ (404|200) /s or
1766 fail +(__ "unexpected results from git check query - ").
1767 Dumper($prefix, $result);
1769 if ($code eq '404') {
1771 } elsif ($code eq '200') {
1776 } elsif ($how eq 'true') {
1778 } elsif ($how eq 'false') {
1781 badcfg f_ "unknown git-check \`%s'", $how;
1785 sub create_remote_git_repo () {
1786 my $how = access_cfg('git-create');
1787 if ($how eq 'ssh-cmd') {
1789 (access_cfg_ssh, access_gituserhost(),
1790 access_runeinfo("git-create $package").
1791 "set -e; cd ".access_cfg('git-path').";".
1792 " cp -a _template $package.git");
1793 } elsif ($how eq 'true') {
1796 badcfg f_ "unknown git-create \`%s'", $how;
1800 our ($dsc_hash,$lastpush_mergeinput);
1801 our ($dsc_distro, $dsc_hint_tag, $dsc_hint_url);
1805 dgit_privdir(); # ensures that $dgit_privdir_made is based on $maindir
1806 $playground = fresh_playground 'dgit/unpack';
1809 sub mktree_in_ud_here () {
1810 playtree_setup $gitcfgs{local};
1813 sub git_write_tree () {
1814 my $tree = cmdoutput @git, qw(write-tree);
1815 $tree =~ m/^\w+$/ or die "$tree ?";
1819 sub git_add_write_tree () {
1820 runcmd @git, qw(add -Af .);
1821 return git_write_tree();
1824 sub remove_stray_gits ($) {
1826 my @gitscmd = qw(find -name .git -prune -print0);
1827 debugcmd "|",@gitscmd;
1828 open GITS, "-|", @gitscmd or confess $!;
1833 print STDERR f_ "%s: warning: removing from %s: %s\n",
1834 $us, $what, (messagequote $_);
1838 $!=0; $?=0; close GITS or failedcmd @gitscmd;
1841 sub mktree_in_ud_from_only_subdir ($;$) {
1842 my ($what,$raw) = @_;
1843 # changes into the subdir
1846 confess "expected one subdir but found @dirs ?" unless @dirs==1;
1847 $dirs[0] =~ m#^([^/]+)/\.$# or die;
1851 remove_stray_gits($what);
1852 mktree_in_ud_here();
1854 my ($format, $fopts) = get_source_format();
1855 if (madformat($format)) {
1860 my $tree=git_add_write_tree();
1861 return ($tree,$dir);
1864 our @files_csum_info_fields =
1865 (['Checksums-Sha256','Digest::SHA', 'new(256)', 'sha256sum'],
1866 ['Checksums-Sha1', 'Digest::SHA', 'new(1)', 'sha1sum'],
1867 ['Files', 'Digest::MD5', 'new()', 'md5sum']);
1869 sub dsc_files_info () {
1870 foreach my $csumi (@files_csum_info_fields) {
1871 my ($fname, $module, $method) = @$csumi;
1872 my $field = $dsc->{$fname};
1873 next unless defined $field;
1874 eval "use $module; 1;" or die $@;
1876 foreach (split /\n/, $field) {
1878 m/^(\w+) (\d+) (\S+)$/ or
1879 fail f_ "could not parse .dsc %s line \`%s'", $fname, $_;
1880 my $digester = eval "$module"."->$method;" or die $@;
1885 Digester => $digester,
1890 fail f_ "missing any supported Checksums-* or Files field in %s",
1891 $dsc->get_option('name');
1895 map { $_->{Filename} } dsc_files_info();
1898 sub files_compare_inputs (@) {
1903 my $showinputs = sub {
1904 return join "; ", map { $_->get_option('name') } @$inputs;
1907 foreach my $in (@$inputs) {
1909 my $in_name = $in->get_option('name');
1911 printdebug "files_compare_inputs $in_name\n";
1913 foreach my $csumi (@files_csum_info_fields) {
1914 my ($fname) = @$csumi;
1915 printdebug "files_compare_inputs $in_name $fname\n";
1917 my $field = $in->{$fname};
1918 next unless defined $field;
1921 foreach (split /\n/, $field) {
1924 my ($info, $f) = m/^(\w+ \d+) (?:\S+ \S+ )?(\S+)$/ or
1925 fail "could not parse $in_name $fname line \`$_'";
1927 printdebug "files_compare_inputs $in_name $fname $f\n";
1931 my $re = \ $record{$f}{$fname};
1933 $fchecked{$f}{$in_name} = 1;
1936 "hash or size of %s varies in %s fields (between: %s)",
1937 $f, $fname, $showinputs->();
1942 @files = sort @files;
1943 $expected_files //= \@files;
1944 "@$expected_files" eq "@files" or
1945 fail f_ "file list in %s varies between hash fields!",
1949 fail f_ "%s has no files list field(s)", $in_name;
1951 printdebug "files_compare_inputs ".Dumper(\%fchecked, \%record)
1954 grep { keys %$_ == @$inputs-1 } values %fchecked
1955 or fail f_ "no file appears in all file lists (looked in: %s)",
1959 sub is_orig_file_in_dsc ($$) {
1960 my ($f, $dsc_files_info) = @_;
1961 return 0 if @$dsc_files_info <= 1;
1962 # One file means no origs, and the filename doesn't have a "what
1963 # part of dsc" component. (Consider versions ending `.orig'.)
1964 return 0 unless $f =~ m/\.$orig_f_tail_re$/o;
1968 # This function determines whether a .changes file is source-only from
1969 # the point of view of dak. Thus, it permits *_source.buildinfo
1972 # It does not, however, permit any other buildinfo files. After a
1973 # source-only upload, the buildds will try to upload files like
1974 # foo_1.2.3_amd64.buildinfo. If the package maintainer included files
1975 # named like this in their (otherwise) source-only upload, the uploads
1976 # of the buildd can be rejected by dak. Fixing the resultant
1977 # situation can require manual intervention. So we block such
1978 # .buildinfo files when the user tells us to perform a source-only
1979 # upload (such as when using the push-source subcommand with the -C
1980 # option, which calls this function).
1982 # Note, though, that when dgit is told to prepare a source-only
1983 # upload, such as when subcommands like build-source and push-source
1984 # without -C are used, dgit has a more restrictive notion of
1985 # source-only .changes than dak: such uploads will never include
1986 # *_source.buildinfo files. This is because there is no use for such
1987 # files when using a tool like dgit to produce the source package, as
1988 # dgit ensures the source is identical to git HEAD.
1989 sub test_source_only_changes ($) {
1991 foreach my $l (split /\n/, getfield $changes, 'Files') {
1992 $l =~ m/\S+$/ or next;
1993 # \.tar\.[a-z0-9]+ covers orig.tar and the tarballs in native packages
1994 unless ($& =~ m/(?:\.dsc|\.diff\.gz|\.tar\.[a-z0-9]+|_source\.buildinfo)$/) {
1995 print f_ "purportedly source-only changes polluted by %s\n", $&;
2002 sub changes_update_origs_from_dsc ($$$$) {
2003 my ($dsc, $changes, $upstreamvsn, $changesfile) = @_;
2005 printdebug "checking origs needed ($upstreamvsn)...\n";
2006 $_ = getfield $changes, 'Files';
2007 m/^\w+ \d+ (\S+ \S+) \S+$/m or
2008 fail __ "cannot find section/priority from .changes Files field";
2009 my $placementinfo = $1;
2011 printdebug "checking origs needed placement '$placementinfo'...\n";
2012 foreach my $l (split /\n/, getfield $dsc, 'Files') {
2013 $l =~ m/\S+$/ or next;
2015 printdebug "origs $file | $l\n";
2016 next unless is_orig_file_of_vsn $file, $upstreamvsn;
2017 printdebug "origs $file is_orig\n";
2018 my $have = archive_query('file_in_archive', $file);
2019 if (!defined $have) {
2020 print STDERR __ <<END;
2021 archive does not support .orig check; hope you used --ch:--sa/-sd if needed
2027 printdebug "origs $file \$#\$have=$#$have\n";
2028 foreach my $h (@$have) {
2031 foreach my $csumi (@files_csum_info_fields) {
2032 my ($fname, $module, $method, $archivefield) = @$csumi;
2033 next unless defined $h->{$archivefield};
2034 $_ = $dsc->{$fname};
2035 next unless defined;
2036 m/^(\w+) .* \Q$file\E$/m or
2037 fail f_ ".dsc %s missing entry for %s", $fname, $file;
2038 if ($h->{$archivefield} eq $1) {
2042 "%s: %s (archive) != %s (local .dsc)",
2043 $archivefield, $h->{$archivefield}, $1;
2046 confess "$file ".Dumper($h)." ?!" if $same && @differ;
2050 f_ "archive %s: %s", $h->{filename}, join "; ", @differ
2053 printdebug "origs $file f.same=$found_same".
2054 " #f._differ=$#found_differ\n";
2055 if (@found_differ && !$found_same) {
2057 (f_ "archive contains %s with different checksum", $file),
2060 # Now we edit the changes file to add or remove it
2061 foreach my $csumi (@files_csum_info_fields) {
2062 my ($fname, $module, $method, $archivefield) = @$csumi;
2063 next unless defined $changes->{$fname};
2065 # in archive, delete from .changes if it's there
2066 $changed{$file} = "removed" if
2067 $changes->{$fname} =~ s/\n.* \Q$file\E$(?:)$//m;
2068 } elsif ($changes->{$fname} =~ m/^.* \Q$file\E$(?:)$/m) {
2069 # not in archive, but it's here in the .changes
2071 my $dsc_data = getfield $dsc, $fname;
2072 $dsc_data =~ m/^(.* \Q$file\E$)$/m or die "$dsc_data $file ?";
2074 $extra =~ s/ \d+ /$&$placementinfo /
2075 or confess "$fname $extra >$dsc_data< ?"
2076 if $fname eq 'Files';
2077 $changes->{$fname} .= "\n". $extra;
2078 $changed{$file} = "added";
2083 foreach my $file (keys %changed) {
2085 "edited .changes for archive .orig contents: %s %s",
2086 $changed{$file}, $file;
2088 my $chtmp = "$changesfile.tmp";
2089 $changes->save($chtmp);
2091 rename $chtmp,$changesfile or die "$changesfile $!";
2093 progress f_ "[new .changes left in %s]", $changesfile;
2096 progress f_ "%s already has appropriate .orig(s) (if any)",
2101 sub make_commit ($) {
2103 return cmdoutput @git, qw(hash-object -w -t commit), $file;
2106 sub clogp_authline ($) {
2108 my $author = getfield $clogp, 'Maintainer';
2109 if ($author =~ m/^[^"\@]+\,/) {
2110 # single entry Maintainer field with unquoted comma
2111 $author = ($& =~ y/,//rd).$'; # strip the comma
2113 # git wants a single author; any remaining commas in $author
2114 # are by now preceded by @ (or "). It seems safer to punt on
2115 # "..." for now rather than attempting to dequote or something.
2116 $author =~ s#,.*##ms unless $author =~ m/"/;
2117 my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
2118 my $authline = "$author $date";
2119 $authline =~ m/$git_authline_re/o or
2120 fail f_ "unexpected commit author line format \`%s'".
2121 " (was generated from changelog Maintainer field)",
2123 return ($1,$2,$3) if wantarray;
2127 sub vendor_patches_distro ($$) {
2128 my ($checkdistro, $what) = @_;
2129 return unless defined $checkdistro;
2131 my $series = "debian/patches/\L$checkdistro\E.series";
2132 printdebug "checking for vendor-specific $series ($what)\n";
2134 if (!open SERIES, "<", $series) {
2135 confess "$series $!" unless $!==ENOENT;
2142 print STDERR __ <<END;
2144 Unfortunately, this source package uses a feature of dpkg-source where
2145 the same source package unpacks to different source code on different
2146 distros. dgit cannot safely operate on such packages on affected
2147 distros, because the meaning of source packages is not stable.
2149 Please ask the distro/maintainer to remove the distro-specific series
2150 files and use a different technique (if necessary, uploading actually
2151 different packages, if different distros are supposed to have
2155 fail f_ "Found active distro-specific series file for".
2156 " %s (%s): %s, cannot continue",
2157 $checkdistro, $what, $series;
2159 die "$series $!" if SERIES->error;
2163 sub check_for_vendor_patches () {
2164 # This dpkg-source feature doesn't seem to be documented anywhere!
2165 # But it can be found in the changelog (reformatted):
2167 # commit 4fa01b70df1dc4458daee306cfa1f987b69da58c
2168 # Author: Raphael Hertzog <hertzog@debian.org>
2169 # Date: Sun Oct 3 09:36:48 2010 +0200
2171 # dpkg-source: correctly create .pc/.quilt_series with alternate
2174 # If you have debian/patches/ubuntu.series and you were
2175 # unpacking the source package on ubuntu, quilt was still
2176 # directed to debian/patches/series instead of
2177 # debian/patches/ubuntu.series.
2179 # debian/changelog | 3 +++
2180 # scripts/Dpkg/Source/Package/V3/quilt.pm | 4 +++-
2181 # 2 files changed, 6 insertions(+), 1 deletion(-)
2184 vendor_patches_distro($ENV{DEB_VENDOR}, "DEB_VENDOR");
2185 vendor_patches_distro(Dpkg::Vendor::get_current_vendor(),
2186 __ "Dpkg::Vendor \`current vendor'");
2187 vendor_patches_distro(access_basedistro(),
2188 __ "(base) distro being accessed");
2189 vendor_patches_distro(access_nomdistro(),
2190 __ "(nominal) distro being accessed");
2193 sub generate_commits_from_dsc () {
2194 # See big comment in fetch_from_archive, below.
2195 # See also README.dsc-import.
2197 changedir $playground;
2199 my @dfi = dsc_files_info();
2200 foreach my $fi (@dfi) {
2201 my $f = $fi->{Filename};
2202 die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
2203 my $upper_f = (bpd_abs()."/$f");
2205 printdebug "considering reusing $f: ";
2207 if (link_ltarget "$upper_f,fetch", $f) {
2208 printdebug "linked (using ...,fetch).\n";
2209 } elsif ((printdebug "($!) "),
2211 fail f_ "accessing %s: %s", "$buildproductsdir/$f,fetch", $!;
2212 } elsif (link_ltarget $upper_f, $f) {
2213 printdebug "linked.\n";
2214 } elsif ((printdebug "($!) "),
2216 fail f_ "accessing %s: %s", "$buildproductsdir/$f", $!;
2218 printdebug "absent.\n";
2222 complete_file_from_dsc('.', $fi, \$refetched)
2225 printdebug "considering saving $f: ";
2227 if (rename_link_xf 1, $f, $upper_f) {
2228 printdebug "linked.\n";
2229 } elsif ((printdebug "($@) "),
2231 fail f_ "saving %s: %s", "$buildproductsdir/$f", $@;
2232 } elsif (!$refetched) {
2233 printdebug "no need.\n";
2234 } elsif (rename_link_xf 1, $f, "$upper_f,fetch") {
2235 printdebug "linked (using ...,fetch).\n";
2236 } elsif ((printdebug "($@) "),
2238 fail f_ "saving %s: %s", "$buildproductsdir/$f,fetch", $@;
2240 printdebug "cannot.\n";
2244 # We unpack and record the orig tarballs first, so that we only
2245 # need disk space for one private copy of the unpacked source.
2246 # But we can't make them into commits until we have the metadata
2247 # from the debian/changelog, so we record the tree objects now and
2248 # make them into commits later.
2250 my $upstreamv = upstreamversion $dsc->{version};
2251 my $orig_f_base = srcfn $upstreamv, '';
2253 foreach my $fi (@dfi) {
2254 # We actually import, and record as a commit, every tarball
2255 # (unless there is only one file, in which case there seems
2258 my $f = $fi->{Filename};
2259 printdebug "import considering $f ";
2260 (printdebug "only one dfi\n"), next if @dfi == 1;
2261 (printdebug "not tar\n"), next unless $f =~ m/\.tar(\.\w+)?$/;
2262 (printdebug "signature\n"), next if $f =~ m/$orig_f_sig_re$/o;
2266 $f =~ m/^\Q$orig_f_base\E\.([^._]+)?\.tar(?:\.\w+)?$/;
2268 printdebug "Y ", (join ' ', map { $_//"(none)" }
2269 $compr_ext, $orig_f_part
2272 my $input = new IO::File $f, '<' or die "$f $!";
2276 if (defined $compr_ext) {
2278 Dpkg::Compression::compression_guess_from_filename $f;
2279 fail "Dpkg::Compression cannot handle file $f in source package"
2280 if defined $compr_ext && !defined $cname;
2282 new Dpkg::Compression::Process compression => $cname;
2283 @compr_cmd = $compr_proc->get_uncompress_cmdline();
2284 my $compr_fh = new IO::Handle;
2285 my $compr_pid = open $compr_fh, "-|" // confess $!;
2287 open STDIN, "<&", $input or confess $!;
2289 die "dgit (child): exec $compr_cmd[0]: $!\n";
2294 rmtree "_unpack-tar";
2295 mkdir "_unpack-tar" or confess $!;
2296 my @tarcmd = qw(tar -x -f -
2297 --no-same-owner --no-same-permissions
2298 --no-acls --no-xattrs --no-selinux);
2299 my $tar_pid = fork // confess $!;
2301 chdir "_unpack-tar" or confess $!;
2302 open STDIN, "<&", $input or confess $!;
2304 die f_ "dgit (child): exec %s: %s", $tarcmd[0], $!;
2306 $!=0; (waitpid $tar_pid, 0) == $tar_pid or confess $!;
2307 !$? or failedcmd @tarcmd;
2310 (@compr_cmd ? ($?==SIGPIPE || failedcmd @compr_cmd)
2312 # finally, we have the results in "tarball", but maybe
2313 # with the wrong permissions
2315 runcmd qw(chmod -R +rwX _unpack-tar);
2316 changedir "_unpack-tar";
2317 remove_stray_gits($f);
2318 mktree_in_ud_here();
2320 my ($tree) = git_add_write_tree();
2321 my $tentries = cmdoutput @git, qw(ls-tree -z), $tree;
2322 if ($tentries =~ m/^\d+ tree (\w+)\t[^\000]+\000$/s) {
2324 printdebug "one subtree $1\n";
2326 printdebug "multiple subtrees\n";
2329 rmtree "_unpack-tar";
2331 my $ent = [ $f, $tree ];
2333 Orig => !!$orig_f_part,
2334 Sort => (!$orig_f_part ? 2 :
2335 $orig_f_part =~ m/-/g ? 1 :
2343 # put any without "_" first (spec is not clear whether files
2344 # are always in the usual order). Tarballs without "_" are
2345 # the main orig or the debian tarball.
2346 $a->{Sort} <=> $b->{Sort} or
2350 my $any_orig = grep { $_->{Orig} } @tartrees;
2352 my $dscfn = "$package.dsc";
2354 my $treeimporthow = 'package';
2356 open D, ">", $dscfn or die "$dscfn: $!";
2357 print D $dscdata or die "$dscfn: $!";
2358 close D or die "$dscfn: $!";
2359 my @cmd = qw(dpkg-source);
2360 push @cmd, '--no-check' if $dsc_checked;
2361 if (madformat $dsc->{format}) {
2362 push @cmd, '--skip-patches';
2363 $treeimporthow = 'unpatched';
2365 push @cmd, qw(-x --), $dscfn;
2368 my ($tree,$dir) = mktree_in_ud_from_only_subdir(__ "source package");
2369 if (madformat $dsc->{format}) {
2370 check_for_vendor_patches();
2374 if (madformat $dsc->{format}) {
2375 my @pcmd = qw(dpkg-source --before-build .);
2376 runcmd shell_cmd 'exec >/dev/null', @pcmd;
2378 $dappliedtree = git_add_write_tree();
2381 my @clogcmd = qw(dpkg-parsechangelog --format rfc822 --all);
2385 printdebug "import clog search...\n";
2386 parsechangelog_loop \@clogcmd, (__ "package changelog"), sub {
2387 my ($thisstanza, $desc) = @_;
2388 no warnings qw(exiting);
2390 $clogp //= $thisstanza;
2392 printdebug "import clog $thisstanza->{version} $desc...\n";
2394 last if !$any_orig; # we don't need $r1clogp
2396 # We look for the first (most recent) changelog entry whose
2397 # version number is lower than the upstream version of this
2398 # package. Then the last (least recent) previous changelog
2399 # entry is treated as the one which introduced this upstream
2400 # version and used for the synthetic commits for the upstream
2403 # One might think that a more sophisticated algorithm would be
2404 # necessary. But: we do not want to scan the whole changelog
2405 # file. Stopping when we see an earlier version, which
2406 # necessarily then is an earlier upstream version, is the only
2407 # realistic way to do that. Then, either the earliest
2408 # changelog entry we have seen so far is indeed the earliest
2409 # upload of this upstream version; or there are only changelog
2410 # entries relating to later upstream versions (which is not
2411 # possible unless the changelog and .dsc disagree about the
2412 # version). Then it remains to choose between the physically
2413 # last entry in the file, and the one with the lowest version
2414 # number. If these are not the same, we guess that the
2415 # versions were created in a non-monotonic order rather than
2416 # that the changelog entries have been misordered.
2418 printdebug "import clog $thisstanza->{version} vs $upstreamv...\n";
2420 last if version_compare($thisstanza->{version}, $upstreamv) < 0;
2421 $r1clogp = $thisstanza;
2423 printdebug "import clog $r1clogp->{version} becomes r1\n";
2426 $clogp or fail __ "package changelog has no entries!";
2428 my $authline = clogp_authline $clogp;
2429 my $changes = getfield $clogp, 'Changes';
2430 $changes =~ s/^\n//; # Changes: \n
2431 my $cversion = getfield $clogp, 'Version';
2434 $r1clogp //= $clogp; # maybe there's only one entry;
2435 my $r1authline = clogp_authline $r1clogp;
2436 # Strictly, r1authline might now be wrong if it's going to be
2437 # unused because !$any_orig. Whatever.
2439 printdebug "import tartrees authline $authline\n";
2440 printdebug "import tartrees r1authline $r1authline\n";
2442 foreach my $tt (@tartrees) {
2443 printdebug "import tartree $tt->{F} $tt->{Tree}\n";
2445 my $mbody = f_ "Import %s", $tt->{F};
2446 $tt->{Commit} = make_commit_text($tt->{Orig} ? <<END_O : <<END_T);
2449 committer $r1authline
2453 [dgit import orig $tt->{F}]
2461 [dgit import tarball $package $cversion $tt->{F}]
2466 printdebug "import main commit\n";
2468 open C, ">../commit.tmp" or confess $!;
2469 print C <<END or confess $!;
2472 print C <<END or confess $! foreach @tartrees;
2475 print C <<END or confess $!;
2481 [dgit import $treeimporthow $package $cversion]
2484 close C or confess $!;
2485 my $rawimport_hash = make_commit qw(../commit.tmp);
2487 if (madformat $dsc->{format}) {
2488 printdebug "import apply patches...\n";
2490 # regularise the state of the working tree so that
2491 # the checkout of $rawimport_hash works nicely.
2492 my $dappliedcommit = make_commit_text(<<END);
2499 runcmd @git, qw(checkout -q -b dapplied), $dappliedcommit;
2501 runcmd @git, qw(checkout -q -b unpa), $rawimport_hash;
2503 # We need the answers to be reproducible
2504 my @authline = clogp_authline($clogp);
2505 local $ENV{GIT_COMMITTER_NAME} = $authline[0];
2506 local $ENV{GIT_COMMITTER_EMAIL} = $authline[1];
2507 local $ENV{GIT_COMMITTER_DATE} = $authline[2];
2508 local $ENV{GIT_AUTHOR_NAME} = $authline[0];
2509 local $ENV{GIT_AUTHOR_EMAIL} = $authline[1];
2510 local $ENV{GIT_AUTHOR_DATE} = $authline[2];
2512 my $path = $ENV{PATH} or die;
2514 # we use ../../gbp-pq-output, which (given that we are in
2515 # $playground/PLAYTREE, and $playground is .git/dgit/unpack,
2518 foreach my $use_absurd (qw(0 1)) {
2519 runcmd @git, qw(checkout -q unpa);
2520 runcmd @git, qw(update-ref -d refs/heads/patch-queue/unpa);
2521 local $ENV{PATH} = $path;
2524 progress "warning: $@";
2525 $path = "$absurdity:$path";
2526 progress f_ "%s: trying slow absurd-git-apply...", $us;
2527 rename "../../gbp-pq-output","../../gbp-pq-output.0"
2532 die "forbid absurd git-apply\n" if $use_absurd
2533 && forceing [qw(import-gitapply-no-absurd)];
2534 die "only absurd git-apply!\n" if !$use_absurd
2535 && forceing [qw(import-gitapply-absurd)];
2537 local $ENV{DGIT_ABSURD_DEBUG} = $debuglevel if $use_absurd;
2538 local $ENV{PATH} = $path if $use_absurd;
2540 my @showcmd = (gbp_pq, qw(import));
2541 my @realcmd = shell_cmd
2542 'exec >/dev/null 2>>../../gbp-pq-output', @showcmd;
2543 debugcmd "+",@realcmd;
2544 if (system @realcmd) {
2545 die f_ "%s failed: %s\n",
2546 +(shellquote @showcmd),
2547 failedcmd_waitstatus();
2550 my $gapplied = git_rev_parse('HEAD');
2551 my $gappliedtree = cmdoutput @git, qw(rev-parse HEAD:);
2552 $gappliedtree eq $dappliedtree or
2553 fail f_ <<END, $gapplied, $gappliedtree, $dappliedtree;
2554 gbp-pq import and dpkg-source disagree!
2555 gbp-pq import gave commit %s
2556 gbp-pq import gave tree %s
2557 dpkg-source --before-build gave tree %s
2559 $rawimport_hash = $gapplied;
2564 { local $@; eval { runcmd qw(cat ../../gbp-pq-output); }; }
2569 progress f_ "synthesised git commit from .dsc %s", $cversion;
2571 my $rawimport_mergeinput = {
2572 Commit => $rawimport_hash,
2573 Info => __ "Import of source package",
2575 my @output = ($rawimport_mergeinput);
2577 if ($lastpush_mergeinput) {
2578 my $oldclogp = mergeinfo_getclogp($lastpush_mergeinput);
2579 my $oversion = getfield $oldclogp, 'Version';
2581 version_compare($oversion, $cversion);
2583 @output = ($rawimport_mergeinput, $lastpush_mergeinput,
2584 { ReverseParents => 1,
2585 Message => (f_ <<END, $package, $cversion, $csuite) });
2586 Record %s (%s) in archive suite %s
2588 } elsif ($vcmp > 0) {
2589 print STDERR f_ <<END, $cversion, $oversion,
2591 Version actually in archive: %s (older)
2592 Last version pushed with dgit: %s (newer or same)
2595 __ $later_warning_msg or confess $!;
2596 @output = $lastpush_mergeinput;
2598 # Same version. Use what's in the server git branch,
2599 # discarding our own import. (This could happen if the
2600 # server automatically imports all packages into git.)
2601 @output = $lastpush_mergeinput;
2609 sub complete_file_from_dsc ($$;$) {
2610 our ($dstdir, $fi, $refetched) = @_;
2611 # Ensures that we have, in $dstdir, the file $fi, with the correct
2612 # contents. (Downloading it from alongside $dscurl if necessary.)
2613 # If $refetched is defined, can overwrite "$dstdir/$fi->{Filename}"
2614 # and will set $$refetched=1 if it did so (or tried to).
2616 my $f = $fi->{Filename};
2617 my $tf = "$dstdir/$f";
2621 my $checkhash = sub {
2622 open F, "<", "$tf" or die "$tf: $!";
2623 $fi->{Digester}->reset();
2624 $fi->{Digester}->addfile(*F);
2625 F->error and confess $!;
2626 $got = $fi->{Digester}->hexdigest();
2627 return $got eq $fi->{Hash};
2630 if (stat_exists $tf) {
2631 if ($checkhash->()) {
2632 progress f_ "using existing %s", $f;
2636 fail f_ "file %s has hash %s but .dsc demands hash %s".
2637 " (perhaps you should delete this file?)",
2638 $f, $got, $fi->{Hash};
2640 progress f_ "need to fetch correct version of %s", $f;
2641 unlink $tf or die "$tf $!";
2644 printdebug "$tf does not exist, need to fetch\n";
2648 $furl =~ s{/[^/]+$}{};
2650 die "$f ?" unless $f =~ m/^\Q${package}\E_/;
2651 die "$f ?" if $f =~ m#/#;
2652 runcmd_ordryrun_local @curl,qw(-f -o),$tf,'--',"$furl";
2653 return 0 if !act_local();
2656 fail f_ "file %s has hash %s but .dsc demands hash %s".
2657 " (got wrong file from archive!)",
2658 $f, $got, $fi->{Hash};
2663 sub ensure_we_have_orig () {
2664 my @dfi = dsc_files_info();
2665 foreach my $fi (@dfi) {
2666 my $f = $fi->{Filename};
2667 next unless is_orig_file_in_dsc($f, \@dfi);
2668 complete_file_from_dsc($buildproductsdir, $fi)
2673 #---------- git fetch ----------
2675 sub lrfetchrefs () { return "refs/dgit-fetch/".access_basedistro(); }
2676 sub lrfetchref () { return lrfetchrefs.'/'.server_branch($csuite); }
2678 # We fetch some parts of lrfetchrefs/*. Ideally we delete these
2679 # locally fetched refs because they have unhelpful names and clutter
2680 # up gitk etc. So we track whether we have "used up" head ref (ie,
2681 # whether we have made another local ref which refers to this object).
2683 # (If we deleted them unconditionally, then we might end up
2684 # re-fetching the same git objects each time dgit fetch was run.)
2686 # So, each use of lrfetchrefs needs to be accompanied by arrangements
2687 # in git_fetch_us to fetch the refs in question, and possibly a call
2688 # to lrfetchref_used.
2690 our (%lrfetchrefs_f, %lrfetchrefs_d);
2691 # $lrfetchrefs_X{lrfetchrefs."/heads/whatever"} = $objid
2693 sub lrfetchref_used ($) {
2694 my ($fullrefname) = @_;
2695 my $objid = $lrfetchrefs_f{$fullrefname};
2696 $lrfetchrefs_d{$fullrefname} = $objid if defined $objid;
2699 sub git_lrfetch_sane {
2700 my ($url, $supplementary, @specs) = @_;
2701 # Make a 'refs/'.lrfetchrefs.'/*' be just like on server,
2702 # at least as regards @specs. Also leave the results in
2703 # %lrfetchrefs_f, and arrange for lrfetchref_used to be
2704 # able to clean these up.
2706 # With $supplementary==1, @specs must not contain wildcards
2707 # and we add to our previous fetches (non-atomically).
2709 # This is rather miserable:
2710 # When git fetch --prune is passed a fetchspec ending with a *,
2711 # it does a plausible thing. If there is no * then:
2712 # - it matches subpaths too, even if the supplied refspec
2713 # starts refs, and behaves completely madly if the source
2714 # has refs/refs/something. (See, for example, Debian #NNNN.)
2715 # - if there is no matching remote ref, it bombs out the whole
2717 # We want to fetch a fixed ref, and we don't know in advance
2718 # if it exists, so this is not suitable.
2720 # Our workaround is to use git ls-remote. git ls-remote has its
2721 # own qairks. Notably, it has the absurd multi-tail-matching
2722 # behaviour: git ls-remote R refs/foo can report refs/foo AND
2723 # refs/refs/foo etc.
2725 # Also, we want an idempotent snapshot, but we have to make two
2726 # calls to the remote: one to git ls-remote and to git fetch. The
2727 # solution is use git ls-remote to obtain a target state, and
2728 # git fetch to try to generate it. If we don't manage to generate
2729 # the target state, we try again.
2731 printdebug "git_lrfetch_sane suppl=$supplementary specs @specs\n";
2733 my $specre = join '|', map {
2736 my $wildcard = $x =~ s/\\\*$/.*/;
2737 die if $wildcard && $supplementary;
2740 printdebug "git_lrfetch_sane specre=$specre\n";
2741 my $wanted_rref = sub {
2743 return m/^(?:$specre)$/;
2746 my $fetch_iteration = 0;
2749 printdebug "git_lrfetch_sane iteration $fetch_iteration\n";
2750 if (++$fetch_iteration > 10) {
2751 fail __ "too many iterations trying to get sane fetch!";
2754 my @look = map { "refs/$_" } @specs;
2755 my @lcmd = (@git, qw(ls-remote -q --refs), $url, @look);
2759 open GITLS, "-|", @lcmd or confess $!;
2761 printdebug "=> ", $_;
2762 m/^(\w+)\s+(\S+)\n/ or die "ls-remote $_ ?";
2763 my ($objid,$rrefname) = ($1,$2);
2764 if (!$wanted_rref->($rrefname)) {
2765 print STDERR f_ <<END, "@look", $rrefname;
2766 warning: git ls-remote %s reported %s; this is silly, ignoring it.
2770 $wantr{$rrefname} = $objid;
2773 close GITLS or failedcmd @lcmd;
2775 # OK, now %want is exactly what we want for refs in @specs
2777 !m/\*$/ && !exists $wantr{"refs/$_"} ? () :
2778 "+refs/$_:".lrfetchrefs."/$_";
2781 printdebug "git_lrfetch_sane fspecs @fspecs\n";
2783 my @fcmd = (@git, qw(fetch -p -n -q), $url, @fspecs);
2784 runcmd_ordryrun_local @fcmd if @fspecs;
2786 if (!$supplementary) {
2787 %lrfetchrefs_f = ();
2791 git_for_each_ref(lrfetchrefs, sub {
2792 my ($objid,$objtype,$lrefname,$reftail) = @_;
2793 $lrfetchrefs_f{$lrefname} = $objid;
2794 $objgot{$objid} = 1;
2797 if ($supplementary) {
2801 foreach my $lrefname (sort keys %lrfetchrefs_f) {
2802 my $rrefname = 'refs'.substr($lrefname, length lrfetchrefs);
2803 if (!exists $wantr{$rrefname}) {
2804 if ($wanted_rref->($rrefname)) {
2806 git-fetch @fspecs created $lrefname which git ls-remote @look didn't list.
2809 print STDERR f_ <<END, "@fspecs", $lrefname
2810 warning: git fetch %s created %s; this is silly, deleting it.
2813 runcmd_ordryrun_local @git, qw(update-ref -d), $lrefname;
2814 delete $lrfetchrefs_f{$lrefname};
2818 foreach my $rrefname (sort keys %wantr) {
2819 my $lrefname = lrfetchrefs.substr($rrefname, 4);
2820 my $got = $lrfetchrefs_f{$lrefname} // '<none>';
2821 my $want = $wantr{$rrefname};
2822 next if $got eq $want;
2823 if (!defined $objgot{$want}) {
2824 fail __ <<END unless act_local();
2825 --dry-run specified but we actually wanted the results of git fetch,
2826 so this is not going to work. Try running dgit fetch first,
2827 or using --damp-run instead of --dry-run.
2829 print STDERR f_ <<END, $lrefname, $want;
2830 warning: git ls-remote suggests we want %s
2831 warning: and it should refer to %s
2832 warning: but git fetch didn't fetch that object to any relevant ref.
2833 warning: This may be due to a race with someone updating the server.
2834 warning: Will try again...
2836 next FETCH_ITERATION;
2839 git-fetch @fspecs made $lrefname=$got but want git ls-remote @look says $want
2841 runcmd_ordryrun_local @git, qw(update-ref -m),
2842 "dgit fetch git fetch fixup", $lrefname, $want;
2843 $lrfetchrefs_f{$lrefname} = $want;
2848 if (defined $csuite) {
2849 printdebug "git_lrfetch_sane: tidying any old suite lrfetchrefs\n";
2850 git_for_each_ref("refs/dgit-fetch/$csuite", sub {
2851 my ($objid,$objtype,$lrefname,$reftail) = @_;
2852 next if $lrfetchrefs_f{$lrefname}; # $csuite eq $distro ?
2853 runcmd_ordryrun_local @git, qw(update-ref -d), $lrefname;
2857 printdebug "git_lrfetch_sane: git fetch --no-insane emulation complete\n",
2858 Dumper(\%lrfetchrefs_f);
2861 sub git_fetch_us () {
2862 # Want to fetch only what we are going to use, unless
2863 # deliberately-not-ff, in which case we must fetch everything.
2865 my @specs = deliberately_not_fast_forward ? qw(tags/*) :
2867 (quiltmode_splitbrain
2868 ? (map { $_->('*',access_nomdistro) }
2869 \&debiantag_new, \&debiantag_maintview)
2870 : debiantags('*',access_nomdistro));
2871 push @specs, server_branch($csuite);
2872 push @specs, $rewritemap;
2873 push @specs, qw(heads/*) if deliberately_not_fast_forward;
2875 my $url = access_giturl();
2876 git_lrfetch_sane $url, 0, @specs;
2879 my @tagpats = debiantags('*',access_nomdistro);
2881 git_for_each_ref([map { "refs/tags/$_" } @tagpats], sub {
2882 my ($objid,$objtype,$fullrefname,$reftail) = @_;
2883 printdebug "currently $fullrefname=$objid\n";
2884 $here{$fullrefname} = $objid;
2886 git_for_each_ref([map { lrfetchrefs."/tags/".$_ } @tagpats], sub {
2887 my ($objid,$objtype,$fullrefname,$reftail) = @_;
2888 my $lref = "refs".substr($fullrefname, length(lrfetchrefs));
2889 printdebug "offered $lref=$objid\n";
2890 if (!defined $here{$lref}) {
2891 my @upd = (@git, qw(update-ref), $lref, $objid, '');
2892 runcmd_ordryrun_local @upd;
2893 lrfetchref_used $fullrefname;
2894 } elsif ($here{$lref} eq $objid) {
2895 lrfetchref_used $fullrefname;
2897 print STDERR f_ "Not updating %s from %s to %s.\n",
2898 $lref, $here{$lref}, $objid;
2903 #---------- dsc and archive handling ----------
2905 sub mergeinfo_getclogp ($) {
2906 # Ensures thit $mi->{Clogp} exists and returns it
2908 $mi->{Clogp} = commit_getclogp($mi->{Commit});
2911 sub mergeinfo_version ($) {
2912 return getfield( (mergeinfo_getclogp $_[0]), 'Version' );
2915 sub fetch_from_archive_record_1 ($) {
2917 runcmd git_update_ref_cmd "dgit fetch $csuite", 'DGIT_ARCHIVE', $hash;
2918 cmdoutput @git, qw(log -n2), $hash;
2919 # ... gives git a chance to complain if our commit is malformed
2922 sub fetch_from_archive_record_2 ($) {
2924 my @upd_cmd = (git_update_ref_cmd 'dgit fetch', lrref(), $hash);
2928 dryrun_report @upd_cmd;
2932 sub parse_dsc_field_def_dsc_distro () {
2933 $dsc_distro //= cfg qw(dgit.default.old-dsc-distro
2934 dgit.default.distro);
2937 sub parse_dsc_field ($$) {
2938 my ($dsc, $what) = @_;
2940 foreach my $field (@ourdscfield) {
2941 $f = $dsc->{$field};
2946 progress f_ "%s: NO git hash", $what;
2947 parse_dsc_field_def_dsc_distro();
2948 } elsif (($dsc_hash, $dsc_distro, $dsc_hint_tag, $dsc_hint_url)
2949 = $f =~ m/^(\w+)\s+($distro_re)\s+($versiontag_re)\s+(\S+)(?:\s|$)/) {
2950 progress f_ "%s: specified git info (%s)", $what, $dsc_distro;
2951 $dsc_hint_tag = [ $dsc_hint_tag ];
2952 } elsif ($f =~ m/^\w+\s*$/) {
2954 parse_dsc_field_def_dsc_distro();
2955 $dsc_hint_tag = [ debiantags +(getfield $dsc, 'Version'),
2957 progress f_ "%s: specified git hash", $what;
2959 fail f_ "%s: invalid Dgit info", $what;
2963 sub resolve_dsc_field_commit ($$) {
2964 my ($already_distro, $already_mapref) = @_;
2966 return unless defined $dsc_hash;
2969 defined $already_mapref &&
2970 ($already_distro eq $dsc_distro || !$chase_dsc_distro)
2971 ? $already_mapref : undef;
2975 my ($what, @fetch) = @_;
2977 local $idistro = $dsc_distro;
2978 my $lrf = lrfetchrefs;
2980 if (!$chase_dsc_distro) {
2981 progress f_ "not chasing .dsc distro %s: not fetching %s",
2986 progress f_ ".dsc names distro %s: fetching %s", $dsc_distro, $what;
2988 my $url = access_giturl();
2989 if (!defined $url) {
2990 defined $dsc_hint_url or fail f_ <<END, $dsc_distro;
2991 .dsc Dgit metadata is in context of distro %s
2992 for which we have no configured url and .dsc provides no hint
2995 $dsc_hint_url =~ m#^([-+0-9a-zA-Z]+):# ? $1 :
2996 $dsc_hint_url =~ m#^/# ? 'file' : 'bad-syntax';
2997 parse_cfg_bool "dsc-url-proto-ok", 'false',
2998 cfg("dgit.dsc-url-proto-ok.$proto",
2999 "dgit.default.dsc-url-proto-ok")
3000 or fail f_ <<END, $dsc_distro, $proto;
3001 .dsc Dgit metadata is in context of distro %s
3002 for which we have no configured url;
3003 .dsc provides hinted url with protocol %s which is unsafe.
3004 (can be overridden by config - consult documentation)
3006 $url = $dsc_hint_url;
3009 git_lrfetch_sane $url, 1, @fetch;
3014 my $rewrite_enable = do {
3015 local $idistro = $dsc_distro;
3016 access_cfg('rewrite-map-enable', 'RETURN-UNDEF');
3019 if (parse_cfg_bool 'rewrite-map-enable', 'true', $rewrite_enable) {
3020 if (!defined $mapref) {
3021 my $lrf = $do_fetch->((__ "rewrite map"), $rewritemap) or return;
3022 $mapref = $lrf.'/'.$rewritemap;
3024 my $rewritemapdata = git_cat_file $mapref.':map';
3025 if (defined $rewritemapdata
3026 && $rewritemapdata =~ m/^$dsc_hash(?:[ \t](\w+))/m) {
3028 "server's git history rewrite map contains a relevant entry!";
3031 if (defined $dsc_hash) {
3032 progress __ "using rewritten git hash in place of .dsc value";
3034 progress __ "server data says .dsc hash is to be disregarded";
3039 if (!defined git_cat_file $dsc_hash) {
3040 my @tags = map { "tags/".$_ } @$dsc_hint_tag;
3041 my $lrf = $do_fetch->((__ "additional commits"), @tags) &&
3042 defined git_cat_file $dsc_hash
3043 or fail f_ <<END, $dsc_hash;
3044 .dsc Dgit metadata requires commit %s
3045 but we could not obtain that object anywhere.
3047 foreach my $t (@tags) {
3048 my $fullrefname = $lrf.'/'.$t;
3049 # print STDERR "CHK $t $fullrefname ".Dumper(\%lrfetchrefs_f);
3050 next unless $lrfetchrefs_f{$fullrefname};
3051 next unless is_fast_fwd "$fullrefname~0", $dsc_hash;
3052 lrfetchref_used $fullrefname;
3057 sub fetch_from_archive () {
3058 ensure_setup_existing_tree();
3060 # Ensures that lrref() is what is actually in the archive, one way
3061 # or another, according to us - ie this client's
3062 # appropritaely-updated archive view. Also returns the commit id.
3063 # If there is nothing in the archive, leaves lrref alone and
3064 # returns undef. git_fetch_us must have already been called.
3068 parse_dsc_field($dsc, __ 'last upload to archive');
3069 resolve_dsc_field_commit access_basedistro,
3070 lrfetchrefs."/".$rewritemap
3072 progress __ "no version available from the archive";
3075 # If the archive's .dsc has a Dgit field, there are three
3076 # relevant git commitids we need to choose between and/or merge
3078 # 1. $dsc_hash: the Dgit field from the archive
3079 # 2. $lastpush_hash: the suite branch on the dgit git server
3080 # 3. $lastfetch_hash: our local tracking brach for the suite
3082 # These may all be distinct and need not be in any fast forward
3085 # If the dsc was pushed to this suite, then the server suite
3086 # branch will have been updated; but it might have been pushed to
3087 # a different suite and copied by the archive. Conversely a more
3088 # recent version may have been pushed with dgit but not appeared
3089 # in the archive (yet).
3091 # $lastfetch_hash may be awkward because archive imports
3092 # (particularly, imports of Dgit-less .dscs) are performed only as
3093 # needed on individual clients, so different clients may perform a
3094 # different subset of them - and these imports are only made
3095 # public during push. So $lastfetch_hash may represent a set of
3096 # imports different to a subsequent upload by a different dgit
3099 # Our approach is as follows:
3101 # As between $dsc_hash and $lastpush_hash: if $lastpush_hash is a
3102 # descendant of $dsc_hash, then it was pushed by a dgit user who
3103 # had based their work on $dsc_hash, so we should prefer it.
3104 # Otherwise, $dsc_hash was installed into this suite in the
3105 # archive other than by a dgit push, and (necessarily) after the
3106 # last dgit push into that suite (since a dgit push would have
3107 # been descended from the dgit server git branch); thus, in that
3108 # case, we prefer the archive's version (and produce a
3109 # pseudo-merge to overwrite the dgit server git branch).
3111 # (If there is no Dgit field in the archive's .dsc then
3112 # generate_commit_from_dsc uses the version numbers to decide
3113 # whether the suite branch or the archive is newer. If the suite
3114 # branch is newer it ignores the archive's .dsc; otherwise it
3115 # generates an import of the .dsc, and produces a pseudo-merge to
3116 # overwrite the suite branch with the archive contents.)
3118 # The outcome of that part of the algorithm is the `public view',
3119 # and is same for all dgit clients: it does not depend on any
3120 # unpublished history in the local tracking branch.
3122 # As between the public view and the local tracking branch: The
3123 # local tracking branch is only updated by dgit fetch, and
3124 # whenever dgit fetch runs it includes the public view in the
3125 # local tracking branch. Therefore if the public view is not
3126 # descended from the local tracking branch, the local tracking
3127 # branch must contain history which was imported from the archive
3128 # but never pushed; and, its tip is now out of date. So, we make
3129 # a pseudo-merge to overwrite the old imports and stitch the old
3132 # Finally: we do not necessarily reify the public view (as
3133 # described above). This is so that we do not end up stacking two
3134 # pseudo-merges. So what we actually do is figure out the inputs
3135 # to any public view pseudo-merge and put them in @mergeinputs.
3138 # $mergeinputs[]{Commit}
3139 # $mergeinputs[]{Info}
3140 # $mergeinputs[0] is the one whose tree we use
3141 # @mergeinputs is in the order we use in the actual commit)
3144 # $mergeinputs[]{Message} is a commit message to use
3145 # $mergeinputs[]{ReverseParents} if def specifies that parent
3146 # list should be in opposite order
3147 # Such an entry has no Commit or Info. It applies only when found
3148 # in the last entry. (This ugliness is to support making
3149 # identical imports to previous dgit versions.)
3151 my $lastpush_hash = git_get_ref(lrfetchref());
3152 printdebug "previous reference hash=$lastpush_hash\n";
3153 $lastpush_mergeinput = $lastpush_hash && {
3154 Commit => $lastpush_hash,
3155 Info => (__ "dgit suite branch on dgit git server"),
3158 my $lastfetch_hash = git_get_ref(lrref());
3159 printdebug "fetch_from_archive: lastfetch=$lastfetch_hash\n";
3160 my $lastfetch_mergeinput = $lastfetch_hash && {
3161 Commit => $lastfetch_hash,
3162 Info => (__ "dgit client's archive history view"),
3165 my $dsc_mergeinput = $dsc_hash && {
3166 Commit => $dsc_hash,
3167 Info => (__ "Dgit field in .dsc from archive"),
3171 my $del_lrfetchrefs = sub {
3174 printdebug "del_lrfetchrefs...\n";
3175 foreach my $fullrefname (sort keys %lrfetchrefs_d) {
3176 my $objid = $lrfetchrefs_d{$fullrefname};
3177 printdebug "del_lrfetchrefs: $objid $fullrefname\n";
3179 $gur ||= new IO::Handle;
3180 open $gur, "|-", qw(git update-ref --stdin) or confess $!;
3182 printf $gur "delete %s %s\n", $fullrefname, $objid;
3185 close $gur or failedcmd "git update-ref delete lrfetchrefs";
3189 if (defined $dsc_hash) {
3190 ensure_we_have_orig();
3191 if (!$lastpush_hash || $dsc_hash eq $lastpush_hash) {
3192 @mergeinputs = $dsc_mergeinput
3193 } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
3194 print STDERR f_ <<END, $dsc_hash, $lastpush_hash,
3196 Git commit in archive is behind the last version allegedly pushed/uploaded.
3197 Commit referred to by archive: %s
3198 Last version pushed with dgit: %s
3201 __ $later_warning_msg or confess $!;
3202 @mergeinputs = ($lastpush_mergeinput);
3204 # Archive has .dsc which is not a descendant of the last dgit
3205 # push. This can happen if the archive moves .dscs about.
3206 # Just follow its lead.
3207 if (is_fast_fwd($lastpush_hash,$dsc_hash)) {
3208 progress __ "archive .dsc names newer git commit";
3209 @mergeinputs = ($dsc_mergeinput);
3211 progress __ "archive .dsc names other git commit, fixing up";
3212 @mergeinputs = ($dsc_mergeinput, $lastpush_mergeinput);
3216 @mergeinputs = generate_commits_from_dsc();
3217 # We have just done an import. Now, our import algorithm might
3218 # have been improved. But even so we do not want to generate
3219 # a new different import of the same package. So if the
3220 # version numbers are the same, just use our existing version.
3221 # If the version numbers are different, the archive has changed
3222 # (perhaps, rewound).
3223 if ($lastfetch_mergeinput &&
3224 !version_compare( (mergeinfo_version $lastfetch_mergeinput),
3225 (mergeinfo_version $mergeinputs[0]) )) {
3226 @mergeinputs = ($lastfetch_mergeinput);
3228 } elsif ($lastpush_hash) {
3229 # only in git, not in the archive yet
3230 @mergeinputs = ($lastpush_mergeinput);
3231 print STDERR f_ <<END,
3233 Package not found in the archive, but has allegedly been pushed using dgit.
3236 __ $later_warning_msg or confess $!;
3238 printdebug "nothing found!\n";
3239 if (defined $skew_warning_vsn) {
3240 print STDERR f_ <<END, $skew_warning_vsn or confess $!;
3242 Warning: relevant archive skew detected.
3243 Archive allegedly contains %s
3244 But we were not able to obtain any version from the archive or git.
3248 unshift @end, $del_lrfetchrefs;
3252 if ($lastfetch_hash &&
3254 my $h = $_->{Commit};
3255 $h and is_fast_fwd($lastfetch_hash, $h);
3256 # If true, one of the existing parents of this commit
3257 # is a descendant of the $lastfetch_hash, so we'll
3258 # be ff from that automatically.
3262 push @mergeinputs, $lastfetch_mergeinput;
3265 printdebug "fetch mergeinfos:\n";
3266 foreach my $mi (@mergeinputs) {
3268 printdebug " commit $mi->{Commit} $mi->{Info}\n";
3270 printdebug sprintf " ReverseParents=%d Message=%s",
3271 $mi->{ReverseParents}, $mi->{Message};
3275 my $compat_info= pop @mergeinputs
3276 if $mergeinputs[$#mergeinputs]{Message};
3278 @mergeinputs = grep { defined $_->{Commit} } @mergeinputs;
3281 if (@mergeinputs > 1) {
3283 my $tree_commit = $mergeinputs[0]{Commit};
3285 my $tree = get_tree_of_commit $tree_commit;;
3287 # We use the changelog author of the package in question the
3288 # author of this pseudo-merge. This is (roughly) correct if
3289 # this commit is simply representing aa non-dgit upload.
3290 # (Roughly because it does not record sponsorship - but we
3291 # don't have sponsorship info because that's in the .changes,
3292 # which isn't in the archivw.)
3294 # But, it might be that we are representing archive history
3295 # updates (including in-archive copies). These are not really
3296 # the responsibility of the person who created the .dsc, but
3297 # there is no-one whose name we should better use. (The
3298 # author of the .dsc-named commit is clearly worse.)
3300 my $useclogp = mergeinfo_getclogp $mergeinputs[0];
3301 my $author = clogp_authline $useclogp;
3302 my $cversion = getfield $useclogp, 'Version';
3304 my $mcf = dgit_privdir()."/mergecommit";
3305 open MC, ">", $mcf or die "$mcf $!";
3306 print MC <<END or confess $!;
3310 my @parents = grep { $_->{Commit} } @mergeinputs;
3311 @parents = reverse @parents if $compat_info->{ReverseParents};
3312 print MC <<END or confess $! foreach @parents;
3316 print MC <<END or confess $!;
3322 if (defined $compat_info->{Message}) {
3323 print MC $compat_info->{Message} or confess $!;
3325 print MC f_ <<END, $package, $cversion, $csuite or confess $!;
3326 Record %s (%s) in archive suite %s
3330 my $message_add_info = sub {
3332 my $mversion = mergeinfo_version $mi;
3333 printf MC " %-20s %s\n", $mversion, $mi->{Info}
3337 $message_add_info->($mergeinputs[0]);
3338 print MC __ <<END or confess $!;
3339 should be treated as descended from
3341 $message_add_info->($_) foreach @mergeinputs[1..$#mergeinputs];
3344 close MC or confess $!;
3345 $hash = make_commit $mcf;
3347 $hash = $mergeinputs[0]{Commit};
3349 printdebug "fetch hash=$hash\n";
3352 my ($lasth, $what) = @_;
3353 return unless $lasth;
3354 confess "$lasth $hash $what ?" unless is_fast_fwd($lasth, $hash);
3357 $chkff->($lastpush_hash, __ 'dgit repo server tip (last push)')
3359 $chkff->($lastfetch_hash, __ 'local tracking tip (last fetch)');
3361 fetch_from_archive_record_1($hash);
3363 if (defined $skew_warning_vsn) {
3364 printdebug "SKEW CHECK WANT $skew_warning_vsn\n";
3365 my $gotclogp = commit_getclogp($hash);
3366 my $got_vsn = getfield $gotclogp, 'Version';
3367 printdebug "SKEW CHECK GOT $got_vsn\n";
3368 if (version_compare($got_vsn, $skew_warning_vsn) < 0) {
3369 print STDERR f_ <<END, $skew_warning_vsn, $got_vsn or confess $!;
3371 Warning: archive skew detected. Using the available version:
3372 Archive allegedly contains %s
3373 We were able to obtain only %s
3379 if ($lastfetch_hash ne $hash) {
3380 fetch_from_archive_record_2($hash);
3383 lrfetchref_used lrfetchref();
3385 check_gitattrs($hash, __ "fetched source tree");
3387 unshift @end, $del_lrfetchrefs;
3391 sub set_local_git_config ($$) {
3393 runcmd @git, qw(config), $k, $v;
3396 sub setup_mergechangelogs (;$) {
3398 return unless $always || access_cfg_bool(1, 'setup-mergechangelogs');
3400 my $driver = 'dpkg-mergechangelogs';
3401 my $cb = "merge.$driver";
3402 confess unless defined $maindir;
3403 my $attrs = "$maindir_gitcommon/info/attributes";
3404 ensuredir "$maindir_gitcommon/info";
3406 open NATTRS, ">", "$attrs.new" or die "$attrs.new $!";
3407 if (!open ATTRS, "<", $attrs) {
3408 $!==ENOENT or die "$attrs: $!";
3412 next if m{^debian/changelog\s};
3413 print NATTRS $_, "\n" or confess $!;
3415 ATTRS->error and confess $!;
3418 print NATTRS "debian/changelog merge=$driver\n" or confess $!;
3421 set_local_git_config "$cb.name", __ 'debian/changelog merge driver';
3422 set_local_git_config "$cb.driver", 'dpkg-mergechangelogs -m %O %A %B %A';
3424 rename "$attrs.new", "$attrs" or die "$attrs: $!";
3427 sub setup_useremail (;$) {
3429 return unless $always || access_cfg_bool(1, 'setup-useremail');
3432 my ($k, $envvar) = @_;
3433 my $v = access_cfg("user-$k", 'RETURN-UNDEF') // $ENV{$envvar};
3434 return unless defined $v;
3435 set_local_git_config "user.$k", $v;
3438 $setup->('email', 'DEBEMAIL');
3439 $setup->('name', 'DEBFULLNAME');
3442 sub ensure_setup_existing_tree () {
3443 my $k = "remote.$remotename.skipdefaultupdate";
3444 my $c = git_get_config $k;
3445 return if defined $c;
3446 set_local_git_config $k, 'true';
3449 sub open_main_gitattrs () {
3450 confess 'internal error no maindir' unless defined $maindir;
3451 my $gai = new IO::File "$maindir_gitcommon/info/attributes"
3453 or die "open $maindir_gitcommon/info/attributes: $!";
3457 our $gitattrs_ourmacro_re = qr{^\[attr\]dgit-defuse-attrs\s};
3459 sub is_gitattrs_setup () {
3462 # 1: gitattributes set up and should be left alone
3464 # 0: there is a dgit-defuse-attrs but it needs fixing
3465 # undef: there is none
3466 my $gai = open_main_gitattrs();
3467 return 0 unless $gai;
3469 next unless m{$gitattrs_ourmacro_re};
3470 return 1 if m{\s-working-tree-encoding\s};
3471 printdebug "is_gitattrs_setup: found old macro\n";
3474 $gai->error and confess $!;
3475 printdebug "is_gitattrs_setup: found nothing\n";
3479 sub setup_gitattrs (;$) {
3481 return unless $always || access_cfg_bool(1, 'setup-gitattributes');
3483 my $already = is_gitattrs_setup();
3486 [attr]dgit-defuse-attrs already found, and proper, in .git/info/attributes
3487 not doing further gitattributes setup
3491 my $new = "[attr]dgit-defuse-attrs $negate_harmful_gitattrs";
3492 my $af = "$maindir_gitcommon/info/attributes";
3493 ensuredir "$maindir_gitcommon/info";
3495 open GAO, "> $af.new" or confess $!;
3496 print GAO <<END, __ <<ENDT or confess $! unless defined $already;
3500 # ^ see GITATTRIBUTES in dgit(7) and dgit setup-new-tree in dgit(1)
3502 my $gai = open_main_gitattrs();
3505 if (m{$gitattrs_ourmacro_re}) {
3506 die unless defined $already;
3510 print GAO $_, "\n" or confess $!;
3512 $gai->error and confess $!;
3514 close GAO or confess $!;
3515 rename "$af.new", "$af" or fail f_ "install %s: %s", $af, $!;
3518 sub setup_new_tree () {
3519 setup_mergechangelogs();
3524 sub check_gitattrs ($$) {
3525 my ($treeish, $what) = @_;
3527 return if is_gitattrs_setup;
3530 my @cmd = (@git, qw(ls-tree -lrz --), "${treeish}:");
3532 my $gafl = new IO::File;
3533 open $gafl, "-|", @cmd or confess $!;
3536 s/^\d+\s+\w+\s+\w+\s+(\d+)\t// or die;
3538 next unless m{(?:^|/)\.gitattributes$};
3540 # oh dear, found one
3541 print STDERR f_ <<END, $what;
3542 dgit: warning: %s contains .gitattributes
3543 dgit: .gitattributes not (fully) defused. Recommended: dgit setup-new-tree.
3548 # tree contains no .gitattributes files
3549 $?=0; $!=0; close $gafl or failedcmd @cmd;
3553 sub multisuite_suite_child ($$$) {
3554 my ($tsuite, $mergeinputs, $fn) = @_;
3555 # in child, sets things up, calls $fn->(), and returns undef
3556 # in parent, returns canonical suite name for $tsuite
3557 my $canonsuitefh = IO::File::new_tmpfile;
3558 my $pid = fork // confess $!;
3562 $us .= " [$isuite]";
3563 $debugprefix .= " ";
3564 progress f_ "fetching %s...", $tsuite;
3565 canonicalise_suite();
3566 print $canonsuitefh $csuite, "\n" or confess $!;
3567 close $canonsuitefh or confess $!;
3571 waitpid $pid,0 == $pid or confess $!;
3572 fail f_ "failed to obtain %s: %s", $tsuite, waitstatusmsg()
3574 seek $canonsuitefh,0,0 or confess $!;
3575 local $csuite = <$canonsuitefh>;
3576 confess $! unless defined $csuite && chomp $csuite;
3578 printdebug "multisuite $tsuite missing\n";
3581 printdebug "multisuite $tsuite ok (canon=$csuite)\n";
3582 push @$mergeinputs, {
3589 sub fork_for_multisuite ($) {
3590 my ($before_fetch_merge) = @_;
3591 # if nothing unusual, just returns ''
3594 # returns 0 to caller in child, to do first of the specified suites
3595 # in child, $csuite is not yet set
3597 # returns 1 to caller in parent, to finish up anything needed after
3598 # in parent, $csuite is set to canonicalised portmanteau
3600 my $org_isuite = $isuite;
3601 my @suites = split /\,/, $isuite;
3602 return '' unless @suites > 1;
3603 printdebug "fork_for_multisuite: @suites\n";
3607 my $cbasesuite = multisuite_suite_child($suites[0], \@mergeinputs,
3609 return 0 unless defined $cbasesuite;
3611 fail f_ "package %s missing in (base suite) %s", $package, $cbasesuite
3612 unless @mergeinputs;
3614 my @csuites = ($cbasesuite);
3616 $before_fetch_merge->();
3618 foreach my $tsuite (@suites[1..$#suites]) {
3619 $tsuite =~ s/^-/$cbasesuite-/;
3620 my $csubsuite = multisuite_suite_child($tsuite, \@mergeinputs,
3627 $csubsuite =~ s/^\Q$cbasesuite\E-/-/;
3628 push @csuites, $csubsuite;
3631 foreach my $mi (@mergeinputs) {
3632 my $ref = git_get_ref $mi->{Ref};
3633 die "$mi->{Ref} ?" unless length $ref;
3634 $mi->{Commit} = $ref;
3637 $csuite = join ",", @csuites;
3639 my $previous = git_get_ref lrref;
3641 unshift @mergeinputs, {
3642 Commit => $previous,
3643 Info => (__ "local combined tracking branch"),
3645 "archive seems to have rewound: local tracking branch is ahead!"),
3649 foreach my $ix (0..$#mergeinputs) {
3650 $mergeinputs[$ix]{Index} = $ix;
3653 @mergeinputs = sort {
3654 -version_compare(mergeinfo_version $a,
3655 mergeinfo_version $b) # highest version first
3657 $a->{Index} <=> $b->{Index}; # earliest in spec first
3663 foreach my $mi (@mergeinputs) {
3664 printdebug "multisuite merge check $mi->{Info}\n";
3665 foreach my $previous (@needed) {
3666 next unless is_fast_fwd $mi->{Commit}, $previous->{Commit};
3667 printdebug "multisuite merge un-needed $previous->{Info}\n";
3671 printdebug "multisuite merge this-needed\n";
3672 $mi->{Character} = '+';
3675 $needed[0]{Character} = '*';
3677 my $output = $needed[0]{Commit};
3680 printdebug "multisuite merge nontrivial\n";
3681 my $tree = cmdoutput qw(git rev-parse), $needed[0]{Commit}.':';
3683 my $commit = "tree $tree\n";
3684 my $msg = f_ "Combine archive branches %s [dgit]\n\n".
3685 "Input branches:\n",
3688 foreach my $mi (sort { $a->{Index} <=> $b->{Index} } @mergeinputs) {
3689 printdebug "multisuite merge include $mi->{Info}\n";
3690 $mi->{Character} //= ' ';
3691 $commit .= "parent $mi->{Commit}\n";
3692 $msg .= sprintf " %s %-25s %s\n",
3694 (mergeinfo_version $mi),
3697 my $authline = clogp_authline mergeinfo_getclogp $needed[0];
3698 $msg .= __ "\nKey\n".
3699 " * marks the highest version branch, which choose to use\n".
3700 " + marks each branch which was not already an ancestor\n\n";
3702 "[dgit multi-suite $csuite]\n";
3704 "author $authline\n".
3705 "committer $authline\n\n";
3706 $output = make_commit_text $commit.$msg;
3707 printdebug "multisuite merge generated $output\n";
3710 fetch_from_archive_record_1($output);
3711 fetch_from_archive_record_2($output);
3713 progress f_ "calculated combined tracking suite %s", $csuite;
3718 sub clone_set_head () {
3719 open H, "> .git/HEAD" or confess $!;
3720 print H "ref: ".lref()."\n" or confess $!;
3721 close H or confess $!;
3723 sub clone_finish ($) {
3725 runcmd @git, qw(reset --hard), lrref();
3726 runcmd qw(bash -ec), <<'END';
3728 git ls-tree -r --name-only -z HEAD | \
3729 xargs -0r touch -h -r . --
3731 printdone f_ "ready for work in %s", $dstdir;
3735 # in multisuite, returns twice!
3736 # once in parent after first suite fetched,
3737 # and then again in child after everything is finished
3739 badusage __ "dry run makes no sense with clone" unless act_local();
3741 my $multi_fetched = fork_for_multisuite(sub {
3742 printdebug "multi clone before fetch merge\n";
3746 if ($multi_fetched) {
3747 printdebug "multi clone after fetch merge\n";
3749 clone_finish($dstdir);
3752 printdebug "clone main body\n";
3754 canonicalise_suite();
3755 my $hasgit = check_for_git();
3756 mkdir $dstdir or fail f_ "create \`%s': %s", $dstdir, $!;
3758 runcmd @git, qw(init -q);
3762 my $giturl = access_giturl(1);
3763 if (defined $giturl) {
3764 runcmd @git, qw(remote add), 'origin', $giturl;
3767 progress __ "fetching existing git history";
3769 runcmd_ordryrun_local @git, qw(fetch origin);
3771 progress __ "starting new git history";
3773 fetch_from_archive() or no_such_package;
3774 my $vcsgiturl = $dsc->{'Vcs-Git'};
3775 if (length $vcsgiturl) {
3776 $vcsgiturl =~ s/\s+-b\s+\S+//g;
3777 runcmd @git, qw(remote add vcs-git), $vcsgiturl;
3779 clone_finish($dstdir);
3783 canonicalise_suite();
3784 if (check_for_git()) {
3787 fetch_from_archive() or no_such_package();
3789 my $vcsgiturl = $dsc && $dsc->{'Vcs-Git'};
3790 if (length $vcsgiturl and
3791 (grep { $csuite eq $_ }
3793 cfg 'dgit.vcs-git.suites')) {
3794 my $current = cfg 'remote.vcs-git.url', 'RETURN-UNDEF';
3795 if (defined $current && $current ne $vcsgiturl) {
3796 print STDERR f_ <<END, $csuite;
3797 FYI: Vcs-Git in %s has different url to your vcs-git remote.
3798 Your vcs-git remote url may be out of date. Use dgit update-vcs-git ?
3802 printdone f_ "fetched into %s", lrref();
3806 my $multi_fetched = fork_for_multisuite(sub { });
3807 fetch_one() unless $multi_fetched; # parent
3808 finish 0 if $multi_fetched eq '0'; # child
3813 runcmd_ordryrun_local @git, qw(merge -m),
3814 (f_ "Merge from %s [dgit]", $csuite),
3816 printdone f_ "fetched to %s and merged into HEAD", lrref();
3819 sub check_not_dirty () {
3820 my @forbid = qw(local-options local-patch-header);
3821 foreach my $f (@forbid) {
3822 if (stat_exists "debian/source/$f") {
3823 fail f_ "git tree contains debian/source/%s", $f;
3827 return if $includedirty;
3829 git_check_unmodified();
3832 sub commit_admin ($) {
3835 runcmd_ordryrun_local @git, qw(commit -m), $m;
3838 sub quiltify_nofix_bail ($$) {
3839 my ($headinfo, $xinfo) = @_;
3840 if ($quilt_mode eq 'nofix') {
3842 "quilt fixup required but quilt mode is \`nofix'\n".
3843 "HEAD commit%s differs from tree implied by debian/patches%s",
3848 sub commit_quilty_patch () {
3849 my $output = cmdoutput @git, qw(status --ignored --porcelain);
3851 foreach my $l (split /\n/, $output) {
3852 next unless $l =~ m/\S/;
3853 if ($l =~ m{^(?:[?!][?!]| [MADRC]) (.pc|debian/patches)}) {
3857 delete $adds{'.pc'}; # if there wasn't one before, don't add it
3859 progress __ "nothing quilty to commit, ok.";
3862 quiltify_nofix_bail "", __ " (wanted to commit patch update)";
3863 my @adds = map { s/[][*?\\]/\\$&/g; $_; } sort keys %adds;
3864 runcmd_ordryrun_local @git, qw(add -f), @adds;
3865 commit_admin +(__ <<ENDT).<<END
3866 Commit Debian 3.0 (quilt) metadata
3869 [dgit ($our_version) quilt-fixup]
3873 sub get_source_format () {
3875 if (open F, "debian/source/options") {
3879 s/\s+$//; # ignore missing final newline
3881 my ($k, $v) = ($`, $'); #');
3882 $v =~ s/^"(.*)"$/$1/;
3888 F->error and confess $!;
3891 confess $! unless $!==&ENOENT;
3894 if (!open F, "debian/source/format") {
3895 confess $! unless $!==&ENOENT;
3899 F->error and confess $!;
3901 return ($_, \%options);
3904 sub madformat_wantfixup ($) {
3906 return 0 unless $format eq '3.0 (quilt)';
3907 our $quilt_mode_warned;
3908 if ($quilt_mode eq 'nocheck') {
3909 progress f_ "Not doing any fixup of \`%s'".
3910 " due to ----no-quilt-fixup or --quilt=nocheck", $format
3911 unless $quilt_mode_warned++;
3914 progress f_ "Format \`%s', need to check/update patch stack", $format
3915 unless $quilt_mode_warned++;
3919 sub maybe_split_brain_save ($$$) {
3920 my ($headref, $dgitview, $msg) = @_;
3921 # => message fragment "$saved" describing disposition of $dgitview
3922 # (used inside parens, in the English texts)
3923 my $save = $internal_object_save{'dgit-view'};
3924 return f_ "commit id %s", $dgitview unless defined $save;
3925 my @cmd = (shell_cmd 'cd "$1"; shift', $maindir,
3927 "dgit --dgit-view-save $msg HEAD=$headref",
3930 return f_ "and left in %s", $save;
3933 # An "infopair" is a tuple [ $thing, $what ]
3934 # (often $thing is a commit hash; $what is a description)
3936 sub infopair_cond_equal ($$) {
3938 $x->[0] eq $y->[0] or fail <<END;
3939 $x->[1] ($x->[0]) not equal to $y->[1] ($y->[0])
3943 sub infopair_lrf_tag_lookup ($$) {
3944 my ($tagnames, $what) = @_;
3945 # $tagname may be an array ref
3946 my @tagnames = ref $tagnames ? @$tagnames : ($tagnames);
3947 printdebug "infopair_lrfetchref_tag_lookup $what @tagnames\n";
3948 foreach my $tagname (@tagnames) {
3949 my $lrefname = lrfetchrefs."/tags/$tagname";
3950 my $tagobj = $lrfetchrefs_f{$lrefname};
3951 next unless defined $tagobj;
3952 printdebug "infopair_lrfetchref_tag_lookup $tagobj $tagname $what\n";
3953 return [ git_rev_parse($tagobj), $what ];
3955 fail @tagnames==1 ? (f_ <<END, $what, "@tagnames")
3956 Wanted tag %s (%s) on dgit server, but not found
3958 : (f_ <<END, $what, "@tagnames");
3959 Wanted tag %s (one of: %s) on dgit server, but not found
3963 sub infopair_cond_ff ($$) {
3964 my ($anc,$desc) = @_;
3965 is_fast_fwd($anc->[0], $desc->[0]) or
3966 fail f_ <<END, $anc->[1], $anc->[0], $desc->[1], $desc->[0];
3967 %s (%s) .. %s (%s) is not fast forward
3971 sub pseudomerge_version_check ($$) {
3972 my ($clogp, $archive_hash) = @_;
3974 my $arch_clogp = commit_getclogp $archive_hash;
3975 my $i_arch_v = [ (getfield $arch_clogp, 'Version'),
3976 __ 'version currently in archive' ];
3977 if (defined $overwrite_version) {
3978 if (length $overwrite_version) {
3979 infopair_cond_equal([ $overwrite_version,
3980 '--overwrite= version' ],
3983 my $v = $i_arch_v->[0];
3985 "Checking package changelog for archive version %s ...", $v;
3988 my @xa = ("-f$v", "-t$v");
3989 my $vclogp = parsechangelog @xa;
3992 [ (getfield $vclogp, $fn),
3993 (f_ "%s field from dpkg-parsechangelog %s",
3996 my $cv = $gf->('Version');
3997 infopair_cond_equal($i_arch_v, $cv);
3998 $cd = $gf->('Distribution');
4001 $@ =~ s/^dgit: //gm;
4003 f_ "Perhaps debian/changelog does not mention %s ?", $v;
4005 fail f_ <<END, $cd->[1], $cd->[0], $v
4007 Your tree seems to based on earlier (not uploaded) %s.
4009 if $cd->[0] =~ m/UNRELEASED/;
4013 printdebug "pseudomerge_version_check i_arch_v @$i_arch_v\n";
4017 sub pseudomerge_make_commit ($$$$ $$) {
4018 my ($clogp, $dgitview, $archive_hash, $i_arch_v,
4019 $msg_cmd, $msg_msg) = @_;
4020 progress f_ "Declaring that HEAD includes all changes in %s...",
4023 my $tree = cmdoutput qw(git rev-parse), "${dgitview}:";
4024 my $authline = clogp_authline $clogp;
4028 !defined $overwrite_version ? ""
4029 : !length $overwrite_version ? " --overwrite"
4030 : " --overwrite=".$overwrite_version;
4032 # Contributing parent is the first parent - that makes
4033 # git rev-list --first-parent DTRT.
4034 my $pmf = dgit_privdir()."/pseudomerge";
4035 open MC, ">", $pmf or die "$pmf $!";
4036 print MC <<END or confess $!;
4039 parent $archive_hash
4047 close MC or confess $!;
4049 return make_commit($pmf);
4052 sub splitbrain_pseudomerge ($$$$) {
4053 my ($clogp, $maintview, $dgitview, $archive_hash) = @_;
4054 # => $merged_dgitview
4055 printdebug "splitbrain_pseudomerge...\n";
4057 # We: debian/PREVIOUS HEAD($maintview)
4058 # expect: o ----------------- o
4061 # a/d/PREVIOUS $dgitview
4064 # we do: `------------------ o
4068 return $dgitview unless defined $archive_hash;
4069 return $dgitview if deliberately_not_fast_forward();
4071 printdebug "splitbrain_pseudomerge...\n";
4073 my $i_arch_v = pseudomerge_version_check($clogp, $archive_hash);
4075 if (!defined $overwrite_version) {
4076 progress __ "Checking that HEAD includes all changes in archive...";
4079 return $dgitview if is_fast_fwd $archive_hash, $dgitview;
4081 if (defined $overwrite_version) {
4083 my $t_dep14 = debiantag_maintview $i_arch_v->[0], access_nomdistro;
4084 my $i_dep14 = infopair_lrf_tag_lookup($t_dep14,
4085 __ "maintainer view tag");
4086 my $t_dgit = debiantag_new $i_arch_v->[0], access_nomdistro;
4087 my $i_dgit = infopair_lrf_tag_lookup($t_dgit, __ "dgit view tag");
4088 my $i_archive = [ $archive_hash, __ "current archive contents" ];
4090 printdebug "splitbrain_pseudomerge i_archive @$i_archive\n";
4092 infopair_cond_equal($i_dgit, $i_archive);
4093 infopair_cond_ff($i_dep14, $i_dgit);
4094 infopair_cond_ff($i_dep14, [ $maintview, 'HEAD' ]);
4097 $@ =~ s/^\n//; chomp $@;
4098 print STDERR <<END.(__ <<ENDT);
4101 | Not fast forward; maybe --overwrite is needed ? Please see dgit(1).
4106 my $arch_v = $i_arch_v->[0];
4107 my $r = pseudomerge_make_commit
4108 $clogp, $dgitview, $archive_hash, $i_arch_v,
4109 "dgit --quilt=$quilt_mode",
4110 (defined $overwrite_version
4111 ? f_ "Declare fast forward from %s\n", $arch_v
4112 : f_ "Make fast forward from %s\n", $arch_v);
4114 maybe_split_brain_save $maintview, $r, "pseudomerge";
4116 progress f_ "Made pseudo-merge of %s into dgit view.", $arch_v;
4120 sub plain_overwrite_pseudomerge ($$$) {
4121 my ($clogp, $head, $archive_hash) = @_;
4123 printdebug "plain_overwrite_pseudomerge...";
4125 my $i_arch_v = pseudomerge_version_check($clogp, $archive_hash);
4127 return $head if is_fast_fwd $archive_hash, $head;
4129 my $m = f_ "Declare fast forward from %s", $i_arch_v->[0];
4131 my $r = pseudomerge_make_commit
4132 $clogp, $head, $archive_hash, $i_arch_v,
4135 runcmd git_update_ref_cmd $m, 'HEAD', $r, $head;
4137 progress f_ "Make pseudo-merge of %s into your HEAD.", $i_arch_v->[0];
4141 sub push_parse_changelog ($) {
4144 my $clogp = Dpkg::Control::Hash->new();
4145 $clogp->load($clogpfn) or die;
4147 my $clogpackage = getfield $clogp, 'Source';
4148 $package //= $clogpackage;
4149 fail f_ "-p specified %s but changelog specified %s",
4150 $package, $clogpackage
4151 unless $package eq $clogpackage;
4152 my $cversion = getfield $clogp, 'Version';
4154 if (!$we_are_initiator) {
4155 # rpush initiator can't do this because it doesn't have $isuite yet
4156 my $tag = debiantag($cversion, access_nomdistro);
4157 runcmd @git, qw(check-ref-format), $tag;
4160 my $dscfn = dscfn($cversion);
4162 return ($clogp, $cversion, $dscfn);
4165 sub push_parse_dsc ($$$) {
4166 my ($dscfn,$dscfnwhat, $cversion) = @_;
4167 $dsc = parsecontrol($dscfn,$dscfnwhat);
4168 my $dversion = getfield $dsc, 'Version';
4169 my $dscpackage = getfield $dsc, 'Source';
4170 ($dscpackage eq $package && $dversion eq $cversion) or
4171 fail f_ "%s is for %s %s but debian/changelog is for %s %s",
4172 $dscfn, $dscpackage, $dversion,
4173 $package, $cversion;
4176 sub push_tagwants ($$$$) {
4177 my ($cversion, $dgithead, $maintviewhead, $tfbase) = @_;
4180 TagFn => \&debiantag,
4185 if (defined $maintviewhead) {
4187 TagFn => \&debiantag_maintview,
4188 Objid => $maintviewhead,
4189 TfSuffix => '-maintview',
4192 } elsif ($dodep14tag eq 'no' ? 0
4193 : $dodep14tag eq 'want' ? access_cfg_tagformats_can_splitbrain
4194 : $dodep14tag eq 'always'
4195 ? (access_cfg_tagformats_can_splitbrain or fail <<END)
4196 --dep14tag-always (or equivalent in config) means server must support
4197 both "new" and "maint" tag formats, but config says it doesn't.
4199 : die "$dodep14tag ?") {
4201 TagFn => \&debiantag_maintview,
4203 TfSuffix => '-dgit',
4207 foreach my $tw (@tagwants) {
4208 $tw->{Tag} = $tw->{TagFn}($cversion, access_nomdistro);
4209 $tw->{Tfn} = sub { $tfbase.$tw->{TfSuffix}.$_[0]; };
4211 printdebug 'push_tagwants: ', Dumper(\@_, \@tagwants);
4215 sub push_mktags ($$ $$ $) {
4217 $changesfile,$changesfilewhat,
4220 die unless $tagwants->[0]{View} eq 'dgit';
4222 my $declaredistro = access_nomdistro();
4223 my $reader_giturl = do { local $access_forpush=0; access_giturl(); };
4224 $dsc->{$ourdscfield[0]} = join " ",
4225 $tagwants->[0]{Objid}, $declaredistro, $tagwants->[0]{Tag},
4227 $dsc->save("$dscfn.tmp") or confess $!;
4229 my $changes = parsecontrol($changesfile,$changesfilewhat);
4230 foreach my $field (qw(Source Distribution Version)) {
4231 $changes->{$field} eq $clogp->{$field} or
4232 fail f_ "changes field %s \`%s' does not match changelog \`%s'",
4233 $field, $changes->{$field}, $clogp->{$field};
4236 my $cversion = getfield $clogp, 'Version';
4237 my $clogsuite = getfield $clogp, 'Distribution';
4239 # We make the git tag by hand because (a) that makes it easier
4240 # to control the "tagger" (b) we can do remote signing
4241 my $authline = clogp_authline $clogp;
4242 my $delibs = join(" ", "",@deliberatelies);
4246 my $tfn = $tw->{Tfn};
4247 my $head = $tw->{Objid};
4248 my $tag = $tw->{Tag};
4250 open TO, '>', $tfn->('.tmp') or confess $!;
4251 print TO <<END or confess $!;
4258 if ($tw->{View} eq 'dgit') {
4259 print TO f_ <<ENDT, $package, $cversion, $clogsuite, $csuite
4260 %s release %s for %s (%s) [dgit]
4263 print TO <<END or confess $!;
4264 [dgit distro=$declaredistro$delibs]
4266 foreach my $ref (sort keys %previously) {
4267 print TO <<END or confess $!;
4268 [dgit previously:$ref=$previously{$ref}]
4271 } elsif ($tw->{View} eq 'maint') {
4272 print TO f_ <<END, $package, $cversion, $clogsuite, $csuite,
4273 %s release %s for %s (%s)
4274 (maintainer view tag generated by dgit --quilt=%s)
4279 confess Dumper($tw)."?";
4282 close TO or confess $!;
4284 my $tagobjfn = $tfn->('.tmp');
4286 if (!defined $keyid) {
4287 $keyid = access_cfg('keyid','RETURN-UNDEF');
4289 if (!defined $keyid) {
4290 $keyid = getfield $clogp, 'Maintainer';
4292 unlink $tfn->('.tmp.asc') or $!==&ENOENT or confess $!;
4293 my @sign_cmd = (@gpg, qw(--detach-sign --armor));
4294 push @sign_cmd, qw(-u),$keyid if defined $keyid;
4295 push @sign_cmd, $tfn->('.tmp');
4296 runcmd_ordryrun @sign_cmd;
4298 $tagobjfn = $tfn->('.signed.tmp');
4299 runcmd shell_cmd "exec >$tagobjfn", qw(cat --),
4300 $tfn->('.tmp'), $tfn->('.tmp.asc');
4306 my @r = map { $mktag->($_); } @$tagwants;
4310 sub sign_changes ($) {
4311 my ($changesfile) = @_;
4313 my @debsign_cmd = @debsign;
4314 push @debsign_cmd, "-k$keyid" if defined $keyid;
4315 push @debsign_cmd, "-p$gpg[0]" if $gpg[0] ne 'gpg';
4316 push @debsign_cmd, $changesfile;
4317 runcmd_ordryrun @debsign_cmd;
4322 printdebug "actually entering push\n";
4324 supplementary_message(__ <<'END');
4325 Push failed, while checking state of the archive.
4326 You can retry the push, after fixing the problem, if you like.
4328 if (check_for_git()) {
4331 my $archive_hash = fetch_from_archive();
4332 if (!$archive_hash) {
4334 fail __ "package appears to be new in this suite;".
4335 " if this is intentional, use --new";
4338 supplementary_message(__ <<'END');
4339 Push failed, while preparing your push.
4340 You can retry the push, after fixing the problem, if you like.
4343 need_tagformat 'new', "quilt mode $quilt_mode"
4344 if quiltmode_splitbrain;
4348 access_giturl(); # check that success is vaguely likely
4349 rpush_handle_protovsn_bothends() if $we_are_initiator;
4352 my $clogpfn = dgit_privdir()."/changelog.822.tmp";
4353 runcmd shell_cmd "exec >$clogpfn", qw(dpkg-parsechangelog);
4355 responder_send_file('parsed-changelog', $clogpfn);
4357 my ($clogp, $cversion, $dscfn) =
4358 push_parse_changelog("$clogpfn");
4360 my $dscpath = "$buildproductsdir/$dscfn";
4361 stat_exists $dscpath or
4362 fail f_ "looked for .dsc %s, but %s; maybe you forgot to build",
4365 responder_send_file('dsc', $dscpath);
4367 push_parse_dsc($dscpath, $dscfn, $cversion);
4369 my $format = getfield $dsc, 'Format';
4370 printdebug "format $format\n";
4372 my $symref = git_get_symref();
4373 my $actualhead = git_rev_parse('HEAD');
4375 if (branch_is_gdr_unstitched_ff($symref, $actualhead, $archive_hash)) {
4376 if (quiltmode_splitbrain()) {
4377 my ($ffq_prev, $gdrlast) = branch_gdr_info($symref, $actualhead);
4378 fail f_ <<END, $ffq_prev, $quilt_mode;
4379 Branch is managed by git-debrebase (%s
4380 exists), but quilt mode (%s) implies a split view.
4381 Pass the right --quilt option or adjust your git config.
4382 Or, maybe, run git-debrebase forget-was-ever-debrebase.
4385 runcmd_ordryrun_local @git_debrebase, 'stitch';
4386 $actualhead = git_rev_parse('HEAD');
4389 my $dgithead = $actualhead;
4390 my $maintviewhead = undef;
4392 my $upstreamversion = upstreamversion $clogp->{Version};
4394 if (madformat_wantfixup($format)) {
4395 # user might have not used dgit build, so maybe do this now:
4396 if (quiltmode_splitbrain()) {
4397 changedir $playground;
4398 quilt_make_fake_dsc($upstreamversion);
4400 ($dgithead, $cachekey) =
4401 quilt_check_splitbrain_cache($actualhead, $upstreamversion);
4402 $dgithead or fail f_
4403 "--quilt=%s but no cached dgit view:
4404 perhaps HEAD changed since dgit build[-source] ?",
4407 $dgithead = splitbrain_pseudomerge($clogp,
4408 $actualhead, $dgithead,
4410 $maintviewhead = $actualhead;
4412 prep_ud(); # so _only_subdir() works, below
4414 commit_quilty_patch();
4418 if (defined $overwrite_version && !defined $maintviewhead
4420 $dgithead = plain_overwrite_pseudomerge($clogp,
4428 if ($archive_hash) {
4429 if (is_fast_fwd($archive_hash, $dgithead)) {
4431 } elsif (deliberately_not_fast_forward) {
4434 fail __ "dgit push: HEAD is not a descendant".
4435 " of the archive's version.\n".
4436 "To overwrite the archive's contents,".
4437 " pass --overwrite[=VERSION].\n".
4438 "To rewind history, if permitted by the archive,".
4439 " use --deliberately-not-fast-forward.";
4443 changedir $playground;
4444 progress f_ "checking that %s corresponds to HEAD", $dscfn;
4445 runcmd qw(dpkg-source -x --),
4446 $dscpath =~ m#^/# ? $dscpath : "$maindir/$dscpath";
4447 my ($tree,$dir) = mktree_in_ud_from_only_subdir("source package");
4448 check_for_vendor_patches() if madformat($dsc->{format});
4450 my @diffcmd = (@git, qw(diff --quiet), $tree, $dgithead);
4451 debugcmd "+",@diffcmd;
4453 my $r = system @diffcmd;
4456 my $referent = $split_brain ? $dgithead : 'HEAD';
4457 my $diffs = cmdoutput @git, qw(diff --stat), $tree, $dgithead;
4460 my $raw = cmdoutput @git,
4461 qw(diff --no-renames -z -r --raw), $tree, $dgithead;
4463 foreach (split /\0/, $raw) {
4464 if (defined $changed) {
4465 push @mode_changes, "$changed: $_\n" if $changed;
4468 } elsif (m/^:0+ 0+ /) {
4470 } elsif (m/^:(?:10*)?(\d+) (?:10*)?(\d+) /) {
4471 $changed = "Mode change from $1 to $2"
4476 if (@mode_changes) {
4477 fail +(f_ <<ENDT, $dscfn).<<END
4478 HEAD specifies a different tree to %s:
4482 .(join '', @mode_changes)
4483 .(f_ <<ENDT, $tree, $referent);
4484 There is a problem with your source tree (see dgit(7) for some hints).
4485 To see a full diff, run git diff %s %s
4489 fail +(f_ <<ENDT, $dscfn).<<END.(f_ <<ENDT, $tree, $referent);
4490 HEAD specifies a different tree to %s:
4494 Perhaps you forgot to build. Or perhaps there is a problem with your
4495 source tree (see dgit(7) for some hints). To see a full diff, run
4502 if (!$changesfile) {
4503 my $pat = changespat $cversion;
4504 my @cs = glob "$buildproductsdir/$pat";
4505 fail f_ "failed to find unique changes file".
4506 " (looked for %s in %s);".
4507 " perhaps you need to use dgit -C",
4508 $pat, $buildproductsdir
4510 ($changesfile) = @cs;
4512 $changesfile = "$buildproductsdir/$changesfile";
4515 # Check that changes and .dsc agree enough
4516 $changesfile =~ m{[^/]*$};
4517 my $changes = parsecontrol($changesfile,$&);
4518 files_compare_inputs($dsc, $changes)
4519 unless forceing [qw(dsc-changes-mismatch)];
4521 # Check whether this is a source only upload
4522 my $hasdebs = $changes->{Files} =~ m{\.deb$}m;
4523 my $sourceonlypolicy = access_cfg 'source-only-uploads';
4524 if ($sourceonlypolicy eq 'ok') {
4525 } elsif ($sourceonlypolicy eq 'always') {
4526 forceable_fail [qw(uploading-binaries)],
4527 __ "uploading binaries, although distro policy is source only"
4529 } elsif ($sourceonlypolicy eq 'never') {
4530 forceable_fail [qw(uploading-source-only)],
4531 __ "source-only upload, although distro policy requires .debs"
4533 } elsif ($sourceonlypolicy eq 'not-wholly-new') {
4534 forceable_fail [qw(uploading-source-only)],
4535 f_ "source-only upload, even though package is entirely NEW\n".
4536 "(this is contrary to policy in %s)",
4540 && !(archive_query('package_not_wholly_new', $package) // 1);
4542 badcfg f_ "unknown source-only-uploads policy \`%s'",
4546 # Perhaps adjust .dsc to contain right set of origs
4547 changes_update_origs_from_dsc($dsc, $changes, $upstreamversion,
4549 unless forceing [qw(changes-origs-exactly)];
4551 # Checks complete, we're going to try and go ahead:
4553 responder_send_file('changes',$changesfile);
4554 responder_send_command("param head $dgithead");
4555 responder_send_command("param csuite $csuite");
4556 responder_send_command("param isuite $isuite");
4557 responder_send_command("param tagformat $tagformat");
4558 if (defined $maintviewhead) {
4559 confess "internal error (protovsn=$protovsn)"
4560 if defined $protovsn and $protovsn < 4;
4561 responder_send_command("param maint-view $maintviewhead");
4564 # Perhaps send buildinfo(s) for signing
4565 my $changes_files = getfield $changes, 'Files';
4566 my @buildinfos = ($changes_files =~ m/ .* (\S+\.buildinfo)$/mg);
4567 foreach my $bi (@buildinfos) {
4568 responder_send_command("param buildinfo-filename $bi");
4569 responder_send_file('buildinfo', "$buildproductsdir/$bi");
4572 if (deliberately_not_fast_forward) {
4573 git_for_each_ref(lrfetchrefs, sub {
4574 my ($objid,$objtype,$lrfetchrefname,$reftail) = @_;
4575 my $rrefname= substr($lrfetchrefname, length(lrfetchrefs) + 1);
4576 responder_send_command("previously $rrefname=$objid");
4577 $previously{$rrefname} = $objid;
4581 my @tagwants = push_tagwants($cversion, $dgithead, $maintviewhead,
4582 dgit_privdir()."/tag");
4585 supplementary_message(__ <<'END');
4586 Push failed, while signing the tag.
4587 You can retry the push, after fixing the problem, if you like.
4589 # If we manage to sign but fail to record it anywhere, it's fine.
4590 if ($we_are_responder) {
4591 @tagobjfns = map { $_->{Tfn}('.signed-tmp') } @tagwants;
4592 responder_receive_files('signed-tag', @tagobjfns);
4594 @tagobjfns = push_mktags($clogp,$dscpath,
4595 $changesfile,$changesfile,
4598 supplementary_message(__ <<'END');
4599 Push failed, *after* signing the tag.
4600 If you want to try again, you should use a new version number.
4603 pairwise { $a->{TagObjFn} = $b } @tagwants, @tagobjfns;
4605 foreach my $tw (@tagwants) {
4606 my $tag = $tw->{Tag};
4607 my $tagobjfn = $tw->{TagObjFn};
4609 cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
4610 runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
4611 runcmd_ordryrun_local
4612 @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
4615 supplementary_message(__ <<'END');
4616 Push failed, while updating the remote git repository - see messages above.
4617 If you want to try again, you should use a new version number.
4619 if (!check_for_git()) {
4620 create_remote_git_repo();
4623 my @pushrefs = $forceflag.$dgithead.":".rrref();
4624 foreach my $tw (@tagwants) {
4625 push @pushrefs, $forceflag."refs/tags/$tw->{Tag}";
4628 runcmd_ordryrun @git,
4629 qw(-c push.followTags=false push), access_giturl(), @pushrefs;
4630 runcmd_ordryrun git_update_ref_cmd 'dgit push', lrref(), $dgithead;
4632 supplementary_message(__ <<'END');
4633 Push failed, while obtaining signatures on the .changes and .dsc.
4634 If it was just that the signature failed, you may try again by using
4635 debsign by hand to sign the changes file (see the command dgit tried,
4636 above), and then dput that changes file to complete the upload.
4637 If you need to change the package, you must use a new version number.
4639 if ($we_are_responder) {
4640 my $dryrunsuffix = act_local() ? "" : ".tmp";
4641 my @rfiles = ($dscpath, $changesfile);
4642 push @rfiles, map { "$buildproductsdir/$_" } @buildinfos;
4643 responder_receive_files('signed-dsc-changes',
4644 map { "$_$dryrunsuffix" } @rfiles);
4647 rename "$dscpath.tmp",$dscpath or die "$dscfn $!";
4649 progress f_ "[new .dsc left in %s.tmp]", $dscpath;
4651 sign_changes $changesfile;
4654 supplementary_message(f_ <<END, $changesfile);
4655 Push failed, while uploading package(s) to the archive server.
4656 You can retry the upload of exactly these same files with dput of:
4658 If that .changes file is broken, you will need to use a new version
4659 number for your next attempt at the upload.
4661 my $host = access_cfg('upload-host','RETURN-UNDEF');
4662 my @hostarg = defined($host) ? ($host,) : ();
4663 runcmd_ordryrun @dput, @hostarg, $changesfile;
4664 printdone f_ "pushed and uploaded %s", $cversion;
4666 supplementary_message('');
4667 responder_send_command("complete");
4671 not_necessarily_a_tree();
4676 badusage __ "-p is not allowed with clone; specify as argument instead"
4677 if defined $package;
4680 } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
4681 ($package,$isuite) = @ARGV;
4682 } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
4683 ($package,$dstdir) = @ARGV;
4684 } elsif (@ARGV==3) {
4685 ($package,$isuite,$dstdir) = @ARGV;
4687 badusage __ "incorrect arguments to dgit clone";
4691 $dstdir ||= "$package";
4692 if (stat_exists $dstdir) {
4693 fail f_ "%s already exists", $dstdir;
4697 if ($rmonerror && !$dryrun_level) {
4698 $cwd_remove= getcwd();
4700 return unless defined $cwd_remove;
4701 if (!chdir "$cwd_remove") {
4702 return if $!==&ENOENT;
4703 confess "chdir $cwd_remove: $!";
4705 printdebug "clone rmonerror removing $dstdir\n";
4707 rmtree($dstdir) or fail f_ "remove %s: %s\n", $dstdir, $!;
4708 } elsif (grep { $! == $_ }
4709 (ENOENT, ENOTDIR, EACCES, EPERM, ELOOP)) {
4711 print STDERR f_ "check whether to remove %s: %s\n",
4718 $cwd_remove = undef;
4721 sub branchsuite () {
4722 my $branch = git_get_symref();
4723 if (defined $branch && $branch =~ m#$lbranch_re#o) {
4730 sub package_from_d_control () {
4731 if (!defined $package) {
4732 my $sourcep = parsecontrol('debian/control','debian/control');
4733 $package = getfield $sourcep, 'Source';
4737 sub fetchpullargs () {
4738 package_from_d_control();
4740 $isuite = branchsuite();
4742 my $clogp = parsechangelog();
4743 my $clogsuite = getfield $clogp, 'Distribution';
4744 $isuite= $clogsuite if $clogsuite ne 'UNRELEASED';
4746 } elsif (@ARGV==1) {
4749 badusage __ "incorrect arguments to dgit fetch or dgit pull";
4763 if (quiltmode_splitbrain()) {
4764 my ($format, $fopts) = get_source_format();
4765 madformat($format) and fail f_ <<END, $quilt_mode
4766 dgit pull not yet supported in split view mode (--quilt=%s)
4774 package_from_d_control();
4775 @ARGV==1 or badusage __ "dgit checkout needs a suite argument";
4779 foreach my $canon (qw(0 1)) {
4784 canonicalise_suite();
4786 if (length git_get_ref lref()) {
4787 # local branch already exists, yay
4790 if (!length git_get_ref lrref()) {
4798 runcmd (@git, qw(update-ref), lref(), lrref(), '');
4801 local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
4802 "dgit checkout $isuite";
4803 runcmd (@git, qw(checkout), lbranch());
4806 sub cmd_update_vcs_git () {
4808 if (@ARGV==0 || $ARGV[0] =~ m/^-/) {
4809 ($specsuite,) = split /\;/, cfg 'dgit.vcs-git.suites';
4811 ($specsuite) = (@ARGV);
4816 if ($ARGV[0] eq '-') {
4818 } elsif ($ARGV[0] eq '-') {
4823 package_from_d_control();
4825 if ($specsuite eq '.') {
4826 $ctrl = parsecontrol 'debian/control', 'debian/control';
4828 $isuite = $specsuite;
4832 my $url = getfield $ctrl, 'Vcs-Git';
4835 my $orgurl = cfg 'remote.vcs-git.url', 'RETURN-UNDEF';
4836 if (!defined $orgurl) {
4837 print STDERR f_ "setting up vcs-git: %s\n", $url;
4838 @cmd = (@git, qw(remote add vcs-git), $url);
4839 } elsif ($orgurl eq $url) {
4840 print STDERR f_ "vcs git already configured: %s\n", $url;
4842 print STDERR f_ "changing vcs-git url to: %s\n", $url;
4843 @cmd = (@git, qw(remote set-url vcs-git), $url);
4845 runcmd_ordryrun_local @cmd;
4847 print f_ "fetching (%s)\n", "@ARGV";
4848 runcmd_ordryrun_local @git, qw(fetch vcs-git), @ARGV;
4854 build_or_push_prep_early();
4859 } elsif (@ARGV==1) {
4860 ($specsuite) = (@ARGV);
4862 badusage f_ "incorrect arguments to dgit %s", $subcommand;
4865 local ($package) = $existing_package; # this is a hack
4866 canonicalise_suite();
4868 canonicalise_suite();
4870 if (defined $specsuite &&
4871 $specsuite ne $isuite &&
4872 $specsuite ne $csuite) {
4873 fail f_ "dgit %s: changelog specifies %s (%s)".
4874 " but command line specifies %s",
4875 $subcommand, $isuite, $csuite, $specsuite;
4884 #---------- remote commands' implementation ----------
4886 sub pre_remote_push_build_host {
4887 my ($nrargs) = shift @ARGV;
4888 my (@rargs) = @ARGV[0..$nrargs-1];
4889 @ARGV = @ARGV[$nrargs..$#ARGV];
4891 my ($dir,$vsnwant) = @rargs;
4892 # vsnwant is a comma-separated list; we report which we have
4893 # chosen in our ready response (so other end can tell if they
4896 $we_are_responder = 1;
4897 $us .= " (build host)";
4899 open PI, "<&STDIN" or confess $!;
4900 open STDIN, "/dev/null" or confess $!;
4901 open PO, ">&STDOUT" or confess $!;
4903 open STDOUT, ">&STDERR" or confess $!;
4907 ($protovsn) = grep {
4908 $vsnwant =~ m{^(?:.*,)?$_(?:,.*)?$}
4909 } @rpushprotovsn_support;
4911 fail f_ "build host has dgit rpush protocol versions %s".
4912 " but invocation host has %s",
4913 (join ",", @rpushprotovsn_support), $vsnwant
4914 unless defined $protovsn;
4918 sub cmd_remote_push_build_host {
4919 responder_send_command("dgit-remote-push-ready $protovsn");
4923 sub pre_remote_push_responder { pre_remote_push_build_host(); }
4924 sub cmd_remote_push_responder { cmd_remote_push_build_host(); }
4925 # ... for compatibility with proto vsn.1 dgit (just so that user gets
4926 # a good error message)
4928 sub rpush_handle_protovsn_bothends () {
4929 if ($protovsn < 4) {
4930 need_tagformat 'old', "rpush negotiated protocol $protovsn";
4939 my $report = i_child_report();
4940 if (defined $report) {
4941 printdebug "($report)\n";
4942 } elsif ($i_child_pid) {
4943 printdebug "(killing build host child $i_child_pid)\n";
4944 kill 15, $i_child_pid;
4946 if (defined $i_tmp && !defined $initiator_tempdir) {
4948 eval { rmtree $i_tmp; };
4953 return unless forkcheck_mainprocess();
4958 my ($base,$selector,@args) = @_;
4959 $selector =~ s/\-/_/g;
4960 { no strict qw(refs); &{"${base}_${selector}"}(@args); }
4964 not_necessarily_a_tree();
4969 if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
4977 push @rargs, join ",", @rpushprotovsn_support;
4980 push @rdgit, @ropts;
4981 push @rdgit, qw(remote-push-build-host), (scalar @rargs), @rargs;
4983 my @cmd = (@ssh, $host, shellquote @rdgit);
4986 $we_are_initiator=1;
4988 if (defined $initiator_tempdir) {
4989 rmtree $initiator_tempdir;
4990 mkdir $initiator_tempdir, 0700
4991 or fail f_ "create %s: %s", $initiator_tempdir, $!;
4992 $i_tmp = $initiator_tempdir;
4996 $i_child_pid = open2(\*RO, \*RI, @cmd);
4998 ($protovsn) = initiator_expect { m/^dgit-remote-push-ready (\S+)/ };
4999 die "$protovsn ?" unless grep { $_ eq $protovsn } @rpushprotovsn_support;
5000 $supplementary_message = '' unless $protovsn >= 3;
5003 my ($icmd,$iargs) = initiator_expect {
5004 m/^(\S+)(?: (.*))?$/;
5007 i_method "i_resp", $icmd, $iargs;
5011 sub i_resp_progress ($) {
5013 my $msg = protocol_read_bytes \*RO, $rhs;
5017 sub i_resp_supplementary_message ($) {
5019 $supplementary_message = protocol_read_bytes \*RO, $rhs;
5022 sub i_resp_complete {
5023 my $pid = $i_child_pid;
5024 $i_child_pid = undef; # prevents killing some other process with same pid
5025 printdebug "waiting for build host child $pid...\n";
5026 my $got = waitpid $pid, 0;
5027 confess $! unless $got == $pid;
5028 fail f_ "build host child failed: %s", waitstatusmsg() if $?;
5031 printdebug __ "all done\n";
5035 sub i_resp_file ($) {
5037 my $localname = i_method "i_localname", $keyword;
5038 my $localpath = "$i_tmp/$localname";
5039 stat_exists $localpath and
5040 badproto \*RO, f_ "file %s (%s) twice", $keyword, $localpath;
5041 protocol_receive_file \*RO, $localpath;
5042 i_method "i_file", $keyword;
5047 sub i_resp_param ($) {
5048 $_[0] =~ m/^(\S+) (.*)$/ or badproto \*RO, __ "bad param spec";
5052 sub i_resp_previously ($) {
5053 $_[0] =~ m#^(refs/tags/\S+)=(\w+)$#
5054 or badproto \*RO, __ "bad previously spec";
5055 my $r = system qw(git check-ref-format), $1;
5056 confess "bad previously ref spec ($r)" if $r;
5057 $previously{$1} = $2;
5062 sub i_resp_want ($) {
5064 die "$keyword ?" if $i_wanted{$keyword}++;
5066 defined $i_param{'csuite'} or badproto \*RO, "premature desire, no csuite";
5067 $isuite = $i_param{'isuite'} // $i_param{'csuite'};
5068 die unless $isuite =~ m/^$suite_re$/;
5071 rpush_handle_protovsn_bothends();
5073 fail f_ "rpush negotiated protocol version %s".
5074 " which does not support quilt mode %s",
5075 $protovsn, $quilt_mode
5076 if quiltmode_splitbrain;
5078 my @localpaths = i_method "i_want", $keyword;
5079 printdebug "[[ $keyword @localpaths\n";
5080 foreach my $localpath (@localpaths) {
5081 protocol_send_file \*RI, $localpath;
5083 print RI "files-end\n" or confess $!;
5086 our ($i_clogp, $i_version, $i_dscfn, $i_changesfn, @i_buildinfos);
5088 sub i_localname_parsed_changelog {
5089 return "remote-changelog.822";
5091 sub i_file_parsed_changelog {
5092 ($i_clogp, $i_version, $i_dscfn) =
5093 push_parse_changelog "$i_tmp/remote-changelog.822";
5094 die if $i_dscfn =~ m#/|^\W#;
5097 sub i_localname_dsc {
5098 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
5103 sub i_localname_buildinfo ($) {
5104 my $bi = $i_param{'buildinfo-filename'};
5105 defined $bi or badproto \*RO, "buildinfo before filename";
5106 defined $i_changesfn or badproto \*RO, "buildinfo before changes";
5107 $bi =~ m{^\Q$package\E_[!-.0-~]*\.buildinfo$}s
5108 or badproto \*RO, "improper buildinfo filename";
5111 sub i_file_buildinfo {
5112 my $bi = $i_param{'buildinfo-filename'};
5113 my $bd = parsecontrol "$i_tmp/$bi", $bi;
5114 my $ch = parsecontrol "$i_tmp/$i_changesfn", 'changes';
5115 if (!forceing [qw(buildinfo-changes-mismatch)]) {
5116 files_compare_inputs($bd, $ch);
5117 (getfield $bd, $_) eq (getfield $ch, $_) or
5118 fail f_ "buildinfo mismatch in field %s", $_
5119 foreach qw(Source Version);
5120 !defined $bd->{$_} or
5121 fail f_ "buildinfo contains forbidden field %s", $_
5122 foreach qw(Changes Changed-by Distribution);
5124 push @i_buildinfos, $bi;
5125 delete $i_param{'buildinfo-filename'};
5128 sub i_localname_changes {
5129 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
5130 $i_changesfn = $i_dscfn;
5131 $i_changesfn =~ s/\.dsc$/_dgit.changes/ or die;
5132 return $i_changesfn;
5134 sub i_file_changes { }
5136 sub i_want_signed_tag {
5137 printdebug Dumper(\%i_param, $i_dscfn);
5138 defined $i_param{'head'} && defined $i_dscfn && defined $i_clogp
5139 && defined $i_param{'csuite'}
5140 or badproto \*RO, "premature desire for signed-tag";
5141 my $head = $i_param{'head'};
5142 die if $head =~ m/[^0-9a-f]/ || $head !~ m/^../;
5144 my $maintview = $i_param{'maint-view'};
5145 die if defined $maintview && $maintview =~ m/[^0-9a-f]/;
5148 if ($protovsn >= 4) {
5149 my $p = $i_param{'tagformat'} // '<undef>';
5151 or badproto \*RO, "tag format mismatch: $p vs. $tagformat";
5154 die unless $i_param{'csuite'} =~ m/^$suite_re$/;
5156 push_parse_dsc $i_dscfn, 'remote dsc', $i_version;
5158 my @tagwants = push_tagwants $i_version, $head, $maintview, "tag";
5161 push_mktags $i_clogp, $i_dscfn,
5162 $i_changesfn, (__ 'remote changes file'),
5166 sub i_want_signed_dsc_changes {
5167 rename "$i_dscfn.tmp","$i_dscfn" or die "$i_dscfn $!";
5168 sign_changes $i_changesfn;
5169 return ($i_dscfn, $i_changesfn, @i_buildinfos);
5172 #---------- building etc. ----------
5178 #----- `3.0 (quilt)' handling -----
5180 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
5182 sub quiltify_dpkg_commit ($$$;$) {
5183 my ($patchname,$author,$msg, $xinfo) = @_;
5186 mkpath '.git/dgit'; # we are in playtree
5187 my $descfn = ".git/dgit/quilt-description.tmp";
5188 open O, '>', $descfn or confess "$descfn: $!";
5189 $msg =~ s/\n+/\n\n/;
5190 print O <<END or confess $!;
5192 ${xinfo}Subject: $msg
5196 close O or confess $!;
5199 local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
5200 local $ENV{'VISUAL'} = $ENV{'EDITOR'};
5201 local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
5202 runcmd @dpkgsource, qw(--commit --include-removal .), $patchname;
5206 sub quiltify_trees_differ ($$;$$$) {
5207 my ($x,$y,$finegrained,$ignorenamesr,$unrepres) = @_;
5208 # returns true iff the two tree objects differ other than in debian/
5209 # with $finegrained,
5210 # returns bitmask 01 - differ in upstream files except .gitignore
5211 # 02 - differ in .gitignore
5212 # if $ignorenamesr is defined, $ingorenamesr->{$fn}
5213 # is set for each modified .gitignore filename $fn
5214 # if $unrepres is defined, array ref to which is appeneded
5215 # a list of unrepresentable changes (removals of upstream files
5218 my @cmd = (@git, qw(diff-tree -z --no-renames));
5219 push @cmd, qw(--name-only) unless $unrepres;
5220 push @cmd, qw(-r) if $finegrained || $unrepres;
5222 my $diffs= cmdoutput @cmd;
5225 foreach my $f (split /\0/, $diffs) {
5226 if ($unrepres && !@lmodes) {
5227 @lmodes = $f =~ m/^\:(\w+) (\w+) \w+ \w+ / or die "$_ ?";
5230 my ($oldmode,$newmode) = @lmodes;
5233 next if $f =~ m#^debian(?:/.*)?$#s;
5237 die __ "not a plain file or symlink\n"
5238 unless $newmode =~ m/^(?:10|12)\d{4}$/ ||
5239 $oldmode =~ m/^(?:10|12)\d{4}$/;
5240 if ($oldmode =~ m/[^0]/ &&
5241 $newmode =~ m/[^0]/) {
5242 # both old and new files exist
5243 die __ "mode or type changed\n" if $oldmode ne $newmode;
5244 die __ "modified symlink\n" unless $newmode =~ m/^10/;
5245 } elsif ($oldmode =~ m/[^0]/) {
5247 die __ "deletion of symlink\n"
5248 unless $oldmode =~ m/^10/;
5251 die __ "creation with non-default mode\n"
5252 unless $newmode =~ m/^100644$/ or
5253 $newmode =~ m/^120000$/;
5257 local $/="\n"; chomp $@;
5258 push @$unrepres, [ $f, "$@ ($oldmode->$newmode)" ];
5262 my $isignore = $f =~ m#^(?:.*/)?.gitignore$#s;
5263 $r |= $isignore ? 02 : 01;
5264 $ignorenamesr->{$f}=1 if $ignorenamesr && $isignore;
5266 printdebug "quiltify_trees_differ $x $y => $r\n";
5270 sub quiltify_tree_sentinelfiles ($) {
5271 # lists the `sentinel' files present in the tree
5273 my $r = cmdoutput @git, qw(ls-tree --name-only), $x,
5274 qw(-- debian/rules debian/control);
5279 sub quiltify_splitbrain_needed () {
5280 if (!$split_brain) {
5281 progress __ "dgit view: changes are required...";
5282 runcmd @git, qw(checkout -q -b dgit-view);
5287 sub quiltify_splitbrain ($$$$$$$) {
5288 my ($clogp, $unapplied, $headref, $oldtiptree, $diffbits,
5289 $editedignores, $cachekey) = @_;
5290 my $gitignore_special = 1;
5291 if ($quilt_mode !~ m/gbp|dpm/) {
5292 # treat .gitignore just like any other upstream file
5293 $diffbits = { %$diffbits };
5294 $_ = !!$_ foreach values %$diffbits;
5295 $gitignore_special = 0;
5297 # We would like any commits we generate to be reproducible
5298 my @authline = clogp_authline($clogp);
5299 local $ENV{GIT_COMMITTER_NAME} = $authline[0];
5300 local $ENV{GIT_COMMITTER_EMAIL} = $authline[1];
5301 local $ENV{GIT_COMMITTER_DATE} = $authline[2];
5302 local $ENV{GIT_AUTHOR_NAME} = $authline[0];
5303 local $ENV{GIT_AUTHOR_EMAIL} = $authline[1];
5304 local $ENV{GIT_AUTHOR_DATE} = $authline[2];
5306 my $fulldiffhint = sub {
5308 my $cmd = "git diff $x $y -- :/ ':!debian'";
5309 $cmd .= " ':!/.gitignore' ':!*/.gitignore'" if $gitignore_special;
5310 return f_ "\nFor full diff showing the problem(s), type:\n %s\n",
5314 if ($quilt_mode =~ m/gbp|unapplied/ &&
5315 ($diffbits->{O2H} & 01)) {
5317 "--quilt=%s specified, implying patches-unapplied git tree\n".
5318 " but git tree differs from orig in upstream files.",
5320 $msg .= $fulldiffhint->($unapplied, 'HEAD');
5321 if (!stat_exists "debian/patches") {
5323 "\n ... debian/patches is missing; perhaps this is a patch queue branch?";
5327 if ($quilt_mode =~ m/dpm/ &&
5328 ($diffbits->{H2A} & 01)) {
5329 fail +(f_ <<END, $quilt_mode). $fulldiffhint->($oldtiptree,'HEAD');
5330 --quilt=%s specified, implying patches-applied git tree
5331 but git tree differs from result of applying debian/patches to upstream
5334 if ($quilt_mode =~ m/gbp|unapplied/ &&
5335 ($diffbits->{O2A} & 01)) { # some patches
5336 quiltify_splitbrain_needed();
5337 progress __ "dgit view: creating patches-applied version using gbp pq";
5338 runcmd shell_cmd 'exec >/dev/null', gbp_pq, qw(import);
5339 # gbp pq import creates a fresh branch; push back to dgit-view
5340 runcmd @git, qw(update-ref refs/heads/dgit-view HEAD);
5341 runcmd @git, qw(checkout -q dgit-view);
5343 if ($quilt_mode =~ m/gbp|dpm/ &&
5344 ($diffbits->{O2A} & 02)) {
5345 fail f_ <<END, $quilt_mode;
5346 --quilt=%s specified, implying that HEAD is for use with a
5347 tool which does not create patches for changes to upstream
5348 .gitignores: but, such patches exist in debian/patches.
5351 if (($diffbits->{O2H} & 02) && # user has modified .gitignore
5352 !($diffbits->{O2A} & 02)) { # patches do not change .gitignore
5353 quiltify_splitbrain_needed();
5355 "dgit view: creating patch to represent .gitignore changes";
5356 ensuredir "debian/patches";
5357 my $gipatch = "debian/patches/auto-gitignore";
5358 open GIPATCH, ">>", "$gipatch" or confess "$gipatch: $!";
5359 stat GIPATCH or confess "$gipatch: $!";
5360 fail f_ "%s already exists; but want to create it".
5361 " to record .gitignore changes",
5364 print GIPATCH +(__ <<END).<<ENDU or die "$gipatch: $!";
5365 Subject: Update .gitignore from Debian packaging branch
5367 The Debian packaging git branch contains these updates to the upstream
5368 .gitignore file(s). This patch is autogenerated, to provide these
5369 updates to users of the official Debian archive view of the package.
5372 [dgit ($our_version) update-gitignore]
5375 close GIPATCH or die "$gipatch: $!";
5376 runcmd shell_cmd "exec >>$gipatch", @git, qw(diff),
5377 $unapplied, $headref, "--", sort keys %$editedignores;
5378 open SERIES, "+>>", "debian/patches/series" or confess $!;
5379 defined seek SERIES, -1, 2 or $!==EINVAL or confess $!;
5381 defined read SERIES, $newline, 1 or confess $!;
5382 print SERIES "\n" or confess $! unless $newline eq "\n";
5383 print SERIES "auto-gitignore\n" or confess $!;
5384 close SERIES or die $!;
5385 runcmd @git, qw(add -f -- debian/patches/series), $gipatch;
5386 commit_admin +(__ <<END).<<ENDU
5387 Commit patch to update .gitignore
5390 [dgit ($our_version) update-gitignore-quilt-fixup]
5394 my $dgitview = git_rev_parse 'HEAD';
5397 reflog_cache_insert "refs/$splitbraincache", $cachekey, $dgitview;
5399 changedir "$playground/work";
5401 my $saved = maybe_split_brain_save $headref, $dgitview, __ "converted";
5402 progress f_ "dgit view: created (%s)", $saved;
5405 sub quiltify ($$$$) {
5406 my ($clogp,$target,$oldtiptree,$failsuggestion) = @_;
5408 # Quilt patchification algorithm
5410 # We search backwards through the history of the main tree's HEAD
5411 # (T) looking for a start commit S whose tree object is identical
5412 # to to the patch tip tree (ie the tree corresponding to the
5413 # current dpkg-committed patch series). For these purposes
5414 # `identical' disregards anything in debian/ - this wrinkle is
5415 # necessary because dpkg-source treates debian/ specially.
5417 # We can only traverse edges where at most one of the ancestors'
5418 # trees differs (in changes outside in debian/). And we cannot
5419 # handle edges which change .pc/ or debian/patches. To avoid
5420 # going down a rathole we avoid traversing edges which introduce
5421 # debian/rules or debian/control. And we set a limit on the
5422 # number of edges we are willing to look at.
5424 # If we succeed, we walk forwards again. For each traversed edge
5425 # PC (with P parent, C child) (starting with P=S and ending with
5426 # C=T) to we do this:
5428 # - dpkg-source --commit with a patch name and message derived from C
5429 # After traversing PT, we git commit the changes which
5430 # should be contained within debian/patches.
5432 # The search for the path S..T is breadth-first. We maintain a
5433 # todo list containing search nodes. A search node identifies a
5434 # commit, and looks something like this:
5436 # Commit => $git_commit_id,
5437 # Child => $c, # or undef if P=T
5438 # Whynot => $reason_edge_PC_unsuitable, # in @nots only
5439 # Nontrivial => true iff $p..$c has relevant changes
5446 my %considered; # saves being exponential on some weird graphs
5448 my $t_sentinels = quiltify_tree_sentinelfiles $target;
5451 my ($search,$whynot) = @_;
5452 printdebug " search NOT $search->{Commit} $whynot\n";
5453 $search->{Whynot} = $whynot;
5454 push @nots, $search;
5455 no warnings qw(exiting);
5464 my $c = shift @todo;
5465 next if $considered{$c->{Commit}}++;
5467 $not->($c, __ "maximum search space exceeded") if --$max_work <= 0;
5469 printdebug "quiltify investigate $c->{Commit}\n";
5472 if (!quiltify_trees_differ $c->{Commit}, $oldtiptree) {
5473 printdebug " search finished hooray!\n";
5478 quiltify_nofix_bail " $c->{Commit}", " (tree object $oldtiptree)";
5479 if ($quilt_mode eq 'smash') {
5480 printdebug " search quitting smash\n";
5484 my $c_sentinels = quiltify_tree_sentinelfiles $c->{Commit};
5485 $not->($c, f_ "has %s not %s", $c_sentinels, $t_sentinels)
5486 if $c_sentinels ne $t_sentinels;
5488 my $commitdata = cmdoutput @git, qw(cat-file commit), $c->{Commit};
5489 $commitdata =~ m/\n\n/;
5491 my @parents = ($commitdata =~ m/^parent (\w+)$/gm);
5492 @parents = map { { Commit => $_, Child => $c } } @parents;
5494 $not->($c, __ "root commit") if !@parents;
5496 foreach my $p (@parents) {
5497 $p->{Nontrivial}= quiltify_trees_differ $p->{Commit},$c->{Commit};
5499 my $ndiffers = grep { $_->{Nontrivial} } @parents;
5500 $not->($c, f_ "merge (%s nontrivial parents)", $ndiffers)
5503 foreach my $p (@parents) {
5504 printdebug "considering C=$c->{Commit} P=$p->{Commit}\n";
5506 my @cmd= (@git, qw(diff-tree -r --name-only),
5507 $p->{Commit},$c->{Commit},
5508 qw(-- debian/patches .pc debian/source/format));
5509 my $patchstackchange = cmdoutput @cmd;
5510 if (length $patchstackchange) {
5511 $patchstackchange =~ s/\n/,/g;
5512 $not->($p, f_ "changed %s", $patchstackchange);
5515 printdebug " search queue P=$p->{Commit} ",
5516 ($p->{Nontrivial} ? "NT" : "triv"),"\n";
5522 printdebug "quiltify want to smash\n";
5525 my $x = $_[0]{Commit};
5526 $x =~ s/(.*?[0-9a-z]{8})[0-9a-z]*$/$1/;
5529 if ($quilt_mode eq 'linear') {
5531 "\n%s: error: quilt fixup cannot be linear. Stopped at:\n",
5533 my $all_gdr = !!@nots;
5534 foreach my $notp (@nots) {
5535 my $c = $notp->{Child};
5536 my $cprange = $abbrev->($notp);
5537 $cprange .= "..".$abbrev->($c) if $c;
5538 print STDERR f_ "%s: %s: %s\n",
5539 $us, $cprange, $notp->{Whynot};
5540 $all_gdr &&= $notp->{Child} &&
5541 (git_cat_file $notp->{Child}{Commit}, 'commit')
5542 =~ m{^\[git-debrebase(?! split[: ]).*\]$}m;
5546 [ grep { $_->[0] ne 'quilt-mode' } @$failsuggestion ]
5548 print STDERR "$us: $_->[1]\n" foreach @$failsuggestion;
5550 "quilt history linearisation failed. Search \`quilt fixup' in dgit(7).\n";
5551 } elsif ($quilt_mode eq 'smash') {
5552 } elsif ($quilt_mode eq 'auto') {
5553 progress __ "quilt fixup cannot be linear, smashing...";
5555 confess "$quilt_mode ?";
5558 my $time = $ENV{'GIT_COMMITTER_DATE'} || time;
5559 $time =~ s/\s.*//; # trim timezone from GIT_COMMITTER_DATE
5561 my $msg = cmdoutput @git, qw(log), "-n$ncommits";
5563 quiltify_dpkg_commit "auto-$version-$target-$time",
5564 (getfield $clogp, 'Maintainer'),
5565 (f_ "Automatically generated patch (%s)\n".
5566 "Last (up to) %s git changes, FYI:\n\n",
5567 $clogp->{Version}, $ncommits).
5572 progress __ "quiltify linearisation planning successful, executing...";
5574 for (my $p = $sref_S;
5575 my $c = $p->{Child};
5577 printdebug "quiltify traverse $p->{Commit}..$c->{Commit}\n";
5578 next unless $p->{Nontrivial};
5580 my $cc = $c->{Commit};
5582 my $commitdata = cmdoutput @git, qw(cat-file commit), $cc;
5583 $commitdata =~ m/\n\n/ or die "$c ?";
5586 $commitdata =~ m/^author (.*) \d+ [-+0-9]+$/m or die "$cc ?";
5589 my $commitdate = cmdoutput
5590 @git, qw(log -n1 --pretty=format:%aD), $cc;
5592 $msg =~ s/^(.*)\n*/$1\n/ or die "$cc $msg ?";
5594 my $strip_nls = sub { $msg =~ s/\n+$//; $msg .= "\n"; };
5601 my $gbp_check_suitable = sub {
5606 die __ "contains unexpected slashes\n" if m{//} || m{/$};
5607 die __ "contains leading punctuation\n" if m{^\W} || m{/\W};
5608 die __ "contains bad character(s)\n" if m{[^-a-z0-9_.+=~/]}i;
5609 die __ "is series file\n" if m{$series_filename_re}o;
5610 die __ "too long\n" if length > 200;
5612 return $_ unless $@;
5614 "quiltifying commit %s: ignoring/dropping Gbp-Pq %s: %s",
5619 if ($msg =~ s/^ (?: gbp(?:-pq)? : \s* name \s+ |
5621 (\S+) \s* \n //ixm) {
5622 $patchname = $gbp_check_suitable->($1, 'Name');
5624 if ($msg =~ s/^ (?: gbp(?:-pq)? : \s* topic \s+ |
5626 (\S+) \s* \n //ixm) {
5627 $patchdir = $gbp_check_suitable->($1, 'Topic');
5632 if (!defined $patchname) {
5633 $patchname = $title;
5634 $patchname =~ s/[.:]$//;
5637 my $converter = new Text::Iconv qw(UTF-8 ASCII//TRANSLIT);
5638 my $translitname = $converter->convert($patchname);
5639 die unless defined $translitname;
5640 $patchname = $translitname;
5643 +(f_ "dgit: patch title transliteration error: %s", $@)
5645 $patchname =~ y/ A-Z/-a-z/;
5646 $patchname =~ y/-a-z0-9_.+=~//cd;
5647 $patchname =~ s/^\W/x-$&/;
5648 $patchname = substr($patchname,0,40);
5649 $patchname .= ".patch";
5651 if (!defined $patchdir) {
5654 if (length $patchdir) {
5655 $patchname = "$patchdir/$patchname";
5657 if ($patchname =~ m{^(.*)/}) {
5658 mkpath "debian/patches/$1";
5663 stat "debian/patches/$patchname$index";
5665 $!==ENOENT or confess "$patchname$index $!";
5667 runcmd @git, qw(checkout -q), $cc;
5669 # We use the tip's changelog so that dpkg-source doesn't
5670 # produce complaining messages from dpkg-parsechangelog. None
5671 # of the information dpkg-source gets from the changelog is
5672 # actually relevant - it gets put into the original message
5673 # which dpkg-source provides our stunt editor, and then
5675 runcmd @git, qw(checkout -q), $target, qw(debian/changelog);
5677 quiltify_dpkg_commit "$patchname$index", $author, $msg,
5678 "Date: $commitdate\n".
5679 "X-Dgit-Generated: $clogp->{Version} $cc\n";
5681 runcmd @git, qw(checkout -q), $cc, qw(debian/changelog);
5684 runcmd @git, qw(checkout -q master);
5687 sub build_maybe_quilt_fixup () {
5688 my ($format,$fopts) = get_source_format;
5689 return unless madformat_wantfixup $format;
5692 check_for_vendor_patches();
5694 if (quiltmode_splitbrain) {
5695 fail <<END unless access_cfg_tagformats_can_splitbrain;
5696 quilt mode $quilt_mode requires split view so server needs to support
5697 both "new" and "maint" tag formats, but config says it doesn't.
5701 my $clogp = parsechangelog();
5702 my $headref = git_rev_parse('HEAD');
5703 my $symref = git_get_symref();
5705 if ($quilt_mode eq 'linear'
5706 && !$fopts->{'single-debian-patch'}
5707 && branch_is_gdr($headref)) {
5708 # This is much faster. It also makes patches that gdr
5709 # likes better for future updates without laundering.
5711 # However, it can fail in some casses where we would
5712 # succeed: if there are existing patches, which correspond
5713 # to a prefix of the branch, but are not in gbp/gdr
5714 # format, gdr will fail (exiting status 7), but we might
5715 # be able to figure out where to start linearising. That
5716 # will be slower so hopefully there's not much to do.
5717 my @cmd = (@git_debrebase,
5718 qw(--noop-ok -funclean-mixed -funclean-ordering
5719 make-patches --quiet-would-amend));
5720 # We tolerate soe snags that gdr wouldn't, by default.
5726 and not ($? == 7*256 or
5727 $? == -1 && $!==ENOENT);
5731 $headref = git_rev_parse('HEAD');
5735 changedir $playground;
5737 my $upstreamversion = upstreamversion $version;
5739 if ($fopts->{'single-debian-patch'}) {
5740 quilt_fixup_singlepatch($clogp, $headref, $upstreamversion);
5742 quilt_fixup_multipatch($clogp, $headref, $upstreamversion);
5746 runcmd_ordryrun_local
5747 @git, qw(pull --ff-only -q), "$playground/work", qw(master);
5750 sub unpack_playtree_mkwork ($) {
5753 mkdir "work" or confess $!;
5755 mktree_in_ud_here();
5756 runcmd @git, qw(reset -q --hard), $headref;
5759 sub unpack_playtree_linkorigs ($$) {
5760 my ($upstreamversion, $fn) = @_;
5761 # calls $fn->($leafname);
5763 my $bpd_abs = bpd_abs();
5764 opendir QFD, $bpd_abs or fail "buildproductsdir: $bpd_abs: $!";
5765 while ($!=0, defined(my $b = readdir QFD)) {
5766 my $f = bpd_abs()."/".$b;
5768 local ($debuglevel) = $debuglevel-1;
5769 printdebug "QF linkorigs $b, $f ?\n";
5771 next unless is_orig_file_of_vsn $b, $upstreamversion;
5772 printdebug "QF linkorigs $b, $f Y\n";
5773 link_ltarget $f, $b or die "$b $!";
5776 die "$buildproductsdir: $!" if $!;
5780 sub quilt_fixup_delete_pc () {
5781 runcmd @git, qw(rm -rqf .pc);
5782 commit_admin +(__ <<END).<<ENDU
5783 Commit removal of .pc (quilt series tracking data)
5786 [dgit ($our_version) upgrade quilt-remove-pc]
5790 sub quilt_fixup_singlepatch ($$$) {
5791 my ($clogp, $headref, $upstreamversion) = @_;
5793 progress __ "starting quiltify (single-debian-patch)";
5795 # dpkg-source --commit generates new patches even if
5796 # single-debian-patch is in debian/source/options. In order to
5797 # get it to generate debian/patches/debian-changes, it is
5798 # necessary to build the source package.
5800 unpack_playtree_linkorigs($upstreamversion, sub { });
5801 unpack_playtree_mkwork($headref);
5803 rmtree("debian/patches");
5805 runcmd @dpkgsource, qw(-b .);
5807 runcmd @dpkgsource, qw(-x), (srcfn $version, ".dsc");
5808 rename srcfn("$upstreamversion", "/debian/patches"),
5809 "work/debian/patches"
5811 or confess "install d/patches: $!";
5814 commit_quilty_patch();
5817 sub quilt_make_fake_dsc ($) {
5818 my ($upstreamversion) = @_;
5820 my $fakeversion="$upstreamversion-~~DGITFAKE";
5822 my $fakedsc=new IO::File 'fake.dsc', '>' or confess $!;
5823 print $fakedsc <<END or confess $!;
5826 Version: $fakeversion
5830 my $dscaddfile=sub {
5833 my $md = new Digest::MD5;
5835 my $fh = new IO::File $b, '<' or die "$b $!";
5836 stat $fh or confess $!;
5840 print $fakedsc " ".$md->hexdigest." $size $b\n" or confess $!;
5843 unpack_playtree_linkorigs($upstreamversion, $dscaddfile);
5845 my @files=qw(debian/source/format debian/rules
5846 debian/control debian/changelog);
5847 foreach my $maybe (qw(debian/patches debian/source/options
5848 debian/tests/control)) {
5849 next unless stat_exists "$maindir/$maybe";
5850 push @files, $maybe;
5853 my $debtar= srcfn $fakeversion,'.debian.tar.gz';
5854 runcmd qw(env GZIP=-1n tar -zcf), "./$debtar", qw(-C), $maindir, @files;
5856 $dscaddfile->($debtar);
5857 close $fakedsc or confess $!;
5860 sub quilt_fakedsc2unapplied ($$) {
5861 my ($headref, $upstreamversion) = @_;
5862 # must be run in the playground
5863 # quilt_make_fake_dsc must have been called
5866 'exec dpkg-source --no-check --skip-patches -x fake.dsc >/dev/null';
5868 my $fakexdir= $package.'-'.(stripepoch $upstreamversion);
5869 rename $fakexdir, "fake" or die "$fakexdir $!";
5873 remove_stray_gits(__ "source package");
5874 mktree_in_ud_here();
5878 rmtree 'debian'; # git checkout commitish paths does not delete!
5879 runcmd @git, qw(checkout -f), $headref, qw(-- debian);
5880 my $unapplied=git_add_write_tree();
5881 printdebug "fake orig tree object $unapplied\n";
5885 sub quilt_check_splitbrain_cache ($$) {
5886 my ($headref, $upstreamversion) = @_;
5887 # Called only if we are in (potentially) split brain mode.
5888 # Called in playground.
5889 # Computes the cache key and looks in the cache.
5890 # Returns ($dgit_view_commitid, $cachekey) or (undef, $cachekey)
5892 my $splitbrain_cachekey;
5895 "dgit: split brain (separate dgit view) may be needed (--quilt=%s).",
5897 # we look in the reflog of dgit-intern/quilt-cache
5898 # we look for an entry whose message is the key for the cache lookup
5899 my @cachekey = (qw(dgit), $our_version);
5900 push @cachekey, $upstreamversion;
5901 push @cachekey, $quilt_mode;
5902 push @cachekey, $headref;
5904 push @cachekey, hashfile('fake.dsc');
5906 my $srcshash = Digest::SHA->new(256);
5907 my %sfs = ( %INC, '$0(dgit)' => $0 );
5908 foreach my $sfk (sort keys %sfs) {
5909 next unless $sfk =~ m/^\$0\b/ || $sfk =~ m{^Debian/Dgit\b};
5910 $srcshash->add($sfk," ");
5911 $srcshash->add(hashfile($sfs{$sfk}));
5912 $srcshash->add("\n");
5914 push @cachekey, $srcshash->hexdigest();
5915 $splitbrain_cachekey = "@cachekey";
5917 printdebug "splitbrain cachekey $splitbrain_cachekey\n";
5919 my $cachehit = reflog_cache_lookup
5920 "refs/$splitbraincache", $splitbrain_cachekey;
5923 unpack_playtree_mkwork($headref);
5924 my $saved = maybe_split_brain_save $headref, $cachehit, "cache-hit";
5925 if ($cachehit ne $headref) {
5926 progress f_ "dgit view: found cached (%s)", $saved;
5927 runcmd @git, qw(checkout -q -b dgit-view), $cachehit;
5929 return ($cachehit, $splitbrain_cachekey);
5931 progress __ "dgit view: found cached, no changes required";
5932 return ($headref, $splitbrain_cachekey);
5935 printdebug "splitbrain cache miss\n";
5936 return (undef, $splitbrain_cachekey);
5939 sub quilt_fixup_multipatch ($$$) {
5940 my ($clogp, $headref, $upstreamversion) = @_;
5942 progress f_ "examining quilt state (multiple patches, %s mode)",
5946 # - honour any existing .pc in case it has any strangeness
5947 # - determine the git commit corresponding to the tip of
5948 # the patch stack (if there is one)
5949 # - if there is such a git commit, convert each subsequent
5950 # git commit into a quilt patch with dpkg-source --commit
5951 # - otherwise convert all the differences in the tree into
5952 # a single git commit
5956 # Our git tree doesn't necessarily contain .pc. (Some versions of
5957 # dgit would include the .pc in the git tree.) If there isn't
5958 # one, we need to generate one by unpacking the patches that we
5961 # We first look for a .pc in the git tree. If there is one, we
5962 # will use it. (This is not the normal case.)
5964 # Otherwise need to regenerate .pc so that dpkg-source --commit
5965 # can work. We do this as follows:
5966 # 1. Collect all relevant .orig from parent directory
5967 # 2. Generate a debian.tar.gz out of
5968 # debian/{patches,rules,source/format,source/options}
5969 # 3. Generate a fake .dsc containing just these fields:
5970 # Format Source Version Files
5971 # 4. Extract the fake .dsc
5972 # Now the fake .dsc has a .pc directory.
5973 # (In fact we do this in every case, because in future we will
5974 # want to search for a good base commit for generating patches.)
5976 # Then we can actually do the dpkg-source --commit
5977 # 1. Make a new working tree with the same object
5978 # store as our main tree and check out the main
5980 # 2. Copy .pc from the fake's extraction, if necessary
5981 # 3. Run dpkg-source --commit
5982 # 4. If the result has changes to debian/, then
5983 # - git add them them
5984 # - git add .pc if we had a .pc in-tree
5986 # 5. If we had a .pc in-tree, delete it, and git commit
5987 # 6. Back in the main tree, fast forward to the new HEAD
5989 # Another situation we may have to cope with is gbp-style
5990 # patches-unapplied trees.
5992 # We would want to detect these, so we know to escape into
5993 # quilt_fixup_gbp. However, this is in general not possible.
5994 # Consider a package with a one patch which the dgit user reverts
5995 # (with git revert or the moral equivalent).
5997 # That is indistinguishable in contents from a patches-unapplied
5998 # tree. And looking at the history to distinguish them is not
5999 # useful because the user might have made a confusing-looking git
6000 # history structure (which ought to produce an error if dgit can't
6001 # cope, not a silent reintroduction of an unwanted patch).
6003 # So gbp users will have to pass an option. But we can usually
6004 # detect their failure to do so: if the tree is not a clean
6005 # patches-applied tree, quilt linearisation fails, but the tree
6006 # _is_ a clean patches-unapplied tree, we can suggest that maybe
6007 # they want --quilt=unapplied.
6009 # To help detect this, when we are extracting the fake dsc, we
6010 # first extract it with --skip-patches, and then apply the patches
6011 # afterwards with dpkg-source --before-build. That lets us save a
6012 # tree object corresponding to .origs.
6014 my $splitbrain_cachekey;
6016 quilt_make_fake_dsc($upstreamversion);
6018 if (quiltmode_splitbrain()) {
6020 ($cachehit, $splitbrain_cachekey) =
6021 quilt_check_splitbrain_cache($headref, $upstreamversion);
6022 return if $cachehit;
6024 my $unapplied=quilt_fakedsc2unapplied($headref, $upstreamversion);
6028 my @bbcmd = (qw(sh -ec), 'exec dpkg-source --before-build . >/dev/null');
6030 if (system @bbcmd) {
6031 failedcmd @bbcmd if $? < 0;
6033 failed to apply your git tree's patch stack (from debian/patches/) to
6034 the corresponding upstream tarball(s). Your source tree and .orig
6035 are probably too inconsistent. dgit can only fix up certain kinds of
6036 anomaly (depending on the quilt mode). Please see --quilt= in dgit(1).
6042 unpack_playtree_mkwork($headref);
6045 if (stat_exists ".pc") {
6047 progress __ "Tree already contains .pc - will use it then delete it.";
6050 rename '../fake/.pc','.pc' or confess $!;
6053 changedir '../fake';
6055 my $oldtiptree=git_add_write_tree();
6056 printdebug "fake o+d/p tree object $unapplied\n";
6057 changedir '../work';
6060 # We calculate some guesswork now about what kind of tree this might
6061 # be. This is mostly for error reporting.
6067 # O = orig, without patches applied
6068 # A = "applied", ie orig with H's debian/patches applied
6069 O2H => quiltify_trees_differ($unapplied,$headref, 1,
6070 \%editedignores, \@unrepres),
6071 H2A => quiltify_trees_differ($headref, $oldtiptree,1),
6072 O2A => quiltify_trees_differ($unapplied,$oldtiptree,1),
6076 foreach my $b (qw(01 02)) {
6077 foreach my $v (qw(O2H O2A H2A)) {
6078 push @dl, ($diffbits->{$v} & $b) ? '##' : '==';
6081 printdebug "differences \@dl @dl.\n";
6084 "%s: base trees orig=%.20s o+d/p=%.20s",
6085 $us, $unapplied, $oldtiptree;
6087 "%s: quilt differences: src: %s orig %s gitignores: %s orig %s\n".
6088 "%s: quilt differences: HEAD %s o+d/p HEAD %s o+d/p",
6089 $us, $dl[0], $dl[1], $dl[3], $dl[4],
6090 $us, $dl[2], $dl[5];
6093 print STDERR f_ "dgit: cannot represent change: %s: %s\n",
6096 forceable_fail [qw(unrepresentable)], __ <<END;
6097 HEAD has changes to .orig[s] which are not representable by `3.0 (quilt)'
6102 if (!($diffbits->{O2H} & $diffbits->{O2A})) {
6103 push @failsuggestion, [ 'unapplied', __
6104 "This might be a patches-unapplied branch." ];
6105 } elsif (!($diffbits->{H2A} & $diffbits->{O2A})) {
6106 push @failsuggestion, [ 'applied', __
6107 "This might be a patches-applied branch." ];
6109 push @failsuggestion, [ 'quilt-mode', __
6110 "Maybe you need one of --[quilt=]gbp --[quilt=]dpm --quilt=unapplied ?" ];
6112 push @failsuggestion, [ 'gitattrs', __
6113 "Warning: Tree has .gitattributes. See GITATTRIBUTES in dgit(7)." ]
6114 if stat_exists '.gitattributes';
6116 push @failsuggestion, [ 'origs', __
6117 "Maybe orig tarball(s) are not identical to git representation?" ];
6119 if (quiltmode_splitbrain()) {
6120 quiltify_splitbrain($clogp, $unapplied, $headref, $oldtiptree,
6121 $diffbits, \%editedignores,
6122 $splitbrain_cachekey);
6126 progress f_ "starting quiltify (multiple patches, %s mode)", $quilt_mode;
6127 quiltify($clogp,$headref,$oldtiptree,\@failsuggestion);
6129 if (!open P, '>>', ".pc/applied-patches") {
6130 $!==&ENOENT or confess $!;
6135 commit_quilty_patch();
6137 if ($mustdeletepc) {
6138 quilt_fixup_delete_pc();
6142 sub quilt_fixup_editor () {
6143 my $descfn = $ENV{$fakeeditorenv};
6144 my $editing = $ARGV[$#ARGV];
6145 open I1, '<', $descfn or confess "$descfn: $!";
6146 open I2, '<', $editing or confess "$editing: $!";
6147 unlink $editing or confess "$editing: $!";
6148 open O, '>', $editing or confess "$editing: $!";
6149 while (<I1>) { print O or confess $!; } I1->error and confess $!;
6152 $copying ||= m/^\-\-\- /;
6153 next unless $copying;
6154 print O or confess $!;
6156 I2->error and confess $!;
6161 sub maybe_apply_patches_dirtily () {
6162 return unless $quilt_mode =~ m/gbp|unapplied/;
6163 print STDERR __ <<END or confess $!;
6165 dgit: Building, or cleaning with rules target, in patches-unapplied tree.
6166 dgit: Have to apply the patches - making the tree dirty.
6167 dgit: (Consider specifying --clean=git and (or) using dgit sbuild.)
6170 $patches_applied_dirtily = 01;
6171 $patches_applied_dirtily |= 02 unless stat_exists '.pc';
6172 runcmd qw(dpkg-source --before-build .);
6175 sub maybe_unapply_patches_again () {
6176 progress __ "dgit: Unapplying patches again to tidy up the tree."
6177 if $patches_applied_dirtily;
6178 runcmd qw(dpkg-source --after-build .)
6179 if $patches_applied_dirtily & 01;
6181 if $patches_applied_dirtily & 02;
6182 $patches_applied_dirtily = 0;
6185 #----- other building -----
6187 our $clean_using_builder;
6188 # ^ tree is to be cleaned by dpkg-source's builtin idea that it should
6189 # clean the tree before building (perhaps invoked indirectly by
6190 # whatever we are using to run the build), rather than separately
6191 # and explicitly by us.
6194 return if $clean_using_builder;
6195 if ($cleanmode eq 'dpkg-source') {
6196 maybe_apply_patches_dirtily();
6197 runcmd_ordryrun_local @dpkgbuildpackage, qw(-T clean);
6198 } elsif ($cleanmode eq 'dpkg-source-d') {
6199 maybe_apply_patches_dirtily();
6200 runcmd_ordryrun_local @dpkgbuildpackage, qw(-d -T clean);
6201 } elsif ($cleanmode eq 'git') {
6202 runcmd_ordryrun_local @git, qw(clean -xdf);
6203 } elsif ($cleanmode eq 'git-ff') {
6204 runcmd_ordryrun_local @git, qw(clean -xdff);
6205 } elsif ($cleanmode eq 'check') {
6206 my $leftovers = cmdoutput @git, qw(clean -xdn);
6207 if (length $leftovers) {
6208 print STDERR $leftovers, "\n" or confess $!;
6210 "tree contains uncommitted files and --clean=check specified";
6212 } elsif ($cleanmode eq 'none') {
6219 badusage __ "clean takes no additional arguments" if @ARGV;
6222 maybe_unapply_patches_again();
6225 # return values from massage_dbp_args are one or both of these flags
6226 sub WANTSRC_SOURCE () { 01; } # caller should build source (separately)
6227 sub WANTSRC_BUILDER () { 02; } # caller should run dpkg-buildpackage
6229 sub build_or_push_prep_early () {
6230 our $build_or_push_prep_early_done //= 0;
6231 return if $build_or_push_prep_early_done++;
6232 badusage f_ "-p is not allowed with dgit %s", $subcommand
6233 if defined $package;
6234 my $clogp = parsechangelog();
6235 $isuite = getfield $clogp, 'Distribution';
6236 $package = getfield $clogp, 'Source';
6237 $version = getfield $clogp, 'Version';
6238 $dscfn = dscfn($version);
6241 sub build_prep_early () {
6242 build_or_push_prep_early();
6247 sub build_prep ($) {
6250 # clean the tree if we're trying to include dirty changes in the
6251 # source package, or we are running the builder in $maindir
6252 clean_tree() if $includedirty || ($wantsrc & WANTSRC_BUILDER);
6253 build_maybe_quilt_fixup();
6255 my $pat = changespat $version;
6256 foreach my $f (glob "$buildproductsdir/$pat") {
6259 fail f_ "remove old changes file %s: %s", $f, $!;
6261 progress f_ "would remove %s", $f;
6267 sub changesopts_initial () {
6268 my @opts =@changesopts[1..$#changesopts];
6271 sub changesopts_version () {
6272 if (!defined $changes_since_version) {
6275 @vsns = archive_query('archive_query');
6276 my @quirk = access_quirk();
6277 if ($quirk[0] eq 'backports') {
6278 local $isuite = $quirk[2];
6280 canonicalise_suite();
6281 push @vsns, archive_query('archive_query');
6287 "archive query failed (queried because --since-version not specified)";
6290 @vsns = map { $_->[0] } @vsns;
6291 @vsns = sort { -version_compare($a, $b) } @vsns;
6292 $changes_since_version = $vsns[0];
6293 progress f_ "changelog will contain changes since %s", $vsns[0];
6295 $changes_since_version = '_';
6296 progress __ "package seems new, not specifying -v<version>";
6299 if ($changes_since_version ne '_') {
6300 return ("-v$changes_since_version");
6306 sub changesopts () {
6307 return (changesopts_initial(), changesopts_version());
6310 sub massage_dbp_args ($;$) {
6311 my ($cmd,$xargs) = @_;
6312 # Since we split the source build out so we can do strange things
6313 # to it, massage the arguments to dpkg-buildpackage so that the
6314 # main build doessn't build source (or add an argument to stop it
6315 # building source by default).
6316 debugcmd '#massaging#', @$cmd if $debuglevel>1;
6317 # -nc has the side effect of specifying -b if nothing else specified
6318 # and some combinations of -S, -b, et al, are errors, rather than
6319 # later simply overriding earlie. So we need to:
6320 # - search the command line for these options
6321 # - pick the last one
6322 # - perhaps add our own as a default
6323 # - perhaps adjust it to the corresponding non-source-building version
6325 foreach my $l ($cmd, $xargs) {
6327 @$l = grep { !(m/^-[SgGFABb]$|^--build=/s and $dmode=$_) } @$l;
6330 #print STDERR "MASS1 ",Dumper($cmd, $xargs, $dmode);
6331 my $r = WANTSRC_BUILDER;
6332 printdebug "massage split $dmode.\n";
6333 if ($dmode =~ s/^--build=//) {
6335 my @d = split /,/, $dmode;
6336 $r |= WANTSRC_SOURCE if grep { s/^full$/binary/ } @d;
6337 $r |= WANTSRC_SOURCE if grep { s/^source$// } @d;
6338 $r |= WANTSRC_BUILDER if grep { m/./ } @d;
6339 fail __ "Wanted to build nothing!" unless $r;
6340 $dmode = '--build='. join ',', grep m/./, @d;
6343 $dmode =~ m/[S]/ ? WANTSRC_SOURCE :
6344 $dmode =~ y/gGF/ABb/ ? WANTSRC_SOURCE | WANTSRC_BUILDER :
6345 $dmode =~ m/[ABb]/ ? WANTSRC_BUILDER :
6348 printdebug "massage done $r $dmode.\n";
6350 #print STDERR "MASS2 ",Dumper($cmd, $xargs, $r);
6356 my $wasdir = must_getcwd();
6357 changedir $buildproductsdir;
6362 # this sub must run with CWD=$buildproductsdir (eg in in_bpd)
6363 sub postbuild_mergechanges ($) {
6364 my ($msg_if_onlyone) = @_;
6365 # If there is only one .changes file, fail with $msg_if_onlyone,
6366 # or if that is undef, be a no-op.
6367 # Returns the changes file to report to the user.
6368 my $pat = changespat $version;
6369 my @changesfiles = grep { !m/_multi\.changes/ } glob $pat;
6370 @changesfiles = sort {
6371 ($b =~ m/_source\.changes$/ <=> $a =~ m/_source\.changes$/)
6375 if (@changesfiles==1) {
6376 fail +(f_ <<END, "@changesfiles").$msg_if_onlyone
6377 only one changes file from build (%s)
6379 if defined $msg_if_onlyone;
6380 $result = $changesfiles[0];
6381 } elsif (@changesfiles==2) {
6382 my $binchanges = parsecontrol($changesfiles[1], "binary changes file");
6383 foreach my $l (split /\n/, getfield $binchanges, 'Files') {
6384 fail f_ "%s found in binaries changes file %s", $l, $binchanges
6387 runcmd_ordryrun_local @mergechanges, @changesfiles;
6388 my $multichanges = changespat $version,'multi';
6390 stat_exists $multichanges or fail f_
6391 "%s unexpectedly not created by build", $multichanges;
6392 foreach my $cf (glob $pat) {
6393 next if $cf eq $multichanges;
6394 rename "$cf", "$cf.inmulti" or fail f_
6395 "install new changes %s\{,.inmulti}: %s", $cf, $!;
6398 $result = $multichanges;
6400 fail f_ "wrong number of different changes files (%s)",
6403 printdone f_ "build successful, results in %s\n", $result
6407 sub midbuild_checkchanges () {
6408 my $pat = changespat $version;
6409 return if $rmchanges;
6410 my @unwanted = map { s#.*/##; $_; } glob "$bpd_glob/$pat";
6412 $_ ne changespat $version,'source' and
6413 $_ ne changespat $version,'multi'
6415 fail +(f_ <<END, $pat, "@unwanted")
6416 changes files other than source matching %s already present; building would result in ambiguity about the intended results.
6417 Suggest you delete %s.
6422 sub midbuild_checkchanges_vanilla ($) {
6424 midbuild_checkchanges() if $wantsrc == (WANTSRC_SOURCE|WANTSRC_BUILDER);
6427 sub postbuild_mergechanges_vanilla ($) {
6429 if ($wantsrc == (WANTSRC_SOURCE|WANTSRC_BUILDER)) {
6431 postbuild_mergechanges(undef);
6434 printdone __ "build successful\n";
6440 $buildproductsdir eq '..' or print STDERR +(f_ <<END, $us, $us);
6441 %s: warning: build-products-dir set, but not supported by dpkg-buildpackage
6442 %s: warning: build-products-dir will be ignored; files will go to ..
6444 $buildproductsdir = '..';
6445 my @dbp = (@dpkgbuildpackage, qw(-us -uc), changesopts_initial(), @ARGV);
6446 my $wantsrc = massage_dbp_args \@dbp;
6447 build_prep($wantsrc);
6448 if ($wantsrc & WANTSRC_SOURCE) {
6450 midbuild_checkchanges_vanilla $wantsrc;
6452 if ($wantsrc & WANTSRC_BUILDER) {
6453 push @dbp, changesopts_version();
6454 maybe_apply_patches_dirtily();
6455 runcmd_ordryrun_local @dbp;
6457 maybe_unapply_patches_again();
6458 postbuild_mergechanges_vanilla $wantsrc;
6462 $quilt_mode //= 'gbp';
6468 # gbp can make .origs out of thin air. In my tests it does this
6469 # even for a 1.0 format package, with no origs present. So I
6470 # guess it keys off just the version number. We don't know
6471 # exactly what .origs ought to exist, but let's assume that we
6472 # should run gbp if: the version has an upstream part and the main
6474 my $upstreamversion = upstreamversion $version;
6475 my $origfnpat = srcfn $upstreamversion, '.orig.tar.*';
6476 my $gbp_make_orig = $version =~ m/-/ && !(() = glob "$bpd_glob/$origfnpat");
6478 if ($gbp_make_orig) {
6480 $cleanmode = 'none'; # don't do it again
6483 my @dbp = @dpkgbuildpackage;
6485 my $wantsrc = massage_dbp_args \@dbp, \@ARGV;
6487 if (!length $gbp_build[0]) {
6488 if (length executable_on_path('git-buildpackage')) {
6489 $gbp_build[0] = qw(git-buildpackage);
6491 $gbp_build[0] = 'gbp buildpackage';
6494 my @cmd = opts_opt_multi_cmd [], @gbp_build;
6496 push @cmd, (qw(-us -uc --git-no-sign-tags),
6497 "--git-builder=".(shellquote @dbp));
6499 if ($gbp_make_orig) {
6500 my $priv = dgit_privdir();
6501 my $ok = "$priv/origs-gen-ok";
6502 unlink $ok or $!==&ENOENT or confess $!;
6503 my @origs_cmd = @cmd;
6504 push @origs_cmd, qw(--git-cleaner=true);
6505 push @origs_cmd, "--git-prebuild=".
6506 "touch ".(shellquote $ok)." ".(shellquote "$priv/no-such-dir/ok");
6507 push @origs_cmd, @ARGV;
6509 debugcmd @origs_cmd;
6511 do { local $!; stat_exists $ok; }
6512 or failedcmd @origs_cmd;
6514 dryrun_report @origs_cmd;
6518 build_prep($wantsrc);
6519 if ($wantsrc & WANTSRC_SOURCE) {
6521 midbuild_checkchanges_vanilla $wantsrc;
6523 if (!$clean_using_builder) {
6524 push @cmd, '--git-cleaner=true';
6527 maybe_unapply_patches_again();
6528 if ($wantsrc & WANTSRC_BUILDER) {
6529 push @cmd, changesopts();
6530 runcmd_ordryrun_local @cmd, @ARGV;
6532 postbuild_mergechanges_vanilla $wantsrc;
6534 sub cmd_git_build { cmd_gbp_build(); } # compatibility with <= 1.0
6536 sub building_source_in_playtree {
6537 # If $includedirty, we have to build the source package from the
6538 # working tree, not a playtree, so that uncommitted changes are
6539 # included (copying or hardlinking them into the playtree could
6542 # Note that if we are building a source package in split brain
6543 # mode we do not support including uncommitted changes, because
6544 # that makes quilt fixup too hard. I.e. ($split_brain && (dgit is
6545 # building a source package)) => !$includedirty
6546 return !$includedirty;
6550 $sourcechanges = changespat $version,'source';
6552 unlink "$buildproductsdir/$sourcechanges" or $!==ENOENT
6553 or fail f_ "remove %s: %s", $sourcechanges, $!;
6555 my @cmd = (@dpkgsource, qw(-b --));
6557 if (building_source_in_playtree()) {
6559 my $headref = git_rev_parse('HEAD');
6560 # If we are in split brain, there is already a playtree with
6561 # the thing we should package into a .dsc (thanks to quilt
6562 # fixup). If not, make a playtree
6563 prep_ud() unless $split_brain;
6564 changedir $playground;
6565 unless ($split_brain) {
6566 my $upstreamversion = upstreamversion $version;
6567 unpack_playtree_linkorigs($upstreamversion, sub { });
6568 unpack_playtree_mkwork($headref);
6572 $leafdir = basename $maindir;
6574 if ($buildproductsdir ne '..') {
6575 # Well, we are going to run dpkg-source -b which consumes
6576 # origs from .. and generates output there. To make this
6577 # work when the bpd is not .. , we would have to (i) link
6578 # origs from bpd to .. , (ii) check for files that
6579 # dpkg-source -b would/might overwrite, and afterwards
6580 # (iii) move all the outputs back to the bpd (iv) except
6581 # for the origs which should be deleted from .. if they
6582 # weren't there beforehand. And if there is an error and
6583 # we don't run to completion we would necessarily leave a
6584 # mess. This is too much. The real way to fix this
6585 # is for dpkg-source to have bpd support.
6586 confess unless $includedirty;
6588 "--include-dirty not supported with --build-products-dir, sorry";
6593 runcmd_ordryrun_local @cmd, $leafdir;
6596 runcmd_ordryrun_local qw(sh -ec),
6597 'exec >../$1; shift; exec "$@"','x', $sourcechanges,
6598 @dpkggenchanges, qw(-S), changesopts();
6601 printdebug "moving $dscfn, $sourcechanges, etc. to ".bpd_abs()."\n";
6602 $dsc = parsecontrol($dscfn, "source package");
6606 printdebug " renaming ($why) $l\n";
6607 rename_link_xf 0, "$l", bpd_abs()."/$l"
6608 or fail f_ "put in place new built file (%s): %s", $l, $@;
6610 foreach my $l (split /\n/, getfield $dsc, 'Files') {
6611 $l =~ m/\S+$/ or next;
6614 $mv->('dsc', $dscfn);
6615 $mv->('changes', $sourcechanges);
6620 sub cmd_build_source {
6621 badusage __ "build-source takes no additional arguments" if @ARGV;
6622 build_prep(WANTSRC_SOURCE);
6624 maybe_unapply_patches_again();
6625 printdone f_ "source built, results in %s and %s",
6626 $dscfn, $sourcechanges;
6629 sub cmd_push_source {
6632 "dgit push-source: --include-dirty/--ignore-dirty does not make".
6633 "sense with push-source!"
6635 build_maybe_quilt_fixup();
6637 my $changes = parsecontrol("$buildproductsdir/$changesfile",
6638 __ "source changes file");
6639 unless (test_source_only_changes($changes)) {
6640 fail __ "user-specified changes file is not source-only";
6643 # Building a source package is very fast, so just do it
6645 confess "er, patches are applied dirtily but shouldn't be.."
6646 if $patches_applied_dirtily;
6647 $changesfile = $sourcechanges;
6652 sub binary_builder {
6653 my ($bbuilder, $pbmc_msg, @args) = @_;
6654 build_prep(WANTSRC_SOURCE);
6656 midbuild_checkchanges();
6659 stat_exists $dscfn or fail f_
6660 "%s (in build products dir): %s", $dscfn, $!;
6661 stat_exists $sourcechanges or fail f_
6662 "%s (in build products dir): %s", $sourcechanges, $!;
6664 runcmd_ordryrun_local @$bbuilder, @args;
6666 maybe_unapply_patches_again();
6668 postbuild_mergechanges($pbmc_msg);
6674 binary_builder(\@sbuild, (__ <<END), qw(-d), $isuite, @ARGV, $dscfn);
6675 perhaps you need to pass -A ? (sbuild's default is to build only
6676 arch-specific binaries; dgit 1.4 used to override that.)
6681 my ($pbuilder) = @_;
6683 # @ARGV is allowed to contain only things that should be passed to
6684 # pbuilder under debbuildopts; just massage those
6685 my $wantsrc = massage_dbp_args \@ARGV;
6687 "you asked for a builder but your debbuildopts didn't ask for".
6688 " any binaries -- is this really what you meant?"
6689 unless $wantsrc & WANTSRC_BUILDER;
6691 "we must build a .dsc to pass to the builder but your debbuiltopts".
6692 " forbids the building of a source package; cannot continue"
6693 unless $wantsrc & WANTSRC_SOURCE;
6694 # We do not want to include the verb "build" in @pbuilder because
6695 # the user can customise @pbuilder and they shouldn't be required
6696 # to include "build" in their customised value. However, if the
6697 # user passes any additional args to pbuilder using the dgit
6698 # option --pbuilder:foo, such args need to come after the "build"
6699 # verb. opts_opt_multi_cmd does all of that.
6700 binary_builder([opts_opt_multi_cmd ["build"], @$pbuilder], undef,
6701 qw(--debbuildopts), "@ARGV", qw(--distribution), $isuite,
6706 pbuilder(\@pbuilder);
6709 sub cmd_cowbuilder {
6710 pbuilder(\@cowbuilder);
6713 sub cmd_quilt_fixup {
6714 badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
6717 build_maybe_quilt_fixup();
6720 sub cmd_print_unapplied_treeish {
6721 badusage __ "incorrect arguments to dgit print-unapplied-treeish"
6723 my $headref = git_rev_parse('HEAD');
6724 my $clogp = commit_getclogp $headref;
6725 $package = getfield $clogp, 'Source';
6726 $version = getfield $clogp, 'Version';
6727 $isuite = getfield $clogp, 'Distribution';
6728 $csuite = $isuite; # we want this to be offline!
6732 changedir $playground;
6733 my $uv = upstreamversion $version;
6734 quilt_make_fake_dsc($uv);
6735 my $u = quilt_fakedsc2unapplied($headref, $uv);
6736 print $u, "\n" or confess $!;
6739 sub import_dsc_result {
6740 my ($dstref, $newhash, $what_log, $what_msg) = @_;
6741 my @cmd = (git_update_ref_cmd $what_log, $dstref, $newhash);
6743 check_gitattrs($newhash, __ "source tree");
6745 progress f_ "dgit: import-dsc: %s", $what_msg;
6748 sub cmd_import_dsc {
6752 last unless $ARGV[0] =~ m/^-/;
6755 if (m/^--require-valid-signature$/) {
6758 badusage f_ "unknown dgit import-dsc sub-option \`%s'", $_;
6762 badusage __ "usage: dgit import-dsc .../PATH/TO/.DSC BRANCH"
6764 my ($dscfn, $dstbranch) = @ARGV;
6766 badusage __ "dry run makes no sense with import-dsc"
6769 my $force = $dstbranch =~ s/^\+// ? +1 :
6770 $dstbranch =~ s/^\.\.// ? -1 :
6772 my $info = $force ? " $&" : '';
6773 $info = "$dscfn$info";
6775 my $specbranch = $dstbranch;
6776 $dstbranch = "refs/heads/$dstbranch" unless $dstbranch =~ m#^refs/#;
6777 $dstbranch = cmdoutput @git, qw(check-ref-format --normalize), $dstbranch;
6779 my @symcmd = (@git, qw(symbolic-ref -q HEAD));
6780 my $chead = cmdoutput_errok @symcmd;
6781 defined $chead or $?==256 or failedcmd @symcmd;
6783 fail f_ "%s is checked out - will not update it", $dstbranch
6784 if defined $chead and $chead eq $dstbranch;
6786 my $oldhash = git_get_ref $dstbranch;
6788 open D, "<", $dscfn or fail f_ "open import .dsc (%s): %s", $dscfn, $!;
6789 $dscdata = do { local $/ = undef; <D>; };
6790 D->error and fail f_ "read %s: %s", $dscfn, $!;
6793 # we don't normally need this so import it here
6794 use Dpkg::Source::Package;
6795 my $dp = new Dpkg::Source::Package filename => $dscfn,
6796 require_valid_signature => $needsig;
6798 local $SIG{__WARN__} = sub {
6800 return unless $needsig;
6801 fail __ "import-dsc signature check failed";
6803 if (!$dp->is_signed()) {
6804 warn f_ "%s: warning: importing unsigned .dsc\n", $us;
6806 my $r = $dp->check_signature();
6807 confess "->check_signature => $r" if $needsig && $r;
6813 $package = getfield $dsc, 'Source';
6815 parse_dsc_field($dsc, __ "Dgit metadata in .dsc")
6816 unless forceing [qw(import-dsc-with-dgit-field)];
6817 parse_dsc_field_def_dsc_distro();
6819 $isuite = 'DGIT-IMPORT-DSC';
6820 $idistro //= $dsc_distro;
6824 if (defined $dsc_hash) {
6826 "dgit: import-dsc of .dsc with Dgit field, using git hash";
6827 resolve_dsc_field_commit undef, undef;
6829 if (defined $dsc_hash) {
6830 my @cmd = (qw(sh -ec),
6831 "echo $dsc_hash | git cat-file --batch-check");
6832 my $objgot = cmdoutput @cmd;
6833 if ($objgot =~ m#^\w+ missing\b#) {
6834 fail f_ <<END, $dsc_hash
6835 .dsc contains Dgit field referring to object %s
6836 Your git tree does not have that object. Try `git fetch' from a
6837 plausible server (browse.dgit.d.o? salsa?), and try the import-dsc again.
6840 if ($oldhash && !is_fast_fwd $oldhash, $dsc_hash) {
6842 progress __ "Not fast forward, forced update.";
6844 fail f_ "Not fast forward to %s", $dsc_hash;
6847 import_dsc_result $dstbranch, $dsc_hash,
6848 "dgit import-dsc (Dgit): $info",
6849 f_ "updated git ref %s", $dstbranch;
6853 fail f_ <<END, $dstbranch, $specbranch, $specbranch
6854 Branch %s already exists
6855 Specify ..%s for a pseudo-merge, binding in existing history
6856 Specify +%s to overwrite, discarding existing history
6858 if $oldhash && !$force;
6860 my @dfi = dsc_files_info();
6861 foreach my $fi (@dfi) {
6862 my $f = $fi->{Filename};
6863 my $here = "$buildproductsdir/$f";
6866 fail f_ "lstat %s works but stat gives %s !", $here, $!;
6868 fail f_ "stat %s: %s", $here, $! unless $! == ENOENT;
6870 if ($dscfn =~ m#^(?:\./+)?\.\./+#) {
6872 } elsif ($dscfn =~ m#^/#) {
6876 "cannot import %s which seems to be inside working tree!",
6879 $there =~ s#/+[^/]+$## or fail f_
6880 "import %s requires .../%s, but it does not exist",
6883 my $test = $there =~ m{^/} ? $there : "../$there";
6884 stat $test or fail f_
6885 "import %s requires %s, but: %s", $dscfn, $test, $!;
6886 symlink $there, $here or fail f_
6887 "symlink %s to %s: %s", $there, $here, $!;
6888 progress f_ "made symlink %s -> %s", $here, $there;
6889 # print STDERR Dumper($fi);
6891 my @mergeinputs = generate_commits_from_dsc();
6892 die unless @mergeinputs == 1;
6894 my $newhash = $mergeinputs[0]{Commit};
6899 "Import, forced update - synthetic orphan git history.";
6900 } elsif ($force < 0) {
6901 progress __ "Import, merging.";
6902 my $tree = cmdoutput @git, qw(rev-parse), "$newhash:";
6903 my $version = getfield $dsc, 'Version';
6904 my $clogp = commit_getclogp $newhash;
6905 my $authline = clogp_authline $clogp;
6906 $newhash = make_commit_text <<ENDU
6914 .(f_ <<END, $package, $version, $dstbranch);
6915 Merge %s (%s) import into %s
6918 die; # caught earlier
6922 import_dsc_result $dstbranch, $newhash,
6923 "dgit import-dsc: $info",
6924 f_ "results are in git ref %s", $dstbranch;
6927 sub pre_archive_api_query () {
6928 not_necessarily_a_tree();
6930 sub cmd_archive_api_query {
6931 badusage __ "need only 1 subpath argument" unless @ARGV==1;
6932 my ($subpath) = @ARGV;
6933 local $isuite = 'DGIT-API-QUERY-CMD';
6934 my @cmd = archive_api_query_cmd($subpath);
6937 exec @cmd or fail f_ "exec curl: %s\n", $!;
6940 sub repos_server_url () {
6941 $package = '_dgit-repos-server';
6942 local $access_forpush = 1;
6943 local $isuite = 'DGIT-REPOS-SERVER';
6944 my $url = access_giturl();
6947 sub pre_clone_dgit_repos_server () {
6948 not_necessarily_a_tree();
6950 sub cmd_clone_dgit_repos_server {
6951 badusage __ "need destination argument" unless @ARGV==1;
6952 my ($destdir) = @ARGV;
6953 my $url = repos_server_url();
6954 my @cmd = (@git, qw(clone), $url, $destdir);
6956 exec @cmd or fail f_ "exec git clone: %s\n", $!;
6959 sub pre_print_dgit_repos_server_source_url () {
6960 not_necessarily_a_tree();
6962 sub cmd_print_dgit_repos_server_source_url {
6964 "no arguments allowed to dgit print-dgit-repos-server-source-url"
6966 my $url = repos_server_url();
6967 print $url, "\n" or confess $!;
6970 sub pre_print_dpkg_source_ignores {
6971 not_necessarily_a_tree();
6973 sub cmd_print_dpkg_source_ignores {
6975 "no arguments allowed to dgit print-dpkg-source-ignores"
6977 print "@dpkg_source_ignores\n" or confess $!;
6980 sub cmd_setup_mergechangelogs {
6981 badusage __ "no arguments allowed to dgit setup-mergechangelogs"
6983 local $isuite = 'DGIT-SETUP-TREE';
6984 setup_mergechangelogs(1);
6987 sub cmd_setup_useremail {
6988 badusage __ "no arguments allowed to dgit setup-useremail" if @ARGV;
6989 local $isuite = 'DGIT-SETUP-TREE';
6993 sub cmd_setup_gitattributes {
6994 badusage __ "no arguments allowed to dgit setup-useremail" if @ARGV;
6995 local $isuite = 'DGIT-SETUP-TREE';
6999 sub cmd_setup_new_tree {
7000 badusage __ "no arguments allowed to dgit setup-tree" if @ARGV;
7001 local $isuite = 'DGIT-SETUP-TREE';
7005 #---------- argument parsing and main program ----------
7008 print "dgit version $our_version\n" or confess $!;
7012 our (%valopts_long, %valopts_short);
7013 our (%funcopts_long);
7015 our (@modeopt_cfgs);
7017 sub defvalopt ($$$$) {
7018 my ($long,$short,$val_re,$how) = @_;
7019 my $oi = { Long => $long, Short => $short, Re => $val_re, How => $how };
7020 $valopts_long{$long} = $oi;
7021 $valopts_short{$short} = $oi;
7022 # $how subref should:
7023 # do whatever assignemnt or thing it likes with $_[0]
7024 # if the option should not be passed on to remote, @rvalopts=()
7025 # or $how can be a scalar ref, meaning simply assign the value
7028 defvalopt '--since-version', '-v', '[^_]+|_', \$changes_since_version;
7029 defvalopt '--distro', '-d', '.+', \$idistro;
7030 defvalopt '', '-k', '.+', \$keyid;
7031 defvalopt '--existing-package','', '.*', \$existing_package;
7032 defvalopt '--build-products-dir','','.*', \$buildproductsdir;
7033 defvalopt '--clean', '', $cleanmode_re, \$cleanmode;
7034 defvalopt '--package', '-p', $package_re, \$package;
7035 defvalopt '--quilt', '', $quilt_modes_re, \$quilt_mode;
7037 defvalopt '', '-C', '.+', sub {
7038 ($changesfile) = (@_);
7039 if ($changesfile =~ s#^(.*)/##) {
7040 $buildproductsdir = $1;
7044 defvalopt '--initiator-tempdir','','.*', sub {
7045 ($initiator_tempdir) = (@_);
7046 $initiator_tempdir =~ m#^/# or
7047 badusage __ "--initiator-tempdir must be used specify an".
7048 " absolute, not relative, directory."
7051 sub defoptmodes ($@) {
7052 my ($varref, $cfgkey, $default, %optmap) = @_;
7054 while (my ($opt,$val) = each %optmap) {
7055 $funcopts_long{$opt} = sub { $$varref = $val; };
7056 $permit{$val} = $val;
7058 push @modeopt_cfgs, {
7061 Default => $default,
7066 defoptmodes \$dodep14tag, qw( dep14tag want
7069 --always-dep14tag always );
7074 if (defined $ENV{'DGIT_SSH'}) {
7075 @ssh = string_to_ssh $ENV{'DGIT_SSH'};
7076 } elsif (defined $ENV{'GIT_SSH'}) {
7077 @ssh = ($ENV{'GIT_SSH'});
7085 if (!defined $val) {
7086 badusage f_ "%s needs a value", $what unless @ARGV;
7088 push @rvalopts, $val;
7090 badusage f_ "bad value \`%s' for %s", $val, $what unless
7091 $val =~ m/^$oi->{Re}$(?!\n)/s;
7092 my $how = $oi->{How};
7093 if (ref($how) eq 'SCALAR') {
7098 push @ropts, @rvalopts;
7102 last unless $ARGV[0] =~ m/^-/;
7106 if (m/^--dry-run$/) {
7109 } elsif (m/^--damp-run$/) {
7112 } elsif (m/^--no-sign$/) {
7115 } elsif (m/^--help$/) {
7117 } elsif (m/^--version$/) {
7119 } elsif (m/^--new$/) {
7122 } elsif (m/^--([-0-9a-z]+)=(.+)/s &&
7123 ($om = $opts_opt_map{$1}) &&
7127 } elsif (m/^--([-0-9a-z]+):(.*)/s &&
7128 !$opts_opt_cmdonly{$1} &&
7129 ($om = $opts_opt_map{$1})) {
7132 } elsif (m/^--(gbp|dpm)$/s) {
7133 push @ropts, "--quilt=$1";
7135 } elsif (m/^--(?:ignore|include)-dirty$/s) {
7138 } elsif (m/^--no-quilt-fixup$/s) {
7140 $quilt_mode = 'nocheck';
7141 } elsif (m/^--no-rm-on-error$/s) {
7144 } elsif (m/^--no-chase-dsc-distro$/s) {
7146 $chase_dsc_distro = 0;
7147 } elsif (m/^--overwrite$/s) {
7149 $overwrite_version = '';
7150 } elsif (m/^--overwrite=(.+)$/s) {
7152 $overwrite_version = $1;
7153 } elsif (m/^--delayed=(\d+)$/s) {
7156 } elsif (my ($k,$v) =
7157 m/^--save-(dgit-view)=(.+)$/s ||
7158 m/^--(dgit-view)-save=(.+)$/s
7161 $v =~ s#^(?!refs/)#refs/heads/#;
7162 $internal_object_save{$k} = $v;
7163 } elsif (m/^--(no-)?rm-old-changes$/s) {
7166 } elsif (m/^--deliberately-($deliberately_re)$/s) {
7168 push @deliberatelies, $&;
7169 } elsif (m/^--force-(.*)/ && defined $forceopts{$1}) {
7173 } elsif (m/^--force-/) {
7175 f_ "%s: warning: ignoring unknown force option %s\n",
7178 } elsif (m/^--dgit-tag-format=(old|new)$/s) {
7179 # undocumented, for testing
7181 $tagformat_want = [ $1, 'command line', 1 ];
7182 # 1 menas overrides distro configuration
7183 } elsif (m/^--config-lookup-explode=(.+)$/s) {
7184 # undocumented, for testing
7186 $gitcfgs{cmdline}{$1} = 'CONFIG-LOOKUP-EXPLODE';
7187 # ^ it's supposed to be an array ref
7188 } elsif (m/^(--[-0-9a-z]+)(=|$)/ && ($oi = $valopts_long{$1})) {
7189 $val = $2 ? $' : undef; #';
7190 $valopt->($oi->{Long});
7191 } elsif ($funcopts_long{$_}) {
7193 $funcopts_long{$_}();
7195 badusage f_ "unknown long option \`%s'", $_;
7202 } elsif (s/^-L/-/) {
7205 } elsif (s/^-h/-/) {
7207 } elsif (s/^-D/-/) {
7211 } elsif (s/^-N/-/) {
7216 push @changesopts, $_;
7218 } elsif (s/^-wn$//s) {
7220 $cleanmode = 'none';
7221 } elsif (s/^-wg$//s) {
7224 } elsif (s/^-wgf$//s) {
7226 $cleanmode = 'git-ff';
7227 } elsif (s/^-wd$//s) {
7229 $cleanmode = 'dpkg-source';
7230 } elsif (s/^-wdd$//s) {
7232 $cleanmode = 'dpkg-source-d';
7233 } elsif (s/^-wc$//s) {
7235 $cleanmode = 'check';
7236 } elsif (s/^-c([^=]*)\=(.*)$//s) {
7237 push @git, '-c', $&;
7238 $gitcfgs{cmdline}{$1} = [ $2 ];
7239 } elsif (s/^-c([^=]+)$//s) {
7240 push @git, '-c', $&;
7241 $gitcfgs{cmdline}{$1} = [ 'true' ];
7242 } elsif (m/^-[a-zA-Z]/ && ($oi = $valopts_short{$&})) {
7244 $val = undef unless length $val;
7245 $valopt->($oi->{Short});
7248 badusage f_ "unknown short option \`%s'", $_;
7255 sub check_env_sanity () {
7256 my $blocked = new POSIX::SigSet;
7257 sigprocmask SIG_UNBLOCK, $blocked, $blocked or confess $!;
7260 foreach my $name (qw(PIPE CHLD)) {
7261 my $signame = "SIG$name";
7262 my $signum = eval "POSIX::$signame" // die;
7263 die f_ "%s is set to something other than SIG_DFL\n",
7265 if defined $SIG{$name} and $SIG{$name} ne 'DEFAULT';
7266 $blocked->ismember($signum) and
7267 die f_ "%s is blocked\n", $signame;
7273 On entry to dgit, %s
7274 This is a bug produced by something in your execution environment.
7280 sub parseopts_late_defaults () {
7281 $isuite //= cfg("dgit-distro.$idistro.default-suite", 'RETURN-UNDEF')
7282 if defined $idistro;
7283 $isuite //= cfg('dgit.default.default-suite');
7285 foreach my $k (keys %opts_opt_map) {
7286 my $om = $opts_opt_map{$k};
7288 my $v = access_cfg("cmd-$k", 'RETURN-UNDEF');
7290 badcfg f_ "cannot set command for %s", $k
7291 unless length $om->[0];
7295 foreach my $c (access_cfg_cfgs("opts-$k")) {
7297 map { $_ ? @$_ : () }
7298 map { $gitcfgs{$_}{$c} }
7299 reverse @gitcfgsources;
7300 printdebug "CL $c ", (join " ", map { shellquote } @vl),
7301 "\n" if $debuglevel >= 4;
7303 badcfg f_ "cannot configure options for %s", $k
7304 if $opts_opt_cmdonly{$k};
7305 my $insertpos = $opts_cfg_insertpos{$k};
7306 @$om = ( @$om[0..$insertpos-1],
7308 @$om[$insertpos..$#$om] );
7312 if (!defined $rmchanges) {
7313 local $access_forpush;
7314 $rmchanges = access_cfg_bool(0, 'rm-old-changes');
7317 if (!defined $quilt_mode) {
7318 local $access_forpush;
7319 $quilt_mode = cfg('dgit.force.quilt-mode', 'RETURN-UNDEF')
7320 // access_cfg('quilt-mode', 'RETURN-UNDEF')
7322 $quilt_mode =~ m/^($quilt_modes_re)$/
7323 or badcfg f_ "unknown quilt-mode \`%s'", $quilt_mode;
7327 foreach my $moc (@modeopt_cfgs) {
7328 local $access_forpush;
7329 my $vr = $moc->{Var};
7330 next if defined $$vr;
7331 $$vr = access_cfg($moc->{Key}, 'RETURN-UNDEF') // $moc->{Default};
7332 my $v = $moc->{Vals}{$$vr};
7333 badcfg f_ "unknown %s setting \`%s'", $moc->{Key}, $$vr
7338 fail __ "dgit: --include-dirty is not supported in split view quilt mode"
7339 if $split_brain && $includedirty;
7341 if (!defined $cleanmode) {
7342 local $access_forpush;
7343 $cleanmode = access_cfg('clean-mode', 'RETURN-UNDEF');
7344 $cleanmode //= 'dpkg-source';
7346 badcfg f_ "unknown clean-mode \`%s'", $cleanmode unless
7347 $cleanmode =~ m/^($cleanmode_re)$(?!\n)/s;
7350 $buildproductsdir //= access_cfg('build-products-dir', 'RETURN-UNDEF');
7351 $buildproductsdir //= '..';
7352 $bpd_glob = $buildproductsdir;
7353 $bpd_glob =~ s#[][\\{}*?~]#\\$&#g;
7356 setlocale(LC_MESSAGES, "");
7359 if ($ENV{$fakeeditorenv}) {
7361 quilt_fixup_editor();
7367 print STDERR __ "DRY RUN ONLY\n" if $dryrun_level > 1;
7368 print STDERR __ "DAMP RUN - WILL MAKE LOCAL (UNSIGNED) CHANGES\n"
7369 if $dryrun_level == 1;
7371 print STDERR __ $helpmsg or confess $!;
7374 $cmd = $subcommand = shift @ARGV;
7377 my $pre_fn = ${*::}{"pre_$cmd"};
7378 $pre_fn->() if $pre_fn;
7380 if ($invoked_in_git_tree) {
7381 changedir_git_toplevel();
7386 my $fn = ${*::}{"cmd_$cmd"};
7387 $fn or badusage f_ "unknown operation %s", $cmd;