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 $actualhead = git_rev_parse('HEAD');
2095 my $dgithead = $actualhead;
2096 my $maintviewhead = undef;
2098 if (madformat($format)) {
2099 # user might have not used dgit build, so maybe do this now:
2100 if (quiltmode_splitbrain()) {
2101 my $upstreamversion = $clogp->{Version};
2102 $upstreamversion =~ s/-[^-]*$//;
2104 quilt_make_fake_dsc($upstreamversion);
2105 my ($dgitview, $cachekey) =
2106 quilt_check_splitbrain_cache($actualhead, $upstreamversion);
2108 "--quilt=$quilt_mode but no cached dgit view:
2109 perhaps tree changed since dgit build[-source] ?";
2111 $dgithead = $dgitview;
2112 $maintviewhead = $actualhead;
2113 changedir '../../../..';
2114 prep_ud(); # so _only_subdir() works, below
2116 commit_quilty_patch();
2120 die 'xxx fast forward (should not depend on quilt mode, but will always be needed if we did $split_brain)' if $split_brain;
2124 progress "checking that $dscfn corresponds to HEAD";
2125 runcmd qw(dpkg-source -x --),
2126 $dscpath =~ m#^/# ? $dscpath : "../../../$dscpath";
2127 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
2128 check_for_vendor_patches() if madformat($dsc->{format});
2129 changedir '../../../..';
2130 my $diffopt = $debuglevel>0 ? '--exit-code' : '--quiet';
2131 my @diffcmd = (@git, qw(diff), $diffopt, $tree, $dgithead);
2132 debugcmd "+",@diffcmd;
2134 my $r = system @diffcmd;
2137 fail "$dscfn specifies a different tree to your HEAD commit;".
2138 " perhaps you forgot to build".
2139 ($diffopt eq '--exit-code' ? "" :
2140 " (run with -D to see full diff output)");
2145 if (!$changesfile) {
2146 my $pat = changespat $cversion;
2147 my @cs = glob "$buildproductsdir/$pat";
2148 fail "failed to find unique changes file".
2149 " (looked for $pat in $buildproductsdir);".
2150 " perhaps you need to use dgit -C"
2152 ($changesfile) = @cs;
2154 $changesfile = "$buildproductsdir/$changesfile";
2157 responder_send_file('changes',$changesfile);
2158 responder_send_command("param head $dgithead");
2159 responder_send_command("param csuite $csuite");
2160 responder_send_command("param tagformat $tagformat");
2162 if (deliberately_not_fast_forward) {
2163 git_for_each_ref(lrfetchrefs, sub {
2164 my ($objid,$objtype,$lrfetchrefname,$reftail) = @_;
2165 my $rrefname= substr($lrfetchrefname, length(lrfetchrefs) + 1);
2166 responder_send_command("previously $rrefname=$objid");
2167 $previously{$rrefname} = $objid;
2171 my @tagwants = push_tagwants($cversion, $dgithead,
2175 supplementary_message(<<'END');
2176 Push failed, while signing the tag.
2177 You can retry the push, after fixing the problem, if you like.
2179 # If we manage to sign but fail to record it anywhere, it's fine.
2180 if ($we_are_responder) {
2181 @tagobjfns = map { $_->{Tfn}('.signed-tmp') } @tagwants;
2182 responder_receive_files('signed-tag', @tagobjfns);
2184 @tagobjfns = push_mktags($clogp,$dscpath,
2185 $changesfile,$changesfile,
2188 supplementary_message(<<'END');
2189 Push failed, *after* signing the tag.
2190 If you want to try again, you should use a new version number.
2193 pairwise { $a->{TagObjFn} = $b } @tagwants, @tagobjfns;
2195 foreach my $tw (@tagwants) {
2196 my $tag = $tw->{Tag};
2197 my $tagobjfn = $tw->{TagObjFn};
2199 cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
2200 runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
2201 runcmd_ordryrun_local
2202 @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
2205 supplementary_message(<<'END');
2206 Push failed, while updating the remote git repository - see messages above.
2207 If you want to try again, you should use a new version number.
2209 if (!check_for_git()) {
2210 create_remote_git_repo();
2213 my @pushrefs = $forceflag."HEAD:".rrref();
2214 foreach my $tw (@tagwants) {
2215 push @pushrefs, $forceflag."refs/tags/$tw->{Tag}";
2218 runcmd_ordryrun @git, qw(push),access_giturl(), @pushrefs;
2219 runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), $dgithead;
2221 supplementary_message(<<'END');
2222 Push failed, after updating the remote git repository.
2223 If you want to try again, you must use a new version number.
2225 if ($we_are_responder) {
2226 my $dryrunsuffix = act_local() ? "" : ".tmp";
2227 responder_receive_files('signed-dsc-changes',
2228 "$dscpath$dryrunsuffix",
2229 "$changesfile$dryrunsuffix");
2232 rename "$dscpath.tmp",$dscpath or die "$dscfn $!";
2234 progress "[new .dsc left in $dscpath.tmp]";
2236 sign_changes $changesfile;
2239 supplementary_message(<<END);
2240 Push failed, while uploading package(s) to the archive server.
2241 You can retry the upload of exactly these same files with dput of:
2243 If that .changes file is broken, you will need to use a new version
2244 number for your next attempt at the upload.
2246 my $host = access_cfg('upload-host','RETURN-UNDEF');
2247 my @hostarg = defined($host) ? ($host,) : ();
2248 runcmd_ordryrun @dput, @hostarg, $changesfile;
2249 printdone "pushed and uploaded $cversion";
2251 supplementary_message('');
2252 responder_send_command("complete");
2259 badusage "-p is not allowed with clone; specify as argument instead"
2260 if defined $package;
2263 } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
2264 ($package,$isuite) = @ARGV;
2265 } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
2266 ($package,$dstdir) = @ARGV;
2267 } elsif (@ARGV==3) {
2268 ($package,$isuite,$dstdir) = @ARGV;
2270 badusage "incorrect arguments to dgit clone";
2272 $dstdir ||= "$package";
2274 if (stat_exists $dstdir) {
2275 fail "$dstdir already exists";
2279 if ($rmonerror && !$dryrun_level) {
2280 $cwd_remove= getcwd();
2282 return unless defined $cwd_remove;
2283 if (!chdir "$cwd_remove") {
2284 return if $!==&ENOENT;
2285 die "chdir $cwd_remove: $!";
2288 rmtree($dstdir) or die "remove $dstdir: $!\n";
2289 } elsif (!grep { $! == $_ }
2290 (ENOENT, ENOTDIR, EACCES, EPERM, ELOOP)) {
2292 print STDERR "check whether to remove $dstdir: $!\n";
2298 $cwd_remove = undef;
2301 sub branchsuite () {
2302 my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
2303 if ($branch =~ m#$lbranch_re#o) {
2310 sub fetchpullargs () {
2312 if (!defined $package) {
2313 my $sourcep = parsecontrol('debian/control','debian/control');
2314 $package = getfield $sourcep, 'Source';
2317 # $isuite = branchsuite(); # this doesn't work because dak hates canons
2319 my $clogp = parsechangelog();
2320 $isuite = getfield $clogp, 'Distribution';
2322 canonicalise_suite();
2323 progress "fetching from suite $csuite";
2324 } elsif (@ARGV==1) {
2326 canonicalise_suite();
2328 badusage "incorrect arguments to dgit fetch or dgit pull";
2347 badusage "-p is not allowed with dgit push" if defined $package;
2349 my $clogp = parsechangelog();
2350 $package = getfield $clogp, 'Source';
2353 } elsif (@ARGV==1) {
2354 ($specsuite) = (@ARGV);
2356 badusage "incorrect arguments to dgit push";
2358 $isuite = getfield $clogp, 'Distribution';
2360 local ($package) = $existing_package; # this is a hack
2361 canonicalise_suite();
2363 canonicalise_suite();
2365 if (defined $specsuite &&
2366 $specsuite ne $isuite &&
2367 $specsuite ne $csuite) {
2368 fail "dgit push: changelog specifies $isuite ($csuite)".
2369 " but command line specifies $specsuite";
2371 supplementary_message(<<'END');
2372 Push failed, while checking state of the archive.
2373 You can retry the push, after fixing the problem, if you like.
2375 if (check_for_git()) {
2379 if (fetch_from_archive()) {
2380 if (is_fast_fwd(lrref(), 'HEAD')) {
2382 } elsif (deliberately_not_fast_forward) {
2385 fail "dgit push: HEAD is not a descendant".
2386 " of the archive's version.\n".
2387 "dgit: To overwrite its contents,".
2388 " use git merge -s ours ".lrref().".\n".
2389 "dgit: To rewind history, if permitted by the archive,".
2390 " use --deliberately-not-fast-forward";
2394 fail "package appears to be new in this suite;".
2395 " if this is intentional, use --new";
2400 #---------- remote commands' implementation ----------
2402 sub cmd_remote_push_build_host {
2403 my ($nrargs) = shift @ARGV;
2404 my (@rargs) = @ARGV[0..$nrargs-1];
2405 @ARGV = @ARGV[$nrargs..$#ARGV];
2407 my ($dir,$vsnwant) = @rargs;
2408 # vsnwant is a comma-separated list; we report which we have
2409 # chosen in our ready response (so other end can tell if they
2412 $we_are_responder = 1;
2413 $us .= " (build host)";
2417 open PI, "<&STDIN" or die $!;
2418 open STDIN, "/dev/null" or die $!;
2419 open PO, ">&STDOUT" or die $!;
2421 open STDOUT, ">&STDERR" or die $!;
2425 ($protovsn) = grep {
2426 $vsnwant =~ m{^(?:.*,)?$_(?:,.*)?$}
2427 } @rpushprotovsn_support;
2429 fail "build host has dgit rpush protocol versions ".
2430 (join ",", @rpushprotovsn_support).
2431 " but invocation host has $vsnwant"
2432 unless defined $protovsn;
2434 responder_send_command("dgit-remote-push-ready $protovsn");
2435 rpush_handle_protovsn_bothends();
2440 sub cmd_remote_push_responder { cmd_remote_push_build_host(); }
2441 # ... for compatibility with proto vsn.1 dgit (just so that user gets
2442 # a good error message)
2444 sub rpush_handle_protovsn_bothends () {
2445 if ($protovsn < 4) {
2446 need_tagformat 'old', "rpush negotiated protocol $protovsn";
2455 my $report = i_child_report();
2456 if (defined $report) {
2457 printdebug "($report)\n";
2458 } elsif ($i_child_pid) {
2459 printdebug "(killing build host child $i_child_pid)\n";
2460 kill 15, $i_child_pid;
2462 if (defined $i_tmp && !defined $initiator_tempdir) {
2464 eval { rmtree $i_tmp; };
2468 END { i_cleanup(); }
2471 my ($base,$selector,@args) = @_;
2472 $selector =~ s/\-/_/g;
2473 { no strict qw(refs); &{"${base}_${selector}"}(@args); }
2480 if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
2488 push @rargs, join ",", @rpushprotovsn_support;
2491 push @rdgit, @ropts;
2492 push @rdgit, qw(remote-push-build-host), (scalar @rargs), @rargs;
2494 my @cmd = (@ssh, $host, shellquote @rdgit);
2497 if (defined $initiator_tempdir) {
2498 rmtree $initiator_tempdir;
2499 mkdir $initiator_tempdir, 0700 or die "$initiator_tempdir: $!";
2500 $i_tmp = $initiator_tempdir;
2504 $i_child_pid = open2(\*RO, \*RI, @cmd);
2506 ($protovsn) = initiator_expect { m/^dgit-remote-push-ready (\S+)/ };
2507 die "$protovsn ?" unless grep { $_ eq $protovsn } @rpushprotovsn_support;
2508 $supplementary_message = '' unless $protovsn >= 3;
2509 rpush_handle_protovsn_bothends();
2511 my ($icmd,$iargs) = initiator_expect {
2512 m/^(\S+)(?: (.*))?$/;
2515 i_method "i_resp", $icmd, $iargs;
2519 sub i_resp_progress ($) {
2521 my $msg = protocol_read_bytes \*RO, $rhs;
2525 sub i_resp_supplementary_message ($) {
2527 $supplementary_message = protocol_read_bytes \*RO, $rhs;
2530 sub i_resp_complete {
2531 my $pid = $i_child_pid;
2532 $i_child_pid = undef; # prevents killing some other process with same pid
2533 printdebug "waiting for build host child $pid...\n";
2534 my $got = waitpid $pid, 0;
2535 die $! unless $got == $pid;
2536 die "build host child failed $?" if $?;
2539 printdebug "all done\n";
2543 sub i_resp_file ($) {
2545 my $localname = i_method "i_localname", $keyword;
2546 my $localpath = "$i_tmp/$localname";
2547 stat_exists $localpath and
2548 badproto \*RO, "file $keyword ($localpath) twice";
2549 protocol_receive_file \*RO, $localpath;
2550 i_method "i_file", $keyword;
2555 sub i_resp_param ($) {
2556 $_[0] =~ m/^(\S+) (.*)$/ or badproto \*RO, "bad param spec";
2560 sub i_resp_previously ($) {
2561 $_[0] =~ m#^(refs/tags/\S+)=(\w+)$#
2562 or badproto \*RO, "bad previously spec";
2563 my $r = system qw(git check-ref-format), $1;
2564 die "bad previously ref spec ($r)" if $r;
2565 $previously{$1} = $2;
2570 sub i_resp_want ($) {
2572 die "$keyword ?" if $i_wanted{$keyword}++;
2573 my @localpaths = i_method "i_want", $keyword;
2574 printdebug "[[ $keyword @localpaths\n";
2575 foreach my $localpath (@localpaths) {
2576 protocol_send_file \*RI, $localpath;
2578 print RI "files-end\n" or die $!;
2581 our ($i_clogp, $i_version, $i_dscfn, $i_changesfn);
2583 sub i_localname_parsed_changelog {
2584 return "remote-changelog.822";
2586 sub i_file_parsed_changelog {
2587 ($i_clogp, $i_version, $i_dscfn) =
2588 push_parse_changelog "$i_tmp/remote-changelog.822";
2589 die if $i_dscfn =~ m#/|^\W#;
2592 sub i_localname_dsc {
2593 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
2598 sub i_localname_changes {
2599 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
2600 $i_changesfn = $i_dscfn;
2601 $i_changesfn =~ s/\.dsc$/_dgit.changes/ or die;
2602 return $i_changesfn;
2604 sub i_file_changes { }
2606 sub i_want_signed_tag {
2607 printdebug Dumper(\%i_param, $i_dscfn);
2608 defined $i_param{'head'} && defined $i_dscfn && defined $i_clogp
2609 && defined $i_param{'csuite'}
2610 or badproto \*RO, "premature desire for signed-tag";
2611 my $head = $i_param{'head'};
2612 die if $head =~ m/[^0-9a-f]/ || $head !~ m/^../;
2615 if ($protovsn >= 4) {
2616 my $p = $i_param{'tagformat'} // '<undef>';
2618 or badproto \*RO, "tag format mismatch: $p vs. $tagformat";
2621 die unless $i_param{'csuite'} =~ m/^$suite_re$/;
2623 push_parse_dsc $i_dscfn, 'remote dsc', $i_version;
2625 my @tagwants = push_tagwants $i_version, $head, "tag";
2628 push_mktags $i_clogp, $i_dscfn,
2629 $i_changesfn, 'remote changes',
2633 sub i_want_signed_dsc_changes {
2634 rename "$i_dscfn.tmp","$i_dscfn" or die "$i_dscfn $!";
2635 sign_changes $i_changesfn;
2636 return ($i_dscfn, $i_changesfn);
2639 #---------- building etc. ----------
2645 #----- `3.0 (quilt)' handling -----
2647 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
2649 sub quiltify_dpkg_commit ($$$;$) {
2650 my ($patchname,$author,$msg, $xinfo) = @_;
2654 my $descfn = ".git/dgit/quilt-description.tmp";
2655 open O, '>', $descfn or die "$descfn: $!";
2658 $msg =~ s/^\s+$/ ./mg;
2659 print O <<END or die $!;
2669 local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
2670 local $ENV{'VISUAL'} = $ENV{'EDITOR'};
2671 local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
2672 runcmd @dpkgsource, qw(--commit .), $patchname;
2676 sub quiltify_trees_differ ($$;$$) {
2677 my ($x,$y,$finegrained,$ignorenamesr) = @_;
2678 # returns true iff the two tree objects differ other than in debian/
2679 # with $finegrained,
2680 # returns bitmask 01 - differ in upstream files except .gitignore
2681 # 02 - differ in .gitignore
2682 # if $ignorenamesr is defined, $ingorenamesr->{$fn}
2683 # is set for each modified .gitignore filename $fn
2685 my @cmd = (@git, qw(diff-tree --name-only -z));
2686 push @cmd, qw(-r) if $finegrained;
2688 my $diffs= cmdoutput @cmd;
2690 foreach my $f (split /\0/, $diffs) {
2691 next if $f =~ m#^debian(?:/.*)?$#s;
2692 my $isignore = $f =~ m#^(?:.*/)?.gitignore$#s;
2693 $r |= $isignore ? 02 : 01;
2694 $ignorenamesr->{$f}=1 if $ignorenamesr && $isignore;
2696 printdebug "quiltify_trees_differ $x $y => $r\n";
2700 sub quiltify_tree_sentinelfiles ($) {
2701 # lists the `sentinel' files present in the tree
2703 my $r = cmdoutput @git, qw(ls-tree --name-only), $x,
2704 qw(-- debian/rules debian/control);
2709 sub quiltify_splitbrain_needed () {
2710 if (!$split_brain) {
2711 progress "dgit view: changes are required...";
2712 runcmd @git, qw(checkout -q -b dgit-view);
2717 sub quiltify_splitbrain ($$$$$$) {
2718 my ($clogp, $unapplied, $headref, $diffbits,
2719 $editedignores, $cachekey) = @_;
2720 if ($quilt_mode !~ m/gbp|dpm/) {
2721 # treat .gitignore just like any other upstream file
2722 $diffbits = { %$diffbits };
2723 $_ = !!$_ foreach values %$diffbits;
2725 # We would like any commits we generate to be reproducible
2726 my @authline = clogp_authline($clogp);
2727 local $ENV{GIT_COMMITTER_NAME} = $authline[0];
2728 local $ENV{GIT_COMMITTER_EMAIL} = $authline[1];
2729 local $ENV{GIT_COMMITTER_DATE} = $authline[2];
2731 if ($quilt_mode =~ m/gbp|unapplied/ &&
2732 ($diffbits->{H2O} & 01)) {
2734 "--quilt=$quilt_mode specified, implying patches-unapplied git tree\n".
2735 " but git tree differs from orig in upstream files.";
2736 if (!stat_exists "debian/patches") {
2738 "\n ... debian/patches is missing; perhaps this is a patch queue branch?";
2742 if ($quilt_mode =~ m/gbp|unapplied/ &&
2743 ($diffbits->{O2A} & 01)) { # some patches
2744 quiltify_splitbrain_needed();
2745 progress "dgit view: creating patches-applied version using gbp pq";
2746 runcmd shell_cmd 'exec >/dev/null', @gbp, qw(pq import);
2747 # gbp pq import creates a fresh branch; push back to dgit-view
2748 runcmd @git, qw(update-ref refs/heads/dgit-view HEAD);
2749 runcmd @git, qw(checkout -q dgit-view);
2751 if (($diffbits->{H2O} & 02) && # user has modified .gitignore
2752 !($diffbits->{O2A} & 02)) { # patches do not change .gitignore
2753 quiltify_splitbrain_needed();
2754 progress "dgit view: creating patch to represent .gitignore changes";
2755 ensuredir "debian/patches";
2756 my $gipatch = "debian/patches/auto-gitignore";
2757 open GIPATCH, ">>", "$gipatch" or die "$gipatch: $!";
2758 stat GIPATCH or die "$gipatch: $!";
2759 fail "$gipatch already exists; but want to create it".
2760 " to record .gitignore changes" if (stat _)[7];
2761 print GIPATCH <<END or die "$gipatch: $!";
2762 Subject: Update .gitignore from Debian packaging branch
2764 The Debian packaging git branch contains these updates to the upstream
2765 .gitignore file(s). This patch is autogenerated, to provide these
2766 updates to users of the official Debian archive view of the package.
2768 [dgit version $our_version]
2771 close GIPATCH or die "$gipatch: $!";
2772 runcmd shell_cmd "exec >>$gipatch", @git, qw(diff),
2773 $unapplied, $headref, "--", sort keys %$editedignores;
2774 open SERIES, "+>>", "debian/patches/series" or die $!;
2775 defined seek SERIES, -1, 2 or $!==EINVAL or die $!;
2777 defined read SERIES, $newline, 1 or die $!;
2778 print SERIES "\n" or die $! unless $newline eq "\n";
2779 print SERIES "auto-gitignore\n" or die $!;
2780 close SERIES or die $!;
2781 runcmd @git, qw(add -- debian/patches/series), $gipatch;
2782 commit_admin "Commit patch to update .gitignore";
2785 my $dgitview = git_rev_parse 'refs/heads/dgit-view';
2787 changedir '../../../..';
2788 ensuredir ".git/logs/refs/dgit-intern";
2789 my $makelogfh = new IO::File ".git/logs/refs/$splitbraincache", '>>'
2791 runcmd @git, qw(update-ref -m), $cachekey, "refs/$splitbraincache",
2794 progress "dgit view: created (commit id $dgitview)";
2796 changedir '.git/dgit/unpack/work';
2799 sub quiltify ($$$$) {
2800 my ($clogp,$target,$oldtiptree,$failsuggestion) = @_;
2802 # Quilt patchification algorithm
2804 # We search backwards through the history of the main tree's HEAD
2805 # (T) looking for a start commit S whose tree object is identical
2806 # to to the patch tip tree (ie the tree corresponding to the
2807 # current dpkg-committed patch series). For these purposes
2808 # `identical' disregards anything in debian/ - this wrinkle is
2809 # necessary because dpkg-source treates debian/ specially.
2811 # We can only traverse edges where at most one of the ancestors'
2812 # trees differs (in changes outside in debian/). And we cannot
2813 # handle edges which change .pc/ or debian/patches. To avoid
2814 # going down a rathole we avoid traversing edges which introduce
2815 # debian/rules or debian/control. And we set a limit on the
2816 # number of edges we are willing to look at.
2818 # If we succeed, we walk forwards again. For each traversed edge
2819 # PC (with P parent, C child) (starting with P=S and ending with
2820 # C=T) to we do this:
2822 # - dpkg-source --commit with a patch name and message derived from C
2823 # After traversing PT, we git commit the changes which
2824 # should be contained within debian/patches.
2826 # The search for the path S..T is breadth-first. We maintain a
2827 # todo list containing search nodes. A search node identifies a
2828 # commit, and looks something like this:
2830 # Commit => $git_commit_id,
2831 # Child => $c, # or undef if P=T
2832 # Whynot => $reason_edge_PC_unsuitable, # in @nots only
2833 # Nontrivial => true iff $p..$c has relevant changes
2840 my %considered; # saves being exponential on some weird graphs
2842 my $t_sentinels = quiltify_tree_sentinelfiles $target;
2845 my ($search,$whynot) = @_;
2846 printdebug " search NOT $search->{Commit} $whynot\n";
2847 $search->{Whynot} = $whynot;
2848 push @nots, $search;
2849 no warnings qw(exiting);
2858 my $c = shift @todo;
2859 next if $considered{$c->{Commit}}++;
2861 $not->($c, "maximum search space exceeded") if --$max_work <= 0;
2863 printdebug "quiltify investigate $c->{Commit}\n";
2866 if (!quiltify_trees_differ $c->{Commit}, $oldtiptree) {
2867 printdebug " search finished hooray!\n";
2872 if ($quilt_mode eq 'nofix') {
2873 fail "quilt fixup required but quilt mode is \`nofix'\n".
2874 "HEAD commit $c->{Commit} differs from tree implied by ".
2875 " debian/patches (tree object $oldtiptree)";
2877 if ($quilt_mode eq 'smash') {
2878 printdebug " search quitting smash\n";
2882 my $c_sentinels = quiltify_tree_sentinelfiles $c->{Commit};
2883 $not->($c, "has $c_sentinels not $t_sentinels")
2884 if $c_sentinels ne $t_sentinels;
2886 my $commitdata = cmdoutput @git, qw(cat-file commit), $c->{Commit};
2887 $commitdata =~ m/\n\n/;
2889 my @parents = ($commitdata =~ m/^parent (\w+)$/gm);
2890 @parents = map { { Commit => $_, Child => $c } } @parents;
2892 $not->($c, "root commit") if !@parents;
2894 foreach my $p (@parents) {
2895 $p->{Nontrivial}= quiltify_trees_differ $p->{Commit},$c->{Commit};
2897 my $ndiffers = grep { $_->{Nontrivial} } @parents;
2898 $not->($c, "merge ($ndiffers nontrivial parents)") if $ndiffers > 1;
2900 foreach my $p (@parents) {
2901 printdebug "considering C=$c->{Commit} P=$p->{Commit}\n";
2903 my @cmd= (@git, qw(diff-tree -r --name-only),
2904 $p->{Commit},$c->{Commit}, qw(-- debian/patches .pc));
2905 my $patchstackchange = cmdoutput @cmd;
2906 if (length $patchstackchange) {
2907 $patchstackchange =~ s/\n/,/g;
2908 $not->($p, "changed $patchstackchange");
2911 printdebug " search queue P=$p->{Commit} ",
2912 ($p->{Nontrivial} ? "NT" : "triv"),"\n";
2918 printdebug "quiltify want to smash\n";
2921 my $x = $_[0]{Commit};
2922 $x =~ s/(.*?[0-9a-z]{8})[0-9a-z]*$/$1/;
2925 my $reportnot = sub {
2927 my $s = $abbrev->($notp);
2928 my $c = $notp->{Child};
2929 $s .= "..".$abbrev->($c) if $c;
2930 $s .= ": ".$notp->{Whynot};
2933 if ($quilt_mode eq 'linear') {
2934 print STDERR "$us: quilt fixup cannot be linear. Stopped at:\n";
2935 foreach my $notp (@nots) {
2936 print STDERR "$us: ", $reportnot->($notp), "\n";
2938 print STDERR "$us: $_\n" foreach @$failsuggestion;
2939 fail "quilt fixup naive history linearisation failed.\n".
2940 "Use dpkg-source --commit by hand; or, --quilt=smash for one ugly patch";
2941 } elsif ($quilt_mode eq 'smash') {
2942 } elsif ($quilt_mode eq 'auto') {
2943 progress "quilt fixup cannot be linear, smashing...";
2945 die "$quilt_mode ?";
2948 my $time = $ENV{'GIT_COMMITTER_DATE'} || time;
2949 $time =~ s/\s.*//; # trim timezone from GIT_COMMITTER_DATE
2951 my $msg = cmdoutput @git, qw(log), "-n$ncommits";
2953 quiltify_dpkg_commit "auto-$version-$target-$time",
2954 (getfield $clogp, 'Maintainer'),
2955 "Automatically generated patch ($clogp->{Version})\n".
2956 "Last (up to) $ncommits git changes, FYI:\n\n". $msg;
2960 progress "quiltify linearisation planning successful, executing...";
2962 for (my $p = $sref_S;
2963 my $c = $p->{Child};
2965 printdebug "quiltify traverse $p->{Commit}..$c->{Commit}\n";
2966 next unless $p->{Nontrivial};
2968 my $cc = $c->{Commit};
2970 my $commitdata = cmdoutput @git, qw(cat-file commit), $cc;
2971 $commitdata =~ m/\n\n/ or die "$c ?";
2974 $commitdata =~ m/^author (.*) \d+ [-+0-9]+$/m or die "$cc ?";
2977 $msg =~ s/^(.*)\n*/$1\n/ or die "$cc $msg ?";
2980 my $patchname = $title;
2981 $patchname =~ s/[.:]$//;
2982 $patchname =~ y/ A-Z/-a-z/;
2983 $patchname =~ y/-a-z0-9_.+=~//cd;
2984 $patchname =~ s/^\W/x-$&/;
2985 $patchname = substr($patchname,0,40);
2988 stat "debian/patches/$patchname$index";
2990 $!==ENOENT or die "$patchname$index $!";
2992 runcmd @git, qw(checkout -q), $cc;
2994 # We use the tip's changelog so that dpkg-source doesn't
2995 # produce complaining messages from dpkg-parsechangelog. None
2996 # of the information dpkg-source gets from the changelog is
2997 # actually relevant - it gets put into the original message
2998 # which dpkg-source provides our stunt editor, and then
3000 runcmd @git, qw(checkout -q), $target, qw(debian/changelog);
3002 quiltify_dpkg_commit "$patchname$index", $author, $msg,
3003 "X-Dgit-Generated: $clogp->{Version} $cc\n";
3005 runcmd @git, qw(checkout -q), $cc, qw(debian/changelog);
3008 runcmd @git, qw(checkout -q master);
3011 sub build_maybe_quilt_fixup () {
3012 my ($format,$fopts) = get_source_format;
3013 return unless madformat $format;
3016 check_for_vendor_patches();
3018 my $clogp = parsechangelog();
3019 my $headref = git_rev_parse('HEAD');
3024 my $upstreamversion=$version;
3025 $upstreamversion =~ s/-[^-]*$//;
3027 if ($fopts->{'single-debian-patch'}) {
3028 quilt_fixup_singlepatch($clogp, $headref, $upstreamversion);
3030 quilt_fixup_multipatch($clogp, $headref, $upstreamversion);
3033 die 'bug' if $split_brain && !$need_split_build_invocation;
3035 changedir '../../../..';
3036 runcmd_ordryrun_local
3037 @git, qw(pull --ff-only -q .git/dgit/unpack/work master);
3040 sub quilt_fixup_mkwork ($) {
3043 mkdir "work" or die $!;
3045 mktree_in_ud_here();
3046 runcmd @git, qw(reset -q --hard), $headref;
3049 sub quilt_fixup_linkorigs ($$) {
3050 my ($upstreamversion, $fn) = @_;
3051 # calls $fn->($leafname);
3053 foreach my $f (<../../../../*>) { #/){
3054 my $b=$f; $b =~ s{.*/}{};
3056 local ($debuglevel) = $debuglevel-1;
3057 printdebug "QF linkorigs $b, $f ?\n";
3059 next unless is_orig_file $b, srcfn $upstreamversion,'';
3060 printdebug "QF linkorigs $b, $f Y\n";
3061 link_ltarget $f, $b or die "$b $!";
3066 sub quilt_fixup_delete_pc () {
3067 runcmd @git, qw(rm -rqf .pc);
3068 commit_admin "Commit removal of .pc (quilt series tracking data)";
3071 sub quilt_fixup_singlepatch ($$$) {
3072 my ($clogp, $headref, $upstreamversion) = @_;
3074 progress "starting quiltify (single-debian-patch)";
3076 # dpkg-source --commit generates new patches even if
3077 # single-debian-patch is in debian/source/options. In order to
3078 # get it to generate debian/patches/debian-changes, it is
3079 # necessary to build the source package.
3081 quilt_fixup_linkorigs($upstreamversion, sub { });
3082 quilt_fixup_mkwork($headref);
3084 rmtree("debian/patches");
3086 runcmd @dpkgsource, qw(-b .);
3088 runcmd @dpkgsource, qw(-x), (srcfn $version, ".dsc");
3089 rename srcfn("$upstreamversion", "/debian/patches"),
3090 "work/debian/patches";
3093 commit_quilty_patch();
3096 sub quilt_make_fake_dsc ($) {
3097 my ($upstreamversion) = @_;
3099 my $fakeversion="$upstreamversion-~~DGITFAKE";
3101 my $fakedsc=new IO::File 'fake.dsc', '>' or die $!;
3102 print $fakedsc <<END or die $!;
3105 Version: $fakeversion
3109 my $dscaddfile=sub {
3112 my $md = new Digest::MD5;
3114 my $fh = new IO::File $b, '<' or die "$b $!";
3119 print $fakedsc " ".$md->hexdigest." $size $b\n" or die $!;
3122 quilt_fixup_linkorigs($upstreamversion, $dscaddfile);
3124 my @files=qw(debian/source/format debian/rules
3125 debian/control debian/changelog);
3126 foreach my $maybe (qw(debian/patches debian/source/options
3127 debian/tests/control)) {
3128 next unless stat_exists "../../../$maybe";
3129 push @files, $maybe;
3132 my $debtar= srcfn $fakeversion,'.debian.tar.gz';
3133 runcmd qw(env GZIP=-1n tar -zcf), "./$debtar", qw(-C ../../..), @files;
3135 $dscaddfile->($debtar);
3136 close $fakedsc or die $!;
3139 sub quilt_check_splitbrain_cache ($$) {
3140 my ($headref, $upstreamversion) = @_;
3141 # Called only if we are in (potentially) split brain mode.
3143 # Computes the cache key and looks in the cache.
3144 # Returns ($dgit_view_commitid, $cachekey) or (undef, $cachekey)
3146 my $splitbrain_cachekey;
3149 "dgit: split brain (separate dgit view) may be needed (--quilt=$quilt_mode).";
3150 # we look in the reflog of dgit-intern/quilt-cache
3151 # we look for an entry whose message is the key for the cache lookup
3152 my @cachekey = (qw(dgit), $our_version);
3153 push @cachekey, $upstreamversion;
3154 push @cachekey, $quilt_mode;
3155 push @cachekey, $headref;
3157 push @cachekey, hashfile('fake.dsc');
3159 my $srcshash = Digest::SHA->new(256);
3160 my %sfs = ( %INC, '$0(dgit)' => $0 );
3161 foreach my $sfk (sort keys %sfs) {
3162 next unless m/^\$0\b/ || m{^Debian/Dgit\b};
3163 $srcshash->add($sfk," ");
3164 $srcshash->add(hashfile($sfs{$sfk}));
3165 $srcshash->add("\n");
3167 push @cachekey, $srcshash->hexdigest();
3168 $splitbrain_cachekey = "@cachekey";
3170 my @cmd = (@git, qw(reflog), '--pretty=format:%H %gs',
3172 printdebug "splitbrain cachekey $splitbrain_cachekey\n";
3173 debugcmd "|(probably)",@cmd;
3174 my $child = open GC, "-|"; defined $child or die $!;
3176 chdir '../../..' or die $!;
3177 if (!stat ".git/logs/refs/$splitbraincache") {
3178 $! == ENOENT or die $!;
3179 printdebug ">(no reflog)\n";
3186 printdebug ">| ", $_, "\n" if $debuglevel > 1;
3187 next unless m/^(\w+) (\S.*\S)$/ && $2 eq $splitbrain_cachekey;
3190 quilt_fixup_mkwork($headref);
3191 if ($cachehit ne $headref) {
3192 progress "dgit view: found cached (commit id $cachehit)";
3193 runcmd @git, qw(checkout -q -b dgit-view), $cachehit;
3195 return ($cachehit, $splitbrain_cachekey);
3197 progress "dgit view: found cached, no changes required";
3198 return ($headref, $splitbrain_cachekey);
3200 die $! if GC->error;
3201 failedcmd unless close GC;
3203 printdebug "splitbrain cache miss\n";
3204 return (undef, $splitbrain_cachekey);
3207 sub quilt_fixup_multipatch ($$$) {
3208 my ($clogp, $headref, $upstreamversion) = @_;
3210 progress "examining quilt state (multiple patches, $quilt_mode mode)";
3213 # - honour any existing .pc in case it has any strangeness
3214 # - determine the git commit corresponding to the tip of
3215 # the patch stack (if there is one)
3216 # - if there is such a git commit, convert each subsequent
3217 # git commit into a quilt patch with dpkg-source --commit
3218 # - otherwise convert all the differences in the tree into
3219 # a single git commit
3223 # Our git tree doesn't necessarily contain .pc. (Some versions of
3224 # dgit would include the .pc in the git tree.) If there isn't
3225 # one, we need to generate one by unpacking the patches that we
3228 # We first look for a .pc in the git tree. If there is one, we
3229 # will use it. (This is not the normal case.)
3231 # Otherwise need to regenerate .pc so that dpkg-source --commit
3232 # can work. We do this as follows:
3233 # 1. Collect all relevant .orig from parent directory
3234 # 2. Generate a debian.tar.gz out of
3235 # debian/{patches,rules,source/format,source/options}
3236 # 3. Generate a fake .dsc containing just these fields:
3237 # Format Source Version Files
3238 # 4. Extract the fake .dsc
3239 # Now the fake .dsc has a .pc directory.
3240 # (In fact we do this in every case, because in future we will
3241 # want to search for a good base commit for generating patches.)
3243 # Then we can actually do the dpkg-source --commit
3244 # 1. Make a new working tree with the same object
3245 # store as our main tree and check out the main
3247 # 2. Copy .pc from the fake's extraction, if necessary
3248 # 3. Run dpkg-source --commit
3249 # 4. If the result has changes to debian/, then
3250 # - git-add them them
3251 # - git-add .pc if we had a .pc in-tree
3253 # 5. If we had a .pc in-tree, delete it, and git-commit
3254 # 6. Back in the main tree, fast forward to the new HEAD
3256 # Another situation we may have to cope with is gbp-style
3257 # patches-unapplied trees.
3259 # We would want to detect these, so we know to escape into
3260 # quilt_fixup_gbp. However, this is in general not possible.
3261 # Consider a package with a one patch which the dgit user reverts
3262 # (with git-revert or the moral equivalent).
3264 # That is indistinguishable in contents from a patches-unapplied
3265 # tree. And looking at the history to distinguish them is not
3266 # useful because the user might have made a confusing-looking git
3267 # history structure (which ought to produce an error if dgit can't
3268 # cope, not a silent reintroduction of an unwanted patch).
3270 # So gbp users will have to pass an option. But we can usually
3271 # detect their failure to do so: if the tree is not a clean
3272 # patches-applied tree, quilt linearisation fails, but the tree
3273 # _is_ a clean patches-unapplied tree, we can suggest that maybe
3274 # they want --quilt=unapplied.
3276 # To help detect this, when we are extracting the fake dsc, we
3277 # first extract it with --skip-patches, and then apply the patches
3278 # afterwards with dpkg-source --before-build. That lets us save a
3279 # tree object corresponding to .origs.
3281 my $splitbrain_cachekey;
3283 quilt_make_fake_dsc($upstreamversion);
3285 if (quiltmode_splitbrain()) {
3287 ($cachehit, $splitbrain_cachekey) =
3288 quilt_check_splitbrain_cache($headref, $upstreamversion);
3289 return if $cachehit;
3293 'exec dpkg-source --no-check --skip-patches -x fake.dsc >/dev/null';
3295 my $fakexdir= $package.'-'.(stripepoch $upstreamversion);
3296 rename $fakexdir, "fake" or die "$fakexdir $!";
3300 remove_stray_gits();
3301 mktree_in_ud_here();
3305 runcmd @git, qw(add -Af .);
3306 my $unapplied=git_write_tree();
3307 printdebug "fake orig tree object $unapplied\n";
3312 'exec dpkg-source --before-build . >/dev/null';
3316 quilt_fixup_mkwork($headref);
3319 if (stat_exists ".pc") {
3321 progress "Tree already contains .pc - will use it then delete it.";
3324 rename '../fake/.pc','.pc' or die $!;
3327 changedir '../fake';
3329 runcmd @git, qw(add -Af .);
3330 my $oldtiptree=git_write_tree();
3331 printdebug "fake o+d/p tree object $unapplied\n";
3332 changedir '../work';
3335 # We calculate some guesswork now about what kind of tree this might
3336 # be. This is mostly for error reporting.
3341 # O = orig, without patches applied
3342 # A = "applied", ie orig with H's debian/patches applied
3343 H2O => quiltify_trees_differ($headref, $unapplied, 1,\%editedignores),
3344 H2A => quiltify_trees_differ($headref, $oldtiptree,1),
3345 O2A => quiltify_trees_differ($unapplied,$oldtiptree,1),
3349 foreach my $b (qw(01 02)) {
3350 foreach my $v (qw(H2O O2A H2A)) {
3351 push @dl, ($diffbits->{$v} & $b) ? '##' : '==';
3354 printdebug "differences \@dl @dl.\n";
3357 "$us: quilt differences: src: %s orig %s gitignores: %s orig %s\n".
3358 "$us: quilt differences: HEAD %s o+d/p HEAD %s o+d/p",
3359 $dl[0], $dl[1], $dl[3], $dl[4],
3363 if (!($diffbits->{H2O} & $diffbits->{O2A})) {
3364 push @failsuggestion, "This might be a patches-unapplied branch.";
3365 } elsif (!($diffbits->{H2A} & $diffbits->{O2A})) {
3366 push @failsuggestion, "This might be a patches-applied branch.";
3368 push @failsuggestion, "Maybe you need to specify one of".
3369 " --quilt=gbp --quilt=dpm --quilt=unapplied ?";
3371 if (quiltmode_splitbrain()) {
3372 quiltify_splitbrain($clogp, $unapplied, $headref,
3373 $diffbits, \%editedignores,
3374 $splitbrain_cachekey);
3378 progress "starting quiltify (multiple patches, $quilt_mode mode)";
3379 quiltify($clogp,$headref,$oldtiptree,\@failsuggestion);
3381 if (!open P, '>>', ".pc/applied-patches") {
3382 $!==&ENOENT or die $!;
3387 commit_quilty_patch();
3389 if ($mustdeletepc) {
3390 quilt_fixup_delete_pc();
3394 sub quilt_fixup_editor () {
3395 my $descfn = $ENV{$fakeeditorenv};
3396 my $editing = $ARGV[$#ARGV];
3397 open I1, '<', $descfn or die "$descfn: $!";
3398 open I2, '<', $editing or die "$editing: $!";
3399 unlink $editing or die "$editing: $!";
3400 open O, '>', $editing or die "$editing: $!";
3401 while (<I1>) { print O or die $!; } I1->error and die $!;
3404 $copying ||= m/^\-\-\- /;
3405 next unless $copying;
3408 I2->error and die $!;
3413 sub maybe_apply_patches_dirtily () {
3414 return unless $quilt_mode =~ m/gbp|unapplied/;
3415 print STDERR <<END or die $!;
3417 dgit: Building, or cleaning with rules target, in patches-unapplied tree.
3418 dgit: Have to apply the patches - making the tree dirty.
3419 dgit: (Consider specifying --clean=git and (or) using dgit sbuild.)
3422 $patches_applied_dirtily = 01;
3423 $patches_applied_dirtily |= 02 unless stat_exists '.pc';
3424 runcmd qw(dpkg-source --before-build .);
3427 sub maybe_unapply_patches_again () {
3428 progress "dgit: Unapplying patches again to tidy up the tree."
3429 if $patches_applied_dirtily;
3430 runcmd qw(dpkg-source --after-build .)
3431 if $patches_applied_dirtily & 01;
3433 if $patches_applied_dirtily & 02;
3436 #----- other building -----
3438 our $clean_using_builder;
3439 # ^ tree is to be cleaned by dpkg-source's builtin idea that it should
3440 # clean the tree before building (perhaps invoked indirectly by
3441 # whatever we are using to run the build), rather than separately
3442 # and explicitly by us.
3445 return if $clean_using_builder;
3446 if ($cleanmode eq 'dpkg-source') {
3447 maybe_apply_patches_dirtily();
3448 runcmd_ordryrun_local @dpkgbuildpackage, qw(-T clean);
3449 } elsif ($cleanmode eq 'dpkg-source-d') {
3450 maybe_apply_patches_dirtily();
3451 runcmd_ordryrun_local @dpkgbuildpackage, qw(-d -T clean);
3452 } elsif ($cleanmode eq 'git') {
3453 runcmd_ordryrun_local @git, qw(clean -xdf);
3454 } elsif ($cleanmode eq 'git-ff') {
3455 runcmd_ordryrun_local @git, qw(clean -xdff);
3456 } elsif ($cleanmode eq 'check') {
3457 my $leftovers = cmdoutput @git, qw(clean -xdn);
3458 if (length $leftovers) {
3459 print STDERR $leftovers, "\n" or die $!;
3460 fail "tree contains uncommitted files and --clean=check specified";
3462 } elsif ($cleanmode eq 'none') {
3469 badusage "clean takes no additional arguments" if @ARGV;
3472 maybe_unapply_patches_again();
3477 badusage "-p is not allowed when building" if defined $package;
3480 my $clogp = parsechangelog();
3481 $isuite = getfield $clogp, 'Distribution';
3482 $package = getfield $clogp, 'Source';
3483 $version = getfield $clogp, 'Version';
3484 build_maybe_quilt_fixup();
3486 my $pat = changespat $version;
3487 foreach my $f (glob "$buildproductsdir/$pat") {
3489 unlink $f or fail "remove old changes file $f: $!";
3491 progress "would remove $f";
3497 sub changesopts_initial () {
3498 my @opts =@changesopts[1..$#changesopts];
3501 sub changesopts_version () {
3502 if (!defined $changes_since_version) {
3503 my @vsns = archive_query('archive_query');
3504 my @quirk = access_quirk();
3505 if ($quirk[0] eq 'backports') {
3506 local $isuite = $quirk[2];
3508 canonicalise_suite();
3509 push @vsns, archive_query('archive_query');
3512 @vsns = map { $_->[0] } @vsns;
3513 @vsns = sort { -version_compare($a, $b) } @vsns;
3514 $changes_since_version = $vsns[0];
3515 progress "changelog will contain changes since $vsns[0]";
3517 $changes_since_version = '_';
3518 progress "package seems new, not specifying -v<version>";
3521 if ($changes_since_version ne '_') {
3522 return ("-v$changes_since_version");
3528 sub changesopts () {
3529 return (changesopts_initial(), changesopts_version());
3532 sub massage_dbp_args ($;$) {
3533 my ($cmd,$xargs) = @_;
3536 # - if we're going to split the source build out so we can
3537 # do strange things to it, massage the arguments to dpkg-buildpackage
3538 # so that the main build doessn't build source (or add an argument
3539 # to stop it building source by default).
3541 # - add -nc to stop dpkg-source cleaning the source tree,
3542 # unless we're not doing a split build and want dpkg-source
3543 # as cleanmode, in which case we can do nothing
3546 # 0 - source will NOT need to be built separately by caller
3547 # +1 - source will need to be built separately by caller
3548 # +2 - source will need to be built separately by caller AND
3549 # dpkg-buildpackage should not in fact be run at all!
3550 debugcmd '#massaging#', @$cmd if $debuglevel>1;
3551 #print STDERR "MASS0 ",Dumper($cmd, $xargs, $need_split_build_invocation);
3552 if ($cleanmode eq 'dpkg-source' && !$need_split_build_invocation) {
3553 $clean_using_builder = 1;
3556 # -nc has the side effect of specifying -b if nothing else specified
3557 # and some combinations of -S, -b, et al, are errors, rather than
3558 # later simply overriding earlie. So we need to:
3559 # - search the command line for these options
3560 # - pick the last one
3561 # - perhaps add our own as a default
3562 # - perhaps adjust it to the corresponding non-source-building version
3564 foreach my $l ($cmd, $xargs) {
3566 @$l = grep { !(m/^-[SgGFABb]$/s and $dmode=$_) } @$l;
3569 #print STDERR "MASS1 ",Dumper($cmd, $xargs, $dmode);
3571 if ($need_split_build_invocation) {
3572 printdebug "massage split $dmode.\n";
3573 $r = $dmode =~ m/[S]/ ? +2 :
3574 $dmode =~ y/gGF/ABb/ ? +1 :
3575 $dmode =~ m/[ABb]/ ? 0 :
3578 printdebug "massage done $r $dmode.\n";
3580 #print STDERR "MASS2 ",Dumper($cmd, $xargs, $r);
3585 my @dbp = (@dpkgbuildpackage, qw(-us -uc), changesopts_initial(), @ARGV);
3586 my $wantsrc = massage_dbp_args \@dbp;
3593 push @dbp, changesopts_version();
3594 maybe_apply_patches_dirtily();
3595 runcmd_ordryrun_local @dbp;
3597 maybe_unapply_patches_again();
3598 printdone "build successful\n";
3602 my @dbp = @dpkgbuildpackage;
3604 my $wantsrc = massage_dbp_args \@dbp, \@ARGV;
3607 if (length executable_on_path('git-buildpackage')) {
3608 @cmd = qw(git-buildpackage);
3610 @cmd = qw(gbp buildpackage);
3612 push @cmd, (qw(-us -uc --git-no-sign-tags), "--git-builder=@dbp");
3617 if (!$clean_using_builder) {
3618 push @cmd, '--git-cleaner=true';
3623 unless (grep { m/^--git-debian-branch|^--git-ignore-branch/ } @ARGV) {
3624 canonicalise_suite();
3625 push @cmd, "--git-debian-branch=".lbranch();
3627 push @cmd, changesopts();
3628 maybe_apply_patches_dirtily();
3629 runcmd_ordryrun_local @cmd, @ARGV;
3631 maybe_unapply_patches_again();
3632 printdone "build successful\n";
3634 sub cmd_git_build { cmd_gbp_build(); } # compatibility with <= 1.0
3637 my $our_cleanmode = $cleanmode;
3638 if ($need_split_build_invocation) {
3639 # Pretend that clean is being done some other way. This
3640 # forces us not to try to use dpkg-buildpackage to clean and
3641 # build source all in one go; and instead we run dpkg-source
3642 # (and build_prep() will do the clean since $clean_using_builder
3644 $our_cleanmode = 'ELSEWHERE';
3646 if ($our_cleanmode =~ m/^dpkg-source/) {
3647 # dpkg-source invocation (below) will clean, so build_prep shouldn't
3648 $clean_using_builder = 1;
3651 $sourcechanges = changespat $version,'source';
3653 unlink "../$sourcechanges" or $!==ENOENT
3654 or fail "remove $sourcechanges: $!";
3656 $dscfn = dscfn($version);
3657 if ($our_cleanmode eq 'dpkg-source') {
3658 maybe_apply_patches_dirtily();
3659 runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc -S),
3661 } elsif ($our_cleanmode eq 'dpkg-source-d') {
3662 maybe_apply_patches_dirtily();
3663 runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc -S -d),
3666 my @cmd = (@dpkgsource, qw(-b --));
3669 runcmd_ordryrun_local @cmd, "work";
3670 my @udfiles = <${package}_*>;
3671 changedir "../../..";
3672 foreach my $f (@udfiles) {
3673 printdebug "source copy, found $f\n";
3676 ($f =~ m/\.debian\.tar(?:\.\w+)$/ &&
3677 $f eq srcfn($version, $&));
3678 printdebug "source copy, found $f - renaming\n";
3679 rename "$ud/$f", "../$f" or $!==ENOENT
3680 or fail "put in place new source file ($f): $!";
3683 my $pwd = must_getcwd();
3684 my $leafdir = basename $pwd;
3686 runcmd_ordryrun_local @cmd, $leafdir;
3689 runcmd_ordryrun_local qw(sh -ec),
3690 'exec >$1; shift; exec "$@"','x',
3691 "../$sourcechanges",
3692 @dpkggenchanges, qw(-S), changesopts();
3696 sub cmd_build_source {
3697 badusage "build-source takes no additional arguments" if @ARGV;
3699 maybe_unapply_patches_again();
3700 printdone "source built, results in $dscfn and $sourcechanges";
3705 my $pat = changespat $version;
3707 my @unwanted = map { s#^\.\./##; $_; } glob "../$pat";
3708 @unwanted = grep { $_ ne changespat $version,'source' } @unwanted;
3709 fail "changes files other than source matching $pat".
3710 " already present (@unwanted);".
3711 " building would result in ambiguity about the intended results"
3716 stat_exists $dscfn or fail "$dscfn (in parent directory): $!";
3717 stat_exists $sourcechanges
3718 or fail "$sourcechanges (in parent directory): $!";
3720 runcmd_ordryrun_local @sbuild, qw(-d), $isuite, @ARGV, $dscfn;
3721 my @changesfiles = glob $pat;
3722 @changesfiles = sort {
3723 ($b =~ m/_source\.changes$/ <=> $a =~ m/_source\.changes$/)
3726 fail "wrong number of different changes files (@changesfiles)"
3727 unless @changesfiles==2;
3728 my $binchanges = parsecontrol($changesfiles[1], "binary changes file");
3729 foreach my $l (split /\n/, getfield $binchanges, 'Files') {
3730 fail "$l found in binaries changes file $binchanges"
3733 runcmd_ordryrun_local @mergechanges, @changesfiles;
3734 my $multichanges = changespat $version,'multi';
3736 stat_exists $multichanges or fail "$multichanges: $!";
3737 foreach my $cf (glob $pat) {
3738 next if $cf eq $multichanges;
3739 rename "$cf", "$cf.inmulti" or fail "$cf\{,.inmulti}: $!";
3742 maybe_unapply_patches_again();
3743 printdone "build successful, results in $multichanges\n" or die $!;
3746 sub cmd_quilt_fixup {
3747 badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
3748 my $clogp = parsechangelog();
3749 $version = getfield $clogp, 'Version';
3750 $package = getfield $clogp, 'Source';
3753 build_maybe_quilt_fixup();
3756 sub cmd_archive_api_query {
3757 badusage "need only 1 subpath argument" unless @ARGV==1;
3758 my ($subpath) = @ARGV;
3759 my @cmd = archive_api_query_cmd($subpath);
3761 exec @cmd or fail "exec curl: $!\n";
3764 sub cmd_clone_dgit_repos_server {
3765 badusage "need destination argument" unless @ARGV==1;
3766 my ($destdir) = @ARGV;
3767 $package = '_dgit-repos-server';
3768 my @cmd = (@git, qw(clone), access_giturl(), $destdir);
3770 exec @cmd or fail "exec git clone: $!\n";
3773 sub cmd_setup_mergechangelogs {
3774 badusage "no arguments allowed to dgit setup-mergechangelogs" if @ARGV;
3775 setup_mergechangelogs(1);
3778 sub cmd_setup_useremail {
3779 badusage "no arguments allowed to dgit setup-mergechangelogs" if @ARGV;
3783 sub cmd_setup_new_tree {
3784 badusage "no arguments allowed to dgit setup-tree" if @ARGV;
3788 #---------- argument parsing and main program ----------
3791 print "dgit version $our_version\n" or die $!;
3795 our (%valopts_long, %valopts_short);
3798 sub defvalopt ($$$$) {
3799 my ($long,$short,$val_re,$how) = @_;
3800 my $oi = { Long => $long, Short => $short, Re => $val_re, How => $how };
3801 $valopts_long{$long} = $oi;
3802 $valopts_short{$short} = $oi;
3803 # $how subref should:
3804 # do whatever assignemnt or thing it likes with $_[0]
3805 # if the option should not be passed on to remote, @rvalopts=()
3806 # or $how can be a scalar ref, meaning simply assign the value
3809 defvalopt '--since-version', '-v', '[^_]+|_', \$changes_since_version;
3810 defvalopt '--distro', '-d', '.+', \$idistro;
3811 defvalopt '', '-k', '.+', \$keyid;
3812 defvalopt '--existing-package','', '.*', \$existing_package;
3813 defvalopt '--build-products-dir','','.*', \$buildproductsdir;
3814 defvalopt '--clean', '', $cleanmode_re, \$cleanmode;
3815 defvalopt '--quilt', '', $quilt_modes_re, \$quilt_mode;
3817 defvalopt '', '-c', '.*=.*', sub { push @git, '-c', @_; };
3819 defvalopt '', '-C', '.+', sub {
3820 ($changesfile) = (@_);
3821 if ($changesfile =~ s#^(.*)/##) {
3822 $buildproductsdir = $1;
3826 defvalopt '--initiator-tempdir','','.*', sub {
3827 ($initiator_tempdir) = (@_);
3828 $initiator_tempdir =~ m#^/# or
3829 badusage "--initiator-tempdir must be used specify an".
3830 " absolute, not relative, directory."
3836 if (defined $ENV{'DGIT_SSH'}) {
3837 @ssh = string_to_ssh $ENV{'DGIT_SSH'};
3838 } elsif (defined $ENV{'GIT_SSH'}) {
3839 @ssh = ($ENV{'GIT_SSH'});
3847 if (!defined $val) {
3848 badusage "$what needs a value" unless @ARGV;
3850 push @rvalopts, $val;
3852 badusage "bad value \`$val' for $what" unless
3853 $val =~ m/^$oi->{Re}$(?!\n)/s;
3854 my $how = $oi->{How};
3855 if (ref($how) eq 'SCALAR') {
3860 push @ropts, @rvalopts;
3864 last unless $ARGV[0] =~ m/^-/;
3868 if (m/^--dry-run$/) {
3871 } elsif (m/^--damp-run$/) {
3874 } elsif (m/^--no-sign$/) {
3877 } elsif (m/^--help$/) {
3879 } elsif (m/^--version$/) {
3881 } elsif (m/^--new$/) {
3884 } elsif (m/^--([-0-9a-z]+)=(.+)/s &&
3885 ($om = $opts_opt_map{$1}) &&
3889 } elsif (m/^--([-0-9a-z]+):(.*)/s &&
3890 !$opts_opt_cmdonly{$1} &&
3891 ($om = $opts_opt_map{$1})) {
3894 } elsif (m/^--ignore-dirty$/s) {
3897 } elsif (m/^--no-quilt-fixup$/s) {
3899 $quilt_mode = 'nocheck';
3900 } elsif (m/^--no-rm-on-error$/s) {
3903 } elsif (m/^--(no-)?rm-old-changes$/s) {
3906 } elsif (m/^--deliberately-($deliberately_re)$/s) {
3908 push @deliberatelies, $&;
3909 } elsif (m/^--dgit-tag-format=(old|new)$/s) {
3910 # undocumented, for testing
3912 $tagformat_want = [ $1, 'command line', 1 ];
3913 # 1 menas overrides distro configuration
3914 } elsif (m/^--always-split-source-build$/s) {
3915 # undocumented, for testing
3917 $need_split_build_invocation = 1;
3918 } elsif (m/^(--[-0-9a-z]+)(=|$)/ && ($oi = $valopts_long{$1})) {
3919 $val = $2 ? $' : undef; #';
3920 $valopt->($oi->{Long});
3922 badusage "unknown long option \`$_'";
3929 } elsif (s/^-L/-/) {
3932 } elsif (s/^-h/-/) {
3934 } elsif (s/^-D/-/) {
3938 } elsif (s/^-N/-/) {
3943 push @changesopts, $_;
3945 } elsif (s/^-wn$//s) {
3947 $cleanmode = 'none';
3948 } elsif (s/^-wg$//s) {
3951 } elsif (s/^-wgf$//s) {
3953 $cleanmode = 'git-ff';
3954 } elsif (s/^-wd$//s) {
3956 $cleanmode = 'dpkg-source';
3957 } elsif (s/^-wdd$//s) {
3959 $cleanmode = 'dpkg-source-d';
3960 } elsif (s/^-wc$//s) {
3962 $cleanmode = 'check';
3963 } elsif (m/^-[a-zA-Z]/ && ($oi = $valopts_short{$&})) {
3965 $val = undef unless length $val;
3966 $valopt->($oi->{Short});
3969 badusage "unknown short option \`$_'";
3976 sub finalise_opts_opts () {
3977 foreach my $k (keys %opts_opt_map) {
3978 my $om = $opts_opt_map{$k};
3980 my $v = access_cfg("cmd-$k", 'RETURN-UNDEF');
3982 badcfg "cannot set command for $k"
3983 unless length $om->[0];
3987 foreach my $c (access_cfg_cfgs("opts-$k")) {
3988 my $vl = $gitcfg{$c};
3989 printdebug "CL $c ",
3990 ($vl ? join " ", map { shellquote } @$vl : ""),
3991 "\n" if $debuglevel >= 4;
3993 badcfg "cannot configure options for $k"
3994 if $opts_opt_cmdonly{$k};
3995 my $insertpos = $opts_cfg_insertpos{$k};
3996 @$om = ( @$om[0..$insertpos-1],
3998 @$om[$insertpos..$#$om] );
4003 if ($ENV{$fakeeditorenv}) {
4005 quilt_fixup_editor();
4011 print STDERR "DRY RUN ONLY\n" if $dryrun_level > 1;
4012 print STDERR "DAMP RUN - WILL MAKE LOCAL (UNSIGNED) CHANGES\n"
4013 if $dryrun_level == 1;
4015 print STDERR $helpmsg or die $!;
4018 my $cmd = shift @ARGV;
4021 if (!defined $rmchanges) {
4022 local $access_forpush;
4023 $rmchanges = access_cfg_bool(0, 'rm-old-changes');
4026 if (!defined $quilt_mode) {
4027 local $access_forpush;
4028 $quilt_mode = cfg('dgit.force.quilt-mode', 'RETURN-UNDEF')
4029 // access_cfg('quilt-mode', 'RETURN-UNDEF')
4031 $quilt_mode =~ m/^($quilt_modes_re)$/
4032 or badcfg "unknown quilt-mode \`$quilt_mode'";
4036 $need_split_build_invocation ||= quiltmode_splitbrain();
4038 if (!defined $cleanmode) {
4039 local $access_forpush;
4040 $cleanmode = access_cfg('clean-mode', 'RETURN-UNDEF');
4041 $cleanmode //= 'dpkg-source';
4043 badcfg "unknown clean-mode \`$cleanmode'" unless
4044 $cleanmode =~ m/^($cleanmode_re)$(?!\n)/s;
4047 my $fn = ${*::}{"cmd_$cmd"};
4048 $fn or badusage "unknown operation $cmd";