3 # Integration between git and Debian-style archives
5 # Copyright (C)2013-2016 Ian Jackson
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
28 use Dpkg::Control::Hash;
30 use File::Temp qw(tempdir);
37 use List::Util qw(any);
38 use List::MoreUtils qw(pairwise);
43 our $our_version = 'UNRELEASED'; ###substituted###
44 our $absurdity = undef; ###substituted###
46 our @rpushprotovsn_support = qw(4 3 2); # 4 is new tag format
49 our $isuite = 'unstable';
55 our $dryrun_level = 0;
57 our $buildproductsdir = '..';
63 our $existing_package = 'dpkg';
65 our $changes_since_version;
67 our $overwrite_version; # undef: not specified; '': check changelog
69 our $quilt_modes_re = 'linear|smash|auto|nofix|nocheck|gbp|dpm|unapplied';
70 our $split_brain_save;
71 our $we_are_responder;
72 our $initiator_tempdir;
73 our $patches_applied_dirtily = 00;
78 our %forceopts = map { $_=>0 }
79 qw(unrepresentable unsupported-source-format
80 dsc-changes-mismatch changes-origs-exactly
81 import-gitapply-absurd
82 import-gitapply-no-absurd
83 import-dsc-with-dgit-field);
85 our %format_ok = map { $_=>1 } ("1.0","3.0 (native)","3.0 (quilt)");
87 our $suite_re = '[-+.0-9a-z]+';
88 our $cleanmode_re = 'dpkg-source(?:-d)?|git|git-ff|check|none';
89 our $orig_f_comp_re = 'orig(?:-[-0-9a-z]+)?';
90 our $orig_f_sig_re = '\\.(?:asc|gpg|pgp)';
91 our $orig_f_tail_re = "$orig_f_comp_re\\.tar(?:\\.\\w+)?(?:$orig_f_sig_re)?";
93 our $git_authline_re = '^([^<>]+) \<(\S+)\> (\d+ [-+]\d+)$';
94 our $splitbraincache = 'dgit-intern/quilt-cache';
97 our (@dget) = qw(dget);
98 our (@curl) = qw(curl);
99 our (@dput) = qw(dput);
100 our (@debsign) = qw(debsign);
101 our (@gpg) = qw(gpg);
102 our (@sbuild) = qw(sbuild);
104 our (@dgit) = qw(dgit);
105 our (@dpkgbuildpackage) = qw(dpkg-buildpackage -i\.git/ -I.git);
106 our (@dpkgsource) = qw(dpkg-source -i\.git/ -I.git);
107 our (@dpkggenchanges) = qw(dpkg-genchanges);
108 our (@mergechanges) = qw(mergechanges -f);
109 our (@gbp_build) = ('');
110 our (@gbp_pq) = ('gbp pq');
111 our (@changesopts) = ('');
113 our %opts_opt_map = ('dget' => \@dget, # accept for compatibility
116 'debsign' => \@debsign,
118 'sbuild' => \@sbuild,
122 'dpkg-source' => \@dpkgsource,
123 'dpkg-buildpackage' => \@dpkgbuildpackage,
124 'dpkg-genchanges' => \@dpkggenchanges,
125 'gbp-build' => \@gbp_build,
126 'gbp-pq' => \@gbp_pq,
127 'ch' => \@changesopts,
128 'mergechanges' => \@mergechanges);
130 our %opts_opt_cmdonly = ('gpg' => 1, 'git' => 1);
131 our %opts_cfg_insertpos = map {
133 scalar @{ $opts_opt_map{$_} }
134 } keys %opts_opt_map;
136 sub finalise_opts_opts();
142 our $supplementary_message = '';
143 our $need_split_build_invocation = 0;
144 our $split_brain = 0;
148 print STDERR "! $_\n" foreach $supplementary_message =~ m/^.+$/mg;
151 our $remotename = 'dgit';
152 our @ourdscfield = qw(Dgit Vcs-Dgit-Master);
156 if (!defined $absurdity) {
158 $absurdity =~ s{/[^/]+$}{/absurd} or die;
162 my ($v,$distro) = @_;
163 return $tagformatfn->($v, $distro);
166 sub debiantag_maintview ($$) {
167 my ($v,$distro) = @_;
172 sub madformat ($) { $_[0] eq '3.0 (quilt)' }
174 sub lbranch () { return "$branchprefix/$csuite"; }
175 my $lbranch_re = '^refs/heads/'.$branchprefix.'/([^/.]+)$';
176 sub lref () { return "refs/heads/".lbranch(); }
177 sub lrref () { return "refs/remotes/$remotename/".server_branch($csuite); }
178 sub rrref () { return server_ref($csuite); }
180 sub lrfetchrefs () { return "refs/dgit-fetch/$csuite"; }
181 sub lrfetchref () { return lrfetchrefs.'/'.server_branch($csuite); }
183 # We fetch some parts of lrfetchrefs/*. Ideally we delete these
184 # locally fetched refs because they have unhelpful names and clutter
185 # up gitk etc. So we track whether we have "used up" head ref (ie,
186 # whether we have made another local ref which refers to this object).
188 # (If we deleted them unconditionally, then we might end up
189 # re-fetching the same git objects each time dgit fetch was run.)
191 # So, leach use of lrfetchrefs needs to be accompanied by arrangements
192 # in git_fetch_us to fetch the refs in question, and possibly a call
193 # to lrfetchref_used.
195 our (%lrfetchrefs_f, %lrfetchrefs_d);
196 # $lrfetchrefs_X{lrfetchrefs."/heads/whatever"} = $objid
198 sub lrfetchref_used ($) {
199 my ($fullrefname) = @_;
200 my $objid = $lrfetchrefs_f{$fullrefname};
201 $lrfetchrefs_d{$fullrefname} = $objid if defined $objid;
212 return "${package}_".(stripepoch $vsn).$sfx
217 return srcfn($vsn,".dsc");
220 sub changespat ($;$) {
221 my ($vsn, $arch) = @_;
222 return "${package}_".(stripepoch $vsn)."_".($arch//'*').".changes";
225 sub upstreamversion ($) {
237 foreach my $f (@end) {
239 print STDERR "$us: cleanup: $@" if length $@;
243 sub badcfg { print STDERR "$us: invalid configuration: @_\n"; exit 12; }
245 sub forceable_fail ($$) {
246 my ($forceoptsl, $msg) = @_;
247 fail $msg unless grep { $forceopts{$_} } @$forceoptsl;
248 print STDERR "warning: overriding problem due to --force:\n". $msg;
252 my ($forceoptsl) = @_;
253 my @got = grep { $forceopts{$_} } @$forceoptsl;
254 return 0 unless @got;
256 "warning: skipping checks or functionality due to --force-$got[0]\n";
259 sub no_such_package () {
260 print STDERR "$us: package $package does not exist in suite $isuite\n";
266 printdebug "CD $newdir\n";
267 chdir $newdir or confess "chdir: $newdir: $!";
270 sub deliberately ($) {
272 return !!grep { $_ eq "--deliberately-$enquiry" } @deliberatelies;
275 sub deliberately_not_fast_forward () {
276 foreach (qw(not-fast-forward fresh-repo)) {
277 return 1 if deliberately($_) || deliberately("TEST-dgit-only-$_");
281 sub quiltmode_splitbrain () {
282 $quilt_mode =~ m/gbp|dpm|unapplied/;
285 sub opts_opt_multi_cmd {
287 push @cmd, split /\s+/, shift @_;
293 return opts_opt_multi_cmd @gbp_pq;
296 #---------- remote protocol support, common ----------
298 # remote push initiator/responder protocol:
299 # $ dgit remote-push-build-host <n-rargs> <rargs>... <push-args>...
300 # where <rargs> is <push-host-dir> <supported-proto-vsn>,... ...
301 # < dgit-remote-push-ready <actual-proto-vsn>
308 # > supplementary-message NBYTES # $protovsn >= 3
313 # > file parsed-changelog
314 # [indicates that output of dpkg-parsechangelog follows]
315 # > data-block NBYTES
316 # > [NBYTES bytes of data (no newline)]
317 # [maybe some more blocks]
326 # > param head DGIT-VIEW-HEAD
327 # > param csuite SUITE
328 # > param tagformat old|new
329 # > param maint-view MAINT-VIEW-HEAD
331 # > previously REFNAME=OBJNAME # if --deliberately-not-fast-forward
332 # # goes into tag, for replay prevention
335 # [indicates that signed tag is wanted]
336 # < data-block NBYTES
337 # < [NBYTES bytes of data (no newline)]
338 # [maybe some more blocks]
342 # > want signed-dsc-changes
343 # < data-block NBYTES [transfer of signed dsc]
345 # < data-block NBYTES [transfer of signed changes]
353 sub i_child_report () {
354 # Sees if our child has died, and reap it if so. Returns a string
355 # describing how it died if it failed, or undef otherwise.
356 return undef unless $i_child_pid;
357 my $got = waitpid $i_child_pid, WNOHANG;
358 return undef if $got <= 0;
359 die unless $got == $i_child_pid;
360 $i_child_pid = undef;
361 return undef unless $?;
362 return "build host child ".waitstatusmsg();
367 fail "connection lost: $!" if $fh->error;
368 fail "protocol violation; $m not expected";
371 sub badproto_badread ($$) {
373 fail "connection lost: $!" if $!;
374 my $report = i_child_report();
375 fail $report if defined $report;
376 badproto $fh, "eof (reading $wh)";
379 sub protocol_expect (&$) {
380 my ($match, $fh) = @_;
383 defined && chomp or badproto_badread $fh, "protocol message";
391 badproto $fh, "\`$_'";
394 sub protocol_send_file ($$) {
395 my ($fh, $ourfn) = @_;
396 open PF, "<", $ourfn or die "$ourfn: $!";
399 my $got = read PF, $d, 65536;
400 die "$ourfn: $!" unless defined $got;
402 print $fh "data-block ".length($d)."\n" or die $!;
403 print $fh $d or die $!;
405 PF->error and die "$ourfn $!";
406 print $fh "data-end\n" or die $!;
410 sub protocol_read_bytes ($$) {
411 my ($fh, $nbytes) = @_;
412 $nbytes =~ m/^[1-9]\d{0,5}$|^0$/ or badproto \*RO, "bad byte count";
414 my $got = read $fh, $d, $nbytes;
415 $got==$nbytes or badproto_badread $fh, "data block";
419 sub protocol_receive_file ($$) {
420 my ($fh, $ourfn) = @_;
421 printdebug "() $ourfn\n";
422 open PF, ">", $ourfn or die "$ourfn: $!";
424 my ($y,$l) = protocol_expect {
425 m/^data-block (.*)$/ ? (1,$1) :
426 m/^data-end$/ ? (0,) :
430 my $d = protocol_read_bytes $fh, $l;
431 print PF $d or die $!;
436 #---------- remote protocol support, responder ----------
438 sub responder_send_command ($) {
440 return unless $we_are_responder;
441 # called even without $we_are_responder
442 printdebug ">> $command\n";
443 print PO $command, "\n" or die $!;
446 sub responder_send_file ($$) {
447 my ($keyword, $ourfn) = @_;
448 return unless $we_are_responder;
449 printdebug "]] $keyword $ourfn\n";
450 responder_send_command "file $keyword";
451 protocol_send_file \*PO, $ourfn;
454 sub responder_receive_files ($@) {
455 my ($keyword, @ourfns) = @_;
456 die unless $we_are_responder;
457 printdebug "[[ $keyword @ourfns\n";
458 responder_send_command "want $keyword";
459 foreach my $fn (@ourfns) {
460 protocol_receive_file \*PI, $fn;
463 protocol_expect { m/^files-end$/ } \*PI;
466 #---------- remote protocol support, initiator ----------
468 sub initiator_expect (&) {
470 protocol_expect { &$match } \*RO;
473 #---------- end remote code ----------
476 if ($we_are_responder) {
478 responder_send_command "progress ".length($m) or die $!;
479 print PO $m or die $!;
489 $ua = LWP::UserAgent->new();
493 progress "downloading $what...";
494 my $r = $ua->get(@_) or die $!;
495 return undef if $r->code == 404;
496 $r->is_success or fail "failed to fetch $what: ".$r->status_line;
497 return $r->decoded_content(charset => 'none');
500 our ($dscdata,$dscurl,$dsc,$dsc_checked,$skew_warning_vsn);
505 failedcmd @_ if system @_;
508 sub act_local () { return $dryrun_level <= 1; }
509 sub act_scary () { return !$dryrun_level; }
512 if (!$dryrun_level) {
513 progress "dgit ok: @_";
515 progress "would be ok: @_ (but dry run only)";
520 printcmd(\*STDERR,$debugprefix."#",@_);
523 sub runcmd_ordryrun {
531 sub runcmd_ordryrun_local {
540 my ($first_shell, @cmd) = @_;
541 return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
544 our $helpmsg = <<END;
546 dgit [dgit-opts] clone [dgit-opts] package [suite] [./dir|/dir]
547 dgit [dgit-opts] fetch|pull [dgit-opts] [suite]
548 dgit [dgit-opts] build [dpkg-buildpackage-opts]
549 dgit [dgit-opts] sbuild [sbuild-opts]
550 dgit [dgit-opts] push [dgit-opts] [suite]
551 dgit [dgit-opts] rpush build-host:build-dir ...
552 important dgit options:
553 -k<keyid> sign tag and package with <keyid> instead of default
554 --dry-run -n do not change anything, but go through the motions
555 --damp-run -L like --dry-run but make local changes, without signing
556 --new -N allow introducing a new package
557 --debug -D increase debug level
558 -c<name>=<value> set git config option (used directly by dgit too)
561 our $later_warning_msg = <<END;
562 Perhaps the upload is stuck in incoming. Using the version from git.
566 print STDERR "$us: @_\n", $helpmsg or die $!;
571 @ARGV or badusage "too few arguments";
572 return scalar shift @ARGV;
576 print $helpmsg or die $!;
580 our $td = $ENV{DGIT_TEST_DUMMY_DIR} || "DGIT_TEST_DUMMY_DIR-unset";
582 our %defcfg = ('dgit.default.distro' => 'debian',
583 'dgit.default.username' => '',
584 'dgit.default.archive-query-default-component' => 'main',
585 'dgit.default.ssh' => 'ssh',
586 'dgit.default.archive-query' => 'madison:',
587 'dgit.default.sshpsql-dbname' => 'service=projectb',
588 'dgit.default.dgit-tag-format' => 'new,old,maint',
589 # old means "repo server accepts pushes with old dgit tags"
590 # new means "repo server accepts pushes with new dgit tags"
591 # maint means "repo server accepts split brain pushes"
592 # hist means "repo server may have old pushes without new tag"
593 # ("hist" is implied by "old")
594 'dgit-distro.debian.archive-query' => 'ftpmasterapi:',
595 'dgit-distro.debian.git-check' => 'url',
596 'dgit-distro.debian.git-check-suffix' => '/info/refs',
597 'dgit-distro.debian.new-private-pushers' => 't',
598 'dgit-distro.debian/push.git-url' => '',
599 'dgit-distro.debian/push.git-host' => 'push.dgit.debian.org',
600 'dgit-distro.debian/push.git-user-force' => 'dgit',
601 'dgit-distro.debian/push.git-proto' => 'git+ssh://',
602 'dgit-distro.debian/push.git-path' => '/dgit/debian/repos',
603 'dgit-distro.debian/push.git-create' => 'true',
604 'dgit-distro.debian/push.git-check' => 'ssh-cmd',
605 'dgit-distro.debian.archive-query-url', 'https://api.ftp-master.debian.org/',
606 # 'dgit-distro.debian.archive-query-tls-key',
607 # '/etc/ssl/certs/%HOST%.pem:/etc/dgit/%HOST%.pem',
608 # ^ this does not work because curl is broken nowadays
609 # Fixing #790093 properly will involve providing providing the key
610 # in some pacagke and maybe updating these paths.
612 # 'dgit-distro.debian.archive-query-tls-curl-args',
613 # '--ca-path=/etc/ssl/ca-debian',
614 # ^ this is a workaround but works (only) on DSA-administered machines
615 'dgit-distro.debian.git-url' => 'https://git.dgit.debian.org',
616 'dgit-distro.debian.git-url-suffix' => '',
617 'dgit-distro.debian.upload-host' => 'ftp-master', # for dput
618 'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/',
619 'dgit-distro.debian.backports-quirk' => '(squeeze)-backports*',
620 'dgit-distro.debian-backports.mirror' => 'http://backports.debian.org/debian-backports/',
621 'dgit-distro.ubuntu.git-check' => 'false',
622 'dgit-distro.ubuntu.mirror' => 'http://archive.ubuntu.com/ubuntu',
623 'dgit-distro.test-dummy.ssh' => "$td/ssh",
624 'dgit-distro.test-dummy.username' => "alice",
625 'dgit-distro.test-dummy.git-check' => "ssh-cmd",
626 'dgit-distro.test-dummy.git-create' => "ssh-cmd",
627 'dgit-distro.test-dummy.git-url' => "$td/git",
628 'dgit-distro.test-dummy.git-host' => "git",
629 'dgit-distro.test-dummy.git-path' => "$td/git",
630 'dgit-distro.test-dummy.archive-query' => "dummycatapi:",
631 'dgit-distro.test-dummy.archive-query-url' => "file://$td/aq/",
632 'dgit-distro.test-dummy.mirror' => "file://$td/mirror/",
633 'dgit-distro.test-dummy.upload-host' => 'test-dummy',
637 our @gitcfgsources = qw(cmdline local global system);
639 sub git_slurp_config () {
640 local ($debuglevel) = $debuglevel-2;
643 # This algoritm is a bit subtle, but this is needed so that for
644 # options which we want to be single-valued, we allow the
645 # different config sources to override properly. See #835858.
646 foreach my $src (@gitcfgsources) {
647 next if $src eq 'cmdline';
648 # we do this ourselves since git doesn't handle it
650 my @cmd = (@git, qw(config -z --get-regexp), "--$src", qw(.*));
653 open GITS, "-|", @cmd or die $!;
656 printdebug "=> ", (messagequote $_), "\n";
658 push @{ $gitcfgs{$src}{$`} }, $'; #';
662 or ($!==0 && $?==256)
667 sub git_get_config ($) {
669 foreach my $src (@gitcfgsources) {
670 my $l = $gitcfgs{$src}{$c};
671 printdebug"C $c ".(defined $l ? messagequote "'$l'" : "undef")."\n"
674 @$l==1 or badcfg "multiple values for $c".
675 " (in $src git config)" if @$l > 1;
683 return undef if $c =~ /RETURN-UNDEF/;
684 my $v = git_get_config($c);
685 return $v if defined $v;
686 my $dv = $defcfg{$c};
687 return $dv if defined $dv;
689 badcfg "need value for one of: @_\n".
690 "$us: distro or suite appears not to be (properly) supported";
693 sub access_basedistro () {
694 if (defined $idistro) {
697 return cfg("dgit-suite.$isuite.distro",
698 "dgit.default.distro");
702 sub access_quirk () {
703 # returns (quirk name, distro to use instead or undef, quirk-specific info)
704 my $basedistro = access_basedistro();
705 my $backports_quirk = cfg("dgit-distro.$basedistro.backports-quirk",
707 if (defined $backports_quirk) {
708 my $re = $backports_quirk;
709 $re =~ s/[^-0-9a-z_\%*()]/\\$&/ig;
711 $re =~ s/\%/([-0-9a-z_]+)/
712 or $re =~ m/[()]/ or badcfg "backports-quirk needs \% or ( )";
713 if ($isuite =~ m/^$re$/) {
714 return ('backports',"$basedistro-backports",$1);
717 return ('none',undef);
722 sub parse_cfg_bool ($$$) {
723 my ($what,$def,$v) = @_;
726 $v =~ m/^[ty1]/ ? 1 :
727 $v =~ m/^[fn0]/ ? 0 :
728 badcfg "$what needs t (true, y, 1) or f (false, n, 0) not \`$v'";
731 sub access_forpush_config () {
732 my $d = access_basedistro();
736 parse_cfg_bool('new-private-pushers', 0,
737 cfg("dgit-distro.$d.new-private-pushers",
740 my $v = cfg("dgit-distro.$d.readonly", 'RETURN-UNDEF');
743 $v =~ m/^[ty1]/ ? 0 : # force readonly, forpush = 0
744 $v =~ m/^[fn0]/ ? 1 : # force nonreadonly, forpush = 1
745 $v =~ m/^[a]/ ? '' : # auto, forpush = ''
746 badcfg "readonly needs t (true, y, 1) or f (false, n, 0) or a (auto)";
749 sub access_forpush () {
750 $access_forpush //= access_forpush_config();
751 return $access_forpush;
755 die "$access_forpush ?" if ($access_forpush // 1) ne 1;
756 badcfg "pushing but distro is configured readonly"
757 if access_forpush_config() eq '0';
759 $supplementary_message = <<'END' unless $we_are_responder;
760 Push failed, before we got started.
761 You can retry the push, after fixing the problem, if you like.
763 finalise_opts_opts();
767 finalise_opts_opts();
770 sub supplementary_message ($) {
772 if (!$we_are_responder) {
773 $supplementary_message = $msg;
775 } elsif ($protovsn >= 3) {
776 responder_send_command "supplementary-message ".length($msg)
778 print PO $msg or die $!;
782 sub access_distros () {
783 # Returns list of distros to try, in order
786 # 0. `instead of' distro name(s) we have been pointed to
787 # 1. the access_quirk distro, if any
788 # 2a. the user's specified distro, or failing that } basedistro
789 # 2b. the distro calculated from the suite }
790 my @l = access_basedistro();
792 my (undef,$quirkdistro) = access_quirk();
793 unshift @l, $quirkdistro;
794 unshift @l, $instead_distro;
795 @l = grep { defined } @l;
797 if (access_forpush()) {
798 @l = map { ("$_/push", $_) } @l;
803 sub access_cfg_cfgs (@) {
806 # The nesting of these loops determines the search order. We put
807 # the key loop on the outside so that we search all the distros
808 # for each key, before going on to the next key. That means that
809 # if access_cfg is called with a more specific, and then a less
810 # specific, key, an earlier distro can override the less specific
811 # without necessarily overriding any more specific keys. (If the
812 # distro wants to override the more specific keys it can simply do
813 # so; whereas if we did the loop the other way around, it would be
814 # impossible to for an earlier distro to override a less specific
815 # key but not the more specific ones without restating the unknown
816 # values of the more specific keys.
819 # We have to deal with RETURN-UNDEF specially, so that we don't
820 # terminate the search prematurely.
822 if (m/RETURN-UNDEF/) { push @rundef, $_; last; }
825 foreach my $d (access_distros()) {
826 push @cfgs, map { "dgit-distro.$d.$_" } @realkeys;
828 push @cfgs, map { "dgit.default.$_" } @realkeys;
835 my (@cfgs) = access_cfg_cfgs(@keys);
836 my $value = cfg(@cfgs);
840 sub access_cfg_bool ($$) {
841 my ($def, @keys) = @_;
842 parse_cfg_bool($keys[0], $def, access_cfg(@keys, 'RETURN-UNDEF'));
845 sub string_to_ssh ($) {
847 if ($spec =~ m/\s/) {
848 return qw(sh -ec), 'exec '.$spec.' "$@"', 'x';
854 sub access_cfg_ssh () {
855 my $gitssh = access_cfg('ssh', 'RETURN-UNDEF');
856 if (!defined $gitssh) {
859 return string_to_ssh $gitssh;
863 sub access_runeinfo ($) {
865 return ": dgit ".access_basedistro()." $info ;";
868 sub access_someuserhost ($) {
870 my $user = access_cfg("$some-user-force", 'RETURN-UNDEF');
871 defined($user) && length($user) or
872 $user = access_cfg("$some-user",'username');
873 my $host = access_cfg("$some-host");
874 return length($user) ? "$user\@$host" : $host;
877 sub access_gituserhost () {
878 return access_someuserhost('git');
881 sub access_giturl (;$) {
883 my $url = access_cfg('git-url','RETURN-UNDEF');
886 my $proto = access_cfg('git-proto', 'RETURN-UNDEF');
887 return undef unless defined $proto;
890 access_gituserhost().
891 access_cfg('git-path');
893 $suffix = access_cfg('git-url-suffix','RETURN-UNDEF');
896 return "$url/$package$suffix";
899 sub parsecontrolfh ($$;$) {
900 my ($fh, $desc, $allowsigned) = @_;
901 our $dpkgcontrolhash_noissigned;
904 my %opts = ('name' => $desc);
905 $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
906 $c = Dpkg::Control::Hash->new(%opts);
907 $c->parse($fh,$desc) or die "parsing of $desc failed";
908 last if $allowsigned;
909 last if $dpkgcontrolhash_noissigned;
910 my $issigned= $c->get_option('is_pgp_signed');
911 if (!defined $issigned) {
912 $dpkgcontrolhash_noissigned= 1;
913 seek $fh, 0,0 or die "seek $desc: $!";
914 } elsif ($issigned) {
915 fail "control file $desc is (already) PGP-signed. ".
916 " Note that dgit push needs to modify the .dsc and then".
917 " do the signature itself";
926 my ($file, $desc, $allowsigned) = @_;
927 my $fh = new IO::Handle;
928 open $fh, '<', $file or die "$file: $!";
929 my $c = parsecontrolfh($fh,$desc,$allowsigned);
930 $fh->error and die $!;
936 my ($dctrl,$field) = @_;
937 my $v = $dctrl->{$field};
938 return $v if defined $v;
939 fail "missing field $field in ".$dctrl->get_option('name');
943 my $c = Dpkg::Control::Hash->new(name => 'parsed changelog');
944 my $p = new IO::Handle;
945 my @cmd = (qw(dpkg-parsechangelog), @_);
946 open $p, '-|', @cmd or die $!;
948 $?=0; $!=0; close $p or failedcmd @cmd;
952 sub commit_getclogp ($) {
953 # Returns the parsed changelog hashref for a particular commit
955 our %commit_getclogp_memo;
956 my $memo = $commit_getclogp_memo{$objid};
957 return $memo if $memo;
959 my $mclog = ".git/dgit/clog-$objid";
960 runcmd shell_cmd "exec >$mclog", @git, qw(cat-file blob),
961 "$objid:debian/changelog";
962 $commit_getclogp_memo{$objid} = parsechangelog("-l$mclog");
967 defined $d or fail "getcwd failed: $!";
971 sub parse_dscdata () {
972 my $dscfh = new IO::File \$dscdata, '<' or die $!;
973 printdebug Dumper($dscdata) if $debuglevel>1;
974 $dsc = parsecontrolfh($dscfh,$dscurl,1);
975 printdebug Dumper($dsc) if $debuglevel>1;
980 sub archive_query ($;@) {
981 my ($method) = shift @_;
982 my $query = access_cfg('archive-query','RETURN-UNDEF');
983 $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
986 { no strict qw(refs); &{"${method}_${proto}"}($proto,$data,@_); }
989 sub archive_query_prepend_mirror {
990 my $m = access_cfg('mirror');
991 return map { [ $_->[0], $m.$_->[1], @$_[2..$#$_] ] } @_;
994 sub pool_dsc_subpath ($$) {
995 my ($vsn,$component) = @_; # $package is implict arg
996 my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
997 return "/pool/$component/$prefix/$package/".dscfn($vsn);
1000 #---------- `ftpmasterapi' archive query method (nascent) ----------
1002 sub archive_api_query_cmd ($) {
1004 my @cmd = (@curl, qw(-sS));
1005 my $url = access_cfg('archive-query-url');
1006 if ($url =~ m#^https://([-.0-9a-z]+)/#) {
1008 my $keys = access_cfg('archive-query-tls-key','RETURN-UNDEF') //'';
1009 foreach my $key (split /\:/, $keys) {
1010 $key =~ s/\%HOST\%/$host/g;
1012 fail "for $url: stat $key: $!" unless $!==ENOENT;
1015 fail "config requested specific TLS key but do not know".
1016 " how to get curl to use exactly that EE key ($key)";
1017 # push @cmd, "--cacert", $key, "--capath", "/dev/enoent";
1018 # # Sadly the above line does not work because of changes
1019 # # to gnutls. The real fix for #790093 may involve
1020 # # new curl options.
1023 # Fixing #790093 properly will involve providing a value
1024 # for this on clients.
1025 my $kargs = access_cfg('archive-query-tls-curl-ca-args','RETURN-UNDEF');
1026 push @cmd, split / /, $kargs if defined $kargs;
1028 push @cmd, $url.$subpath;
1032 sub api_query ($$;$) {
1034 my ($data, $subpath, $ok404) = @_;
1035 badcfg "ftpmasterapi archive query method takes no data part"
1037 my @cmd = archive_api_query_cmd($subpath);
1038 my $url = $cmd[$#cmd];
1039 push @cmd, qw(-w %{http_code});
1040 my $json = cmdoutput @cmd;
1041 unless ($json =~ s/\d+\d+\d$//) {
1042 failedcmd_report_cmd undef, @cmd;
1043 fail "curl failed to print 3-digit HTTP code";
1046 return undef if $code eq '404' && $ok404;
1047 fail "fetch of $url gave HTTP code $code"
1048 unless $url =~ m#^file://# or $code =~ m/^2/;
1049 return decode_json($json);
1052 sub canonicalise_suite_ftpmasterapi {
1053 my ($proto,$data) = @_;
1054 my $suites = api_query($data, 'suites');
1056 foreach my $entry (@$suites) {
1058 my $v = $entry->{$_};
1059 defined $v && $v eq $isuite;
1060 } qw(codename name);
1061 push @matched, $entry;
1063 fail "unknown suite $isuite" unless @matched;
1066 @matched==1 or die "multiple matches for suite $isuite\n";
1067 $cn = "$matched[0]{codename}";
1068 defined $cn or die "suite $isuite info has no codename\n";
1069 $cn =~ m/^$suite_re$/ or die "suite $isuite maps to bad codename\n";
1071 die "bad ftpmaster api response: $@\n".Dumper(\@matched)
1076 sub archive_query_ftpmasterapi {
1077 my ($proto,$data) = @_;
1078 my $info = api_query($data, "dsc_in_suite/$isuite/$package");
1080 my $digester = Digest::SHA->new(256);
1081 foreach my $entry (@$info) {
1083 my $vsn = "$entry->{version}";
1084 my ($ok,$msg) = version_check $vsn;
1085 die "bad version: $msg\n" unless $ok;
1086 my $component = "$entry->{component}";
1087 $component =~ m/^$component_re$/ or die "bad component";
1088 my $filename = "$entry->{filename}";
1089 $filename && $filename !~ m#[^-+:._~0-9a-zA-Z/]|^[/.]|/[/.]#
1090 or die "bad filename";
1091 my $sha256sum = "$entry->{sha256sum}";
1092 $sha256sum =~ m/^[0-9a-f]+$/ or die "bad sha256sum";
1093 push @rows, [ $vsn, "/pool/$component/$filename",
1094 $digester, $sha256sum ];
1096 die "bad ftpmaster api response: $@\n".Dumper($entry)
1099 @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
1100 return archive_query_prepend_mirror @rows;
1103 sub file_in_archive_ftpmasterapi {
1104 my ($proto,$data,$filename) = @_;
1105 my $pat = $filename;
1108 $pat =~ s#[^-+_.0-9a-z/]# sprintf '%%%02x', ord $& #ge;
1109 my $info = api_query($data, "file_in_archive/$pat", 1);
1112 #---------- `dummyapicat' archive query method ----------
1114 sub archive_query_dummycatapi { archive_query_ftpmasterapi @_; }
1115 sub canonicalise_suite_dummycatapi { canonicalise_suite_ftpmasterapi @_; }
1117 sub file_in_archive_dummycatapi ($$$) {
1118 my ($proto,$data,$filename) = @_;
1119 my $mirror = access_cfg('mirror');
1120 $mirror =~ s#^file://#/# or die "$mirror ?";
1122 my @cmd = (qw(sh -ec), '
1124 find -name "$2" -print0 |
1126 ', qw(x), $mirror, $filename);
1127 debugcmd "-|", @cmd;
1128 open FIA, "-|", @cmd or die $!;
1131 printdebug "| $_\n";
1132 m/^(\w+) (\S+)$/ or die "$_ ?";
1133 push @out, { sha256sum => $1, filename => $2 };
1135 close FIA or die failedcmd @cmd;
1139 #---------- `madison' archive query method ----------
1141 sub archive_query_madison {
1142 return archive_query_prepend_mirror
1143 map { [ @$_[0..1] ] } madison_get_parse(@_);
1146 sub madison_get_parse {
1147 my ($proto,$data) = @_;
1148 die unless $proto eq 'madison';
1149 if (!length $data) {
1150 $data= access_cfg('madison-distro','RETURN-UNDEF');
1151 $data //= access_basedistro();
1153 $rmad{$proto,$data,$package} ||= cmdoutput
1154 qw(rmadison -asource),"-s$isuite","-u$data",$package;
1155 my $rmad = $rmad{$proto,$data,$package};
1158 foreach my $l (split /\n/, $rmad) {
1159 $l =~ m{^ \s*( [^ \t|]+ )\s* \|
1160 \s*( [^ \t|]+ )\s* \|
1161 \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
1162 \s*( [^ \t|]+ )\s* }x or die "$rmad ?";
1163 $1 eq $package or die "$rmad $package ?";
1170 $component = access_cfg('archive-query-default-component');
1172 $5 eq 'source' or die "$rmad ?";
1173 push @out, [$vsn,pool_dsc_subpath($vsn,$component),$newsuite];
1175 return sort { -version_compare($a->[0],$b->[0]); } @out;
1178 sub canonicalise_suite_madison {
1179 # madison canonicalises for us
1180 my @r = madison_get_parse(@_);
1182 "unable to canonicalise suite using package $package".
1183 " which does not appear to exist in suite $isuite;".
1184 " --existing-package may help";
1188 sub file_in_archive_madison { return undef; }
1190 #---------- `sshpsql' archive query method ----------
1193 my ($data,$runeinfo,$sql) = @_;
1194 if (!length $data) {
1195 $data= access_someuserhost('sshpsql').':'.
1196 access_cfg('sshpsql-dbname');
1198 $data =~ m/:/ or badcfg "invalid sshpsql method string \`$data'";
1199 my ($userhost,$dbname) = ($`,$'); #';
1201 my @cmd = (access_cfg_ssh, $userhost,
1202 access_runeinfo("ssh-psql $runeinfo").
1203 " export LC_MESSAGES=C; export LC_CTYPE=C;".
1204 " ".shellquote qw(psql -A), $dbname, qw(-c), $sql);
1206 open P, "-|", @cmd or die $!;
1209 printdebug(">|$_|\n");
1212 $!=0; $?=0; close P or failedcmd @cmd;
1214 my $nrows = pop @rows;
1215 $nrows =~ s/^\((\d+) rows?\)$/$1/ or die "$nrows ?";
1216 @rows == $nrows+1 or die "$nrows ".(scalar @rows)." ?";
1217 @rows = map { [ split /\|/, $_ ] } @rows;
1218 my $ncols = scalar @{ shift @rows };
1219 die if grep { scalar @$_ != $ncols } @rows;
1223 sub sql_injection_check {
1224 foreach (@_) { die "$_ $& ?" if m{[^-+=:_.,/0-9a-zA-Z]}; }
1227 sub archive_query_sshpsql ($$) {
1228 my ($proto,$data) = @_;
1229 sql_injection_check $isuite, $package;
1230 my @rows = sshpsql($data, "archive-query $isuite $package", <<END);
1231 SELECT source.version, component.name, files.filename, files.sha256sum
1233 JOIN src_associations ON source.id = src_associations.source
1234 JOIN suite ON suite.id = src_associations.suite
1235 JOIN dsc_files ON dsc_files.source = source.id
1236 JOIN files_archive_map ON files_archive_map.file_id = dsc_files.file
1237 JOIN component ON component.id = files_archive_map.component_id
1238 JOIN files ON files.id = dsc_files.file
1239 WHERE ( suite.suite_name='$isuite' OR suite.codename='$isuite' )
1240 AND source.source='$package'
1241 AND files.filename LIKE '%.dsc';
1243 @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
1244 my $digester = Digest::SHA->new(256);
1246 my ($vsn,$component,$filename,$sha256sum) = @$_;
1247 [ $vsn, "/pool/$component/$filename",$digester,$sha256sum ];
1249 return archive_query_prepend_mirror @rows;
1252 sub canonicalise_suite_sshpsql ($$) {
1253 my ($proto,$data) = @_;
1254 sql_injection_check $isuite;
1255 my @rows = sshpsql($data, "canonicalise-suite $isuite", <<END);
1256 SELECT suite.codename
1257 FROM suite where suite_name='$isuite' or codename='$isuite';
1259 @rows = map { $_->[0] } @rows;
1260 fail "unknown suite $isuite" unless @rows;
1261 die "ambiguous $isuite: @rows ?" if @rows>1;
1265 sub file_in_archive_sshpsql ($$$) { return undef; }
1267 #---------- `dummycat' archive query method ----------
1269 sub canonicalise_suite_dummycat ($$) {
1270 my ($proto,$data) = @_;
1271 my $dpath = "$data/suite.$isuite";
1272 if (!open C, "<", $dpath) {
1273 $!==ENOENT or die "$dpath: $!";
1274 printdebug "dummycat canonicalise_suite $isuite $dpath ENOENT\n";
1278 chomp or die "$dpath: $!";
1280 printdebug "dummycat canonicalise_suite $isuite $dpath = $_\n";
1284 sub archive_query_dummycat ($$) {
1285 my ($proto,$data) = @_;
1286 canonicalise_suite();
1287 my $dpath = "$data/package.$csuite.$package";
1288 if (!open C, "<", $dpath) {
1289 $!==ENOENT or die "$dpath: $!";
1290 printdebug "dummycat query $csuite $package $dpath ENOENT\n";
1298 printdebug "dummycat query $csuite $package $dpath | $_\n";
1299 my @row = split /\s+/, $_;
1300 @row==2 or die "$dpath: $_ ?";
1303 C->error and die "$dpath: $!";
1305 return archive_query_prepend_mirror
1306 sort { -version_compare($a->[0],$b->[0]); } @rows;
1309 sub file_in_archive_dummycat () { return undef; }
1311 #---------- tag format handling ----------
1313 sub access_cfg_tagformats () {
1314 split /\,/, access_cfg('dgit-tag-format');
1317 sub need_tagformat ($$) {
1318 my ($fmt, $why) = @_;
1319 fail "need to use tag format $fmt ($why) but also need".
1320 " to use tag format $tagformat_want->[0] ($tagformat_want->[1])".
1321 " - no way to proceed"
1322 if $tagformat_want && $tagformat_want->[0] ne $fmt;
1323 $tagformat_want = [$fmt, $why, $tagformat_want->[2] // 0];
1326 sub select_tagformat () {
1328 return if $tagformatfn && !$tagformat_want;
1329 die 'bug' if $tagformatfn && $tagformat_want;
1330 # ... $tagformat_want assigned after previous select_tagformat
1332 my (@supported) = grep { $_ =~ m/^(?:old|new)$/ } access_cfg_tagformats();
1333 printdebug "select_tagformat supported @supported\n";
1335 $tagformat_want //= [ $supported[0], "distro access configuration", 0 ];
1336 printdebug "select_tagformat specified @$tagformat_want\n";
1338 my ($fmt,$why,$override) = @$tagformat_want;
1340 fail "target distro supports tag formats @supported".
1341 " but have to use $fmt ($why)"
1343 or grep { $_ eq $fmt } @supported;
1345 $tagformat_want = undef;
1347 $tagformatfn = ${*::}{"debiantag_$fmt"};
1349 fail "trying to use unknown tag format \`$fmt' ($why) !"
1350 unless $tagformatfn;
1353 #---------- archive query entrypoints and rest of program ----------
1355 sub canonicalise_suite () {
1356 return if defined $csuite;
1357 fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
1358 $csuite = archive_query('canonicalise_suite');
1359 if ($isuite ne $csuite) {
1360 progress "canonical suite name for $isuite is $csuite";
1364 sub get_archive_dsc () {
1365 canonicalise_suite();
1366 my @vsns = archive_query('archive_query');
1367 foreach my $vinfo (@vsns) {
1368 my ($vsn,$vsn_dscurl,$digester,$digest) = @$vinfo;
1369 $dscurl = $vsn_dscurl;
1370 $dscdata = url_get($dscurl);
1372 $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
1377 $digester->add($dscdata);
1378 my $got = $digester->hexdigest();
1380 fail "$dscurl has hash $got but".
1381 " archive told us to expect $digest";
1384 my $fmt = getfield $dsc, 'Format';
1385 $format_ok{$fmt} or forceable_fail [qw(unsupported-source-format)],
1386 "unsupported source format $fmt, sorry";
1388 $dsc_checked = !!$digester;
1389 printdebug "get_archive_dsc: Version ".(getfield $dsc, 'Version')."\n";
1393 printdebug "get_archive_dsc: nothing in archive, returning undef\n";
1396 sub check_for_git ();
1397 sub check_for_git () {
1399 my $how = access_cfg('git-check');
1400 if ($how eq 'ssh-cmd') {
1402 (access_cfg_ssh, access_gituserhost(),
1403 access_runeinfo("git-check $package").
1404 " set -e; cd ".access_cfg('git-path').";".
1405 " if test -d $package.git; then echo 1; else echo 0; fi");
1406 my $r= cmdoutput @cmd;
1407 if (defined $r and $r =~ m/^divert (\w+)$/) {
1409 my ($usedistro,) = access_distros();
1410 # NB that if we are pushing, $usedistro will be $distro/push
1411 $instead_distro= cfg("dgit-distro.$usedistro.diverts.$divert");
1412 $instead_distro =~ s{^/}{ access_basedistro()."/" }e;
1413 progress "diverting to $divert (using config for $instead_distro)";
1414 return check_for_git();
1416 failedcmd @cmd unless defined $r and $r =~ m/^[01]$/;
1418 } elsif ($how eq 'url') {
1419 my $prefix = access_cfg('git-check-url','git-url');
1420 my $suffix = access_cfg('git-check-suffix','git-suffix',
1421 'RETURN-UNDEF') // '.git';
1422 my $url = "$prefix/$package$suffix";
1423 my @cmd = (@curl, qw(-sS -I), $url);
1424 my $result = cmdoutput @cmd;
1425 $result =~ s/^\S+ 200 .*\n\r?\n//;
1426 # curl -sS -I with https_proxy prints
1427 # HTTP/1.0 200 Connection established
1428 $result =~ m/^\S+ (404|200) /s or
1429 fail "unexpected results from git check query - ".
1430 Dumper($prefix, $result);
1432 if ($code eq '404') {
1434 } elsif ($code eq '200') {
1439 } elsif ($how eq 'true') {
1441 } elsif ($how eq 'false') {
1444 badcfg "unknown git-check \`$how'";
1448 sub create_remote_git_repo () {
1449 my $how = access_cfg('git-create');
1450 if ($how eq 'ssh-cmd') {
1452 (access_cfg_ssh, access_gituserhost(),
1453 access_runeinfo("git-create $package").
1454 "set -e; cd ".access_cfg('git-path').";".
1455 " cp -a _template $package.git");
1456 } elsif ($how eq 'true') {
1459 badcfg "unknown git-create \`$how'";
1463 our ($dsc_hash,$lastpush_mergeinput);
1465 our $ud = '.git/dgit/unpack';
1475 sub mktree_in_ud_here () {
1476 runcmd qw(git init -q);
1477 runcmd qw(git config gc.auto 0);
1478 rmtree('.git/objects');
1479 symlink '../../../../objects','.git/objects' or die $!;
1482 sub git_write_tree () {
1483 my $tree = cmdoutput @git, qw(write-tree);
1484 $tree =~ m/^\w+$/ or die "$tree ?";
1488 sub remove_stray_gits () {
1489 my @gitscmd = qw(find -name .git -prune -print0);
1490 debugcmd "|",@gitscmd;
1491 open GITS, "-|", @gitscmd or die $!;
1496 print STDERR "$us: warning: removing from source package: ",
1497 (messagequote $_), "\n";
1501 $!=0; $?=0; close GITS or failedcmd @gitscmd;
1504 sub mktree_in_ud_from_only_subdir (;$) {
1507 # changes into the subdir
1509 die "expected one subdir but found @dirs ?" unless @dirs==1;
1510 $dirs[0] =~ m#^([^/]+)/\.$# or die;
1514 remove_stray_gits();
1515 mktree_in_ud_here();
1517 my ($format, $fopts) = get_source_format();
1518 if (madformat($format)) {
1523 runcmd @git, qw(add -Af);
1524 my $tree=git_write_tree();
1525 return ($tree,$dir);
1528 our @files_csum_info_fields =
1529 (['Checksums-Sha256','Digest::SHA', 'new(256)', 'sha256sum'],
1530 ['Checksums-Sha1', 'Digest::SHA', 'new(1)', 'sha1sum'],
1531 ['Files', 'Digest::MD5', 'new()', 'md5sum']);
1533 sub dsc_files_info () {
1534 foreach my $csumi (@files_csum_info_fields) {
1535 my ($fname, $module, $method) = @$csumi;
1536 my $field = $dsc->{$fname};
1537 next unless defined $field;
1538 eval "use $module; 1;" or die $@;
1540 foreach (split /\n/, $field) {
1542 m/^(\w+) (\d+) (\S+)$/ or
1543 fail "could not parse .dsc $fname line \`$_'";
1544 my $digester = eval "$module"."->$method;" or die $@;
1549 Digester => $digester,
1554 fail "missing any supported Checksums-* or Files field in ".
1555 $dsc->get_option('name');
1559 map { $_->{Filename} } dsc_files_info();
1562 sub files_compare_inputs (@) {
1567 my $showinputs = sub {
1568 return join "; ", map { $_->get_option('name') } @$inputs;
1571 foreach my $in (@$inputs) {
1573 my $in_name = $in->get_option('name');
1575 printdebug "files_compare_inputs $in_name\n";
1577 foreach my $csumi (@files_csum_info_fields) {
1578 my ($fname) = @$csumi;
1579 printdebug "files_compare_inputs $in_name $fname\n";
1581 my $field = $in->{$fname};
1582 next unless defined $field;
1585 foreach (split /\n/, $field) {
1588 my ($info, $f) = m/^(\w+ \d+) (?:\S+ \S+ )?(\S+)$/ or
1589 fail "could not parse $in_name $fname line \`$_'";
1591 printdebug "files_compare_inputs $in_name $fname $f\n";
1595 my $re = \ $record{$f}{$fname};
1597 $fchecked{$f}{$in_name} = 1;
1599 fail "hash or size of $f varies in $fname fields".
1600 " (between: ".$showinputs->().")";
1605 @files = sort @files;
1606 $expected_files //= \@files;
1607 "@$expected_files" eq "@files" or
1608 fail "file list in $in_name varies between hash fields!";
1611 fail "$in_name has no files list field(s)";
1613 printdebug "files_compare_inputs ".Dumper(\%fchecked, \%record)
1616 grep { keys %$_ == @$inputs-1 } values %fchecked
1617 or fail "no file appears in all file lists".
1618 " (looked in: ".$showinputs->().")";
1621 sub is_orig_file_in_dsc ($$) {
1622 my ($f, $dsc_files_info) = @_;
1623 return 0 if @$dsc_files_info <= 1;
1624 # One file means no origs, and the filename doesn't have a "what
1625 # part of dsc" component. (Consider versions ending `.orig'.)
1626 return 0 unless $f =~ m/\.$orig_f_tail_re$/o;
1630 sub is_orig_file_of_vsn ($$) {
1631 my ($f, $upstreamvsn) = @_;
1632 my $base = srcfn $upstreamvsn, '';
1633 return 0 unless $f =~ m/^\Q$base\E\.$orig_f_tail_re$/;
1637 sub changes_update_origs_from_dsc ($$$$) {
1638 my ($dsc, $changes, $upstreamvsn, $changesfile) = @_;
1640 printdebug "checking origs needed ($upstreamvsn)...\n";
1641 $_ = getfield $changes, 'Files';
1642 m/^\w+ \d+ (\S+ \S+) \S+$/m or
1643 fail "cannot find section/priority from .changes Files field";
1644 my $placementinfo = $1;
1646 printdebug "checking origs needed placement '$placementinfo'...\n";
1647 foreach my $l (split /\n/, getfield $dsc, 'Files') {
1648 $l =~ m/\S+$/ or next;
1650 printdebug "origs $file | $l\n";
1651 next unless is_orig_file_of_vsn $file, $upstreamvsn;
1652 printdebug "origs $file is_orig\n";
1653 my $have = archive_query('file_in_archive', $file);
1654 if (!defined $have) {
1656 archive does not support .orig check; hope you used --ch:--sa/-sd if needed
1662 printdebug "origs $file \$#\$have=$#$have\n";
1663 foreach my $h (@$have) {
1666 foreach my $csumi (@files_csum_info_fields) {
1667 my ($fname, $module, $method, $archivefield) = @$csumi;
1668 next unless defined $h->{$archivefield};
1669 $_ = $dsc->{$fname};
1670 next unless defined;
1671 m/^(\w+) .* \Q$file\E$/m or
1672 fail ".dsc $fname missing entry for $file";
1673 if ($h->{$archivefield} eq $1) {
1677 "$archivefield: $h->{$archivefield} (archive) != $1 (local .dsc)";
1680 die "$file ".Dumper($h)." ?!" if $same && @differ;
1683 push @found_differ, "archive $h->{filename}: ".join "; ", @differ
1686 print "origs $file f.same=$found_same #f._differ=$#found_differ\n";
1687 if (@found_differ && !$found_same) {
1689 "archive contains $file with different checksum",
1692 # Now we edit the changes file to add or remove it
1693 foreach my $csumi (@files_csum_info_fields) {
1694 my ($fname, $module, $method, $archivefield) = @$csumi;
1695 next unless defined $changes->{$fname};
1697 # in archive, delete from .changes if it's there
1698 $changed{$file} = "removed" if
1699 $changes->{$fname} =~ s/^.* \Q$file\E$(?:)\n//m;
1700 } elsif ($changes->{$fname} =~ m/^.* \Q$file\E$(?:)\n/m) {
1701 # not in archive, but it's here in the .changes
1703 my $dsc_data = getfield $dsc, $fname;
1704 $dsc_data =~ m/^(.* \Q$file\E$)\n/m or die "$dsc_data $file ?";
1706 $extra =~ s/ \d+ /$&$placementinfo /
1707 or die "$fname $extra >$dsc_data< ?"
1708 if $fname eq 'Files';
1709 $changes->{$fname} .= "\n". $extra;
1710 $changed{$file} = "added";
1715 foreach my $file (keys %changed) {
1717 "edited .changes for archive .orig contents: %s %s",
1718 $changed{$file}, $file;
1720 my $chtmp = "$changesfile.tmp";
1721 $changes->save($chtmp);
1723 rename $chtmp,$changesfile or die "$changesfile $!";
1725 progress "[new .changes left in $changesfile]";
1728 progress "$changesfile already has appropriate .orig(s) (if any)";
1732 sub make_commit ($) {
1734 return cmdoutput @git, qw(hash-object -w -t commit), $file;
1737 sub make_commit_text ($) {
1740 my @cmd = (@git, qw(hash-object -w -t commit --stdin));
1742 print Dumper($text) if $debuglevel > 1;
1743 my $child = open2($out, $in, @cmd) or die $!;
1746 print $in $text or die $!;
1747 close $in or die $!;
1749 $h =~ m/^\w+$/ or die;
1751 printdebug "=> $h\n";
1754 waitpid $child, 0 == $child or die "$child $!";
1755 $? and failedcmd @cmd;
1759 sub clogp_authline ($) {
1761 my $author = getfield $clogp, 'Maintainer';
1762 $author =~ s#,.*##ms;
1763 my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
1764 my $authline = "$author $date";
1765 $authline =~ m/$git_authline_re/o or
1766 fail "unexpected commit author line format \`$authline'".
1767 " (was generated from changelog Maintainer field)";
1768 return ($1,$2,$3) if wantarray;
1772 sub vendor_patches_distro ($$) {
1773 my ($checkdistro, $what) = @_;
1774 return unless defined $checkdistro;
1776 my $series = "debian/patches/\L$checkdistro\E.series";
1777 printdebug "checking for vendor-specific $series ($what)\n";
1779 if (!open SERIES, "<", $series) {
1780 die "$series $!" unless $!==ENOENT;
1789 Unfortunately, this source package uses a feature of dpkg-source where
1790 the same source package unpacks to different source code on different
1791 distros. dgit cannot safely operate on such packages on affected
1792 distros, because the meaning of source packages is not stable.
1794 Please ask the distro/maintainer to remove the distro-specific series
1795 files and use a different technique (if necessary, uploading actually
1796 different packages, if different distros are supposed to have
1800 fail "Found active distro-specific series file for".
1801 " $checkdistro ($what): $series, cannot continue";
1803 die "$series $!" if SERIES->error;
1807 sub check_for_vendor_patches () {
1808 # This dpkg-source feature doesn't seem to be documented anywhere!
1809 # But it can be found in the changelog (reformatted):
1811 # commit 4fa01b70df1dc4458daee306cfa1f987b69da58c
1812 # Author: Raphael Hertzog <hertzog@debian.org>
1813 # Date: Sun Oct 3 09:36:48 2010 +0200
1815 # dpkg-source: correctly create .pc/.quilt_series with alternate
1818 # If you have debian/patches/ubuntu.series and you were
1819 # unpacking the source package on ubuntu, quilt was still
1820 # directed to debian/patches/series instead of
1821 # debian/patches/ubuntu.series.
1823 # debian/changelog | 3 +++
1824 # scripts/Dpkg/Source/Package/V3/quilt.pm | 4 +++-
1825 # 2 files changed, 6 insertions(+), 1 deletion(-)
1828 vendor_patches_distro($ENV{DEB_VENDOR}, "DEB_VENDOR");
1829 vendor_patches_distro(Dpkg::Vendor::get_current_vendor(),
1830 "Dpkg::Vendor \`current vendor'");
1831 vendor_patches_distro(access_basedistro(),
1832 "distro being accessed");
1835 sub generate_commits_from_dsc () {
1836 # See big comment in fetch_from_archive, below.
1837 # See also README.dsc-import.
1841 my @dfi = dsc_files_info();
1842 foreach my $fi (@dfi) {
1843 my $f = $fi->{Filename};
1844 die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
1846 printdebug "considering linking $f: ";
1848 link_ltarget "../../../../$f", $f
1849 or ((printdebug "($!) "), 0)
1853 printdebug "linked.\n";
1855 complete_file_from_dsc('.', $fi)
1858 if (is_orig_file_in_dsc($f, \@dfi)) {
1859 link $f, "../../../../$f"
1865 # We unpack and record the orig tarballs first, so that we only
1866 # need disk space for one private copy of the unpacked source.
1867 # But we can't make them into commits until we have the metadata
1868 # from the debian/changelog, so we record the tree objects now and
1869 # make them into commits later.
1871 my $upstreamv = upstreamversion $dsc->{version};
1872 my $orig_f_base = srcfn $upstreamv, '';
1874 foreach my $fi (@dfi) {
1875 # We actually import, and record as a commit, every tarball
1876 # (unless there is only one file, in which case there seems
1879 my $f = $fi->{Filename};
1880 printdebug "import considering $f ";
1881 (printdebug "only one dfi\n"), next if @dfi == 1;
1882 (printdebug "not tar\n"), next unless $f =~ m/\.tar(\.\w+)?$/;
1883 (printdebug "signature\n"), next if $f =~ m/$orig_f_sig_re$/o;
1887 $f =~ m/^\Q$orig_f_base\E\.([^._]+)?\.tar(?:\.\w+)?$/;
1889 printdebug "Y ", (join ' ', map { $_//"(none)" }
1890 $compr_ext, $orig_f_part
1893 my $input = new IO::File $f, '<' or die "$f $!";
1897 if (defined $compr_ext) {
1899 Dpkg::Compression::compression_guess_from_filename $f;
1900 fail "Dpkg::Compression cannot handle file $f in source package"
1901 if defined $compr_ext && !defined $cname;
1903 new Dpkg::Compression::Process compression => $cname;
1904 my @compr_cmd = $compr_proc->get_uncompress_cmdline();
1905 my $compr_fh = new IO::Handle;
1906 my $compr_pid = open $compr_fh, "-|" // die $!;
1908 open STDIN, "<&", $input or die $!;
1910 die "dgit (child): exec $compr_cmd[0]: $!\n";
1915 rmtree "../unpack-tar";
1916 mkdir "../unpack-tar" or die $!;
1917 my @tarcmd = qw(tar -x -f -
1918 --no-same-owner --no-same-permissions
1919 --no-acls --no-xattrs --no-selinux);
1920 my $tar_pid = fork // die $!;
1922 chdir "../unpack-tar" or die $!;
1923 open STDIN, "<&", $input or die $!;
1925 die "dgit (child): exec $tarcmd[0]: $!";
1927 $!=0; (waitpid $tar_pid, 0) == $tar_pid or die $!;
1928 !$? or failedcmd @tarcmd;
1931 (@compr_cmd ? failedcmd @compr_cmd
1933 # finally, we have the results in "tarball", but maybe
1934 # with the wrong permissions
1936 runcmd qw(chmod -R +rwX ../unpack-tar);
1937 changedir "../unpack-tar";
1938 my ($tree) = mktree_in_ud_from_only_subdir(1);
1939 changedir "../../unpack";
1940 rmtree "../unpack-tar";
1942 my $ent = [ $f, $tree ];
1944 Orig => !!$orig_f_part,
1945 Sort => (!$orig_f_part ? 2 :
1946 $orig_f_part =~ m/-/g ? 1 :
1954 # put any without "_" first (spec is not clear whether files
1955 # are always in the usual order). Tarballs without "_" are
1956 # the main orig or the debian tarball.
1957 $a->{Sort} <=> $b->{Sort} or
1961 my $any_orig = grep { $_->{Orig} } @tartrees;
1963 my $dscfn = "$package.dsc";
1965 my $treeimporthow = 'package';
1967 open D, ">", $dscfn or die "$dscfn: $!";
1968 print D $dscdata or die "$dscfn: $!";
1969 close D or die "$dscfn: $!";
1970 my @cmd = qw(dpkg-source);
1971 push @cmd, '--no-check' if $dsc_checked;
1972 if (madformat $dsc->{format}) {
1973 push @cmd, '--skip-patches';
1974 $treeimporthow = 'unpatched';
1976 push @cmd, qw(-x --), $dscfn;
1979 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1980 if (madformat $dsc->{format}) {
1981 check_for_vendor_patches();
1985 if (madformat $dsc->{format}) {
1986 my @pcmd = qw(dpkg-source --before-build .);
1987 runcmd shell_cmd 'exec >/dev/null', @pcmd;
1989 runcmd @git, qw(add -Af);
1990 $dappliedtree = git_write_tree();
1993 my @clogcmd = qw(dpkg-parsechangelog --format rfc822 --all);
1994 debugcmd "|",@clogcmd;
1995 open CLOGS, "-|", @clogcmd or die $!;
2000 printdebug "import clog search...\n";
2003 my $stanzatext = do { local $/=""; <CLOGS>; };
2004 printdebug "import clogp ".Dumper($stanzatext) if $debuglevel>1;
2005 last if !defined $stanzatext;
2007 my $desc = "package changelog, entry no.$.";
2008 open my $stanzafh, "<", \$stanzatext or die;
2009 my $thisstanza = parsecontrolfh $stanzafh, $desc, 1;
2010 $clogp //= $thisstanza;
2012 printdebug "import clog $thisstanza->{version} $desc...\n";
2014 last if !$any_orig; # we don't need $r1clogp
2016 # We look for the first (most recent) changelog entry whose
2017 # version number is lower than the upstream version of this
2018 # package. Then the last (least recent) previous changelog
2019 # entry is treated as the one which introduced this upstream
2020 # version and used for the synthetic commits for the upstream
2023 # One might think that a more sophisticated algorithm would be
2024 # necessary. But: we do not want to scan the whole changelog
2025 # file. Stopping when we see an earlier version, which
2026 # necessarily then is an earlier upstream version, is the only
2027 # realistic way to do that. Then, either the earliest
2028 # changelog entry we have seen so far is indeed the earliest
2029 # upload of this upstream version; or there are only changelog
2030 # entries relating to later upstream versions (which is not
2031 # possible unless the changelog and .dsc disagree about the
2032 # version). Then it remains to choose between the physically
2033 # last entry in the file, and the one with the lowest version
2034 # number. If these are not the same, we guess that the
2035 # versions were created in a non-monotic order rather than
2036 # that the changelog entries have been misordered.
2038 printdebug "import clog $thisstanza->{version} vs $upstreamv...\n";
2040 last if version_compare($thisstanza->{version}, $upstreamv) < 0;
2041 $r1clogp = $thisstanza;
2043 printdebug "import clog $r1clogp->{version} becomes r1\n";
2045 die $! if CLOGS->error;
2046 close CLOGS or $?==SIGPIPE or failedcmd @clogcmd;
2048 $clogp or fail "package changelog has no entries!";
2050 my $authline = clogp_authline $clogp;
2051 my $changes = getfield $clogp, 'Changes';
2052 my $cversion = getfield $clogp, 'Version';
2055 $r1clogp //= $clogp; # maybe there's only one entry;
2056 my $r1authline = clogp_authline $r1clogp;
2057 # Strictly, r1authline might now be wrong if it's going to be
2058 # unused because !$any_orig. Whatever.
2060 printdebug "import tartrees authline $authline\n";
2061 printdebug "import tartrees r1authline $r1authline\n";
2063 foreach my $tt (@tartrees) {
2064 printdebug "import tartree $tt->{F} $tt->{Tree}\n";
2066 $tt->{Commit} = make_commit_text($tt->{Orig} ? <<END_O : <<END_T);
2069 committer $r1authline
2073 [dgit import orig $tt->{F}]
2081 [dgit import tarball $package $cversion $tt->{F}]
2086 printdebug "import main commit\n";
2088 open C, ">../commit.tmp" or die $!;
2089 print C <<END or die $!;
2092 print C <<END or die $! foreach @tartrees;
2095 print C <<END or die $!;
2101 [dgit import $treeimporthow $package $cversion]
2105 my $rawimport_hash = make_commit qw(../commit.tmp);
2107 if (madformat $dsc->{format}) {
2108 printdebug "import apply patches...\n";
2110 # regularise the state of the working tree so that
2111 # the checkout of $rawimport_hash works nicely.
2112 my $dappliedcommit = make_commit_text(<<END);
2119 runcmd @git, qw(checkout -q -b dapplied), $dappliedcommit;
2121 runcmd @git, qw(checkout -q -b unpa), $rawimport_hash;
2123 # We need the answers to be reproducible
2124 my @authline = clogp_authline($clogp);
2125 local $ENV{GIT_COMMITTER_NAME} = $authline[0];
2126 local $ENV{GIT_COMMITTER_EMAIL} = $authline[1];
2127 local $ENV{GIT_COMMITTER_DATE} = $authline[2];
2128 local $ENV{GIT_AUTHOR_NAME} = $authline[0];
2129 local $ENV{GIT_AUTHOR_EMAIL} = $authline[1];
2130 local $ENV{GIT_AUTHOR_DATE} = $authline[2];
2132 my $path = $ENV{PATH} or die;
2134 foreach my $use_absurd (qw(0 1)) {
2135 local $ENV{PATH} = $path;
2138 progress "warning: $@";
2139 $path = "$absurdity:$path";
2140 progress "$us: trying slow absurd-git-apply...";
2141 rename "../../gbp-pq-output","../../gbp-pq-output.0"
2146 die "forbid absurd git-apply\n" if $use_absurd
2147 && forceing [qw(import-gitapply-no-absurd)];
2148 die "only absurd git-apply!\n" if !$use_absurd
2149 && forceing [qw(import-gitapply-absurd)];
2151 local $ENV{PATH} = $path if $use_absurd;
2153 my @showcmd = (gbp_pq, qw(import));
2154 my @realcmd = shell_cmd
2155 'exec >/dev/null 2>../../gbp-pq-output', @showcmd;
2156 debugcmd "+",@realcmd;
2157 if (system @realcmd) {
2158 die +(shellquote @showcmd).
2160 failedcmd_waitstatus()."\n";
2163 my $gapplied = git_rev_parse('HEAD');
2164 my $gappliedtree = cmdoutput @git, qw(rev-parse HEAD:);
2165 $gappliedtree eq $dappliedtree or
2167 gbp-pq import and dpkg-source disagree!
2168 gbp-pq import gave commit $gapplied
2169 gbp-pq import gave tree $gappliedtree
2170 dpkg-source --before-build gave tree $dappliedtree
2172 $rawimport_hash = $gapplied;
2177 { local $@; eval { runcmd qw(cat ../../gbp-pq-output); }; }
2182 progress "synthesised git commit from .dsc $cversion";
2184 my $rawimport_mergeinput = {
2185 Commit => $rawimport_hash,
2186 Info => "Import of source package",
2188 my @output = ($rawimport_mergeinput);
2190 if ($lastpush_mergeinput) {
2191 my $oldclogp = mergeinfo_getclogp($lastpush_mergeinput);
2192 my $oversion = getfield $oldclogp, 'Version';
2194 version_compare($oversion, $cversion);
2196 @output = ($rawimport_mergeinput, $lastpush_mergeinput,
2197 { Message => <<END, ReverseParents => 1 });
2198 Record $package ($cversion) in archive suite $csuite
2200 } elsif ($vcmp > 0) {
2201 print STDERR <<END or die $!;
2203 Version actually in archive: $cversion (older)
2204 Last version pushed with dgit: $oversion (newer or same)
2207 @output = $lastpush_mergeinput;
2209 # Same version. Use what's in the server git branch,
2210 # discarding our own import. (This could happen if the
2211 # server automatically imports all packages into git.)
2212 @output = $lastpush_mergeinput;
2215 changedir '../../../..';
2220 sub complete_file_from_dsc ($$) {
2221 our ($dstdir, $fi) = @_;
2222 # Ensures that we have, in $dir, the file $fi, with the correct
2223 # contents. (Downloading it from alongside $dscurl if necessary.)
2225 my $f = $fi->{Filename};
2226 my $tf = "$dstdir/$f";
2229 if (stat_exists $tf) {
2230 progress "using existing $f";
2232 printdebug "$tf does not exist, need to fetch\n";
2234 $furl =~ s{/[^/]+$}{};
2236 die "$f ?" unless $f =~ m/^\Q${package}\E_/;
2237 die "$f ?" if $f =~ m#/#;
2238 runcmd_ordryrun_local @curl,qw(-f -o),$tf,'--',"$furl";
2239 return 0 if !act_local();
2243 open F, "<", "$tf" or die "$tf: $!";
2244 $fi->{Digester}->reset();
2245 $fi->{Digester}->addfile(*F);
2246 F->error and die $!;
2247 my $got = $fi->{Digester}->hexdigest();
2248 $got eq $fi->{Hash} or
2249 fail "file $f has hash $got but .dsc".
2250 " demands hash $fi->{Hash} ".
2251 ($downloaded ? "(got wrong file from archive!)"
2252 : "(perhaps you should delete this file?)");
2257 sub ensure_we_have_orig () {
2258 my @dfi = dsc_files_info();
2259 foreach my $fi (@dfi) {
2260 my $f = $fi->{Filename};
2261 next unless is_orig_file_in_dsc($f, \@dfi);
2262 complete_file_from_dsc('..', $fi)
2267 sub git_fetch_us () {
2268 # Want to fetch only what we are going to use, unless
2269 # deliberately-not-ff, in which case we must fetch everything.
2271 my @specs = deliberately_not_fast_forward ? qw(tags/*) :
2273 (quiltmode_splitbrain
2274 ? (map { $_->('*',access_basedistro) }
2275 \&debiantag_new, \&debiantag_maintview)
2276 : debiantags('*',access_basedistro));
2277 push @specs, server_branch($csuite);
2278 push @specs, qw(heads/*) if deliberately_not_fast_forward;
2280 # This is rather miserable:
2281 # When git fetch --prune is passed a fetchspec ending with a *,
2282 # it does a plausible thing. If there is no * then:
2283 # - it matches subpaths too, even if the supplied refspec
2284 # starts refs, and behaves completely madly if the source
2285 # has refs/refs/something. (See, for example, Debian #NNNN.)
2286 # - if there is no matching remote ref, it bombs out the whole
2288 # We want to fetch a fixed ref, and we don't know in advance
2289 # if it exists, so this is not suitable.
2291 # Our workaround is to use git ls-remote. git ls-remote has its
2292 # own qairks. Notably, it has the absurd multi-tail-matching
2293 # behaviour: git ls-remote R refs/foo can report refs/foo AND
2294 # refs/refs/foo etc.
2296 # Also, we want an idempotent snapshot, but we have to make two
2297 # calls to the remote: one to git ls-remote and to git fetch. The
2298 # solution is use git ls-remote to obtain a target state, and
2299 # git fetch to try to generate it. If we don't manage to generate
2300 # the target state, we try again.
2302 printdebug "git_fetch_us specs @specs\n";
2304 my $specre = join '|', map {
2310 printdebug "git_fetch_us specre=$specre\n";
2311 my $wanted_rref = sub {
2313 return m/^(?:$specre)$/o;
2316 my $fetch_iteration = 0;
2319 printdebug "git_fetch_us iteration $fetch_iteration\n";
2320 if (++$fetch_iteration > 10) {
2321 fail "too many iterations trying to get sane fetch!";
2324 my @look = map { "refs/$_" } @specs;
2325 my @lcmd = (@git, qw(ls-remote -q --refs), access_giturl(), @look);
2329 open GITLS, "-|", @lcmd or die $!;
2331 printdebug "=> ", $_;
2332 m/^(\w+)\s+(\S+)\n/ or die "ls-remote $_ ?";
2333 my ($objid,$rrefname) = ($1,$2);
2334 if (!$wanted_rref->($rrefname)) {
2336 warning: git ls-remote @look reported $rrefname; this is silly, ignoring it.
2340 $wantr{$rrefname} = $objid;
2343 close GITLS or failedcmd @lcmd;
2345 # OK, now %want is exactly what we want for refs in @specs
2347 !m/\*$/ && !exists $wantr{"refs/$_"} ? () :
2348 "+refs/$_:".lrfetchrefs."/$_";
2351 printdebug "git_fetch_us fspecs @fspecs\n";
2353 my @fcmd = (@git, qw(fetch -p -n -q), access_giturl(), @fspecs);
2354 runcmd_ordryrun_local @git, qw(fetch -p -n -q), access_giturl(),
2357 %lrfetchrefs_f = ();
2360 git_for_each_ref(lrfetchrefs, sub {
2361 my ($objid,$objtype,$lrefname,$reftail) = @_;
2362 $lrfetchrefs_f{$lrefname} = $objid;
2363 $objgot{$objid} = 1;
2366 foreach my $lrefname (sort keys %lrfetchrefs_f) {
2367 my $rrefname = 'refs'.substr($lrefname, length lrfetchrefs);
2368 if (!exists $wantr{$rrefname}) {
2369 if ($wanted_rref->($rrefname)) {
2371 git-fetch @fspecs created $lrefname which git ls-remote @look didn't list.
2375 warning: git fetch @fspecs created $lrefname; this is silly, deleting it.
2378 runcmd_ordryrun_local @git, qw(update-ref -d), $lrefname;
2379 delete $lrfetchrefs_f{$lrefname};
2383 foreach my $rrefname (sort keys %wantr) {
2384 my $lrefname = lrfetchrefs.substr($rrefname, 4);
2385 my $got = $lrfetchrefs_f{$lrefname} // '<none>';
2386 my $want = $wantr{$rrefname};
2387 next if $got eq $want;
2388 if (!defined $objgot{$want}) {
2390 warning: git ls-remote suggests we want $lrefname
2391 warning: and it should refer to $want
2392 warning: but git fetch didn't fetch that object to any relevant ref.
2393 warning: This may be due to a race with someone updating the server.
2394 warning: Will try again...
2396 next FETCH_ITERATION;
2399 git-fetch @fspecs made $lrefname=$got but want git ls-remote @look says $want
2401 runcmd_ordryrun_local @git, qw(update-ref -m),
2402 "dgit fetch git fetch fixup", $lrefname, $want;
2403 $lrfetchrefs_f{$lrefname} = $want;
2407 printdebug "git_fetch_us: git fetch --no-insane emulation complete\n",
2408 Dumper(\%lrfetchrefs_f);
2411 my @tagpats = debiantags('*',access_basedistro);
2413 git_for_each_ref([map { "refs/tags/$_" } @tagpats], sub {
2414 my ($objid,$objtype,$fullrefname,$reftail) = @_;
2415 printdebug "currently $fullrefname=$objid\n";
2416 $here{$fullrefname} = $objid;
2418 git_for_each_ref([map { lrfetchrefs."/tags/".$_ } @tagpats], sub {
2419 my ($objid,$objtype,$fullrefname,$reftail) = @_;
2420 my $lref = "refs".substr($fullrefname, length(lrfetchrefs));
2421 printdebug "offered $lref=$objid\n";
2422 if (!defined $here{$lref}) {
2423 my @upd = (@git, qw(update-ref), $lref, $objid, '');
2424 runcmd_ordryrun_local @upd;
2425 lrfetchref_used $fullrefname;
2426 } elsif ($here{$lref} eq $objid) {
2427 lrfetchref_used $fullrefname;
2430 "Not updateting $lref from $here{$lref} to $objid.\n";
2435 sub mergeinfo_getclogp ($) {
2436 # Ensures thit $mi->{Clogp} exists and returns it
2438 $mi->{Clogp} = commit_getclogp($mi->{Commit});
2441 sub mergeinfo_version ($) {
2442 return getfield( (mergeinfo_getclogp $_[0]), 'Version' );
2445 sub fetch_from_archive () {
2446 ensure_setup_existing_tree();
2448 # Ensures that lrref() is what is actually in the archive, one way
2449 # or another, according to us - ie this client's
2450 # appropritaely-updated archive view. Also returns the commit id.
2451 # If there is nothing in the archive, leaves lrref alone and
2452 # returns undef. git_fetch_us must have already been called.
2456 foreach my $field (@ourdscfield) {
2457 $dsc_hash = $dsc->{$field};
2458 last if defined $dsc_hash;
2460 if (defined $dsc_hash) {
2461 $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
2463 progress "last upload to archive specified git hash";
2465 progress "last upload to archive has NO git hash";
2468 progress "no version available from the archive";
2471 # If the archive's .dsc has a Dgit field, there are three
2472 # relevant git commitids we need to choose between and/or merge
2474 # 1. $dsc_hash: the Dgit field from the archive
2475 # 2. $lastpush_hash: the suite branch on the dgit git server
2476 # 3. $lastfetch_hash: our local tracking brach for the suite
2478 # These may all be distinct and need not be in any fast forward
2481 # If the dsc was pushed to this suite, then the server suite
2482 # branch will have been updated; but it might have been pushed to
2483 # a different suite and copied by the archive. Conversely a more
2484 # recent version may have been pushed with dgit but not appeared
2485 # in the archive (yet).
2487 # $lastfetch_hash may be awkward because archive imports
2488 # (particularly, imports of Dgit-less .dscs) are performed only as
2489 # needed on individual clients, so different clients may perform a
2490 # different subset of them - and these imports are only made
2491 # public during push. So $lastfetch_hash may represent a set of
2492 # imports different to a subsequent upload by a different dgit
2495 # Our approach is as follows:
2497 # As between $dsc_hash and $lastpush_hash: if $lastpush_hash is a
2498 # descendant of $dsc_hash, then it was pushed by a dgit user who
2499 # had based their work on $dsc_hash, so we should prefer it.
2500 # Otherwise, $dsc_hash was installed into this suite in the
2501 # archive other than by a dgit push, and (necessarily) after the
2502 # last dgit push into that suite (since a dgit push would have
2503 # been descended from the dgit server git branch); thus, in that
2504 # case, we prefer the archive's version (and produce a
2505 # pseudo-merge to overwrite the dgit server git branch).
2507 # (If there is no Dgit field in the archive's .dsc then
2508 # generate_commit_from_dsc uses the version numbers to decide
2509 # whether the suite branch or the archive is newer. If the suite
2510 # branch is newer it ignores the archive's .dsc; otherwise it
2511 # generates an import of the .dsc, and produces a pseudo-merge to
2512 # overwrite the suite branch with the archive contents.)
2514 # The outcome of that part of the algorithm is the `public view',
2515 # and is same for all dgit clients: it does not depend on any
2516 # unpublished history in the local tracking branch.
2518 # As between the public view and the local tracking branch: The
2519 # local tracking branch is only updated by dgit fetch, and
2520 # whenever dgit fetch runs it includes the public view in the
2521 # local tracking branch. Therefore if the public view is not
2522 # descended from the local tracking branch, the local tracking
2523 # branch must contain history which was imported from the archive
2524 # but never pushed; and, its tip is now out of date. So, we make
2525 # a pseudo-merge to overwrite the old imports and stitch the old
2528 # Finally: we do not necessarily reify the public view (as
2529 # described above). This is so that we do not end up stacking two
2530 # pseudo-merges. So what we actually do is figure out the inputs
2531 # to any public view pseudo-merge and put them in @mergeinputs.
2534 # $mergeinputs[]{Commit}
2535 # $mergeinputs[]{Info}
2536 # $mergeinputs[0] is the one whose tree we use
2537 # @mergeinputs is in the order we use in the actual commit)
2540 # $mergeinputs[]{Message} is a commit message to use
2541 # $mergeinputs[]{ReverseParents} if def specifies that parent
2542 # list should be in opposite order
2543 # Such an entry has no Commit or Info. It applies only when found
2544 # in the last entry. (This ugliness is to support making
2545 # identical imports to previous dgit versions.)
2547 my $lastpush_hash = git_get_ref(lrfetchref());
2548 printdebug "previous reference hash=$lastpush_hash\n";
2549 $lastpush_mergeinput = $lastpush_hash && {
2550 Commit => $lastpush_hash,
2551 Info => "dgit suite branch on dgit git server",
2554 my $lastfetch_hash = git_get_ref(lrref());
2555 printdebug "fetch_from_archive: lastfetch=$lastfetch_hash\n";
2556 my $lastfetch_mergeinput = $lastfetch_hash && {
2557 Commit => $lastfetch_hash,
2558 Info => "dgit client's archive history view",
2561 my $dsc_mergeinput = $dsc_hash && {
2562 Commit => $dsc_hash,
2563 Info => "Dgit field in .dsc from archive",
2567 my $del_lrfetchrefs = sub {
2570 printdebug "del_lrfetchrefs...\n";
2571 foreach my $fullrefname (sort keys %lrfetchrefs_d) {
2572 my $objid = $lrfetchrefs_d{$fullrefname};
2573 printdebug "del_lrfetchrefs: $objid $fullrefname\n";
2575 $gur ||= new IO::Handle;
2576 open $gur, "|-", qw(git update-ref --stdin) or die $!;
2578 printf $gur "delete %s %s\n", $fullrefname, $objid;
2581 close $gur or failedcmd "git update-ref delete lrfetchrefs";
2585 if (defined $dsc_hash) {
2586 ensure_we_have_orig();
2587 if (!$lastpush_hash || $dsc_hash eq $lastpush_hash) {
2588 @mergeinputs = $dsc_mergeinput
2589 } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
2590 print STDERR <<END or die $!;
2592 Git commit in archive is behind the last version allegedly pushed/uploaded.
2593 Commit referred to by archive: $dsc_hash
2594 Last version pushed with dgit: $lastpush_hash
2597 @mergeinputs = ($lastpush_mergeinput);
2599 # Archive has .dsc which is not a descendant of the last dgit
2600 # push. This can happen if the archive moves .dscs about.
2601 # Just follow its lead.
2602 if (is_fast_fwd($lastpush_hash,$dsc_hash)) {
2603 progress "archive .dsc names newer git commit";
2604 @mergeinputs = ($dsc_mergeinput);
2606 progress "archive .dsc names other git commit, fixing up";
2607 @mergeinputs = ($dsc_mergeinput, $lastpush_mergeinput);
2611 @mergeinputs = generate_commits_from_dsc();
2612 # We have just done an import. Now, our import algorithm might
2613 # have been improved. But even so we do not want to generate
2614 # a new different import of the same package. So if the
2615 # version numbers are the same, just use our existing version.
2616 # If the version numbers are different, the archive has changed
2617 # (perhaps, rewound).
2618 if ($lastfetch_mergeinput &&
2619 !version_compare( (mergeinfo_version $lastfetch_mergeinput),
2620 (mergeinfo_version $mergeinputs[0]) )) {
2621 @mergeinputs = ($lastfetch_mergeinput);
2623 } elsif ($lastpush_hash) {
2624 # only in git, not in the archive yet
2625 @mergeinputs = ($lastpush_mergeinput);
2626 print STDERR <<END or die $!;
2628 Package not found in the archive, but has allegedly been pushed using dgit.
2632 printdebug "nothing found!\n";
2633 if (defined $skew_warning_vsn) {
2634 print STDERR <<END or die $!;
2636 Warning: relevant archive skew detected.
2637 Archive allegedly contains $skew_warning_vsn
2638 But we were not able to obtain any version from the archive or git.
2642 unshift @end, $del_lrfetchrefs;
2646 if ($lastfetch_hash &&
2648 my $h = $_->{Commit};
2649 $h and is_fast_fwd($lastfetch_hash, $h);
2650 # If true, one of the existing parents of this commit
2651 # is a descendant of the $lastfetch_hash, so we'll
2652 # be ff from that automatically.
2656 push @mergeinputs, $lastfetch_mergeinput;
2659 printdebug "fetch mergeinfos:\n";
2660 foreach my $mi (@mergeinputs) {
2662 printdebug " commit $mi->{Commit} $mi->{Info}\n";
2664 printdebug sprintf " ReverseParents=%d Message=%s",
2665 $mi->{ReverseParents}, $mi->{Message};
2669 my $compat_info= pop @mergeinputs
2670 if $mergeinputs[$#mergeinputs]{Message};
2672 @mergeinputs = grep { defined $_->{Commit} } @mergeinputs;
2675 if (@mergeinputs > 1) {
2677 my $tree_commit = $mergeinputs[0]{Commit};
2679 my $tree = cmdoutput @git, qw(cat-file commit), $tree_commit;
2680 $tree =~ m/\n\n/; $tree = $`;
2681 $tree =~ m/^tree (\w+)$/m or die "$dsc_hash tree ?";
2684 # We use the changelog author of the package in question the
2685 # author of this pseudo-merge. This is (roughly) correct if
2686 # this commit is simply representing aa non-dgit upload.
2687 # (Roughly because it does not record sponsorship - but we
2688 # don't have sponsorship info because that's in the .changes,
2689 # which isn't in the archivw.)
2691 # But, it might be that we are representing archive history
2692 # updates (including in-archive copies). These are not really
2693 # the responsibility of the person who created the .dsc, but
2694 # there is no-one whose name we should better use. (The
2695 # author of the .dsc-named commit is clearly worse.)
2697 my $useclogp = mergeinfo_getclogp $mergeinputs[0];
2698 my $author = clogp_authline $useclogp;
2699 my $cversion = getfield $useclogp, 'Version';
2701 my $mcf = ".git/dgit/mergecommit";
2702 open MC, ">", $mcf or die "$mcf $!";
2703 print MC <<END or die $!;
2707 my @parents = grep { $_->{Commit} } @mergeinputs;
2708 @parents = reverse @parents if $compat_info->{ReverseParents};
2709 print MC <<END or die $! foreach @parents;
2713 print MC <<END or die $!;
2719 if (defined $compat_info->{Message}) {
2720 print MC $compat_info->{Message} or die $!;
2722 print MC <<END or die $!;
2723 Record $package ($cversion) in archive suite $csuite
2727 my $message_add_info = sub {
2729 my $mversion = mergeinfo_version $mi;
2730 printf MC " %-20s %s\n", $mversion, $mi->{Info}
2734 $message_add_info->($mergeinputs[0]);
2735 print MC <<END or die $!;
2736 should be treated as descended from
2738 $message_add_info->($_) foreach @mergeinputs[1..$#mergeinputs];
2742 $hash = make_commit $mcf;
2744 $hash = $mergeinputs[0]{Commit};
2746 printdebug "fetch hash=$hash\n";
2749 my ($lasth, $what) = @_;
2750 return unless $lasth;
2751 die "$lasth $hash $what ?" unless is_fast_fwd($lasth, $hash);
2754 $chkff->($lastpush_hash, 'dgit repo server tip (last push)')
2756 $chkff->($lastfetch_hash, 'local tracking tip (last fetch)');
2758 runcmd @git, qw(update-ref -m), "dgit fetch $csuite",
2759 'DGIT_ARCHIVE', $hash;
2760 cmdoutput @git, qw(log -n2), $hash;
2761 # ... gives git a chance to complain if our commit is malformed
2763 if (defined $skew_warning_vsn) {
2765 printdebug "SKEW CHECK WANT $skew_warning_vsn\n";
2766 my $gotclogp = commit_getclogp($hash);
2767 my $got_vsn = getfield $gotclogp, 'Version';
2768 printdebug "SKEW CHECK GOT $got_vsn\n";
2769 if (version_compare($got_vsn, $skew_warning_vsn) < 0) {
2770 print STDERR <<END or die $!;
2772 Warning: archive skew detected. Using the available version:
2773 Archive allegedly contains $skew_warning_vsn
2774 We were able to obtain only $got_vsn
2780 if ($lastfetch_hash ne $hash) {
2781 my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
2785 dryrun_report @upd_cmd;
2789 lrfetchref_used lrfetchref();
2791 unshift @end, $del_lrfetchrefs;
2795 sub set_local_git_config ($$) {
2797 runcmd @git, qw(config), $k, $v;
2800 sub setup_mergechangelogs (;$) {
2802 return unless $always || access_cfg_bool(1, 'setup-mergechangelogs');
2804 my $driver = 'dpkg-mergechangelogs';
2805 my $cb = "merge.$driver";
2806 my $attrs = '.git/info/attributes';
2807 ensuredir '.git/info';
2809 open NATTRS, ">", "$attrs.new" or die "$attrs.new $!";
2810 if (!open ATTRS, "<", $attrs) {
2811 $!==ENOENT or die "$attrs: $!";
2815 next if m{^debian/changelog\s};
2816 print NATTRS $_, "\n" or die $!;
2818 ATTRS->error and die $!;
2821 print NATTRS "debian/changelog merge=$driver\n" or die $!;
2824 set_local_git_config "$cb.name", 'debian/changelog merge driver';
2825 set_local_git_config "$cb.driver", 'dpkg-mergechangelogs -m %O %A %B %A';
2827 rename "$attrs.new", "$attrs" or die "$attrs: $!";
2830 sub setup_useremail (;$) {
2832 return unless $always || access_cfg_bool(1, 'setup-useremail');
2835 my ($k, $envvar) = @_;
2836 my $v = access_cfg("user-$k", 'RETURN-UNDEF') // $ENV{$envvar};
2837 return unless defined $v;
2838 set_local_git_config "user.$k", $v;
2841 $setup->('email', 'DEBEMAIL');
2842 $setup->('name', 'DEBFULLNAME');
2845 sub ensure_setup_existing_tree () {
2846 my $k = "remote.$remotename.skipdefaultupdate";
2847 my $c = git_get_config $k;
2848 return if defined $c;
2849 set_local_git_config $k, 'true';
2852 sub setup_new_tree () {
2853 setup_mergechangelogs();
2859 canonicalise_suite();
2860 badusage "dry run makes no sense with clone" unless act_local();
2861 my $hasgit = check_for_git();
2862 mkdir $dstdir or fail "create \`$dstdir': $!";
2864 runcmd @git, qw(init -q);
2865 my $giturl = access_giturl(1);
2866 if (defined $giturl) {
2867 open H, "> .git/HEAD" or die $!;
2868 print H "ref: ".lref()."\n" or die $!;
2870 runcmd @git, qw(remote add), 'origin', $giturl;
2873 progress "fetching existing git history";
2875 runcmd_ordryrun_local @git, qw(fetch origin);
2877 progress "starting new git history";
2879 fetch_from_archive() or no_such_package;
2880 my $vcsgiturl = $dsc->{'Vcs-Git'};
2881 if (length $vcsgiturl) {
2882 $vcsgiturl =~ s/\s+-b\s+\S+//g;
2883 runcmd @git, qw(remote add vcs-git), $vcsgiturl;
2886 runcmd @git, qw(reset --hard), lrref();
2887 runcmd qw(bash -ec), <<'END';
2889 git ls-tree -r --name-only -z HEAD | \
2890 xargs -0r touch -r . --
2892 printdone "ready for work in $dstdir";
2896 if (check_for_git()) {
2899 fetch_from_archive() or no_such_package();
2900 printdone "fetched into ".lrref();
2905 runcmd_ordryrun_local @git, qw(merge -m),"Merge from $csuite [dgit]",
2907 printdone "fetched to ".lrref()." and merged into HEAD";
2910 sub check_not_dirty () {
2911 foreach my $f (qw(local-options local-patch-header)) {
2912 if (stat_exists "debian/source/$f") {
2913 fail "git tree contains debian/source/$f";
2917 return if $ignoredirty;
2919 my @cmd = (@git, qw(diff --quiet HEAD));
2921 $!=0; $?=-1; system @cmd;
2924 fail "working tree is dirty (does not match HEAD)";
2930 sub commit_admin ($) {
2933 runcmd_ordryrun_local @git, qw(commit -m), $m;
2936 sub commit_quilty_patch () {
2937 my $output = cmdoutput @git, qw(status --porcelain);
2939 foreach my $l (split /\n/, $output) {
2940 next unless $l =~ m/\S/;
2941 if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
2945 delete $adds{'.pc'}; # if there wasn't one before, don't add it
2947 progress "nothing quilty to commit, ok.";
2950 my @adds = map { s/[][*?\\]/\\$&/g; $_; } sort keys %adds;
2951 runcmd_ordryrun_local @git, qw(add -f), @adds;
2953 Commit Debian 3.0 (quilt) metadata
2955 [dgit ($our_version) quilt-fixup]
2959 sub get_source_format () {
2961 if (open F, "debian/source/options") {
2965 s/\s+$//; # ignore missing final newline
2967 my ($k, $v) = ($`, $'); #');
2968 $v =~ s/^"(.*)"$/$1/;
2974 F->error and die $!;
2977 die $! unless $!==&ENOENT;
2980 if (!open F, "debian/source/format") {
2981 die $! unless $!==&ENOENT;
2985 F->error and die $!;
2987 return ($_, \%options);
2990 sub madformat_wantfixup ($) {
2992 return 0 unless $format eq '3.0 (quilt)';
2993 our $quilt_mode_warned;
2994 if ($quilt_mode eq 'nocheck') {
2995 progress "Not doing any fixup of \`$format' due to".
2996 " ----no-quilt-fixup or --quilt=nocheck"
2997 unless $quilt_mode_warned++;
3000 progress "Format \`$format', need to check/update patch stack"
3001 unless $quilt_mode_warned++;
3005 sub maybe_split_brain_save ($$$) {
3006 my ($headref, $dgitview, $msg) = @_;
3007 # => message fragment "$saved" describing disposition of $dgitview
3008 return "commit id $dgitview" unless defined $split_brain_save;
3009 my @cmd = (shell_cmd "cd ../../../..",
3010 @git, qw(update-ref -m),
3011 "dgit --dgit-view-save $msg HEAD=$headref",
3012 $split_brain_save, $dgitview);
3014 return "and left in $split_brain_save";
3017 # An "infopair" is a tuple [ $thing, $what ]
3018 # (often $thing is a commit hash; $what is a description)
3020 sub infopair_cond_equal ($$) {
3022 $x->[0] eq $y->[0] or fail <<END;
3023 $x->[1] ($x->[0]) not equal to $y->[1] ($y->[0])
3027 sub infopair_lrf_tag_lookup ($$) {
3028 my ($tagnames, $what) = @_;
3029 # $tagname may be an array ref
3030 my @tagnames = ref $tagnames ? @$tagnames : ($tagnames);
3031 printdebug "infopair_lrfetchref_tag_lookup $what @tagnames\n";
3032 foreach my $tagname (@tagnames) {
3033 my $lrefname = lrfetchrefs."/tags/$tagname";
3034 my $tagobj = $lrfetchrefs_f{$lrefname};
3035 next unless defined $tagobj;
3036 printdebug "infopair_lrfetchref_tag_lookup $tagobj $tagname $what\n";
3037 return [ git_rev_parse($tagobj), $what ];
3039 fail @tagnames==1 ? <<END : <<END;
3040 Wanted tag $what (@tagnames) on dgit server, but not found
3042 Wanted tag $what (one of: @tagnames) on dgit server, but not found
3046 sub infopair_cond_ff ($$) {
3047 my ($anc,$desc) = @_;
3048 is_fast_fwd($anc->[0], $desc->[0]) or fail <<END;
3049 $anc->[1] ($anc->[0]) .. $desc->[1] ($desc->[0]) is not fast forward
3053 sub pseudomerge_version_check ($$) {
3054 my ($clogp, $archive_hash) = @_;
3056 my $arch_clogp = commit_getclogp $archive_hash;
3057 my $i_arch_v = [ (getfield $arch_clogp, 'Version'),
3058 'version currently in archive' ];
3059 if (defined $overwrite_version) {
3060 if (length $overwrite_version) {
3061 infopair_cond_equal([ $overwrite_version,
3062 '--overwrite= version' ],
3065 my $v = $i_arch_v->[0];
3066 progress "Checking package changelog for archive version $v ...";
3068 my @xa = ("-f$v", "-t$v");
3069 my $vclogp = parsechangelog @xa;
3070 my $cv = [ (getfield $vclogp, 'Version'),
3071 "Version field from dpkg-parsechangelog @xa" ];
3072 infopair_cond_equal($i_arch_v, $cv);
3075 $@ =~ s/^dgit: //gm;
3077 "Perhaps debian/changelog does not mention $v ?";
3082 printdebug "pseudomerge_version_check i_arch_v @$i_arch_v\n";
3086 sub pseudomerge_make_commit ($$$$ $$) {
3087 my ($clogp, $dgitview, $archive_hash, $i_arch_v,
3088 $msg_cmd, $msg_msg) = @_;
3089 progress "Declaring that HEAD inciudes all changes in $i_arch_v->[0]...";
3091 my $tree = cmdoutput qw(git rev-parse), "${dgitview}:";
3092 my $authline = clogp_authline $clogp;
3096 !defined $overwrite_version ? ""
3097 : !length $overwrite_version ? " --overwrite"
3098 : " --overwrite=".$overwrite_version;
3101 my $pmf = ".git/dgit/pseudomerge";
3102 open MC, ">", $pmf or die "$pmf $!";
3103 print MC <<END or die $!;
3106 parent $archive_hash
3116 return make_commit($pmf);
3119 sub splitbrain_pseudomerge ($$$$) {
3120 my ($clogp, $maintview, $dgitview, $archive_hash) = @_;
3121 # => $merged_dgitview
3122 printdebug "splitbrain_pseudomerge...\n";
3124 # We: debian/PREVIOUS HEAD($maintview)
3125 # expect: o ----------------- o
3128 # a/d/PREVIOUS $dgitview
3131 # we do: `------------------ o
3135 return $dgitview unless defined $archive_hash;
3137 printdebug "splitbrain_pseudomerge...\n";
3139 my $i_arch_v = pseudomerge_version_check($clogp, $archive_hash);
3141 if (!defined $overwrite_version) {
3142 progress "Checking that HEAD inciudes all changes in archive...";
3145 return $dgitview if is_fast_fwd $archive_hash, $dgitview;
3147 if (defined $overwrite_version) {
3149 my $t_dep14 = debiantag_maintview $i_arch_v->[0], access_basedistro;
3150 my $i_dep14 = infopair_lrf_tag_lookup($t_dep14, "maintainer view tag");
3151 my $t_dgit = debiantag_new $i_arch_v->[0], access_basedistro;
3152 my $i_dgit = infopair_lrf_tag_lookup($t_dgit, "dgit view tag");
3153 my $i_archive = [ $archive_hash, "current archive contents" ];
3155 printdebug "splitbrain_pseudomerge i_archive @$i_archive\n";
3157 infopair_cond_equal($i_dgit, $i_archive);
3158 infopair_cond_ff($i_dep14, $i_dgit);
3159 infopair_cond_ff($i_dep14, [ $maintview, 'HEAD' ]);
3163 $us: check failed (maybe --overwrite is needed, consult documentation)
3168 my $r = pseudomerge_make_commit
3169 $clogp, $dgitview, $archive_hash, $i_arch_v,
3170 "dgit --quilt=$quilt_mode",
3171 (defined $overwrite_version ? <<END_OVERWR : <<END_MAKEFF);
3172 Declare fast forward from $i_arch_v->[0]
3174 Make fast forward from $i_arch_v->[0]
3177 maybe_split_brain_save $maintview, $r, "pseudomerge";
3179 progress "Made pseudo-merge of $i_arch_v->[0] into dgit view.";
3183 sub plain_overwrite_pseudomerge ($$$) {
3184 my ($clogp, $head, $archive_hash) = @_;
3186 printdebug "plain_overwrite_pseudomerge...";
3188 my $i_arch_v = pseudomerge_version_check($clogp, $archive_hash);
3190 return $head if is_fast_fwd $archive_hash, $head;
3192 my $m = "Declare fast forward from $i_arch_v->[0]";
3194 my $r = pseudomerge_make_commit
3195 $clogp, $head, $archive_hash, $i_arch_v,
3198 runcmd @git, qw(update-ref -m), $m, 'HEAD', $r, $head;
3200 progress "Make pseudo-merge of $i_arch_v->[0] into your HEAD.";
3204 sub push_parse_changelog ($) {
3207 my $clogp = Dpkg::Control::Hash->new();
3208 $clogp->load($clogpfn) or die;
3210 my $clogpackage = getfield $clogp, 'Source';
3211 $package //= $clogpackage;
3212 fail "-p specified $package but changelog specified $clogpackage"
3213 unless $package eq $clogpackage;
3214 my $cversion = getfield $clogp, 'Version';
3215 my $tag = debiantag($cversion, access_basedistro);
3216 runcmd @git, qw(check-ref-format), $tag;
3218 my $dscfn = dscfn($cversion);
3220 return ($clogp, $cversion, $dscfn);
3223 sub push_parse_dsc ($$$) {
3224 my ($dscfn,$dscfnwhat, $cversion) = @_;
3225 $dsc = parsecontrol($dscfn,$dscfnwhat);
3226 my $dversion = getfield $dsc, 'Version';
3227 my $dscpackage = getfield $dsc, 'Source';
3228 ($dscpackage eq $package && $dversion eq $cversion) or
3229 fail "$dscfn is for $dscpackage $dversion".
3230 " but debian/changelog is for $package $cversion";
3233 sub push_tagwants ($$$$) {
3234 my ($cversion, $dgithead, $maintviewhead, $tfbase) = @_;
3237 TagFn => \&debiantag,
3242 if (defined $maintviewhead) {
3244 TagFn => \&debiantag_maintview,
3245 Objid => $maintviewhead,
3246 TfSuffix => '-maintview',
3250 foreach my $tw (@tagwants) {
3251 $tw->{Tag} = $tw->{TagFn}($cversion, access_basedistro);
3252 $tw->{Tfn} = sub { $tfbase.$tw->{TfSuffix}.$_[0]; };
3254 printdebug 'push_tagwants: ', Dumper(\@_, \@tagwants);
3258 sub push_mktags ($$ $$ $) {
3260 $changesfile,$changesfilewhat,
3263 die unless $tagwants->[0]{View} eq 'dgit';
3265 $dsc->{$ourdscfield[0]} = $tagwants->[0]{Objid};
3266 $dsc->save("$dscfn.tmp") or die $!;
3268 my $changes = parsecontrol($changesfile,$changesfilewhat);
3269 foreach my $field (qw(Source Distribution Version)) {
3270 $changes->{$field} eq $clogp->{$field} or
3271 fail "changes field $field \`$changes->{$field}'".
3272 " does not match changelog \`$clogp->{$field}'";
3275 my $cversion = getfield $clogp, 'Version';
3276 my $clogsuite = getfield $clogp, 'Distribution';
3278 # We make the git tag by hand because (a) that makes it easier
3279 # to control the "tagger" (b) we can do remote signing
3280 my $authline = clogp_authline $clogp;
3281 my $delibs = join(" ", "",@deliberatelies);
3282 my $declaredistro = access_basedistro();
3286 my $tfn = $tw->{Tfn};
3287 my $head = $tw->{Objid};
3288 my $tag = $tw->{Tag};
3290 open TO, '>', $tfn->('.tmp') or die $!;
3291 print TO <<END or die $!;
3298 if ($tw->{View} eq 'dgit') {
3299 print TO <<END or die $!;
3300 $package release $cversion for $clogsuite ($csuite) [dgit]
3301 [dgit distro=$declaredistro$delibs]
3303 foreach my $ref (sort keys %previously) {
3304 print TO <<END or die $!;
3305 [dgit previously:$ref=$previously{$ref}]
3308 } elsif ($tw->{View} eq 'maint') {
3309 print TO <<END or die $!;
3310 $package release $cversion for $clogsuite ($csuite)
3311 (maintainer view tag generated by dgit --quilt=$quilt_mode)
3314 die Dumper($tw)."?";
3319 my $tagobjfn = $tfn->('.tmp');
3321 if (!defined $keyid) {
3322 $keyid = access_cfg('keyid','RETURN-UNDEF');
3324 if (!defined $keyid) {
3325 $keyid = getfield $clogp, 'Maintainer';
3327 unlink $tfn->('.tmp.asc') or $!==&ENOENT or die $!;
3328 my @sign_cmd = (@gpg, qw(--detach-sign --armor));
3329 push @sign_cmd, qw(-u),$keyid if defined $keyid;
3330 push @sign_cmd, $tfn->('.tmp');
3331 runcmd_ordryrun @sign_cmd;
3333 $tagobjfn = $tfn->('.signed.tmp');
3334 runcmd shell_cmd "exec >$tagobjfn", qw(cat --),
3335 $tfn->('.tmp'), $tfn->('.tmp.asc');
3341 my @r = map { $mktag->($_); } @$tagwants;
3345 sub sign_changes ($) {
3346 my ($changesfile) = @_;
3348 my @debsign_cmd = @debsign;
3349 push @debsign_cmd, "-k$keyid" if defined $keyid;
3350 push @debsign_cmd, "-p$gpg[0]" if $gpg[0] ne 'gpg';
3351 push @debsign_cmd, $changesfile;
3352 runcmd_ordryrun @debsign_cmd;
3357 printdebug "actually entering push\n";
3359 supplementary_message(<<'END');
3360 Push failed, while checking state of the archive.
3361 You can retry the push, after fixing the problem, if you like.
3363 if (check_for_git()) {
3366 my $archive_hash = fetch_from_archive();
3367 if (!$archive_hash) {
3369 fail "package appears to be new in this suite;".
3370 " if this is intentional, use --new";
3373 supplementary_message(<<'END');
3374 Push failed, while preparing your push.
3375 You can retry the push, after fixing the problem, if you like.
3378 need_tagformat 'new', "quilt mode $quilt_mode"
3379 if quiltmode_splitbrain;
3383 access_giturl(); # check that success is vaguely likely
3386 my $clogpfn = ".git/dgit/changelog.822.tmp";
3387 runcmd shell_cmd "exec >$clogpfn", qw(dpkg-parsechangelog);
3389 responder_send_file('parsed-changelog', $clogpfn);
3391 my ($clogp, $cversion, $dscfn) =
3392 push_parse_changelog("$clogpfn");
3394 my $dscpath = "$buildproductsdir/$dscfn";
3395 stat_exists $dscpath or
3396 fail "looked for .dsc $dscfn, but $!;".
3397 " maybe you forgot to build";
3399 responder_send_file('dsc', $dscpath);
3401 push_parse_dsc($dscpath, $dscfn, $cversion);
3403 my $format = getfield $dsc, 'Format';
3404 printdebug "format $format\n";
3406 my $actualhead = git_rev_parse('HEAD');
3407 my $dgithead = $actualhead;
3408 my $maintviewhead = undef;
3410 my $upstreamversion = upstreamversion $clogp->{Version};
3412 if (madformat_wantfixup($format)) {
3413 # user might have not used dgit build, so maybe do this now:
3414 if (quiltmode_splitbrain()) {
3416 quilt_make_fake_dsc($upstreamversion);
3418 ($dgithead, $cachekey) =
3419 quilt_check_splitbrain_cache($actualhead, $upstreamversion);
3421 "--quilt=$quilt_mode but no cached dgit view:
3422 perhaps tree changed since dgit build[-source] ?";
3424 $dgithead = splitbrain_pseudomerge($clogp,
3425 $actualhead, $dgithead,
3427 $maintviewhead = $actualhead;
3428 changedir '../../../..';
3429 prep_ud(); # so _only_subdir() works, below
3431 commit_quilty_patch();
3435 if (defined $overwrite_version && !defined $maintviewhead) {
3436 $dgithead = plain_overwrite_pseudomerge($clogp,
3444 if ($archive_hash) {
3445 if (is_fast_fwd($archive_hash, $dgithead)) {
3447 } elsif (deliberately_not_fast_forward) {
3450 fail "dgit push: HEAD is not a descendant".
3451 " of the archive's version.\n".
3452 "To overwrite the archive's contents,".
3453 " pass --overwrite[=VERSION].\n".
3454 "To rewind history, if permitted by the archive,".
3455 " use --deliberately-not-fast-forward.";
3460 progress "checking that $dscfn corresponds to HEAD";
3461 runcmd qw(dpkg-source -x --),
3462 $dscpath =~ m#^/# ? $dscpath : "../../../$dscpath";
3463 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
3464 check_for_vendor_patches() if madformat($dsc->{format});
3465 changedir '../../../..';
3466 my @diffcmd = (@git, qw(diff --quiet), $tree, $dgithead);
3467 debugcmd "+",@diffcmd;
3469 my $r = system @diffcmd;
3472 my $diffs = cmdoutput @git, qw(diff --stat), $tree, $dgithead;
3474 HEAD specifies a different tree to $dscfn:
3476 Perhaps you forgot to build. Or perhaps there is a problem with your
3477 source tree (see dgit(7) for some hints). To see a full diff, run
3484 if (!$changesfile) {
3485 my $pat = changespat $cversion;
3486 my @cs = glob "$buildproductsdir/$pat";
3487 fail "failed to find unique changes file".
3488 " (looked for $pat in $buildproductsdir);".
3489 " perhaps you need to use dgit -C"
3491 ($changesfile) = @cs;
3493 $changesfile = "$buildproductsdir/$changesfile";
3496 # Check that changes and .dsc agree enough
3497 $changesfile =~ m{[^/]*$};
3498 my $changes = parsecontrol($changesfile,$&);
3499 files_compare_inputs($dsc, $changes)
3500 unless forceing [qw(dsc-changes-mismatch)];
3502 # Perhaps adjust .dsc to contain right set of origs
3503 changes_update_origs_from_dsc($dsc, $changes, $upstreamversion,
3505 unless forceing [qw(changes-origs-exactly)];
3507 # Checks complete, we're going to try and go ahead:
3509 responder_send_file('changes',$changesfile);
3510 responder_send_command("param head $dgithead");
3511 responder_send_command("param csuite $csuite");
3512 responder_send_command("param tagformat $tagformat");
3513 if (defined $maintviewhead) {
3514 die unless ($protovsn//4) >= 4;
3515 responder_send_command("param maint-view $maintviewhead");
3518 if (deliberately_not_fast_forward) {
3519 git_for_each_ref(lrfetchrefs, sub {
3520 my ($objid,$objtype,$lrfetchrefname,$reftail) = @_;
3521 my $rrefname= substr($lrfetchrefname, length(lrfetchrefs) + 1);
3522 responder_send_command("previously $rrefname=$objid");
3523 $previously{$rrefname} = $objid;
3527 my @tagwants = push_tagwants($cversion, $dgithead, $maintviewhead,
3531 supplementary_message(<<'END');
3532 Push failed, while signing the tag.
3533 You can retry the push, after fixing the problem, if you like.
3535 # If we manage to sign but fail to record it anywhere, it's fine.
3536 if ($we_are_responder) {
3537 @tagobjfns = map { $_->{Tfn}('.signed-tmp') } @tagwants;
3538 responder_receive_files('signed-tag', @tagobjfns);
3540 @tagobjfns = push_mktags($clogp,$dscpath,
3541 $changesfile,$changesfile,
3544 supplementary_message(<<'END');
3545 Push failed, *after* signing the tag.
3546 If you want to try again, you should use a new version number.
3549 pairwise { $a->{TagObjFn} = $b } @tagwants, @tagobjfns;
3551 foreach my $tw (@tagwants) {
3552 my $tag = $tw->{Tag};
3553 my $tagobjfn = $tw->{TagObjFn};
3555 cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
3556 runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
3557 runcmd_ordryrun_local
3558 @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
3561 supplementary_message(<<'END');
3562 Push failed, while updating the remote git repository - see messages above.
3563 If you want to try again, you should use a new version number.
3565 if (!check_for_git()) {
3566 create_remote_git_repo();
3569 my @pushrefs = $forceflag.$dgithead.":".rrref();
3570 foreach my $tw (@tagwants) {
3571 push @pushrefs, $forceflag."refs/tags/$tw->{Tag}";
3574 runcmd_ordryrun @git,
3575 qw(-c push.followTags=false push), access_giturl(), @pushrefs;
3576 runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), $dgithead;
3578 supplementary_message(<<'END');
3579 Push failed, after updating the remote git repository.
3580 If you want to try again, you must use a new version number.
3582 if ($we_are_responder) {
3583 my $dryrunsuffix = act_local() ? "" : ".tmp";
3584 responder_receive_files('signed-dsc-changes',
3585 "$dscpath$dryrunsuffix",
3586 "$changesfile$dryrunsuffix");
3589 rename "$dscpath.tmp",$dscpath or die "$dscfn $!";
3591 progress "[new .dsc left in $dscpath.tmp]";
3593 sign_changes $changesfile;
3596 supplementary_message(<<END);
3597 Push failed, while uploading package(s) to the archive server.
3598 You can retry the upload of exactly these same files with dput of:
3600 If that .changes file is broken, you will need to use a new version
3601 number for your next attempt at the upload.
3603 my $host = access_cfg('upload-host','RETURN-UNDEF');
3604 my @hostarg = defined($host) ? ($host,) : ();
3605 runcmd_ordryrun @dput, @hostarg, $changesfile;
3606 printdone "pushed and uploaded $cversion";
3608 supplementary_message('');
3609 responder_send_command("complete");
3616 badusage "-p is not allowed with clone; specify as argument instead"
3617 if defined $package;
3620 } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
3621 ($package,$isuite) = @ARGV;
3622 } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
3623 ($package,$dstdir) = @ARGV;
3624 } elsif (@ARGV==3) {
3625 ($package,$isuite,$dstdir) = @ARGV;
3627 badusage "incorrect arguments to dgit clone";
3629 $dstdir ||= "$package";
3631 if (stat_exists $dstdir) {
3632 fail "$dstdir already exists";
3636 if ($rmonerror && !$dryrun_level) {
3637 $cwd_remove= getcwd();
3639 return unless defined $cwd_remove;
3640 if (!chdir "$cwd_remove") {
3641 return if $!==&ENOENT;
3642 die "chdir $cwd_remove: $!";
3645 rmtree($dstdir) or die "remove $dstdir: $!\n";
3646 } elsif (grep { $! == $_ }
3647 (ENOENT, ENOTDIR, EACCES, EPERM, ELOOP)) {
3649 print STDERR "check whether to remove $dstdir: $!\n";
3655 $cwd_remove = undef;
3658 sub branchsuite () {
3659 my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
3660 if ($branch =~ m#$lbranch_re#o) {
3667 sub fetchpullargs () {
3669 if (!defined $package) {
3670 my $sourcep = parsecontrol('debian/control','debian/control');
3671 $package = getfield $sourcep, 'Source';
3674 # $isuite = branchsuite(); # this doesn't work because dak hates canons
3676 my $clogp = parsechangelog();
3677 $isuite = getfield $clogp, 'Distribution';
3679 canonicalise_suite();
3680 progress "fetching from suite $csuite";
3681 } elsif (@ARGV==1) {
3683 canonicalise_suite();
3685 badusage "incorrect arguments to dgit fetch or dgit pull";
3698 if (quiltmode_splitbrain()) {
3699 my ($format, $fopts) = get_source_format();
3700 madformat($format) and fail <<END
3701 dgit pull not yet supported in split view mode (--quilt=$quilt_mode)
3710 badusage "-p is not allowed with dgit push" if defined $package;
3712 my $clogp = parsechangelog();
3713 $package = getfield $clogp, 'Source';
3716 } elsif (@ARGV==1) {
3717 ($specsuite) = (@ARGV);
3719 badusage "incorrect arguments to dgit push";
3721 $isuite = getfield $clogp, 'Distribution';
3723 local ($package) = $existing_package; # this is a hack
3724 canonicalise_suite();
3726 canonicalise_suite();
3728 if (defined $specsuite &&
3729 $specsuite ne $isuite &&
3730 $specsuite ne $csuite) {
3731 fail "dgit push: changelog specifies $isuite ($csuite)".
3732 " but command line specifies $specsuite";
3737 #---------- remote commands' implementation ----------
3739 sub cmd_remote_push_build_host {
3740 my ($nrargs) = shift @ARGV;
3741 my (@rargs) = @ARGV[0..$nrargs-1];
3742 @ARGV = @ARGV[$nrargs..$#ARGV];
3744 my ($dir,$vsnwant) = @rargs;
3745 # vsnwant is a comma-separated list; we report which we have
3746 # chosen in our ready response (so other end can tell if they
3749 $we_are_responder = 1;
3750 $us .= " (build host)";
3754 open PI, "<&STDIN" or die $!;
3755 open STDIN, "/dev/null" or die $!;
3756 open PO, ">&STDOUT" or die $!;
3758 open STDOUT, ">&STDERR" or die $!;
3762 ($protovsn) = grep {
3763 $vsnwant =~ m{^(?:.*,)?$_(?:,.*)?$}
3764 } @rpushprotovsn_support;
3766 fail "build host has dgit rpush protocol versions ".
3767 (join ",", @rpushprotovsn_support).
3768 " but invocation host has $vsnwant"
3769 unless defined $protovsn;
3771 responder_send_command("dgit-remote-push-ready $protovsn");
3772 rpush_handle_protovsn_bothends();
3777 sub cmd_remote_push_responder { cmd_remote_push_build_host(); }
3778 # ... for compatibility with proto vsn.1 dgit (just so that user gets
3779 # a good error message)
3781 sub rpush_handle_protovsn_bothends () {
3782 if ($protovsn < 4) {
3783 need_tagformat 'old', "rpush negotiated protocol $protovsn";
3792 my $report = i_child_report();
3793 if (defined $report) {
3794 printdebug "($report)\n";
3795 } elsif ($i_child_pid) {
3796 printdebug "(killing build host child $i_child_pid)\n";
3797 kill 15, $i_child_pid;
3799 if (defined $i_tmp && !defined $initiator_tempdir) {
3801 eval { rmtree $i_tmp; };
3805 END { i_cleanup(); }
3808 my ($base,$selector,@args) = @_;
3809 $selector =~ s/\-/_/g;
3810 { no strict qw(refs); &{"${base}_${selector}"}(@args); }
3817 if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
3825 push @rargs, join ",", @rpushprotovsn_support;
3828 push @rdgit, @ropts;
3829 push @rdgit, qw(remote-push-build-host), (scalar @rargs), @rargs;
3831 my @cmd = (@ssh, $host, shellquote @rdgit);
3834 if (defined $initiator_tempdir) {
3835 rmtree $initiator_tempdir;
3836 mkdir $initiator_tempdir, 0700 or die "$initiator_tempdir: $!";
3837 $i_tmp = $initiator_tempdir;
3841 $i_child_pid = open2(\*RO, \*RI, @cmd);
3843 ($protovsn) = initiator_expect { m/^dgit-remote-push-ready (\S+)/ };
3844 die "$protovsn ?" unless grep { $_ eq $protovsn } @rpushprotovsn_support;
3845 $supplementary_message = '' unless $protovsn >= 3;
3847 fail "rpush negotiated protocol version $protovsn".
3848 " which does not support quilt mode $quilt_mode"
3849 if quiltmode_splitbrain;
3851 rpush_handle_protovsn_bothends();
3853 my ($icmd,$iargs) = initiator_expect {
3854 m/^(\S+)(?: (.*))?$/;
3857 i_method "i_resp", $icmd, $iargs;
3861 sub i_resp_progress ($) {
3863 my $msg = protocol_read_bytes \*RO, $rhs;
3867 sub i_resp_supplementary_message ($) {
3869 $supplementary_message = protocol_read_bytes \*RO, $rhs;
3872 sub i_resp_complete {
3873 my $pid = $i_child_pid;
3874 $i_child_pid = undef; # prevents killing some other process with same pid
3875 printdebug "waiting for build host child $pid...\n";
3876 my $got = waitpid $pid, 0;
3877 die $! unless $got == $pid;
3878 die "build host child failed $?" if $?;
3881 printdebug "all done\n";
3885 sub i_resp_file ($) {
3887 my $localname = i_method "i_localname", $keyword;
3888 my $localpath = "$i_tmp/$localname";
3889 stat_exists $localpath and
3890 badproto \*RO, "file $keyword ($localpath) twice";
3891 protocol_receive_file \*RO, $localpath;
3892 i_method "i_file", $keyword;
3897 sub i_resp_param ($) {
3898 $_[0] =~ m/^(\S+) (.*)$/ or badproto \*RO, "bad param spec";
3902 sub i_resp_previously ($) {
3903 $_[0] =~ m#^(refs/tags/\S+)=(\w+)$#
3904 or badproto \*RO, "bad previously spec";
3905 my $r = system qw(git check-ref-format), $1;
3906 die "bad previously ref spec ($r)" if $r;
3907 $previously{$1} = $2;
3912 sub i_resp_want ($) {
3914 die "$keyword ?" if $i_wanted{$keyword}++;
3915 my @localpaths = i_method "i_want", $keyword;
3916 printdebug "[[ $keyword @localpaths\n";
3917 foreach my $localpath (@localpaths) {
3918 protocol_send_file \*RI, $localpath;
3920 print RI "files-end\n" or die $!;
3923 our ($i_clogp, $i_version, $i_dscfn, $i_changesfn);
3925 sub i_localname_parsed_changelog {
3926 return "remote-changelog.822";
3928 sub i_file_parsed_changelog {
3929 ($i_clogp, $i_version, $i_dscfn) =
3930 push_parse_changelog "$i_tmp/remote-changelog.822";
3931 die if $i_dscfn =~ m#/|^\W#;
3934 sub i_localname_dsc {
3935 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
3940 sub i_localname_changes {
3941 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
3942 $i_changesfn = $i_dscfn;
3943 $i_changesfn =~ s/\.dsc$/_dgit.changes/ or die;
3944 return $i_changesfn;
3946 sub i_file_changes { }
3948 sub i_want_signed_tag {
3949 printdebug Dumper(\%i_param, $i_dscfn);
3950 defined $i_param{'head'} && defined $i_dscfn && defined $i_clogp
3951 && defined $i_param{'csuite'}
3952 or badproto \*RO, "premature desire for signed-tag";
3953 my $head = $i_param{'head'};
3954 die if $head =~ m/[^0-9a-f]/ || $head !~ m/^../;
3956 my $maintview = $i_param{'maint-view'};
3957 die if defined $maintview && $maintview =~ m/[^0-9a-f]/;
3960 if ($protovsn >= 4) {
3961 my $p = $i_param{'tagformat'} // '<undef>';
3963 or badproto \*RO, "tag format mismatch: $p vs. $tagformat";
3966 die unless $i_param{'csuite'} =~ m/^$suite_re$/;
3968 push_parse_dsc $i_dscfn, 'remote dsc', $i_version;
3970 my @tagwants = push_tagwants $i_version, $head, $maintview, "tag";
3973 push_mktags $i_clogp, $i_dscfn,
3974 $i_changesfn, 'remote changes',
3978 sub i_want_signed_dsc_changes {
3979 rename "$i_dscfn.tmp","$i_dscfn" or die "$i_dscfn $!";
3980 sign_changes $i_changesfn;
3981 return ($i_dscfn, $i_changesfn);
3984 #---------- building etc. ----------
3990 #----- `3.0 (quilt)' handling -----
3992 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
3994 sub quiltify_dpkg_commit ($$$;$) {
3995 my ($patchname,$author,$msg, $xinfo) = @_;
3999 my $descfn = ".git/dgit/quilt-description.tmp";
4000 open O, '>', $descfn or die "$descfn: $!";
4001 $msg =~ s/\n+/\n\n/;
4002 print O <<END or die $!;
4004 ${xinfo}Subject: $msg
4011 local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
4012 local $ENV{'VISUAL'} = $ENV{'EDITOR'};
4013 local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
4014 runcmd @dpkgsource, qw(--commit .), $patchname;
4018 sub quiltify_trees_differ ($$;$$$) {
4019 my ($x,$y,$finegrained,$ignorenamesr,$unrepres) = @_;
4020 # returns true iff the two tree objects differ other than in debian/
4021 # with $finegrained,
4022 # returns bitmask 01 - differ in upstream files except .gitignore
4023 # 02 - differ in .gitignore
4024 # if $ignorenamesr is defined, $ingorenamesr->{$fn}
4025 # is set for each modified .gitignore filename $fn
4026 # if $unrepres is defined, array ref to which is appeneded
4027 # a list of unrepresentable changes (removals of upstream files
4030 my @cmd = (@git, qw(diff-tree -z));
4031 push @cmd, qw(--name-only) unless $unrepres;
4032 push @cmd, qw(-r) if $finegrained || $unrepres;
4034 my $diffs= cmdoutput @cmd;
4037 foreach my $f (split /\0/, $diffs) {
4038 if ($unrepres && !@lmodes) {
4039 @lmodes = $f =~ m/^\:(\w+) (\w+) \w+ \w+ / or die "$_ ?";
4042 my ($oldmode,$newmode) = @lmodes;
4045 next if $f =~ m#^debian(?:/.*)?$#s;
4049 die "deleted\n" unless $newmode =~ m/[^0]/;
4050 die "not a plain file\n" unless $newmode =~ m/^10\d{4}$/;
4051 if ($oldmode =~ m/[^0]/) {
4052 die "mode changed\n" if $oldmode ne $newmode;
4054 die "non-default mode\n" unless $newmode =~ m/^100644$/;
4058 local $/="\n"; chomp $@;
4059 push @$unrepres, [ $f, $@ ];
4063 my $isignore = $f =~ m#^(?:.*/)?.gitignore$#s;
4064 $r |= $isignore ? 02 : 01;
4065 $ignorenamesr->{$f}=1 if $ignorenamesr && $isignore;
4067 printdebug "quiltify_trees_differ $x $y => $r\n";
4071 sub quiltify_tree_sentinelfiles ($) {
4072 # lists the `sentinel' files present in the tree
4074 my $r = cmdoutput @git, qw(ls-tree --name-only), $x,
4075 qw(-- debian/rules debian/control);
4080 sub quiltify_splitbrain_needed () {
4081 if (!$split_brain) {
4082 progress "dgit view: changes are required...";
4083 runcmd @git, qw(checkout -q -b dgit-view);
4088 sub quiltify_splitbrain ($$$$$$) {
4089 my ($clogp, $unapplied, $headref, $diffbits,
4090 $editedignores, $cachekey) = @_;
4091 if ($quilt_mode !~ m/gbp|dpm/) {
4092 # treat .gitignore just like any other upstream file
4093 $diffbits = { %$diffbits };
4094 $_ = !!$_ foreach values %$diffbits;
4096 # We would like any commits we generate to be reproducible
4097 my @authline = clogp_authline($clogp);
4098 local $ENV{GIT_COMMITTER_NAME} = $authline[0];
4099 local $ENV{GIT_COMMITTER_EMAIL} = $authline[1];
4100 local $ENV{GIT_COMMITTER_DATE} = $authline[2];
4101 local $ENV{GIT_AUTHOR_NAME} = $authline[0];
4102 local $ENV{GIT_AUTHOR_EMAIL} = $authline[1];
4103 local $ENV{GIT_AUTHOR_DATE} = $authline[2];
4105 if ($quilt_mode =~ m/gbp|unapplied/ &&
4106 ($diffbits->{O2H} & 01)) {
4108 "--quilt=$quilt_mode specified, implying patches-unapplied git tree\n".
4109 " but git tree differs from orig in upstream files.";
4110 if (!stat_exists "debian/patches") {
4112 "\n ... debian/patches is missing; perhaps this is a patch queue branch?";
4116 if ($quilt_mode =~ m/dpm/ &&
4117 ($diffbits->{H2A} & 01)) {
4119 --quilt=$quilt_mode specified, implying patches-applied git tree
4120 but git tree differs from result of applying debian/patches to upstream
4123 if ($quilt_mode =~ m/gbp|unapplied/ &&
4124 ($diffbits->{O2A} & 01)) { # some patches
4125 quiltify_splitbrain_needed();
4126 progress "dgit view: creating patches-applied version using gbp pq";
4127 runcmd shell_cmd 'exec >/dev/null', gbp_pq, qw(import);
4128 # gbp pq import creates a fresh branch; push back to dgit-view
4129 runcmd @git, qw(update-ref refs/heads/dgit-view HEAD);
4130 runcmd @git, qw(checkout -q dgit-view);
4132 if ($quilt_mode =~ m/gbp|dpm/ &&
4133 ($diffbits->{O2A} & 02)) {
4135 --quilt=$quilt_mode specified, implying that HEAD is for use with a
4136 tool which does not create patches for changes to upstream
4137 .gitignores: but, such patches exist in debian/patches.
4140 if (($diffbits->{O2H} & 02) && # user has modified .gitignore
4141 !($diffbits->{O2A} & 02)) { # patches do not change .gitignore
4142 quiltify_splitbrain_needed();
4143 progress "dgit view: creating patch to represent .gitignore changes";
4144 ensuredir "debian/patches";
4145 my $gipatch = "debian/patches/auto-gitignore";
4146 open GIPATCH, ">>", "$gipatch" or die "$gipatch: $!";
4147 stat GIPATCH or die "$gipatch: $!";
4148 fail "$gipatch already exists; but want to create it".
4149 " to record .gitignore changes" if (stat _)[7];
4150 print GIPATCH <<END or die "$gipatch: $!";
4151 Subject: Update .gitignore from Debian packaging branch
4153 The Debian packaging git branch contains these updates to the upstream
4154 .gitignore file(s). This patch is autogenerated, to provide these
4155 updates to users of the official Debian archive view of the package.
4157 [dgit ($our_version) update-gitignore]
4160 close GIPATCH or die "$gipatch: $!";
4161 runcmd shell_cmd "exec >>$gipatch", @git, qw(diff),
4162 $unapplied, $headref, "--", sort keys %$editedignores;
4163 open SERIES, "+>>", "debian/patches/series" or die $!;
4164 defined seek SERIES, -1, 2 or $!==EINVAL or die $!;
4166 defined read SERIES, $newline, 1 or die $!;
4167 print SERIES "\n" or die $! unless $newline eq "\n";
4168 print SERIES "auto-gitignore\n" or die $!;
4169 close SERIES or die $!;
4170 runcmd @git, qw(add -- debian/patches/series), $gipatch;
4172 Commit patch to update .gitignore
4174 [dgit ($our_version) update-gitignore-quilt-fixup]
4178 my $dgitview = git_rev_parse 'HEAD';
4180 changedir '../../../..';
4181 # When we no longer need to support squeeze, use --create-reflog
4183 ensuredir ".git/logs/refs/dgit-intern";
4184 my $makelogfh = new IO::File ".git/logs/refs/$splitbraincache", '>>'
4187 my $oldcache = git_get_ref "refs/$splitbraincache";
4188 if ($oldcache eq $dgitview) {
4189 my $tree = cmdoutput qw(git rev-parse), "$dgitview:";
4190 # git update-ref doesn't always update, in this case. *sigh*
4191 my $dummy = make_commit_text <<END;
4194 author Dgit <dgit\@example.com> 1000000000 +0000
4195 committer Dgit <dgit\@example.com> 1000000000 +0000
4197 Dummy commit - do not use
4199 runcmd @git, qw(update-ref -m), "dgit $our_version - dummy",
4200 "refs/$splitbraincache", $dummy;
4202 runcmd @git, qw(update-ref -m), $cachekey, "refs/$splitbraincache",
4205 changedir '.git/dgit/unpack/work';
4207 my $saved = maybe_split_brain_save $headref, $dgitview, "converted";
4208 progress "dgit view: created ($saved)";
4211 sub quiltify ($$$$) {
4212 my ($clogp,$target,$oldtiptree,$failsuggestion) = @_;
4214 # Quilt patchification algorithm
4216 # We search backwards through the history of the main tree's HEAD
4217 # (T) looking for a start commit S whose tree object is identical
4218 # to to the patch tip tree (ie the tree corresponding to the
4219 # current dpkg-committed patch series). For these purposes
4220 # `identical' disregards anything in debian/ - this wrinkle is
4221 # necessary because dpkg-source treates debian/ specially.
4223 # We can only traverse edges where at most one of the ancestors'
4224 # trees differs (in changes outside in debian/). And we cannot
4225 # handle edges which change .pc/ or debian/patches. To avoid
4226 # going down a rathole we avoid traversing edges which introduce
4227 # debian/rules or debian/control. And we set a limit on the
4228 # number of edges we are willing to look at.
4230 # If we succeed, we walk forwards again. For each traversed edge
4231 # PC (with P parent, C child) (starting with P=S and ending with
4232 # C=T) to we do this:
4234 # - dpkg-source --commit with a patch name and message derived from C
4235 # After traversing PT, we git commit the changes which
4236 # should be contained within debian/patches.
4238 # The search for the path S..T is breadth-first. We maintain a
4239 # todo list containing search nodes. A search node identifies a
4240 # commit, and looks something like this:
4242 # Commit => $git_commit_id,
4243 # Child => $c, # or undef if P=T
4244 # Whynot => $reason_edge_PC_unsuitable, # in @nots only
4245 # Nontrivial => true iff $p..$c has relevant changes
4252 my %considered; # saves being exponential on some weird graphs
4254 my $t_sentinels = quiltify_tree_sentinelfiles $target;
4257 my ($search,$whynot) = @_;
4258 printdebug " search NOT $search->{Commit} $whynot\n";
4259 $search->{Whynot} = $whynot;
4260 push @nots, $search;
4261 no warnings qw(exiting);
4270 my $c = shift @todo;
4271 next if $considered{$c->{Commit}}++;
4273 $not->($c, "maximum search space exceeded") if --$max_work <= 0;
4275 printdebug "quiltify investigate $c->{Commit}\n";
4278 if (!quiltify_trees_differ $c->{Commit}, $oldtiptree) {
4279 printdebug " search finished hooray!\n";
4284 if ($quilt_mode eq 'nofix') {
4285 fail "quilt fixup required but quilt mode is \`nofix'\n".
4286 "HEAD commit $c->{Commit} differs from tree implied by ".
4287 " debian/patches (tree object $oldtiptree)";
4289 if ($quilt_mode eq 'smash') {
4290 printdebug " search quitting smash\n";
4294 my $c_sentinels = quiltify_tree_sentinelfiles $c->{Commit};
4295 $not->($c, "has $c_sentinels not $t_sentinels")
4296 if $c_sentinels ne $t_sentinels;
4298 my $commitdata = cmdoutput @git, qw(cat-file commit), $c->{Commit};
4299 $commitdata =~ m/\n\n/;
4301 my @parents = ($commitdata =~ m/^parent (\w+)$/gm);
4302 @parents = map { { Commit => $_, Child => $c } } @parents;
4304 $not->($c, "root commit") if !@parents;
4306 foreach my $p (@parents) {
4307 $p->{Nontrivial}= quiltify_trees_differ $p->{Commit},$c->{Commit};
4309 my $ndiffers = grep { $_->{Nontrivial} } @parents;
4310 $not->($c, "merge ($ndiffers nontrivial parents)") if $ndiffers > 1;
4312 foreach my $p (@parents) {
4313 printdebug "considering C=$c->{Commit} P=$p->{Commit}\n";
4315 my @cmd= (@git, qw(diff-tree -r --name-only),
4316 $p->{Commit},$c->{Commit}, qw(-- debian/patches .pc));
4317 my $patchstackchange = cmdoutput @cmd;
4318 if (length $patchstackchange) {
4319 $patchstackchange =~ s/\n/,/g;
4320 $not->($p, "changed $patchstackchange");
4323 printdebug " search queue P=$p->{Commit} ",
4324 ($p->{Nontrivial} ? "NT" : "triv"),"\n";
4330 printdebug "quiltify want to smash\n";
4333 my $x = $_[0]{Commit};
4334 $x =~ s/(.*?[0-9a-z]{8})[0-9a-z]*$/$1/;
4337 my $reportnot = sub {
4339 my $s = $abbrev->($notp);
4340 my $c = $notp->{Child};
4341 $s .= "..".$abbrev->($c) if $c;
4342 $s .= ": ".$notp->{Whynot};
4345 if ($quilt_mode eq 'linear') {
4346 print STDERR "$us: quilt fixup cannot be linear. Stopped at:\n";
4347 foreach my $notp (@nots) {
4348 print STDERR "$us: ", $reportnot->($notp), "\n";
4350 print STDERR "$us: $_\n" foreach @$failsuggestion;
4351 fail "quilt fixup naive history linearisation failed.\n".
4352 "Use dpkg-source --commit by hand; or, --quilt=smash for one ugly patch";
4353 } elsif ($quilt_mode eq 'smash') {
4354 } elsif ($quilt_mode eq 'auto') {
4355 progress "quilt fixup cannot be linear, smashing...";
4357 die "$quilt_mode ?";
4360 my $time = $ENV{'GIT_COMMITTER_DATE'} || time;
4361 $time =~ s/\s.*//; # trim timezone from GIT_COMMITTER_DATE
4363 my $msg = cmdoutput @git, qw(log), "-n$ncommits";
4365 quiltify_dpkg_commit "auto-$version-$target-$time",
4366 (getfield $clogp, 'Maintainer'),
4367 "Automatically generated patch ($clogp->{Version})\n".
4368 "Last (up to) $ncommits git changes, FYI:\n\n". $msg;
4372 progress "quiltify linearisation planning successful, executing...";
4374 for (my $p = $sref_S;
4375 my $c = $p->{Child};
4377 printdebug "quiltify traverse $p->{Commit}..$c->{Commit}\n";
4378 next unless $p->{Nontrivial};
4380 my $cc = $c->{Commit};
4382 my $commitdata = cmdoutput @git, qw(cat-file commit), $cc;
4383 $commitdata =~ m/\n\n/ or die "$c ?";
4386 $commitdata =~ m/^author (.*) \d+ [-+0-9]+$/m or die "$cc ?";
4389 my $commitdate = cmdoutput
4390 @git, qw(log -n1 --pretty=format:%aD), $cc;
4392 $msg =~ s/^(.*)\n*/$1\n/ or die "$cc $msg ?";
4394 my $strip_nls = sub { $msg =~ s/\n+$//; $msg .= "\n"; };
4401 my $gbp_check_suitable = sub {
4406 die "contains unexpected slashes\n" if m{//} || m{/$};
4407 die "contains leading punctuation\n" if m{^\W} || m{/\W};
4408 die "contains bad character(s)\n" if m{[^-a-z0-9_.+=~/]}i;
4409 die "too long" if length > 200;
4411 return $_ unless $@;
4412 print STDERR "quiltifying commit $cc:".
4413 " ignoring/dropping Gbp-Pq $what: $@";
4417 if ($msg =~ s/^ (?: gbp(?:-pq)? : \s* name \s+ |
4419 (\S+) \s* \n //ixm) {
4420 $patchname = $gbp_check_suitable->($1, 'Name');
4422 if ($msg =~ s/^ (?: gbp(?:-pq)? : \s* topic \s+ |
4424 (\S+) \s* \n //ixm) {
4425 $patchdir = $gbp_check_suitable->($1, 'Topic');
4430 if (!defined $patchname) {
4431 $patchname = $title;
4432 $patchname =~ s/[.:]$//;
4435 my $converter = new Text::Iconv qw(UTF-8 ASCII//TRANSLIT);
4436 my $translitname = $converter->convert($patchname);
4437 die unless defined $translitname;
4438 $patchname = $translitname;
4441 "dgit: patch title transliteration error: $@"
4443 $patchname =~ y/ A-Z/-a-z/;
4444 $patchname =~ y/-a-z0-9_.+=~//cd;
4445 $patchname =~ s/^\W/x-$&/;
4446 $patchname = substr($patchname,0,40);
4448 if (!defined $patchdir) {
4451 if (length $patchdir) {
4452 $patchname = "$patchdir/$patchname";
4454 if ($patchname =~ m{^(.*)/}) {
4455 mkpath "debian/patches/$1";
4460 stat "debian/patches/$patchname$index";
4462 $!==ENOENT or die "$patchname$index $!";
4464 runcmd @git, qw(checkout -q), $cc;
4466 # We use the tip's changelog so that dpkg-source doesn't
4467 # produce complaining messages from dpkg-parsechangelog. None
4468 # of the information dpkg-source gets from the changelog is
4469 # actually relevant - it gets put into the original message
4470 # which dpkg-source provides our stunt editor, and then
4472 runcmd @git, qw(checkout -q), $target, qw(debian/changelog);
4474 quiltify_dpkg_commit "$patchname$index", $author, $msg,
4475 "Date: $commitdate\n".
4476 "X-Dgit-Generated: $clogp->{Version} $cc\n";
4478 runcmd @git, qw(checkout -q), $cc, qw(debian/changelog);
4481 runcmd @git, qw(checkout -q master);
4484 sub build_maybe_quilt_fixup () {
4485 my ($format,$fopts) = get_source_format;
4486 return unless madformat_wantfixup $format;
4489 check_for_vendor_patches();
4491 if (quiltmode_splitbrain) {
4492 foreach my $needtf (qw(new maint)) {
4493 next if grep { $_ eq $needtf } access_cfg_tagformats;
4495 quilt mode $quilt_mode requires split view so server needs to support
4496 both "new" and "maint" tag formats, but config says it doesn't.
4501 my $clogp = parsechangelog();
4502 my $headref = git_rev_parse('HEAD');
4507 my $upstreamversion = upstreamversion $version;
4509 if ($fopts->{'single-debian-patch'}) {
4510 quilt_fixup_singlepatch($clogp, $headref, $upstreamversion);
4512 quilt_fixup_multipatch($clogp, $headref, $upstreamversion);
4515 die 'bug' if $split_brain && !$need_split_build_invocation;
4517 changedir '../../../..';
4518 runcmd_ordryrun_local
4519 @git, qw(pull --ff-only -q .git/dgit/unpack/work master);
4522 sub quilt_fixup_mkwork ($) {
4525 mkdir "work" or die $!;
4527 mktree_in_ud_here();
4528 runcmd @git, qw(reset -q --hard), $headref;
4531 sub quilt_fixup_linkorigs ($$) {
4532 my ($upstreamversion, $fn) = @_;
4533 # calls $fn->($leafname);
4535 foreach my $f (<../../../../*>) { #/){
4536 my $b=$f; $b =~ s{.*/}{};
4538 local ($debuglevel) = $debuglevel-1;
4539 printdebug "QF linkorigs $b, $f ?\n";
4541 next unless is_orig_file_of_vsn $b, $upstreamversion;
4542 printdebug "QF linkorigs $b, $f Y\n";
4543 link_ltarget $f, $b or die "$b $!";
4548 sub quilt_fixup_delete_pc () {
4549 runcmd @git, qw(rm -rqf .pc);
4551 Commit removal of .pc (quilt series tracking data)
4553 [dgit ($our_version) upgrade quilt-remove-pc]
4557 sub quilt_fixup_singlepatch ($$$) {
4558 my ($clogp, $headref, $upstreamversion) = @_;
4560 progress "starting quiltify (single-debian-patch)";
4562 # dpkg-source --commit generates new patches even if
4563 # single-debian-patch is in debian/source/options. In order to
4564 # get it to generate debian/patches/debian-changes, it is
4565 # necessary to build the source package.
4567 quilt_fixup_linkorigs($upstreamversion, sub { });
4568 quilt_fixup_mkwork($headref);
4570 rmtree("debian/patches");
4572 runcmd @dpkgsource, qw(-b .);
4574 runcmd @dpkgsource, qw(-x), (srcfn $version, ".dsc");
4575 rename srcfn("$upstreamversion", "/debian/patches"),
4576 "work/debian/patches";
4579 commit_quilty_patch();
4582 sub quilt_make_fake_dsc ($) {
4583 my ($upstreamversion) = @_;
4585 my $fakeversion="$upstreamversion-~~DGITFAKE";
4587 my $fakedsc=new IO::File 'fake.dsc', '>' or die $!;
4588 print $fakedsc <<END or die $!;
4591 Version: $fakeversion
4595 my $dscaddfile=sub {
4598 my $md = new Digest::MD5;
4600 my $fh = new IO::File $b, '<' or die "$b $!";
4605 print $fakedsc " ".$md->hexdigest." $size $b\n" or die $!;
4608 quilt_fixup_linkorigs($upstreamversion, $dscaddfile);
4610 my @files=qw(debian/source/format debian/rules
4611 debian/control debian/changelog);
4612 foreach my $maybe (qw(debian/patches debian/source/options
4613 debian/tests/control)) {
4614 next unless stat_exists "../../../$maybe";
4615 push @files, $maybe;
4618 my $debtar= srcfn $fakeversion,'.debian.tar.gz';
4619 runcmd qw(env GZIP=-1n tar -zcf), "./$debtar", qw(-C ../../..), @files;
4621 $dscaddfile->($debtar);
4622 close $fakedsc or die $!;
4625 sub quilt_check_splitbrain_cache ($$) {
4626 my ($headref, $upstreamversion) = @_;
4627 # Called only if we are in (potentially) split brain mode.
4629 # Computes the cache key and looks in the cache.
4630 # Returns ($dgit_view_commitid, $cachekey) or (undef, $cachekey)
4632 my $splitbrain_cachekey;
4635 "dgit: split brain (separate dgit view) may be needed (--quilt=$quilt_mode).";
4636 # we look in the reflog of dgit-intern/quilt-cache
4637 # we look for an entry whose message is the key for the cache lookup
4638 my @cachekey = (qw(dgit), $our_version);
4639 push @cachekey, $upstreamversion;
4640 push @cachekey, $quilt_mode;
4641 push @cachekey, $headref;
4643 push @cachekey, hashfile('fake.dsc');
4645 my $srcshash = Digest::SHA->new(256);
4646 my %sfs = ( %INC, '$0(dgit)' => $0 );
4647 foreach my $sfk (sort keys %sfs) {
4648 next unless $sfk =~ m/^\$0\b/ || $sfk =~ m{^Debian/Dgit\b};
4649 $srcshash->add($sfk," ");
4650 $srcshash->add(hashfile($sfs{$sfk}));
4651 $srcshash->add("\n");
4653 push @cachekey, $srcshash->hexdigest();
4654 $splitbrain_cachekey = "@cachekey";
4656 my @cmd = (@git, qw(log -g), '--pretty=format:%H %gs',
4658 printdebug "splitbrain cachekey $splitbrain_cachekey\n";
4659 debugcmd "|(probably)",@cmd;
4660 my $child = open GC, "-|"; defined $child or die $!;
4662 chdir '../../..' or die $!;
4663 if (!stat ".git/logs/refs/$splitbraincache") {
4664 $! == ENOENT or die $!;
4665 printdebug ">(no reflog)\n";
4672 printdebug ">| ", $_, "\n" if $debuglevel > 1;
4673 next unless m/^(\w+) (\S.*\S)$/ && $2 eq $splitbrain_cachekey;
4676 quilt_fixup_mkwork($headref);
4677 my $saved = maybe_split_brain_save $headref, $cachehit, "cache-hit";
4678 if ($cachehit ne $headref) {
4679 progress "dgit view: found cached ($saved)";
4680 runcmd @git, qw(checkout -q -b dgit-view), $cachehit;
4682 return ($cachehit, $splitbrain_cachekey);
4684 progress "dgit view: found cached, no changes required";
4685 return ($headref, $splitbrain_cachekey);
4687 die $! if GC->error;
4688 failedcmd unless close GC;
4690 printdebug "splitbrain cache miss\n";
4691 return (undef, $splitbrain_cachekey);
4694 sub quilt_fixup_multipatch ($$$) {
4695 my ($clogp, $headref, $upstreamversion) = @_;
4697 progress "examining quilt state (multiple patches, $quilt_mode mode)";
4700 # - honour any existing .pc in case it has any strangeness
4701 # - determine the git commit corresponding to the tip of
4702 # the patch stack (if there is one)
4703 # - if there is such a git commit, convert each subsequent
4704 # git commit into a quilt patch with dpkg-source --commit
4705 # - otherwise convert all the differences in the tree into
4706 # a single git commit
4710 # Our git tree doesn't necessarily contain .pc. (Some versions of
4711 # dgit would include the .pc in the git tree.) If there isn't
4712 # one, we need to generate one by unpacking the patches that we
4715 # We first look for a .pc in the git tree. If there is one, we
4716 # will use it. (This is not the normal case.)
4718 # Otherwise need to regenerate .pc so that dpkg-source --commit
4719 # can work. We do this as follows:
4720 # 1. Collect all relevant .orig from parent directory
4721 # 2. Generate a debian.tar.gz out of
4722 # debian/{patches,rules,source/format,source/options}
4723 # 3. Generate a fake .dsc containing just these fields:
4724 # Format Source Version Files
4725 # 4. Extract the fake .dsc
4726 # Now the fake .dsc has a .pc directory.
4727 # (In fact we do this in every case, because in future we will
4728 # want to search for a good base commit for generating patches.)
4730 # Then we can actually do the dpkg-source --commit
4731 # 1. Make a new working tree with the same object
4732 # store as our main tree and check out the main
4734 # 2. Copy .pc from the fake's extraction, if necessary
4735 # 3. Run dpkg-source --commit
4736 # 4. If the result has changes to debian/, then
4737 # - git add them them
4738 # - git add .pc if we had a .pc in-tree
4740 # 5. If we had a .pc in-tree, delete it, and git commit
4741 # 6. Back in the main tree, fast forward to the new HEAD
4743 # Another situation we may have to cope with is gbp-style
4744 # patches-unapplied trees.
4746 # We would want to detect these, so we know to escape into
4747 # quilt_fixup_gbp. However, this is in general not possible.
4748 # Consider a package with a one patch which the dgit user reverts
4749 # (with git revert or the moral equivalent).
4751 # That is indistinguishable in contents from a patches-unapplied
4752 # tree. And looking at the history to distinguish them is not
4753 # useful because the user might have made a confusing-looking git
4754 # history structure (which ought to produce an error if dgit can't
4755 # cope, not a silent reintroduction of an unwanted patch).
4757 # So gbp users will have to pass an option. But we can usually
4758 # detect their failure to do so: if the tree is not a clean
4759 # patches-applied tree, quilt linearisation fails, but the tree
4760 # _is_ a clean patches-unapplied tree, we can suggest that maybe
4761 # they want --quilt=unapplied.
4763 # To help detect this, when we are extracting the fake dsc, we
4764 # first extract it with --skip-patches, and then apply the patches
4765 # afterwards with dpkg-source --before-build. That lets us save a
4766 # tree object corresponding to .origs.
4768 my $splitbrain_cachekey;
4770 quilt_make_fake_dsc($upstreamversion);
4772 if (quiltmode_splitbrain()) {
4774 ($cachehit, $splitbrain_cachekey) =
4775 quilt_check_splitbrain_cache($headref, $upstreamversion);
4776 return if $cachehit;
4780 'exec dpkg-source --no-check --skip-patches -x fake.dsc >/dev/null';
4782 my $fakexdir= $package.'-'.(stripepoch $upstreamversion);
4783 rename $fakexdir, "fake" or die "$fakexdir $!";
4787 remove_stray_gits();
4788 mktree_in_ud_here();
4792 runcmd @git, qw(add -Af .);
4793 my $unapplied=git_write_tree();
4794 printdebug "fake orig tree object $unapplied\n";
4798 my @bbcmd = (qw(sh -ec), 'exec dpkg-source --before-build . >/dev/null');
4800 if (system @bbcmd) {
4801 failedcmd @bbcmd if $? < 0;
4803 failed to apply your git tree's patch stack (from debian/patches/) to
4804 the corresponding upstream tarball(s). Your source tree and .orig
4805 are probably too inconsistent. dgit can only fix up certain kinds of
4806 anomaly (depending on the quilt mode). See --quilt= in dgit(1).
4812 quilt_fixup_mkwork($headref);
4815 if (stat_exists ".pc") {
4817 progress "Tree already contains .pc - will use it then delete it.";
4820 rename '../fake/.pc','.pc' or die $!;
4823 changedir '../fake';
4825 runcmd @git, qw(add -Af .);
4826 my $oldtiptree=git_write_tree();
4827 printdebug "fake o+d/p tree object $unapplied\n";
4828 changedir '../work';
4831 # We calculate some guesswork now about what kind of tree this might
4832 # be. This is mostly for error reporting.
4838 # O = orig, without patches applied
4839 # A = "applied", ie orig with H's debian/patches applied
4840 O2H => quiltify_trees_differ($unapplied,$headref, 1,
4841 \%editedignores, \@unrepres),
4842 H2A => quiltify_trees_differ($headref, $oldtiptree,1),
4843 O2A => quiltify_trees_differ($unapplied,$oldtiptree,1),
4847 foreach my $b (qw(01 02)) {
4848 foreach my $v (qw(O2H O2A H2A)) {
4849 push @dl, ($diffbits->{$v} & $b) ? '##' : '==';
4852 printdebug "differences \@dl @dl.\n";
4855 "$us: base trees orig=%.20s o+d/p=%.20s",
4856 $unapplied, $oldtiptree;
4858 "$us: quilt differences: src: %s orig %s gitignores: %s orig %s\n".
4859 "$us: quilt differences: HEAD %s o+d/p HEAD %s o+d/p",
4860 $dl[0], $dl[1], $dl[3], $dl[4],
4864 print STDERR "dgit: cannot represent change: $_->[1]: $_->[0]\n"
4866 forceable_fail [qw(unrepresentable)], <<END;
4867 HEAD has changes to .orig[s] which are not representable by `3.0 (quilt)'
4872 if (!($diffbits->{O2H} & $diffbits->{O2A})) {
4873 push @failsuggestion, "This might be a patches-unapplied branch.";
4874 } elsif (!($diffbits->{H2A} & $diffbits->{O2A})) {
4875 push @failsuggestion, "This might be a patches-applied branch.";
4877 push @failsuggestion, "Maybe you need to specify one of".
4878 " --[quilt=]gbp --[quilt=]dpm --quilt=unapplied ?";
4880 if (quiltmode_splitbrain()) {
4881 quiltify_splitbrain($clogp, $unapplied, $headref,
4882 $diffbits, \%editedignores,
4883 $splitbrain_cachekey);
4887 progress "starting quiltify (multiple patches, $quilt_mode mode)";
4888 quiltify($clogp,$headref,$oldtiptree,\@failsuggestion);
4890 if (!open P, '>>', ".pc/applied-patches") {
4891 $!==&ENOENT or die $!;
4896 commit_quilty_patch();
4898 if ($mustdeletepc) {
4899 quilt_fixup_delete_pc();
4903 sub quilt_fixup_editor () {
4904 my $descfn = $ENV{$fakeeditorenv};
4905 my $editing = $ARGV[$#ARGV];
4906 open I1, '<', $descfn or die "$descfn: $!";
4907 open I2, '<', $editing or die "$editing: $!";
4908 unlink $editing or die "$editing: $!";
4909 open O, '>', $editing or die "$editing: $!";
4910 while (<I1>) { print O or die $!; } I1->error and die $!;
4913 $copying ||= m/^\-\-\- /;
4914 next unless $copying;
4917 I2->error and die $!;
4922 sub maybe_apply_patches_dirtily () {
4923 return unless $quilt_mode =~ m/gbp|unapplied/;
4924 print STDERR <<END or die $!;
4926 dgit: Building, or cleaning with rules target, in patches-unapplied tree.
4927 dgit: Have to apply the patches - making the tree dirty.
4928 dgit: (Consider specifying --clean=git and (or) using dgit sbuild.)
4931 $patches_applied_dirtily = 01;
4932 $patches_applied_dirtily |= 02 unless stat_exists '.pc';
4933 runcmd qw(dpkg-source --before-build .);
4936 sub maybe_unapply_patches_again () {
4937 progress "dgit: Unapplying patches again to tidy up the tree."
4938 if $patches_applied_dirtily;
4939 runcmd qw(dpkg-source --after-build .)
4940 if $patches_applied_dirtily & 01;
4942 if $patches_applied_dirtily & 02;
4943 $patches_applied_dirtily = 0;
4946 #----- other building -----
4948 our $clean_using_builder;
4949 # ^ tree is to be cleaned by dpkg-source's builtin idea that it should
4950 # clean the tree before building (perhaps invoked indirectly by
4951 # whatever we are using to run the build), rather than separately
4952 # and explicitly by us.
4955 return if $clean_using_builder;
4956 if ($cleanmode eq 'dpkg-source') {
4957 maybe_apply_patches_dirtily();
4958 runcmd_ordryrun_local @dpkgbuildpackage, qw(-T clean);
4959 } elsif ($cleanmode eq 'dpkg-source-d') {
4960 maybe_apply_patches_dirtily();
4961 runcmd_ordryrun_local @dpkgbuildpackage, qw(-d -T clean);
4962 } elsif ($cleanmode eq 'git') {
4963 runcmd_ordryrun_local @git, qw(clean -xdf);
4964 } elsif ($cleanmode eq 'git-ff') {
4965 runcmd_ordryrun_local @git, qw(clean -xdff);
4966 } elsif ($cleanmode eq 'check') {
4967 my $leftovers = cmdoutput @git, qw(clean -xdn);
4968 if (length $leftovers) {
4969 print STDERR $leftovers, "\n" or die $!;
4970 fail "tree contains uncommitted files and --clean=check specified";
4972 } elsif ($cleanmode eq 'none') {
4979 badusage "clean takes no additional arguments" if @ARGV;
4982 maybe_unapply_patches_again();
4985 sub build_prep_early () {
4986 our $build_prep_early_done //= 0;
4987 return if $build_prep_early_done++;
4989 badusage "-p is not allowed when building" if defined $package;
4990 my $clogp = parsechangelog();
4991 $isuite = getfield $clogp, 'Distribution';
4992 $package = getfield $clogp, 'Source';
4993 $version = getfield $clogp, 'Version';
5000 build_maybe_quilt_fixup();
5002 my $pat = changespat $version;
5003 foreach my $f (glob "$buildproductsdir/$pat") {
5005 unlink $f or fail "remove old changes file $f: $!";
5007 progress "would remove $f";
5013 sub changesopts_initial () {
5014 my @opts =@changesopts[1..$#changesopts];
5017 sub changesopts_version () {
5018 if (!defined $changes_since_version) {
5019 my @vsns = archive_query('archive_query');
5020 my @quirk = access_quirk();
5021 if ($quirk[0] eq 'backports') {
5022 local $isuite = $quirk[2];
5024 canonicalise_suite();
5025 push @vsns, archive_query('archive_query');
5028 @vsns = map { $_->[0] } @vsns;
5029 @vsns = sort { -version_compare($a, $b) } @vsns;
5030 $changes_since_version = $vsns[0];
5031 progress "changelog will contain changes since $vsns[0]";
5033 $changes_since_version = '_';
5034 progress "package seems new, not specifying -v<version>";
5037 if ($changes_since_version ne '_') {
5038 return ("-v$changes_since_version");
5044 sub changesopts () {
5045 return (changesopts_initial(), changesopts_version());
5048 sub massage_dbp_args ($;$) {
5049 my ($cmd,$xargs) = @_;
5052 # - if we're going to split the source build out so we can
5053 # do strange things to it, massage the arguments to dpkg-buildpackage
5054 # so that the main build doessn't build source (or add an argument
5055 # to stop it building source by default).
5057 # - add -nc to stop dpkg-source cleaning the source tree,
5058 # unless we're not doing a split build and want dpkg-source
5059 # as cleanmode, in which case we can do nothing
5062 # 0 - source will NOT need to be built separately by caller
5063 # +1 - source will need to be built separately by caller
5064 # +2 - source will need to be built separately by caller AND
5065 # dpkg-buildpackage should not in fact be run at all!
5066 debugcmd '#massaging#', @$cmd if $debuglevel>1;
5067 #print STDERR "MASS0 ",Dumper($cmd, $xargs, $need_split_build_invocation);
5068 if ($cleanmode eq 'dpkg-source' && !$need_split_build_invocation) {
5069 $clean_using_builder = 1;
5072 # -nc has the side effect of specifying -b if nothing else specified
5073 # and some combinations of -S, -b, et al, are errors, rather than
5074 # later simply overriding earlie. So we need to:
5075 # - search the command line for these options
5076 # - pick the last one
5077 # - perhaps add our own as a default
5078 # - perhaps adjust it to the corresponding non-source-building version
5080 foreach my $l ($cmd, $xargs) {
5082 @$l = grep { !(m/^-[SgGFABb]$/s and $dmode=$_) } @$l;
5085 #print STDERR "MASS1 ",Dumper($cmd, $xargs, $dmode);
5087 if ($need_split_build_invocation) {
5088 printdebug "massage split $dmode.\n";
5089 $r = $dmode =~ m/[S]/ ? +2 :
5090 $dmode =~ y/gGF/ABb/ ? +1 :
5091 $dmode =~ m/[ABb]/ ? 0 :
5094 printdebug "massage done $r $dmode.\n";
5096 #print STDERR "MASS2 ",Dumper($cmd, $xargs, $r);
5102 my $wasdir = must_getcwd();
5108 sub postbuild_mergechanges ($) { # must run with CWD=.. (eg in in_parent)
5109 my ($msg_if_onlyone) = @_;
5110 # If there is only one .changes file, fail with $msg_if_onlyone,
5111 # or if that is undef, be a no-op.
5112 # Returns the changes file to report to the user.
5113 my $pat = changespat $version;
5114 my @changesfiles = glob $pat;
5115 @changesfiles = sort {
5116 ($b =~ m/_source\.changes$/ <=> $a =~ m/_source\.changes$/)
5120 if (@changesfiles==1) {
5121 fail <<END.$msg_if_onlyone if defined $msg_if_onlyone;
5122 only one changes file from build (@changesfiles)
5124 $result = $changesfiles[0];
5125 } elsif (@changesfiles==2) {
5126 my $binchanges = parsecontrol($changesfiles[1], "binary changes file");
5127 foreach my $l (split /\n/, getfield $binchanges, 'Files') {
5128 fail "$l found in binaries changes file $binchanges"
5131 runcmd_ordryrun_local @mergechanges, @changesfiles;
5132 my $multichanges = changespat $version,'multi';
5134 stat_exists $multichanges or fail "$multichanges: $!";
5135 foreach my $cf (glob $pat) {
5136 next if $cf eq $multichanges;
5137 rename "$cf", "$cf.inmulti" or fail "$cf\{,.inmulti}: $!";
5140 $result = $multichanges;
5142 fail "wrong number of different changes files (@changesfiles)";
5144 printdone "build successful, results in $result\n" or die $!;
5147 sub midbuild_checkchanges () {
5148 my $pat = changespat $version;
5149 return if $rmchanges;
5150 my @unwanted = map { s#^\.\./##; $_; } glob "../$pat";
5151 @unwanted = grep { $_ ne changespat $version,'source' } @unwanted;
5153 changes files other than source matching $pat already present; building would result in ambiguity about the intended results.
5154 Suggest you delete @unwanted.
5159 sub midbuild_checkchanges_vanilla ($) {
5161 midbuild_checkchanges() if $wantsrc == 1;
5164 sub postbuild_mergechanges_vanilla ($) {
5166 if ($wantsrc == 1) {
5168 postbuild_mergechanges(undef);
5171 printdone "build successful\n";
5176 my @dbp = (@dpkgbuildpackage, qw(-us -uc), changesopts_initial(), @ARGV);
5177 my $wantsrc = massage_dbp_args \@dbp;
5180 midbuild_checkchanges_vanilla $wantsrc;
5185 push @dbp, changesopts_version();
5186 maybe_apply_patches_dirtily();
5187 runcmd_ordryrun_local @dbp;
5189 maybe_unapply_patches_again();
5190 postbuild_mergechanges_vanilla $wantsrc;
5194 $quilt_mode //= 'gbp';
5200 # gbp can make .origs out of thin air. In my tests it does this
5201 # even for a 1.0 format package, with no origs present. So I
5202 # guess it keys off just the version number. We don't know
5203 # exactly what .origs ought to exist, but let's assume that we
5204 # should run gbp if: the version has an upstream part and the main
5206 my $upstreamversion = upstreamversion $version;
5207 my $origfnpat = srcfn $upstreamversion, '.orig.tar.*';
5208 my $gbp_make_orig = $version =~ m/-/ && !(() = glob "../$origfnpat");
5210 if ($gbp_make_orig) {
5212 $cleanmode = 'none'; # don't do it again
5213 $need_split_build_invocation = 1;
5216 my @dbp = @dpkgbuildpackage;
5218 my $wantsrc = massage_dbp_args \@dbp, \@ARGV;
5220 if (!length $gbp_build[0]) {
5221 if (length executable_on_path('git-buildpackage')) {
5222 $gbp_build[0] = qw(git-buildpackage);
5224 $gbp_build[0] = 'gbp buildpackage';
5227 my @cmd = opts_opt_multi_cmd @gbp_build;
5229 push @cmd, (qw(-us -uc --git-no-sign-tags), "--git-builder=@dbp");
5231 if ($gbp_make_orig) {
5232 ensuredir '.git/dgit';
5233 my $ok = '.git/dgit/origs-gen-ok';
5234 unlink $ok or $!==&ENOENT or die $!;
5235 my @origs_cmd = @cmd;
5236 push @origs_cmd, qw(--git-cleaner=true);
5237 push @origs_cmd, "--git-prebuild=touch $ok .git/dgit/no-such-dir/ok";
5238 push @origs_cmd, @ARGV;
5240 debugcmd @origs_cmd;
5242 do { local $!; stat_exists $ok; }
5243 or failedcmd @origs_cmd;
5245 dryrun_report @origs_cmd;
5251 midbuild_checkchanges_vanilla $wantsrc;
5253 if (!$clean_using_builder) {
5254 push @cmd, '--git-cleaner=true';
5258 maybe_unapply_patches_again();
5260 push @cmd, changesopts();
5261 runcmd_ordryrun_local @cmd, @ARGV;
5263 postbuild_mergechanges_vanilla $wantsrc;
5265 sub cmd_git_build { cmd_gbp_build(); } # compatibility with <= 1.0
5268 my $our_cleanmode = $cleanmode;
5269 if ($need_split_build_invocation) {
5270 # Pretend that clean is being done some other way. This
5271 # forces us not to try to use dpkg-buildpackage to clean and
5272 # build source all in one go; and instead we run dpkg-source
5273 # (and build_prep() will do the clean since $clean_using_builder
5275 $our_cleanmode = 'ELSEWHERE';
5277 if ($our_cleanmode =~ m/^dpkg-source/) {
5278 # dpkg-source invocation (below) will clean, so build_prep shouldn't
5279 $clean_using_builder = 1;
5282 $sourcechanges = changespat $version,'source';
5284 unlink "../$sourcechanges" or $!==ENOENT
5285 or fail "remove $sourcechanges: $!";
5287 $dscfn = dscfn($version);
5288 if ($our_cleanmode eq 'dpkg-source') {
5289 maybe_apply_patches_dirtily();
5290 runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc -S),
5292 } elsif ($our_cleanmode eq 'dpkg-source-d') {
5293 maybe_apply_patches_dirtily();
5294 runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc -S -d),
5297 my @cmd = (@dpkgsource, qw(-b --));
5300 runcmd_ordryrun_local @cmd, "work";
5301 my @udfiles = <${package}_*>;
5302 changedir "../../..";
5303 foreach my $f (@udfiles) {
5304 printdebug "source copy, found $f\n";
5307 ($f =~ m/\.debian\.tar(?:\.\w+)$/ &&
5308 $f eq srcfn($version, $&));
5309 printdebug "source copy, found $f - renaming\n";
5310 rename "$ud/$f", "../$f" or $!==ENOENT
5311 or fail "put in place new source file ($f): $!";
5314 my $pwd = must_getcwd();
5315 my $leafdir = basename $pwd;
5317 runcmd_ordryrun_local @cmd, $leafdir;
5320 runcmd_ordryrun_local qw(sh -ec),
5321 'exec >$1; shift; exec "$@"','x',
5322 "../$sourcechanges",
5323 @dpkggenchanges, qw(-S), changesopts();
5327 sub cmd_build_source {
5328 badusage "build-source takes no additional arguments" if @ARGV;
5330 maybe_unapply_patches_again();
5331 printdone "source built, results in $dscfn and $sourcechanges";
5336 midbuild_checkchanges();
5339 stat_exists $dscfn or fail "$dscfn (in parent directory): $!";
5340 stat_exists $sourcechanges
5341 or fail "$sourcechanges (in parent directory): $!";
5343 runcmd_ordryrun_local @sbuild, qw(-d), $isuite, @ARGV, $dscfn;
5345 maybe_unapply_patches_again();
5347 postbuild_mergechanges(<<END);
5348 perhaps you need to pass -A ? (sbuild's default is to build only
5349 arch-specific binaries; dgit 1.4 used to override that.)
5354 sub cmd_quilt_fixup {
5355 badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
5356 my $clogp = parsechangelog();
5357 $version = getfield $clogp, 'Version';
5358 $package = getfield $clogp, 'Source';
5361 build_maybe_quilt_fixup();
5364 sub cmd_import_dsc {
5368 last unless $ARGV[0] =~ m/^-/;
5371 if (m/^--require-valid-signature$/) {
5374 badusage "unknown dgit import-dsc sub-option \`$_'";
5378 badusage "usage: dgit import-dsc .../PATH/TO/.DSC BRANCH" unless @ARGV==2;
5379 my ($dscfn, $dstbranch) = @ARGV;
5381 badusage "dry run makes no sense with import-dsc" unless act_local();
5383 my $force = $dstbranch =~ s/^\+// ? +1 :
5384 $dstbranch =~ s/^\.\.// ? -1 :
5386 my $info = $force ? " $&" : '';
5387 $info = "$dscfn$info";
5389 my $specbranch = $dstbranch;
5390 $dstbranch = "refs/heads/$dstbranch" unless $dstbranch =~ m#^refs/#;
5391 $dstbranch = cmdoutput @git, qw(check-ref-format --normalize), $dstbranch;
5393 my @symcmd = (@git, qw(symbolic-ref -q HEAD));
5394 my $chead = cmdoutput_errok @symcmd;
5395 defined $chead or $?==256 or failedcmd @symcmd;
5397 fail "$dstbranch is checked out - will not update it"
5398 if defined $chead and $chead eq $dstbranch;
5400 my $oldhash = git_get_ref $dstbranch;
5402 open D, "<", $dscfn or fail "open import .dsc ($dscfn): $!";
5403 $dscdata = do { local $/ = undef; <D>; };
5404 D->error and fail "read $dscfn: $!";
5407 # we don't normally need this so import it here
5408 use Dpkg::Source::Package;
5409 my $dp = new Dpkg::Source::Package filename => $dscfn,
5410 require_valid_signature => $needsig;
5412 local $SIG{__WARN__} = sub {
5414 return unless $needsig;
5415 fail "import-dsc signature check failed";
5417 if (!$dp->is_signed()) {
5418 warn "$us: warning: importing unsigned .dsc\n";
5420 my $r = $dp->check_signature();
5421 die "->check_signature => $r" if $needsig && $r;
5427 my $dgit_commit = $dsc->{$ourdscfield[0]};
5428 if (defined $dgit_commit &&
5429 !forceing [qw(import-dsc-with-dgit-field)]) {
5430 $dgit_commit =~ m/\w+/ or fail "invalid hash in .dsc";
5431 progress "dgit: import-dsc of .dsc with Dgit field, using git hash";
5432 my @cmd = (qw(sh -ec),
5433 "echo $dgit_commit | git cat-file --batch-check");
5434 my $objgot = cmdoutput @cmd;
5435 if ($objgot =~ m#^\w+ missing\b#) {
5437 .dsc contains Dgit field referring to object $dgit_commit
5438 Your git tree does not have that object. Try `git fetch' from a
5439 plausible server (browse.dgit.d.o? alioth?), and try the import-dsc again.
5442 if ($oldhash && !is_fast_fwd $oldhash, $dgit_commit) {
5444 progress "Not fast forward, forced update.";
5446 fail "Not fast forward to $dgit_commit";
5449 @cmd = (@git, qw(update-ref -m), "dgit import-dsc (Dgit): $info",
5450 $dstbranch, $dgit_commit);
5452 progress "dgit: import-dsc updated git ref $dstbranch";
5457 Branch $dstbranch already exists
5458 Specify ..$specbranch for a pseudo-merge, binding in existing history
5459 Specify +$specbranch to overwrite, discarding existing history
5461 if $oldhash && !$force;
5463 $package = getfield $dsc, 'Source';
5464 my @dfi = dsc_files_info();
5465 foreach my $fi (@dfi) {
5466 my $f = $fi->{Filename};
5468 next if lstat $here;
5469 fail "stat $here: $!" unless $! == ENOENT;
5471 if ($dscfn =~ m#^(?:\./+)?\.\./+#) {
5473 } elsif ($dscfn =~ m#^/#) {
5476 fail "cannot import $dscfn which seems to be inside working tree!";
5478 $there =~ s#/+[^/]+$## or
5479 fail "cannot import $dscfn which seems to not have a basename";
5481 symlink $there, $here or fail "symlink $there to $here: $!";
5482 progress "made symlink $here -> $there";
5483 print STDERR Dumper($fi);
5485 my @mergeinputs = generate_commits_from_dsc();
5486 die unless @mergeinputs == 1;
5488 my $newhash = $mergeinputs[0]{Commit};
5492 progress "Import, forced update - synthetic orphan git history.";
5493 } elsif ($force < 0) {
5494 progress "Import, merging.";
5495 my $tree = cmdoutput @git, qw(rev-parse), "$newhash:";
5496 my $version = getfield $dsc, 'Version';
5497 $newhash = make_commit_text <<END;
5502 Merge $package ($version) import into $dstbranch
5505 die; # caught earlier
5509 my @cmd = (@git, qw(update-ref -m), "dgit import-dsc: $info",
5510 $dstbranch, $newhash);
5512 progress "dgit: import-dsc results are in in git ref $dstbranch";
5515 sub cmd_archive_api_query {
5516 badusage "need only 1 subpath argument" unless @ARGV==1;
5517 my ($subpath) = @ARGV;
5518 my @cmd = archive_api_query_cmd($subpath);
5521 exec @cmd or fail "exec curl: $!\n";
5524 sub cmd_clone_dgit_repos_server {
5525 badusage "need destination argument" unless @ARGV==1;
5526 my ($destdir) = @ARGV;
5527 $package = '_dgit-repos-server';
5528 my @cmd = (@git, qw(clone), access_giturl(), $destdir);
5530 exec @cmd or fail "exec git clone: $!\n";
5533 sub cmd_setup_mergechangelogs {
5534 badusage "no arguments allowed to dgit setup-mergechangelogs" if @ARGV;
5535 setup_mergechangelogs(1);
5538 sub cmd_setup_useremail {
5539 badusage "no arguments allowed to dgit setup-mergechangelogs" if @ARGV;
5543 sub cmd_setup_new_tree {
5544 badusage "no arguments allowed to dgit setup-tree" if @ARGV;
5548 #---------- argument parsing and main program ----------
5551 print "dgit version $our_version\n" or die $!;
5555 our (%valopts_long, %valopts_short);
5558 sub defvalopt ($$$$) {
5559 my ($long,$short,$val_re,$how) = @_;
5560 my $oi = { Long => $long, Short => $short, Re => $val_re, How => $how };
5561 $valopts_long{$long} = $oi;
5562 $valopts_short{$short} = $oi;
5563 # $how subref should:
5564 # do whatever assignemnt or thing it likes with $_[0]
5565 # if the option should not be passed on to remote, @rvalopts=()
5566 # or $how can be a scalar ref, meaning simply assign the value
5569 defvalopt '--since-version', '-v', '[^_]+|_', \$changes_since_version;
5570 defvalopt '--distro', '-d', '.+', \$idistro;
5571 defvalopt '', '-k', '.+', \$keyid;
5572 defvalopt '--existing-package','', '.*', \$existing_package;
5573 defvalopt '--build-products-dir','','.*', \$buildproductsdir;
5574 defvalopt '--clean', '', $cleanmode_re, \$cleanmode;
5575 defvalopt '--package', '-p', $package_re, \$package;
5576 defvalopt '--quilt', '', $quilt_modes_re, \$quilt_mode;
5578 defvalopt '', '-C', '.+', sub {
5579 ($changesfile) = (@_);
5580 if ($changesfile =~ s#^(.*)/##) {
5581 $buildproductsdir = $1;
5585 defvalopt '--initiator-tempdir','','.*', sub {
5586 ($initiator_tempdir) = (@_);
5587 $initiator_tempdir =~ m#^/# or
5588 badusage "--initiator-tempdir must be used specify an".
5589 " absolute, not relative, directory."
5595 if (defined $ENV{'DGIT_SSH'}) {
5596 @ssh = string_to_ssh $ENV{'DGIT_SSH'};
5597 } elsif (defined $ENV{'GIT_SSH'}) {
5598 @ssh = ($ENV{'GIT_SSH'});
5606 if (!defined $val) {
5607 badusage "$what needs a value" unless @ARGV;
5609 push @rvalopts, $val;
5611 badusage "bad value \`$val' for $what" unless
5612 $val =~ m/^$oi->{Re}$(?!\n)/s;
5613 my $how = $oi->{How};
5614 if (ref($how) eq 'SCALAR') {
5619 push @ropts, @rvalopts;
5623 last unless $ARGV[0] =~ m/^-/;
5627 if (m/^--dry-run$/) {
5630 } elsif (m/^--damp-run$/) {
5633 } elsif (m/^--no-sign$/) {
5636 } elsif (m/^--help$/) {
5638 } elsif (m/^--version$/) {
5640 } elsif (m/^--new$/) {
5643 } elsif (m/^--([-0-9a-z]+)=(.+)/s &&
5644 ($om = $opts_opt_map{$1}) &&
5648 } elsif (m/^--([-0-9a-z]+):(.*)/s &&
5649 !$opts_opt_cmdonly{$1} &&
5650 ($om = $opts_opt_map{$1})) {
5653 } elsif (m/^--(gbp|dpm)$/s) {
5654 push @ropts, "--quilt=$1";
5656 } elsif (m/^--ignore-dirty$/s) {
5659 } elsif (m/^--no-quilt-fixup$/s) {
5661 $quilt_mode = 'nocheck';
5662 } elsif (m/^--no-rm-on-error$/s) {
5665 } elsif (m/^--overwrite$/s) {
5667 $overwrite_version = '';
5668 } elsif (m/^--overwrite=(.+)$/s) {
5670 $overwrite_version = $1;
5671 } elsif (m/^--delayed=(\d+)$/s) {
5674 } elsif (m/^--dgit-view-save=(.+)$/s) {
5676 $split_brain_save = $1;
5677 $split_brain_save =~ s#^(?!refs/)#refs/heads/#;
5678 } elsif (m/^--(no-)?rm-old-changes$/s) {
5681 } elsif (m/^--deliberately-($deliberately_re)$/s) {
5683 push @deliberatelies, $&;
5684 } elsif (m/^--force-(.*)/ && defined $forceopts{$1}) {
5688 } elsif (m/^--force-/) {
5690 "$us: warning: ignoring unknown force option $_\n";
5692 } elsif (m/^--dgit-tag-format=(old|new)$/s) {
5693 # undocumented, for testing
5695 $tagformat_want = [ $1, 'command line', 1 ];
5696 # 1 menas overrides distro configuration
5697 } elsif (m/^--always-split-source-build$/s) {
5698 # undocumented, for testing
5700 $need_split_build_invocation = 1;
5701 } elsif (m/^(--[-0-9a-z]+)(=|$)/ && ($oi = $valopts_long{$1})) {
5702 $val = $2 ? $' : undef; #';
5703 $valopt->($oi->{Long});
5705 badusage "unknown long option \`$_'";
5712 } elsif (s/^-L/-/) {
5715 } elsif (s/^-h/-/) {
5717 } elsif (s/^-D/-/) {
5721 } elsif (s/^-N/-/) {
5726 push @changesopts, $_;
5728 } elsif (s/^-wn$//s) {
5730 $cleanmode = 'none';
5731 } elsif (s/^-wg$//s) {
5734 } elsif (s/^-wgf$//s) {
5736 $cleanmode = 'git-ff';
5737 } elsif (s/^-wd$//s) {
5739 $cleanmode = 'dpkg-source';
5740 } elsif (s/^-wdd$//s) {
5742 $cleanmode = 'dpkg-source-d';
5743 } elsif (s/^-wc$//s) {
5745 $cleanmode = 'check';
5746 } elsif (s/^-c([^=]*)\=(.*)$//s) {
5747 push @git, '-c', $&;
5748 $gitcfgs{cmdline}{$1} = [ $2 ];
5749 } elsif (s/^-c([^=]+)$//s) {
5750 push @git, '-c', $&;
5751 $gitcfgs{cmdline}{$1} = [ 'true' ];
5752 } elsif (m/^-[a-zA-Z]/ && ($oi = $valopts_short{$&})) {
5754 $val = undef unless length $val;
5755 $valopt->($oi->{Short});
5758 badusage "unknown short option \`$_'";
5765 sub check_env_sanity () {
5766 my $blocked = new POSIX::SigSet;
5767 sigprocmask SIG_UNBLOCK, $blocked, $blocked or die $!;
5770 foreach my $name (qw(PIPE CHLD)) {
5771 my $signame = "SIG$name";
5772 my $signum = eval "POSIX::$signame" // die;
5773 ($SIG{$name} // 'DEFAULT') eq 'DEFAULT' or
5774 die "$signame is set to something other than SIG_DFL\n";
5775 $blocked->ismember($signum) and
5776 die "$signame is blocked\n";
5782 On entry to dgit, $@
5783 This is a bug produced by something in in your execution environment.
5789 sub finalise_opts_opts () {
5790 foreach my $k (keys %opts_opt_map) {
5791 my $om = $opts_opt_map{$k};
5793 my $v = access_cfg("cmd-$k", 'RETURN-UNDEF');
5795 badcfg "cannot set command for $k"
5796 unless length $om->[0];
5800 foreach my $c (access_cfg_cfgs("opts-$k")) {
5802 map { $_ ? @$_ : () }
5803 map { $gitcfgs{$_}{$c} }
5804 reverse @gitcfgsources;
5805 printdebug "CL $c ", (join " ", map { shellquote } @vl),
5806 "\n" if $debuglevel >= 4;
5808 badcfg "cannot configure options for $k"
5809 if $opts_opt_cmdonly{$k};
5810 my $insertpos = $opts_cfg_insertpos{$k};
5811 @$om = ( @$om[0..$insertpos-1],
5813 @$om[$insertpos..$#$om] );
5818 if ($ENV{$fakeeditorenv}) {
5820 quilt_fixup_editor();
5827 print STDERR "DRY RUN ONLY\n" if $dryrun_level > 1;
5828 print STDERR "DAMP RUN - WILL MAKE LOCAL (UNSIGNED) CHANGES\n"
5829 if $dryrun_level == 1;
5831 print STDERR $helpmsg or die $!;
5834 my $cmd = shift @ARGV;
5837 my $pre_fn = ${*::}{"pre_$cmd"};
5838 $pre_fn->() if $pre_fn;
5840 if (!defined $rmchanges) {
5841 local $access_forpush;
5842 $rmchanges = access_cfg_bool(0, 'rm-old-changes');
5845 if (!defined $quilt_mode) {
5846 local $access_forpush;
5847 $quilt_mode = cfg('dgit.force.quilt-mode', 'RETURN-UNDEF')
5848 // access_cfg('quilt-mode', 'RETURN-UNDEF')
5850 $quilt_mode =~ m/^($quilt_modes_re)$/
5851 or badcfg "unknown quilt-mode \`$quilt_mode'";
5855 $need_split_build_invocation ||= quiltmode_splitbrain();
5857 if (!defined $cleanmode) {
5858 local $access_forpush;
5859 $cleanmode = access_cfg('clean-mode', 'RETURN-UNDEF');
5860 $cleanmode //= 'dpkg-source';
5862 badcfg "unknown clean-mode \`$cleanmode'" unless
5863 $cleanmode =~ m/^($cleanmode_re)$(?!\n)/s;
5866 my $fn = ${*::}{"cmd_$cmd"};
5867 $fn or badusage "unknown operation $cmd";