3 # Integration between git and Debian-style archives
5 # Copyright (C)2013 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/>.
21 $SIG{__WARN__} = sub { die $_[0]; };
26 use Dpkg::Control::Hash;
28 use File::Temp qw(tempdir);
39 our $our_version = 'UNRELEASED'; ###substituted###
41 our $rpushprotovsn = 2;
43 our $isuite = 'unstable';
49 our $dryrun_level = 0;
51 our $buildproductsdir = '..';
57 our $existing_package = 'dpkg';
58 our $cleanmode = 'dpkg-source';
59 our $changes_since_version;
61 our $quilt_modes_re = 'linear|smash|auto|nofix|nocheck';
62 our $we_are_responder;
63 our $initiator_tempdir;
65 our %format_ok = map { $_=>1 } ("1.0","3.0 (native)","3.0 (quilt)");
67 our $suite_re = '[-+.0-9a-z]+';
70 our (@dget) = qw(dget);
71 our (@curl) = qw(curl -f);
72 our (@dput) = qw(dput);
73 our (@debsign) = qw(debsign);
75 our (@sbuild) = qw(sbuild -A);
77 our (@dgit) = qw(dgit);
78 our (@dpkgbuildpackage) = qw(dpkg-buildpackage -i\.git/ -I.git);
79 our (@dpkgsource) = qw(dpkg-source -i\.git/ -I.git);
80 our (@dpkggenchanges) = qw(dpkg-genchanges);
81 our (@mergechanges) = qw(mergechanges -f);
82 our (@changesopts) = ('');
84 our %opts_opt_map = ('dget' => \@dget, # accept for compatibility
87 'debsign' => \@debsign,
92 'dpkg-source' => \@dpkgsource,
93 'dpkg-buildpackage' => \@dpkgbuildpackage,
94 'dpkg-genchanges' => \@dpkggenchanges,
95 'ch' => \@changesopts,
96 'mergechanges' => \@mergechanges);
98 our %opts_opt_cmdonly = ('gpg' => 1);
103 open DEBUG, ">/dev/null" or die $!;
107 our $remotename = 'dgit';
108 our @ourdscfield = qw(Dgit Vcs-Dgit-Master);
112 sub lbranch () { return "$branchprefix/$csuite"; }
113 my $lbranch_re = '^refs/heads/'.$branchprefix.'/([^/.]+)$';
114 sub lref () { return "refs/heads/".lbranch(); }
115 sub lrref () { return "refs/remotes/$remotename/".server_branch($csuite); }
116 sub rrref () { return server_ref($csuite); }
126 return "${package}_".(stripepoch $vsn).$sfx
131 return srcfn($vsn,".dsc");
135 our $debugprefix = '';
140 foreach my $f (@end) {
142 warn "$us: cleanup: $@" if length $@;
146 our @signames = split / /, $Config{sig_name};
148 sub waitstatusmsg () {
150 return "terminated, reporting successful completion";
151 } elsif (!($? & 255)) {
152 return "failed with error exit status ".WEXITSTATUS($?);
153 } elsif (WIFSIGNALED($?)) {
154 my $signum=WTERMSIG($?);
155 return "died due to fatal signal ".
156 ($signames[$signum] // "number $signum").
157 ($? & 128 ? " (core dumped)" : ""); # POSIX(3pm) has no WCOREDUMP
159 return "failed with unknown wait status ".$?;
163 sub printdebug { print DEBUG $debugprefix, @_ or die $!; }
167 my $prefix = $us.($we_are_responder ? " (build host)" : "").": ";
168 $s =~ s/^/$prefix/gm;
172 sub badcfg { print STDERR "$us: invalid configuration: @_\n"; exit 12; }
174 sub no_such_package () {
175 print STDERR "$us: package $package does not exist in suite $isuite\n";
181 return "+".rrref().":".lrref();
186 printdebug "CD $newdir\n";
187 chdir $newdir or die "chdir: $newdir: $!";
190 sub deliberately ($) {
191 return !!grep { $_[0] eq $_ } @deliberatelies;
194 #---------- remote protocol support, common ----------
196 # remote push initiator/responder protocol:
197 # < dgit-remote-push-ready [optional extra info ignored by old initiators]
199 # > file parsed-changelog
200 # [indicates that output of dpkg-parsechangelog follows]
201 # > data-block NBYTES
202 # > [NBYTES bytes of data (no newline)]
203 # [maybe some more blocks]
215 # [indicates that signed tag is wanted]
216 # < data-block NBYTES
217 # < [NBYTES bytes of data (no newline)]
218 # [maybe some more blocks]
222 # > want signed-dsc-changes
223 # < data-block NBYTES [transfer of signed dsc]
225 # < data-block NBYTES [transfer of signed changes]
233 sub i_child_report () {
234 # Sees if our child has died, and reap it if so. Returns a string
235 # describing how it died if it failed, or undef otherwise.
236 return undef unless $i_child_pid;
237 my $got = waitpid $i_child_pid, WNOHANG;
238 return undef if $got <= 0;
239 die unless $got == $i_child_pid;
240 $i_child_pid = undef;
241 return undef unless $?;
242 return "build host child ".waitstatusmsg();
247 fail "connection lost: $!" if $fh->error;
248 fail "protocol violation; $m not expected";
251 sub badproto_badread ($$) {
253 fail "connection lost: $!" if $!;
254 my $report = i_child_report();
255 fail $report if defined $report;
256 badproto $fh, "eof (reading $wh)";
259 sub protocol_expect (&$) {
260 my ($match, $fh) = @_;
263 defined && chomp or badproto_badread $fh, "protocol message";
271 badproto $fh, "\`$_'";
274 sub protocol_send_file ($$) {
275 my ($fh, $ourfn) = @_;
276 open PF, "<", $ourfn or die "$ourfn: $!";
279 my $got = read PF, $d, 65536;
280 die "$ourfn: $!" unless defined $got;
282 print $fh "data-block ".length($d)."\n" or die $!;
283 print $fh $d or die $!;
285 PF->error and die "$ourfn $!";
286 print $fh "data-end\n" or die $!;
290 sub protocol_read_bytes ($$) {
291 my ($fh, $nbytes) = @_;
292 $nbytes =~ m/^[1-9]\d{0,5}$/ or badproto \*RO, "bad byte count";
294 my $got = read $fh, $d, $nbytes;
295 $got==$nbytes or badproto_badread $fh, "data block";
299 sub protocol_receive_file ($$) {
300 my ($fh, $ourfn) = @_;
301 printdebug "() $ourfn\n";
302 open PF, ">", $ourfn or die "$ourfn: $!";
304 my ($y,$l) = protocol_expect {
305 m/^data-block (.*)$/ ? (1,$1) :
306 m/^data-end$/ ? (0,) :
310 my $d = protocol_read_bytes $fh, $l;
311 print PF $d or die $!;
316 #---------- remote protocol support, responder ----------
318 sub responder_send_command ($) {
320 return unless $we_are_responder;
321 # called even without $we_are_responder
322 printdebug ">> $command\n";
323 print PO $command, "\n" or die $!;
326 sub responder_send_file ($$) {
327 my ($keyword, $ourfn) = @_;
328 return unless $we_are_responder;
329 printdebug "]] $keyword $ourfn\n";
330 responder_send_command "file $keyword";
331 protocol_send_file \*PO, $ourfn;
334 sub responder_receive_files ($@) {
335 my ($keyword, @ourfns) = @_;
336 die unless $we_are_responder;
337 printdebug "[[ $keyword @ourfns\n";
338 responder_send_command "want $keyword";
339 foreach my $fn (@ourfns) {
340 protocol_receive_file \*PI, $fn;
343 protocol_expect { m/^files-end$/ } \*PI;
346 #---------- remote protocol support, initiator ----------
348 sub initiator_expect (&) {
350 protocol_expect { &$match } \*RO;
353 #---------- end remote code ----------
356 if ($we_are_responder) {
358 responder_send_command "progress ".length($m) or die $!;
359 print PO $m or die $!;
369 $ua = LWP::UserAgent->new();
373 progress "downloading $what...";
374 my $r = $ua->get(@_) or die $!;
375 return undef if $r->code == 404;
376 $r->is_success or fail "failed to fetch $what: ".$r->status_line;
377 return $r->decoded_content(charset => 'none');
380 our ($dscdata,$dscurl,$dsc,$dsc_checked,$skew_warning_vsn);
387 if (m{[^-=_./0-9a-z]}i) {
394 return join ' ', @out;
399 my $intro = shift @_;
400 print $fh $intro," " or die $!;
401 print $fh shellquote @_ or die $!;
402 print $fh "\n" or die $!;
406 { local ($!); printcmd \*STDERR, "$us: failed command:", @_ or die $!; };
408 fail "failed to fork/exec: $!";
410 fail "subprocess ".waitstatusmsg();
412 fail "subprocess produced invalid output";
417 printcmd(\*DEBUG,$debugprefix."+",@_) if $debug>0;
419 failedcmd @_ if system @_;
422 sub act_local () { return $dryrun_level <= 1; }
423 sub act_scary () { return !$dryrun_level; }
426 if (!$dryrun_level) {
427 progress "dgit ok: @_";
429 progress "would be ok: @_ (but dry run only)";
433 sub cmdoutput_errok {
434 die Dumper(\@_)." ?" if grep { !defined } @_;
435 printcmd(\*DEBUG,$debugprefix."|",@_) if $debug>0;
436 open P, "-|", @_ or die $!;
439 { local $/ = undef; $d = <P>; }
441 if (!close P) { printdebug "=>!$?\n" if $debug>0; return undef; }
444 printdebug "=> \`$&'",(length $' ? '...' : ''),"\n" if $debug>0; #';
449 my $d = cmdoutput_errok @_;
450 defined $d or failedcmd @_;
455 printcmd(\*STDERR,$debugprefix."#",@_);
458 sub runcmd_ordryrun {
466 sub runcmd_ordryrun_local {
475 my ($first_shell, @cmd) = @_;
476 return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
479 our $helpmsg = <<END;
481 dgit [dgit-opts] clone [dgit-opts] package [suite] [./dir|/dir]
482 dgit [dgit-opts] fetch|pull [dgit-opts] [suite]
483 dgit [dgit-opts] build [git-buildpackage-opts|dpkg-buildpackage-opts]
484 dgit [dgit-opts] push [dgit-opts] [suite]
485 dgit [dgit-opts] rpush build-host:build-dir ...
486 important dgit options:
487 -k<keyid> sign tag and package with <keyid> instead of default
488 --dry-run -n do not change anything, but go through the motions
489 --damp-run -L like --dry-run but make local changes, without signing
490 --new -N allow introducing a new package
491 --debug -D increase debug level
492 -c<name>=<value> set git config option (used directly by dgit too)
495 our $later_warning_msg = <<END;
496 Perhaps the upload is stuck in incoming. Using the version from git.
500 print STDERR "$us: @_\n", $helpmsg or die $!;
505 @ARGV or badusage "too few arguments";
506 return scalar shift @ARGV;
510 print $helpmsg or die $!;
514 our $td = $ENV{DGIT_TEST_DUMMY_DIR} || "DGIT_TEST_DUMMY_DIR-unset";
516 our %defcfg = ('dgit.default.distro' => 'debian',
517 'dgit.default.username' => '',
518 'dgit.default.archive-query-default-component' => 'main',
519 'dgit.default.ssh' => 'ssh',
520 'dgit.default.archive-query' => 'madison:',
521 'dgit.default.sshpsql-dbname' => 'service=projectb',
522 'dgit-distro.debian.archive-query' => 'ftpmasterapi:',
523 'dgit-distro.debian.git-host' => 'dgit-git.debian.net',
524 'dgit-distro.debian.git-user-force' => 'dgit',
525 'dgit-distro.debian.git-proto' => 'git+ssh://',
526 'dgit-distro.debian.git-path' => '/dgit/debian/repos',
527 'dgit-distro.debian.git-check' => 'ssh-cmd',
528 'dgit-distro.debian.archive-query-url', 'https://api.ftp-master.debian.org/',
529 'dgit-distro.debian.archive-query-tls-key',
530 '/etc/ssl/certs/%HOST%.pem:/etc/dgit/%HOST%.pem',
531 'dgit-distro.debian.diverts.alioth' => '/alioth',
532 'dgit-distro.debian/alioth.git-host' => 'git.debian.org',
533 'dgit-distro.debian/alioth.git-user-force' => '',
534 'dgit-distro.debian/alioth.git-proto' => 'git+ssh://',
535 'dgit-distro.debian/alioth.git-path' => '/git/dgit-repos/repos',
536 'dgit-distro.debian/alioth.git-create' => 'ssh-cmd',
537 'dgit-distro.debian.upload-host' => 'ftp-master', # for dput
538 'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/',
539 'dgit-distro.debian.backports-quirk' => '(squeeze)-backports*',
540 'dgit-distro.debian-backports.mirror' => 'http://backports.debian.org/debian-backports/',
541 'dgit-distro.ubuntu.git-check' => 'false',
542 'dgit-distro.ubuntu.mirror' => 'http://archive.ubuntu.com/ubuntu',
543 'dgit-distro.test-dummy.ssh' => "$td/ssh",
544 'dgit-distro.test-dummy.username' => "alice",
545 'dgit-distro.test-dummy.git-check' => "ssh-cmd",
546 'dgit-distro.test-dummy.git-create' => "ssh-cmd",
547 'dgit-distro.test-dummy.git-url' => "$td/git",
548 'dgit-distro.test-dummy.git-host' => "git",
549 'dgit-distro.test-dummy.git-path' => "$td/git",
550 'dgit-distro.test-dummy.archive-query' => "ftpmasterapi:",
551 'dgit-distro.test-dummy.archive-query-url' => "file://$td/aq/",
552 'dgit-distro.test-dummy.mirror' => "file://$td/mirror/",
553 'dgit-distro.test-dummy.upload-host' => 'test-dummy',
558 return undef if $c =~ /RETURN-UNDEF/;
559 my @cmd = (@git, qw(config --), $c);
562 local ($debug) = $debug-1;
563 $v = cmdoutput_errok @cmd;
570 my $dv = $defcfg{$c};
571 return $dv if defined $dv;
573 badcfg "need value for one of: @_\n".
574 "$us: distro or suite appears not to be (properly) supported";
577 sub access_basedistro () {
578 if (defined $idistro) {
581 return cfg("dgit-suite.$isuite.distro",
582 "dgit.default.distro");
586 sub access_quirk () {
587 # returns (quirk name, distro to use instead or undef, quirk-specific info)
588 my $basedistro = access_basedistro();
589 my $backports_quirk = cfg("dgit-distro.$basedistro.backports-quirk",
591 if (defined $backports_quirk) {
592 my $re = $backports_quirk;
593 $re =~ s/[^-0-9a-z_\%*()]/\\$&/ig;
595 $re =~ s/\%/([-0-9a-z_]+)/
596 or $re =~ m/[()]/ or badcfg "backports-quirk needs \% or ( )";
597 if ($isuite =~ m/^$re$/) {
598 return ('backports',"$basedistro-backports",$1);
601 return ('none',undef);
604 sub access_distros () {
605 # Returns list of distros to try, in order
608 # 0. `instead of' distro name(s) we have been pointed to
609 # 1. the access_quirk distro, if any
610 # 2a. the user's specified distro, or failing that } basedistro
611 # 2b. the distro calculated from the suite }
612 my @l = access_basedistro();
614 my (undef,$quirkdistro) = access_quirk();
615 unshift @l, $quirkdistro;
616 unshift @l, $instead_distro;
617 return grep { defined } @l;
623 # The nesting of these loops determines the search order. We put
624 # the key loop on the outside so that we search all the distros
625 # for each key, before going on to the next key. That means that
626 # if access_cfg is called with a more specific, and then a less
627 # specific, key, an earlier distro can override the less specific
628 # without necessarily overriding any more specific keys. (If the
629 # distro wants to override the more specific keys it can simply do
630 # so; whereas if we did the loop the other way around, it would be
631 # impossible to for an earlier distro to override a less specific
632 # key but not the more specific ones without restating the unknown
633 # values of the more specific keys.
636 # We have to deal with RETURN-UNDEF specially, so that we don't
637 # terminate the search prematurely.
639 if (m/RETURN-UNDEF/) { push @rundef, $_; last; }
642 foreach my $d (access_distros()) {
643 push @cfgs, map { "dgit-distro.$d.$_" } @realkeys;
645 push @cfgs, map { "dgit.default.$_" } @realkeys;
647 my $value = cfg(@cfgs);
651 sub string_to_ssh ($) {
653 if ($spec =~ m/\s/) {
654 return qw(sh -ec), 'exec '.$spec.' "$@"', 'x';
660 sub access_cfg_ssh () {
661 my $gitssh = access_cfg('ssh', 'RETURN-UNDEF');
662 if (!defined $gitssh) {
665 return string_to_ssh $gitssh;
669 sub access_runeinfo ($) {
671 return ": dgit ".access_basedistro()." $info ;";
674 sub access_someuserhost ($) {
676 my $user = access_cfg("$some-user-force", 'RETURN-UNDEF');
677 defined($user) && length($user) or
678 $user = access_cfg("$some-user",'username');
679 my $host = access_cfg("$some-host");
680 return length($user) ? "$user\@$host" : $host;
683 sub access_gituserhost () {
684 return access_someuserhost('git');
687 sub access_giturl (;$) {
689 my $url = access_cfg('git-url','RETURN-UNDEF');
691 my $proto = access_cfg('git-proto', 'RETURN-UNDEF');
692 return undef unless defined $proto;
695 access_gituserhost().
696 access_cfg('git-path');
698 return "$url/$package.git";
701 sub parsecontrolfh ($$;$) {
702 my ($fh, $desc, $allowsigned) = @_;
703 our $dpkgcontrolhash_noissigned;
706 my %opts = ('name' => $desc);
707 $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
708 $c = Dpkg::Control::Hash->new(%opts);
709 $c->parse($fh,$desc) or die "parsing of $desc failed";
710 last if $allowsigned;
711 last if $dpkgcontrolhash_noissigned;
712 my $issigned= $c->get_option('is_pgp_signed');
713 if (!defined $issigned) {
714 $dpkgcontrolhash_noissigned= 1;
715 seek $fh, 0,0 or die "seek $desc: $!";
716 } elsif ($issigned) {
717 fail "control file $desc is (already) PGP-signed. ".
718 " Note that dgit push needs to modify the .dsc and then".
719 " do the signature itself";
728 my ($file, $desc) = @_;
729 my $fh = new IO::Handle;
730 open $fh, '<', $file or die "$file: $!";
731 my $c = parsecontrolfh($fh,$desc);
732 $fh->error and die $!;
738 my ($dctrl,$field) = @_;
739 my $v = $dctrl->{$field};
740 return $v if defined $v;
741 fail "missing field $field in ".$v->get_option('name');
745 my $c = Dpkg::Control::Hash->new();
746 my $p = new IO::Handle;
747 my @cmd = (qw(dpkg-parsechangelog), @_);
748 open $p, '-|', @cmd or die $!;
750 $?=0; $!=0; close $p or failedcmd @cmd;
754 sub git_get_ref ($) {
756 my $got = cmdoutput_errok @git, qw(show-ref --), $refname;
758 $?==256 or fail "git show-ref failed (status $?)";
759 printdebug "ref $refname= [show-ref exited 1]\n";
762 if ($got =~ m/^(\w+) \Q$refname\E$/m) {
763 printdebug "ref $refname=$1\n";
766 printdebug "ref $refname= [no match]\n";
773 defined $d or fail "getcwd failed: $!";
779 sub archive_query ($) {
781 my $query = access_cfg('archive-query','RETURN-UNDEF');
782 $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
785 { no strict qw(refs); &{"${method}_${proto}"}($proto,$data); }
788 sub pool_dsc_subpath ($$) {
789 my ($vsn,$component) = @_; # $package is implict arg
790 my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
791 return "/pool/$component/$prefix/$package/".dscfn($vsn);
794 #---------- `ftpmasterapi' archive query method (nascent) ----------
796 sub archive_api_query_cmd ($) {
798 my @cmd = qw(curl -sS);
799 my $url = access_cfg('archive-query-url');
800 if ($url =~ m#^https://([-.0-9a-z]+)/#) {
802 my $keys = access_cfg('archive-query-tls-key','RETURN-UNDEF');
803 foreach my $key (split /\:/, $keys) {
804 $key =~ s/\%HOST\%/$host/g;
806 fail "for $url: stat $key: $!" unless $!==ENOENT;
809 push @cmd, "--ca-certificate=$key", "--ca-directory=/dev/enoent";
813 push @cmd, $url.$subpath;
819 my ($data, $subpath) = @_;
820 badcfg "ftpmasterapi archive query method takes no data part"
822 my @cmd = archive_api_query_cmd($subpath);
823 my $json = cmdoutput @cmd;
824 return decode_json($json);
827 sub canonicalise_suite_ftpmasterapi () {
828 my ($proto,$data) = @_;
829 my $suites = api_query($data, 'suites');
831 foreach my $entry (@$suites) {
833 my $v = $entry->{$_};
834 defined $v && $v eq $isuite;
836 push @matched, $entry;
838 fail "unknown suite $isuite" unless @matched;
841 @matched==1 or die "multiple matches for suite $isuite\n";
842 $cn = "$matched[0]{codename}";
843 defined $cn or die "suite $isuite info has no codename\n";
844 $cn =~ m/^$suite_re$/ or die "suite $isuite maps to bad codename\n";
846 die "bad ftpmaster api response: $@\n".Dumper(\@matched)
851 sub archive_query_ftpmasterapi () {
852 my ($proto,$data) = @_;
853 my $info = api_query($data, "dsc_in_suite/$isuite/$package");
855 my $digester = Digest::SHA->new(256);
856 foreach my $entry (@$info) {
858 my $vsn = "$entry->{version}";
859 my ($ok,$msg) = version_check $vsn;
860 die "bad version: $msg\n" unless $ok;
861 my $component = "$entry->{component}";
862 $component =~ m/^$component_re$/ or die "bad component";
863 my $filename = "$entry->{filename}";
864 $filename && $filename !~ m#[^-+:._~0-9a-zA-Z/]|^[/.]|/[/.]#
865 or die "bad filename";
866 my $sha256sum = "$entry->{sha256sum}";
867 $sha256sum =~ m/^[0-9a-f]+$/ or die "bad sha256sum";
868 push @rows, [ $vsn, "/pool/$component/$filename",
869 $digester, $sha256sum ];
871 die "bad ftpmaster api response: $@\n".Dumper($entry)
874 @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
878 #---------- `madison' archive query method ----------
880 sub archive_query_madison {
881 return map { [ @$_[0..1] ] } madison_get_parse(@_);
884 sub madison_get_parse {
885 my ($proto,$data) = @_;
886 die unless $proto eq 'madison';
888 $data= access_cfg('madison-distro','RETURN-UNDEF');
889 $data //= access_basedistro();
891 $rmad{$proto,$data,$package} ||= cmdoutput
892 qw(rmadison -asource),"-s$isuite","-u$data",$package;
893 my $rmad = $rmad{$proto,$data,$package};
896 foreach my $l (split /\n/, $rmad) {
897 $l =~ m{^ \s*( [^ \t|]+ )\s* \|
898 \s*( [^ \t|]+ )\s* \|
899 \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
900 \s*( [^ \t|]+ )\s* }x or die "$rmad ?";
901 $1 eq $package or die "$rmad $package ?";
908 $component = access_cfg('archive-query-default-component');
910 $5 eq 'source' or die "$rmad ?";
911 push @out, [$vsn,pool_dsc_subpath($vsn,$component),$newsuite];
913 return sort { -version_compare($a->[0],$b->[0]); } @out;
916 sub canonicalise_suite_madison {
917 # madison canonicalises for us
918 my @r = madison_get_parse(@_);
920 "unable to canonicalise suite using package $package".
921 " which does not appear to exist in suite $isuite;".
922 " --existing-package may help";
926 #---------- `sshpsql' archive query method ----------
929 my ($data,$runeinfo,$sql) = @_;
931 $data= access_someuserhost('sshpsql').':'.
932 access_cfg('sshpsql-dbname');
934 $data =~ m/:/ or badcfg "invalid sshpsql method string \`$data'";
935 my ($userhost,$dbname) = ($`,$'); #';
937 my @cmd = (access_cfg_ssh, $userhost,
938 access_runeinfo("ssh-psql $runeinfo").
939 " export LC_MESSAGES=C; export LC_CTYPE=C;".
940 " ".shellquote qw(psql -A), $dbname, qw(-c), $sql);
941 printcmd(\*DEBUG,$debugprefix."|",@cmd) if $debug>0;
942 open P, "-|", @cmd or die $!;
945 printdebug("$debugprefix>|$_|\n");
948 $!=0; $?=0; close P or failedcmd @cmd;
950 my $nrows = pop @rows;
951 $nrows =~ s/^\((\d+) rows?\)$/$1/ or die "$nrows ?";
952 @rows == $nrows+1 or die "$nrows ".(scalar @rows)." ?";
953 @rows = map { [ split /\|/, $_ ] } @rows;
954 my $ncols = scalar @{ shift @rows };
955 die if grep { scalar @$_ != $ncols } @rows;
959 sub sql_injection_check {
960 foreach (@_) { die "$_ $& ?" if m{[^-+=:_.,/0-9a-zA-Z]}; }
963 sub archive_query_sshpsql ($$) {
964 my ($proto,$data) = @_;
965 sql_injection_check $isuite, $package;
966 my @rows = sshpsql($data, "archive-query $isuite $package", <<END);
967 SELECT source.version, component.name, files.filename, files.sha256sum
969 JOIN src_associations ON source.id = src_associations.source
970 JOIN suite ON suite.id = src_associations.suite
971 JOIN dsc_files ON dsc_files.source = source.id
972 JOIN files_archive_map ON files_archive_map.file_id = dsc_files.file
973 JOIN component ON component.id = files_archive_map.component_id
974 JOIN files ON files.id = dsc_files.file
975 WHERE ( suite.suite_name='$isuite' OR suite.codename='$isuite' )
976 AND source.source='$package'
977 AND files.filename LIKE '%.dsc';
979 @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
980 my $digester = Digest::SHA->new(256);
982 my ($vsn,$component,$filename,$sha256sum) = @$_;
983 [ $vsn, "/pool/$component/$filename",$digester,$sha256sum ];
988 sub canonicalise_suite_sshpsql ($$) {
989 my ($proto,$data) = @_;
990 sql_injection_check $isuite;
991 my @rows = sshpsql($data, "canonicalise-suite $isuite", <<END);
992 SELECT suite.codename
993 FROM suite where suite_name='$isuite' or codename='$isuite';
995 @rows = map { $_->[0] } @rows;
996 fail "unknown suite $isuite" unless @rows;
997 die "ambiguous $isuite: @rows ?" if @rows>1;
1001 #---------- `dummycat' archive query method ----------
1003 sub canonicalise_suite_dummycat ($$) {
1004 my ($proto,$data) = @_;
1005 my $dpath = "$data/suite.$isuite";
1006 if (!open C, "<", $dpath) {
1007 $!==ENOENT or die "$dpath: $!";
1008 printdebug "dummycat canonicalise_suite $isuite $dpath ENOENT\n";
1012 chomp or die "$dpath: $!";
1014 printdebug "dummycat canonicalise_suite $isuite $dpath = $_\n";
1018 sub archive_query_dummycat ($$) {
1019 my ($proto,$data) = @_;
1020 canonicalise_suite();
1021 my $dpath = "$data/package.$csuite.$package";
1022 if (!open C, "<", $dpath) {
1023 $!==ENOENT or die "$dpath: $!";
1024 printdebug "dummycat query $csuite $package $dpath ENOENT\n";
1032 printdebug "dummycat query $csuite $package $dpath | $_\n";
1033 my @row = split /\s+/, $_;
1034 @row==2 or die "$dpath: $_ ?";
1037 C->error and die "$dpath: $!";
1039 return sort { -version_compare($a->[0],$b->[0]); } @rows;
1042 #---------- archive query entrypoints and rest of program ----------
1044 sub canonicalise_suite () {
1045 return if defined $csuite;
1046 fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
1047 $csuite = archive_query('canonicalise_suite');
1048 if ($isuite ne $csuite) {
1049 progress "canonical suite name for $isuite is $csuite";
1053 sub get_archive_dsc () {
1054 canonicalise_suite();
1055 my @vsns = archive_query('archive_query');
1056 foreach my $vinfo (@vsns) {
1057 my ($vsn,$subpath,$digester,$digest) = @$vinfo;
1058 $dscurl = access_cfg('mirror').$subpath;
1059 $dscdata = url_get($dscurl);
1061 $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
1066 $digester->add($dscdata);
1067 my $got = $digester->hexdigest();
1069 fail "$dscurl has hash $got but".
1070 " archive told us to expect $digest";
1072 my $dscfh = new IO::File \$dscdata, '<' or die $!;
1073 printdebug Dumper($dscdata) if $debug>1;
1074 $dsc = parsecontrolfh($dscfh,$dscurl,1);
1075 printdebug Dumper($dsc) if $debug>1;
1076 my $fmt = getfield $dsc, 'Format';
1077 fail "unsupported source format $fmt, sorry" unless $format_ok{$fmt};
1078 $dsc_checked = !!$digester;
1084 sub check_for_git ();
1085 sub check_for_git () {
1087 my $how = access_cfg('git-check');
1088 if ($how eq 'ssh-cmd') {
1090 (access_cfg_ssh, access_gituserhost(),
1091 access_runeinfo("git-check $package").
1092 " set -e; cd ".access_cfg('git-path').";".
1093 " if test -d $package.git; then echo 1; else echo 0; fi");
1094 my $r= cmdoutput @cmd;
1095 if ($r =~ m/^divert (\w+)$/) {
1097 my ($usedistro,) = access_distros();
1098 $instead_distro= cfg("dgit-distro.$usedistro.diverts.$divert");
1099 $instead_distro =~ s{^/}{ access_basedistro()."/" }e;
1100 printdebug "diverting $divert so using distro $instead_distro\n";
1101 return check_for_git();
1103 failedcmd @cmd unless $r =~ m/^[01]$/;
1105 } elsif ($how eq 'true') {
1107 } elsif ($how eq 'false') {
1110 badcfg "unknown git-check \`$how'";
1114 sub create_remote_git_repo () {
1115 my $how = access_cfg('git-create');
1116 if ($how eq 'ssh-cmd') {
1118 (access_cfg_ssh, access_gituserhost(),
1119 access_runeinfo("git-create $package").
1120 "set -e; cd ".access_cfg('git-path').";".
1121 " cp -a _template $package.git");
1122 } elsif ($how eq 'true') {
1125 badcfg "unknown git-create \`$how'";
1129 our ($dsc_hash,$lastpush_hash);
1131 our $ud = '.git/dgit/unpack';
1136 mkdir $ud or die $!;
1139 sub mktree_in_ud_here () {
1140 runcmd qw(git init -q);
1141 rmtree('.git/objects');
1142 symlink '../../../../objects','.git/objects' or die $!;
1145 sub git_write_tree () {
1146 my $tree = cmdoutput @git, qw(write-tree);
1147 $tree =~ m/^\w+$/ or die "$tree ?";
1151 sub mktree_in_ud_from_only_subdir () {
1152 # changes into the subdir
1154 die unless @dirs==1;
1155 $dirs[0] =~ m#^([^/]+)/\.$# or die;
1158 fail "source package contains .git directory" if stat_exists '.git';
1159 mktree_in_ud_here();
1160 my $format=get_source_format();
1161 if (madformat($format)) {
1164 runcmd @git, qw(add -Af);
1165 my $tree=git_write_tree();
1166 return ($tree,$dir);
1169 sub dsc_files_info () {
1170 foreach my $csumi (['Checksums-Sha256','Digest::SHA', 'new(256)'],
1171 ['Checksums-Sha1', 'Digest::SHA', 'new(1)'],
1172 ['Files', 'Digest::MD5', 'new()']) {
1173 my ($fname, $module, $method) = @$csumi;
1174 my $field = $dsc->{$fname};
1175 next unless defined $field;
1176 eval "use $module; 1;" or die $@;
1178 foreach (split /\n/, $field) {
1180 m/^(\w+) (\d+) (\S+)$/ or
1181 fail "could not parse .dsc $fname line \`$_'";
1182 my $digester = eval "$module"."->$method;" or die $@;
1187 Digester => $digester,
1192 fail "missing any supported Checksums-* or Files field in ".
1193 $dsc->get_option('name');
1197 map { $_->{Filename} } dsc_files_info();
1200 sub is_orig_file ($;$) {
1203 m/\.orig(?:-\w+)?\.tar\.\w+$/ or return 0;
1204 defined $base or return 1;
1208 sub make_commit ($) {
1210 return cmdoutput @git, qw(hash-object -w -t commit), $file;
1213 sub clogp_authline ($) {
1215 my $author = getfield $clogp, 'Maintainer';
1216 $author =~ s#,.*##ms;
1217 my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
1218 my $authline = "$author $date";
1219 $authline =~ m/^[^<>]+ \<\S+\> \d+ [-+]\d+$/ or
1220 fail "unexpected commit author line format \`$authline'".
1221 " (was generated from changelog Maintainer field)";
1225 sub generate_commit_from_dsc () {
1229 foreach my $fi (dsc_files_info()) {
1230 my $f = $fi->{Filename};
1231 die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
1233 link "../../../$f", $f
1237 complete_file_from_dsc('.', $fi);
1239 if (is_orig_file($f)) {
1240 link $f, "../../../../$f"
1246 my $dscfn = "$package.dsc";
1248 open D, ">", $dscfn or die "$dscfn: $!";
1249 print D $dscdata or die "$dscfn: $!";
1250 close D or die "$dscfn: $!";
1251 my @cmd = qw(dpkg-source);
1252 push @cmd, '--no-check' if $dsc_checked;
1253 push @cmd, qw(-x --), $dscfn;
1256 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1257 runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
1258 my $clogp = parsecontrol('../changelog.tmp',"commit's changelog");
1259 my $authline = clogp_authline $clogp;
1260 my $changes = getfield $clogp, 'Changes';
1261 open C, ">../commit.tmp" or die $!;
1262 print C <<END or die $!;
1269 # imported from the archive
1272 my $outputhash = make_commit qw(../commit.tmp);
1273 my $cversion = getfield $clogp, 'Version';
1274 progress "synthesised git commit from .dsc $cversion";
1275 if ($lastpush_hash) {
1276 runcmd @git, qw(reset --hard), $lastpush_hash;
1277 runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
1278 my $oldclogp = parsecontrol('../changelogold.tmp','previous changelog');
1279 my $oversion = getfield $oldclogp, 'Version';
1281 version_compare($oversion, $cversion);
1283 # git upload/ is earlier vsn than archive, use archive
1284 open C, ">../commit2.tmp" or die $!;
1285 print C <<END or die $!;
1287 parent $lastpush_hash
1292 Record $package ($cversion) in archive suite $csuite
1294 $outputhash = make_commit qw(../commit2.tmp);
1295 } elsif ($vcmp > 0) {
1296 print STDERR <<END or die $!;
1298 Version actually in archive: $cversion (older)
1299 Last allegedly pushed/uploaded: $oversion (newer or same)
1302 $outputhash = $lastpush_hash;
1304 $outputhash = $lastpush_hash;
1307 changedir '../../../..';
1308 runcmd @git, qw(update-ref -m),"dgit fetch import $cversion",
1309 'DGIT_ARCHIVE', $outputhash;
1310 cmdoutput @git, qw(log -n2), $outputhash;
1311 # ... gives git a chance to complain if our commit is malformed
1316 sub complete_file_from_dsc ($$) {
1317 our ($dstdir, $fi) = @_;
1318 # Ensures that we have, in $dir, the file $fi, with the correct
1319 # contents. (Downloading it from alongside $dscurl if necessary.)
1321 my $f = $fi->{Filename};
1322 my $tf = "$dstdir/$f";
1325 if (stat_exists $tf) {
1326 progress "using existing $f";
1329 $furl =~ s{/[^/]+$}{};
1331 die "$f ?" unless $f =~ m/^${package}_/;
1332 die "$f ?" if $f =~ m#/#;
1333 runcmd_ordryrun_local @curl,qw(-o),$tf,'--',"$furl";
1334 next if !act_local();
1338 open F, "<", "$tf" or die "$tf: $!";
1339 $fi->{Digester}->reset();
1340 $fi->{Digester}->addfile(*F);
1341 F->error and die $!;
1342 my $got = $fi->{Digester}->hexdigest();
1343 $got eq $fi->{Hash} or
1344 fail "file $f has hash $got but .dsc".
1345 " demands hash $fi->{Hash} ".
1346 ($downloaded ? "(got wrong file from archive!)"
1347 : "(perhaps you should delete this file?)");
1350 sub ensure_we_have_orig () {
1351 foreach my $fi (dsc_files_info()) {
1352 my $f = $fi->{Filename};
1353 next unless is_orig_file($f);
1354 complete_file_from_dsc('..', $fi);
1359 return cmdoutput @git, qw(rev-parse), "$_[0]~0";
1362 sub is_fast_fwd ($$) {
1363 my ($ancestor,$child) = @_;
1364 my @cmd = (@git, qw(merge-base), $ancestor, $child);
1365 my $mb = cmdoutput_errok @cmd;
1367 return rev_parse($mb) eq rev_parse($ancestor);
1369 $?==256 or failedcmd @cmd;
1374 sub git_fetch_us () {
1375 runcmd_ordryrun_local @git, qw(fetch),access_giturl(),fetchspec();
1378 sub fetch_from_archive () {
1379 # ensures that lrref() is what is actually in the archive,
1380 # one way or another
1384 foreach my $field (@ourdscfield) {
1385 $dsc_hash = $dsc->{$field};
1386 last if defined $dsc_hash;
1388 if (defined $dsc_hash) {
1389 $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
1391 progress "last upload to archive specified git hash";
1393 progress "last upload to archive has NO git hash";
1396 progress "no version available from the archive";
1399 $lastpush_hash = git_get_ref(lrref());
1400 printdebug "previous reference hash=$lastpush_hash\n";
1402 if (defined $dsc_hash) {
1403 fail "missing remote git history even though dsc has hash -".
1404 " could not find ref ".lrref().
1405 " (should have been fetched from ".access_giturl()."#".rrref().")"
1406 unless $lastpush_hash;
1408 ensure_we_have_orig();
1409 if ($dsc_hash eq $lastpush_hash) {
1410 } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
1411 print STDERR <<END or die $!;
1413 Git commit in archive is behind the last version allegedly pushed/uploaded.
1414 Commit referred to by archive: $dsc_hash
1415 Last allegedly pushed/uploaded: $lastpush_hash
1418 $hash = $lastpush_hash;
1420 fail "git head (".lrref()."=$lastpush_hash) is not a ".
1421 "descendant of archive's .dsc hash ($dsc_hash)";
1424 $hash = generate_commit_from_dsc();
1425 } elsif ($lastpush_hash) {
1426 # only in git, not in the archive yet
1427 $hash = $lastpush_hash;
1428 print STDERR <<END or die $!;
1430 Package not found in the archive, but has allegedly been pushed using dgit.
1434 printdebug "nothing found!\n";
1435 if (defined $skew_warning_vsn) {
1436 print STDERR <<END or die $!;
1438 Warning: relevant archive skew detected.
1439 Archive allegedly contains $skew_warning_vsn
1440 But we were not able to obtain any version from the archive or git.
1446 printdebug "current hash=$hash\n";
1447 if ($lastpush_hash) {
1448 fail "not fast forward on last upload branch!".
1449 " (archive's version left in DGIT_ARCHIVE)"
1450 unless is_fast_fwd($lastpush_hash, $hash);
1452 if (defined $skew_warning_vsn) {
1454 printdebug "SKEW CHECK WANT $skew_warning_vsn\n";
1455 my $clogf = ".git/dgit/changelog.tmp";
1456 runcmd shell_cmd "exec >$clogf",
1457 @git, qw(cat-file blob), "$hash:debian/changelog";
1458 my $gotclogp = parsechangelog("-l$clogf");
1459 my $got_vsn = getfield $gotclogp, 'Version';
1460 printdebug "SKEW CHECK GOT $got_vsn\n";
1461 if (version_compare($got_vsn, $skew_warning_vsn) < 0) {
1462 print STDERR <<END or die $!;
1464 Warning: archive skew detected. Using the available version:
1465 Archive allegedly contains $skew_warning_vsn
1466 We were able to obtain only $got_vsn
1471 if ($lastpush_hash ne $hash) {
1472 my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
1476 dryrun_report @upd_cmd;
1484 canonicalise_suite();
1485 badusage "dry run makes no sense with clone" unless act_local();
1486 my $hasgit = check_for_git();
1487 mkdir $dstdir or die "$dstdir $!";
1489 runcmd @git, qw(init -q);
1490 my $giturl = access_giturl(1);
1491 if (defined $giturl) {
1492 runcmd @git, qw(config), "remote.$remotename.fetch", fetchspec();
1493 open H, "> .git/HEAD" or die $!;
1494 print H "ref: ".lref()."\n" or die $!;
1496 runcmd @git, qw(remote add), 'origin', $giturl;
1499 progress "fetching existing git history";
1501 runcmd_ordryrun_local @git, qw(fetch origin);
1503 progress "starting new git history";
1505 fetch_from_archive() or no_such_package;
1506 my $vcsgiturl = $dsc->{'Vcs-Git'};
1507 if (length $vcsgiturl) {
1508 $vcsgiturl =~ s/\s+-b\s+\S+//g;
1509 runcmd @git, qw(remote add vcs-git), $vcsgiturl;
1511 runcmd @git, qw(reset --hard), lrref();
1512 printdone "ready for work in $dstdir";
1516 if (check_for_git()) {
1519 fetch_from_archive() or no_such_package();
1520 printdone "fetched into ".lrref();
1525 runcmd_ordryrun_local @git, qw(merge -m),"Merge from $csuite [dgit]",
1527 printdone "fetched to ".lrref()." and merged into HEAD";
1530 sub check_not_dirty () {
1531 return if $ignoredirty;
1532 my @cmd = (@git, qw(diff --quiet HEAD));
1533 printcmd(\*DEBUG,$debugprefix."+",@cmd) if $debug>0;
1534 $!=0; $?=0; system @cmd;
1535 return if !$! && !$?;
1536 if (!$! && $?==256) {
1537 fail "working tree is dirty (does not match HEAD)";
1543 sub commit_admin ($) {
1546 runcmd_ordryrun_local @git, qw(commit -m), $m;
1549 sub commit_quilty_patch () {
1550 my $output = cmdoutput @git, qw(status --porcelain);
1552 foreach my $l (split /\n/, $output) {
1553 next unless $l =~ m/\S/;
1554 if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
1558 delete $adds{'.pc'}; # if there wasn't one before, don't add it
1560 progress "nothing quilty to commit, ok.";
1563 runcmd_ordryrun_local @git, qw(add), sort keys %adds;
1564 commit_admin "Commit Debian 3.0 (quilt) metadata";
1567 sub get_source_format () {
1568 if (!open F, "debian/source/format") {
1569 die $! unless $!==&ENOENT;
1573 F->error and die $!;
1580 return 0 unless $format eq '3.0 (quilt)';
1581 if ($quilt_mode eq 'nocheck') {
1582 progress "Not doing any fixup of \`$format' due to --no-quilt-fixup";
1585 progress "Format \`$format', checking/updating patch stack";
1589 sub push_parse_changelog ($) {
1592 my $clogp = Dpkg::Control::Hash->new();
1593 $clogp->load($clogpfn) or die;
1595 $package = getfield $clogp, 'Source';
1596 my $cversion = getfield $clogp, 'Version';
1597 my $tag = debiantag($cversion);
1598 runcmd @git, qw(check-ref-format), $tag;
1600 my $dscfn = dscfn($cversion);
1602 return ($clogp, $cversion, $tag, $dscfn);
1605 sub push_parse_dsc ($$$) {
1606 my ($dscfn,$dscfnwhat, $cversion) = @_;
1607 $dsc = parsecontrol($dscfn,$dscfnwhat);
1608 my $dversion = getfield $dsc, 'Version';
1609 my $dscpackage = getfield $dsc, 'Source';
1610 ($dscpackage eq $package && $dversion eq $cversion) or
1611 fail "$dscfn is for $dscpackage $dversion".
1612 " but debian/changelog is for $package $cversion";
1615 sub push_mktag ($$$$$$$) {
1616 my ($head,$clogp,$tag,
1618 $changesfile,$changesfilewhat,
1621 $dsc->{$ourdscfield[0]} = $head;
1622 $dsc->save("$dscfn.tmp") or die $!;
1624 my $changes = parsecontrol($changesfile,$changesfilewhat);
1625 foreach my $field (qw(Source Distribution Version)) {
1626 $changes->{$field} eq $clogp->{$field} or
1627 fail "changes field $field \`$changes->{$field}'".
1628 " does not match changelog \`$clogp->{$field}'";
1631 my $cversion = getfield $clogp, 'Version';
1632 my $clogsuite = getfield $clogp, 'Distribution';
1634 # We make the git tag by hand because (a) that makes it easier
1635 # to control the "tagger" (b) we can do remote signing
1636 my $authline = clogp_authline $clogp;
1637 my $delibs = join(" ", "",@deliberatelies);
1638 my $declaredistro = access_basedistro();
1639 open TO, '>', $tfn->('.tmp') or die $!;
1640 print TO <<END or die $!;
1646 $package release $cversion for $clogsuite ($csuite) [dgit]
1647 [dgit distro=$declaredistro$delibs]
1649 foreach my $ref (sort keys %supersedes) {
1650 print TO <<END or die $!;
1651 [dgit supersede:$ref=$supersedes{$ref}]
1657 my $tagobjfn = $tfn->('.tmp');
1659 if (!defined $keyid) {
1660 $keyid = access_cfg('keyid','RETURN-UNDEF');
1662 unlink $tfn->('.tmp.asc') or $!==&ENOENT or die $!;
1663 my @sign_cmd = (@gpg, qw(--detach-sign --armor));
1664 push @sign_cmd, qw(-u),$keyid if defined $keyid;
1665 push @sign_cmd, $tfn->('.tmp');
1666 runcmd_ordryrun @sign_cmd;
1668 $tagobjfn = $tfn->('.signed.tmp');
1669 runcmd shell_cmd "exec >$tagobjfn", qw(cat --),
1670 $tfn->('.tmp'), $tfn->('.tmp.asc');
1677 sub sign_changes ($) {
1678 my ($changesfile) = @_;
1680 my @debsign_cmd = @debsign;
1681 push @debsign_cmd, "-k$keyid" if defined $keyid;
1682 push @debsign_cmd, "-p$gpg[0]" if $gpg[0] ne 'gpg';
1683 push @debsign_cmd, $changesfile;
1684 runcmd_ordryrun @debsign_cmd;
1689 printdebug "actually entering push\n";
1692 access_giturl(); # check that success is vaguely likely
1694 my $clogpfn = ".git/dgit/changelog.822.tmp";
1695 runcmd shell_cmd "exec >$clogpfn", qw(dpkg-parsechangelog);
1697 responder_send_file('parsed-changelog', $clogpfn);
1699 my ($clogp, $cversion, $tag, $dscfn) =
1700 push_parse_changelog("$clogpfn");
1702 my $dscpath = "$buildproductsdir/$dscfn";
1703 stat_exists $dscpath or
1704 fail "looked for .dsc $dscfn, but $!;".
1705 " maybe you forgot to build";
1707 responder_send_file('dsc', $dscpath);
1709 push_parse_dsc($dscpath, $dscfn, $cversion);
1711 my $format = getfield $dsc, 'Format';
1712 printdebug "format $format\n";
1713 if (madformat($format)) {
1714 commit_quilty_patch();
1718 progress "checking that $dscfn corresponds to HEAD";
1719 runcmd qw(dpkg-source -x --),
1720 $dscpath =~ m#^/# ? $dscpath : "../../../$dscpath";
1721 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1722 changedir '../../../..';
1723 my $diffopt = $debug>0 ? '--exit-code' : '--quiet';
1724 my @diffcmd = (@git, qw(diff), $diffopt, $tree);
1725 printcmd \*DEBUG,$debugprefix."+",@diffcmd;
1727 my $r = system @diffcmd;
1730 fail "$dscfn specifies a different tree to your HEAD commit;".
1731 " perhaps you forgot to build".
1732 ($diffopt eq '--exit-code' ? "" :
1733 " (run with -D to see full diff output)");
1739 #do fast forward check and maybe fake merge
1740 # if (!is_fast_fwd(mainbranch
1741 # runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
1742 # map { lref($_).":".rref($_) }
1744 my $head = rev_parse('HEAD');
1745 if (!$changesfile) {
1746 my $multi = "$buildproductsdir/".
1747 "${package}_".(stripepoch $cversion)."_multi.changes";
1748 if (stat_exists "$multi") {
1749 $changesfile = $multi;
1751 my $pat = "${package}_".(stripepoch $cversion)."_*.changes";
1752 my @cs = glob "$buildproductsdir/$pat";
1753 fail "failed to find unique changes file".
1754 " (looked for $pat in $buildproductsdir, or $multi);".
1755 " perhaps you need to use dgit -C"
1757 ($changesfile) = @cs;
1760 $changesfile = "$buildproductsdir/$changesfile";
1763 responder_send_file('changes',$changesfile);
1764 responder_send_command("param head $head");
1765 responder_send_command("param csuite $csuite");
1767 my $forceflag = deliberately('not-fast-forward') ? '+' : '';
1768 if ($forceflag && defined $lastpush_hash) {
1769 git_for_each_tag_referring($lastpush_hash, sub {
1770 my ($objid,$fullrefname,$tagname) = @_;
1771 responder_send_command("supersedes $fullrefname=$objid");
1772 $supersedes{$fullrefname} = $objid;
1776 my $tfn = sub { ".git/dgit/tag$_[0]"; };
1779 if ($we_are_responder) {
1780 $tagobjfn = $tfn->('.signed.tmp');
1781 responder_receive_files('signed-tag', $tagobjfn);
1784 push_mktag($head,$clogp,$tag,
1786 $changesfile,$changesfile,
1790 my $tag_obj_hash = cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
1791 runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
1792 runcmd_ordryrun_local @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
1793 runcmd_ordryrun @git, qw(tag -v --), $tag;
1795 if (!check_for_git()) {
1796 create_remote_git_repo();
1798 runcmd_ordryrun @git, qw(push),access_giturl(),
1799 $forceflag."HEAD:".rrref(), "refs/tags/$tag";
1800 runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), 'HEAD';
1802 if ($we_are_responder) {
1803 my $dryrunsuffix = act_local() ? "" : ".tmp";
1804 responder_receive_files('signed-dsc-changes',
1805 "$dscpath$dryrunsuffix",
1806 "$changesfile$dryrunsuffix");
1809 rename "$dscpath.tmp",$dscpath or die "$dscfn $!";
1811 progress "[new .dsc left in $dscpath.tmp]";
1813 sign_changes $changesfile;
1816 my $host = access_cfg('upload-host','RETURN-UNDEF');
1817 my @hostarg = defined($host) ? ($host,) : ();
1818 runcmd_ordryrun @dput, @hostarg, $changesfile;
1819 printdone "pushed and uploaded $cversion";
1821 responder_send_command("complete");
1827 badusage "-p is not allowed with clone; specify as argument instead"
1828 if defined $package;
1831 } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
1832 ($package,$isuite) = @ARGV;
1833 } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
1834 ($package,$dstdir) = @ARGV;
1835 } elsif (@ARGV==3) {
1836 ($package,$isuite,$dstdir) = @ARGV;
1838 badusage "incorrect arguments to dgit clone";
1840 $dstdir ||= "$package";
1842 if (stat_exists $dstdir) {
1843 fail "$dstdir already exists";
1847 if ($rmonerror && !$dryrun_level) {
1848 $cwd_remove= getcwd();
1850 return unless defined $cwd_remove;
1851 if (!chdir "$cwd_remove") {
1852 return if $!==&ENOENT;
1853 die "chdir $cwd_remove: $!";
1855 rmtree($dstdir) or die "remove $dstdir: $!\n";
1860 $cwd_remove = undef;
1863 sub branchsuite () {
1864 my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
1865 if ($branch =~ m#$lbranch_re#o) {
1872 sub fetchpullargs () {
1873 if (!defined $package) {
1874 my $sourcep = parsecontrol('debian/control','debian/control');
1875 $package = getfield $sourcep, 'Source';
1878 # $isuite = branchsuite(); # this doesn't work because dak hates canons
1880 my $clogp = parsechangelog();
1881 $isuite = getfield $clogp, 'Distribution';
1883 canonicalise_suite();
1884 progress "fetching from suite $csuite";
1885 } elsif (@ARGV==1) {
1887 canonicalise_suite();
1889 badusage "incorrect arguments to dgit fetch or dgit pull";
1907 badusage "-p is not allowed with dgit push" if defined $package;
1909 my $clogp = parsechangelog();
1910 $package = getfield $clogp, 'Source';
1913 } elsif (@ARGV==1) {
1914 ($specsuite) = (@ARGV);
1916 badusage "incorrect arguments to dgit push";
1918 $isuite = getfield $clogp, 'Distribution';
1920 local ($package) = $existing_package; # this is a hack
1921 canonicalise_suite();
1923 if (defined $specsuite && $specsuite ne $isuite) {
1924 canonicalise_suite();
1925 $csuite eq $specsuite or
1926 fail "dgit push: changelog specifies $isuite ($csuite)".
1927 " but command line specifies $specsuite";
1929 if (check_for_git()) {
1932 if (fetch_from_archive()) {
1933 is_fast_fwd(lrref(), 'HEAD') or
1934 fail "dgit push: HEAD is not a descendant".
1935 " of the archive's version.\n".
1936 "$us: To overwrite it, use git merge -s ours ".lrref().".";
1939 fail "package appears to be new in this suite;".
1940 " if this is intentional, use --new";
1945 #---------- remote commands' implementation ----------
1947 sub cmd_remote_push_build_host {
1948 my ($nrargs) = shift @ARGV;
1949 my (@rargs) = @ARGV[0..$nrargs-1];
1950 @ARGV = @ARGV[$nrargs..$#ARGV];
1952 my ($dir,$vsnwant) = @rargs;
1953 # vsnwant is a comma-separated list; we report which we have
1954 # chosen in our ready response (so other end can tell if they
1957 $we_are_responder = 1;
1959 open PI, "<&STDIN" or die $!;
1960 open STDIN, "/dev/null" or die $!;
1961 open PO, ">&STDOUT" or die $!;
1963 open STDOUT, ">&STDERR" or die $!;
1967 fail "build host has dgit rpush protocol version".
1968 " $rpushprotovsn but invocation host has $vsnwant"
1969 unless grep { $rpushprotovsn eq $_ } split /,/, $vsnwant;
1971 responder_send_command("dgit-remote-push-ready $rpushprotovsn");
1977 sub cmd_remote_push_responder { cmd_remote_push_build_host(); }
1978 # ... for compatibility with proto vsn.1 dgit (just so that user gets
1979 # a good error message)
1985 my $report = i_child_report();
1986 if (defined $report) {
1987 printdebug "($report)\n";
1988 } elsif ($i_child_pid) {
1989 printdebug "(killing build host child $i_child_pid)\n";
1990 kill 15, $i_child_pid;
1992 if (defined $i_tmp && !defined $initiator_tempdir) {
1994 eval { rmtree $i_tmp; };
1998 END { i_cleanup(); }
2001 my ($base,$selector,@args) = @_;
2002 $selector =~ s/\-/_/g;
2003 { no strict qw(refs); &{"${base}_${selector}"}(@args); }
2009 if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
2016 my @rargs = ($dir,$rpushprotovsn);
2019 push @rdgit, @ropts;
2020 push @rdgit, qw(remote-push-build-host), (scalar @rargs), @rargs;
2022 my @cmd = (@ssh, $host, shellquote @rdgit);
2023 printcmd \*DEBUG,$debugprefix."+",@cmd;
2025 if (defined $initiator_tempdir) {
2026 rmtree $initiator_tempdir;
2027 mkdir $initiator_tempdir, 0700 or die "$initiator_tempdir: $!";
2028 $i_tmp = $initiator_tempdir;
2032 $i_child_pid = open2(\*RO, \*RI, @cmd);
2034 initiator_expect { m/^dgit-remote-push-ready/ };
2036 my ($icmd,$iargs) = initiator_expect {
2037 m/^(\S+)(?: (.*))?$/;
2040 i_method "i_resp", $icmd, $iargs;
2044 sub i_resp_progress ($) {
2046 my $msg = protocol_read_bytes \*RO, $rhs;
2050 sub i_resp_complete {
2051 my $pid = $i_child_pid;
2052 $i_child_pid = undef; # prevents killing some other process with same pid
2053 printdebug "waiting for build host child $pid...\n";
2054 my $got = waitpid $pid, 0;
2055 die $! unless $got == $pid;
2056 die "build host child failed $?" if $?;
2059 printdebug "all done\n";
2063 sub i_resp_file ($) {
2065 my $localname = i_method "i_localname", $keyword;
2066 my $localpath = "$i_tmp/$localname";
2067 stat_exists $localpath and
2068 badproto \*RO, "file $keyword ($localpath) twice";
2069 protocol_receive_file \*RO, $localpath;
2070 i_method "i_file", $keyword;
2075 sub i_resp_param ($) {
2076 $_[0] =~ m/^(\S+) (.*)$/ or badproto \*RO, "bad param spec";
2080 sub i_resp_supersedes ($) {
2081 $_[0] =~ m#^(refs/tags/\S+)=(\w+)$#
2082 or badproto \*RO, "bad supersedes spec";
2083 my $r = system qw(git check-ref-format), $1;
2084 die "bad supersedes ref spec ($r)" if $r;
2085 $supersedes{$1} = $2;
2090 sub i_resp_want ($) {
2092 die "$keyword ?" if $i_wanted{$keyword}++;
2093 my @localpaths = i_method "i_want", $keyword;
2094 printdebug "[[ $keyword @localpaths\n";
2095 foreach my $localpath (@localpaths) {
2096 protocol_send_file \*RI, $localpath;
2098 print RI "files-end\n" or die $!;
2101 our ($i_clogp, $i_version, $i_tag, $i_dscfn, $i_changesfn);
2103 sub i_localname_parsed_changelog {
2104 return "remote-changelog.822";
2106 sub i_file_parsed_changelog {
2107 ($i_clogp, $i_version, $i_tag, $i_dscfn) =
2108 push_parse_changelog "$i_tmp/remote-changelog.822";
2109 die if $i_dscfn =~ m#/|^\W#;
2112 sub i_localname_dsc {
2113 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
2118 sub i_localname_changes {
2119 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
2120 $i_changesfn = $i_dscfn;
2121 $i_changesfn =~ s/\.dsc$/_dgit.changes/ or die;
2122 return $i_changesfn;
2124 sub i_file_changes { }
2126 sub i_want_signed_tag {
2127 printdebug Dumper(\%i_param, $i_dscfn);
2128 defined $i_param{'head'} && defined $i_dscfn && defined $i_clogp
2129 && defined $i_param{'csuite'}
2130 or badproto \*RO, "premature desire for signed-tag";
2131 my $head = $i_param{'head'};
2132 die if $head =~ m/[^0-9a-f]/ || $head !~ m/^../;
2134 die unless $i_param{'csuite'} =~ m/^$suite_re$/;
2136 push_parse_dsc $i_dscfn, 'remote dsc', $i_version;
2139 push_mktag $head, $i_clogp, $i_tag,
2141 $i_changesfn, 'remote changes',
2142 sub { "tag$_[0]"; };
2147 sub i_want_signed_dsc_changes {
2148 rename "$i_dscfn.tmp","$i_dscfn" or die "$i_dscfn $!";
2149 sign_changes $i_changesfn;
2150 return ($i_dscfn, $i_changesfn);
2153 #---------- building etc. ----------
2159 #----- `3.0 (quilt)' handling -----
2161 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
2163 sub quiltify_dpkg_commit ($$$;$) {
2164 my ($patchname,$author,$msg, $xinfo) = @_;
2168 my $descfn = ".git/dgit/quilt-description.tmp";
2169 open O, '>', $descfn or die "$descfn: $!";
2172 $msg =~ s/^\s+$/ ./mg;
2173 print O <<END or die $!;
2183 local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
2184 local $ENV{'VISUAL'} = $ENV{'EDITOR'};
2185 local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
2186 runcmd_ordryrun_local @dpkgsource, qw(--commit .), $patchname;
2190 sub quiltify_trees_differ ($$) {
2192 # returns 1 iff the two tree objects differ other than in debian/
2194 my @cmd = (@git, qw(diff-tree --name-only -z), $x, $y);
2195 my $diffs= cmdoutput @cmd;
2196 foreach my $f (split /\0/, $diffs) {
2197 next if $f eq 'debian';
2203 sub quiltify_tree_sentinelfiles ($) {
2204 # lists the `sentinel' files present in the tree
2206 my $r = cmdoutput @git, qw(ls-tree --name-only), $x,
2207 qw(-- debian/rules debian/control);
2213 my ($clogp,$target) = @_;
2215 # Quilt patchification algorithm
2217 # We search backwards through the history of the main tree's HEAD
2218 # (T) looking for a start commit S whose tree object is identical
2219 # to to the patch tip tree (ie the tree corresponding to the
2220 # current dpkg-committed patch series). For these purposes
2221 # `identical' disregards anything in debian/ - this wrinkle is
2222 # necessary because dpkg-source treates debian/ specially.
2224 # We can only traverse edges where at most one of the ancestors'
2225 # trees differs (in changes outside in debian/). And we cannot
2226 # handle edges which change .pc/ or debian/patches. To avoid
2227 # going down a rathole we avoid traversing edges which introduce
2228 # debian/rules or debian/control. And we set a limit on the
2229 # number of edges we are willing to look at.
2231 # If we succeed, we walk forwards again. For each traversed edge
2232 # PC (with P parent, C child) (starting with P=S and ending with
2233 # C=T) to we do this:
2235 # - dpkg-source --commit with a patch name and message derived from C
2236 # After traversing PT, we git commit the changes which
2237 # should be contained within debian/patches.
2239 changedir '../fake';
2240 mktree_in_ud_here();
2242 runcmd @git, 'add', '.';
2243 my $oldtiptree=git_write_tree();
2244 changedir '../work';
2246 # The search for the path S..T is breadth-first. We maintain a
2247 # todo list containing search nodes. A search node identifies a
2248 # commit, and looks something like this:
2250 # Commit => $git_commit_id,
2251 # Child => $c, # or undef if P=T
2252 # Whynot => $reason_edge_PC_unsuitable, # in @nots only
2253 # Nontrivial => true iff $p..$c has relevant changes
2260 my %considered; # saves being exponential on some weird graphs
2262 my $t_sentinels = quiltify_tree_sentinelfiles $target;
2265 my ($search,$whynot) = @_;
2266 printdebug " search NOT $search->{Commit} $whynot\n";
2267 $search->{Whynot} = $whynot;
2268 push @nots, $search;
2269 no warnings qw(exiting);
2278 my $c = shift @todo;
2279 next if $considered{$c->{Commit}}++;
2281 $not->($c, "maximum search space exceeded") if --$max_work <= 0;
2283 printdebug "quiltify investigate $c->{Commit}\n";
2286 if (!quiltify_trees_differ $c->{Commit}, $oldtiptree) {
2287 printdebug " search finished hooray!\n";
2292 if ($quilt_mode eq 'nofix') {
2293 fail "quilt fixup required but quilt mode is \`nofix'\n".
2294 "HEAD commit $c->{Commit} differs from tree implied by ".
2295 " debian/patches (tree object $oldtiptree)";
2297 if ($quilt_mode eq 'smash') {
2298 printdebug " search quitting smash\n";
2302 my $c_sentinels = quiltify_tree_sentinelfiles $c->{Commit};
2303 $not->($c, "has $c_sentinels not $t_sentinels")
2304 if $c_sentinels ne $t_sentinels;
2306 my $commitdata = cmdoutput @git, qw(cat-file commit), $c->{Commit};
2307 $commitdata =~ m/\n\n/;
2309 my @parents = ($commitdata =~ m/^parent (\w+)$/gm);
2310 @parents = map { { Commit => $_, Child => $c } } @parents;
2312 $not->($c, "root commit") if !@parents;
2314 foreach my $p (@parents) {
2315 $p->{Nontrivial}= quiltify_trees_differ $p->{Commit},$c->{Commit};
2317 my $ndiffers = grep { $_->{Nontrivial} } @parents;
2318 $not->($c, "merge ($ndiffers nontrivial parents)") if $ndiffers > 1;
2320 foreach my $p (@parents) {
2321 printdebug "considering C=$c->{Commit} P=$p->{Commit}\n";
2323 my @cmd= (@git, qw(diff-tree -r --name-only),
2324 $p->{Commit},$c->{Commit}, qw(-- debian/patches .pc));
2325 my $patchstackchange = cmdoutput @cmd;
2326 if (length $patchstackchange) {
2327 $patchstackchange =~ s/\n/,/g;
2328 $not->($p, "changed $patchstackchange");
2331 printdebug " search queue P=$p->{Commit} ",
2332 ($p->{Nontrivial} ? "NT" : "triv"),"\n";
2338 printdebug "quiltify want to smash\n";
2341 my $x = $_[0]{Commit};
2342 $x =~ s/(.*?[0-9a-z]{8})[0-9a-z]*$/$1/;
2345 my $reportnot = sub {
2347 my $s = $abbrev->($notp);
2348 my $c = $notp->{Child};
2349 $s .= "..".$abbrev->($c) if $c;
2350 $s .= ": ".$c->{Whynot};
2353 if ($quilt_mode eq 'linear') {
2354 print STDERR "$us: quilt fixup cannot be linear. Stopped at:\n";
2355 foreach my $notp (@nots) {
2356 print STDERR "$us: ", $reportnot->($notp), "\n";
2358 fail "quilt fixup naive history linearisation failed.\n".
2359 "Use dpkg-source --commit by hand; or, --quilt=smash for one ugly patch";
2360 } elsif ($quilt_mode eq 'smash') {
2361 } elsif ($quilt_mode eq 'auto') {
2362 progress "quilt fixup cannot be linear, smashing...";
2364 die "$quilt_mode ?";
2369 my $msg = cmdoutput @git, qw(log), "-n$ncommits";
2371 quiltify_dpkg_commit "auto-$version-$target-$time",
2372 (getfield $clogp, 'Maintainer'),
2373 "Automatically generated patch ($clogp->{Version})\n".
2374 "Last (up to) $ncommits git changes, FYI:\n\n". $msg;
2378 progress "quiltify linearisation planning successful, executing...";
2380 for (my $p = $sref_S;
2381 my $c = $p->{Child};
2383 printdebug "quiltify traverse $p->{Commit}..$c->{Commit}\n";
2384 next unless $p->{Nontrivial};
2386 my $cc = $c->{Commit};
2388 my $commitdata = cmdoutput @git, qw(cat-file commit), $cc;
2389 $commitdata =~ m/\n\n/ or die "$c ?";
2392 $commitdata =~ m/^author (.*) \d+ [-+0-9]+$/m or die "$cc ?";
2395 $msg =~ s/^(.*)\n*/$1\n/ or die "$cc $msg ?";
2398 my $patchname = $title;
2399 $patchname =~ s/[.:]$//;
2400 $patchname =~ y/ A-Z/-a-z/;
2401 $patchname =~ y/-a-z0-9_.+=~//cd;
2402 $patchname =~ s/^\W/x-$&/;
2403 $patchname = substr($patchname,0,40);
2406 stat "debian/patches/$patchname$index";
2408 $!==ENOENT or die "$patchname$index $!";
2410 runcmd @git, qw(checkout -q), $cc;
2412 # We use the tip's changelog so that dpkg-source doesn't
2413 # produce complaining messages from dpkg-parsechangelog. None
2414 # of the information dpkg-source gets from the changelog is
2415 # actually relevant - it gets put into the original message
2416 # which dpkg-source provides our stunt editor, and then
2418 runcmd @git, qw(checkout -q), $target, qw(debian/changelog);
2420 quiltify_dpkg_commit "$patchname$index", $author, $msg,
2421 "X-Dgit-Generated: $clogp->{Version} $cc\n";
2423 runcmd @git, qw(checkout -q), $cc, qw(debian/changelog);
2426 runcmd @git, qw(checkout -q master);
2429 sub build_maybe_quilt_fixup () {
2430 my $format=get_source_format;
2431 return unless madformat $format;
2435 # - honour any existing .pc in case it has any strangeness
2436 # - determine the git commit corresponding to the tip of
2437 # the patch stack (if there is one)
2438 # - if there is such a git commit, convert each subsequent
2439 # git commit into a quilt patch with dpkg-source --commit
2440 # - otherwise convert all the differences in the tree into
2441 # a single git commit
2445 # Our git tree doesn't necessarily contain .pc. (Some versions of
2446 # dgit would include the .pc in the git tree.) If there isn't
2447 # one, we need to generate one by unpacking the patches that we
2450 # We first look for a .pc in the git tree. If there is one, we
2451 # will use it. (This is not the normal case.)
2453 # Otherwise need to regenerate .pc so that dpkg-source --commit
2454 # can work. We do this as follows:
2455 # 1. Collect all relevant .orig from parent directory
2456 # 2. Generate a debian.tar.gz out of
2457 # debian/{patches,rules,source/format}
2458 # 3. Generate a fake .dsc containing just these fields:
2459 # Format Source Version Files
2460 # 4. Extract the fake .dsc
2461 # Now the fake .dsc has a .pc directory.
2462 # (In fact we do this in every case, because in future we will
2463 # want to search for a good base commit for generating patches.)
2465 # Then we can actually do the dpkg-source --commit
2466 # 1. Make a new working tree with the same object
2467 # store as our main tree and check out the main
2469 # 2. Copy .pc from the fake's extraction, if necessary
2470 # 3. Run dpkg-source --commit
2471 # 4. If the result has changes to debian/, then
2472 # - git-add them them
2473 # - git-add .pc if we had a .pc in-tree
2475 # 5. If we had a .pc in-tree, delete it, and git-commit
2476 # 6. Back in the main tree, fast forward to the new HEAD
2478 my $clogp = parsechangelog();
2479 my $headref = rev_parse('HEAD');
2484 my $upstreamversion=$version;
2485 $upstreamversion =~ s/-[^-]*$//;
2487 my $fakeversion="$upstreamversion-~~DGITFAKE";
2489 my $fakedsc=new IO::File 'fake.dsc', '>' or die $!;
2490 print $fakedsc <<END or die $!;
2493 Version: $fakeversion
2497 my $dscaddfile=sub {
2500 my $md = new Digest::MD5;
2502 my $fh = new IO::File $b, '<' or die "$b $!";
2507 print $fakedsc " ".$md->hexdigest." $size $b\n" or die $!;
2510 foreach my $f (<../../../../*>) { #/){
2511 my $b=$f; $b =~ s{.*/}{};
2512 next unless is_orig_file $b, srcfn $upstreamversion,'';
2513 link $f, $b or die "$b $!";
2517 my @files=qw(debian/source/format debian/rules);
2518 if (stat_exists '../../../debian/patches') {
2519 push @files, 'debian/patches';
2522 my $debtar= srcfn $fakeversion,'.debian.tar.gz';
2523 runcmd qw(env GZIP=-1 tar -zcf), "./$debtar", qw(-C ../../..), @files;
2525 $dscaddfile->($debtar);
2526 close $fakedsc or die $!;
2528 runcmd qw(sh -ec), 'exec dpkg-source --no-check -x fake.dsc >/dev/null';
2530 my $fakexdir= $package.'-'.(stripepoch $upstreamversion);
2531 rename $fakexdir, "fake" or die "$fakexdir $!";
2533 mkdir "work" or die $!;
2535 mktree_in_ud_here();
2536 runcmd @git, qw(reset --hard), $headref;
2539 if (stat_exists ".pc") {
2541 progress "Tree already contains .pc - will use it then delete it.";
2544 rename '../fake/.pc','.pc' or die $!;
2547 quiltify($clogp,$headref);
2549 if (!open P, '>>', ".pc/applied-patches") {
2550 $!==&ENOENT or die $!;
2555 commit_quilty_patch();
2557 if ($mustdeletepc) {
2558 runcmd @git, qw(rm -rq .pc);
2559 commit_admin "Commit removal of .pc (quilt series tracking data)";
2562 changedir '../../../..';
2563 runcmd @git, qw(pull --ff-only -q .git/dgit/unpack/work master);
2566 sub quilt_fixup_editor () {
2567 my $descfn = $ENV{$fakeeditorenv};
2568 my $editing = $ARGV[$#ARGV];
2569 open I1, '<', $descfn or die "$descfn: $!";
2570 open I2, '<', $editing or die "$editing: $!";
2571 unlink $editing or die "$editing: $!";
2572 open O, '>', $editing or die "$editing: $!";
2573 while (<I1>) { print O or die $!; } I1->error and die $!;
2576 $copying ||= m/^\-\-\- /;
2577 next unless $copying;
2580 I2->error and die $!;
2585 #----- other building -----
2588 if ($cleanmode eq 'dpkg-source') {
2589 runcmd_ordryrun_local @dpkgbuildpackage, qw(-T clean);
2590 } elsif ($cleanmode eq 'git') {
2591 runcmd_ordryrun_local @git, qw(clean -xdf);
2592 } elsif ($cleanmode eq 'none') {
2599 badusage "clean takes no additional arguments" if @ARGV;
2604 badusage "-p is not allowed when building" if defined $package;
2607 my $clogp = parsechangelog();
2608 $isuite = getfield $clogp, 'Distribution';
2609 $package = getfield $clogp, 'Source';
2610 $version = getfield $clogp, 'Version';
2611 build_maybe_quilt_fixup();
2614 sub changesopts () {
2615 my @opts =@changesopts[1..$#changesopts];
2616 if (!defined $changes_since_version) {
2617 my @vsns = archive_query('archive_query');
2618 my @quirk = access_quirk();
2619 if ($quirk[0] eq 'backports') {
2620 local $isuite = $quirk[2];
2622 canonicalise_suite();
2623 push @vsns, archive_query('archive_query');
2626 @vsns = map { $_->[0] } @vsns;
2627 @vsns = sort { -version_compare($a, $b) } @vsns;
2628 $changes_since_version = $vsns[0];
2629 progress "changelog will contain changes since $vsns[0]";
2631 $changes_since_version = '_';
2632 progress "package seems new, not specifying -v<version>";
2635 if ($changes_since_version ne '_') {
2636 unshift @opts, "-v$changes_since_version";
2643 runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc), changesopts(), @ARGV;
2644 printdone "build successful\n";
2650 (qw(git-buildpackage -us -uc --git-no-sign-tags),
2651 "--git-builder=@dpkgbuildpackage");
2652 unless (grep { m/^--git-debian-branch|^--git-ignore-branch/ } @ARGV) {
2653 canonicalise_suite();
2654 push @cmd, "--git-debian-branch=".lbranch();
2656 push @cmd, changesopts();
2657 runcmd_ordryrun_local @cmd, @ARGV;
2658 printdone "build successful\n";
2663 $sourcechanges = "${package}_".(stripepoch $version)."_source.changes";
2664 $dscfn = dscfn($version);
2665 if ($cleanmode eq 'dpkg-source') {
2666 runcmd_ordryrun_local (@dpkgbuildpackage, qw(-us -uc -S)),
2669 my $pwd = must_getcwd();
2670 my $leafdir = basename $pwd;
2672 runcmd_ordryrun_local @dpkgsource, qw(-b --), $leafdir;
2674 runcmd_ordryrun_local qw(sh -ec),
2675 'exec >$1; shift; exec "$@"','x',
2676 "../$sourcechanges",
2677 @dpkggenchanges, qw(-S), changesopts();
2681 sub cmd_build_source {
2682 badusage "build-source takes no additional arguments" if @ARGV;
2684 printdone "source built, results in $dscfn and $sourcechanges";
2690 my $pat = "${package}_".(stripepoch $version)."_*.changes";
2692 stat_exist $dscfn or fail "$dscfn (in parent directory): $!";
2693 stat_exists $sourcechanges
2694 or fail "$sourcechanges (in parent directory): $!";
2695 foreach my $cf (glob $pat) {
2696 next if $cf eq $sourcechanges;
2697 unlink $cf or fail "remove $cf: $!";
2700 runcmd_ordryrun_local @sbuild, @ARGV, qw(-d), $isuite, $dscfn;
2701 my @changesfiles = glob $pat;
2702 @changesfiles = sort {
2703 ($b =~ m/_source\.changes$/ <=> $a =~ m/_source\.changes$/)
2706 fail "wrong number of different changes files (@changesfiles)"
2707 unless @changesfiles;
2708 runcmd_ordryrun_local @mergechanges, @changesfiles;
2709 my $multichanges = "${package}_".(stripepoch $version)."_multi.changes";
2711 stat_exists $multichanges or fail "$multichanges: $!";
2713 printdone "build successful, results in $multichanges\n" or die $!;
2716 sub cmd_quilt_fixup {
2717 badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
2718 my $clogp = parsechangelog();
2719 $version = getfield $clogp, 'Version';
2720 $package = getfield $clogp, 'Source';
2721 build_maybe_quilt_fixup();
2724 sub cmd_archive_api_query {
2725 badusage "need only 1 subpath argument" unless @ARGV==1;
2726 my ($subpath) = @ARGV;
2727 my @cmd = archive_api_query_cmd($subpath);
2728 exec @cmd or fail "exec curl: $!\n";
2731 #---------- argument parsing and main program ----------
2734 print "dgit version $our_version\n" or die $!;
2741 if (defined $ENV{'DGIT_SSH'}) {
2742 @ssh = string_to_ssh $ENV{'DGIT_SSH'};
2743 } elsif (defined $ENV{'GIT_SSH'}) {
2744 @ssh = ($ENV{'GIT_SSH'});
2748 last unless $ARGV[0] =~ m/^-/;
2752 if (m/^--dry-run$/) {
2755 } elsif (m/^--damp-run$/) {
2758 } elsif (m/^--no-sign$/) {
2761 } elsif (m/^--help$/) {
2763 } elsif (m/^--version$/) {
2765 } elsif (m/^--new$/) {
2768 } elsif (m/^--since-version=([^_]+|_)$/) {
2770 $changes_since_version = $1;
2771 } elsif (m/^--([-0-9a-z]+)=(.*)/s &&
2772 ($om = $opts_opt_map{$1}) &&
2776 } elsif (m/^--([-0-9a-z]+):(.*)/s &&
2777 !$opts_opt_cmdonly{$1} &&
2778 ($om = $opts_opt_map{$1})) {
2781 } elsif (m/^--existing-package=(.*)/s) {
2783 $existing_package = $1;
2784 } elsif (m/^--initiator-tempdir=(.*)/s) {
2785 $initiator_tempdir = $1;
2786 $initiator_tempdir =~ m#^/# or
2787 badusage "--initiator-tempdir must be used specify an".
2788 " absolute, not relative, directory."
2789 } elsif (m/^--distro=(.*)/s) {
2792 } elsif (m/^--build-products-dir=(.*)/s) {
2794 $buildproductsdir = $1;
2795 } elsif (m/^--clean=(dpkg-source|git|none)$/s) {
2798 } elsif (m/^--clean=(.*)$/s) {
2799 badusage "unknown cleaning mode \`$1'";
2800 } elsif (m/^--quilt=($quilt_modes_re)$/s) {
2803 } elsif (m/^--quilt=(.*)$/s) {
2804 badusage "unknown quilt fixup mode \`$1'";
2805 } elsif (m/^--ignore-dirty$/s) {
2808 } elsif (m/^--no-quilt-fixup$/s) {
2810 $quilt_mode = 'nocheck';
2811 } elsif (m/^--no-rm-on-error$/s) {
2814 } elsif (m/^--deliberately-($suite_re)$/s) {
2816 push @deliberatelies, $&;
2818 badusage "unknown long option \`$_'";
2825 } elsif (s/^-L/-/) {
2828 } elsif (s/^-h/-/) {
2830 } elsif (s/^-D/-/) {
2832 open DEBUG, ">&STDERR" or die $!;
2835 } elsif (s/^-N/-/) {
2838 } elsif (s/^-v([^_]+|_)$//s) {
2840 $changes_since_version = $1;
2843 push @changesopts, $_;
2845 } elsif (s/^-c(.*=.*)//s) {
2847 push @git, '-c', $1;
2848 } elsif (s/^-d(.+)//s) {
2851 } elsif (s/^-C(.+)//s) {
2854 if ($changesfile =~ s#^(.*)/##) {
2855 $buildproductsdir = $1;
2857 } elsif (s/^-k(.+)//s) {
2859 } elsif (m/^-[vdCk]$/) {
2861 "option \`$_' requires an argument (and no space before the argument)";
2862 } elsif (s/^-wn$//s) {
2864 $cleanmode = 'none';
2865 } elsif (s/^-wg$//s) {
2868 } elsif (s/^-wd$//s) {
2870 $cleanmode = 'dpkg-source';
2872 badusage "unknown short option \`$_'";
2879 if ($ENV{$fakeeditorenv}) {
2880 quilt_fixup_editor();
2884 print STDERR "DRY RUN ONLY\n" if $dryrun_level > 1;
2885 print STDERR "DAMP RUN - WILL MAKE LOCAL (UNSIGNED) CHANGES\n"
2886 if $dryrun_level == 1;
2888 print STDERR $helpmsg or die $!;
2891 my $cmd = shift @ARGV;
2894 if (!defined $quilt_mode) {
2895 $quilt_mode = cfg('dgit.force.quilt-mode', 'RETURN-UNDEF')
2896 // access_cfg('quilt-mode', 'RETURN-UNDEF')
2898 $quilt_mode =~ m/^($quilt_modes_re)$/
2899 or badcfg "unknown quilt-mode \`$quilt_mode'";
2903 my $fn = ${*::}{"cmd_$cmd"};
2904 $fn or badusage "unknown operation $cmd";