3 # Integration between git and Debian-style archives
5 # Copyright (C)2013-2015 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::MoreUtils qw(pairwise);
41 our $our_version = 'UNRELEASED'; ###substituted###
43 our @rpushprotovsn_support = qw(3 2); # 4 is new tag format
46 our $isuite = 'unstable';
52 our $dryrun_level = 0;
54 our $buildproductsdir = '..';
60 our $existing_package = 'dpkg';
62 our $changes_since_version;
65 our $quilt_modes_re = 'linear|smash|auto|nofix|nocheck|gbp|unapplied';
66 our $we_are_responder;
67 our $initiator_tempdir;
68 our $patches_applied_dirtily = 00;
73 our %format_ok = map { $_=>1 } ("1.0","3.0 (native)","3.0 (quilt)");
75 our $suite_re = '[-+.0-9a-z]+';
76 our $cleanmode_re = 'dpkg-source(?:-d)?|git|git-ff|check|none';
78 our $git_authline_re = '^([^<>]+) \<(\S+)\> (\d+ [-+]\d+)$';
79 our $splitbraincache = 'dgit-intern/quilt-cache';
82 our (@dget) = qw(dget);
83 our (@curl) = qw(curl -f);
84 our (@dput) = qw(dput);
85 our (@debsign) = qw(debsign);
87 our (@sbuild) = qw(sbuild);
89 our (@dgit) = qw(dgit);
90 our (@dpkgbuildpackage) = qw(dpkg-buildpackage -i\.git/ -I.git);
91 our (@dpkgsource) = qw(dpkg-source -i\.git/ -I.git);
92 our (@dpkggenchanges) = qw(dpkg-genchanges);
93 our (@mergechanges) = qw(mergechanges -f);
95 our (@changesopts) = ('');
97 our %opts_opt_map = ('dget' => \@dget, # accept for compatibility
100 'debsign' => \@debsign,
102 'sbuild' => \@sbuild,
106 'dpkg-source' => \@dpkgsource,
107 'dpkg-buildpackage' => \@dpkgbuildpackage,
108 'dpkg-genchanges' => \@dpkggenchanges,
110 'ch' => \@changesopts,
111 'mergechanges' => \@mergechanges);
113 our %opts_opt_cmdonly = ('gpg' => 1, 'git' => 1);
114 our %opts_cfg_insertpos = map {
116 scalar @{ $opts_opt_map{$_} }
117 } keys %opts_opt_map;
119 sub finalise_opts_opts();
125 our $supplementary_message = '';
126 our $need_split_build_invocation = 0;
127 our $split_brain = 0;
131 print STDERR "! $_\n" foreach $supplementary_message =~ m/^.+$/mg;
134 our $remotename = 'dgit';
135 our @ourdscfield = qw(Dgit Vcs-Dgit-Master);
140 my ($v,$distro) = @_;
141 return $tagformatfn->($v, $distro);
144 sub lbranch () { return "$branchprefix/$csuite"; }
145 my $lbranch_re = '^refs/heads/'.$branchprefix.'/([^/.]+)$';
146 sub lref () { return "refs/heads/".lbranch(); }
147 sub lrref () { return "refs/remotes/$remotename/".server_branch($csuite); }
148 sub rrref () { return server_ref($csuite); }
150 sub lrfetchrefs () { return "refs/dgit-fetch/$csuite"; }
160 return "${package}_".(stripepoch $vsn).$sfx
165 return srcfn($vsn,".dsc");
168 sub changespat ($;$) {
169 my ($vsn, $arch) = @_;
170 return "${package}_".(stripepoch $vsn)."_".($arch//'*').".changes";
179 foreach my $f (@end) {
181 print STDERR "$us: cleanup: $@" if length $@;
185 sub badcfg { print STDERR "$us: invalid configuration: @_\n"; exit 12; }
187 sub no_such_package () {
188 print STDERR "$us: package $package does not exist in suite $isuite\n";
194 return "+".rrref().":".lrref();
199 printdebug "CD $newdir\n";
200 chdir $newdir or die "chdir: $newdir: $!";
203 sub deliberately ($) {
205 return !!grep { $_ eq "--deliberately-$enquiry" } @deliberatelies;
208 sub deliberately_not_fast_forward () {
209 foreach (qw(not-fast-forward fresh-repo)) {
210 return 1 if deliberately($_) || deliberately("TEST-dgit-only-$_");
214 sub quiltmode_splitbrain () {
215 $quilt_mode =~ m/gbp|dpm|unapplied/;
218 #---------- remote protocol support, common ----------
220 # remote push initiator/responder protocol:
221 # $ dgit remote-push-build-host <n-rargs> <rargs>... <push-args>...
222 # where <rargs> is <push-host-dir> <supported-proto-vsn>,... ...
223 # < dgit-remote-push-ready <actual-proto-vsn>
230 # > supplementary-message NBYTES # $protovsn >= 3
235 # > file parsed-changelog
236 # [indicates that output of dpkg-parsechangelog follows]
237 # > data-block NBYTES
238 # > [NBYTES bytes of data (no newline)]
239 # [maybe some more blocks]
249 # > param csuite SUITE
250 # > param tagformat old|new
252 # > previously REFNAME=OBJNAME # if --deliberately-not-fast-forward
253 # # goes into tag, for replay prevention
256 # [indicates that signed tag is wanted]
257 # < data-block NBYTES
258 # < [NBYTES bytes of data (no newline)]
259 # [maybe some more blocks]
263 # > want signed-dsc-changes
264 # < data-block NBYTES [transfer of signed dsc]
266 # < data-block NBYTES [transfer of signed changes]
274 sub i_child_report () {
275 # Sees if our child has died, and reap it if so. Returns a string
276 # describing how it died if it failed, or undef otherwise.
277 return undef unless $i_child_pid;
278 my $got = waitpid $i_child_pid, WNOHANG;
279 return undef if $got <= 0;
280 die unless $got == $i_child_pid;
281 $i_child_pid = undef;
282 return undef unless $?;
283 return "build host child ".waitstatusmsg();
288 fail "connection lost: $!" if $fh->error;
289 fail "protocol violation; $m not expected";
292 sub badproto_badread ($$) {
294 fail "connection lost: $!" if $!;
295 my $report = i_child_report();
296 fail $report if defined $report;
297 badproto $fh, "eof (reading $wh)";
300 sub protocol_expect (&$) {
301 my ($match, $fh) = @_;
304 defined && chomp or badproto_badread $fh, "protocol message";
312 badproto $fh, "\`$_'";
315 sub protocol_send_file ($$) {
316 my ($fh, $ourfn) = @_;
317 open PF, "<", $ourfn or die "$ourfn: $!";
320 my $got = read PF, $d, 65536;
321 die "$ourfn: $!" unless defined $got;
323 print $fh "data-block ".length($d)."\n" or die $!;
324 print $fh $d or die $!;
326 PF->error and die "$ourfn $!";
327 print $fh "data-end\n" or die $!;
331 sub protocol_read_bytes ($$) {
332 my ($fh, $nbytes) = @_;
333 $nbytes =~ m/^[1-9]\d{0,5}$|^0$/ or badproto \*RO, "bad byte count";
335 my $got = read $fh, $d, $nbytes;
336 $got==$nbytes or badproto_badread $fh, "data block";
340 sub protocol_receive_file ($$) {
341 my ($fh, $ourfn) = @_;
342 printdebug "() $ourfn\n";
343 open PF, ">", $ourfn or die "$ourfn: $!";
345 my ($y,$l) = protocol_expect {
346 m/^data-block (.*)$/ ? (1,$1) :
347 m/^data-end$/ ? (0,) :
351 my $d = protocol_read_bytes $fh, $l;
352 print PF $d or die $!;
357 #---------- remote protocol support, responder ----------
359 sub responder_send_command ($) {
361 return unless $we_are_responder;
362 # called even without $we_are_responder
363 printdebug ">> $command\n";
364 print PO $command, "\n" or die $!;
367 sub responder_send_file ($$) {
368 my ($keyword, $ourfn) = @_;
369 return unless $we_are_responder;
370 printdebug "]] $keyword $ourfn\n";
371 responder_send_command "file $keyword";
372 protocol_send_file \*PO, $ourfn;
375 sub responder_receive_files ($@) {
376 my ($keyword, @ourfns) = @_;
377 die unless $we_are_responder;
378 printdebug "[[ $keyword @ourfns\n";
379 responder_send_command "want $keyword";
380 foreach my $fn (@ourfns) {
381 protocol_receive_file \*PI, $fn;
384 protocol_expect { m/^files-end$/ } \*PI;
387 #---------- remote protocol support, initiator ----------
389 sub initiator_expect (&) {
391 protocol_expect { &$match } \*RO;
394 #---------- end remote code ----------
397 if ($we_are_responder) {
399 responder_send_command "progress ".length($m) or die $!;
400 print PO $m or die $!;
410 $ua = LWP::UserAgent->new();
414 progress "downloading $what...";
415 my $r = $ua->get(@_) or die $!;
416 return undef if $r->code == 404;
417 $r->is_success or fail "failed to fetch $what: ".$r->status_line;
418 return $r->decoded_content(charset => 'none');
421 our ($dscdata,$dscurl,$dsc,$dsc_checked,$skew_warning_vsn);
426 failedcmd @_ if system @_;
429 sub act_local () { return $dryrun_level <= 1; }
430 sub act_scary () { return !$dryrun_level; }
433 if (!$dryrun_level) {
434 progress "dgit ok: @_";
436 progress "would be ok: @_ (but dry run only)";
441 printcmd(\*STDERR,$debugprefix."#",@_);
444 sub runcmd_ordryrun {
452 sub runcmd_ordryrun_local {
461 my ($first_shell, @cmd) = @_;
462 return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
465 our $helpmsg = <<END;
467 dgit [dgit-opts] clone [dgit-opts] package [suite] [./dir|/dir]
468 dgit [dgit-opts] fetch|pull [dgit-opts] [suite]
469 dgit [dgit-opts] build [dpkg-buildpackage-opts]
470 dgit [dgit-opts] sbuild [sbuild-opts]
471 dgit [dgit-opts] push [dgit-opts] [suite]
472 dgit [dgit-opts] rpush build-host:build-dir ...
473 important dgit options:
474 -k<keyid> sign tag and package with <keyid> instead of default
475 --dry-run -n do not change anything, but go through the motions
476 --damp-run -L like --dry-run but make local changes, without signing
477 --new -N allow introducing a new package
478 --debug -D increase debug level
479 -c<name>=<value> set git config option (used directly by dgit too)
482 our $later_warning_msg = <<END;
483 Perhaps the upload is stuck in incoming. Using the version from git.
487 print STDERR "$us: @_\n", $helpmsg or die $!;
492 @ARGV or badusage "too few arguments";
493 return scalar shift @ARGV;
497 print $helpmsg or die $!;
501 our $td = $ENV{DGIT_TEST_DUMMY_DIR} || "DGIT_TEST_DUMMY_DIR-unset";
503 our %defcfg = ('dgit.default.distro' => 'debian',
504 'dgit.default.username' => '',
505 'dgit.default.archive-query-default-component' => 'main',
506 'dgit.default.ssh' => 'ssh',
507 'dgit.default.archive-query' => 'madison:',
508 'dgit.default.sshpsql-dbname' => 'service=projectb',
509 'dgit.default.dgit-tag-format' => 'old,new',
510 'dgit-distro.debian.archive-query' => 'ftpmasterapi:',
511 'dgit-distro.debian.git-check' => 'url',
512 'dgit-distro.debian.git-check-suffix' => '/info/refs',
513 'dgit-distro.debian.new-private-pushers' => 't',
514 'dgit-distro.debian.dgit-tag-format' => 'old',
515 'dgit-distro.debian/push.git-url' => '',
516 'dgit-distro.debian/push.git-host' => 'push.dgit.debian.org',
517 'dgit-distro.debian/push.git-user-force' => 'dgit',
518 'dgit-distro.debian/push.git-proto' => 'git+ssh://',
519 'dgit-distro.debian/push.git-path' => '/dgit/debian/repos',
520 'dgit-distro.debian/push.git-create' => 'true',
521 'dgit-distro.debian/push.git-check' => 'ssh-cmd',
522 'dgit-distro.debian.archive-query-url', 'https://api.ftp-master.debian.org/',
523 # 'dgit-distro.debian.archive-query-tls-key',
524 # '/etc/ssl/certs/%HOST%.pem:/etc/dgit/%HOST%.pem',
525 # ^ this does not work because curl is broken nowadays
526 # Fixing #790093 properly will involve providing providing the key
527 # in some pacagke and maybe updating these paths.
529 # 'dgit-distro.debian.archive-query-tls-curl-args',
530 # '--ca-path=/etc/ssl/ca-debian',
531 # ^ this is a workaround but works (only) on DSA-administered machines
532 'dgit-distro.debian.git-url' => 'https://git.dgit.debian.org',
533 'dgit-distro.debian.git-url-suffix' => '',
534 'dgit-distro.debian.upload-host' => 'ftp-master', # for dput
535 'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/',
536 'dgit-distro.debian.backports-quirk' => '(squeeze)-backports*',
537 'dgit-distro.debian-backports.mirror' => 'http://backports.debian.org/debian-backports/',
538 'dgit-distro.ubuntu.git-check' => 'false',
539 'dgit-distro.ubuntu.mirror' => 'http://archive.ubuntu.com/ubuntu',
540 'dgit-distro.test-dummy.ssh' => "$td/ssh",
541 'dgit-distro.test-dummy.username' => "alice",
542 'dgit-distro.test-dummy.git-check' => "ssh-cmd",
543 'dgit-distro.test-dummy.git-create' => "ssh-cmd",
544 'dgit-distro.test-dummy.git-url' => "$td/git",
545 'dgit-distro.test-dummy.git-host' => "git",
546 'dgit-distro.test-dummy.git-path' => "$td/git",
547 'dgit-distro.test-dummy.archive-query' => "ftpmasterapi:",
548 'dgit-distro.test-dummy.archive-query-url' => "file://$td/aq/",
549 'dgit-distro.test-dummy.mirror' => "file://$td/mirror/",
550 'dgit-distro.test-dummy.upload-host' => 'test-dummy',
555 sub git_slurp_config () {
556 local ($debuglevel) = $debuglevel-2;
559 my @cmd = (@git, qw(config -z --get-regexp .*));
562 open GITS, "-|", @cmd or die $!;
565 printdebug "=> ", (messagequote $_), "\n";
567 push @{ $gitcfg{$`} }, $'; #';
571 or ($!==0 && $?==256)
575 sub git_get_config ($) {
578 printdebug"C $c ".(defined $l ? messagequote "'$l'" : "undef")."\n"
581 @$l==1 or badcfg "multiple values for $c" if @$l > 1;
587 return undef if $c =~ /RETURN-UNDEF/;
588 my $v = git_get_config($c);
589 return $v if defined $v;
590 my $dv = $defcfg{$c};
591 return $dv if defined $dv;
593 badcfg "need value for one of: @_\n".
594 "$us: distro or suite appears not to be (properly) supported";
597 sub access_basedistro () {
598 if (defined $idistro) {
601 return cfg("dgit-suite.$isuite.distro",
602 "dgit.default.distro");
606 sub access_quirk () {
607 # returns (quirk name, distro to use instead or undef, quirk-specific info)
608 my $basedistro = access_basedistro();
609 my $backports_quirk = cfg("dgit-distro.$basedistro.backports-quirk",
611 if (defined $backports_quirk) {
612 my $re = $backports_quirk;
613 $re =~ s/[^-0-9a-z_\%*()]/\\$&/ig;
615 $re =~ s/\%/([-0-9a-z_]+)/
616 or $re =~ m/[()]/ or badcfg "backports-quirk needs \% or ( )";
617 if ($isuite =~ m/^$re$/) {
618 return ('backports',"$basedistro-backports",$1);
621 return ('none',undef);
626 sub parse_cfg_bool ($$$) {
627 my ($what,$def,$v) = @_;
630 $v =~ m/^[ty1]/ ? 1 :
631 $v =~ m/^[fn0]/ ? 0 :
632 badcfg "$what needs t (true, y, 1) or f (false, n, 0) not \`$v'";
635 sub access_forpush_config () {
636 my $d = access_basedistro();
640 parse_cfg_bool('new-private-pushers', 0,
641 cfg("dgit-distro.$d.new-private-pushers",
644 my $v = cfg("dgit-distro.$d.readonly", 'RETURN-UNDEF');
647 $v =~ m/^[ty1]/ ? 0 : # force readonly, forpush = 0
648 $v =~ m/^[fn0]/ ? 1 : # force nonreadonly, forpush = 1
649 $v =~ m/^[a]/ ? '' : # auto, forpush = ''
650 badcfg "readonly needs t (true, y, 1) or f (false, n, 0) or a (auto)";
653 sub access_forpush () {
654 $access_forpush //= access_forpush_config();
655 return $access_forpush;
659 die "$access_forpush ?" if ($access_forpush // 1) ne 1;
660 badcfg "pushing but distro is configured readonly"
661 if access_forpush_config() eq '0';
663 $supplementary_message = <<'END' unless $we_are_responder;
664 Push failed, before we got started.
665 You can retry the push, after fixing the problem, if you like.
667 finalise_opts_opts();
671 finalise_opts_opts();
674 sub supplementary_message ($) {
676 if (!$we_are_responder) {
677 $supplementary_message = $msg;
679 } elsif ($protovsn >= 3) {
680 responder_send_command "supplementary-message ".length($msg)
682 print PO $msg or die $!;
686 sub access_distros () {
687 # Returns list of distros to try, in order
690 # 0. `instead of' distro name(s) we have been pointed to
691 # 1. the access_quirk distro, if any
692 # 2a. the user's specified distro, or failing that } basedistro
693 # 2b. the distro calculated from the suite }
694 my @l = access_basedistro();
696 my (undef,$quirkdistro) = access_quirk();
697 unshift @l, $quirkdistro;
698 unshift @l, $instead_distro;
699 @l = grep { defined } @l;
701 if (access_forpush()) {
702 @l = map { ("$_/push", $_) } @l;
707 sub access_cfg_cfgs (@) {
710 # The nesting of these loops determines the search order. We put
711 # the key loop on the outside so that we search all the distros
712 # for each key, before going on to the next key. That means that
713 # if access_cfg is called with a more specific, and then a less
714 # specific, key, an earlier distro can override the less specific
715 # without necessarily overriding any more specific keys. (If the
716 # distro wants to override the more specific keys it can simply do
717 # so; whereas if we did the loop the other way around, it would be
718 # impossible to for an earlier distro to override a less specific
719 # key but not the more specific ones without restating the unknown
720 # values of the more specific keys.
723 # We have to deal with RETURN-UNDEF specially, so that we don't
724 # terminate the search prematurely.
726 if (m/RETURN-UNDEF/) { push @rundef, $_; last; }
729 foreach my $d (access_distros()) {
730 push @cfgs, map { "dgit-distro.$d.$_" } @realkeys;
732 push @cfgs, map { "dgit.default.$_" } @realkeys;
739 my (@cfgs) = access_cfg_cfgs(@keys);
740 my $value = cfg(@cfgs);
744 sub access_cfg_bool ($$) {
745 my ($def, @keys) = @_;
746 parse_cfg_bool($keys[0], $def, access_cfg(@keys, 'RETURN-UNDEF'));
749 sub string_to_ssh ($) {
751 if ($spec =~ m/\s/) {
752 return qw(sh -ec), 'exec '.$spec.' "$@"', 'x';
758 sub access_cfg_ssh () {
759 my $gitssh = access_cfg('ssh', 'RETURN-UNDEF');
760 if (!defined $gitssh) {
763 return string_to_ssh $gitssh;
767 sub access_runeinfo ($) {
769 return ": dgit ".access_basedistro()." $info ;";
772 sub access_someuserhost ($) {
774 my $user = access_cfg("$some-user-force", 'RETURN-UNDEF');
775 defined($user) && length($user) or
776 $user = access_cfg("$some-user",'username');
777 my $host = access_cfg("$some-host");
778 return length($user) ? "$user\@$host" : $host;
781 sub access_gituserhost () {
782 return access_someuserhost('git');
785 sub access_giturl (;$) {
787 my $url = access_cfg('git-url','RETURN-UNDEF');
790 my $proto = access_cfg('git-proto', 'RETURN-UNDEF');
791 return undef unless defined $proto;
794 access_gituserhost().
795 access_cfg('git-path');
797 $suffix = access_cfg('git-url-suffix','RETURN-UNDEF');
800 return "$url/$package$suffix";
803 sub parsecontrolfh ($$;$) {
804 my ($fh, $desc, $allowsigned) = @_;
805 our $dpkgcontrolhash_noissigned;
808 my %opts = ('name' => $desc);
809 $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
810 $c = Dpkg::Control::Hash->new(%opts);
811 $c->parse($fh,$desc) or die "parsing of $desc failed";
812 last if $allowsigned;
813 last if $dpkgcontrolhash_noissigned;
814 my $issigned= $c->get_option('is_pgp_signed');
815 if (!defined $issigned) {
816 $dpkgcontrolhash_noissigned= 1;
817 seek $fh, 0,0 or die "seek $desc: $!";
818 } elsif ($issigned) {
819 fail "control file $desc is (already) PGP-signed. ".
820 " Note that dgit push needs to modify the .dsc and then".
821 " do the signature itself";
830 my ($file, $desc) = @_;
831 my $fh = new IO::Handle;
832 open $fh, '<', $file or die "$file: $!";
833 my $c = parsecontrolfh($fh,$desc);
834 $fh->error and die $!;
840 my ($dctrl,$field) = @_;
841 my $v = $dctrl->{$field};
842 return $v if defined $v;
843 fail "missing field $field in ".$v->get_option('name');
847 my $c = Dpkg::Control::Hash->new();
848 my $p = new IO::Handle;
849 my @cmd = (qw(dpkg-parsechangelog), @_);
850 open $p, '-|', @cmd or die $!;
852 $?=0; $!=0; close $p or failedcmd @cmd;
858 defined $d or fail "getcwd failed: $!";
864 sub archive_query ($) {
866 my $query = access_cfg('archive-query','RETURN-UNDEF');
867 $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
870 { no strict qw(refs); &{"${method}_${proto}"}($proto,$data); }
873 sub pool_dsc_subpath ($$) {
874 my ($vsn,$component) = @_; # $package is implict arg
875 my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
876 return "/pool/$component/$prefix/$package/".dscfn($vsn);
879 #---------- `ftpmasterapi' archive query method (nascent) ----------
881 sub archive_api_query_cmd ($) {
883 my @cmd = qw(curl -sS);
884 my $url = access_cfg('archive-query-url');
885 if ($url =~ m#^https://([-.0-9a-z]+)/#) {
887 my $keys = access_cfg('archive-query-tls-key','RETURN-UNDEF') //'';
888 foreach my $key (split /\:/, $keys) {
889 $key =~ s/\%HOST\%/$host/g;
891 fail "for $url: stat $key: $!" unless $!==ENOENT;
894 fail "config requested specific TLS key but do not know".
895 " how to get curl to use exactly that EE key ($key)";
896 # push @cmd, "--cacert", $key, "--capath", "/dev/enoent";
897 # # Sadly the above line does not work because of changes
898 # # to gnutls. The real fix for #790093 may involve
899 # # new curl options.
902 # Fixing #790093 properly will involve providing a value
903 # for this on clients.
904 my $kargs = access_cfg('archive-query-tls-curl-ca-args','RETURN-UNDEF');
905 push @cmd, split / /, $kargs if defined $kargs;
907 push @cmd, $url.$subpath;
913 my ($data, $subpath) = @_;
914 badcfg "ftpmasterapi archive query method takes no data part"
916 my @cmd = archive_api_query_cmd($subpath);
917 my $json = cmdoutput @cmd;
918 return decode_json($json);
921 sub canonicalise_suite_ftpmasterapi () {
922 my ($proto,$data) = @_;
923 my $suites = api_query($data, 'suites');
925 foreach my $entry (@$suites) {
927 my $v = $entry->{$_};
928 defined $v && $v eq $isuite;
930 push @matched, $entry;
932 fail "unknown suite $isuite" unless @matched;
935 @matched==1 or die "multiple matches for suite $isuite\n";
936 $cn = "$matched[0]{codename}";
937 defined $cn or die "suite $isuite info has no codename\n";
938 $cn =~ m/^$suite_re$/ or die "suite $isuite maps to bad codename\n";
940 die "bad ftpmaster api response: $@\n".Dumper(\@matched)
945 sub archive_query_ftpmasterapi () {
946 my ($proto,$data) = @_;
947 my $info = api_query($data, "dsc_in_suite/$isuite/$package");
949 my $digester = Digest::SHA->new(256);
950 foreach my $entry (@$info) {
952 my $vsn = "$entry->{version}";
953 my ($ok,$msg) = version_check $vsn;
954 die "bad version: $msg\n" unless $ok;
955 my $component = "$entry->{component}";
956 $component =~ m/^$component_re$/ or die "bad component";
957 my $filename = "$entry->{filename}";
958 $filename && $filename !~ m#[^-+:._~0-9a-zA-Z/]|^[/.]|/[/.]#
959 or die "bad filename";
960 my $sha256sum = "$entry->{sha256sum}";
961 $sha256sum =~ m/^[0-9a-f]+$/ or die "bad sha256sum";
962 push @rows, [ $vsn, "/pool/$component/$filename",
963 $digester, $sha256sum ];
965 die "bad ftpmaster api response: $@\n".Dumper($entry)
968 @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
972 #---------- `madison' archive query method ----------
974 sub archive_query_madison {
975 return map { [ @$_[0..1] ] } madison_get_parse(@_);
978 sub madison_get_parse {
979 my ($proto,$data) = @_;
980 die unless $proto eq 'madison';
982 $data= access_cfg('madison-distro','RETURN-UNDEF');
983 $data //= access_basedistro();
985 $rmad{$proto,$data,$package} ||= cmdoutput
986 qw(rmadison -asource),"-s$isuite","-u$data",$package;
987 my $rmad = $rmad{$proto,$data,$package};
990 foreach my $l (split /\n/, $rmad) {
991 $l =~ m{^ \s*( [^ \t|]+ )\s* \|
992 \s*( [^ \t|]+ )\s* \|
993 \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
994 \s*( [^ \t|]+ )\s* }x or die "$rmad ?";
995 $1 eq $package or die "$rmad $package ?";
1002 $component = access_cfg('archive-query-default-component');
1004 $5 eq 'source' or die "$rmad ?";
1005 push @out, [$vsn,pool_dsc_subpath($vsn,$component),$newsuite];
1007 return sort { -version_compare($a->[0],$b->[0]); } @out;
1010 sub canonicalise_suite_madison {
1011 # madison canonicalises for us
1012 my @r = madison_get_parse(@_);
1014 "unable to canonicalise suite using package $package".
1015 " which does not appear to exist in suite $isuite;".
1016 " --existing-package may help";
1020 #---------- `sshpsql' archive query method ----------
1023 my ($data,$runeinfo,$sql) = @_;
1024 if (!length $data) {
1025 $data= access_someuserhost('sshpsql').':'.
1026 access_cfg('sshpsql-dbname');
1028 $data =~ m/:/ or badcfg "invalid sshpsql method string \`$data'";
1029 my ($userhost,$dbname) = ($`,$'); #';
1031 my @cmd = (access_cfg_ssh, $userhost,
1032 access_runeinfo("ssh-psql $runeinfo").
1033 " export LC_MESSAGES=C; export LC_CTYPE=C;".
1034 " ".shellquote qw(psql -A), $dbname, qw(-c), $sql);
1036 open P, "-|", @cmd or die $!;
1039 printdebug(">|$_|\n");
1042 $!=0; $?=0; close P or failedcmd @cmd;
1044 my $nrows = pop @rows;
1045 $nrows =~ s/^\((\d+) rows?\)$/$1/ or die "$nrows ?";
1046 @rows == $nrows+1 or die "$nrows ".(scalar @rows)." ?";
1047 @rows = map { [ split /\|/, $_ ] } @rows;
1048 my $ncols = scalar @{ shift @rows };
1049 die if grep { scalar @$_ != $ncols } @rows;
1053 sub sql_injection_check {
1054 foreach (@_) { die "$_ $& ?" if m{[^-+=:_.,/0-9a-zA-Z]}; }
1057 sub archive_query_sshpsql ($$) {
1058 my ($proto,$data) = @_;
1059 sql_injection_check $isuite, $package;
1060 my @rows = sshpsql($data, "archive-query $isuite $package", <<END);
1061 SELECT source.version, component.name, files.filename, files.sha256sum
1063 JOIN src_associations ON source.id = src_associations.source
1064 JOIN suite ON suite.id = src_associations.suite
1065 JOIN dsc_files ON dsc_files.source = source.id
1066 JOIN files_archive_map ON files_archive_map.file_id = dsc_files.file
1067 JOIN component ON component.id = files_archive_map.component_id
1068 JOIN files ON files.id = dsc_files.file
1069 WHERE ( suite.suite_name='$isuite' OR suite.codename='$isuite' )
1070 AND source.source='$package'
1071 AND files.filename LIKE '%.dsc';
1073 @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
1074 my $digester = Digest::SHA->new(256);
1076 my ($vsn,$component,$filename,$sha256sum) = @$_;
1077 [ $vsn, "/pool/$component/$filename",$digester,$sha256sum ];
1082 sub canonicalise_suite_sshpsql ($$) {
1083 my ($proto,$data) = @_;
1084 sql_injection_check $isuite;
1085 my @rows = sshpsql($data, "canonicalise-suite $isuite", <<END);
1086 SELECT suite.codename
1087 FROM suite where suite_name='$isuite' or codename='$isuite';
1089 @rows = map { $_->[0] } @rows;
1090 fail "unknown suite $isuite" unless @rows;
1091 die "ambiguous $isuite: @rows ?" if @rows>1;
1095 #---------- `dummycat' archive query method ----------
1097 sub canonicalise_suite_dummycat ($$) {
1098 my ($proto,$data) = @_;
1099 my $dpath = "$data/suite.$isuite";
1100 if (!open C, "<", $dpath) {
1101 $!==ENOENT or die "$dpath: $!";
1102 printdebug "dummycat canonicalise_suite $isuite $dpath ENOENT\n";
1106 chomp or die "$dpath: $!";
1108 printdebug "dummycat canonicalise_suite $isuite $dpath = $_\n";
1112 sub archive_query_dummycat ($$) {
1113 my ($proto,$data) = @_;
1114 canonicalise_suite();
1115 my $dpath = "$data/package.$csuite.$package";
1116 if (!open C, "<", $dpath) {
1117 $!==ENOENT or die "$dpath: $!";
1118 printdebug "dummycat query $csuite $package $dpath ENOENT\n";
1126 printdebug "dummycat query $csuite $package $dpath | $_\n";
1127 my @row = split /\s+/, $_;
1128 @row==2 or die "$dpath: $_ ?";
1131 C->error and die "$dpath: $!";
1133 return sort { -version_compare($a->[0],$b->[0]); } @rows;
1136 #---------- tag format handling ----------
1138 sub access_cfg_tagformats () {
1139 split /\,/, access_cfg('dgit-tag-format');
1142 sub need_tagformat ($$) {
1143 my ($fmt, $why) = @_;
1144 fail "need to use tag format $fmt ($why) but also need".
1145 " to use tag format $tagformat_want->[0] ($tagformat_want->[1])".
1146 " - no way to proceed"
1147 if $tagformat_want && $tagformat_want->[0] ne $fmt;
1148 $tagformat_want = [$fmt, $why, $tagformat_want->[2] // 0];
1151 sub select_tagformat () {
1153 return if $tagformatfn && !$tagformat_want;
1154 die 'bug' if $tagformatfn && $tagformat_want;
1155 # ... $tagformat_want assigned after previous select_tagformat
1157 my (@supported) = access_cfg_tagformats();
1158 printdebug "select_tagformat supported @supported\n";
1160 $tagformat_want //= [ $supported[0], "distro access configuration", 0 ];
1161 printdebug "select_tagformat specified @$tagformat_want\n";
1163 my ($fmt,$why,$override) = @$tagformat_want;
1165 fail "target distro supports tag formats @supported".
1166 " but have to use $fmt ($why)"
1168 or grep { $_ eq $fmt } @supported;
1170 $tagformat_want = undef;
1172 $tagformatfn = ${*::}{"debiantag_$fmt"};
1174 fail "trying to use unknown tag format \`$fmt' ($why) !"
1175 unless $tagformatfn;
1178 #---------- archive query entrypoints and rest of program ----------
1180 sub canonicalise_suite () {
1181 return if defined $csuite;
1182 fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
1183 $csuite = archive_query('canonicalise_suite');
1184 if ($isuite ne $csuite) {
1185 progress "canonical suite name for $isuite is $csuite";
1189 sub get_archive_dsc () {
1190 canonicalise_suite();
1191 my @vsns = archive_query('archive_query');
1192 foreach my $vinfo (@vsns) {
1193 my ($vsn,$subpath,$digester,$digest) = @$vinfo;
1194 $dscurl = access_cfg('mirror').$subpath;
1195 $dscdata = url_get($dscurl);
1197 $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
1202 $digester->add($dscdata);
1203 my $got = $digester->hexdigest();
1205 fail "$dscurl has hash $got but".
1206 " archive told us to expect $digest";
1208 my $dscfh = new IO::File \$dscdata, '<' or die $!;
1209 printdebug Dumper($dscdata) if $debuglevel>1;
1210 $dsc = parsecontrolfh($dscfh,$dscurl,1);
1211 printdebug Dumper($dsc) if $debuglevel>1;
1212 my $fmt = getfield $dsc, 'Format';
1213 fail "unsupported source format $fmt, sorry" unless $format_ok{$fmt};
1214 $dsc_checked = !!$digester;
1220 sub check_for_git ();
1221 sub check_for_git () {
1223 my $how = access_cfg('git-check');
1224 if ($how eq 'ssh-cmd') {
1226 (access_cfg_ssh, access_gituserhost(),
1227 access_runeinfo("git-check $package").
1228 " set -e; cd ".access_cfg('git-path').";".
1229 " if test -d $package.git; then echo 1; else echo 0; fi");
1230 my $r= cmdoutput @cmd;
1231 if (defined $r and $r =~ m/^divert (\w+)$/) {
1233 my ($usedistro,) = access_distros();
1234 # NB that if we are pushing, $usedistro will be $distro/push
1235 $instead_distro= cfg("dgit-distro.$usedistro.diverts.$divert");
1236 $instead_distro =~ s{^/}{ access_basedistro()."/" }e;
1237 progress "diverting to $divert (using config for $instead_distro)";
1238 return check_for_git();
1240 failedcmd @cmd unless defined $r and $r =~ m/^[01]$/;
1242 } elsif ($how eq 'url') {
1243 my $prefix = access_cfg('git-check-url','git-url');
1244 my $suffix = access_cfg('git-check-suffix','git-suffix',
1245 'RETURN-UNDEF') // '.git';
1246 my $url = "$prefix/$package$suffix";
1247 my @cmd = (qw(curl -sS -I), $url);
1248 my $result = cmdoutput @cmd;
1249 $result =~ s/^\S+ 200 .*\n\r?\n//;
1250 # curl -sS -I with https_proxy prints
1251 # HTTP/1.0 200 Connection established
1252 $result =~ m/^\S+ (404|200) /s or
1253 fail "unexpected results from git check query - ".
1254 Dumper($prefix, $result);
1256 if ($code eq '404') {
1258 } elsif ($code eq '200') {
1263 } elsif ($how eq 'true') {
1265 } elsif ($how eq 'false') {
1268 badcfg "unknown git-check \`$how'";
1272 sub create_remote_git_repo () {
1273 my $how = access_cfg('git-create');
1274 if ($how eq 'ssh-cmd') {
1276 (access_cfg_ssh, access_gituserhost(),
1277 access_runeinfo("git-create $package").
1278 "set -e; cd ".access_cfg('git-path').";".
1279 " cp -a _template $package.git");
1280 } elsif ($how eq 'true') {
1283 badcfg "unknown git-create \`$how'";
1287 our ($dsc_hash,$lastpush_hash);
1289 our $ud = '.git/dgit/unpack';
1299 sub mktree_in_ud_here () {
1300 runcmd qw(git init -q);
1301 rmtree('.git/objects');
1302 symlink '../../../../objects','.git/objects' or die $!;
1305 sub git_write_tree () {
1306 my $tree = cmdoutput @git, qw(write-tree);
1307 $tree =~ m/^\w+$/ or die "$tree ?";
1311 sub remove_stray_gits () {
1312 my @gitscmd = qw(find -name .git -prune -print0);
1313 debugcmd "|",@gitscmd;
1314 open GITS, "-|", @gitscmd or die $!;
1319 print STDERR "$us: warning: removing from source package: ",
1320 (messagequote $_), "\n";
1324 $!=0; $?=0; close GITS or failedcmd @gitscmd;
1327 sub mktree_in_ud_from_only_subdir () {
1328 # changes into the subdir
1330 die "@dirs ?" unless @dirs==1;
1331 $dirs[0] =~ m#^([^/]+)/\.$# or die;
1335 remove_stray_gits();
1336 mktree_in_ud_here();
1337 my ($format, $fopts) = get_source_format();
1338 if (madformat($format)) {
1341 runcmd @git, qw(add -Af);
1342 my $tree=git_write_tree();
1343 return ($tree,$dir);
1346 sub dsc_files_info () {
1347 foreach my $csumi (['Checksums-Sha256','Digest::SHA', 'new(256)'],
1348 ['Checksums-Sha1', 'Digest::SHA', 'new(1)'],
1349 ['Files', 'Digest::MD5', 'new()']) {
1350 my ($fname, $module, $method) = @$csumi;
1351 my $field = $dsc->{$fname};
1352 next unless defined $field;
1353 eval "use $module; 1;" or die $@;
1355 foreach (split /\n/, $field) {
1357 m/^(\w+) (\d+) (\S+)$/ or
1358 fail "could not parse .dsc $fname line \`$_'";
1359 my $digester = eval "$module"."->$method;" or die $@;
1364 Digester => $digester,
1369 fail "missing any supported Checksums-* or Files field in ".
1370 $dsc->get_option('name');
1374 map { $_->{Filename} } dsc_files_info();
1377 sub is_orig_file ($;$) {
1380 m/\.orig(?:-\w+)?\.tar\.\w+$/ or return 0;
1381 defined $base or return 1;
1385 sub make_commit ($) {
1387 return cmdoutput @git, qw(hash-object -w -t commit), $file;
1390 sub clogp_authline ($) {
1392 my $author = getfield $clogp, 'Maintainer';
1393 $author =~ s#,.*##ms;
1394 my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
1395 my $authline = "$author $date";
1396 $authline =~ m/$git_authline_re/o or
1397 fail "unexpected commit author line format \`$authline'".
1398 " (was generated from changelog Maintainer field)";
1399 return ($1,$2,$3) if wantarray;
1403 sub vendor_patches_distro ($$) {
1404 my ($checkdistro, $what) = @_;
1405 return unless defined $checkdistro;
1407 my $series = "debian/patches/\L$checkdistro\E.series";
1408 printdebug "checking for vendor-specific $series ($what)\n";
1410 if (!open SERIES, "<", $series) {
1411 die "$series $!" unless $!==ENOENT;
1420 Unfortunately, this source package uses a feature of dpkg-source where
1421 the same source package unpacks to different source code on different
1422 distros. dgit cannot safely operate on such packages on affected
1423 distros, because the meaning of source packages is not stable.
1425 Please ask the distro/maintainer to remove the distro-specific series
1426 files and use a different technique (if necessary, uploading actually
1427 different packages, if different distros are supposed to have
1431 fail "Found active distro-specific series file for".
1432 " $checkdistro ($what): $series, cannot continue";
1434 die "$series $!" if SERIES->error;
1438 sub check_for_vendor_patches () {
1439 # This dpkg-source feature doesn't seem to be documented anywhere!
1440 # But it can be found in the changelog (reformatted):
1442 # commit 4fa01b70df1dc4458daee306cfa1f987b69da58c
1443 # Author: Raphael Hertzog <hertzog@debian.org>
1444 # Date: Sun Oct 3 09:36:48 2010 +0200
1446 # dpkg-source: correctly create .pc/.quilt_series with alternate
1449 # If you have debian/patches/ubuntu.series and you were
1450 # unpacking the source package on ubuntu, quilt was still
1451 # directed to debian/patches/series instead of
1452 # debian/patches/ubuntu.series.
1454 # debian/changelog | 3 +++
1455 # scripts/Dpkg/Source/Package/V3/quilt.pm | 4 +++-
1456 # 2 files changed, 6 insertions(+), 1 deletion(-)
1459 vendor_patches_distro($ENV{DEB_VENDOR}, "DEB_VENDOR");
1460 vendor_patches_distro(Dpkg::Vendor::get_current_vendor(),
1461 "Dpkg::Vendor \`current vendor'");
1462 vendor_patches_distro(access_basedistro(),
1463 "distro being accessed");
1466 sub generate_commit_from_dsc () {
1470 foreach my $fi (dsc_files_info()) {
1471 my $f = $fi->{Filename};
1472 die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
1474 link_ltarget "../../../$f", $f
1478 complete_file_from_dsc('.', $fi)
1481 if (is_orig_file($f)) {
1482 link $f, "../../../../$f"
1488 my $dscfn = "$package.dsc";
1490 open D, ">", $dscfn or die "$dscfn: $!";
1491 print D $dscdata or die "$dscfn: $!";
1492 close D or die "$dscfn: $!";
1493 my @cmd = qw(dpkg-source);
1494 push @cmd, '--no-check' if $dsc_checked;
1495 push @cmd, qw(-x --), $dscfn;
1498 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1499 check_for_vendor_patches() if madformat($dsc->{format});
1500 runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
1501 my $clogp = parsecontrol('../changelog.tmp',"commit's changelog");
1502 my $authline = clogp_authline $clogp;
1503 my $changes = getfield $clogp, 'Changes';
1504 open C, ">../commit.tmp" or die $!;
1505 print C <<END or die $!;
1512 # imported from the archive
1515 my $outputhash = make_commit qw(../commit.tmp);
1516 my $cversion = getfield $clogp, 'Version';
1517 progress "synthesised git commit from .dsc $cversion";
1518 if ($lastpush_hash) {
1519 runcmd @git, qw(reset -q --hard), $lastpush_hash;
1520 runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
1521 my $oldclogp = parsecontrol('../changelogold.tmp','previous changelog');
1522 my $oversion = getfield $oldclogp, 'Version';
1524 version_compare($oversion, $cversion);
1526 # git upload/ is earlier vsn than archive, use archive
1527 open C, ">../commit2.tmp" or die $!;
1528 print C <<END or die $!;
1530 parent $lastpush_hash
1535 Record $package ($cversion) in archive suite $csuite
1537 $outputhash = make_commit qw(../commit2.tmp);
1538 } elsif ($vcmp > 0) {
1539 print STDERR <<END or die $!;
1541 Version actually in archive: $cversion (older)
1542 Last allegedly pushed/uploaded: $oversion (newer or same)
1545 $outputhash = $lastpush_hash;
1547 $outputhash = $lastpush_hash;
1550 changedir '../../../..';
1551 runcmd @git, qw(update-ref -m),"dgit fetch import $cversion",
1552 'DGIT_ARCHIVE', $outputhash;
1553 cmdoutput @git, qw(log -n2), $outputhash;
1554 # ... gives git a chance to complain if our commit is malformed
1559 sub complete_file_from_dsc ($$) {
1560 our ($dstdir, $fi) = @_;
1561 # Ensures that we have, in $dir, the file $fi, with the correct
1562 # contents. (Downloading it from alongside $dscurl if necessary.)
1564 my $f = $fi->{Filename};
1565 my $tf = "$dstdir/$f";
1568 if (stat_exists $tf) {
1569 progress "using existing $f";
1572 $furl =~ s{/[^/]+$}{};
1574 die "$f ?" unless $f =~ m/^\Q${package}\E_/;
1575 die "$f ?" if $f =~ m#/#;
1576 runcmd_ordryrun_local @curl,qw(-o),$tf,'--',"$furl";
1577 return 0 if !act_local();
1581 open F, "<", "$tf" or die "$tf: $!";
1582 $fi->{Digester}->reset();
1583 $fi->{Digester}->addfile(*F);
1584 F->error and die $!;
1585 my $got = $fi->{Digester}->hexdigest();
1586 $got eq $fi->{Hash} or
1587 fail "file $f has hash $got but .dsc".
1588 " demands hash $fi->{Hash} ".
1589 ($downloaded ? "(got wrong file from archive!)"
1590 : "(perhaps you should delete this file?)");
1595 sub ensure_we_have_orig () {
1596 foreach my $fi (dsc_files_info()) {
1597 my $f = $fi->{Filename};
1598 next unless is_orig_file($f);
1599 complete_file_from_dsc('..', $fi)
1604 sub git_fetch_us () {
1605 my @specs = (fetchspec());
1607 map { "+refs/$_/*:".lrfetchrefs."/$_/*" }
1609 runcmd_ordryrun_local @git, qw(fetch -p -n -q), access_giturl(), @specs;
1612 my @tagpats = debiantags('*',access_basedistro);
1614 git_for_each_ref([map { "refs/tags/$_" } @tagpats], sub {
1615 my ($objid,$objtype,$fullrefname,$reftail) = @_;
1616 printdebug "currently $fullrefname=$objid\n";
1617 $here{$fullrefname} = $objid;
1619 git_for_each_ref([map { lrfetchrefs."/tags/".$_ } @tagpats], sub {
1620 my ($objid,$objtype,$fullrefname,$reftail) = @_;
1621 my $lref = "refs".substr($fullrefname, length lrfetchrefs);
1622 printdebug "offered $lref=$objid\n";
1623 if (!defined $here{$lref}) {
1624 my @upd = (@git, qw(update-ref), $lref, $objid, '');
1625 runcmd_ordryrun_local @upd;
1626 } elsif ($here{$lref} eq $objid) {
1629 "Not updateting $lref from $here{$lref} to $objid.\n";
1634 sub fetch_from_archive () {
1635 # ensures that lrref() is what is actually in the archive,
1636 # one way or another
1640 foreach my $field (@ourdscfield) {
1641 $dsc_hash = $dsc->{$field};
1642 last if defined $dsc_hash;
1644 if (defined $dsc_hash) {
1645 $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
1647 progress "last upload to archive specified git hash";
1649 progress "last upload to archive has NO git hash";
1652 progress "no version available from the archive";
1655 $lastpush_hash = git_get_ref(lrref());
1656 printdebug "previous reference hash=$lastpush_hash\n";
1658 if (defined $dsc_hash) {
1659 fail "missing remote git history even though dsc has hash -".
1660 " could not find ref ".lrref().
1661 " (should have been fetched from ".access_giturl()."#".rrref().")"
1662 unless $lastpush_hash;
1664 ensure_we_have_orig();
1665 if ($dsc_hash eq $lastpush_hash) {
1666 } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
1667 print STDERR <<END or die $!;
1669 Git commit in archive is behind the last version allegedly pushed/uploaded.
1670 Commit referred to by archive: $dsc_hash
1671 Last allegedly pushed/uploaded: $lastpush_hash
1674 $hash = $lastpush_hash;
1676 fail "git head (".lrref()."=$lastpush_hash) is not a ".
1677 "descendant of archive's .dsc hash ($dsc_hash)";
1680 $hash = generate_commit_from_dsc();
1681 } elsif ($lastpush_hash) {
1682 # only in git, not in the archive yet
1683 $hash = $lastpush_hash;
1684 print STDERR <<END or die $!;
1686 Package not found in the archive, but has allegedly been pushed using dgit.
1690 printdebug "nothing found!\n";
1691 if (defined $skew_warning_vsn) {
1692 print STDERR <<END or die $!;
1694 Warning: relevant archive skew detected.
1695 Archive allegedly contains $skew_warning_vsn
1696 But we were not able to obtain any version from the archive or git.
1702 printdebug "current hash=$hash\n";
1703 if ($lastpush_hash) {
1704 fail "not fast forward on last upload branch!".
1705 " (archive's version left in DGIT_ARCHIVE)"
1706 unless is_fast_fwd($lastpush_hash, $hash);
1708 if (defined $skew_warning_vsn) {
1710 printdebug "SKEW CHECK WANT $skew_warning_vsn\n";
1711 my $clogf = ".git/dgit/changelog.tmp";
1712 runcmd shell_cmd "exec >$clogf",
1713 @git, qw(cat-file blob), "$hash:debian/changelog";
1714 my $gotclogp = parsechangelog("-l$clogf");
1715 my $got_vsn = getfield $gotclogp, 'Version';
1716 printdebug "SKEW CHECK GOT $got_vsn\n";
1717 if (version_compare($got_vsn, $skew_warning_vsn) < 0) {
1718 print STDERR <<END or die $!;
1720 Warning: archive skew detected. Using the available version:
1721 Archive allegedly contains $skew_warning_vsn
1722 We were able to obtain only $got_vsn
1727 if ($lastpush_hash ne $hash) {
1728 my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
1732 dryrun_report @upd_cmd;
1738 sub set_local_git_config ($$) {
1740 runcmd @git, qw(config), $k, $v;
1743 sub setup_mergechangelogs (;$) {
1745 return unless $always || access_cfg_bool(1, 'setup-mergechangelogs');
1747 my $driver = 'dpkg-mergechangelogs';
1748 my $cb = "merge.$driver";
1749 my $attrs = '.git/info/attributes';
1750 ensuredir '.git/info';
1752 open NATTRS, ">", "$attrs.new" or die "$attrs.new $!";
1753 if (!open ATTRS, "<", $attrs) {
1754 $!==ENOENT or die "$attrs: $!";
1758 next if m{^debian/changelog\s};
1759 print NATTRS $_, "\n" or die $!;
1761 ATTRS->error and die $!;
1764 print NATTRS "debian/changelog merge=$driver\n" or die $!;
1767 set_local_git_config "$cb.name", 'debian/changelog merge driver';
1768 set_local_git_config "$cb.driver", 'dpkg-mergechangelogs -m %O %A %B %A';
1770 rename "$attrs.new", "$attrs" or die "$attrs: $!";
1773 sub setup_useremail (;$) {
1775 return unless $always || access_cfg_bool(1, 'setup-useremail');
1778 my ($k, $envvar) = @_;
1779 my $v = access_cfg("user-$k", 'RETURN-UNDEF') // $ENV{$envvar};
1780 return unless defined $v;
1781 set_local_git_config "user.$k", $v;
1784 $setup->('email', 'DEBEMAIL');
1785 $setup->('name', 'DEBFULLNAME');
1788 sub setup_new_tree () {
1789 setup_mergechangelogs();
1795 canonicalise_suite();
1796 badusage "dry run makes no sense with clone" unless act_local();
1797 my $hasgit = check_for_git();
1798 mkdir $dstdir or fail "create \`$dstdir': $!";
1800 runcmd @git, qw(init -q);
1801 my $giturl = access_giturl(1);
1802 if (defined $giturl) {
1803 set_local_git_config "remote.$remotename.fetch", fetchspec();
1804 open H, "> .git/HEAD" or die $!;
1805 print H "ref: ".lref()."\n" or die $!;
1807 runcmd @git, qw(remote add), 'origin', $giturl;
1810 progress "fetching existing git history";
1812 runcmd_ordryrun_local @git, qw(fetch origin);
1814 progress "starting new git history";
1816 fetch_from_archive() or no_such_package;
1817 my $vcsgiturl = $dsc->{'Vcs-Git'};
1818 if (length $vcsgiturl) {
1819 $vcsgiturl =~ s/\s+-b\s+\S+//g;
1820 runcmd @git, qw(remote add vcs-git), $vcsgiturl;
1823 runcmd @git, qw(reset --hard), lrref();
1824 printdone "ready for work in $dstdir";
1828 if (check_for_git()) {
1831 fetch_from_archive() or no_such_package();
1832 printdone "fetched into ".lrref();
1837 runcmd_ordryrun_local @git, qw(merge -m),"Merge from $csuite [dgit]",
1839 printdone "fetched to ".lrref()." and merged into HEAD";
1842 sub check_not_dirty () {
1843 foreach my $f (qw(local-options local-patch-header)) {
1844 if (stat_exists "debian/source/$f") {
1845 fail "git tree contains debian/source/$f";
1849 return if $ignoredirty;
1851 my @cmd = (@git, qw(diff --quiet HEAD));
1853 $!=0; $?=-1; system @cmd;
1856 fail "working tree is dirty (does not match HEAD)";
1862 sub commit_admin ($) {
1865 runcmd_ordryrun_local @git, qw(commit -m), $m;
1868 sub commit_quilty_patch () {
1869 my $output = cmdoutput @git, qw(status --porcelain);
1871 foreach my $l (split /\n/, $output) {
1872 next unless $l =~ m/\S/;
1873 if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
1877 delete $adds{'.pc'}; # if there wasn't one before, don't add it
1879 progress "nothing quilty to commit, ok.";
1882 my @adds = map { s/[][*?\\]/\\$&/g; $_; } sort keys %adds;
1883 runcmd_ordryrun_local @git, qw(add -f), @adds;
1884 commit_admin "Commit Debian 3.0 (quilt) metadata";
1887 sub get_source_format () {
1889 if (open F, "debian/source/options") {
1893 s/\s+$//; # ignore missing final newline
1895 my ($k, $v) = ($`, $'); #');
1896 $v =~ s/^"(.*)"$/$1/;
1902 F->error and die $!;
1905 die $! unless $!==&ENOENT;
1908 if (!open F, "debian/source/format") {
1909 die $! unless $!==&ENOENT;
1913 F->error and die $!;
1915 return ($_, \%options);
1920 return 0 unless $format eq '3.0 (quilt)';
1921 our $quilt_mode_warned;
1922 if ($quilt_mode eq 'nocheck') {
1923 progress "Not doing any fixup of \`$format' due to".
1924 " ----no-quilt-fixup or --quilt=nocheck"
1925 unless $quilt_mode_warned++;
1928 progress "Format \`$format', need to check/update patch stack"
1929 unless $quilt_mode_warned++;
1933 sub push_parse_changelog ($) {
1936 my $clogp = Dpkg::Control::Hash->new();
1937 $clogp->load($clogpfn) or die;
1939 $package = getfield $clogp, 'Source';
1940 my $cversion = getfield $clogp, 'Version';
1941 my $tag = debiantag($cversion, access_basedistro);
1942 runcmd @git, qw(check-ref-format), $tag;
1944 my $dscfn = dscfn($cversion);
1946 return ($clogp, $cversion, $dscfn);
1949 sub push_parse_dsc ($$$) {
1950 my ($dscfn,$dscfnwhat, $cversion) = @_;
1951 $dsc = parsecontrol($dscfn,$dscfnwhat);
1952 my $dversion = getfield $dsc, 'Version';
1953 my $dscpackage = getfield $dsc, 'Source';
1954 ($dscpackage eq $package && $dversion eq $cversion) or
1955 fail "$dscfn is for $dscpackage $dversion".
1956 " but debian/changelog is for $package $cversion";
1959 sub push_tagwants ($$$) {
1960 my ($cversion, $dgithead, $tfbase) = @_;
1963 TagFn => \&debiantag,
1968 foreach my $tw (@tagwants) {
1969 $tw->{Tag} = $tw->{TagFn}($cversion, access_basedistro);
1970 $tw->{Tfn} = sub { $tfbase.$tw->{TfSuffix}.$_[0]; };
1975 sub push_mktags ($$ $$ $) {
1977 $changesfile,$changesfilewhat,
1980 die unless $tagwants->[0]{View} eq 'dgit';
1982 $dsc->{$ourdscfield[0]} = $tagwants->[0]{Objid};
1983 $dsc->save("$dscfn.tmp") or die $!;
1985 my $changes = parsecontrol($changesfile,$changesfilewhat);
1986 foreach my $field (qw(Source Distribution Version)) {
1987 $changes->{$field} eq $clogp->{$field} or
1988 fail "changes field $field \`$changes->{$field}'".
1989 " does not match changelog \`$clogp->{$field}'";
1992 my $cversion = getfield $clogp, 'Version';
1993 my $clogsuite = getfield $clogp, 'Distribution';
1995 # We make the git tag by hand because (a) that makes it easier
1996 # to control the "tagger" (b) we can do remote signing
1997 my $authline = clogp_authline $clogp;
1998 my $delibs = join(" ", "",@deliberatelies);
1999 my $declaredistro = access_basedistro();
2003 my $tfn = $tw->{Tfn};
2004 my $head = $tw->{Objid};
2005 my $tag = $tw->{Tag};
2007 open TO, '>', $tfn->('.tmp') or die $!;
2008 print TO <<END or die $!;
2014 $package release $cversion for $clogsuite ($csuite) [dgit]
2015 [dgit distro=$declaredistro$delibs]
2017 foreach my $ref (sort keys %previously) {
2018 print TO <<END or die $!;
2019 [dgit previously:$ref=$previously{$ref}]
2025 my $tagobjfn = $tfn->('.tmp');
2027 if (!defined $keyid) {
2028 $keyid = access_cfg('keyid','RETURN-UNDEF');
2030 if (!defined $keyid) {
2031 $keyid = getfield $clogp, 'Maintainer';
2033 unlink $tfn->('.tmp.asc') or $!==&ENOENT or die $!;
2034 my @sign_cmd = (@gpg, qw(--detach-sign --armor));
2035 push @sign_cmd, qw(-u),$keyid if defined $keyid;
2036 push @sign_cmd, $tfn->('.tmp');
2037 runcmd_ordryrun @sign_cmd;
2039 $tagobjfn = $tfn->('.signed.tmp');
2040 runcmd shell_cmd "exec >$tagobjfn", qw(cat --),
2041 $tfn->('.tmp'), $tfn->('.tmp.asc');
2047 my @r = map { $mktag->($_); } @$tagwants;
2051 sub sign_changes ($) {
2052 my ($changesfile) = @_;
2054 my @debsign_cmd = @debsign;
2055 push @debsign_cmd, "-k$keyid" if defined $keyid;
2056 push @debsign_cmd, "-p$gpg[0]" if $gpg[0] ne 'gpg';
2057 push @debsign_cmd, $changesfile;
2058 runcmd_ordryrun @debsign_cmd;
2063 my ($forceflag) = @_;
2064 printdebug "actually entering push\n";
2065 supplementary_message(<<'END');
2066 Push failed, while preparing your push.
2067 You can retry the push, after fixing the problem, if you like.
2071 access_giturl(); # check that success is vaguely likely
2074 my $clogpfn = ".git/dgit/changelog.822.tmp";
2075 runcmd shell_cmd "exec >$clogpfn", qw(dpkg-parsechangelog);
2077 responder_send_file('parsed-changelog', $clogpfn);
2079 my ($clogp, $cversion, $dscfn) =
2080 push_parse_changelog("$clogpfn");
2082 my $dscpath = "$buildproductsdir/$dscfn";
2083 stat_exists $dscpath or
2084 fail "looked for .dsc $dscfn, but $!;".
2085 " maybe you forgot to build";
2087 responder_send_file('dsc', $dscpath);
2089 push_parse_dsc($dscpath, $dscfn, $cversion);
2091 my $format = getfield $dsc, 'Format';
2092 printdebug "format $format\n";
2094 my $head = git_rev_parse('HEAD');
2096 if (madformat($format)) {
2097 # user might have not used dgit build, so maybe do this now:
2098 if (quiltmode_splitbrain()) {
2099 my $upstreamversion = $clogp->{Version};
2100 $upstreamversion =~ s/-[^-]*$//;
2102 quilt_make_fake_dsc($upstreamversion);
2103 my ($dgitview, $cachekey) =
2104 quilt_check_splitbrain_cache($head, $upstreamversion);
2106 "--quilt=$quilt_mode but no cached dgit view:
2107 perhaps tree changed since dgit build[-source] ?";
2109 changedir '../../../..';
2110 prep_ud(); # so _only_subdir() works, below
2112 commit_quilty_patch();
2116 die 'xxx fast forward (should not depend on quilt mode, but will always be needed if we did $split_brain)' if $split_brain;
2120 progress "checking that $dscfn corresponds to HEAD";
2121 runcmd qw(dpkg-source -x --),
2122 $dscpath =~ m#^/# ? $dscpath : "../../../$dscpath";
2123 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
2124 check_for_vendor_patches() if madformat($dsc->{format});
2125 changedir '../../../..';
2126 my $diffopt = $debuglevel>0 ? '--exit-code' : '--quiet';
2127 my @diffcmd = (@git, qw(diff), $diffopt, $tree);
2128 debugcmd "+",@diffcmd;
2130 my $r = system @diffcmd;
2133 fail "$dscfn specifies a different tree to your HEAD commit;".
2134 " perhaps you forgot to build".
2135 ($diffopt eq '--exit-code' ? "" :
2136 " (run with -D to see full diff output)");
2141 if (!$changesfile) {
2142 my $pat = changespat $cversion;
2143 my @cs = glob "$buildproductsdir/$pat";
2144 fail "failed to find unique changes file".
2145 " (looked for $pat in $buildproductsdir);".
2146 " perhaps you need to use dgit -C"
2148 ($changesfile) = @cs;
2150 $changesfile = "$buildproductsdir/$changesfile";
2153 responder_send_file('changes',$changesfile);
2154 responder_send_command("param head $head");
2155 responder_send_command("param csuite $csuite");
2156 responder_send_command("param tagformat $tagformat");
2158 if (deliberately_not_fast_forward) {
2159 git_for_each_ref(lrfetchrefs, sub {
2160 my ($objid,$objtype,$lrfetchrefname,$reftail) = @_;
2161 my $rrefname= substr($lrfetchrefname, length(lrfetchrefs) + 1);
2162 responder_send_command("previously $rrefname=$objid");
2163 $previously{$rrefname} = $objid;
2167 my @tagwants = push_tagwants($cversion, $head,
2171 supplementary_message(<<'END');
2172 Push failed, while signing the tag.
2173 You can retry the push, after fixing the problem, if you like.
2175 # If we manage to sign but fail to record it anywhere, it's fine.
2176 if ($we_are_responder) {
2177 @tagobjfns = map { $_->{Tfn}('.signed-tmp') } @tagwants;
2178 responder_receive_files('signed-tag', @tagobjfns);
2180 @tagobjfns = push_mktags($clogp,$dscpath,
2181 $changesfile,$changesfile,
2184 supplementary_message(<<'END');
2185 Push failed, *after* signing the tag.
2186 If you want to try again, you should use a new version number.
2189 pairwise { $a->{TagObjFn} = $b } @tagwants, @tagobjfns;
2191 foreach my $tw (@tagwants) {
2192 my $tag = $tw->{Tag};
2193 my $tagobjfn = $tw->{TagObjFn};
2195 cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
2196 runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
2197 runcmd_ordryrun_local
2198 @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
2201 supplementary_message(<<'END');
2202 Push failed, while updating the remote git repository - see messages above.
2203 If you want to try again, you should use a new version number.
2205 if (!check_for_git()) {
2206 create_remote_git_repo();
2209 my @pushrefs = $forceflag."HEAD:".rrref();
2210 foreach my $tw (@tagwants) {
2211 push @pushrefs, $forceflag."refs/tags/$tw->{Tag}";
2214 runcmd_ordryrun @git, qw(push),access_giturl(), @pushrefs;
2215 runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), 'HEAD';
2217 supplementary_message(<<'END');
2218 Push failed, after updating the remote git repository.
2219 If you want to try again, you must use a new version number.
2221 if ($we_are_responder) {
2222 my $dryrunsuffix = act_local() ? "" : ".tmp";
2223 responder_receive_files('signed-dsc-changes',
2224 "$dscpath$dryrunsuffix",
2225 "$changesfile$dryrunsuffix");
2228 rename "$dscpath.tmp",$dscpath or die "$dscfn $!";
2230 progress "[new .dsc left in $dscpath.tmp]";
2232 sign_changes $changesfile;
2235 supplementary_message(<<END);
2236 Push failed, while uploading package(s) to the archive server.
2237 You can retry the upload of exactly these same files with dput of:
2239 If that .changes file is broken, you will need to use a new version
2240 number for your next attempt at the upload.
2242 my $host = access_cfg('upload-host','RETURN-UNDEF');
2243 my @hostarg = defined($host) ? ($host,) : ();
2244 runcmd_ordryrun @dput, @hostarg, $changesfile;
2245 printdone "pushed and uploaded $cversion";
2247 supplementary_message('');
2248 responder_send_command("complete");
2255 badusage "-p is not allowed with clone; specify as argument instead"
2256 if defined $package;
2259 } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
2260 ($package,$isuite) = @ARGV;
2261 } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
2262 ($package,$dstdir) = @ARGV;
2263 } elsif (@ARGV==3) {
2264 ($package,$isuite,$dstdir) = @ARGV;
2266 badusage "incorrect arguments to dgit clone";
2268 $dstdir ||= "$package";
2270 if (stat_exists $dstdir) {
2271 fail "$dstdir already exists";
2275 if ($rmonerror && !$dryrun_level) {
2276 $cwd_remove= getcwd();
2278 return unless defined $cwd_remove;
2279 if (!chdir "$cwd_remove") {
2280 return if $!==&ENOENT;
2281 die "chdir $cwd_remove: $!";
2284 rmtree($dstdir) or die "remove $dstdir: $!\n";
2285 } elsif (!grep { $! == $_ }
2286 (ENOENT, ENOTDIR, EACCES, EPERM, ELOOP)) {
2288 print STDERR "check whether to remove $dstdir: $!\n";
2294 $cwd_remove = undef;
2297 sub branchsuite () {
2298 my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
2299 if ($branch =~ m#$lbranch_re#o) {
2306 sub fetchpullargs () {
2308 if (!defined $package) {
2309 my $sourcep = parsecontrol('debian/control','debian/control');
2310 $package = getfield $sourcep, 'Source';
2313 # $isuite = branchsuite(); # this doesn't work because dak hates canons
2315 my $clogp = parsechangelog();
2316 $isuite = getfield $clogp, 'Distribution';
2318 canonicalise_suite();
2319 progress "fetching from suite $csuite";
2320 } elsif (@ARGV==1) {
2322 canonicalise_suite();
2324 badusage "incorrect arguments to dgit fetch or dgit pull";
2343 badusage "-p is not allowed with dgit push" if defined $package;
2345 my $clogp = parsechangelog();
2346 $package = getfield $clogp, 'Source';
2349 } elsif (@ARGV==1) {
2350 ($specsuite) = (@ARGV);
2352 badusage "incorrect arguments to dgit push";
2354 $isuite = getfield $clogp, 'Distribution';
2356 local ($package) = $existing_package; # this is a hack
2357 canonicalise_suite();
2359 canonicalise_suite();
2361 if (defined $specsuite &&
2362 $specsuite ne $isuite &&
2363 $specsuite ne $csuite) {
2364 fail "dgit push: changelog specifies $isuite ($csuite)".
2365 " but command line specifies $specsuite";
2367 supplementary_message(<<'END');
2368 Push failed, while checking state of the archive.
2369 You can retry the push, after fixing the problem, if you like.
2371 if (check_for_git()) {
2375 if (fetch_from_archive()) {
2376 if (is_fast_fwd(lrref(), 'HEAD')) {
2378 } elsif (deliberately_not_fast_forward) {
2381 fail "dgit push: HEAD is not a descendant".
2382 " of the archive's version.\n".
2383 "dgit: To overwrite its contents,".
2384 " use git merge -s ours ".lrref().".\n".
2385 "dgit: To rewind history, if permitted by the archive,".
2386 " use --deliberately-not-fast-forward";
2390 fail "package appears to be new in this suite;".
2391 " if this is intentional, use --new";
2396 #---------- remote commands' implementation ----------
2398 sub cmd_remote_push_build_host {
2399 my ($nrargs) = shift @ARGV;
2400 my (@rargs) = @ARGV[0..$nrargs-1];
2401 @ARGV = @ARGV[$nrargs..$#ARGV];
2403 my ($dir,$vsnwant) = @rargs;
2404 # vsnwant is a comma-separated list; we report which we have
2405 # chosen in our ready response (so other end can tell if they
2408 $we_are_responder = 1;
2409 $us .= " (build host)";
2413 open PI, "<&STDIN" or die $!;
2414 open STDIN, "/dev/null" or die $!;
2415 open PO, ">&STDOUT" or die $!;
2417 open STDOUT, ">&STDERR" or die $!;
2421 ($protovsn) = grep {
2422 $vsnwant =~ m{^(?:.*,)?$_(?:,.*)?$}
2423 } @rpushprotovsn_support;
2425 fail "build host has dgit rpush protocol versions ".
2426 (join ",", @rpushprotovsn_support).
2427 " but invocation host has $vsnwant"
2428 unless defined $protovsn;
2430 responder_send_command("dgit-remote-push-ready $protovsn");
2431 rpush_handle_protovsn_bothends();
2436 sub cmd_remote_push_responder { cmd_remote_push_build_host(); }
2437 # ... for compatibility with proto vsn.1 dgit (just so that user gets
2438 # a good error message)
2440 sub rpush_handle_protovsn_bothends () {
2441 if ($protovsn < 4) {
2442 need_tagformat 'old', "rpush negotiated protocol $protovsn";
2451 my $report = i_child_report();
2452 if (defined $report) {
2453 printdebug "($report)\n";
2454 } elsif ($i_child_pid) {
2455 printdebug "(killing build host child $i_child_pid)\n";
2456 kill 15, $i_child_pid;
2458 if (defined $i_tmp && !defined $initiator_tempdir) {
2460 eval { rmtree $i_tmp; };
2464 END { i_cleanup(); }
2467 my ($base,$selector,@args) = @_;
2468 $selector =~ s/\-/_/g;
2469 { no strict qw(refs); &{"${base}_${selector}"}(@args); }
2476 if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
2484 push @rargs, join ",", @rpushprotovsn_support;
2487 push @rdgit, @ropts;
2488 push @rdgit, qw(remote-push-build-host), (scalar @rargs), @rargs;
2490 my @cmd = (@ssh, $host, shellquote @rdgit);
2493 if (defined $initiator_tempdir) {
2494 rmtree $initiator_tempdir;
2495 mkdir $initiator_tempdir, 0700 or die "$initiator_tempdir: $!";
2496 $i_tmp = $initiator_tempdir;
2500 $i_child_pid = open2(\*RO, \*RI, @cmd);
2502 ($protovsn) = initiator_expect { m/^dgit-remote-push-ready (\S+)/ };
2503 die "$protovsn ?" unless grep { $_ eq $protovsn } @rpushprotovsn_support;
2504 $supplementary_message = '' unless $protovsn >= 3;
2505 rpush_handle_protovsn_bothends();
2507 my ($icmd,$iargs) = initiator_expect {
2508 m/^(\S+)(?: (.*))?$/;
2511 i_method "i_resp", $icmd, $iargs;
2515 sub i_resp_progress ($) {
2517 my $msg = protocol_read_bytes \*RO, $rhs;
2521 sub i_resp_supplementary_message ($) {
2523 $supplementary_message = protocol_read_bytes \*RO, $rhs;
2526 sub i_resp_complete {
2527 my $pid = $i_child_pid;
2528 $i_child_pid = undef; # prevents killing some other process with same pid
2529 printdebug "waiting for build host child $pid...\n";
2530 my $got = waitpid $pid, 0;
2531 die $! unless $got == $pid;
2532 die "build host child failed $?" if $?;
2535 printdebug "all done\n";
2539 sub i_resp_file ($) {
2541 my $localname = i_method "i_localname", $keyword;
2542 my $localpath = "$i_tmp/$localname";
2543 stat_exists $localpath and
2544 badproto \*RO, "file $keyword ($localpath) twice";
2545 protocol_receive_file \*RO, $localpath;
2546 i_method "i_file", $keyword;
2551 sub i_resp_param ($) {
2552 $_[0] =~ m/^(\S+) (.*)$/ or badproto \*RO, "bad param spec";
2556 sub i_resp_previously ($) {
2557 $_[0] =~ m#^(refs/tags/\S+)=(\w+)$#
2558 or badproto \*RO, "bad previously spec";
2559 my $r = system qw(git check-ref-format), $1;
2560 die "bad previously ref spec ($r)" if $r;
2561 $previously{$1} = $2;
2566 sub i_resp_want ($) {
2568 die "$keyword ?" if $i_wanted{$keyword}++;
2569 my @localpaths = i_method "i_want", $keyword;
2570 printdebug "[[ $keyword @localpaths\n";
2571 foreach my $localpath (@localpaths) {
2572 protocol_send_file \*RI, $localpath;
2574 print RI "files-end\n" or die $!;
2577 our ($i_clogp, $i_version, $i_dscfn, $i_changesfn);
2579 sub i_localname_parsed_changelog {
2580 return "remote-changelog.822";
2582 sub i_file_parsed_changelog {
2583 ($i_clogp, $i_version, $i_dscfn) =
2584 push_parse_changelog "$i_tmp/remote-changelog.822";
2585 die if $i_dscfn =~ m#/|^\W#;
2588 sub i_localname_dsc {
2589 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
2594 sub i_localname_changes {
2595 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
2596 $i_changesfn = $i_dscfn;
2597 $i_changesfn =~ s/\.dsc$/_dgit.changes/ or die;
2598 return $i_changesfn;
2600 sub i_file_changes { }
2602 sub i_want_signed_tag {
2603 printdebug Dumper(\%i_param, $i_dscfn);
2604 defined $i_param{'head'} && defined $i_dscfn && defined $i_clogp
2605 && defined $i_param{'csuite'}
2606 or badproto \*RO, "premature desire for signed-tag";
2607 my $head = $i_param{'head'};
2608 die if $head =~ m/[^0-9a-f]/ || $head !~ m/^../;
2611 if ($protovsn >= 4) {
2612 my $p = $i_param{'tagformat'} // '<undef>';
2614 or badproto \*RO, "tag format mismatch: $p vs. $tagformat";
2617 die unless $i_param{'csuite'} =~ m/^$suite_re$/;
2619 push_parse_dsc $i_dscfn, 'remote dsc', $i_version;
2621 my @tagwants = push_tagwants $i_version, $head, "tag";
2624 push_mktags $i_clogp, $i_dscfn,
2625 $i_changesfn, 'remote changes',
2629 sub i_want_signed_dsc_changes {
2630 rename "$i_dscfn.tmp","$i_dscfn" or die "$i_dscfn $!";
2631 sign_changes $i_changesfn;
2632 return ($i_dscfn, $i_changesfn);
2635 #---------- building etc. ----------
2641 #----- `3.0 (quilt)' handling -----
2643 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
2645 sub quiltify_dpkg_commit ($$$;$) {
2646 my ($patchname,$author,$msg, $xinfo) = @_;
2650 my $descfn = ".git/dgit/quilt-description.tmp";
2651 open O, '>', $descfn or die "$descfn: $!";
2654 $msg =~ s/^\s+$/ ./mg;
2655 print O <<END or die $!;
2665 local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
2666 local $ENV{'VISUAL'} = $ENV{'EDITOR'};
2667 local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
2668 runcmd @dpkgsource, qw(--commit .), $patchname;
2672 sub quiltify_trees_differ ($$;$$) {
2673 my ($x,$y,$finegrained,$ignorenamesr) = @_;
2674 # returns true iff the two tree objects differ other than in debian/
2675 # with $finegrained,
2676 # returns bitmask 01 - differ in upstream files except .gitignore
2677 # 02 - differ in .gitignore
2678 # if $ignorenamesr is defined, $ingorenamesr->{$fn}
2679 # is set for each modified .gitignore filename $fn
2681 my @cmd = (@git, qw(diff-tree --name-only -z));
2682 push @cmd, qw(-r) if $finegrained;
2684 my $diffs= cmdoutput @cmd;
2686 foreach my $f (split /\0/, $diffs) {
2687 next if $f =~ m#^debian(?:/.*)?$#s;
2688 my $isignore = $f =~ m#^(?:.*/)?.gitignore$#s;
2689 $r |= $isignore ? 02 : 01;
2690 $ignorenamesr->{$f}=1 if $ignorenamesr && $isignore;
2692 printdebug "quiltify_trees_differ $x $y => $r\n";
2696 sub quiltify_tree_sentinelfiles ($) {
2697 # lists the `sentinel' files present in the tree
2699 my $r = cmdoutput @git, qw(ls-tree --name-only), $x,
2700 qw(-- debian/rules debian/control);
2705 sub quiltify_splitbrain_needed () {
2706 if (!$split_brain) {
2707 progress "dgit view: changes are required...";
2708 runcmd @git, qw(checkout -q -b dgit-view);
2713 sub quiltify_splitbrain ($$$$$$) {
2714 my ($clogp, $unapplied, $headref, $diffbits,
2715 $editedignores, $cachekey) = @_;
2716 if ($quilt_mode !~ m/gbp|dpm/) {
2717 # treat .gitignore just like any other upstream file
2718 $diffbits = { %$diffbits };
2719 $_ = !!$_ foreach values %$diffbits;
2721 # We would like any commits we generate to be reproducible
2722 my @authline = clogp_authline($clogp);
2723 local $ENV{GIT_COMMITTER_NAME} = $authline[0];
2724 local $ENV{GIT_COMMITTER_EMAIL} = $authline[1];
2725 local $ENV{GIT_COMMITTER_DATE} = $authline[2];
2727 if ($quilt_mode =~ m/gbp|unapplied/ &&
2728 ($diffbits->{H2O} & 01)) {
2730 "--quilt=$quilt_mode specified, implying patches-unapplied git tree\n".
2731 " but git tree differs from orig in upstream files.";
2732 if (!stat_exists "debian/patches") {
2734 "\n ... debian/patches is missing; perhaps this is a patch queue branch?";
2738 if ($quilt_mode =~ m/gbp|unapplied/ &&
2739 ($diffbits->{O2A} & 01)) { # some patches
2740 quiltify_splitbrain_needed();
2741 progress "dgit view: creating patches-applied version using gbp pq";
2742 runcmd shell_cmd 'exec >/dev/null', @gbp, qw(pq import);
2743 # gbp pq import creates a fresh branch; push back to dgit-view
2744 runcmd @git, qw(update-ref refs/heads/dgit-view HEAD);
2745 runcmd @git, qw(checkout -q dgit-view);
2747 if (($diffbits->{H2O} & 02) && # user has modified .gitignore
2748 !($diffbits->{O2A} & 02)) { # patches do not change .gitignore
2749 quiltify_splitbrain_needed();
2750 progress "dgit view: creating patch to represent .gitignore changes";
2751 ensuredir "debian/patches";
2752 my $gipatch = "debian/patches/auto-gitignore";
2753 open GIPATCH, ">>", "$gipatch" or die "$gipatch: $!";
2754 stat GIPATCH or die "$gipatch: $!";
2755 fail "$gipatch already exists; but want to create it".
2756 " to record .gitignore changes" if (stat _)[7];
2757 print GIPATCH <<END or die "$gipatch: $!";
2758 Subject: Update .gitignore from Debian packaging branch
2760 The Debian packaging git branch contains these updates to the upstream
2761 .gitignore file(s). This patch is autogenerated, to provide these
2762 updates to users of the official Debian archive view of the package.
2764 [dgit version $our_version]
2767 close GIPATCH or die "$gipatch: $!";
2768 runcmd shell_cmd "exec >>$gipatch", @git, qw(diff),
2769 $unapplied, $headref, "--", sort keys %$editedignores;
2770 open SERIES, "+>>", "debian/patches/series" or die $!;
2771 defined seek SERIES, -1, 2 or $!==EINVAL or die $!;
2773 defined read SERIES, $newline, 1 or die $!;
2774 print SERIES "\n" or die $! unless $newline eq "\n";
2775 print SERIES "auto-gitignore\n" or die $!;
2776 close SERIES or die $!;
2777 runcmd @git, qw(add -- debian/patches/series), $gipatch;
2778 commit_admin "Commit patch to update .gitignore";
2781 my $dgitview = git_rev_parse 'refs/heads/dgit-view';
2783 changedir '../../../..';
2784 ensuredir ".git/logs/refs/dgit-intern";
2785 my $makelogfh = new IO::File ".git/logs/refs/$splitbraincache", '>>'
2787 runcmd @git, qw(update-ref -m), $cachekey, "refs/$splitbraincache",
2790 progress "dgit view: created (commit id $dgitview)";
2792 changedir '.git/dgit/unpack/work';
2795 sub quiltify ($$$$) {
2796 my ($clogp,$target,$oldtiptree,$failsuggestion) = @_;
2798 # Quilt patchification algorithm
2800 # We search backwards through the history of the main tree's HEAD
2801 # (T) looking for a start commit S whose tree object is identical
2802 # to to the patch tip tree (ie the tree corresponding to the
2803 # current dpkg-committed patch series). For these purposes
2804 # `identical' disregards anything in debian/ - this wrinkle is
2805 # necessary because dpkg-source treates debian/ specially.
2807 # We can only traverse edges where at most one of the ancestors'
2808 # trees differs (in changes outside in debian/). And we cannot
2809 # handle edges which change .pc/ or debian/patches. To avoid
2810 # going down a rathole we avoid traversing edges which introduce
2811 # debian/rules or debian/control. And we set a limit on the
2812 # number of edges we are willing to look at.
2814 # If we succeed, we walk forwards again. For each traversed edge
2815 # PC (with P parent, C child) (starting with P=S and ending with
2816 # C=T) to we do this:
2818 # - dpkg-source --commit with a patch name and message derived from C
2819 # After traversing PT, we git commit the changes which
2820 # should be contained within debian/patches.
2822 # The search for the path S..T is breadth-first. We maintain a
2823 # todo list containing search nodes. A search node identifies a
2824 # commit, and looks something like this:
2826 # Commit => $git_commit_id,
2827 # Child => $c, # or undef if P=T
2828 # Whynot => $reason_edge_PC_unsuitable, # in @nots only
2829 # Nontrivial => true iff $p..$c has relevant changes
2836 my %considered; # saves being exponential on some weird graphs
2838 my $t_sentinels = quiltify_tree_sentinelfiles $target;
2841 my ($search,$whynot) = @_;
2842 printdebug " search NOT $search->{Commit} $whynot\n";
2843 $search->{Whynot} = $whynot;
2844 push @nots, $search;
2845 no warnings qw(exiting);
2854 my $c = shift @todo;
2855 next if $considered{$c->{Commit}}++;
2857 $not->($c, "maximum search space exceeded") if --$max_work <= 0;
2859 printdebug "quiltify investigate $c->{Commit}\n";
2862 if (!quiltify_trees_differ $c->{Commit}, $oldtiptree) {
2863 printdebug " search finished hooray!\n";
2868 if ($quilt_mode eq 'nofix') {
2869 fail "quilt fixup required but quilt mode is \`nofix'\n".
2870 "HEAD commit $c->{Commit} differs from tree implied by ".
2871 " debian/patches (tree object $oldtiptree)";
2873 if ($quilt_mode eq 'smash') {
2874 printdebug " search quitting smash\n";
2878 my $c_sentinels = quiltify_tree_sentinelfiles $c->{Commit};
2879 $not->($c, "has $c_sentinels not $t_sentinels")
2880 if $c_sentinels ne $t_sentinels;
2882 my $commitdata = cmdoutput @git, qw(cat-file commit), $c->{Commit};
2883 $commitdata =~ m/\n\n/;
2885 my @parents = ($commitdata =~ m/^parent (\w+)$/gm);
2886 @parents = map { { Commit => $_, Child => $c } } @parents;
2888 $not->($c, "root commit") if !@parents;
2890 foreach my $p (@parents) {
2891 $p->{Nontrivial}= quiltify_trees_differ $p->{Commit},$c->{Commit};
2893 my $ndiffers = grep { $_->{Nontrivial} } @parents;
2894 $not->($c, "merge ($ndiffers nontrivial parents)") if $ndiffers > 1;
2896 foreach my $p (@parents) {
2897 printdebug "considering C=$c->{Commit} P=$p->{Commit}\n";
2899 my @cmd= (@git, qw(diff-tree -r --name-only),
2900 $p->{Commit},$c->{Commit}, qw(-- debian/patches .pc));
2901 my $patchstackchange = cmdoutput @cmd;
2902 if (length $patchstackchange) {
2903 $patchstackchange =~ s/\n/,/g;
2904 $not->($p, "changed $patchstackchange");
2907 printdebug " search queue P=$p->{Commit} ",
2908 ($p->{Nontrivial} ? "NT" : "triv"),"\n";
2914 printdebug "quiltify want to smash\n";
2917 my $x = $_[0]{Commit};
2918 $x =~ s/(.*?[0-9a-z]{8})[0-9a-z]*$/$1/;
2921 my $reportnot = sub {
2923 my $s = $abbrev->($notp);
2924 my $c = $notp->{Child};
2925 $s .= "..".$abbrev->($c) if $c;
2926 $s .= ": ".$notp->{Whynot};
2929 if ($quilt_mode eq 'linear') {
2930 print STDERR "$us: quilt fixup cannot be linear. Stopped at:\n";
2931 foreach my $notp (@nots) {
2932 print STDERR "$us: ", $reportnot->($notp), "\n";
2934 print STDERR "$us: $_\n" foreach @$failsuggestion;
2935 fail "quilt fixup naive history linearisation failed.\n".
2936 "Use dpkg-source --commit by hand; or, --quilt=smash for one ugly patch";
2937 } elsif ($quilt_mode eq 'smash') {
2938 } elsif ($quilt_mode eq 'auto') {
2939 progress "quilt fixup cannot be linear, smashing...";
2941 die "$quilt_mode ?";
2944 my $time = $ENV{'GIT_COMMITTER_DATE'} || time;
2945 $time =~ s/\s.*//; # trim timezone from GIT_COMMITTER_DATE
2947 my $msg = cmdoutput @git, qw(log), "-n$ncommits";
2949 quiltify_dpkg_commit "auto-$version-$target-$time",
2950 (getfield $clogp, 'Maintainer'),
2951 "Automatically generated patch ($clogp->{Version})\n".
2952 "Last (up to) $ncommits git changes, FYI:\n\n". $msg;
2956 progress "quiltify linearisation planning successful, executing...";
2958 for (my $p = $sref_S;
2959 my $c = $p->{Child};
2961 printdebug "quiltify traverse $p->{Commit}..$c->{Commit}\n";
2962 next unless $p->{Nontrivial};
2964 my $cc = $c->{Commit};
2966 my $commitdata = cmdoutput @git, qw(cat-file commit), $cc;
2967 $commitdata =~ m/\n\n/ or die "$c ?";
2970 $commitdata =~ m/^author (.*) \d+ [-+0-9]+$/m or die "$cc ?";
2973 $msg =~ s/^(.*)\n*/$1\n/ or die "$cc $msg ?";
2976 my $patchname = $title;
2977 $patchname =~ s/[.:]$//;
2978 $patchname =~ y/ A-Z/-a-z/;
2979 $patchname =~ y/-a-z0-9_.+=~//cd;
2980 $patchname =~ s/^\W/x-$&/;
2981 $patchname = substr($patchname,0,40);
2984 stat "debian/patches/$patchname$index";
2986 $!==ENOENT or die "$patchname$index $!";
2988 runcmd @git, qw(checkout -q), $cc;
2990 # We use the tip's changelog so that dpkg-source doesn't
2991 # produce complaining messages from dpkg-parsechangelog. None
2992 # of the information dpkg-source gets from the changelog is
2993 # actually relevant - it gets put into the original message
2994 # which dpkg-source provides our stunt editor, and then
2996 runcmd @git, qw(checkout -q), $target, qw(debian/changelog);
2998 quiltify_dpkg_commit "$patchname$index", $author, $msg,
2999 "X-Dgit-Generated: $clogp->{Version} $cc\n";
3001 runcmd @git, qw(checkout -q), $cc, qw(debian/changelog);
3004 runcmd @git, qw(checkout -q master);
3007 sub build_maybe_quilt_fixup () {
3008 my ($format,$fopts) = get_source_format;
3009 return unless madformat $format;
3012 check_for_vendor_patches();
3014 my $clogp = parsechangelog();
3015 my $headref = git_rev_parse('HEAD');
3020 my $upstreamversion=$version;
3021 $upstreamversion =~ s/-[^-]*$//;
3023 if ($fopts->{'single-debian-patch'}) {
3024 quilt_fixup_singlepatch($clogp, $headref, $upstreamversion);
3026 quilt_fixup_multipatch($clogp, $headref, $upstreamversion);
3029 die 'bug' if $split_brain && !$need_split_build_invocation;
3031 changedir '../../../..';
3032 runcmd_ordryrun_local
3033 @git, qw(pull --ff-only -q .git/dgit/unpack/work master);
3036 sub quilt_fixup_mkwork ($) {
3039 mkdir "work" or die $!;
3041 mktree_in_ud_here();
3042 runcmd @git, qw(reset -q --hard), $headref;
3045 sub quilt_fixup_linkorigs ($$) {
3046 my ($upstreamversion, $fn) = @_;
3047 # calls $fn->($leafname);
3049 foreach my $f (<../../../../*>) { #/){
3050 my $b=$f; $b =~ s{.*/}{};
3052 local ($debuglevel) = $debuglevel-1;
3053 printdebug "QF linkorigs $b, $f ?\n";
3055 next unless is_orig_file $b, srcfn $upstreamversion,'';
3056 printdebug "QF linkorigs $b, $f Y\n";
3057 link_ltarget $f, $b or die "$b $!";
3062 sub quilt_fixup_delete_pc () {
3063 runcmd @git, qw(rm -rqf .pc);
3064 commit_admin "Commit removal of .pc (quilt series tracking data)";
3067 sub quilt_fixup_singlepatch ($$$) {
3068 my ($clogp, $headref, $upstreamversion) = @_;
3070 progress "starting quiltify (single-debian-patch)";
3072 # dpkg-source --commit generates new patches even if
3073 # single-debian-patch is in debian/source/options. In order to
3074 # get it to generate debian/patches/debian-changes, it is
3075 # necessary to build the source package.
3077 quilt_fixup_linkorigs($upstreamversion, sub { });
3078 quilt_fixup_mkwork($headref);
3080 rmtree("debian/patches");
3082 runcmd @dpkgsource, qw(-b .);
3084 runcmd @dpkgsource, qw(-x), (srcfn $version, ".dsc");
3085 rename srcfn("$upstreamversion", "/debian/patches"),
3086 "work/debian/patches";
3089 commit_quilty_patch();
3092 sub quilt_make_fake_dsc ($) {
3093 my ($upstreamversion) = @_;
3095 my $fakeversion="$upstreamversion-~~DGITFAKE";
3097 my $fakedsc=new IO::File 'fake.dsc', '>' or die $!;
3098 print $fakedsc <<END or die $!;
3101 Version: $fakeversion
3105 my $dscaddfile=sub {
3108 my $md = new Digest::MD5;
3110 my $fh = new IO::File $b, '<' or die "$b $!";
3115 print $fakedsc " ".$md->hexdigest." $size $b\n" or die $!;
3118 quilt_fixup_linkorigs($upstreamversion, $dscaddfile);
3120 my @files=qw(debian/source/format debian/rules
3121 debian/control debian/changelog);
3122 foreach my $maybe (qw(debian/patches debian/source/options
3123 debian/tests/control)) {
3124 next unless stat_exists "../../../$maybe";
3125 push @files, $maybe;
3128 my $debtar= srcfn $fakeversion,'.debian.tar.gz';
3129 runcmd qw(env GZIP=-1n tar -zcf), "./$debtar", qw(-C ../../..), @files;
3131 $dscaddfile->($debtar);
3132 close $fakedsc or die $!;
3135 sub quilt_check_splitbrain_cache ($$) {
3136 my ($headref, $upstreamversion) = @_;
3137 # Called only if we are in (potentially) split brain mode.
3139 # Computes the cache key and looks in the cache.
3140 # Returns ($dgit_view_commitid, $cachekey) or (undef, $cachekey)
3142 my $splitbrain_cachekey;
3145 "dgit: split brain (separate dgit view) may be needed (--quilt=$quilt_mode).";
3146 # we look in the reflog of dgit-intern/quilt-cache
3147 # we look for an entry whose message is the key for the cache lookup
3148 my @cachekey = (qw(dgit), $our_version);
3149 push @cachekey, $upstreamversion;
3150 push @cachekey, $quilt_mode;
3151 push @cachekey, $headref;
3153 push @cachekey, hashfile('fake.dsc');
3155 my $srcshash = Digest::SHA->new(256);
3156 my %sfs = ( %INC, '$0(dgit)' => $0 );
3157 foreach my $sfk (sort keys %sfs) {
3158 next unless m/^\$0\b/ || m{^Debian/Dgit\b};
3159 $srcshash->add($sfk," ");
3160 $srcshash->add(hashfile($sfs{$sfk}));
3161 $srcshash->add("\n");
3163 push @cachekey, $srcshash->hexdigest();
3164 $splitbrain_cachekey = "@cachekey";
3166 my @cmd = (@git, qw(reflog), '--pretty=format:%H %gs',
3168 printdebug "splitbrain cachekey $splitbrain_cachekey\n";
3169 debugcmd "|(probably)",@cmd;
3170 my $child = open GC, "-|"; defined $child or die $!;
3172 chdir '../../..' or die $!;
3173 if (!stat ".git/logs/refs/$splitbraincache") {
3174 $! == ENOENT or die $!;
3175 printdebug ">(no reflog)\n";
3182 printdebug ">| ", $_, "\n" if $debuglevel > 1;
3183 next unless m/^(\w+) (\S.*\S)$/ && $2 eq $splitbrain_cachekey;
3186 quilt_fixup_mkwork($headref);
3187 if ($cachehit ne $headref) {
3188 progress "dgit view: found cached (commit id $cachehit)";
3189 runcmd @git, qw(checkout -q -b dgit-view), $cachehit;
3191 return ($cachehit, $splitbrain_cachekey);
3193 progress "dgit view: found cached, no changes required";
3194 return ($headref, $splitbrain_cachekey);
3196 die $! if GC->error;
3197 failedcmd unless close GC;
3199 printdebug "splitbrain cache miss\n";
3200 return (undef, $splitbrain_cachekey);
3203 sub quilt_fixup_multipatch ($$$) {
3204 my ($clogp, $headref, $upstreamversion) = @_;
3206 progress "examining quilt state (multiple patches, $quilt_mode mode)";
3209 # - honour any existing .pc in case it has any strangeness
3210 # - determine the git commit corresponding to the tip of
3211 # the patch stack (if there is one)
3212 # - if there is such a git commit, convert each subsequent
3213 # git commit into a quilt patch with dpkg-source --commit
3214 # - otherwise convert all the differences in the tree into
3215 # a single git commit
3219 # Our git tree doesn't necessarily contain .pc. (Some versions of
3220 # dgit would include the .pc in the git tree.) If there isn't
3221 # one, we need to generate one by unpacking the patches that we
3224 # We first look for a .pc in the git tree. If there is one, we
3225 # will use it. (This is not the normal case.)
3227 # Otherwise need to regenerate .pc so that dpkg-source --commit
3228 # can work. We do this as follows:
3229 # 1. Collect all relevant .orig from parent directory
3230 # 2. Generate a debian.tar.gz out of
3231 # debian/{patches,rules,source/format,source/options}
3232 # 3. Generate a fake .dsc containing just these fields:
3233 # Format Source Version Files
3234 # 4. Extract the fake .dsc
3235 # Now the fake .dsc has a .pc directory.
3236 # (In fact we do this in every case, because in future we will
3237 # want to search for a good base commit for generating patches.)
3239 # Then we can actually do the dpkg-source --commit
3240 # 1. Make a new working tree with the same object
3241 # store as our main tree and check out the main
3243 # 2. Copy .pc from the fake's extraction, if necessary
3244 # 3. Run dpkg-source --commit
3245 # 4. If the result has changes to debian/, then
3246 # - git-add them them
3247 # - git-add .pc if we had a .pc in-tree
3249 # 5. If we had a .pc in-tree, delete it, and git-commit
3250 # 6. Back in the main tree, fast forward to the new HEAD
3252 # Another situation we may have to cope with is gbp-style
3253 # patches-unapplied trees.
3255 # We would want to detect these, so we know to escape into
3256 # quilt_fixup_gbp. However, this is in general not possible.
3257 # Consider a package with a one patch which the dgit user reverts
3258 # (with git-revert or the moral equivalent).
3260 # That is indistinguishable in contents from a patches-unapplied
3261 # tree. And looking at the history to distinguish them is not
3262 # useful because the user might have made a confusing-looking git
3263 # history structure (which ought to produce an error if dgit can't
3264 # cope, not a silent reintroduction of an unwanted patch).
3266 # So gbp users will have to pass an option. But we can usually
3267 # detect their failure to do so: if the tree is not a clean
3268 # patches-applied tree, quilt linearisation fails, but the tree
3269 # _is_ a clean patches-unapplied tree, we can suggest that maybe
3270 # they want --quilt=unapplied.
3272 # To help detect this, when we are extracting the fake dsc, we
3273 # first extract it with --skip-patches, and then apply the patches
3274 # afterwards with dpkg-source --before-build. That lets us save a
3275 # tree object corresponding to .origs.
3277 my $splitbrain_cachekey;
3279 quilt_make_fake_dsc($upstreamversion);
3281 if (quiltmode_splitbrain()) {
3283 ($cachehit, $splitbrain_cachekey) =
3284 quilt_check_splitbrain_cache($headref, $upstreamversion);
3285 return if $cachehit;
3289 'exec dpkg-source --no-check --skip-patches -x fake.dsc >/dev/null';
3291 my $fakexdir= $package.'-'.(stripepoch $upstreamversion);
3292 rename $fakexdir, "fake" or die "$fakexdir $!";
3296 remove_stray_gits();
3297 mktree_in_ud_here();
3301 runcmd @git, qw(add -Af .);
3302 my $unapplied=git_write_tree();
3303 printdebug "fake orig tree object $unapplied\n";
3308 'exec dpkg-source --before-build . >/dev/null';
3312 quilt_fixup_mkwork($headref);
3315 if (stat_exists ".pc") {
3317 progress "Tree already contains .pc - will use it then delete it.";
3320 rename '../fake/.pc','.pc' or die $!;
3323 changedir '../fake';
3325 runcmd @git, qw(add -Af .);
3326 my $oldtiptree=git_write_tree();
3327 printdebug "fake o+d/p tree object $unapplied\n";
3328 changedir '../work';
3331 # We calculate some guesswork now about what kind of tree this might
3332 # be. This is mostly for error reporting.
3337 # O = orig, without patches applied
3338 # A = "applied", ie orig with H's debian/patches applied
3339 H2O => quiltify_trees_differ($headref, $unapplied, 1,\%editedignores),
3340 H2A => quiltify_trees_differ($headref, $oldtiptree,1),
3341 O2A => quiltify_trees_differ($unapplied,$oldtiptree,1),
3345 foreach my $b (qw(01 02)) {
3346 foreach my $v (qw(H2O O2A H2A)) {
3347 push @dl, ($diffbits->{$v} & $b) ? '##' : '==';
3350 printdebug "differences \@dl @dl.\n";
3353 "$us: quilt differences: src: %s orig %s gitignores: %s orig %s\n".
3354 "$us: quilt differences: HEAD %s o+d/p HEAD %s o+d/p",
3355 $dl[0], $dl[1], $dl[3], $dl[4],
3359 if (!($diffbits->{H2O} & $diffbits->{O2A})) {
3360 push @failsuggestion, "This might be a patches-unapplied branch.";
3361 } elsif (!($diffbits->{H2A} & $diffbits->{O2A})) {
3362 push @failsuggestion, "This might be a patches-applied branch.";
3364 push @failsuggestion, "Maybe you need to specify one of".
3365 " --quilt=gbp --quilt=dpm --quilt=unapplied ?";
3367 if (quiltmode_splitbrain()) {
3368 quiltify_splitbrain($clogp, $unapplied, $headref,
3369 $diffbits, \%editedignores,
3370 $splitbrain_cachekey);
3374 progress "starting quiltify (multiple patches, $quilt_mode mode)";
3375 quiltify($clogp,$headref,$oldtiptree,\@failsuggestion);
3377 if (!open P, '>>', ".pc/applied-patches") {
3378 $!==&ENOENT or die $!;
3383 commit_quilty_patch();
3385 if ($mustdeletepc) {
3386 quilt_fixup_delete_pc();
3390 sub quilt_fixup_editor () {
3391 my $descfn = $ENV{$fakeeditorenv};
3392 my $editing = $ARGV[$#ARGV];
3393 open I1, '<', $descfn or die "$descfn: $!";
3394 open I2, '<', $editing or die "$editing: $!";
3395 unlink $editing or die "$editing: $!";
3396 open O, '>', $editing or die "$editing: $!";
3397 while (<I1>) { print O or die $!; } I1->error and die $!;
3400 $copying ||= m/^\-\-\- /;
3401 next unless $copying;
3404 I2->error and die $!;
3409 sub maybe_apply_patches_dirtily () {
3410 return unless $quilt_mode =~ m/gbp|unapplied/;
3411 print STDERR <<END or die $!;
3413 dgit: Building, or cleaning with rules target, in patches-unapplied tree.
3414 dgit: Have to apply the patches - making the tree dirty.
3415 dgit: (Consider specifying --clean=git and (or) using dgit sbuild.)
3418 $patches_applied_dirtily = 01;
3419 $patches_applied_dirtily |= 02 unless stat_exists '.pc';
3420 runcmd qw(dpkg-source --before-build .);
3423 sub maybe_unapply_patches_again () {
3424 progress "dgit: Unapplying patches again to tidy up the tree."
3425 if $patches_applied_dirtily;
3426 runcmd qw(dpkg-source --after-build .)
3427 if $patches_applied_dirtily & 01;
3429 if $patches_applied_dirtily & 02;
3432 #----- other building -----
3434 our $clean_using_builder;
3435 # ^ tree is to be cleaned by dpkg-source's builtin idea that it should
3436 # clean the tree before building (perhaps invoked indirectly by
3437 # whatever we are using to run the build), rather than separately
3438 # and explicitly by us.
3441 return if $clean_using_builder;
3442 if ($cleanmode eq 'dpkg-source') {
3443 maybe_apply_patches_dirtily();
3444 runcmd_ordryrun_local @dpkgbuildpackage, qw(-T clean);
3445 } elsif ($cleanmode eq 'dpkg-source-d') {
3446 maybe_apply_patches_dirtily();
3447 runcmd_ordryrun_local @dpkgbuildpackage, qw(-d -T clean);
3448 } elsif ($cleanmode eq 'git') {
3449 runcmd_ordryrun_local @git, qw(clean -xdf);
3450 } elsif ($cleanmode eq 'git-ff') {
3451 runcmd_ordryrun_local @git, qw(clean -xdff);
3452 } elsif ($cleanmode eq 'check') {
3453 my $leftovers = cmdoutput @git, qw(clean -xdn);
3454 if (length $leftovers) {
3455 print STDERR $leftovers, "\n" or die $!;
3456 fail "tree contains uncommitted files and --clean=check specified";
3458 } elsif ($cleanmode eq 'none') {
3465 badusage "clean takes no additional arguments" if @ARGV;
3468 maybe_unapply_patches_again();
3473 badusage "-p is not allowed when building" if defined $package;
3476 my $clogp = parsechangelog();
3477 $isuite = getfield $clogp, 'Distribution';
3478 $package = getfield $clogp, 'Source';
3479 $version = getfield $clogp, 'Version';
3480 build_maybe_quilt_fixup();
3482 my $pat = changespat $version;
3483 foreach my $f (glob "$buildproductsdir/$pat") {
3485 unlink $f or fail "remove old changes file $f: $!";
3487 progress "would remove $f";
3493 sub changesopts_initial () {
3494 my @opts =@changesopts[1..$#changesopts];
3497 sub changesopts_version () {
3498 if (!defined $changes_since_version) {
3499 my @vsns = archive_query('archive_query');
3500 my @quirk = access_quirk();
3501 if ($quirk[0] eq 'backports') {
3502 local $isuite = $quirk[2];
3504 canonicalise_suite();
3505 push @vsns, archive_query('archive_query');
3508 @vsns = map { $_->[0] } @vsns;
3509 @vsns = sort { -version_compare($a, $b) } @vsns;
3510 $changes_since_version = $vsns[0];
3511 progress "changelog will contain changes since $vsns[0]";
3513 $changes_since_version = '_';
3514 progress "package seems new, not specifying -v<version>";
3517 if ($changes_since_version ne '_') {
3518 return ("-v$changes_since_version");
3524 sub changesopts () {
3525 return (changesopts_initial(), changesopts_version());
3528 sub massage_dbp_args ($;$) {
3529 my ($cmd,$xargs) = @_;
3532 # - if we're going to split the source build out so we can
3533 # do strange things to it, massage the arguments to dpkg-buildpackage
3534 # so that the main build doessn't build source (or add an argument
3535 # to stop it building source by default).
3537 # - add -nc to stop dpkg-source cleaning the source tree,
3538 # unless we're not doing a split build and want dpkg-source
3539 # as cleanmode, in which case we can do nothing
3542 # 0 - source will NOT need to be built separately by caller
3543 # +1 - source will need to be built separately by caller
3544 # +2 - source will need to be built separately by caller AND
3545 # dpkg-buildpackage should not in fact be run at all!
3546 debugcmd '#massaging#', @$cmd if $debuglevel>1;
3547 #print STDERR "MASS0 ",Dumper($cmd, $xargs, $need_split_build_invocation);
3548 if ($cleanmode eq 'dpkg-source' && !$need_split_build_invocation) {
3549 $clean_using_builder = 1;
3552 # -nc has the side effect of specifying -b if nothing else specified
3553 # and some combinations of -S, -b, et al, are errors, rather than
3554 # later simply overriding earlie. So we need to:
3555 # - search the command line for these options
3556 # - pick the last one
3557 # - perhaps add our own as a default
3558 # - perhaps adjust it to the corresponding non-source-building version
3560 foreach my $l ($cmd, $xargs) {
3562 @$l = grep { !(m/^-[SgGFABb]$/s and $dmode=$_) } @$l;
3565 #print STDERR "MASS1 ",Dumper($cmd, $xargs, $dmode);
3567 if ($need_split_build_invocation) {
3568 printdebug "massage split $dmode.\n";
3569 $r = $dmode =~ m/[S]/ ? +2 :
3570 $dmode =~ y/gGF/ABb/ ? +1 :
3571 $dmode =~ m/[ABb]/ ? 0 :
3574 printdebug "massage done $r $dmode.\n";
3576 #print STDERR "MASS2 ",Dumper($cmd, $xargs, $r);
3581 my @dbp = (@dpkgbuildpackage, qw(-us -uc), changesopts_initial(), @ARGV);
3582 my $wantsrc = massage_dbp_args \@dbp;
3589 push @dbp, changesopts_version();
3590 maybe_apply_patches_dirtily();
3591 runcmd_ordryrun_local @dbp;
3593 maybe_unapply_patches_again();
3594 printdone "build successful\n";
3598 my @dbp = @dpkgbuildpackage;
3600 my $wantsrc = massage_dbp_args \@dbp, \@ARGV;
3603 if (length executable_on_path('git-buildpackage')) {
3604 @cmd = qw(git-buildpackage);
3606 @cmd = qw(gbp buildpackage);
3608 push @cmd, (qw(-us -uc --git-no-sign-tags), "--git-builder=@dbp");
3613 if (!$clean_using_builder) {
3614 push @cmd, '--git-cleaner=true';
3619 unless (grep { m/^--git-debian-branch|^--git-ignore-branch/ } @ARGV) {
3620 canonicalise_suite();
3621 push @cmd, "--git-debian-branch=".lbranch();
3623 push @cmd, changesopts();
3624 maybe_apply_patches_dirtily();
3625 runcmd_ordryrun_local @cmd, @ARGV;
3627 maybe_unapply_patches_again();
3628 printdone "build successful\n";
3630 sub cmd_git_build { cmd_gbp_build(); } # compatibility with <= 1.0
3633 my $our_cleanmode = $cleanmode;
3634 if ($need_split_build_invocation) {
3635 # Pretend that clean is being done some other way. This
3636 # forces us not to try to use dpkg-buildpackage to clean and
3637 # build source all in one go; and instead we run dpkg-source
3638 # (and build_prep() will do the clean since $clean_using_builder
3640 $our_cleanmode = 'ELSEWHERE';
3642 if ($our_cleanmode =~ m/^dpkg-source/) {
3643 # dpkg-source invocation (below) will clean, so build_prep shouldn't
3644 $clean_using_builder = 1;
3647 $sourcechanges = changespat $version,'source';
3649 unlink "../$sourcechanges" or $!==ENOENT
3650 or fail "remove $sourcechanges: $!";
3652 $dscfn = dscfn($version);
3653 if ($our_cleanmode eq 'dpkg-source') {
3654 maybe_apply_patches_dirtily();
3655 runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc -S),
3657 } elsif ($our_cleanmode eq 'dpkg-source-d') {
3658 maybe_apply_patches_dirtily();
3659 runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc -S -d),
3662 my @cmd = (@dpkgsource, qw(-b --));
3665 runcmd_ordryrun_local @cmd, "work";
3666 my @udfiles = <${package}_*>;
3667 changedir "../../..";
3668 foreach my $f (@udfiles) {
3669 printdebug "source copy, found $f\n";
3672 ($f =~ m/\.debian\.tar(?:\.\w+)$/ &&
3673 $f eq srcfn($version, $&));
3674 printdebug "source copy, found $f - renaming\n";
3675 rename "$ud/$f", "../$f" or $!==ENOENT
3676 or fail "put in place new source file ($f): $!";
3679 my $pwd = must_getcwd();
3680 my $leafdir = basename $pwd;
3682 runcmd_ordryrun_local @cmd, $leafdir;
3685 runcmd_ordryrun_local qw(sh -ec),
3686 'exec >$1; shift; exec "$@"','x',
3687 "../$sourcechanges",
3688 @dpkggenchanges, qw(-S), changesopts();
3692 sub cmd_build_source {
3693 badusage "build-source takes no additional arguments" if @ARGV;
3695 maybe_unapply_patches_again();
3696 printdone "source built, results in $dscfn and $sourcechanges";
3701 my $pat = changespat $version;
3703 my @unwanted = map { s#^\.\./##; $_; } glob "../$pat";
3704 @unwanted = grep { $_ ne changespat $version,'source' } @unwanted;
3705 fail "changes files other than source matching $pat".
3706 " already present (@unwanted);".
3707 " building would result in ambiguity about the intended results"
3712 stat_exists $dscfn or fail "$dscfn (in parent directory): $!";
3713 stat_exists $sourcechanges
3714 or fail "$sourcechanges (in parent directory): $!";
3716 runcmd_ordryrun_local @sbuild, qw(-d), $isuite, @ARGV, $dscfn;
3717 my @changesfiles = glob $pat;
3718 @changesfiles = sort {
3719 ($b =~ m/_source\.changes$/ <=> $a =~ m/_source\.changes$/)
3722 fail "wrong number of different changes files (@changesfiles)"
3723 unless @changesfiles==2;
3724 my $binchanges = parsecontrol($changesfiles[1], "binary changes file");
3725 foreach my $l (split /\n/, getfield $binchanges, 'Files') {
3726 fail "$l found in binaries changes file $binchanges"
3729 runcmd_ordryrun_local @mergechanges, @changesfiles;
3730 my $multichanges = changespat $version,'multi';
3732 stat_exists $multichanges or fail "$multichanges: $!";
3733 foreach my $cf (glob $pat) {
3734 next if $cf eq $multichanges;
3735 rename "$cf", "$cf.inmulti" or fail "$cf\{,.inmulti}: $!";
3738 maybe_unapply_patches_again();
3739 printdone "build successful, results in $multichanges\n" or die $!;
3742 sub cmd_quilt_fixup {
3743 badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
3744 my $clogp = parsechangelog();
3745 $version = getfield $clogp, 'Version';
3746 $package = getfield $clogp, 'Source';
3749 build_maybe_quilt_fixup();
3752 sub cmd_archive_api_query {
3753 badusage "need only 1 subpath argument" unless @ARGV==1;
3754 my ($subpath) = @ARGV;
3755 my @cmd = archive_api_query_cmd($subpath);
3757 exec @cmd or fail "exec curl: $!\n";
3760 sub cmd_clone_dgit_repos_server {
3761 badusage "need destination argument" unless @ARGV==1;
3762 my ($destdir) = @ARGV;
3763 $package = '_dgit-repos-server';
3764 my @cmd = (@git, qw(clone), access_giturl(), $destdir);
3766 exec @cmd or fail "exec git clone: $!\n";
3769 sub cmd_setup_mergechangelogs {
3770 badusage "no arguments allowed to dgit setup-mergechangelogs" if @ARGV;
3771 setup_mergechangelogs(1);
3774 sub cmd_setup_useremail {
3775 badusage "no arguments allowed to dgit setup-mergechangelogs" if @ARGV;
3779 sub cmd_setup_new_tree {
3780 badusage "no arguments allowed to dgit setup-tree" if @ARGV;
3784 #---------- argument parsing and main program ----------
3787 print "dgit version $our_version\n" or die $!;
3791 our (%valopts_long, %valopts_short);
3794 sub defvalopt ($$$$) {
3795 my ($long,$short,$val_re,$how) = @_;
3796 my $oi = { Long => $long, Short => $short, Re => $val_re, How => $how };
3797 $valopts_long{$long} = $oi;
3798 $valopts_short{$short} = $oi;
3799 # $how subref should:
3800 # do whatever assignemnt or thing it likes with $_[0]
3801 # if the option should not be passed on to remote, @rvalopts=()
3802 # or $how can be a scalar ref, meaning simply assign the value
3805 defvalopt '--since-version', '-v', '[^_]+|_', \$changes_since_version;
3806 defvalopt '--distro', '-d', '.+', \$idistro;
3807 defvalopt '', '-k', '.+', \$keyid;
3808 defvalopt '--existing-package','', '.*', \$existing_package;
3809 defvalopt '--build-products-dir','','.*', \$buildproductsdir;
3810 defvalopt '--clean', '', $cleanmode_re, \$cleanmode;
3811 defvalopt '--quilt', '', $quilt_modes_re, \$quilt_mode;
3813 defvalopt '', '-c', '.*=.*', sub { push @git, '-c', @_; };
3815 defvalopt '', '-C', '.+', sub {
3816 ($changesfile) = (@_);
3817 if ($changesfile =~ s#^(.*)/##) {
3818 $buildproductsdir = $1;
3822 defvalopt '--initiator-tempdir','','.*', sub {
3823 ($initiator_tempdir) = (@_);
3824 $initiator_tempdir =~ m#^/# or
3825 badusage "--initiator-tempdir must be used specify an".
3826 " absolute, not relative, directory."
3832 if (defined $ENV{'DGIT_SSH'}) {
3833 @ssh = string_to_ssh $ENV{'DGIT_SSH'};
3834 } elsif (defined $ENV{'GIT_SSH'}) {
3835 @ssh = ($ENV{'GIT_SSH'});
3843 if (!defined $val) {
3844 badusage "$what needs a value" unless @ARGV;
3846 push @rvalopts, $val;
3848 badusage "bad value \`$val' for $what" unless
3849 $val =~ m/^$oi->{Re}$(?!\n)/s;
3850 my $how = $oi->{How};
3851 if (ref($how) eq 'SCALAR') {
3856 push @ropts, @rvalopts;
3860 last unless $ARGV[0] =~ m/^-/;
3864 if (m/^--dry-run$/) {
3867 } elsif (m/^--damp-run$/) {
3870 } elsif (m/^--no-sign$/) {
3873 } elsif (m/^--help$/) {
3875 } elsif (m/^--version$/) {
3877 } elsif (m/^--new$/) {
3880 } elsif (m/^--([-0-9a-z]+)=(.+)/s &&
3881 ($om = $opts_opt_map{$1}) &&
3885 } elsif (m/^--([-0-9a-z]+):(.*)/s &&
3886 !$opts_opt_cmdonly{$1} &&
3887 ($om = $opts_opt_map{$1})) {
3890 } elsif (m/^--ignore-dirty$/s) {
3893 } elsif (m/^--no-quilt-fixup$/s) {
3895 $quilt_mode = 'nocheck';
3896 } elsif (m/^--no-rm-on-error$/s) {
3899 } elsif (m/^--(no-)?rm-old-changes$/s) {
3902 } elsif (m/^--deliberately-($deliberately_re)$/s) {
3904 push @deliberatelies, $&;
3905 } elsif (m/^--dgit-tag-format=(old|new)$/s) {
3906 # undocumented, for testing
3908 $tagformat_want = [ $1, 'command line', 1 ];
3909 # 1 menas overrides distro configuration
3910 } elsif (m/^--always-split-source-build$/s) {
3911 # undocumented, for testing
3913 $need_split_build_invocation = 1;
3914 } elsif (m/^(--[-0-9a-z]+)(=|$)/ && ($oi = $valopts_long{$1})) {
3915 $val = $2 ? $' : undef; #';
3916 $valopt->($oi->{Long});
3918 badusage "unknown long option \`$_'";
3925 } elsif (s/^-L/-/) {
3928 } elsif (s/^-h/-/) {
3930 } elsif (s/^-D/-/) {
3934 } elsif (s/^-N/-/) {
3939 push @changesopts, $_;
3941 } elsif (s/^-wn$//s) {
3943 $cleanmode = 'none';
3944 } elsif (s/^-wg$//s) {
3947 } elsif (s/^-wgf$//s) {
3949 $cleanmode = 'git-ff';
3950 } elsif (s/^-wd$//s) {
3952 $cleanmode = 'dpkg-source';
3953 } elsif (s/^-wdd$//s) {
3955 $cleanmode = 'dpkg-source-d';
3956 } elsif (s/^-wc$//s) {
3958 $cleanmode = 'check';
3959 } elsif (m/^-[a-zA-Z]/ && ($oi = $valopts_short{$&})) {
3961 $val = undef unless length $val;
3962 $valopt->($oi->{Short});
3965 badusage "unknown short option \`$_'";
3972 sub finalise_opts_opts () {
3973 foreach my $k (keys %opts_opt_map) {
3974 my $om = $opts_opt_map{$k};
3976 my $v = access_cfg("cmd-$k", 'RETURN-UNDEF');
3978 badcfg "cannot set command for $k"
3979 unless length $om->[0];
3983 foreach my $c (access_cfg_cfgs("opts-$k")) {
3984 my $vl = $gitcfg{$c};
3985 printdebug "CL $c ",
3986 ($vl ? join " ", map { shellquote } @$vl : ""),
3987 "\n" if $debuglevel >= 4;
3989 badcfg "cannot configure options for $k"
3990 if $opts_opt_cmdonly{$k};
3991 my $insertpos = $opts_cfg_insertpos{$k};
3992 @$om = ( @$om[0..$insertpos-1],
3994 @$om[$insertpos..$#$om] );
3999 if ($ENV{$fakeeditorenv}) {
4001 quilt_fixup_editor();
4007 print STDERR "DRY RUN ONLY\n" if $dryrun_level > 1;
4008 print STDERR "DAMP RUN - WILL MAKE LOCAL (UNSIGNED) CHANGES\n"
4009 if $dryrun_level == 1;
4011 print STDERR $helpmsg or die $!;
4014 my $cmd = shift @ARGV;
4017 if (!defined $rmchanges) {
4018 local $access_forpush;
4019 $rmchanges = access_cfg_bool(0, 'rm-old-changes');
4022 if (!defined $quilt_mode) {
4023 local $access_forpush;
4024 $quilt_mode = cfg('dgit.force.quilt-mode', 'RETURN-UNDEF')
4025 // access_cfg('quilt-mode', 'RETURN-UNDEF')
4027 $quilt_mode =~ m/^($quilt_modes_re)$/
4028 or badcfg "unknown quilt-mode \`$quilt_mode'";
4032 $need_split_build_invocation ||= quiltmode_splitbrain();
4034 if (!defined $cleanmode) {
4035 local $access_forpush;
4036 $cleanmode = access_cfg('clean-mode', 'RETURN-UNDEF');
4037 $cleanmode //= 'dpkg-source';
4039 badcfg "unknown clean-mode \`$cleanmode'" unless
4040 $cleanmode =~ m/^($cleanmode_re)$(?!\n)/s;
4043 my $fn = ${*::}{"cmd_$cmd"};
4044 $fn or badusage "unknown operation $cmd";