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 $we_are_responder;
71 our $initiator_tempdir;
72 our $patches_applied_dirtily = 00;
77 our %forceopts = map { $_=>0 }
78 qw(unrepresentable unsupported-source-format
79 dsc-changes-mismatch changes-origs-exactly
80 import-gitapply-absurd
81 import-gitapply-no-absurd
82 import-dsc-with-dgit-field);
84 our %format_ok = map { $_=>1 } ("1.0","3.0 (native)","3.0 (quilt)");
86 our $suite_re = '[-+.0-9a-z]+';
87 our $cleanmode_re = 'dpkg-source(?:-d)?|git|git-ff|check|none';
88 our $orig_f_comp_re = 'orig(?:-[-0-9a-z]+)?';
89 our $orig_f_sig_re = '\\.(?:asc|gpg|pgp)';
90 our $orig_f_tail_re = "$orig_f_comp_re\\.tar(?:\\.\\w+)?(?:$orig_f_sig_re)?";
92 our $git_authline_re = '^([^<>]+) \<(\S+)\> (\d+ [-+]\d+)$';
93 our $splitbraincache = 'dgit-intern/quilt-cache';
96 our (@dget) = qw(dget);
97 our (@curl) = qw(curl);
98 our (@dput) = qw(dput);
99 our (@debsign) = qw(debsign);
100 our (@gpg) = qw(gpg);
101 our (@sbuild) = qw(sbuild);
103 our (@dgit) = qw(dgit);
104 our (@dpkgbuildpackage) = qw(dpkg-buildpackage -i\.git/ -I.git);
105 our (@dpkgsource) = qw(dpkg-source -i\.git/ -I.git);
106 our (@dpkggenchanges) = qw(dpkg-genchanges);
107 our (@mergechanges) = qw(mergechanges -f);
108 our (@gbp_build) = ('');
109 our (@gbp_pq) = ('gbp pq');
110 our (@changesopts) = ('');
112 our %opts_opt_map = ('dget' => \@dget, # accept for compatibility
115 'debsign' => \@debsign,
117 'sbuild' => \@sbuild,
121 'dpkg-source' => \@dpkgsource,
122 'dpkg-buildpackage' => \@dpkgbuildpackage,
123 'dpkg-genchanges' => \@dpkggenchanges,
124 'gbp-build' => \@gbp_build,
125 'gbp-pq' => \@gbp_pq,
126 'ch' => \@changesopts,
127 'mergechanges' => \@mergechanges);
129 our %opts_opt_cmdonly = ('gpg' => 1, 'git' => 1);
130 our %opts_cfg_insertpos = map {
132 scalar @{ $opts_opt_map{$_} }
133 } keys %opts_opt_map;
135 sub finalise_opts_opts();
141 our $supplementary_message = '';
142 our $need_split_build_invocation = 0;
143 our $split_brain = 0;
147 print STDERR "! $_\n" foreach $supplementary_message =~ m/^.+$/mg;
150 our $remotename = 'dgit';
151 our @ourdscfield = qw(Dgit Vcs-Dgit-Master);
155 if (!defined $absurdity) {
157 $absurdity =~ s{/[^/]+$}{/absurd} or die;
161 my ($v,$distro) = @_;
162 return $tagformatfn->($v, $distro);
165 sub debiantag_maintview ($$) {
166 my ($v,$distro) = @_;
171 sub madformat ($) { $_[0] eq '3.0 (quilt)' }
173 sub lbranch () { return "$branchprefix/$csuite"; }
174 my $lbranch_re = '^refs/heads/'.$branchprefix.'/([^/.]+)$';
175 sub lref () { return "refs/heads/".lbranch(); }
176 sub lrref () { return "refs/remotes/$remotename/".server_branch($csuite); }
177 sub rrref () { return server_ref($csuite); }
179 sub lrfetchrefs () { return "refs/dgit-fetch/$csuite"; }
180 sub lrfetchref () { return lrfetchrefs.'/'.server_branch($csuite); }
182 # We fetch some parts of lrfetchrefs/*. Ideally we delete these
183 # locally fetched refs because they have unhelpful names and clutter
184 # up gitk etc. So we track whether we have "used up" head ref (ie,
185 # whether we have made another local ref which refers to this object).
187 # (If we deleted them unconditionally, then we might end up
188 # re-fetching the same git objects each time dgit fetch was run.)
190 # So, leach use of lrfetchrefs needs to be accompanied by arrangements
191 # in git_fetch_us to fetch the refs in question, and possibly a call
192 # to lrfetchref_used.
194 our (%lrfetchrefs_f, %lrfetchrefs_d);
195 # $lrfetchrefs_X{lrfetchrefs."/heads/whatever"} = $objid
197 sub lrfetchref_used ($) {
198 my ($fullrefname) = @_;
199 my $objid = $lrfetchrefs_f{$fullrefname};
200 $lrfetchrefs_d{$fullrefname} = $objid if defined $objid;
211 return "${package}_".(stripepoch $vsn).$sfx
216 return srcfn($vsn,".dsc");
219 sub changespat ($;$) {
220 my ($vsn, $arch) = @_;
221 return "${package}_".(stripepoch $vsn)."_".($arch//'*').".changes";
230 foreach my $f (@end) {
232 print STDERR "$us: cleanup: $@" if length $@;
236 sub badcfg { print STDERR "$us: invalid configuration: @_\n"; exit 12; }
238 sub forceable_fail ($$) {
239 my ($forceoptsl, $msg) = @_;
240 fail $msg unless grep { $forceopts{$_} } @$forceoptsl;
241 print STDERR "warning: overriding problem due to --force:\n". $msg;
245 my ($forceoptsl) = @_;
246 my @got = grep { $forceopts{$_} } @$forceoptsl;
247 return 0 unless @got;
249 "warning: skipping checks or functionality due to --force-$got[0]\n";
252 sub no_such_package () {
253 print STDERR "$us: package $package does not exist in suite $isuite\n";
259 printdebug "CD $newdir\n";
260 chdir $newdir or confess "chdir: $newdir: $!";
263 sub deliberately ($) {
265 return !!grep { $_ eq "--deliberately-$enquiry" } @deliberatelies;
268 sub deliberately_not_fast_forward () {
269 foreach (qw(not-fast-forward fresh-repo)) {
270 return 1 if deliberately($_) || deliberately("TEST-dgit-only-$_");
274 sub quiltmode_splitbrain () {
275 $quilt_mode =~ m/gbp|dpm|unapplied/;
278 sub opts_opt_multi_cmd {
280 push @cmd, split /\s+/, shift @_;
286 return opts_opt_multi_cmd @gbp_pq;
289 #---------- remote protocol support, common ----------
291 # remote push initiator/responder protocol:
292 # $ dgit remote-push-build-host <n-rargs> <rargs>... <push-args>...
293 # where <rargs> is <push-host-dir> <supported-proto-vsn>,... ...
294 # < dgit-remote-push-ready <actual-proto-vsn>
301 # > supplementary-message NBYTES # $protovsn >= 3
306 # > file parsed-changelog
307 # [indicates that output of dpkg-parsechangelog follows]
308 # > data-block NBYTES
309 # > [NBYTES bytes of data (no newline)]
310 # [maybe some more blocks]
319 # > param head DGIT-VIEW-HEAD
320 # > param csuite SUITE
321 # > param tagformat old|new
322 # > param maint-view MAINT-VIEW-HEAD
324 # > previously REFNAME=OBJNAME # if --deliberately-not-fast-forward
325 # # goes into tag, for replay prevention
328 # [indicates that signed tag is wanted]
329 # < data-block NBYTES
330 # < [NBYTES bytes of data (no newline)]
331 # [maybe some more blocks]
335 # > want signed-dsc-changes
336 # < data-block NBYTES [transfer of signed dsc]
338 # < data-block NBYTES [transfer of signed changes]
346 sub i_child_report () {
347 # Sees if our child has died, and reap it if so. Returns a string
348 # describing how it died if it failed, or undef otherwise.
349 return undef unless $i_child_pid;
350 my $got = waitpid $i_child_pid, WNOHANG;
351 return undef if $got <= 0;
352 die unless $got == $i_child_pid;
353 $i_child_pid = undef;
354 return undef unless $?;
355 return "build host child ".waitstatusmsg();
360 fail "connection lost: $!" if $fh->error;
361 fail "protocol violation; $m not expected";
364 sub badproto_badread ($$) {
366 fail "connection lost: $!" if $!;
367 my $report = i_child_report();
368 fail $report if defined $report;
369 badproto $fh, "eof (reading $wh)";
372 sub protocol_expect (&$) {
373 my ($match, $fh) = @_;
376 defined && chomp or badproto_badread $fh, "protocol message";
384 badproto $fh, "\`$_'";
387 sub protocol_send_file ($$) {
388 my ($fh, $ourfn) = @_;
389 open PF, "<", $ourfn or die "$ourfn: $!";
392 my $got = read PF, $d, 65536;
393 die "$ourfn: $!" unless defined $got;
395 print $fh "data-block ".length($d)."\n" or die $!;
396 print $fh $d or die $!;
398 PF->error and die "$ourfn $!";
399 print $fh "data-end\n" or die $!;
403 sub protocol_read_bytes ($$) {
404 my ($fh, $nbytes) = @_;
405 $nbytes =~ m/^[1-9]\d{0,5}$|^0$/ or badproto \*RO, "bad byte count";
407 my $got = read $fh, $d, $nbytes;
408 $got==$nbytes or badproto_badread $fh, "data block";
412 sub protocol_receive_file ($$) {
413 my ($fh, $ourfn) = @_;
414 printdebug "() $ourfn\n";
415 open PF, ">", $ourfn or die "$ourfn: $!";
417 my ($y,$l) = protocol_expect {
418 m/^data-block (.*)$/ ? (1,$1) :
419 m/^data-end$/ ? (0,) :
423 my $d = protocol_read_bytes $fh, $l;
424 print PF $d or die $!;
429 #---------- remote protocol support, responder ----------
431 sub responder_send_command ($) {
433 return unless $we_are_responder;
434 # called even without $we_are_responder
435 printdebug ">> $command\n";
436 print PO $command, "\n" or die $!;
439 sub responder_send_file ($$) {
440 my ($keyword, $ourfn) = @_;
441 return unless $we_are_responder;
442 printdebug "]] $keyword $ourfn\n";
443 responder_send_command "file $keyword";
444 protocol_send_file \*PO, $ourfn;
447 sub responder_receive_files ($@) {
448 my ($keyword, @ourfns) = @_;
449 die unless $we_are_responder;
450 printdebug "[[ $keyword @ourfns\n";
451 responder_send_command "want $keyword";
452 foreach my $fn (@ourfns) {
453 protocol_receive_file \*PI, $fn;
456 protocol_expect { m/^files-end$/ } \*PI;
459 #---------- remote protocol support, initiator ----------
461 sub initiator_expect (&) {
463 protocol_expect { &$match } \*RO;
466 #---------- end remote code ----------
469 if ($we_are_responder) {
471 responder_send_command "progress ".length($m) or die $!;
472 print PO $m or die $!;
482 $ua = LWP::UserAgent->new();
486 progress "downloading $what...";
487 my $r = $ua->get(@_) or die $!;
488 return undef if $r->code == 404;
489 $r->is_success or fail "failed to fetch $what: ".$r->status_line;
490 return $r->decoded_content(charset => 'none');
493 our ($dscdata,$dscurl,$dsc,$dsc_checked,$skew_warning_vsn);
498 failedcmd @_ if system @_;
501 sub act_local () { return $dryrun_level <= 1; }
502 sub act_scary () { return !$dryrun_level; }
505 if (!$dryrun_level) {
506 progress "dgit ok: @_";
508 progress "would be ok: @_ (but dry run only)";
513 printcmd(\*STDERR,$debugprefix."#",@_);
516 sub runcmd_ordryrun {
524 sub runcmd_ordryrun_local {
533 my ($first_shell, @cmd) = @_;
534 return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
537 our $helpmsg = <<END;
539 dgit [dgit-opts] clone [dgit-opts] package [suite] [./dir|/dir]
540 dgit [dgit-opts] fetch|pull [dgit-opts] [suite]
541 dgit [dgit-opts] build [dpkg-buildpackage-opts]
542 dgit [dgit-opts] sbuild [sbuild-opts]
543 dgit [dgit-opts] push [dgit-opts] [suite]
544 dgit [dgit-opts] rpush build-host:build-dir ...
545 important dgit options:
546 -k<keyid> sign tag and package with <keyid> instead of default
547 --dry-run -n do not change anything, but go through the motions
548 --damp-run -L like --dry-run but make local changes, without signing
549 --new -N allow introducing a new package
550 --debug -D increase debug level
551 -c<name>=<value> set git config option (used directly by dgit too)
554 our $later_warning_msg = <<END;
555 Perhaps the upload is stuck in incoming. Using the version from git.
559 print STDERR "$us: @_\n", $helpmsg or die $!;
564 @ARGV or badusage "too few arguments";
565 return scalar shift @ARGV;
569 print $helpmsg or die $!;
573 our $td = $ENV{DGIT_TEST_DUMMY_DIR} || "DGIT_TEST_DUMMY_DIR-unset";
575 our %defcfg = ('dgit.default.distro' => 'debian',
576 'dgit.default.username' => '',
577 'dgit.default.archive-query-default-component' => 'main',
578 'dgit.default.ssh' => 'ssh',
579 'dgit.default.archive-query' => 'madison:',
580 'dgit.default.sshpsql-dbname' => 'service=projectb',
581 'dgit.default.dgit-tag-format' => 'new,old,maint',
582 # old means "repo server accepts pushes with old dgit tags"
583 # new means "repo server accepts pushes with new dgit tags"
584 # maint means "repo server accepts split brain pushes"
585 # hist means "repo server may have old pushes without new tag"
586 # ("hist" is implied by "old")
587 'dgit-distro.debian.archive-query' => 'ftpmasterapi:',
588 'dgit-distro.debian.git-check' => 'url',
589 'dgit-distro.debian.git-check-suffix' => '/info/refs',
590 'dgit-distro.debian.new-private-pushers' => 't',
591 'dgit-distro.debian/push.git-url' => '',
592 'dgit-distro.debian/push.git-host' => 'push.dgit.debian.org',
593 'dgit-distro.debian/push.git-user-force' => 'dgit',
594 'dgit-distro.debian/push.git-proto' => 'git+ssh://',
595 'dgit-distro.debian/push.git-path' => '/dgit/debian/repos',
596 'dgit-distro.debian/push.git-create' => 'true',
597 'dgit-distro.debian/push.git-check' => 'ssh-cmd',
598 'dgit-distro.debian.archive-query-url', 'https://api.ftp-master.debian.org/',
599 # 'dgit-distro.debian.archive-query-tls-key',
600 # '/etc/ssl/certs/%HOST%.pem:/etc/dgit/%HOST%.pem',
601 # ^ this does not work because curl is broken nowadays
602 # Fixing #790093 properly will involve providing providing the key
603 # in some pacagke and maybe updating these paths.
605 # 'dgit-distro.debian.archive-query-tls-curl-args',
606 # '--ca-path=/etc/ssl/ca-debian',
607 # ^ this is a workaround but works (only) on DSA-administered machines
608 'dgit-distro.debian.git-url' => 'https://git.dgit.debian.org',
609 'dgit-distro.debian.git-url-suffix' => '',
610 'dgit-distro.debian.upload-host' => 'ftp-master', # for dput
611 'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/',
612 'dgit-distro.debian.backports-quirk' => '(squeeze)-backports*',
613 'dgit-distro.debian-backports.mirror' => 'http://backports.debian.org/debian-backports/',
614 'dgit-distro.ubuntu.git-check' => 'false',
615 'dgit-distro.ubuntu.mirror' => 'http://archive.ubuntu.com/ubuntu',
616 'dgit-distro.test-dummy.ssh' => "$td/ssh",
617 'dgit-distro.test-dummy.username' => "alice",
618 'dgit-distro.test-dummy.git-check' => "ssh-cmd",
619 'dgit-distro.test-dummy.git-create' => "ssh-cmd",
620 'dgit-distro.test-dummy.git-url' => "$td/git",
621 'dgit-distro.test-dummy.git-host' => "git",
622 'dgit-distro.test-dummy.git-path' => "$td/git",
623 'dgit-distro.test-dummy.archive-query' => "dummycatapi:",
624 'dgit-distro.test-dummy.archive-query-url' => "file://$td/aq/",
625 'dgit-distro.test-dummy.mirror' => "file://$td/mirror/",
626 'dgit-distro.test-dummy.upload-host' => 'test-dummy',
630 our @gitcfgsources = qw(cmdline local global system);
632 sub git_slurp_config () {
633 local ($debuglevel) = $debuglevel-2;
636 # This algoritm is a bit subtle, but this is needed so that for
637 # options which we want to be single-valued, we allow the
638 # different config sources to override properly. See #835858.
639 foreach my $src (@gitcfgsources) {
640 next if $src eq 'cmdline';
641 # we do this ourselves since git doesn't handle it
643 my @cmd = (@git, qw(config -z --get-regexp), "--$src", qw(.*));
646 open GITS, "-|", @cmd or die $!;
649 printdebug "=> ", (messagequote $_), "\n";
651 push @{ $gitcfgs{$src}{$`} }, $'; #';
655 or ($!==0 && $?==256)
660 sub git_get_config ($) {
662 foreach my $src (@gitcfgsources) {
663 my $l = $gitcfgs{$src}{$c};
664 printdebug"C $c ".(defined $l ? messagequote "'$l'" : "undef")."\n"
667 @$l==1 or badcfg "multiple values for $c".
668 " (in $src git config)" if @$l > 1;
676 return undef if $c =~ /RETURN-UNDEF/;
677 my $v = git_get_config($c);
678 return $v if defined $v;
679 my $dv = $defcfg{$c};
680 return $dv if defined $dv;
682 badcfg "need value for one of: @_\n".
683 "$us: distro or suite appears not to be (properly) supported";
686 sub access_basedistro () {
687 if (defined $idistro) {
690 return cfg("dgit-suite.$isuite.distro",
691 "dgit.default.distro");
695 sub access_quirk () {
696 # returns (quirk name, distro to use instead or undef, quirk-specific info)
697 my $basedistro = access_basedistro();
698 my $backports_quirk = cfg("dgit-distro.$basedistro.backports-quirk",
700 if (defined $backports_quirk) {
701 my $re = $backports_quirk;
702 $re =~ s/[^-0-9a-z_\%*()]/\\$&/ig;
704 $re =~ s/\%/([-0-9a-z_]+)/
705 or $re =~ m/[()]/ or badcfg "backports-quirk needs \% or ( )";
706 if ($isuite =~ m/^$re$/) {
707 return ('backports',"$basedistro-backports",$1);
710 return ('none',undef);
715 sub parse_cfg_bool ($$$) {
716 my ($what,$def,$v) = @_;
719 $v =~ m/^[ty1]/ ? 1 :
720 $v =~ m/^[fn0]/ ? 0 :
721 badcfg "$what needs t (true, y, 1) or f (false, n, 0) not \`$v'";
724 sub access_forpush_config () {
725 my $d = access_basedistro();
729 parse_cfg_bool('new-private-pushers', 0,
730 cfg("dgit-distro.$d.new-private-pushers",
733 my $v = cfg("dgit-distro.$d.readonly", 'RETURN-UNDEF');
736 $v =~ m/^[ty1]/ ? 0 : # force readonly, forpush = 0
737 $v =~ m/^[fn0]/ ? 1 : # force nonreadonly, forpush = 1
738 $v =~ m/^[a]/ ? '' : # auto, forpush = ''
739 badcfg "readonly needs t (true, y, 1) or f (false, n, 0) or a (auto)";
742 sub access_forpush () {
743 $access_forpush //= access_forpush_config();
744 return $access_forpush;
748 die "$access_forpush ?" if ($access_forpush // 1) ne 1;
749 badcfg "pushing but distro is configured readonly"
750 if access_forpush_config() eq '0';
752 $supplementary_message = <<'END' unless $we_are_responder;
753 Push failed, before we got started.
754 You can retry the push, after fixing the problem, if you like.
756 finalise_opts_opts();
760 finalise_opts_opts();
763 sub supplementary_message ($) {
765 if (!$we_are_responder) {
766 $supplementary_message = $msg;
768 } elsif ($protovsn >= 3) {
769 responder_send_command "supplementary-message ".length($msg)
771 print PO $msg or die $!;
775 sub access_distros () {
776 # Returns list of distros to try, in order
779 # 0. `instead of' distro name(s) we have been pointed to
780 # 1. the access_quirk distro, if any
781 # 2a. the user's specified distro, or failing that } basedistro
782 # 2b. the distro calculated from the suite }
783 my @l = access_basedistro();
785 my (undef,$quirkdistro) = access_quirk();
786 unshift @l, $quirkdistro;
787 unshift @l, $instead_distro;
788 @l = grep { defined } @l;
790 if (access_forpush()) {
791 @l = map { ("$_/push", $_) } @l;
796 sub access_cfg_cfgs (@) {
799 # The nesting of these loops determines the search order. We put
800 # the key loop on the outside so that we search all the distros
801 # for each key, before going on to the next key. That means that
802 # if access_cfg is called with a more specific, and then a less
803 # specific, key, an earlier distro can override the less specific
804 # without necessarily overriding any more specific keys. (If the
805 # distro wants to override the more specific keys it can simply do
806 # so; whereas if we did the loop the other way around, it would be
807 # impossible to for an earlier distro to override a less specific
808 # key but not the more specific ones without restating the unknown
809 # values of the more specific keys.
812 # We have to deal with RETURN-UNDEF specially, so that we don't
813 # terminate the search prematurely.
815 if (m/RETURN-UNDEF/) { push @rundef, $_; last; }
818 foreach my $d (access_distros()) {
819 push @cfgs, map { "dgit-distro.$d.$_" } @realkeys;
821 push @cfgs, map { "dgit.default.$_" } @realkeys;
828 my (@cfgs) = access_cfg_cfgs(@keys);
829 my $value = cfg(@cfgs);
833 sub access_cfg_bool ($$) {
834 my ($def, @keys) = @_;
835 parse_cfg_bool($keys[0], $def, access_cfg(@keys, 'RETURN-UNDEF'));
838 sub string_to_ssh ($) {
840 if ($spec =~ m/\s/) {
841 return qw(sh -ec), 'exec '.$spec.' "$@"', 'x';
847 sub access_cfg_ssh () {
848 my $gitssh = access_cfg('ssh', 'RETURN-UNDEF');
849 if (!defined $gitssh) {
852 return string_to_ssh $gitssh;
856 sub access_runeinfo ($) {
858 return ": dgit ".access_basedistro()." $info ;";
861 sub access_someuserhost ($) {
863 my $user = access_cfg("$some-user-force", 'RETURN-UNDEF');
864 defined($user) && length($user) or
865 $user = access_cfg("$some-user",'username');
866 my $host = access_cfg("$some-host");
867 return length($user) ? "$user\@$host" : $host;
870 sub access_gituserhost () {
871 return access_someuserhost('git');
874 sub access_giturl (;$) {
876 my $url = access_cfg('git-url','RETURN-UNDEF');
879 my $proto = access_cfg('git-proto', 'RETURN-UNDEF');
880 return undef unless defined $proto;
883 access_gituserhost().
884 access_cfg('git-path');
886 $suffix = access_cfg('git-url-suffix','RETURN-UNDEF');
889 return "$url/$package$suffix";
892 sub parsecontrolfh ($$;$) {
893 my ($fh, $desc, $allowsigned) = @_;
894 our $dpkgcontrolhash_noissigned;
897 my %opts = ('name' => $desc);
898 $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
899 $c = Dpkg::Control::Hash->new(%opts);
900 $c->parse($fh,$desc) or die "parsing of $desc failed";
901 last if $allowsigned;
902 last if $dpkgcontrolhash_noissigned;
903 my $issigned= $c->get_option('is_pgp_signed');
904 if (!defined $issigned) {
905 $dpkgcontrolhash_noissigned= 1;
906 seek $fh, 0,0 or die "seek $desc: $!";
907 } elsif ($issigned) {
908 fail "control file $desc is (already) PGP-signed. ".
909 " Note that dgit push needs to modify the .dsc and then".
910 " do the signature itself";
919 my ($file, $desc) = @_;
920 my $fh = new IO::Handle;
921 open $fh, '<', $file or die "$file: $!";
922 my $c = parsecontrolfh($fh,$desc);
923 $fh->error and die $!;
929 my ($dctrl,$field) = @_;
930 my $v = $dctrl->{$field};
931 return $v if defined $v;
932 fail "missing field $field in ".$dctrl->get_option('name');
936 my $c = Dpkg::Control::Hash->new(name => 'parsed changelog');
937 my $p = new IO::Handle;
938 my @cmd = (qw(dpkg-parsechangelog), @_);
939 open $p, '-|', @cmd or die $!;
941 $?=0; $!=0; close $p or failedcmd @cmd;
945 sub commit_getclogp ($) {
946 # Returns the parsed changelog hashref for a particular commit
948 our %commit_getclogp_memo;
949 my $memo = $commit_getclogp_memo{$objid};
950 return $memo if $memo;
952 my $mclog = ".git/dgit/clog-$objid";
953 runcmd shell_cmd "exec >$mclog", @git, qw(cat-file blob),
954 "$objid:debian/changelog";
955 $commit_getclogp_memo{$objid} = parsechangelog("-l$mclog");
960 defined $d or fail "getcwd failed: $!";
964 sub parse_dscdata () {
965 my $dscfh = new IO::File \$dscdata, '<' or die $!;
966 printdebug Dumper($dscdata) if $debuglevel>1;
967 $dsc = parsecontrolfh($dscfh,$dscurl,1);
968 printdebug Dumper($dsc) if $debuglevel>1;
973 sub archive_query ($;@) {
974 my ($method) = shift @_;
975 my $query = access_cfg('archive-query','RETURN-UNDEF');
976 $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
979 { no strict qw(refs); &{"${method}_${proto}"}($proto,$data,@_); }
982 sub pool_dsc_subpath ($$) {
983 my ($vsn,$component) = @_; # $package is implict arg
984 my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
985 return "/pool/$component/$prefix/$package/".dscfn($vsn);
988 #---------- `ftpmasterapi' archive query method (nascent) ----------
990 sub archive_api_query_cmd ($) {
992 my @cmd = (@curl, qw(-sS));
993 my $url = access_cfg('archive-query-url');
994 if ($url =~ m#^https://([-.0-9a-z]+)/#) {
996 my $keys = access_cfg('archive-query-tls-key','RETURN-UNDEF') //'';
997 foreach my $key (split /\:/, $keys) {
998 $key =~ s/\%HOST\%/$host/g;
1000 fail "for $url: stat $key: $!" unless $!==ENOENT;
1003 fail "config requested specific TLS key but do not know".
1004 " how to get curl to use exactly that EE key ($key)";
1005 # push @cmd, "--cacert", $key, "--capath", "/dev/enoent";
1006 # # Sadly the above line does not work because of changes
1007 # # to gnutls. The real fix for #790093 may involve
1008 # # new curl options.
1011 # Fixing #790093 properly will involve providing a value
1012 # for this on clients.
1013 my $kargs = access_cfg('archive-query-tls-curl-ca-args','RETURN-UNDEF');
1014 push @cmd, split / /, $kargs if defined $kargs;
1016 push @cmd, $url.$subpath;
1020 sub api_query ($$;$) {
1022 my ($data, $subpath, $ok404) = @_;
1023 badcfg "ftpmasterapi archive query method takes no data part"
1025 my @cmd = archive_api_query_cmd($subpath);
1026 my $url = $cmd[$#cmd];
1027 push @cmd, qw(-w %{http_code});
1028 my $json = cmdoutput @cmd;
1029 unless ($json =~ s/\d+\d+\d$//) {
1030 failedcmd_report_cmd undef, @cmd;
1031 fail "curl failed to print 3-digit HTTP code";
1034 return undef if $code eq '404' && $ok404;
1035 fail "fetch of $url gave HTTP code $code"
1036 unless $url =~ m#^file://# or $code =~ m/^2/;
1037 return decode_json($json);
1040 sub canonicalise_suite_ftpmasterapi {
1041 my ($proto,$data) = @_;
1042 my $suites = api_query($data, 'suites');
1044 foreach my $entry (@$suites) {
1046 my $v = $entry->{$_};
1047 defined $v && $v eq $isuite;
1048 } qw(codename name);
1049 push @matched, $entry;
1051 fail "unknown suite $isuite" unless @matched;
1054 @matched==1 or die "multiple matches for suite $isuite\n";
1055 $cn = "$matched[0]{codename}";
1056 defined $cn or die "suite $isuite info has no codename\n";
1057 $cn =~ m/^$suite_re$/ or die "suite $isuite maps to bad codename\n";
1059 die "bad ftpmaster api response: $@\n".Dumper(\@matched)
1064 sub archive_query_ftpmasterapi {
1065 my ($proto,$data) = @_;
1066 my $info = api_query($data, "dsc_in_suite/$isuite/$package");
1068 my $digester = Digest::SHA->new(256);
1069 foreach my $entry (@$info) {
1071 my $vsn = "$entry->{version}";
1072 my ($ok,$msg) = version_check $vsn;
1073 die "bad version: $msg\n" unless $ok;
1074 my $component = "$entry->{component}";
1075 $component =~ m/^$component_re$/ or die "bad component";
1076 my $filename = "$entry->{filename}";
1077 $filename && $filename !~ m#[^-+:._~0-9a-zA-Z/]|^[/.]|/[/.]#
1078 or die "bad filename";
1079 my $sha256sum = "$entry->{sha256sum}";
1080 $sha256sum =~ m/^[0-9a-f]+$/ or die "bad sha256sum";
1081 push @rows, [ $vsn, "/pool/$component/$filename",
1082 $digester, $sha256sum ];
1084 die "bad ftpmaster api response: $@\n".Dumper($entry)
1087 @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
1091 sub file_in_archive_ftpmasterapi {
1092 my ($proto,$data,$filename) = @_;
1093 my $pat = $filename;
1096 $pat =~ s#[^-+_.0-9a-z/]# sprintf '%%%02x', ord $& #ge;
1097 my $info = api_query($data, "file_in_archive/$pat", 1);
1100 #---------- `dummyapicat' archive query method ----------
1102 sub archive_query_dummycatapi { archive_query_ftpmasterapi @_; }
1103 sub canonicalise_suite_dummycatapi { canonicalise_suite_ftpmasterapi @_; }
1105 sub file_in_archive_dummycatapi ($$$) {
1106 my ($proto,$data,$filename) = @_;
1107 my $mirror = access_cfg('mirror');
1108 $mirror =~ s#^file://#/# or die "$mirror ?";
1110 my @cmd = (qw(sh -ec), '
1112 find -name "$2" -print0 |
1114 ', qw(x), $mirror, $filename);
1115 debugcmd "-|", @cmd;
1116 open FIA, "-|", @cmd or die $!;
1119 printdebug "| $_\n";
1120 m/^(\w+) (\S+)$/ or die "$_ ?";
1121 push @out, { sha256sum => $1, filename => $2 };
1123 close FIA or die failedcmd @cmd;
1127 #---------- `madison' archive query method ----------
1129 sub archive_query_madison {
1130 return map { [ @$_[0..1] ] } madison_get_parse(@_);
1133 sub madison_get_parse {
1134 my ($proto,$data) = @_;
1135 die unless $proto eq 'madison';
1136 if (!length $data) {
1137 $data= access_cfg('madison-distro','RETURN-UNDEF');
1138 $data //= access_basedistro();
1140 $rmad{$proto,$data,$package} ||= cmdoutput
1141 qw(rmadison -asource),"-s$isuite","-u$data",$package;
1142 my $rmad = $rmad{$proto,$data,$package};
1145 foreach my $l (split /\n/, $rmad) {
1146 $l =~ m{^ \s*( [^ \t|]+ )\s* \|
1147 \s*( [^ \t|]+ )\s* \|
1148 \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
1149 \s*( [^ \t|]+ )\s* }x or die "$rmad ?";
1150 $1 eq $package or die "$rmad $package ?";
1157 $component = access_cfg('archive-query-default-component');
1159 $5 eq 'source' or die "$rmad ?";
1160 push @out, [$vsn,pool_dsc_subpath($vsn,$component),$newsuite];
1162 return sort { -version_compare($a->[0],$b->[0]); } @out;
1165 sub canonicalise_suite_madison {
1166 # madison canonicalises for us
1167 my @r = madison_get_parse(@_);
1169 "unable to canonicalise suite using package $package".
1170 " which does not appear to exist in suite $isuite;".
1171 " --existing-package may help";
1175 sub file_in_archive_madison { return undef; }
1177 #---------- `sshpsql' archive query method ----------
1180 my ($data,$runeinfo,$sql) = @_;
1181 if (!length $data) {
1182 $data= access_someuserhost('sshpsql').':'.
1183 access_cfg('sshpsql-dbname');
1185 $data =~ m/:/ or badcfg "invalid sshpsql method string \`$data'";
1186 my ($userhost,$dbname) = ($`,$'); #';
1188 my @cmd = (access_cfg_ssh, $userhost,
1189 access_runeinfo("ssh-psql $runeinfo").
1190 " export LC_MESSAGES=C; export LC_CTYPE=C;".
1191 " ".shellquote qw(psql -A), $dbname, qw(-c), $sql);
1193 open P, "-|", @cmd or die $!;
1196 printdebug(">|$_|\n");
1199 $!=0; $?=0; close P or failedcmd @cmd;
1201 my $nrows = pop @rows;
1202 $nrows =~ s/^\((\d+) rows?\)$/$1/ or die "$nrows ?";
1203 @rows == $nrows+1 or die "$nrows ".(scalar @rows)." ?";
1204 @rows = map { [ split /\|/, $_ ] } @rows;
1205 my $ncols = scalar @{ shift @rows };
1206 die if grep { scalar @$_ != $ncols } @rows;
1210 sub sql_injection_check {
1211 foreach (@_) { die "$_ $& ?" if m{[^-+=:_.,/0-9a-zA-Z]}; }
1214 sub archive_query_sshpsql ($$) {
1215 my ($proto,$data) = @_;
1216 sql_injection_check $isuite, $package;
1217 my @rows = sshpsql($data, "archive-query $isuite $package", <<END);
1218 SELECT source.version, component.name, files.filename, files.sha256sum
1220 JOIN src_associations ON source.id = src_associations.source
1221 JOIN suite ON suite.id = src_associations.suite
1222 JOIN dsc_files ON dsc_files.source = source.id
1223 JOIN files_archive_map ON files_archive_map.file_id = dsc_files.file
1224 JOIN component ON component.id = files_archive_map.component_id
1225 JOIN files ON files.id = dsc_files.file
1226 WHERE ( suite.suite_name='$isuite' OR suite.codename='$isuite' )
1227 AND source.source='$package'
1228 AND files.filename LIKE '%.dsc';
1230 @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
1231 my $digester = Digest::SHA->new(256);
1233 my ($vsn,$component,$filename,$sha256sum) = @$_;
1234 [ $vsn, "/pool/$component/$filename",$digester,$sha256sum ];
1239 sub canonicalise_suite_sshpsql ($$) {
1240 my ($proto,$data) = @_;
1241 sql_injection_check $isuite;
1242 my @rows = sshpsql($data, "canonicalise-suite $isuite", <<END);
1243 SELECT suite.codename
1244 FROM suite where suite_name='$isuite' or codename='$isuite';
1246 @rows = map { $_->[0] } @rows;
1247 fail "unknown suite $isuite" unless @rows;
1248 die "ambiguous $isuite: @rows ?" if @rows>1;
1252 sub file_in_archive_sshpsql ($$$) { return undef; }
1254 #---------- `dummycat' archive query method ----------
1256 sub canonicalise_suite_dummycat ($$) {
1257 my ($proto,$data) = @_;
1258 my $dpath = "$data/suite.$isuite";
1259 if (!open C, "<", $dpath) {
1260 $!==ENOENT or die "$dpath: $!";
1261 printdebug "dummycat canonicalise_suite $isuite $dpath ENOENT\n";
1265 chomp or die "$dpath: $!";
1267 printdebug "dummycat canonicalise_suite $isuite $dpath = $_\n";
1271 sub archive_query_dummycat ($$) {
1272 my ($proto,$data) = @_;
1273 canonicalise_suite();
1274 my $dpath = "$data/package.$csuite.$package";
1275 if (!open C, "<", $dpath) {
1276 $!==ENOENT or die "$dpath: $!";
1277 printdebug "dummycat query $csuite $package $dpath ENOENT\n";
1285 printdebug "dummycat query $csuite $package $dpath | $_\n";
1286 my @row = split /\s+/, $_;
1287 @row==2 or die "$dpath: $_ ?";
1290 C->error and die "$dpath: $!";
1292 return sort { -version_compare($a->[0],$b->[0]); } @rows;
1295 sub file_in_archive_dummycat () { return undef; }
1297 #---------- tag format handling ----------
1299 sub access_cfg_tagformats () {
1300 split /\,/, access_cfg('dgit-tag-format');
1303 sub need_tagformat ($$) {
1304 my ($fmt, $why) = @_;
1305 fail "need to use tag format $fmt ($why) but also need".
1306 " to use tag format $tagformat_want->[0] ($tagformat_want->[1])".
1307 " - no way to proceed"
1308 if $tagformat_want && $tagformat_want->[0] ne $fmt;
1309 $tagformat_want = [$fmt, $why, $tagformat_want->[2] // 0];
1312 sub select_tagformat () {
1314 return if $tagformatfn && !$tagformat_want;
1315 die 'bug' if $tagformatfn && $tagformat_want;
1316 # ... $tagformat_want assigned after previous select_tagformat
1318 my (@supported) = grep { $_ =~ m/^(?:old|new)$/ } access_cfg_tagformats();
1319 printdebug "select_tagformat supported @supported\n";
1321 $tagformat_want //= [ $supported[0], "distro access configuration", 0 ];
1322 printdebug "select_tagformat specified @$tagformat_want\n";
1324 my ($fmt,$why,$override) = @$tagformat_want;
1326 fail "target distro supports tag formats @supported".
1327 " but have to use $fmt ($why)"
1329 or grep { $_ eq $fmt } @supported;
1331 $tagformat_want = undef;
1333 $tagformatfn = ${*::}{"debiantag_$fmt"};
1335 fail "trying to use unknown tag format \`$fmt' ($why) !"
1336 unless $tagformatfn;
1339 #---------- archive query entrypoints and rest of program ----------
1341 sub canonicalise_suite () {
1342 return if defined $csuite;
1343 fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
1344 $csuite = archive_query('canonicalise_suite');
1345 if ($isuite ne $csuite) {
1346 progress "canonical suite name for $isuite is $csuite";
1350 sub get_archive_dsc () {
1351 canonicalise_suite();
1352 my @vsns = archive_query('archive_query');
1353 foreach my $vinfo (@vsns) {
1354 my ($vsn,$subpath,$digester,$digest) = @$vinfo;
1355 $dscurl = access_cfg('mirror').$subpath;
1356 $dscdata = url_get($dscurl);
1358 $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
1363 $digester->add($dscdata);
1364 my $got = $digester->hexdigest();
1366 fail "$dscurl has hash $got but".
1367 " archive told us to expect $digest";
1370 my $fmt = getfield $dsc, 'Format';
1371 $format_ok{$fmt} or forceable_fail [qw(unsupported-source-format)],
1372 "unsupported source format $fmt, sorry";
1374 $dsc_checked = !!$digester;
1375 printdebug "get_archive_dsc: Version ".(getfield $dsc, 'Version')."\n";
1379 printdebug "get_archive_dsc: nothing in archive, returning undef\n";
1382 sub check_for_git ();
1383 sub check_for_git () {
1385 my $how = access_cfg('git-check');
1386 if ($how eq 'ssh-cmd') {
1388 (access_cfg_ssh, access_gituserhost(),
1389 access_runeinfo("git-check $package").
1390 " set -e; cd ".access_cfg('git-path').";".
1391 " if test -d $package.git; then echo 1; else echo 0; fi");
1392 my $r= cmdoutput @cmd;
1393 if (defined $r and $r =~ m/^divert (\w+)$/) {
1395 my ($usedistro,) = access_distros();
1396 # NB that if we are pushing, $usedistro will be $distro/push
1397 $instead_distro= cfg("dgit-distro.$usedistro.diverts.$divert");
1398 $instead_distro =~ s{^/}{ access_basedistro()."/" }e;
1399 progress "diverting to $divert (using config for $instead_distro)";
1400 return check_for_git();
1402 failedcmd @cmd unless defined $r and $r =~ m/^[01]$/;
1404 } elsif ($how eq 'url') {
1405 my $prefix = access_cfg('git-check-url','git-url');
1406 my $suffix = access_cfg('git-check-suffix','git-suffix',
1407 'RETURN-UNDEF') // '.git';
1408 my $url = "$prefix/$package$suffix";
1409 my @cmd = (@curl, qw(-sS -I), $url);
1410 my $result = cmdoutput @cmd;
1411 $result =~ s/^\S+ 200 .*\n\r?\n//;
1412 # curl -sS -I with https_proxy prints
1413 # HTTP/1.0 200 Connection established
1414 $result =~ m/^\S+ (404|200) /s or
1415 fail "unexpected results from git check query - ".
1416 Dumper($prefix, $result);
1418 if ($code eq '404') {
1420 } elsif ($code eq '200') {
1425 } elsif ($how eq 'true') {
1427 } elsif ($how eq 'false') {
1430 badcfg "unknown git-check \`$how'";
1434 sub create_remote_git_repo () {
1435 my $how = access_cfg('git-create');
1436 if ($how eq 'ssh-cmd') {
1438 (access_cfg_ssh, access_gituserhost(),
1439 access_runeinfo("git-create $package").
1440 "set -e; cd ".access_cfg('git-path').";".
1441 " cp -a _template $package.git");
1442 } elsif ($how eq 'true') {
1445 badcfg "unknown git-create \`$how'";
1449 our ($dsc_hash,$lastpush_mergeinput);
1451 our $ud = '.git/dgit/unpack';
1461 sub mktree_in_ud_here () {
1462 runcmd qw(git init -q);
1463 runcmd qw(git config gc.auto 0);
1464 rmtree('.git/objects');
1465 symlink '../../../../objects','.git/objects' or die $!;
1468 sub git_write_tree () {
1469 my $tree = cmdoutput @git, qw(write-tree);
1470 $tree =~ m/^\w+$/ or die "$tree ?";
1474 sub remove_stray_gits () {
1475 my @gitscmd = qw(find -name .git -prune -print0);
1476 debugcmd "|",@gitscmd;
1477 open GITS, "-|", @gitscmd or die $!;
1482 print STDERR "$us: warning: removing from source package: ",
1483 (messagequote $_), "\n";
1487 $!=0; $?=0; close GITS or failedcmd @gitscmd;
1490 sub mktree_in_ud_from_only_subdir (;$) {
1493 # changes into the subdir
1495 die "expected one subdir but found @dirs ?" unless @dirs==1;
1496 $dirs[0] =~ m#^([^/]+)/\.$# or die;
1500 remove_stray_gits();
1501 mktree_in_ud_here();
1503 my ($format, $fopts) = get_source_format();
1504 if (madformat($format)) {
1509 runcmd @git, qw(add -Af);
1510 my $tree=git_write_tree();
1511 return ($tree,$dir);
1514 our @files_csum_info_fields =
1515 (['Checksums-Sha256','Digest::SHA', 'new(256)', 'sha256sum'],
1516 ['Checksums-Sha1', 'Digest::SHA', 'new(1)', 'sha1sum'],
1517 ['Files', 'Digest::MD5', 'new()', 'md5sum']);
1519 sub dsc_files_info () {
1520 foreach my $csumi (@files_csum_info_fields) {
1521 my ($fname, $module, $method) = @$csumi;
1522 my $field = $dsc->{$fname};
1523 next unless defined $field;
1524 eval "use $module; 1;" or die $@;
1526 foreach (split /\n/, $field) {
1528 m/^(\w+) (\d+) (\S+)$/ or
1529 fail "could not parse .dsc $fname line \`$_'";
1530 my $digester = eval "$module"."->$method;" or die $@;
1535 Digester => $digester,
1540 fail "missing any supported Checksums-* or Files field in ".
1541 $dsc->get_option('name');
1545 map { $_->{Filename} } dsc_files_info();
1548 sub files_compare_inputs (@) {
1553 my $showinputs = sub {
1554 return join "; ", map { $_->get_option('name') } @$inputs;
1557 foreach my $in (@$inputs) {
1559 my $in_name = $in->get_option('name');
1561 printdebug "files_compare_inputs $in_name\n";
1563 foreach my $csumi (@files_csum_info_fields) {
1564 my ($fname) = @$csumi;
1565 printdebug "files_compare_inputs $in_name $fname\n";
1567 my $field = $in->{$fname};
1568 next unless defined $field;
1571 foreach (split /\n/, $field) {
1574 my ($info, $f) = m/^(\w+ \d+) (?:\S+ \S+ )?(\S+)$/ or
1575 fail "could not parse $in_name $fname line \`$_'";
1577 printdebug "files_compare_inputs $in_name $fname $f\n";
1581 my $re = \ $record{$f}{$fname};
1583 $fchecked{$f}{$in_name} = 1;
1585 fail "hash or size of $f varies in $fname fields".
1586 " (between: ".$showinputs->().")";
1591 @files = sort @files;
1592 $expected_files //= \@files;
1593 "@$expected_files" eq "@files" or
1594 fail "file list in $in_name varies between hash fields!";
1597 fail "$in_name has no files list field(s)";
1599 printdebug "files_compare_inputs ".Dumper(\%fchecked, \%record)
1602 grep { keys %$_ == @$inputs-1 } values %fchecked
1603 or fail "no file appears in all file lists".
1604 " (looked in: ".$showinputs->().")";
1607 sub is_orig_file_in_dsc ($$) {
1608 my ($f, $dsc_files_info) = @_;
1609 return 0 if @$dsc_files_info <= 1;
1610 # One file means no origs, and the filename doesn't have a "what
1611 # part of dsc" component. (Consider versions ending `.orig'.)
1612 return 0 unless $f =~ m/\.$orig_f_tail_re$/o;
1616 sub is_orig_file_of_vsn ($$) {
1617 my ($f, $upstreamvsn) = @_;
1618 my $base = srcfn $upstreamvsn, '';
1619 return 0 unless $f =~ m/^\Q$base\E\.$orig_f_tail_re$/;
1623 sub changes_update_origs_from_dsc ($$$$) {
1624 my ($dsc, $changes, $upstreamvsn, $changesfile) = @_;
1626 printdebug "checking origs needed ($upstreamvsn)...\n";
1627 $_ = getfield $changes, 'Files';
1628 m/^\w+ \d+ (\S+ \S+) \S+$/m or
1629 fail "cannot find section/priority from .changes Files field";
1630 my $placementinfo = $1;
1632 printdebug "checking origs needed placement '$placementinfo'...\n";
1633 foreach my $l (split /\n/, getfield $dsc, 'Files') {
1634 $l =~ m/\S+$/ or next;
1636 printdebug "origs $file | $l\n";
1637 next unless is_orig_file_of_vsn $file, $upstreamvsn;
1638 printdebug "origs $file is_orig\n";
1639 my $have = archive_query('file_in_archive', $file);
1640 if (!defined $have) {
1642 archive does not support .orig check; hope you used --ch:--sa/-sd if needed
1648 printdebug "origs $file \$#\$have=$#$have\n";
1649 foreach my $h (@$have) {
1652 foreach my $csumi (@files_csum_info_fields) {
1653 my ($fname, $module, $method, $archivefield) = @$csumi;
1654 next unless defined $h->{$archivefield};
1655 $_ = $dsc->{$fname};
1656 next unless defined;
1657 m/^(\w+) .* \Q$file\E$/m or
1658 fail ".dsc $fname missing entry for $file";
1659 if ($h->{$archivefield} eq $1) {
1663 "$archivefield: $h->{$archivefield} (archive) != $1 (local .dsc)";
1666 die "$file ".Dumper($h)." ?!" if $same && @differ;
1669 push @found_differ, "archive $h->{filename}: ".join "; ", @differ
1672 print "origs $file f.same=$found_same #f._differ=$#found_differ\n";
1673 if (@found_differ && !$found_same) {
1675 "archive contains $file with different checksum",
1678 # Now we edit the changes file to add or remove it
1679 foreach my $csumi (@files_csum_info_fields) {
1680 my ($fname, $module, $method, $archivefield) = @$csumi;
1681 next unless defined $changes->{$fname};
1683 # in archive, delete from .changes if it's there
1684 $changed{$file} = "removed" if
1685 $changes->{$fname} =~ s/^.* \Q$file\E$(?:)\n//m;
1686 } elsif ($changes->{$fname} =~ m/^.* \Q$file\E$(?:)\n/m) {
1687 # not in archive, but it's here in the .changes
1689 my $dsc_data = getfield $dsc, $fname;
1690 $dsc_data =~ m/^(.* \Q$file\E$)\n/m or die "$dsc_data $file ?";
1692 $extra =~ s/ \d+ /$&$placementinfo /
1693 or die "$fname $extra >$dsc_data< ?"
1694 if $fname eq 'Files';
1695 $changes->{$fname} .= "\n". $extra;
1696 $changed{$file} = "added";
1701 foreach my $file (keys %changed) {
1703 "edited .changes for archive .orig contents: %s %s",
1704 $changed{$file}, $file;
1706 my $chtmp = "$changesfile.tmp";
1707 $changes->save($chtmp);
1709 rename $chtmp,$changesfile or die "$changesfile $!";
1711 progress "[new .changes left in $changesfile]";
1714 progress "$changesfile already has appropriate .orig(s) (if any)";
1718 sub make_commit ($) {
1720 return cmdoutput @git, qw(hash-object -w -t commit), $file;
1723 sub make_commit_text ($) {
1726 my @cmd = (@git, qw(hash-object -w -t commit --stdin));
1728 print Dumper($text) if $debuglevel > 1;
1729 my $child = open2($out, $in, @cmd) or die $!;
1732 print $in $text or die $!;
1733 close $in or die $!;
1735 $h =~ m/^\w+$/ or die;
1737 printdebug "=> $h\n";
1740 waitpid $child, 0 == $child or die "$child $!";
1741 $? and failedcmd @cmd;
1745 sub clogp_authline ($) {
1747 my $author = getfield $clogp, 'Maintainer';
1748 $author =~ s#,.*##ms;
1749 my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
1750 my $authline = "$author $date";
1751 $authline =~ m/$git_authline_re/o or
1752 fail "unexpected commit author line format \`$authline'".
1753 " (was generated from changelog Maintainer field)";
1754 return ($1,$2,$3) if wantarray;
1758 sub vendor_patches_distro ($$) {
1759 my ($checkdistro, $what) = @_;
1760 return unless defined $checkdistro;
1762 my $series = "debian/patches/\L$checkdistro\E.series";
1763 printdebug "checking for vendor-specific $series ($what)\n";
1765 if (!open SERIES, "<", $series) {
1766 die "$series $!" unless $!==ENOENT;
1775 Unfortunately, this source package uses a feature of dpkg-source where
1776 the same source package unpacks to different source code on different
1777 distros. dgit cannot safely operate on such packages on affected
1778 distros, because the meaning of source packages is not stable.
1780 Please ask the distro/maintainer to remove the distro-specific series
1781 files and use a different technique (if necessary, uploading actually
1782 different packages, if different distros are supposed to have
1786 fail "Found active distro-specific series file for".
1787 " $checkdistro ($what): $series, cannot continue";
1789 die "$series $!" if SERIES->error;
1793 sub check_for_vendor_patches () {
1794 # This dpkg-source feature doesn't seem to be documented anywhere!
1795 # But it can be found in the changelog (reformatted):
1797 # commit 4fa01b70df1dc4458daee306cfa1f987b69da58c
1798 # Author: Raphael Hertzog <hertzog@debian.org>
1799 # Date: Sun Oct 3 09:36:48 2010 +0200
1801 # dpkg-source: correctly create .pc/.quilt_series with alternate
1804 # If you have debian/patches/ubuntu.series and you were
1805 # unpacking the source package on ubuntu, quilt was still
1806 # directed to debian/patches/series instead of
1807 # debian/patches/ubuntu.series.
1809 # debian/changelog | 3 +++
1810 # scripts/Dpkg/Source/Package/V3/quilt.pm | 4 +++-
1811 # 2 files changed, 6 insertions(+), 1 deletion(-)
1814 vendor_patches_distro($ENV{DEB_VENDOR}, "DEB_VENDOR");
1815 vendor_patches_distro(Dpkg::Vendor::get_current_vendor(),
1816 "Dpkg::Vendor \`current vendor'");
1817 vendor_patches_distro(access_basedistro(),
1818 "distro being accessed");
1821 sub generate_commits_from_dsc () {
1822 # See big comment in fetch_from_archive, below.
1823 # See also README.dsc-import.
1827 my @dfi = dsc_files_info();
1828 foreach my $fi (@dfi) {
1829 my $f = $fi->{Filename};
1830 die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
1832 printdebug "considering linking $f: ";
1834 link_ltarget "../../../../$f", $f
1835 or ((printdebug "($!) "), 0)
1839 printdebug "linked.\n";
1841 complete_file_from_dsc('.', $fi)
1844 if (is_orig_file_in_dsc($f, \@dfi)) {
1845 link $f, "../../../../$f"
1851 # We unpack and record the orig tarballs first, so that we only
1852 # need disk space for one private copy of the unpacked source.
1853 # But we can't make them into commits until we have the metadata
1854 # from the debian/changelog, so we record the tree objects now and
1855 # make them into commits later.
1857 my $upstreamv = $dsc->{version};
1858 $upstreamv =~ s/-[^-]+$//;
1859 my $orig_f_base = srcfn $upstreamv, '';
1861 foreach my $fi (@dfi) {
1862 # We actually import, and record as a commit, every tarball
1863 # (unless there is only one file, in which case there seems
1866 my $f = $fi->{Filename};
1867 printdebug "import considering $f ";
1868 (printdebug "only one dfi\n"), next if @dfi == 1;
1869 (printdebug "not tar\n"), next unless $f =~ m/\.tar(\.\w+)?$/;
1870 (printdebug "signature\n"), next if $f =~ m/$orig_f_sig_re$/o;
1874 $f =~ m/^\Q$orig_f_base\E\.([^._]+)?\.tar(?:\.\w+)?$/;
1876 printdebug "Y ", (join ' ', map { $_//"(none)" }
1877 $compr_ext, $orig_f_part
1880 my $input = new IO::File $f, '<' or die "$f $!";
1884 if (defined $compr_ext) {
1886 Dpkg::Compression::compression_guess_from_filename $f;
1887 fail "Dpkg::Compression cannot handle file $f in source package"
1888 if defined $compr_ext && !defined $cname;
1890 new Dpkg::Compression::Process compression => $cname;
1891 my @compr_cmd = $compr_proc->get_uncompress_cmdline();
1892 my $compr_fh = new IO::Handle;
1893 my $compr_pid = open $compr_fh, "-|" // die $!;
1895 open STDIN, "<&", $input or die $!;
1897 die "dgit (child): exec $compr_cmd[0]: $!\n";
1902 rmtree "../unpack-tar";
1903 mkdir "../unpack-tar" or die $!;
1904 my @tarcmd = qw(tar -x -f -
1905 --no-same-owner --no-same-permissions
1906 --no-acls --no-xattrs --no-selinux);
1907 my $tar_pid = fork // die $!;
1909 chdir "../unpack-tar" or die $!;
1910 open STDIN, "<&", $input or die $!;
1912 die "dgit (child): exec $tarcmd[0]: $!";
1914 $!=0; (waitpid $tar_pid, 0) == $tar_pid or die $!;
1915 !$? or failedcmd @tarcmd;
1918 (@compr_cmd ? failedcmd @compr_cmd
1920 # finally, we have the results in "tarball", but maybe
1921 # with the wrong permissions
1923 runcmd qw(chmod -R +rwX ../unpack-tar);
1924 changedir "../unpack-tar";
1925 my ($tree) = mktree_in_ud_from_only_subdir(1);
1926 changedir "../../unpack";
1927 rmtree "../unpack-tar";
1929 my $ent = [ $f, $tree ];
1931 Orig => !!$orig_f_part,
1932 Sort => (!$orig_f_part ? 2 :
1933 $orig_f_part =~ m/-/g ? 1 :
1941 # put any without "_" first (spec is not clear whether files
1942 # are always in the usual order). Tarballs without "_" are
1943 # the main orig or the debian tarball.
1944 $a->{Sort} <=> $b->{Sort} or
1948 my $any_orig = grep { $_->{Orig} } @tartrees;
1950 my $dscfn = "$package.dsc";
1952 my $treeimporthow = 'package';
1954 open D, ">", $dscfn or die "$dscfn: $!";
1955 print D $dscdata or die "$dscfn: $!";
1956 close D or die "$dscfn: $!";
1957 my @cmd = qw(dpkg-source);
1958 push @cmd, '--no-check' if $dsc_checked;
1959 if (madformat $dsc->{format}) {
1960 push @cmd, '--skip-patches';
1961 $treeimporthow = 'unpatched';
1963 push @cmd, qw(-x --), $dscfn;
1966 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1967 if (madformat $dsc->{format}) {
1968 check_for_vendor_patches();
1972 if (madformat $dsc->{format}) {
1973 my @pcmd = qw(dpkg-source --before-build .);
1974 runcmd shell_cmd 'exec >/dev/null', @pcmd;
1976 runcmd @git, qw(add -Af);
1977 $dappliedtree = git_write_tree();
1980 my @clogcmd = qw(dpkg-parsechangelog --format rfc822 --all);
1981 debugcmd "|",@clogcmd;
1982 open CLOGS, "-|", @clogcmd or die $!;
1987 printdebug "import clog search...\n";
1990 my $stanzatext = do { local $/=""; <CLOGS>; };
1991 printdebug "import clogp ".Dumper($stanzatext) if $debuglevel>1;
1992 last if !defined $stanzatext;
1994 my $desc = "package changelog, entry no.$.";
1995 open my $stanzafh, "<", \$stanzatext or die;
1996 my $thisstanza = parsecontrolfh $stanzafh, $desc, 1;
1997 $clogp //= $thisstanza;
1999 printdebug "import clog $thisstanza->{version} $desc...\n";
2001 last if !$any_orig; # we don't need $r1clogp
2003 # We look for the first (most recent) changelog entry whose
2004 # version number is lower than the upstream version of this
2005 # package. Then the last (least recent) previous changelog
2006 # entry is treated as the one which introduced this upstream
2007 # version and used for the synthetic commits for the upstream
2010 # One might think that a more sophisticated algorithm would be
2011 # necessary. But: we do not want to scan the whole changelog
2012 # file. Stopping when we see an earlier version, which
2013 # necessarily then is an earlier upstream version, is the only
2014 # realistic way to do that. Then, either the earliest
2015 # changelog entry we have seen so far is indeed the earliest
2016 # upload of this upstream version; or there are only changelog
2017 # entries relating to later upstream versions (which is not
2018 # possible unless the changelog and .dsc disagree about the
2019 # version). Then it remains to choose between the physically
2020 # last entry in the file, and the one with the lowest version
2021 # number. If these are not the same, we guess that the
2022 # versions were created in a non-monotic order rather than
2023 # that the changelog entries have been misordered.
2025 printdebug "import clog $thisstanza->{version} vs $upstreamv...\n";
2027 last if version_compare($thisstanza->{version}, $upstreamv) < 0;
2028 $r1clogp = $thisstanza;
2030 printdebug "import clog $r1clogp->{version} becomes r1\n";
2032 die $! if CLOGS->error;
2033 close CLOGS or $?==SIGPIPE or failedcmd @clogcmd;
2035 $clogp or fail "package changelog has no entries!";
2037 my $authline = clogp_authline $clogp;
2038 my $changes = getfield $clogp, 'Changes';
2039 my $cversion = getfield $clogp, 'Version';
2042 $r1clogp //= $clogp; # maybe there's only one entry;
2043 my $r1authline = clogp_authline $r1clogp;
2044 # Strictly, r1authline might now be wrong if it's going to be
2045 # unused because !$any_orig. Whatever.
2047 printdebug "import tartrees authline $authline\n";
2048 printdebug "import tartrees r1authline $r1authline\n";
2050 foreach my $tt (@tartrees) {
2051 printdebug "import tartree $tt->{F} $tt->{Tree}\n";
2053 $tt->{Commit} = make_commit_text($tt->{Orig} ? <<END_O : <<END_T);
2056 committer $r1authline
2060 [dgit import orig $tt->{F}]
2068 [dgit import tarball $package $cversion $tt->{F}]
2073 printdebug "import main commit\n";
2075 open C, ">../commit.tmp" or die $!;
2076 print C <<END or die $!;
2079 print C <<END or die $! foreach @tartrees;
2082 print C <<END or die $!;
2088 [dgit import $treeimporthow $package $cversion]
2092 my $rawimport_hash = make_commit qw(../commit.tmp);
2094 if (madformat $dsc->{format}) {
2095 printdebug "import apply patches...\n";
2097 # regularise the state of the working tree so that
2098 # the checkout of $rawimport_hash works nicely.
2099 my $dappliedcommit = make_commit_text(<<END);
2106 runcmd @git, qw(checkout -q -b dapplied), $dappliedcommit;
2108 runcmd @git, qw(checkout -q -b unpa), $rawimport_hash;
2110 # We need the answers to be reproducible
2111 my @authline = clogp_authline($clogp);
2112 local $ENV{GIT_COMMITTER_NAME} = $authline[0];
2113 local $ENV{GIT_COMMITTER_EMAIL} = $authline[1];
2114 local $ENV{GIT_COMMITTER_DATE} = $authline[2];
2115 local $ENV{GIT_AUTHOR_NAME} = $authline[0];
2116 local $ENV{GIT_AUTHOR_EMAIL} = $authline[1];
2117 local $ENV{GIT_AUTHOR_DATE} = $authline[2];
2119 my $path = $ENV{PATH} or die;
2121 foreach my $use_absurd (qw(0 1)) {
2122 local $ENV{PATH} = $path;
2125 progress "warning: $@";
2126 $path = "$absurdity:$path";
2127 progress "$us: trying slow absurd-git-apply...";
2128 rename "../../gbp-pq-output","../../gbp-pq-output.0"
2133 die "forbid absurd git-apply\n" if $use_absurd
2134 && forceing [qw(import-gitapply-no-absurd)];
2135 die "only absurd git-apply!\n" if !$use_absurd
2136 && forceing [qw(import-gitapply-absurd)];
2138 local $ENV{PATH} = $path if $use_absurd;
2140 my @showcmd = (gbp_pq, qw(import));
2141 my @realcmd = shell_cmd
2142 'exec >/dev/null 2>../../gbp-pq-output', @showcmd;
2143 debugcmd "+",@realcmd;
2144 if (system @realcmd) {
2145 die +(shellquote @showcmd).
2147 failedcmd_waitstatus()."\n";
2150 my $gapplied = git_rev_parse('HEAD');
2151 my $gappliedtree = cmdoutput @git, qw(rev-parse HEAD:);
2152 $gappliedtree eq $dappliedtree or
2154 gbp-pq import and dpkg-source disagree!
2155 gbp-pq import gave commit $gapplied
2156 gbp-pq import gave tree $gappliedtree
2157 dpkg-source --before-build gave tree $dappliedtree
2159 $rawimport_hash = $gapplied;
2164 { local $@; eval { runcmd qw(cat ../../gbp-pq-output); }; }
2169 progress "synthesised git commit from .dsc $cversion";
2171 my $rawimport_mergeinput = {
2172 Commit => $rawimport_hash,
2173 Info => "Import of source package",
2175 my @output = ($rawimport_mergeinput);
2177 if ($lastpush_mergeinput) {
2178 my $oldclogp = mergeinfo_getclogp($lastpush_mergeinput);
2179 my $oversion = getfield $oldclogp, 'Version';
2181 version_compare($oversion, $cversion);
2183 @output = ($rawimport_mergeinput, $lastpush_mergeinput,
2184 { Message => <<END, ReverseParents => 1 });
2185 Record $package ($cversion) in archive suite $csuite
2187 } elsif ($vcmp > 0) {
2188 print STDERR <<END or die $!;
2190 Version actually in archive: $cversion (older)
2191 Last version pushed with dgit: $oversion (newer or same)
2194 @output = $lastpush_mergeinput;
2196 # Same version. Use what's in the server git branch,
2197 # discarding our own import. (This could happen if the
2198 # server automatically imports all packages into git.)
2199 @output = $lastpush_mergeinput;
2202 changedir '../../../..';
2207 sub complete_file_from_dsc ($$) {
2208 our ($dstdir, $fi) = @_;
2209 # Ensures that we have, in $dir, the file $fi, with the correct
2210 # contents. (Downloading it from alongside $dscurl if necessary.)
2212 my $f = $fi->{Filename};
2213 my $tf = "$dstdir/$f";
2216 if (stat_exists $tf) {
2217 progress "using existing $f";
2219 printdebug "$tf does not exist, need to fetch\n";
2221 $furl =~ s{/[^/]+$}{};
2223 die "$f ?" unless $f =~ m/^\Q${package}\E_/;
2224 die "$f ?" if $f =~ m#/#;
2225 runcmd_ordryrun_local @curl,qw(-f -o),$tf,'--',"$furl";
2226 return 0 if !act_local();
2230 open F, "<", "$tf" or die "$tf: $!";
2231 $fi->{Digester}->reset();
2232 $fi->{Digester}->addfile(*F);
2233 F->error and die $!;
2234 my $got = $fi->{Digester}->hexdigest();
2235 $got eq $fi->{Hash} or
2236 fail "file $f has hash $got but .dsc".
2237 " demands hash $fi->{Hash} ".
2238 ($downloaded ? "(got wrong file from archive!)"
2239 : "(perhaps you should delete this file?)");
2244 sub ensure_we_have_orig () {
2245 my @dfi = dsc_files_info();
2246 foreach my $fi (@dfi) {
2247 my $f = $fi->{Filename};
2248 next unless is_orig_file_in_dsc($f, \@dfi);
2249 complete_file_from_dsc('..', $fi)
2254 sub git_fetch_us () {
2255 # Want to fetch only what we are going to use, unless
2256 # deliberately-not-ff, in which case we must fetch everything.
2258 my @specs = deliberately_not_fast_forward ? qw(tags/*) :
2260 (quiltmode_splitbrain
2261 ? (map { $_->('*',access_basedistro) }
2262 \&debiantag_new, \&debiantag_maintview)
2263 : debiantags('*',access_basedistro));
2264 push @specs, server_branch($csuite);
2265 push @specs, qw(heads/*) if deliberately_not_fast_forward;
2267 # This is rather miserable:
2268 # When git fetch --prune is passed a fetchspec ending with a *,
2269 # it does a plausible thing. If there is no * then:
2270 # - it matches subpaths too, even if the supplied refspec
2271 # starts refs, and behaves completely madly if the source
2272 # has refs/refs/something. (See, for example, Debian #NNNN.)
2273 # - if there is no matching remote ref, it bombs out the whole
2275 # We want to fetch a fixed ref, and we don't know in advance
2276 # if it exists, so this is not suitable.
2278 # Our workaround is to use git ls-remote. git ls-remote has its
2279 # own qairks. Notably, it has the absurd multi-tail-matching
2280 # behaviour: git ls-remote R refs/foo can report refs/foo AND
2281 # refs/refs/foo etc.
2283 # Also, we want an idempotent snapshot, but we have to make two
2284 # calls to the remote: one to git ls-remote and to git fetch. The
2285 # solution is use git ls-remote to obtain a target state, and
2286 # git fetch to try to generate it. If we don't manage to generate
2287 # the target state, we try again.
2289 my $specre = join '|', map {
2295 printdebug "git_fetch_us specre=$specre\n";
2296 my $wanted_rref = sub {
2298 return m/^(?:$specre)$/o;
2301 my $fetch_iteration = 0;
2304 if (++$fetch_iteration > 10) {
2305 fail "too many iterations trying to get sane fetch!";
2308 my @look = map { "refs/$_" } @specs;
2309 my @lcmd = (@git, qw(ls-remote -q --refs), access_giturl(), @look);
2313 open GITLS, "-|", @lcmd or die $!;
2315 printdebug "=> ", $_;
2316 m/^(\w+)\s+(\S+)\n/ or die "ls-remote $_ ?";
2317 my ($objid,$rrefname) = ($1,$2);
2318 if (!$wanted_rref->($rrefname)) {
2320 warning: git ls-remote @look reported $rrefname; this is silly, ignoring it.
2324 $wantr{$rrefname} = $objid;
2327 close GITLS or failedcmd @lcmd;
2329 # OK, now %want is exactly what we want for refs in @specs
2331 return () if !m/\*$/ && !exists $wantr{"refs/$_"};
2332 "+refs/$_:".lrfetchrefs."/$_";
2335 my @fcmd = (@git, qw(fetch -p -n -q), access_giturl(), @fspecs);
2336 runcmd_ordryrun_local @git, qw(fetch -p -n -q), access_giturl(),
2339 %lrfetchrefs_f = ();
2342 git_for_each_ref(lrfetchrefs, sub {
2343 my ($objid,$objtype,$lrefname,$reftail) = @_;
2344 $lrfetchrefs_f{$lrefname} = $objid;
2345 $objgot{$objid} = 1;
2348 foreach my $lrefname (sort keys %lrfetchrefs_f) {
2349 my $rrefname = 'refs'.substr($lrefname, length lrfetchrefs);
2350 if (!exists $wantr{$rrefname}) {
2351 if ($wanted_rref->($rrefname)) {
2353 git-fetch @fspecs created $lrefname which git ls-remote @look didn't list.
2357 warning: git fetch @fspecs created $lrefname; this is silly, deleting it.
2360 runcmd_ordryrun_local @git, qw(update-ref -d), $lrefname;
2361 delete $lrfetchrefs_f{$lrefname};
2365 foreach my $rrefname (sort keys %wantr) {
2366 my $lrefname = lrfetchrefs.substr($rrefname, 4);
2367 my $got = $lrfetchrefs_f{$lrefname} // '<none>';
2368 my $want = $wantr{$rrefname};
2369 next if $got eq $want;
2370 if (!defined $objgot{$want}) {
2372 warning: git ls-remote suggests we want $lrefname
2373 warning: and it should refer to $want
2374 warning: but git fetch didn't fetch that object to any relevant ref.
2375 warning: This may be due to a race with someone updating the server.
2376 warning: Will try again...
2378 next FETCH_ITERATION;
2381 git-fetch @fspecs made $lrefname=$got but want git ls-remote @look says $want
2383 runcmd_ordryrun_local @git, qw(update-ref -m),
2384 "dgit fetch git fetch fixup", $lrefname, $want;
2385 $lrfetchrefs_f{$lrefname} = $want;
2389 printdebug "git_fetch_us: git fetch --no-insane emulation complete\n",
2390 Dumper(\%lrfetchrefs_f);
2393 my @tagpats = debiantags('*',access_basedistro);
2395 git_for_each_ref([map { "refs/tags/$_" } @tagpats], sub {
2396 my ($objid,$objtype,$fullrefname,$reftail) = @_;
2397 printdebug "currently $fullrefname=$objid\n";
2398 $here{$fullrefname} = $objid;
2400 git_for_each_ref([map { lrfetchrefs."/tags/".$_ } @tagpats], sub {
2401 my ($objid,$objtype,$fullrefname,$reftail) = @_;
2402 my $lref = "refs".substr($fullrefname, length(lrfetchrefs));
2403 printdebug "offered $lref=$objid\n";
2404 if (!defined $here{$lref}) {
2405 my @upd = (@git, qw(update-ref), $lref, $objid, '');
2406 runcmd_ordryrun_local @upd;
2407 lrfetchref_used $fullrefname;
2408 } elsif ($here{$lref} eq $objid) {
2409 lrfetchref_used $fullrefname;
2412 "Not updateting $lref from $here{$lref} to $objid.\n";
2417 sub mergeinfo_getclogp ($) {
2418 # Ensures thit $mi->{Clogp} exists and returns it
2420 $mi->{Clogp} = commit_getclogp($mi->{Commit});
2423 sub mergeinfo_version ($) {
2424 return getfield( (mergeinfo_getclogp $_[0]), 'Version' );
2427 sub fetch_from_archive () {
2428 ensure_setup_existing_tree();
2430 # Ensures that lrref() is what is actually in the archive, one way
2431 # or another, according to us - ie this client's
2432 # appropritaely-updated archive view. Also returns the commit id.
2433 # If there is nothing in the archive, leaves lrref alone and
2434 # returns undef. git_fetch_us must have already been called.
2438 foreach my $field (@ourdscfield) {
2439 $dsc_hash = $dsc->{$field};
2440 last if defined $dsc_hash;
2442 if (defined $dsc_hash) {
2443 $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
2445 progress "last upload to archive specified git hash";
2447 progress "last upload to archive has NO git hash";
2450 progress "no version available from the archive";
2453 # If the archive's .dsc has a Dgit field, there are three
2454 # relevant git commitids we need to choose between and/or merge
2456 # 1. $dsc_hash: the Dgit field from the archive
2457 # 2. $lastpush_hash: the suite branch on the dgit git server
2458 # 3. $lastfetch_hash: our local tracking brach for the suite
2460 # These may all be distinct and need not be in any fast forward
2463 # If the dsc was pushed to this suite, then the server suite
2464 # branch will have been updated; but it might have been pushed to
2465 # a different suite and copied by the archive. Conversely a more
2466 # recent version may have been pushed with dgit but not appeared
2467 # in the archive (yet).
2469 # $lastfetch_hash may be awkward because archive imports
2470 # (particularly, imports of Dgit-less .dscs) are performed only as
2471 # needed on individual clients, so different clients may perform a
2472 # different subset of them - and these imports are only made
2473 # public during push. So $lastfetch_hash may represent a set of
2474 # imports different to a subsequent upload by a different dgit
2477 # Our approach is as follows:
2479 # As between $dsc_hash and $lastpush_hash: if $lastpush_hash is a
2480 # descendant of $dsc_hash, then it was pushed by a dgit user who
2481 # had based their work on $dsc_hash, so we should prefer it.
2482 # Otherwise, $dsc_hash was installed into this suite in the
2483 # archive other than by a dgit push, and (necessarily) after the
2484 # last dgit push into that suite (since a dgit push would have
2485 # been descended from the dgit server git branch); thus, in that
2486 # case, we prefer the archive's version (and produce a
2487 # pseudo-merge to overwrite the dgit server git branch).
2489 # (If there is no Dgit field in the archive's .dsc then
2490 # generate_commit_from_dsc uses the version numbers to decide
2491 # whether the suite branch or the archive is newer. If the suite
2492 # branch is newer it ignores the archive's .dsc; otherwise it
2493 # generates an import of the .dsc, and produces a pseudo-merge to
2494 # overwrite the suite branch with the archive contents.)
2496 # The outcome of that part of the algorithm is the `public view',
2497 # and is same for all dgit clients: it does not depend on any
2498 # unpublished history in the local tracking branch.
2500 # As between the public view and the local tracking branch: The
2501 # local tracking branch is only updated by dgit fetch, and
2502 # whenever dgit fetch runs it includes the public view in the
2503 # local tracking branch. Therefore if the public view is not
2504 # descended from the local tracking branch, the local tracking
2505 # branch must contain history which was imported from the archive
2506 # but never pushed; and, its tip is now out of date. So, we make
2507 # a pseudo-merge to overwrite the old imports and stitch the old
2510 # Finally: we do not necessarily reify the public view (as
2511 # described above). This is so that we do not end up stacking two
2512 # pseudo-merges. So what we actually do is figure out the inputs
2513 # to any public view pseudo-merge and put them in @mergeinputs.
2516 # $mergeinputs[]{Commit}
2517 # $mergeinputs[]{Info}
2518 # $mergeinputs[0] is the one whose tree we use
2519 # @mergeinputs is in the order we use in the actual commit)
2522 # $mergeinputs[]{Message} is a commit message to use
2523 # $mergeinputs[]{ReverseParents} if def specifies that parent
2524 # list should be in opposite order
2525 # Such an entry has no Commit or Info. It applies only when found
2526 # in the last entry. (This ugliness is to support making
2527 # identical imports to previous dgit versions.)
2529 my $lastpush_hash = git_get_ref(lrfetchref());
2530 printdebug "previous reference hash=$lastpush_hash\n";
2531 $lastpush_mergeinput = $lastpush_hash && {
2532 Commit => $lastpush_hash,
2533 Info => "dgit suite branch on dgit git server",
2536 my $lastfetch_hash = git_get_ref(lrref());
2537 printdebug "fetch_from_archive: lastfetch=$lastfetch_hash\n";
2538 my $lastfetch_mergeinput = $lastfetch_hash && {
2539 Commit => $lastfetch_hash,
2540 Info => "dgit client's archive history view",
2543 my $dsc_mergeinput = $dsc_hash && {
2544 Commit => $dsc_hash,
2545 Info => "Dgit field in .dsc from archive",
2549 my $del_lrfetchrefs = sub {
2552 printdebug "del_lrfetchrefs...\n";
2553 foreach my $fullrefname (sort keys %lrfetchrefs_d) {
2554 my $objid = $lrfetchrefs_d{$fullrefname};
2555 printdebug "del_lrfetchrefs: $objid $fullrefname\n";
2557 $gur ||= new IO::Handle;
2558 open $gur, "|-", qw(git update-ref --stdin) or die $!;
2560 printf $gur "delete %s %s\n", $fullrefname, $objid;
2563 close $gur or failedcmd "git update-ref delete lrfetchrefs";
2567 if (defined $dsc_hash) {
2568 fail "missing remote git history even though dsc has hash -".
2569 " could not find ref ".rref()." at ".access_giturl()
2570 unless $lastpush_hash;
2571 ensure_we_have_orig();
2572 if ($dsc_hash eq $lastpush_hash) {
2573 @mergeinputs = $dsc_mergeinput
2574 } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
2575 print STDERR <<END or die $!;
2577 Git commit in archive is behind the last version allegedly pushed/uploaded.
2578 Commit referred to by archive: $dsc_hash
2579 Last version pushed with dgit: $lastpush_hash
2582 @mergeinputs = ($lastpush_mergeinput);
2584 # Archive has .dsc which is not a descendant of the last dgit
2585 # push. This can happen if the archive moves .dscs about.
2586 # Just follow its lead.
2587 if (is_fast_fwd($lastpush_hash,$dsc_hash)) {
2588 progress "archive .dsc names newer git commit";
2589 @mergeinputs = ($dsc_mergeinput);
2591 progress "archive .dsc names other git commit, fixing up";
2592 @mergeinputs = ($dsc_mergeinput, $lastpush_mergeinput);
2596 @mergeinputs = generate_commits_from_dsc();
2597 # We have just done an import. Now, our import algorithm might
2598 # have been improved. But even so we do not want to generate
2599 # a new different import of the same package. So if the
2600 # version numbers are the same, just use our existing version.
2601 # If the version numbers are different, the archive has changed
2602 # (perhaps, rewound).
2603 if ($lastfetch_mergeinput &&
2604 !version_compare( (mergeinfo_version $lastfetch_mergeinput),
2605 (mergeinfo_version $mergeinputs[0]) )) {
2606 @mergeinputs = ($lastfetch_mergeinput);
2608 } elsif ($lastpush_hash) {
2609 # only in git, not in the archive yet
2610 @mergeinputs = ($lastpush_mergeinput);
2611 print STDERR <<END or die $!;
2613 Package not found in the archive, but has allegedly been pushed using dgit.
2617 printdebug "nothing found!\n";
2618 if (defined $skew_warning_vsn) {
2619 print STDERR <<END or die $!;
2621 Warning: relevant archive skew detected.
2622 Archive allegedly contains $skew_warning_vsn
2623 But we were not able to obtain any version from the archive or git.
2627 unshift @end, $del_lrfetchrefs;
2631 if ($lastfetch_hash &&
2633 my $h = $_->{Commit};
2634 $h and is_fast_fwd($lastfetch_hash, $h);
2635 # If true, one of the existing parents of this commit
2636 # is a descendant of the $lastfetch_hash, so we'll
2637 # be ff from that automatically.
2641 push @mergeinputs, $lastfetch_mergeinput;
2644 printdebug "fetch mergeinfos:\n";
2645 foreach my $mi (@mergeinputs) {
2647 printdebug " commit $mi->{Commit} $mi->{Info}\n";
2649 printdebug sprintf " ReverseParents=%d Message=%s",
2650 $mi->{ReverseParents}, $mi->{Message};
2654 my $compat_info= pop @mergeinputs
2655 if $mergeinputs[$#mergeinputs]{Message};
2657 @mergeinputs = grep { defined $_->{Commit} } @mergeinputs;
2660 if (@mergeinputs > 1) {
2662 my $tree_commit = $mergeinputs[0]{Commit};
2664 my $tree = cmdoutput @git, qw(cat-file commit), $tree_commit;
2665 $tree =~ m/\n\n/; $tree = $`;
2666 $tree =~ m/^tree (\w+)$/m or die "$dsc_hash tree ?";
2669 # We use the changelog author of the package in question the
2670 # author of this pseudo-merge. This is (roughly) correct if
2671 # this commit is simply representing aa non-dgit upload.
2672 # (Roughly because it does not record sponsorship - but we
2673 # don't have sponsorship info because that's in the .changes,
2674 # which isn't in the archivw.)
2676 # But, it might be that we are representing archive history
2677 # updates (including in-archive copies). These are not really
2678 # the responsibility of the person who created the .dsc, but
2679 # there is no-one whose name we should better use. (The
2680 # author of the .dsc-named commit is clearly worse.)
2682 my $useclogp = mergeinfo_getclogp $mergeinputs[0];
2683 my $author = clogp_authline $useclogp;
2684 my $cversion = getfield $useclogp, 'Version';
2686 my $mcf = ".git/dgit/mergecommit";
2687 open MC, ">", $mcf or die "$mcf $!";
2688 print MC <<END or die $!;
2692 my @parents = grep { $_->{Commit} } @mergeinputs;
2693 @parents = reverse @parents if $compat_info->{ReverseParents};
2694 print MC <<END or die $! foreach @parents;
2698 print MC <<END or die $!;
2704 if (defined $compat_info->{Message}) {
2705 print MC $compat_info->{Message} or die $!;
2707 print MC <<END or die $!;
2708 Record $package ($cversion) in archive suite $csuite
2712 my $message_add_info = sub {
2714 my $mversion = mergeinfo_version $mi;
2715 printf MC " %-20s %s\n", $mversion, $mi->{Info}
2719 $message_add_info->($mergeinputs[0]);
2720 print MC <<END or die $!;
2721 should be treated as descended from
2723 $message_add_info->($_) foreach @mergeinputs[1..$#mergeinputs];
2727 $hash = make_commit $mcf;
2729 $hash = $mergeinputs[0]{Commit};
2731 printdebug "fetch hash=$hash\n";
2734 my ($lasth, $what) = @_;
2735 return unless $lasth;
2736 die "$lasth $hash $what ?" unless is_fast_fwd($lasth, $hash);
2739 $chkff->($lastpush_hash, 'dgit repo server tip (last push)');
2740 $chkff->($lastfetch_hash, 'local tracking tip (last fetch)');
2742 runcmd @git, qw(update-ref -m), "dgit fetch $csuite",
2743 'DGIT_ARCHIVE', $hash;
2744 cmdoutput @git, qw(log -n2), $hash;
2745 # ... gives git a chance to complain if our commit is malformed
2747 if (defined $skew_warning_vsn) {
2749 printdebug "SKEW CHECK WANT $skew_warning_vsn\n";
2750 my $gotclogp = commit_getclogp($hash);
2751 my $got_vsn = getfield $gotclogp, 'Version';
2752 printdebug "SKEW CHECK GOT $got_vsn\n";
2753 if (version_compare($got_vsn, $skew_warning_vsn) < 0) {
2754 print STDERR <<END or die $!;
2756 Warning: archive skew detected. Using the available version:
2757 Archive allegedly contains $skew_warning_vsn
2758 We were able to obtain only $got_vsn
2764 if ($lastfetch_hash ne $hash) {
2765 my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
2769 dryrun_report @upd_cmd;
2773 lrfetchref_used lrfetchref();
2775 unshift @end, $del_lrfetchrefs;
2779 sub set_local_git_config ($$) {
2781 runcmd @git, qw(config), $k, $v;
2784 sub setup_mergechangelogs (;$) {
2786 return unless $always || access_cfg_bool(1, 'setup-mergechangelogs');
2788 my $driver = 'dpkg-mergechangelogs';
2789 my $cb = "merge.$driver";
2790 my $attrs = '.git/info/attributes';
2791 ensuredir '.git/info';
2793 open NATTRS, ">", "$attrs.new" or die "$attrs.new $!";
2794 if (!open ATTRS, "<", $attrs) {
2795 $!==ENOENT or die "$attrs: $!";
2799 next if m{^debian/changelog\s};
2800 print NATTRS $_, "\n" or die $!;
2802 ATTRS->error and die $!;
2805 print NATTRS "debian/changelog merge=$driver\n" or die $!;
2808 set_local_git_config "$cb.name", 'debian/changelog merge driver';
2809 set_local_git_config "$cb.driver", 'dpkg-mergechangelogs -m %O %A %B %A';
2811 rename "$attrs.new", "$attrs" or die "$attrs: $!";
2814 sub setup_useremail (;$) {
2816 return unless $always || access_cfg_bool(1, 'setup-useremail');
2819 my ($k, $envvar) = @_;
2820 my $v = access_cfg("user-$k", 'RETURN-UNDEF') // $ENV{$envvar};
2821 return unless defined $v;
2822 set_local_git_config "user.$k", $v;
2825 $setup->('email', 'DEBEMAIL');
2826 $setup->('name', 'DEBFULLNAME');
2829 sub ensure_setup_existing_tree () {
2830 my $k = "remote.$remotename.skipdefaultupdate";
2831 my $c = git_get_config $k;
2832 return if defined $c;
2833 set_local_git_config $k, 'true';
2836 sub setup_new_tree () {
2837 setup_mergechangelogs();
2843 canonicalise_suite();
2844 badusage "dry run makes no sense with clone" unless act_local();
2845 my $hasgit = check_for_git();
2846 mkdir $dstdir or fail "create \`$dstdir': $!";
2848 runcmd @git, qw(init -q);
2849 my $giturl = access_giturl(1);
2850 if (defined $giturl) {
2851 open H, "> .git/HEAD" or die $!;
2852 print H "ref: ".lref()."\n" or die $!;
2854 runcmd @git, qw(remote add), 'origin', $giturl;
2857 progress "fetching existing git history";
2859 runcmd_ordryrun_local @git, qw(fetch origin);
2861 progress "starting new git history";
2863 fetch_from_archive() or no_such_package;
2864 my $vcsgiturl = $dsc->{'Vcs-Git'};
2865 if (length $vcsgiturl) {
2866 $vcsgiturl =~ s/\s+-b\s+\S+//g;
2867 runcmd @git, qw(remote add vcs-git), $vcsgiturl;
2870 runcmd @git, qw(reset --hard), lrref();
2871 printdone "ready for work in $dstdir";
2875 if (check_for_git()) {
2878 fetch_from_archive() or no_such_package();
2879 printdone "fetched into ".lrref();
2884 runcmd_ordryrun_local @git, qw(merge -m),"Merge from $csuite [dgit]",
2886 printdone "fetched to ".lrref()." and merged into HEAD";
2889 sub check_not_dirty () {
2890 foreach my $f (qw(local-options local-patch-header)) {
2891 if (stat_exists "debian/source/$f") {
2892 fail "git tree contains debian/source/$f";
2896 return if $ignoredirty;
2898 my @cmd = (@git, qw(diff --quiet HEAD));
2900 $!=0; $?=-1; system @cmd;
2903 fail "working tree is dirty (does not match HEAD)";
2909 sub commit_admin ($) {
2912 runcmd_ordryrun_local @git, qw(commit -m), $m;
2915 sub commit_quilty_patch () {
2916 my $output = cmdoutput @git, qw(status --porcelain);
2918 foreach my $l (split /\n/, $output) {
2919 next unless $l =~ m/\S/;
2920 if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
2924 delete $adds{'.pc'}; # if there wasn't one before, don't add it
2926 progress "nothing quilty to commit, ok.";
2929 my @adds = map { s/[][*?\\]/\\$&/g; $_; } sort keys %adds;
2930 runcmd_ordryrun_local @git, qw(add -f), @adds;
2932 Commit Debian 3.0 (quilt) metadata
2934 [dgit ($our_version) quilt-fixup]
2938 sub get_source_format () {
2940 if (open F, "debian/source/options") {
2944 s/\s+$//; # ignore missing final newline
2946 my ($k, $v) = ($`, $'); #');
2947 $v =~ s/^"(.*)"$/$1/;
2953 F->error and die $!;
2956 die $! unless $!==&ENOENT;
2959 if (!open F, "debian/source/format") {
2960 die $! unless $!==&ENOENT;
2964 F->error and die $!;
2966 return ($_, \%options);
2969 sub madformat_wantfixup ($) {
2971 return 0 unless $format eq '3.0 (quilt)';
2972 our $quilt_mode_warned;
2973 if ($quilt_mode eq 'nocheck') {
2974 progress "Not doing any fixup of \`$format' due to".
2975 " ----no-quilt-fixup or --quilt=nocheck"
2976 unless $quilt_mode_warned++;
2979 progress "Format \`$format', need to check/update patch stack"
2980 unless $quilt_mode_warned++;
2984 # An "infopair" is a tuple [ $thing, $what ]
2985 # (often $thing is a commit hash; $what is a description)
2987 sub infopair_cond_equal ($$) {
2989 $x->[0] eq $y->[0] or fail <<END;
2990 $x->[1] ($x->[0]) not equal to $y->[1] ($y->[0])
2994 sub infopair_lrf_tag_lookup ($$) {
2995 my ($tagnames, $what) = @_;
2996 # $tagname may be an array ref
2997 my @tagnames = ref $tagnames ? @$tagnames : ($tagnames);
2998 printdebug "infopair_lrfetchref_tag_lookup $what @tagnames\n";
2999 foreach my $tagname (@tagnames) {
3000 my $lrefname = lrfetchrefs."/tags/$tagname";
3001 my $tagobj = $lrfetchrefs_f{$lrefname};
3002 next unless defined $tagobj;
3003 printdebug "infopair_lrfetchref_tag_lookup $tagobj $tagname $what\n";
3004 return [ git_rev_parse($tagobj), $what ];
3006 fail @tagnames==1 ? <<END : <<END;
3007 Wanted tag $what (@tagnames) on dgit server, but not found
3009 Wanted tag $what (one of: @tagnames) on dgit server, but not found
3013 sub infopair_cond_ff ($$) {
3014 my ($anc,$desc) = @_;
3015 is_fast_fwd($anc->[0], $desc->[0]) or fail <<END;
3016 $anc->[1] ($anc->[0]) .. $desc->[1] ($desc->[0]) is not fast forward
3020 sub pseudomerge_version_check ($$) {
3021 my ($clogp, $archive_hash) = @_;
3023 my $arch_clogp = commit_getclogp $archive_hash;
3024 my $i_arch_v = [ (getfield $arch_clogp, 'Version'),
3025 'version currently in archive' ];
3026 if (defined $overwrite_version) {
3027 if (length $overwrite_version) {
3028 infopair_cond_equal([ $overwrite_version,
3029 '--overwrite= version' ],
3032 my $v = $i_arch_v->[0];
3033 progress "Checking package changelog for archive version $v ...";
3035 my @xa = ("-f$v", "-t$v");
3036 my $vclogp = parsechangelog @xa;
3037 my $cv = [ (getfield $vclogp, 'Version'),
3038 "Version field from dpkg-parsechangelog @xa" ];
3039 infopair_cond_equal($i_arch_v, $cv);
3042 $@ =~ s/^dgit: //gm;
3044 "Perhaps debian/changelog does not mention $v ?";
3049 printdebug "pseudomerge_version_check i_arch_v @$i_arch_v\n";
3053 sub pseudomerge_make_commit ($$$$ $$) {
3054 my ($clogp, $dgitview, $archive_hash, $i_arch_v,
3055 $msg_cmd, $msg_msg) = @_;
3056 progress "Declaring that HEAD inciudes all changes in $i_arch_v->[0]...";
3058 my $tree = cmdoutput qw(git rev-parse), "${dgitview}:";
3059 my $authline = clogp_authline $clogp;
3063 !defined $overwrite_version ? ""
3064 : !length $overwrite_version ? " --overwrite"
3065 : " --overwrite=".$overwrite_version;
3068 my $pmf = ".git/dgit/pseudomerge";
3069 open MC, ">", $pmf or die "$pmf $!";
3070 print MC <<END or die $!;
3073 parent $archive_hash
3083 return make_commit($pmf);
3086 sub splitbrain_pseudomerge ($$$$) {
3087 my ($clogp, $maintview, $dgitview, $archive_hash) = @_;
3088 # => $merged_dgitview
3089 printdebug "splitbrain_pseudomerge...\n";
3091 # We: debian/PREVIOUS HEAD($maintview)
3092 # expect: o ----------------- o
3095 # a/d/PREVIOUS $dgitview
3098 # we do: `------------------ o
3102 return $dgitview unless defined $archive_hash;
3104 printdebug "splitbrain_pseudomerge...\n";
3106 my $i_arch_v = pseudomerge_version_check($clogp, $archive_hash);
3108 if (!defined $overwrite_version) {
3109 progress "Checking that HEAD inciudes all changes in archive...";
3112 return $dgitview if is_fast_fwd $archive_hash, $dgitview;
3114 if (defined $overwrite_version) {
3116 my $t_dep14 = debiantag_maintview $i_arch_v->[0], access_basedistro;
3117 my $i_dep14 = infopair_lrf_tag_lookup($t_dep14, "maintainer view tag");
3118 my $t_dgit = debiantag_new $i_arch_v->[0], access_basedistro;
3119 my $i_dgit = infopair_lrf_tag_lookup($t_dgit, "dgit view tag");
3120 my $i_archive = [ $archive_hash, "current archive contents" ];
3122 printdebug "splitbrain_pseudomerge i_archive @$i_archive\n";
3124 infopair_cond_equal($i_dgit, $i_archive);
3125 infopair_cond_ff($i_dep14, $i_dgit);
3126 infopair_cond_ff($i_dep14, [ $maintview, 'HEAD' ]);
3130 $us: check failed (maybe --overwrite is needed, consult documentation)
3135 my $r = pseudomerge_make_commit
3136 $clogp, $dgitview, $archive_hash, $i_arch_v,
3137 "dgit --quilt=$quilt_mode",
3138 (defined $overwrite_version ? <<END_OVERWR : <<END_MAKEFF);
3139 Declare fast forward from $i_arch_v->[0]
3141 Make fast forward from $i_arch_v->[0]
3144 progress "Made pseudo-merge of $i_arch_v->[0] into dgit view.";
3148 sub plain_overwrite_pseudomerge ($$$) {
3149 my ($clogp, $head, $archive_hash) = @_;
3151 printdebug "plain_overwrite_pseudomerge...";
3153 my $i_arch_v = pseudomerge_version_check($clogp, $archive_hash);
3155 return $head if is_fast_fwd $archive_hash, $head;
3157 my $m = "Declare fast forward from $i_arch_v->[0]";
3159 my $r = pseudomerge_make_commit
3160 $clogp, $head, $archive_hash, $i_arch_v,
3163 runcmd @git, qw(update-ref -m), $m, 'HEAD', $r, $head;
3165 progress "Make pseudo-merge of $i_arch_v->[0] into your HEAD.";
3169 sub push_parse_changelog ($) {
3172 my $clogp = Dpkg::Control::Hash->new();
3173 $clogp->load($clogpfn) or die;
3175 $package = getfield $clogp, 'Source';
3176 my $cversion = getfield $clogp, 'Version';
3177 my $tag = debiantag($cversion, access_basedistro);
3178 runcmd @git, qw(check-ref-format), $tag;
3180 my $dscfn = dscfn($cversion);
3182 return ($clogp, $cversion, $dscfn);
3185 sub push_parse_dsc ($$$) {
3186 my ($dscfn,$dscfnwhat, $cversion) = @_;
3187 $dsc = parsecontrol($dscfn,$dscfnwhat);
3188 my $dversion = getfield $dsc, 'Version';
3189 my $dscpackage = getfield $dsc, 'Source';
3190 ($dscpackage eq $package && $dversion eq $cversion) or
3191 fail "$dscfn is for $dscpackage $dversion".
3192 " but debian/changelog is for $package $cversion";
3195 sub push_tagwants ($$$$) {
3196 my ($cversion, $dgithead, $maintviewhead, $tfbase) = @_;
3199 TagFn => \&debiantag,
3204 if (defined $maintviewhead) {
3206 TagFn => \&debiantag_maintview,
3207 Objid => $maintviewhead,
3208 TfSuffix => '-maintview',
3212 foreach my $tw (@tagwants) {
3213 $tw->{Tag} = $tw->{TagFn}($cversion, access_basedistro);
3214 $tw->{Tfn} = sub { $tfbase.$tw->{TfSuffix}.$_[0]; };
3216 printdebug 'push_tagwants: ', Dumper(\@_, \@tagwants);
3220 sub push_mktags ($$ $$ $) {
3222 $changesfile,$changesfilewhat,
3225 die unless $tagwants->[0]{View} eq 'dgit';
3227 $dsc->{$ourdscfield[0]} = $tagwants->[0]{Objid};
3228 $dsc->save("$dscfn.tmp") or die $!;
3230 my $changes = parsecontrol($changesfile,$changesfilewhat);
3231 foreach my $field (qw(Source Distribution Version)) {
3232 $changes->{$field} eq $clogp->{$field} or
3233 fail "changes field $field \`$changes->{$field}'".
3234 " does not match changelog \`$clogp->{$field}'";
3237 my $cversion = getfield $clogp, 'Version';
3238 my $clogsuite = getfield $clogp, 'Distribution';
3240 # We make the git tag by hand because (a) that makes it easier
3241 # to control the "tagger" (b) we can do remote signing
3242 my $authline = clogp_authline $clogp;
3243 my $delibs = join(" ", "",@deliberatelies);
3244 my $declaredistro = access_basedistro();
3248 my $tfn = $tw->{Tfn};
3249 my $head = $tw->{Objid};
3250 my $tag = $tw->{Tag};
3252 open TO, '>', $tfn->('.tmp') or die $!;
3253 print TO <<END or die $!;
3260 if ($tw->{View} eq 'dgit') {
3261 print TO <<END or die $!;
3262 $package release $cversion for $clogsuite ($csuite) [dgit]
3263 [dgit distro=$declaredistro$delibs]
3265 foreach my $ref (sort keys %previously) {
3266 print TO <<END or die $!;
3267 [dgit previously:$ref=$previously{$ref}]
3270 } elsif ($tw->{View} eq 'maint') {
3271 print TO <<END or die $!;
3272 $package release $cversion for $clogsuite ($csuite)
3273 (maintainer view tag generated by dgit --quilt=$quilt_mode)
3276 die Dumper($tw)."?";
3281 my $tagobjfn = $tfn->('.tmp');
3283 if (!defined $keyid) {
3284 $keyid = access_cfg('keyid','RETURN-UNDEF');
3286 if (!defined $keyid) {
3287 $keyid = getfield $clogp, 'Maintainer';
3289 unlink $tfn->('.tmp.asc') or $!==&ENOENT or die $!;
3290 my @sign_cmd = (@gpg, qw(--detach-sign --armor));
3291 push @sign_cmd, qw(-u),$keyid if defined $keyid;
3292 push @sign_cmd, $tfn->('.tmp');
3293 runcmd_ordryrun @sign_cmd;
3295 $tagobjfn = $tfn->('.signed.tmp');
3296 runcmd shell_cmd "exec >$tagobjfn", qw(cat --),
3297 $tfn->('.tmp'), $tfn->('.tmp.asc');
3303 my @r = map { $mktag->($_); } @$tagwants;
3307 sub sign_changes ($) {
3308 my ($changesfile) = @_;
3310 my @debsign_cmd = @debsign;
3311 push @debsign_cmd, "-k$keyid" if defined $keyid;
3312 push @debsign_cmd, "-p$gpg[0]" if $gpg[0] ne 'gpg';
3313 push @debsign_cmd, $changesfile;
3314 runcmd_ordryrun @debsign_cmd;
3319 printdebug "actually entering push\n";
3321 supplementary_message(<<'END');
3322 Push failed, while checking state of the archive.
3323 You can retry the push, after fixing the problem, if you like.
3325 if (check_for_git()) {
3328 my $archive_hash = fetch_from_archive();
3329 if (!$archive_hash) {
3331 fail "package appears to be new in this suite;".
3332 " if this is intentional, use --new";
3335 supplementary_message(<<'END');
3336 Push failed, while preparing your push.
3337 You can retry the push, after fixing the problem, if you like.
3340 need_tagformat 'new', "quilt mode $quilt_mode"
3341 if quiltmode_splitbrain;
3345 access_giturl(); # check that success is vaguely likely
3348 my $clogpfn = ".git/dgit/changelog.822.tmp";
3349 runcmd shell_cmd "exec >$clogpfn", qw(dpkg-parsechangelog);
3351 responder_send_file('parsed-changelog', $clogpfn);
3353 my ($clogp, $cversion, $dscfn) =
3354 push_parse_changelog("$clogpfn");
3356 my $dscpath = "$buildproductsdir/$dscfn";
3357 stat_exists $dscpath or
3358 fail "looked for .dsc $dscfn, but $!;".
3359 " maybe you forgot to build";
3361 responder_send_file('dsc', $dscpath);
3363 push_parse_dsc($dscpath, $dscfn, $cversion);
3365 my $format = getfield $dsc, 'Format';
3366 printdebug "format $format\n";
3368 my $actualhead = git_rev_parse('HEAD');
3369 my $dgithead = $actualhead;
3370 my $maintviewhead = undef;
3372 my $upstreamversion = $clogp->{Version};
3373 $upstreamversion =~ s/-[^-]*$//;
3375 if (madformat_wantfixup($format)) {
3376 # user might have not used dgit build, so maybe do this now:
3377 if (quiltmode_splitbrain()) {
3379 quilt_make_fake_dsc($upstreamversion);
3381 ($dgithead, $cachekey) =
3382 quilt_check_splitbrain_cache($actualhead, $upstreamversion);
3384 "--quilt=$quilt_mode but no cached dgit view:
3385 perhaps tree changed since dgit build[-source] ?";
3387 $dgithead = splitbrain_pseudomerge($clogp,
3388 $actualhead, $dgithead,
3390 $maintviewhead = $actualhead;
3391 changedir '../../../..';
3392 prep_ud(); # so _only_subdir() works, below
3394 commit_quilty_patch();
3398 if (defined $overwrite_version && !defined $maintviewhead) {
3399 $dgithead = plain_overwrite_pseudomerge($clogp,
3407 if ($archive_hash) {
3408 if (is_fast_fwd($archive_hash, $dgithead)) {
3410 } elsif (deliberately_not_fast_forward) {
3413 fail "dgit push: HEAD is not a descendant".
3414 " of the archive's version.\n".
3415 "To overwrite the archive's contents,".
3416 " pass --overwrite[=VERSION].\n".
3417 "To rewind history, if permitted by the archive,".
3418 " use --deliberately-not-fast-forward.";
3423 progress "checking that $dscfn corresponds to HEAD";
3424 runcmd qw(dpkg-source -x --),
3425 $dscpath =~ m#^/# ? $dscpath : "../../../$dscpath";
3426 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
3427 check_for_vendor_patches() if madformat($dsc->{format});
3428 changedir '../../../..';
3429 my @diffcmd = (@git, qw(diff --quiet), $tree, $dgithead);
3430 debugcmd "+",@diffcmd;
3432 my $r = system @diffcmd;
3435 my $diffs = cmdoutput @git, qw(diff --stat), $tree, $dgithead;
3437 HEAD specifies a different tree to $dscfn:
3439 Perhaps you forgot to build. Or perhaps there is a problem with your
3440 source tree (see dgit(7) for some hints). To see a full diff, run
3447 if (!$changesfile) {
3448 my $pat = changespat $cversion;
3449 my @cs = glob "$buildproductsdir/$pat";
3450 fail "failed to find unique changes file".
3451 " (looked for $pat in $buildproductsdir);".
3452 " perhaps you need to use dgit -C"
3454 ($changesfile) = @cs;
3456 $changesfile = "$buildproductsdir/$changesfile";
3459 # Check that changes and .dsc agree enough
3460 $changesfile =~ m{[^/]*$};
3461 my $changes = parsecontrol($changesfile,$&);
3462 files_compare_inputs($dsc, $changes)
3463 unless forceing [qw(dsc-changes-mismatch)];
3465 # Perhaps adjust .dsc to contain right set of origs
3466 changes_update_origs_from_dsc($dsc, $changes, $upstreamversion,
3468 unless forceing [qw(changes-origs-exactly)];
3470 # Checks complete, we're going to try and go ahead:
3472 responder_send_file('changes',$changesfile);
3473 responder_send_command("param head $dgithead");
3474 responder_send_command("param csuite $csuite");
3475 responder_send_command("param tagformat $tagformat");
3476 if (defined $maintviewhead) {
3477 die unless ($protovsn//4) >= 4;
3478 responder_send_command("param maint-view $maintviewhead");
3481 if (deliberately_not_fast_forward) {
3482 git_for_each_ref(lrfetchrefs, sub {
3483 my ($objid,$objtype,$lrfetchrefname,$reftail) = @_;
3484 my $rrefname= substr($lrfetchrefname, length(lrfetchrefs) + 1);
3485 responder_send_command("previously $rrefname=$objid");
3486 $previously{$rrefname} = $objid;
3490 my @tagwants = push_tagwants($cversion, $dgithead, $maintviewhead,
3494 supplementary_message(<<'END');
3495 Push failed, while signing the tag.
3496 You can retry the push, after fixing the problem, if you like.
3498 # If we manage to sign but fail to record it anywhere, it's fine.
3499 if ($we_are_responder) {
3500 @tagobjfns = map { $_->{Tfn}('.signed-tmp') } @tagwants;
3501 responder_receive_files('signed-tag', @tagobjfns);
3503 @tagobjfns = push_mktags($clogp,$dscpath,
3504 $changesfile,$changesfile,
3507 supplementary_message(<<'END');
3508 Push failed, *after* signing the tag.
3509 If you want to try again, you should use a new version number.
3512 pairwise { $a->{TagObjFn} = $b } @tagwants, @tagobjfns;
3514 foreach my $tw (@tagwants) {
3515 my $tag = $tw->{Tag};
3516 my $tagobjfn = $tw->{TagObjFn};
3518 cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
3519 runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
3520 runcmd_ordryrun_local
3521 @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
3524 supplementary_message(<<'END');
3525 Push failed, while updating the remote git repository - see messages above.
3526 If you want to try again, you should use a new version number.
3528 if (!check_for_git()) {
3529 create_remote_git_repo();
3532 my @pushrefs = $forceflag.$dgithead.":".rrref();
3533 foreach my $tw (@tagwants) {
3534 push @pushrefs, $forceflag."refs/tags/$tw->{Tag}";
3537 runcmd_ordryrun @git,
3538 qw(-c push.followTags=false push), access_giturl(), @pushrefs;
3539 runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), $dgithead;
3541 supplementary_message(<<'END');
3542 Push failed, after updating the remote git repository.
3543 If you want to try again, you must use a new version number.
3545 if ($we_are_responder) {
3546 my $dryrunsuffix = act_local() ? "" : ".tmp";
3547 responder_receive_files('signed-dsc-changes',
3548 "$dscpath$dryrunsuffix",
3549 "$changesfile$dryrunsuffix");
3552 rename "$dscpath.tmp",$dscpath or die "$dscfn $!";
3554 progress "[new .dsc left in $dscpath.tmp]";
3556 sign_changes $changesfile;
3559 supplementary_message(<<END);
3560 Push failed, while uploading package(s) to the archive server.
3561 You can retry the upload of exactly these same files with dput of:
3563 If that .changes file is broken, you will need to use a new version
3564 number for your next attempt at the upload.
3566 my $host = access_cfg('upload-host','RETURN-UNDEF');
3567 my @hostarg = defined($host) ? ($host,) : ();
3568 runcmd_ordryrun @dput, @hostarg, $changesfile;
3569 printdone "pushed and uploaded $cversion";
3571 supplementary_message('');
3572 responder_send_command("complete");
3579 badusage "-p is not allowed with clone; specify as argument instead"
3580 if defined $package;
3583 } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
3584 ($package,$isuite) = @ARGV;
3585 } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
3586 ($package,$dstdir) = @ARGV;
3587 } elsif (@ARGV==3) {
3588 ($package,$isuite,$dstdir) = @ARGV;
3590 badusage "incorrect arguments to dgit clone";
3592 $dstdir ||= "$package";
3594 if (stat_exists $dstdir) {
3595 fail "$dstdir already exists";
3599 if ($rmonerror && !$dryrun_level) {
3600 $cwd_remove= getcwd();
3602 return unless defined $cwd_remove;
3603 if (!chdir "$cwd_remove") {
3604 return if $!==&ENOENT;
3605 die "chdir $cwd_remove: $!";
3608 rmtree($dstdir) or die "remove $dstdir: $!\n";
3609 } elsif (grep { $! == $_ }
3610 (ENOENT, ENOTDIR, EACCES, EPERM, ELOOP)) {
3612 print STDERR "check whether to remove $dstdir: $!\n";
3618 $cwd_remove = undef;
3621 sub branchsuite () {
3622 my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
3623 if ($branch =~ m#$lbranch_re#o) {
3630 sub fetchpullargs () {
3632 if (!defined $package) {
3633 my $sourcep = parsecontrol('debian/control','debian/control');
3634 $package = getfield $sourcep, 'Source';
3637 # $isuite = branchsuite(); # this doesn't work because dak hates canons
3639 my $clogp = parsechangelog();
3640 $isuite = getfield $clogp, 'Distribution';
3642 canonicalise_suite();
3643 progress "fetching from suite $csuite";
3644 } elsif (@ARGV==1) {
3646 canonicalise_suite();
3648 badusage "incorrect arguments to dgit fetch or dgit pull";
3667 badusage "-p is not allowed with dgit push" if defined $package;
3669 my $clogp = parsechangelog();
3670 $package = getfield $clogp, 'Source';
3673 } elsif (@ARGV==1) {
3674 ($specsuite) = (@ARGV);
3676 badusage "incorrect arguments to dgit push";
3678 $isuite = getfield $clogp, 'Distribution';
3680 local ($package) = $existing_package; # this is a hack
3681 canonicalise_suite();
3683 canonicalise_suite();
3685 if (defined $specsuite &&
3686 $specsuite ne $isuite &&
3687 $specsuite ne $csuite) {
3688 fail "dgit push: changelog specifies $isuite ($csuite)".
3689 " but command line specifies $specsuite";
3694 #---------- remote commands' implementation ----------
3696 sub cmd_remote_push_build_host {
3697 my ($nrargs) = shift @ARGV;
3698 my (@rargs) = @ARGV[0..$nrargs-1];
3699 @ARGV = @ARGV[$nrargs..$#ARGV];
3701 my ($dir,$vsnwant) = @rargs;
3702 # vsnwant is a comma-separated list; we report which we have
3703 # chosen in our ready response (so other end can tell if they
3706 $we_are_responder = 1;
3707 $us .= " (build host)";
3711 open PI, "<&STDIN" or die $!;
3712 open STDIN, "/dev/null" or die $!;
3713 open PO, ">&STDOUT" or die $!;
3715 open STDOUT, ">&STDERR" or die $!;