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/>.
25 use Dpkg::Control::Hash;
27 use File::Temp qw(tempdir);
38 our $our_version = 'UNRELEASED'; ###substituted###
40 our $rpushprotovsn = 2;
42 our $isuite = 'unstable';
48 our $dryrun_level = 0;
50 our $buildproductsdir = '..';
56 our $existing_package = 'dpkg';
57 our $cleanmode = 'dpkg-source';
58 our $changes_since_version;
60 our $quilt_modes_re = 'linear|smash|auto|nofix|nocheck';
61 our $we_are_responder;
62 our $initiator_tempdir;
64 our %format_ok = map { $_=>1 } ("1.0","3.0 (native)","3.0 (quilt)");
66 our $suite_re = '[-+.0-9a-z]+';
69 our (@dget) = qw(dget);
70 our (@curl) = qw(curl -f);
71 our (@dput) = qw(dput);
72 our (@debsign) = qw(debsign);
74 our (@sbuild) = qw(sbuild -A);
76 our (@dgit) = qw(dgit);
77 our (@dpkgbuildpackage) = qw(dpkg-buildpackage -i\.git/ -I.git);
78 our (@dpkgsource) = qw(dpkg-source -i\.git/ -I.git);
79 our (@dpkggenchanges) = qw(dpkg-genchanges);
80 our (@mergechanges) = qw(mergechanges -f);
81 our (@changesopts) = ('');
83 our %opts_opt_map = ('dget' => \@dget, # accept for compatibility
86 'debsign' => \@debsign,
91 'dpkg-source' => \@dpkgsource,
92 'dpkg-buildpackage' => \@dpkgbuildpackage,
93 'dpkg-genchanges' => \@dpkggenchanges,
94 'ch' => \@changesopts,
95 'mergechanges' => \@mergechanges);
97 our %opts_opt_cmdonly = ('gpg' => 1);
102 open DEBUG, ">/dev/null" or die $!;
106 our $remotename = 'dgit';
107 our @ourdscfield = qw(Dgit Vcs-Dgit-Master);
111 sub lbranch () { return "$branchprefix/$csuite"; }
112 my $lbranch_re = '^refs/heads/'.$branchprefix.'/([^/.]+)$';
113 sub lref () { return "refs/heads/".lbranch(); }
114 sub lrref () { return "refs/remotes/$remotename/".server_branch($csuite); }
115 sub rrref () { return server_ref($csuite); }
125 return "${package}_".(stripepoch $vsn).$sfx
130 return srcfn($vsn,".dsc");
134 our $debugprefix = '';
139 foreach my $f (@end) {
141 warn "$us: cleanup: $@" if length $@;
145 our @signames = split / /, $Config{sig_name};
147 sub waitstatusmsg () {
149 return "terminated, reporting successful completion";
150 } elsif (!($? & 255)) {
151 return "failed with error exit status ".WEXITSTATUS($?);
152 } elsif (WIFSIGNALED($?)) {
153 my $signum=WTERMSIG($?);
154 return "died due to fatal signal ".
155 ($signames[$signum] // "number $signum").
156 ($? & 128 ? " (core dumped)" : ""); # POSIX(3pm) has no WCOREDUMP
158 return "failed with unknown wait status ".$?;
162 sub printdebug { print DEBUG $debugprefix, @_ or die $!; }
166 my $prefix = $us.($we_are_responder ? " (build host)" : "").": ";
167 $s =~ s/^/$prefix/gm;
171 sub badcfg { print STDERR "$us: invalid configuration: @_\n"; exit 12; }
173 sub no_such_package () {
174 print STDERR "$us: package $package does not exist in suite $isuite\n";
180 return "+".rrref().":".lrref();
185 printdebug "CD $newdir\n";
186 chdir $newdir or die "chdir: $newdir: $!";
189 sub deliberately ($) {
190 return !!grep { $_[0] eq $_ } @deliberatelies;
193 #---------- remote protocol support, common ----------
195 # remote push initiator/responder protocol:
196 # < dgit-remote-push-ready [optional extra info ignored by old initiators]
198 # > file parsed-changelog
199 # [indicates that output of dpkg-parsechangelog follows]
200 # > data-block NBYTES
201 # > [NBYTES bytes of data (no newline)]
202 # [maybe some more blocks]
214 # [indicates that signed tag is wanted]
215 # < data-block NBYTES
216 # < [NBYTES bytes of data (no newline)]
217 # [maybe some more blocks]
221 # > want signed-dsc-changes
222 # < data-block NBYTES [transfer of signed dsc]
224 # < data-block NBYTES [transfer of signed changes]
232 sub i_child_report () {
233 # Sees if our child has died, and reap it if so. Returns a string
234 # describing how it died if it failed, or undef otherwise.
235 return undef unless $i_child_pid;
236 my $got = waitpid $i_child_pid, WNOHANG;
237 return undef if $got <= 0;
238 die unless $got == $i_child_pid;
239 $i_child_pid = undef;
240 return undef unless $?;
241 return "build host child ".waitstatusmsg();
246 fail "connection lost: $!" if $fh->error;
247 fail "protocol violation; $m not expected";
250 sub badproto_badread ($$) {
252 fail "connection lost: $!" if $!;
253 my $report = i_child_report();
254 fail $report if defined $report;
255 badproto $fh, "eof (reading $wh)";
258 sub protocol_expect (&$) {
259 my ($match, $fh) = @_;
262 defined && chomp or badproto_badread $fh, "protocol message";
270 badproto $fh, "\`$_'";
273 sub protocol_send_file ($$) {
274 my ($fh, $ourfn) = @_;
275 open PF, "<", $ourfn or die "$ourfn: $!";
278 my $got = read PF, $d, 65536;
279 die "$ourfn: $!" unless defined $got;
281 print $fh "data-block ".length($d)."\n" or die $!;
282 print $fh $d or die $!;
284 PF->error and die "$ourfn $!";
285 print $fh "data-end\n" or die $!;
289 sub protocol_read_bytes ($$) {
290 my ($fh, $nbytes) = @_;
291 $nbytes =~ m/^[1-9]\d{0,5}$/ or badproto \*RO, "bad byte count";
293 my $got = read $fh, $d, $nbytes;
294 $got==$nbytes or badproto_badread $fh, "data block";
298 sub protocol_receive_file ($$) {
299 my ($fh, $ourfn) = @_;
300 printdebug "() $ourfn\n";
301 open PF, ">", $ourfn or die "$ourfn: $!";
303 my ($y,$l) = protocol_expect {
304 m/^data-block (.*)$/ ? (1,$1) :
305 m/^data-end$/ ? (0,) :
309 my $d = protocol_read_bytes $fh, $l;
310 print PF $d or die $!;
315 #---------- remote protocol support, responder ----------
317 sub responder_send_command ($) {
319 return unless $we_are_responder;
320 # called even without $we_are_responder
321 printdebug ">> $command\n";
322 print PO $command, "\n" or die $!;
325 sub responder_send_file ($$) {
326 my ($keyword, $ourfn) = @_;
327 return unless $we_are_responder;
328 printdebug "]] $keyword $ourfn\n";
329 responder_send_command "file $keyword";
330 protocol_send_file \*PO, $ourfn;
333 sub responder_receive_files ($@) {
334 my ($keyword, @ourfns) = @_;
335 die unless $we_are_responder;
336 printdebug "[[ $keyword @ourfns\n";
337 responder_send_command "want $keyword";
338 foreach my $fn (@ourfns) {
339 protocol_receive_file \*PI, $fn;
342 protocol_expect { m/^files-end$/ } \*PI;
345 #---------- remote protocol support, initiator ----------
347 sub initiator_expect (&) {
349 protocol_expect { &$match } \*RO;
352 #---------- end remote code ----------
355 if ($we_are_responder) {
357 responder_send_command "progress ".length($m) or die $!;
358 print PO $m or die $!;
368 $ua = LWP::UserAgent->new();
372 progress "downloading $what...";
373 my $r = $ua->get(@_) or die $!;
374 return undef if $r->code == 404;
375 $r->is_success or fail "failed to fetch $what: ".$r->status_line;
376 return $r->decoded_content(charset => 'none');
379 our ($dscdata,$dscurl,$dsc,$dsc_checked,$skew_warning_vsn);
386 if (m{[^-=_./0-9a-z]}i) {
393 return join ' ', @out;
398 my $intro = shift @_;
399 print $fh $intro," " or die $!;
400 print $fh shellquote @_ or die $!;
401 print $fh "\n" or die $!;
405 { local ($!); printcmd \*STDERR, "$us: failed command:", @_ or die $!; };
407 fail "failed to fork/exec: $!";
409 fail "subprocess ".waitstatusmsg();
411 fail "subprocess produced invalid output";
416 printcmd(\*DEBUG,$debugprefix."+",@_) if $debug>0;
418 failedcmd @_ if system @_;
421 sub act_local () { return $dryrun_level <= 1; }
422 sub act_scary () { return !$dryrun_level; }
425 if (!$dryrun_level) {
426 progress "dgit ok: @_";
428 progress "would be ok: @_ (but dry run only)";
432 sub cmdoutput_errok {
433 die Dumper(\@_)." ?" if grep { !defined } @_;
434 printcmd(\*DEBUG,$debugprefix."|",@_) if $debug>0;
435 open P, "-|", @_ or die $!;
438 { local $/ = undef; $d = <P>; }
440 if (!close P) { printdebug "=>!$?\n" if $debug>0; return undef; }
443 printdebug "=> \`$&'",(length $' ? '...' : ''),"\n" if $debug>0; #';
448 my $d = cmdoutput_errok @_;
449 defined $d or failedcmd @_;
454 printcmd(\*STDERR,$debugprefix."#",@_);
457 sub runcmd_ordryrun {
465 sub runcmd_ordryrun_local {
474 my ($first_shell, @cmd) = @_;
475 return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
478 our $helpmsg = <<END;
480 dgit [dgit-opts] clone [dgit-opts] package [suite] [./dir|/dir]
481 dgit [dgit-opts] fetch|pull [dgit-opts] [suite]
482 dgit [dgit-opts] build [git-buildpackage-opts|dpkg-buildpackage-opts]
483 dgit [dgit-opts] push [dgit-opts] [suite]
484 dgit [dgit-opts] rpush build-host:build-dir ...
485 important dgit options:
486 -k<keyid> sign tag and package with <keyid> instead of default
487 --dry-run -n do not change anything, but go through the motions
488 --damp-run -L like --dry-run but make local changes, without signing
489 --new -N allow introducing a new package
490 --debug -D increase debug level
491 -c<name>=<value> set git config option (used directly by dgit too)
494 our $later_warning_msg = <<END;
495 Perhaps the upload is stuck in incoming. Using the version from git.
499 print STDERR "$us: @_\n", $helpmsg or die $!;
504 @ARGV or badusage "too few arguments";
505 return scalar shift @ARGV;
509 print $helpmsg or die $!;
513 our $td = $ENV{DGIT_TEST_DUMMY_DIR} || "DGIT_TEST_DUMMY_DIR-unset";
515 our %defcfg = ('dgit.default.distro' => 'debian',
516 'dgit.default.username' => '',
517 'dgit.default.archive-query-default-component' => 'main',
518 'dgit.default.ssh' => 'ssh',
519 'dgit.default.archive-query' => 'madison:',
520 'dgit.default.sshpsql-dbname' => 'service=projectb',
521 'dgit-distro.debian.archive-query' => 'sshpsql:',
522 'dgit-distro.debian.git-host' => 'dgit-git.debian.net',
523 'dgit-distro.debian.git-user-force' => 'dgit',
524 'dgit-distro.debian.git-proto' => 'git+ssh://',
525 'dgit-distro.debian.git-path' => '/dgit/debian/repos',
526 'dgit-distro.debian.git-check' => 'ssh-cmd',
527 'dgit-distro.debian.archive-query-url', 'https://api.ftp-master.debian.org/',
528 'dgit-distro.debian.archive-query-tls-key',
529 '/etc/ssl/certs/%HOST%.pem:/etc/dgit/%HOST%.pem',
530 'dgit-distro.debian.diverts.alioth' => '/alioth',
531 'dgit-distro.debian/alioth.git-host' => 'git.debian.org',
532 'dgit-distro.debian/alioth.git-user-force' => '',
533 'dgit-distro.debian/alioth.git-proto' => 'git+ssh://',
534 'dgit-distro.debian/alioth.git-path' => '/git/dgit-repos/repos',
535 'dgit-distro.debian/alioth.git-create' => 'ssh-cmd',
536 'dgit-distro.debian.sshpsql-host' => 'mirror.ftp-master.debian.org',
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' => "dummycat:$td/aq",
551 'dgit-distro.test-dummy.mirror' => "file://$td/mirror/",
552 'dgit-distro.test-dummy.upload-host' => 'test-dummy',
557 return undef if $c =~ /RETURN-UNDEF/;
558 my @cmd = (@git, qw(config --), $c);
561 local ($debug) = $debug-1;
562 $v = cmdoutput_errok @cmd;
569 my $dv = $defcfg{$c};
570 return $dv if defined $dv;
572 badcfg "need value for one of: @_\n".
573 "$us: distro or suite appears not to be (properly) supported";
576 sub access_basedistro () {
577 if (defined $idistro) {
580 return cfg("dgit-suite.$isuite.distro",
581 "dgit.default.distro");
585 sub access_quirk () {
586 # returns (quirk name, distro to use instead or undef, quirk-specific info)
587 my $basedistro = access_basedistro();
588 my $backports_quirk = cfg("dgit-distro.$basedistro.backports-quirk",
590 if (defined $backports_quirk) {
591 my $re = $backports_quirk;
592 $re =~ s/[^-0-9a-z_\%*()]/\\$&/ig;
594 $re =~ s/\%/([-0-9a-z_]+)/
595 or $re =~ m/[()]/ or badcfg "backports-quirk needs \% or ( )";
596 if ($isuite =~ m/^$re$/) {
597 return ('backports',"$basedistro-backports",$1);
600 return ('none',undef);
603 sub access_distros () {
604 # Returns list of distros to try, in order
607 # 0. `instead of' distro name(s) we have been pointed to
608 # 1. the access_quirk distro, if any
609 # 2a. the user's specified distro, or failing that } basedistro
610 # 2b. the distro calculated from the suite }
611 my @l = access_basedistro();
613 my (undef,$quirkdistro) = access_quirk();
614 unshift @l, $quirkdistro;
615 unshift @l, $instead_distro;
616 return grep { defined } @l;
622 # The nesting of these loops determines the search order. We put
623 # the key loop on the outside so that we search all the distros
624 # for each key, before going on to the next key. That means that
625 # if access_cfg is called with a more specific, and then a less
626 # specific, key, an earlier distro can override the less specific
627 # without necessarily overriding any more specific keys. (If the
628 # distro wants to override the more specific keys it can simply do
629 # so; whereas if we did the loop the other way around, it would be
630 # impossible to for an earlier distro to override a less specific
631 # key but not the more specific ones without restating the unknown
632 # values of the more specific keys.
635 # We have to deal with RETURN-UNDEF specially, so that we don't
636 # terminate the search prematurely.
638 if (m/RETURN-UNDEF/) { push @rundef, $_; last; }
641 foreach my $d (access_distros()) {
642 push @cfgs, map { "dgit-distro.$d.$_" } @realkeys;
644 push @cfgs, map { "dgit.default.$_" } @realkeys;
646 my $value = cfg(@cfgs);
650 sub string_to_ssh ($) {
652 if ($spec =~ m/\s/) {
653 return qw(sh -ec), 'exec '.$spec.' "$@"', 'x';
659 sub access_cfg_ssh () {
660 my $gitssh = access_cfg('ssh', 'RETURN-UNDEF');
661 if (!defined $gitssh) {
664 return string_to_ssh $gitssh;
668 sub access_runeinfo ($) {
670 return ": dgit ".access_basedistro()." $info ;";
673 sub access_someuserhost ($) {
675 my $user = access_cfg("$some-user-force", 'RETURN-UNDEF');
676 defined($user) && length($user) or
677 $user = access_cfg("$some-user",'username');
678 my $host = access_cfg("$some-host");
679 return length($user) ? "$user\@$host" : $host;
682 sub access_gituserhost () {
683 return access_someuserhost('git');
686 sub access_giturl (;$) {
688 my $url = access_cfg('git-url','RETURN-UNDEF');
690 my $proto = access_cfg('git-proto', 'RETURN-UNDEF');
691 return undef unless defined $proto;
694 access_gituserhost().
695 access_cfg('git-path');
697 return "$url/$package.git";
700 sub parsecontrolfh ($$;$) {
701 my ($fh, $desc, $allowsigned) = @_;
702 our $dpkgcontrolhash_noissigned;
705 my %opts = ('name' => $desc);
706 $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
707 $c = Dpkg::Control::Hash->new(%opts);
708 $c->parse($fh,$desc) or die "parsing of $desc failed";
709 last if $allowsigned;
710 last if $dpkgcontrolhash_noissigned;
711 my $issigned= $c->get_option('is_pgp_signed');
712 if (!defined $issigned) {
713 $dpkgcontrolhash_noissigned= 1;
714 seek $fh, 0,0 or die "seek $desc: $!";
715 } elsif ($issigned) {
716 fail "control file $desc is (already) PGP-signed. ".
717 " Note that dgit push needs to modify the .dsc and then".
718 " do the signature itself";
727 my ($file, $desc) = @_;
728 my $fh = new IO::Handle;
729 open $fh, '<', $file or die "$file: $!";
730 my $c = parsecontrolfh($fh,$desc);
731 $fh->error and die $!;
737 my ($dctrl,$field) = @_;
738 my $v = $dctrl->{$field};
739 return $v if defined $v;
740 fail "missing field $field in ".$v->get_option('name');
744 my $c = Dpkg::Control::Hash->new();
745 my $p = new IO::Handle;
746 my @cmd = (qw(dpkg-parsechangelog), @_);
747 open $p, '-|', @cmd or die $!;
749 $?=0; $!=0; close $p or failedcmd @cmd;
753 sub git_get_ref ($) {
755 my $got = cmdoutput_errok @git, qw(show-ref --), $refname;
757 $?==256 or fail "git show-ref failed (status $?)";
758 printdebug "ref $refname= [show-ref exited 1]\n";
761 if ($got =~ m/^(\w+) \Q$refname\E$/m) {
762 printdebug "ref $refname=$1\n";
765 printdebug "ref $refname= [no match]\n";
772 defined $d or fail "getcwd failed: $!";
778 sub archive_query ($) {
780 my $query = access_cfg('archive-query','RETURN-UNDEF');
781 $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
784 { no strict qw(refs); &{"${method}_${proto}"}($proto,$data); }
787 sub pool_dsc_subpath ($$) {
788 my ($vsn,$component) = @_; # $package is implict arg
789 my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
790 return "/pool/$component/$prefix/$package/".dscfn($vsn);
793 #---------- `ftpmaster-api' archive query method (nascent) ----------
795 sub archive_api_query_cmd ($) {
797 my @cmd = qw(curl -sS);
798 my $url = access_cfg('archive-query-url');
799 if ($url =~ m#^https://([-.0-9a-z]+)/#) {
801 my $keys = access_cfg('archive-query-tls-key','RETURN-UNDEF');
802 foreach my $key (split /\:/, $keys) {
803 $key =~ s/\%HOST\%/$host/g;
805 fail "for $url: stat $key: $!" unless $!==ENOENT;
808 push @cmd, "--ca-certificate=$key", "--ca-directory=/dev/enoent";
812 push @cmd, $url.$subpath;
816 #---------- `madison' archive query method ----------
818 sub archive_query_madison {
819 return map { [ @$_[0..1] ] } madison_get_parse(@_);
822 sub madison_get_parse {
823 my ($proto,$data) = @_;
824 die unless $proto eq 'madison';
826 $data= access_cfg('madison-distro','RETURN-UNDEF');
827 $data //= access_basedistro();
829 $rmad{$proto,$data,$package} ||= cmdoutput
830 qw(rmadison -asource),"-s$isuite","-u$data",$package;
831 my $rmad = $rmad{$proto,$data,$package};
834 foreach my $l (split /\n/, $rmad) {
835 $l =~ m{^ \s*( [^ \t|]+ )\s* \|
836 \s*( [^ \t|]+ )\s* \|
837 \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
838 \s*( [^ \t|]+ )\s* }x or die "$rmad ?";
839 $1 eq $package or die "$rmad $package ?";
846 $component = access_cfg('archive-query-default-component');
848 $5 eq 'source' or die "$rmad ?";
849 push @out, [$vsn,pool_dsc_subpath($vsn,$component),$newsuite];
851 return sort { -version_compare($a->[0],$b->[0]); } @out;
854 sub canonicalise_suite_madison {
855 # madison canonicalises for us
856 my @r = madison_get_parse(@_);
858 "unable to canonicalise suite using package $package".
859 " which does not appear to exist in suite $isuite;".
860 " --existing-package may help";
864 #---------- `sshpsql' archive query method ----------
867 my ($data,$runeinfo,$sql) = @_;
869 $data= access_someuserhost('sshpsql').':'.
870 access_cfg('sshpsql-dbname');
872 $data =~ m/:/ or badcfg "invalid sshpsql method string \`$data'";
873 my ($userhost,$dbname) = ($`,$'); #';
875 my @cmd = (access_cfg_ssh, $userhost,
876 access_runeinfo("ssh-psql $runeinfo").
878 " ".shellquote qw(psql -A), $dbname, qw(-c), $sql);
879 printcmd(\*DEBUG,$debugprefix."|",@cmd) if $debug>0;
880 open P, "-|", @cmd or die $!;
883 printdebug("$debugprefix>|$_|\n");
886 $!=0; $?=0; close P or failedcmd @cmd;
888 my $nrows = pop @rows;
889 $nrows =~ s/^\((\d+) rows?\)$/$1/ or die "$nrows ?";
890 @rows == $nrows+1 or die "$nrows ".(scalar @rows)." ?";
891 @rows = map { [ split /\|/, $_ ] } @rows;
892 my $ncols = scalar @{ shift @rows };
893 die if grep { scalar @$_ != $ncols } @rows;
897 sub sql_injection_check {
898 foreach (@_) { die "$_ $& ?" if m{[^-+=:_.,/0-9a-zA-Z]}; }
901 sub archive_query_sshpsql ($$) {
902 my ($proto,$data) = @_;
903 sql_injection_check $isuite, $package;
904 my @rows = sshpsql($data, "archive-query $isuite $package", <<END);
905 SELECT source.version, component.name, files.filename, files.sha256sum
907 JOIN src_associations ON source.id = src_associations.source
908 JOIN suite ON suite.id = src_associations.suite
909 JOIN dsc_files ON dsc_files.source = source.id
910 JOIN files_archive_map ON files_archive_map.file_id = dsc_files.file
911 JOIN component ON component.id = files_archive_map.component_id
912 JOIN files ON files.id = dsc_files.file
913 WHERE ( suite.suite_name='$isuite' OR suite.codename='$isuite' )
914 AND source.source='$package'
915 AND files.filename LIKE '%.dsc';
917 @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
918 my $digester = Digest::SHA->new(256);
920 my ($vsn,$component,$filename,$sha256sum) = @$_;
921 [ $vsn, "/pool/$component/$filename",$digester,$sha256sum ];
926 sub canonicalise_suite_sshpsql ($$) {
927 my ($proto,$data) = @_;
928 sql_injection_check $isuite;
929 my @rows = sshpsql($data, "canonicalise-suite $isuite", <<END);
930 SELECT suite.codename
931 FROM suite where suite_name='$isuite' or codename='$isuite';
933 @rows = map { $_->[0] } @rows;
934 fail "unknown suite $isuite" unless @rows;
935 die "ambiguous $isuite: @rows ?" if @rows>1;
939 #---------- `dummycat' archive query method ----------
941 sub canonicalise_suite_dummycat ($$) {
942 my ($proto,$data) = @_;
943 my $dpath = "$data/suite.$isuite";
944 if (!open C, "<", $dpath) {
945 $!==ENOENT or die "$dpath: $!";
946 printdebug "dummycat canonicalise_suite $isuite $dpath ENOENT\n";
950 chomp or die "$dpath: $!";
952 printdebug "dummycat canonicalise_suite $isuite $dpath = $_\n";
956 sub archive_query_dummycat ($$) {
957 my ($proto,$data) = @_;
958 canonicalise_suite();
959 my $dpath = "$data/package.$csuite.$package";
960 if (!open C, "<", $dpath) {
961 $!==ENOENT or die "$dpath: $!";
962 printdebug "dummycat query $csuite $package $dpath ENOENT\n";
970 printdebug "dummycat query $csuite $package $dpath | $_\n";
971 my @row = split /\s+/, $_;
972 @row==2 or die "$dpath: $_ ?";
975 C->error and die "$dpath: $!";
977 return sort { -version_compare($a->[0],$b->[0]); } @rows;
980 #---------- archive query entrypoints and rest of program ----------
982 sub canonicalise_suite () {
983 return if defined $csuite;
984 fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
985 $csuite = archive_query('canonicalise_suite');
986 if ($isuite ne $csuite) {
987 progress "canonical suite name for $isuite is $csuite";
991 sub get_archive_dsc () {
992 canonicalise_suite();
993 my @vsns = archive_query('archive_query');
994 foreach my $vinfo (@vsns) {
995 my ($vsn,$subpath,$digester,$digest) = @$vinfo;
996 $dscurl = access_cfg('mirror').$subpath;
997 $dscdata = url_get($dscurl);
999 $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
1004 $digester->add($dscdata);
1005 my $got = $digester->hexdigest();
1007 fail "$dscurl has hash $got but".
1008 " archive told us to expect $digest";
1010 my $dscfh = new IO::File \$dscdata, '<' or die $!;
1011 printdebug Dumper($dscdata) if $debug>1;
1012 $dsc = parsecontrolfh($dscfh,$dscurl,1);
1013 printdebug Dumper($dsc) if $debug>1;
1014 my $fmt = getfield $dsc, 'Format';
1015 fail "unsupported source format $fmt, sorry" unless $format_ok{$fmt};
1016 $dsc_checked = !!$digester;
1022 sub check_for_git ();
1023 sub check_for_git () {
1025 my $how = access_cfg('git-check');
1026 if ($how eq 'ssh-cmd') {
1028 (access_cfg_ssh, access_gituserhost(),
1029 access_runeinfo("git-check $package").
1030 " set -e; cd ".access_cfg('git-path').";".
1031 " if test -d $package.git; then echo 1; else echo 0; fi");
1032 my $r= cmdoutput @cmd;
1033 if ($r =~ m/^divert (\w+)$/) {
1035 my ($usedistro,) = access_distros();
1036 $instead_distro= cfg("dgit-distro.$usedistro.diverts.$divert");
1037 $instead_distro =~ s{^/}{ access_basedistro()."/" }e;
1038 printdebug "diverting $divert so using distro $instead_distro\n";
1039 return check_for_git();
1041 failedcmd @cmd unless $r =~ m/^[01]$/;
1043 } elsif ($how eq 'true') {
1045 } elsif ($how eq 'false') {
1048 badcfg "unknown git-check \`$how'";
1052 sub create_remote_git_repo () {
1053 my $how = access_cfg('git-create');
1054 if ($how eq 'ssh-cmd') {
1056 (access_cfg_ssh, access_gituserhost(),
1057 access_runeinfo("git-create $package").
1058 "set -e; cd ".access_cfg('git-path').";".
1059 " cp -a _template $package.git");
1060 } elsif ($how eq 'true') {
1063 badcfg "unknown git-create \`$how'";
1067 our ($dsc_hash,$lastpush_hash);
1069 our $ud = '.git/dgit/unpack';
1074 mkdir $ud or die $!;
1077 sub mktree_in_ud_here () {
1078 runcmd qw(git init -q);
1079 rmtree('.git/objects');
1080 symlink '../../../../objects','.git/objects' or die $!;
1083 sub git_write_tree () {
1084 my $tree = cmdoutput @git, qw(write-tree);
1085 $tree =~ m/^\w+$/ or die "$tree ?";
1089 sub mktree_in_ud_from_only_subdir () {
1090 # changes into the subdir
1092 die unless @dirs==1;
1093 $dirs[0] =~ m#^([^/]+)/\.$# or die;
1096 fail "source package contains .git directory" if stat_exists '.git';
1097 mktree_in_ud_here();
1098 my $format=get_source_format();
1099 if (madformat($format)) {
1102 runcmd @git, qw(add -Af);
1103 my $tree=git_write_tree();
1104 return ($tree,$dir);
1107 sub dsc_files_info () {
1108 foreach my $csumi (['Checksums-Sha256','Digest::SHA', 'new(256)'],
1109 ['Checksums-Sha1', 'Digest::SHA', 'new(1)'],
1110 ['Files', 'Digest::MD5', 'new()']) {
1111 my ($fname, $module, $method) = @$csumi;
1112 my $field = $dsc->{$fname};
1113 next unless defined $field;
1114 eval "use $module; 1;" or die $@;
1116 foreach (split /\n/, $field) {
1118 m/^(\w+) (\d+) (\S+)$/ or
1119 fail "could not parse .dsc $fname line \`$_'";
1120 my $digester = eval "$module"."->$method;" or die $@;
1125 Digester => $digester,
1130 fail "missing any supported Checksums-* or Files field in ".
1131 $dsc->get_option('name');
1135 map { $_->{Filename} } dsc_files_info();
1138 sub is_orig_file ($;$) {
1141 m/\.orig(?:-\w+)?\.tar\.\w+$/ or return 0;
1142 defined $base or return 1;
1146 sub make_commit ($) {
1148 return cmdoutput @git, qw(hash-object -w -t commit), $file;
1151 sub clogp_authline ($) {
1153 my $author = getfield $clogp, 'Maintainer';
1154 $author =~ s#,.*##ms;
1155 my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
1156 my $authline = "$author $date";
1157 $authline =~ m/^[^<>]+ \<\S+\> \d+ [-+]\d+$/ or
1158 fail "unexpected commit author line format \`$authline'".
1159 " (was generated from changelog Maintainer field)";
1163 sub generate_commit_from_dsc () {
1167 foreach my $fi (dsc_files_info()) {
1168 my $f = $fi->{Filename};
1169 die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
1171 link "../../../$f", $f
1175 complete_file_from_dsc('.', $fi);
1177 if (is_orig_file($f)) {
1178 link $f, "../../../../$f"
1184 my $dscfn = "$package.dsc";
1186 open D, ">", $dscfn or die "$dscfn: $!";
1187 print D $dscdata or die "$dscfn: $!";
1188 close D or die "$dscfn: $!";
1189 my @cmd = qw(dpkg-source);
1190 push @cmd, '--no-check' if $dsc_checked;
1191 push @cmd, qw(-x --), $dscfn;
1194 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1195 runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
1196 my $clogp = parsecontrol('../changelog.tmp',"commit's changelog");
1197 my $authline = clogp_authline $clogp;
1198 my $changes = getfield $clogp, 'Changes';
1199 open C, ">../commit.tmp" or die $!;
1200 print C <<END or die $!;
1207 # imported from the archive
1210 my $outputhash = make_commit qw(../commit.tmp);
1211 my $cversion = getfield $clogp, 'Version';
1212 progress "synthesised git commit from .dsc $cversion";
1213 if ($lastpush_hash) {
1214 runcmd @git, qw(reset --hard), $lastpush_hash;
1215 runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
1216 my $oldclogp = parsecontrol('../changelogold.tmp','previous changelog');
1217 my $oversion = getfield $oldclogp, 'Version';
1219 version_compare($oversion, $cversion);
1221 # git upload/ is earlier vsn than archive, use archive
1222 open C, ">../commit2.tmp" or die $!;
1223 print C <<END or die $!;
1225 parent $lastpush_hash
1230 Record $package ($cversion) in archive suite $csuite
1232 $outputhash = make_commit qw(../commit2.tmp);
1233 } elsif ($vcmp > 0) {
1234 print STDERR <<END or die $!;
1236 Version actually in archive: $cversion (older)
1237 Last allegedly pushed/uploaded: $oversion (newer or same)
1240 $outputhash = $lastpush_hash;
1242 $outputhash = $lastpush_hash;
1245 changedir '../../../..';
1246 runcmd @git, qw(update-ref -m),"dgit fetch import $cversion",
1247 'DGIT_ARCHIVE', $outputhash;
1248 cmdoutput @git, qw(log -n2), $outputhash;
1249 # ... gives git a chance to complain if our commit is malformed
1254 sub complete_file_from_dsc ($$) {
1255 our ($dstdir, $fi) = @_;
1256 # Ensures that we have, in $dir, the file $fi, with the correct
1257 # contents. (Downloading it from alongside $dscurl if necessary.)
1259 my $f = $fi->{Filename};
1260 my $tf = "$dstdir/$f";
1263 if (stat_exists $tf) {
1264 progress "using existing $f";
1267 $furl =~ s{/[^/]+$}{};
1269 die "$f ?" unless $f =~ m/^${package}_/;
1270 die "$f ?" if $f =~ m#/#;
1271 runcmd_ordryrun_local @curl,qw(-o),$tf,'--',"$furl";
1272 next if !act_local();
1276 open F, "<", "$tf" or die "$tf: $!";
1277 $fi->{Digester}->reset();
1278 $fi->{Digester}->addfile(*F);
1279 F->error and die $!;
1280 my $got = $fi->{Digester}->hexdigest();
1281 $got eq $fi->{Hash} or
1282 fail "file $f has hash $got but .dsc".
1283 " demands hash $fi->{Hash} ".
1284 ($downloaded ? "(got wrong file from archive!)"
1285 : "(perhaps you should delete this file?)");
1288 sub ensure_we_have_orig () {
1289 foreach my $fi (dsc_files_info()) {
1290 my $f = $fi->{Filename};
1291 next unless is_orig_file($f);
1292 complete_file_from_dsc('..', $fi);
1297 return cmdoutput @git, qw(rev-parse), "$_[0]~0";
1300 sub is_fast_fwd ($$) {
1301 my ($ancestor,$child) = @_;
1302 my @cmd = (@git, qw(merge-base), $ancestor, $child);
1303 my $mb = cmdoutput_errok @cmd;
1305 return rev_parse($mb) eq rev_parse($ancestor);
1307 $?==256 or failedcmd @cmd;
1312 sub git_fetch_us () {
1313 runcmd_ordryrun_local @git, qw(fetch),access_giturl(),fetchspec();
1316 sub fetch_from_archive () {
1317 # ensures that lrref() is what is actually in the archive,
1318 # one way or another
1322 foreach my $field (@ourdscfield) {
1323 $dsc_hash = $dsc->{$field};
1324 last if defined $dsc_hash;
1326 if (defined $dsc_hash) {
1327 $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
1329 progress "last upload to archive specified git hash";
1331 progress "last upload to archive has NO git hash";
1334 progress "no version available from the archive";
1337 $lastpush_hash = git_get_ref(lrref());
1338 printdebug "previous reference hash=$lastpush_hash\n";
1340 if (defined $dsc_hash) {
1341 fail "missing remote git history even though dsc has hash -".
1342 " could not find ref ".lrref().
1343 " (should have been fetched from ".access_giturl()."#".rrref().")"
1344 unless $lastpush_hash;
1346 ensure_we_have_orig();
1347 if ($dsc_hash eq $lastpush_hash) {
1348 } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
1349 print STDERR <<END or die $!;
1351 Git commit in archive is behind the last version allegedly pushed/uploaded.
1352 Commit referred to by archive: $dsc_hash
1353 Last allegedly pushed/uploaded: $lastpush_hash
1356 $hash = $lastpush_hash;
1358 fail "git head (".lrref()."=$lastpush_hash) is not a ".
1359 "descendant of archive's .dsc hash ($dsc_hash)";
1362 $hash = generate_commit_from_dsc();
1363 } elsif ($lastpush_hash) {
1364 # only in git, not in the archive yet
1365 $hash = $lastpush_hash;
1366 print STDERR <<END or die $!;
1368 Package not found in the archive, but has allegedly been pushed using dgit.
1372 printdebug "nothing found!\n";
1373 if (defined $skew_warning_vsn) {
1374 print STDERR <<END or die $!;
1376 Warning: relevant archive skew detected.
1377 Archive allegedly contains $skew_warning_vsn
1378 But we were not able to obtain any version from the archive or git.
1384 printdebug "current hash=$hash\n";
1385 if ($lastpush_hash) {
1386 fail "not fast forward on last upload branch!".
1387 " (archive's version left in DGIT_ARCHIVE)"
1388 unless is_fast_fwd($lastpush_hash, $hash);
1390 if (defined $skew_warning_vsn) {
1392 printdebug "SKEW CHECK WANT $skew_warning_vsn\n";
1393 my $clogf = ".git/dgit/changelog.tmp";
1394 runcmd shell_cmd "exec >$clogf",
1395 @git, qw(cat-file blob), "$hash:debian/changelog";
1396 my $gotclogp = parsechangelog("-l$clogf");
1397 my $got_vsn = getfield $gotclogp, 'Version';
1398 printdebug "SKEW CHECK GOT $got_vsn\n";
1399 if (version_compare($got_vsn, $skew_warning_vsn) < 0) {
1400 print STDERR <<END or die $!;
1402 Warning: archive skew detected. Using the available version:
1403 Archive allegedly contains $skew_warning_vsn
1404 We were able to obtain only $got_vsn
1409 if ($lastpush_hash ne $hash) {
1410 my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
1414 dryrun_report @upd_cmd;
1422 canonicalise_suite();
1423 badusage "dry run makes no sense with clone" unless act_local();
1424 my $hasgit = check_for_git();
1425 mkdir $dstdir or die "$dstdir $!";
1427 runcmd @git, qw(init -q);
1428 my $giturl = access_giturl(1);
1429 if (defined $giturl) {
1430 runcmd @git, qw(config), "remote.$remotename.fetch", fetchspec();
1431 open H, "> .git/HEAD" or die $!;
1432 print H "ref: ".lref()."\n" or die $!;
1434 runcmd @git, qw(remote add), 'origin', $giturl;
1437 progress "fetching existing git history";
1439 runcmd_ordryrun_local @git, qw(fetch origin);
1441 progress "starting new git history";
1443 fetch_from_archive() or no_such_package;
1444 my $vcsgiturl = $dsc->{'Vcs-Git'};
1445 $vcsgiturl =~ s/\s+-b\s+\S+//g;
1446 if (length $vcsgiturl) {
1447 runcmd @git, qw(remote add vcs-git), $vcsgiturl;
1449 runcmd @git, qw(reset --hard), lrref();
1450 printdone "ready for work in $dstdir";
1454 if (check_for_git()) {
1457 fetch_from_archive() or no_such_package();
1458 printdone "fetched into ".lrref();
1463 runcmd_ordryrun_local @git, qw(merge -m),"Merge from $csuite [dgit]",
1465 printdone "fetched to ".lrref()." and merged into HEAD";
1468 sub check_not_dirty () {
1469 return if $ignoredirty;
1470 my @cmd = (@git, qw(diff --quiet HEAD));
1471 printcmd(\*DEBUG,$debugprefix."+",@cmd) if $debug>0;
1472 $!=0; $?=0; system @cmd;
1473 return if !$! && !$?;
1474 if (!$! && $?==256) {
1475 fail "working tree is dirty (does not match HEAD)";
1481 sub commit_admin ($) {
1484 runcmd_ordryrun_local @git, qw(commit -m), $m;
1487 sub commit_quilty_patch () {
1488 my $output = cmdoutput @git, qw(status --porcelain);
1490 foreach my $l (split /\n/, $output) {
1491 next unless $l =~ m/\S/;
1492 if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
1496 delete $adds{'.pc'}; # if there wasn't one before, don't add it
1498 progress "nothing quilty to commit, ok.";
1501 runcmd_ordryrun_local @git, qw(add), sort keys %adds;
1502 commit_admin "Commit Debian 3.0 (quilt) metadata";
1505 sub get_source_format () {
1506 if (!open F, "debian/source/format") {
1507 die $! unless $!==&ENOENT;
1511 F->error and die $!;
1518 return 0 unless $format eq '3.0 (quilt)';
1519 if ($quilt_mode eq 'nocheck') {
1520 progress "Not doing any fixup of \`$format' due to --no-quilt-fixup";
1523 progress "Format \`$format', checking/updating patch stack";
1527 sub push_parse_changelog ($) {
1530 my $clogp = Dpkg::Control::Hash->new();
1531 $clogp->load($clogpfn) or die;
1533 $package = getfield $clogp, 'Source';
1534 my $cversion = getfield $clogp, 'Version';
1535 my $tag = debiantag($cversion);
1536 runcmd @git, qw(check-ref-format), $tag;
1538 my $dscfn = dscfn($cversion);
1540 return ($clogp, $cversion, $tag, $dscfn);
1543 sub push_parse_dsc ($$$) {
1544 my ($dscfn,$dscfnwhat, $cversion) = @_;
1545 $dsc = parsecontrol($dscfn,$dscfnwhat);
1546 my $dversion = getfield $dsc, 'Version';
1547 my $dscpackage = getfield $dsc, 'Source';
1548 ($dscpackage eq $package && $dversion eq $cversion) or
1549 fail "$dscfn is for $dscpackage $dversion".
1550 " but debian/changelog is for $package $cversion";
1553 sub push_mktag ($$$$$$$) {
1554 my ($head,$clogp,$tag,
1556 $changesfile,$changesfilewhat,
1559 $dsc->{$ourdscfield[0]} = $head;
1560 $dsc->save("$dscfn.tmp") or die $!;
1562 my $changes = parsecontrol($changesfile,$changesfilewhat);
1563 foreach my $field (qw(Source Distribution Version)) {
1564 $changes->{$field} eq $clogp->{$field} or
1565 fail "changes field $field \`$changes->{$field}'".
1566 " does not match changelog \`$clogp->{$field}'";
1569 my $cversion = getfield $clogp, 'Version';
1570 my $clogsuite = getfield $clogp, 'Distribution';
1572 # We make the git tag by hand because (a) that makes it easier
1573 # to control the "tagger" (b) we can do remote signing
1574 my $authline = clogp_authline $clogp;
1575 my $delibs = join(" ", "",@deliberatelies);
1576 my $declaredistro = access_basedistro();
1577 open TO, '>', $tfn->('.tmp') or die $!;
1578 print TO <<END or die $!;
1584 $package release $cversion for $clogsuite ($csuite) [dgit]
1585 [dgit distro=$declaredistro$delibs]
1587 foreach my $ref (sort keys %supersedes) {
1588 print TO <<END or die $!;
1589 [dgit supersede:$ref=$supersedes{$ref}]
1595 my $tagobjfn = $tfn->('.tmp');
1597 if (!defined $keyid) {
1598 $keyid = access_cfg('keyid','RETURN-UNDEF');
1600 unlink $tfn->('.tmp.asc') or $!==&ENOENT or die $!;
1601 my @sign_cmd = (@gpg, qw(--detach-sign --armor));
1602 push @sign_cmd, qw(-u),$keyid if defined $keyid;
1603 push @sign_cmd, $tfn->('.tmp');
1604 runcmd_ordryrun @sign_cmd;
1606 $tagobjfn = $tfn->('.signed.tmp');
1607 runcmd shell_cmd "exec >$tagobjfn", qw(cat --),
1608 $tfn->('.tmp'), $tfn->('.tmp.asc');
1615 sub sign_changes ($) {
1616 my ($changesfile) = @_;
1618 my @debsign_cmd = @debsign;
1619 push @debsign_cmd, "-k$keyid" if defined $keyid;
1620 push @debsign_cmd, "-p$gpg[0]" if $gpg[0] ne 'gpg';
1621 push @debsign_cmd, $changesfile;
1622 runcmd_ordryrun @debsign_cmd;
1627 printdebug "actually entering push\n";
1630 access_giturl(); # check that success is vaguely likely
1632 my $clogpfn = ".git/dgit/changelog.822.tmp";
1633 runcmd shell_cmd "exec >$clogpfn", qw(dpkg-parsechangelog);
1635 responder_send_file('parsed-changelog', $clogpfn);
1637 my ($clogp, $cversion, $tag, $dscfn) =
1638 push_parse_changelog("$clogpfn");
1640 my $dscpath = "$buildproductsdir/$dscfn";
1641 stat_exists $dscpath or
1642 fail "looked for .dsc $dscfn, but $!;".
1643 " maybe you forgot to build";
1645 responder_send_file('dsc', $dscpath);
1647 push_parse_dsc($dscpath, $dscfn, $cversion);
1649 my $format = getfield $dsc, 'Format';
1650 printdebug "format $format\n";
1651 if (madformat($format)) {
1652 commit_quilty_patch();
1656 progress "checking that $dscfn corresponds to HEAD";
1657 runcmd qw(dpkg-source -x --),
1658 $dscpath =~ m#^/# ? $dscpath : "../../../$dscpath";
1659 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1660 changedir '../../../..';
1661 my $diffopt = $debug>0 ? '--exit-code' : '--quiet';
1662 my @diffcmd = (@git, qw(diff), $diffopt, $tree);
1663 printcmd \*DEBUG,$debugprefix."+",@diffcmd;
1665 my $r = system @diffcmd;
1668 fail "$dscfn specifies a different tree to your HEAD commit;".
1669 " perhaps you forgot to build".
1670 ($diffopt eq '--exit-code' ? "" :
1671 " (run with -D to see full diff output)");
1677 #do fast forward check and maybe fake merge
1678 # if (!is_fast_fwd(mainbranch
1679 # runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
1680 # map { lref($_).":".rref($_) }
1682 my $head = rev_parse('HEAD');
1683 if (!$changesfile) {
1684 my $multi = "$buildproductsdir/".
1685 "${package}_".(stripepoch $cversion)."_multi.changes";
1686 if (stat_exists "$multi") {
1687 $changesfile = $multi;
1689 my $pat = "${package}_".(stripepoch $cversion)."_*.changes";
1690 my @cs = glob "$buildproductsdir/$pat";
1691 fail "failed to find unique changes file".
1692 " (looked for $pat in $buildproductsdir, or $multi);".
1693 " perhaps you need to use dgit -C"
1695 ($changesfile) = @cs;
1698 $changesfile = "$buildproductsdir/$changesfile";
1701 responder_send_file('changes',$changesfile);
1702 responder_send_command("param head $head");
1703 responder_send_command("param csuite $csuite");
1705 my $forceflag = deliberately('not-fast-forward') ? '+' : '';
1706 if ($forceflag && defined $lastpush_hash) {
1707 git_for_each_tag_referring($lastpush_hash, sub {
1708 my ($objid,$fullrefname,$tagname) = @_;
1709 responder_send_command("supersedes $fullrefname=$objid");
1710 $supersedes{$fullrefname} = $objid;
1714 my $tfn = sub { ".git/dgit/tag$_[0]"; };
1717 if ($we_are_responder) {
1718 $tagobjfn = $tfn->('.signed.tmp');
1719 responder_receive_files('signed-tag', $tagobjfn);
1722 push_mktag($head,$clogp,$tag,
1724 $changesfile,$changesfile,
1728 my $tag_obj_hash = cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
1729 runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
1730 runcmd_ordryrun_local @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
1731 runcmd_ordryrun @git, qw(tag -v --), $tag;
1733 if (!check_for_git()) {
1734 create_remote_git_repo();
1736 runcmd_ordryrun @git, qw(push),access_giturl(),
1737 $forceflag."HEAD:".rrref(), "refs/tags/$tag";
1738 runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), 'HEAD';
1740 if ($we_are_responder) {
1741 my $dryrunsuffix = act_local() ? "" : ".tmp";
1742 responder_receive_files('signed-dsc-changes',
1743 "$dscpath$dryrunsuffix",
1744 "$changesfile$dryrunsuffix");
1747 rename "$dscpath.tmp",$dscpath or die "$dscfn $!";
1749 progress "[new .dsc left in $dscpath.tmp]";
1751 sign_changes $changesfile;
1754 my $host = access_cfg('upload-host','RETURN-UNDEF');
1755 my @hostarg = defined($host) ? ($host,) : ();
1756 runcmd_ordryrun @dput, @hostarg, $changesfile;
1757 printdone "pushed and uploaded $cversion";
1759 responder_send_command("complete");
1765 badusage "-p is not allowed with clone; specify as argument instead"
1766 if defined $package;
1769 } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
1770 ($package,$isuite) = @ARGV;
1771 } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
1772 ($package,$dstdir) = @ARGV;
1773 } elsif (@ARGV==3) {
1774 ($package,$isuite,$dstdir) = @ARGV;
1776 badusage "incorrect arguments to dgit clone";
1778 $dstdir ||= "$package";
1780 if (stat_exists $dstdir) {
1781 fail "$dstdir already exists";
1785 if ($rmonerror && !$dryrun_level) {
1786 $cwd_remove= getcwd();
1788 return unless defined $cwd_remove;
1789 if (!chdir "$cwd_remove") {
1790 return if $!==&ENOENT;
1791 die "chdir $cwd_remove: $!";
1793 rmtree($dstdir) or die "remove $dstdir: $!\n";
1798 $cwd_remove = undef;
1801 sub branchsuite () {
1802 my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
1803 if ($branch =~ m#$lbranch_re#o) {
1810 sub fetchpullargs () {
1811 if (!defined $package) {
1812 my $sourcep = parsecontrol('debian/control','debian/control');
1813 $package = getfield $sourcep, 'Source';
1816 # $isuite = branchsuite(); # this doesn't work because dak hates canons
1818 my $clogp = parsechangelog();
1819 $isuite = getfield $clogp, 'Distribution';
1821 canonicalise_suite();
1822 progress "fetching from suite $csuite";
1823 } elsif (@ARGV==1) {
1825 canonicalise_suite();
1827 badusage "incorrect arguments to dgit fetch or dgit pull";
1845 badusage "-p is not allowed with dgit push" if defined $package;
1847 my $clogp = parsechangelog();
1848 $package = getfield $clogp, 'Source';
1851 } elsif (@ARGV==1) {
1852 ($specsuite) = (@ARGV);
1854 badusage "incorrect arguments to dgit push";
1856 $isuite = getfield $clogp, 'Distribution';
1858 local ($package) = $existing_package; # this is a hack
1859 canonicalise_suite();
1861 if (defined $specsuite && $specsuite ne $isuite) {
1862 canonicalise_suite();
1863 $csuite eq $specsuite or
1864 fail "dgit push: changelog specifies $isuite ($csuite)".
1865 " but command line specifies $specsuite";
1867 if (check_for_git()) {
1870 if (fetch_from_archive()) {
1871 is_fast_fwd(lrref(), 'HEAD') or
1872 fail "dgit push: HEAD is not a descendant".
1873 " of the archive's version.\n".
1874 "$us: To overwrite it, use git merge -s ours ".lrref().".";
1877 fail "package appears to be new in this suite;".
1878 " if this is intentional, use --new";
1883 #---------- remote commands' implementation ----------
1885 sub cmd_remote_push_build_host {
1886 my ($nrargs) = shift @ARGV;
1887 my (@rargs) = @ARGV[0..$nrargs-1];
1888 @ARGV = @ARGV[$nrargs..$#ARGV];
1890 my ($dir,$vsnwant) = @rargs;
1891 # vsnwant is a comma-separated list; we report which we have
1892 # chosen in our ready response (so other end can tell if they
1895 $we_are_responder = 1;
1897 open PI, "<&STDIN" or die $!;
1898 open STDIN, "/dev/null" or die $!;
1899 open PO, ">&STDOUT" or die $!;
1901 open STDOUT, ">&STDERR" or die $!;
1905 fail "build host has dgit rpush protocol version".
1906 " $rpushprotovsn but invocation host has $vsnwant"
1907 unless grep { $rpushprotovsn eq $_ } split /,/, $vsnwant;
1909 responder_send_command("dgit-remote-push-ready $rpushprotovsn");
1915 sub cmd_remote_push_responder { cmd_remote_push_build_host(); }
1916 # ... for compatibility with proto vsn.1 dgit (just so that user gets
1917 # a good error message)
1923 my $report = i_child_report();
1924 if (defined $report) {
1925 printdebug "($report)\n";
1926 } elsif ($i_child_pid) {
1927 printdebug "(killing build host child $i_child_pid)\n";
1928 kill 15, $i_child_pid;
1930 if (defined $i_tmp && !defined $initiator_tempdir) {
1932 eval { rmtree $i_tmp; };
1936 END { i_cleanup(); }
1939 my ($base,$selector,@args) = @_;
1940 $selector =~ s/\-/_/g;
1941 { no strict qw(refs); &{"${base}_${selector}"}(@args); }
1947 if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
1954 my @rargs = ($dir,$rpushprotovsn);
1957 push @rdgit, @ropts;
1958 push @rdgit, qw(remote-push-build-host), (scalar @rargs), @rargs;
1960 my @cmd = (@ssh, $host, shellquote @rdgit);
1961 printcmd \*DEBUG,$debugprefix."+",@cmd;
1963 if (defined $initiator_tempdir) {
1964 rmtree $initiator_tempdir;
1965 mkdir $initiator_tempdir, 0700 or die "$initiator_tempdir: $!";
1966 $i_tmp = $initiator_tempdir;
1970 $i_child_pid = open2(\*RO, \*RI, @cmd);
1972 initiator_expect { m/^dgit-remote-push-ready/ };
1974 my ($icmd,$iargs) = initiator_expect {
1975 m/^(\S+)(?: (.*))?$/;
1978 i_method "i_resp", $icmd, $iargs;
1982 sub i_resp_progress ($) {
1984 my $msg = protocol_read_bytes \*RO, $rhs;
1988 sub i_resp_complete {
1989 my $pid = $i_child_pid;
1990 $i_child_pid = undef; # prevents killing some other process with same pid
1991 printdebug "waiting for build host child $pid...\n";
1992 my $got = waitpid $pid, 0;
1993 die $! unless $got == $pid;
1994 die "build host child failed $?" if $?;
1997 printdebug "all done\n";
2001 sub i_resp_file ($) {
2003 my $localname = i_method "i_localname", $keyword;
2004 my $localpath = "$i_tmp/$localname";
2005 stat_exists $localpath and
2006 badproto \*RO, "file $keyword ($localpath) twice";
2007 protocol_receive_file \*RO, $localpath;
2008 i_method "i_file", $keyword;
2013 sub i_resp_param ($) {
2014 $_[0] =~ m/^(\S+) (.*)$/ or badproto \*RO, "bad param spec";
2018 sub i_resp_supersedes ($) {
2019 $_[0] =~ m#^(refs/tags/\S+)=(\w+)$#
2020 or badproto \*RO, "bad supersedes spec";
2021 my $r = system qw(git check-ref-format), $1;
2022 die "bad supersedes ref spec ($r)" if $r;
2023 $supersedes{$1} = $2;
2028 sub i_resp_want ($) {
2030 die "$keyword ?" if $i_wanted{$keyword}++;
2031 my @localpaths = i_method "i_want", $keyword;
2032 printdebug "[[ $keyword @localpaths\n";
2033 foreach my $localpath (@localpaths) {
2034 protocol_send_file \*RI, $localpath;
2036 print RI "files-end\n" or die $!;
2039 our ($i_clogp, $i_version, $i_tag, $i_dscfn, $i_changesfn);
2041 sub i_localname_parsed_changelog {
2042 return "remote-changelog.822";
2044 sub i_file_parsed_changelog {
2045 ($i_clogp, $i_version, $i_tag, $i_dscfn) =
2046 push_parse_changelog "$i_tmp/remote-changelog.822";
2047 die if $i_dscfn =~ m#/|^\W#;
2050 sub i_localname_dsc {
2051 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
2056 sub i_localname_changes {
2057 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
2058 $i_changesfn = $i_dscfn;
2059 $i_changesfn =~ s/\.dsc$/_dgit.changes/ or die;
2060 return $i_changesfn;
2062 sub i_file_changes { }
2064 sub i_want_signed_tag {
2065 printdebug Dumper(\%i_param, $i_dscfn);
2066 defined $i_param{'head'} && defined $i_dscfn && defined $i_clogp
2067 && defined $i_param{'csuite'}
2068 or badproto \*RO, "premature desire for signed-tag";
2069 my $head = $i_param{'head'};
2070 die if $head =~ m/[^0-9a-f]/ || $head !~ m/^../;
2072 die unless $i_param{'csuite'} =~ m/^$suite_re$/;
2074 push_parse_dsc $i_dscfn, 'remote dsc', $i_version;
2077 push_mktag $head, $i_clogp, $i_tag,
2079 $i_changesfn, 'remote changes',
2080 sub { "tag$_[0]"; };
2085 sub i_want_signed_dsc_changes {
2086 rename "$i_dscfn.tmp","$i_dscfn" or die "$i_dscfn $!";
2087 sign_changes $i_changesfn;
2088 return ($i_dscfn, $i_changesfn);
2091 #---------- building etc. ----------
2097 #----- `3.0 (quilt)' handling -----
2099 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
2101 sub quiltify_dpkg_commit ($$$;$) {
2102 my ($patchname,$author,$msg, $xinfo) = @_;
2106 my $descfn = ".git/dgit/quilt-description.tmp";
2107 open O, '>', $descfn or die "$descfn: $!";
2110 $msg =~ s/^\s+$/ ./mg;
2111 print O <<END or die $!;
2121 local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
2122 local $ENV{'VISUAL'} = $ENV{'EDITOR'};
2123 local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
2124 runcmd_ordryrun_local @dpkgsource, qw(--commit .), $patchname;
2128 sub quiltify_trees_differ ($$) {
2130 # returns 1 iff the two tree objects differ other than in debian/
2132 my @cmd = (@git, qw(diff-tree --name-only -z), $x, $y);
2133 my $diffs= cmdoutput @cmd;
2134 foreach my $f (split /\0/, $diffs) {
2135 next if $f eq 'debian';
2141 sub quiltify_tree_sentinelfiles ($) {
2142 # lists the `sentinel' files present in the tree
2144 my $r = cmdoutput @git, qw(ls-tree --name-only), $x,
2145 qw(-- debian/rules debian/control);
2151 my ($clogp,$target) = @_;
2153 # Quilt patchification algorithm
2155 # We search backwards through the history of the main tree's HEAD
2156 # (T) looking for a start commit S whose tree object is identical
2157 # to to the patch tip tree (ie the tree corresponding to the
2158 # current dpkg-committed patch series). For these purposes
2159 # `identical' disregards anything in debian/ - this wrinkle is
2160 # necessary because dpkg-source treates debian/ specially.
2162 # We can only traverse edges where at most one of the ancestors'
2163 # trees differs (in changes outside in debian/). And we cannot
2164 # handle edges which change .pc/ or debian/patches. To avoid
2165 # going down a rathole we avoid traversing edges which introduce
2166 # debian/rules or debian/control. And we set a limit on the
2167 # number of edges we are willing to look at.
2169 # If we succeed, we walk forwards again. For each traversed edge
2170 # PC (with P parent, C child) (starting with P=S and ending with
2171 # C=T) to we do this:
2173 # - dpkg-source --commit with a patch name and message derived from C
2174 # After traversing PT, we git commit the changes which
2175 # should be contained within debian/patches.
2177 changedir '../fake';
2178 mktree_in_ud_here();
2180 runcmd @git, 'add', '.';
2181 my $oldtiptree=git_write_tree();
2182 changedir '../work';
2184 # The search for the path S..T is breadth-first. We maintain a
2185 # todo list containing search nodes. A search node identifies a
2186 # commit, and looks something like this:
2188 # Commit => $git_commit_id,
2189 # Child => $c, # or undef if P=T
2190 # Whynot => $reason_edge_PC_unsuitable, # in @nots only
2191 # Nontrivial => true iff $p..$c has relevant changes
2198 my %considered; # saves being exponential on some weird graphs
2200 my $t_sentinels = quiltify_tree_sentinelfiles $target;
2203 my ($search,$whynot) = @_;
2204 printdebug " search NOT $search->{Commit} $whynot\n";
2205 $search->{Whynot} = $whynot;
2206 push @nots, $search;
2207 no warnings qw(exiting);
2216 my $c = shift @todo;
2217 next if $considered{$c->{Commit}}++;
2219 $not->($c, "maximum search space exceeded") if --$max_work <= 0;
2221 printdebug "quiltify investigate $c->{Commit}\n";
2224 if (!quiltify_trees_differ $c->{Commit}, $oldtiptree) {
2225 printdebug " search finished hooray!\n";
2230 if ($quilt_mode eq 'nofix') {
2231 fail "quilt fixup required but quilt mode is \`nofix'\n".
2232 "HEAD commit $c->{Commit} differs from tree implied by ".
2233 " debian/patches (tree object $oldtiptree)";
2235 if ($quilt_mode eq 'smash') {
2236 printdebug " search quitting smash\n";
2240 my $c_sentinels = quiltify_tree_sentinelfiles $c->{Commit};
2241 $not->($c, "has $c_sentinels not $t_sentinels")
2242 if $c_sentinels ne $t_sentinels;
2244 my $commitdata = cmdoutput @git, qw(cat-file commit), $c->{Commit};
2245 $commitdata =~ m/\n\n/;
2247 my @parents = ($commitdata =~ m/^parent (\w+)$/gm);
2248 @parents = map { { Commit => $_, Child => $c } } @parents;
2250 $not->($c, "root commit") if !@parents;
2252 foreach my $p (@parents) {
2253 $p->{Nontrivial}= quiltify_trees_differ $p->{Commit},$c->{Commit};
2255 my $ndiffers = grep { $_->{Nontrivial} } @parents;
2256 $not->($c, "merge ($ndiffers nontrivial parents)") if $ndiffers > 1;
2258 foreach my $p (@parents) {
2259 printdebug "considering C=$c->{Commit} P=$p->{Commit}\n";
2261 my @cmd= (@git, qw(diff-tree -r --name-only),
2262 $p->{Commit},$c->{Commit}, qw(-- debian/patches .pc));
2263 my $patchstackchange = cmdoutput @cmd;
2264 if (length $patchstackchange) {
2265 $patchstackchange =~ s/\n/,/g;
2266 $not->($p, "changed $patchstackchange");
2269 printdebug " search queue P=$p->{Commit} ",
2270 ($p->{Nontrivial} ? "NT" : "triv"),"\n";
2276 printdebug "quiltify want to smash\n";
2279 my $x = $_[0]{Commit};
2280 $x =~ s/(.*?[0-9a-z]{8})[0-9a-z]*$/$1/;
2283 my $reportnot = sub {
2285 my $s = $abbrev->($notp);
2286 my $c = $notp->{Child};
2287 $s .= "..".$abbrev->($c) if $c;
2288 $s .= ": ".$c->{Whynot};
2291 if ($quilt_mode eq 'linear') {
2292 print STDERR "$us: quilt fixup cannot be linear. Stopped at:\n";
2293 foreach my $notp (@nots) {
2294 print STDERR "$us: ", $reportnot->($notp), "\n";
2296 fail "quilt fixup naive history linearisation failed.\n".
2297 "Use dpkg-source --commit by hand; or, --quilt=smash for one ugly patch";
2298 } elsif ($quilt_mode eq 'smash') {
2299 } elsif ($quilt_mode eq 'auto') {
2300 progress "quilt fixup cannot be linear, smashing...";
2302 die "$quilt_mode ?";
2307 my $msg = cmdoutput @git, qw(log), "-n$ncommits";
2309 quiltify_dpkg_commit "auto-$version-$target-$time",
2310 (getfield $clogp, 'Maintainer'),
2311 "Automatically generated patch ($clogp->{Version})\n".
2312 "Last (up to) $ncommits git changes, FYI:\n\n". $msg;
2316 progress "quiltify linearisation planning successful, executing...";
2318 for (my $p = $sref_S;
2319 my $c = $p->{Child};
2321 printdebug "quiltify traverse $p->{Commit}..$c->{Commit}\n";
2322 next unless $p->{Nontrivial};
2324 my $cc = $c->{Commit};
2326 my $commitdata = cmdoutput @git, qw(cat-file commit), $cc;
2327 $commitdata =~ m/\n\n/ or die "$c ?";
2330 $commitdata =~ m/^author (.*) \d+ [-+0-9]+$/m or die "$cc ?";
2333 $msg =~ s/^(.*)\n*/$1\n/ or die "$cc $msg ?";
2336 my $patchname = $title;
2337 $patchname =~ s/[.:]$//;
2338 $patchname =~ y/ A-Z/-a-z/;
2339 $patchname =~ y/-a-z0-9_.+=~//cd;
2340 $patchname =~ s/^\W/x-$&/;
2341 $patchname = substr($patchname,0,40);
2344 stat "debian/patches/$patchname$index";
2346 $!==ENOENT or die "$patchname$index $!";
2348 runcmd @git, qw(checkout -q), $cc;
2350 # We use the tip's changelog so that dpkg-source doesn't
2351 # produce complaining messages from dpkg-parsechangelog. None
2352 # of the information dpkg-source gets from the changelog is
2353 # actually relevant - it gets put into the original message
2354 # which dpkg-source provides our stunt editor, and then
2356 runcmd @git, qw(checkout -q), $target, qw(debian/changelog);
2358 quiltify_dpkg_commit "$patchname$index", $author, $msg,
2359 "X-Dgit-Generated: $clogp->{Version} $cc\n";
2361 runcmd @git, qw(checkout -q), $cc, qw(debian/changelog);
2364 runcmd @git, qw(checkout -q master);
2367 sub build_maybe_quilt_fixup () {
2368 my $format=get_source_format;
2369 return unless madformat $format;
2373 # - honour any existing .pc in case it has any strangeness
2374 # - determine the git commit corresponding to the tip of
2375 # the patch stack (if there is one)
2376 # - if there is such a git commit, convert each subsequent
2377 # git commit into a quilt patch with dpkg-source --commit
2378 # - otherwise convert all the differences in the tree into
2379 # a single git commit
2383 # Our git tree doesn't necessarily contain .pc. (Some versions of
2384 # dgit would include the .pc in the git tree.) If there isn't
2385 # one, we need to generate one by unpacking the patches that we
2388 # We first look for a .pc in the git tree. If there is one, we
2389 # will use it. (This is not the normal case.)
2391 # Otherwise need to regenerate .pc so that dpkg-source --commit
2392 # can work. We do this as follows:
2393 # 1. Collect all relevant .orig from parent directory
2394 # 2. Generate a debian.tar.gz out of
2395 # debian/{patches,rules,source/format}
2396 # 3. Generate a fake .dsc containing just these fields:
2397 # Format Source Version Files
2398 # 4. Extract the fake .dsc
2399 # Now the fake .dsc has a .pc directory.
2400 # (In fact we do this in every case, because in future we will
2401 # want to search for a good base commit for generating patches.)
2403 # Then we can actually do the dpkg-source --commit
2404 # 1. Make a new working tree with the same object
2405 # store as our main tree and check out the main
2407 # 2. Copy .pc from the fake's extraction, if necessary
2408 # 3. Run dpkg-source --commit
2409 # 4. If the result has changes to debian/, then
2410 # - git-add them them
2411 # - git-add .pc if we had a .pc in-tree
2413 # 5. If we had a .pc in-tree, delete it, and git-commit
2414 # 6. Back in the main tree, fast forward to the new HEAD
2416 my $clogp = parsechangelog();
2417 my $headref = rev_parse('HEAD');
2422 my $upstreamversion=$version;
2423 $upstreamversion =~ s/-[^-]*$//;
2425 my $fakeversion="$upstreamversion-~~DGITFAKE";
2427 my $fakedsc=new IO::File 'fake.dsc', '>' or die $!;
2428 print $fakedsc <<END or die $!;
2431 Version: $fakeversion
2435 my $dscaddfile=sub {
2438 my $md = new Digest::MD5;
2440 my $fh = new IO::File $b, '<' or die "$b $!";
2445 print $fakedsc " ".$md->hexdigest." $size $b\n" or die $!;
2448 foreach my $f (<../../../../*>) { #/){
2449 my $b=$f; $b =~ s{.*/}{};
2450 next unless is_orig_file $b, srcfn $upstreamversion,'';
2451 link $f, $b or die "$b $!";
2455 my @files=qw(debian/source/format debian/rules);
2456 if (stat_exists '../../../debian/patches') {
2457 push @files, 'debian/patches';
2460 my $debtar= srcfn $fakeversion,'.debian.tar.gz';
2461 runcmd qw(env GZIP=-1 tar -zcf), "./$debtar", qw(-C ../../..), @files;
2463 $dscaddfile->($debtar);
2464 close $fakedsc or die $!;
2466 runcmd qw(sh -ec), 'exec dpkg-source --no-check -x fake.dsc >/dev/null';
2468 my $fakexdir= $package.'-'.(stripepoch $upstreamversion);
2469 rename $fakexdir, "fake" or die "$fakexdir $!";
2471 mkdir "work" or die $!;
2473 mktree_in_ud_here();
2474 runcmd @git, qw(reset --hard), $headref;
2477 if (stat_exists ".pc") {
2479 progress "Tree already contains .pc - will use it then delete it.";
2482 rename '../fake/.pc','.pc' or die $!;
2485 quiltify($clogp,$headref);
2487 if (!open P, '>>', ".pc/applied-patches") {
2488 $!==&ENOENT or die $!;
2493 commit_quilty_patch();
2495 if ($mustdeletepc) {
2496 runcmd @git, qw(rm -rq .pc);
2497 commit_admin "Commit removal of .pc (quilt series tracking data)";
2500 changedir '../../../..';
2501 runcmd @git, qw(pull --ff-only -q .git/dgit/unpack/work master);
2504 sub quilt_fixup_editor () {
2505 my $descfn = $ENV{$fakeeditorenv};
2506 my $editing = $ARGV[$#ARGV];
2507 open I1, '<', $descfn or die "$descfn: $!";
2508 open I2, '<', $editing or die "$editing: $!";
2509 unlink $editing or die "$editing: $!";
2510 open O, '>', $editing or die "$editing: $!";
2511 while (<I1>) { print O or die $!; } I1->error and die $!;
2514 $copying ||= m/^\-\-\- /;
2515 next unless $copying;
2518 I2->error and die $!;
2523 #----- other building -----
2526 if ($cleanmode eq 'dpkg-source') {
2527 runcmd_ordryrun_local @dpkgbuildpackage, qw(-T clean);
2528 } elsif ($cleanmode eq 'git') {
2529 runcmd_ordryrun_local @git, qw(clean -xdf);
2530 } elsif ($cleanmode eq 'none') {
2537 badusage "clean takes no additional arguments" if @ARGV;
2542 badusage "-p is not allowed when building" if defined $package;
2545 my $clogp = parsechangelog();
2546 $isuite = getfield $clogp, 'Distribution';
2547 $package = getfield $clogp, 'Source';
2548 $version = getfield $clogp, 'Version';
2549 build_maybe_quilt_fixup();
2552 sub changesopts () {
2553 my @opts =@changesopts[1..$#changesopts];
2554 if (!defined $changes_since_version) {
2555 my @vsns = archive_query('archive_query');
2556 my @quirk = access_quirk();
2557 if ($quirk[0] eq 'backports') {
2558 local $isuite = $quirk[2];
2560 canonicalise_suite();
2561 push @vsns, archive_query('archive_query');
2564 @vsns = map { $_->[0] } @vsns;
2565 @vsns = sort { -version_compare($a, $b) } @vsns;
2566 $changes_since_version = $vsns[0];
2567 progress "changelog will contain changes since $vsns[0]";
2569 $changes_since_version = '_';
2570 progress "package seems new, not specifying -v<version>";
2573 if ($changes_since_version ne '_') {
2574 unshift @opts, "-v$changes_since_version";
2581 runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc), changesopts(), @ARGV;
2582 printdone "build successful\n";
2588 (qw(git-buildpackage -us -uc --git-no-sign-tags),
2589 "--git-builder=@dpkgbuildpackage");
2590 unless (grep { m/^--git-debian-branch|^--git-ignore-branch/ } @ARGV) {
2591 canonicalise_suite();
2592 push @cmd, "--git-debian-branch=".lbranch();
2594 push @cmd, changesopts();
2595 runcmd_ordryrun_local @cmd, @ARGV;
2596 printdone "build successful\n";
2601 $sourcechanges = "${package}_".(stripepoch $version)."_source.changes";
2602 $dscfn = dscfn($version);
2603 if ($cleanmode eq 'dpkg-source') {
2604 runcmd_ordryrun_local (@dpkgbuildpackage, qw(-us -uc -S)),
2607 my $pwd = must_getcwd();
2608 my $leafdir = basename $pwd;
2610 runcmd_ordryrun_local @dpkgsource, qw(-b --), $leafdir;
2612 runcmd_ordryrun_local qw(sh -ec),
2613 'exec >$1; shift; exec "$@"','x',
2614 "../$sourcechanges",
2615 @dpkggenchanges, qw(-S), changesopts();
2619 sub cmd_build_source {
2620 badusage "build-source takes no additional arguments" if @ARGV;
2622 printdone "source built, results in $dscfn and $sourcechanges";
2628 my $pat = "${package}_".(stripepoch $version)."_*.changes";
2630 stat_exist $dscfn or fail "$dscfn (in parent directory): $!";
2631 stat_exists $sourcechanges
2632 or fail "$sourcechanges (in parent directory): $!";
2633 foreach my $cf (glob $pat) {
2634 next if $cf eq $sourcechanges;
2635 unlink $cf or fail "remove $cf: $!";
2638 runcmd_ordryrun_local @sbuild, @ARGV, qw(-d), $isuite, $dscfn;
2639 my @changesfiles = glob $pat;
2640 @changesfiles = sort {
2641 ($b =~ m/_source\.changes$/ <=> $a =~ m/_source\.changes$/)
2644 fail "wrong number of different changes files (@changesfiles)"
2645 unless @changesfiles;
2646 runcmd_ordryrun_local @mergechanges, @changesfiles;
2647 my $multichanges = "${package}_".(stripepoch $version)."_multi.changes";
2649 stat_exists $multichanges or fail "$multichanges: $!";
2651 printdone "build successful, results in $multichanges\n" or die $!;
2654 sub cmd_quilt_fixup {
2655 badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
2656 my $clogp = parsechangelog();
2657 $version = getfield $clogp, 'Version';
2658 $package = getfield $clogp, 'Source';
2659 build_maybe_quilt_fixup();
2662 sub cmd_archive_api_query {
2663 badusage "need only 1 subpath argument" unless @ARGV==1;
2664 my ($subpath) = @ARGV;
2665 my @cmd = archive_api_query_cmd($subpath);
2666 exec @cmd or fail "exec curl: $!\n";
2669 #---------- argument parsing and main program ----------
2672 print "dgit version $our_version\n" or die $!;
2679 if (defined $ENV{'DGIT_SSH'}) {
2680 @ssh = string_to_ssh $ENV{'DGIT_SSH'};
2681 } elsif (defined $ENV{'GIT_SSH'}) {
2682 @ssh = ($ENV{'GIT_SSH'});
2686 last unless $ARGV[0] =~ m/^-/;
2690 if (m/^--dry-run$/) {
2693 } elsif (m/^--damp-run$/) {
2696 } elsif (m/^--no-sign$/) {
2699 } elsif (m/^--help$/) {
2701 } elsif (m/^--version$/) {
2703 } elsif (m/^--new$/) {
2706 } elsif (m/^--since-version=([^_]+|_)$/) {
2708 $changes_since_version = $1;
2709 } elsif (m/^--([-0-9a-z]+)=(.*)/s &&
2710 ($om = $opts_opt_map{$1}) &&
2714 } elsif (m/^--([-0-9a-z]+):(.*)/s &&
2715 !$opts_opt_cmdonly{$1} &&
2716 ($om = $opts_opt_map{$1})) {
2719 } elsif (m/^--existing-package=(.*)/s) {
2721 $existing_package = $1;
2722 } elsif (m/^--initiator-tempdir=(.*)/s) {
2723 $initiator_tempdir = $1;
2724 $initiator_tempdir =~ m#^/# or
2725 badusage "--initiator-tempdir must be used specify an".
2726 " absolute, not relative, directory."
2727 } elsif (m/^--distro=(.*)/s) {
2730 } elsif (m/^--build-products-dir=(.*)/s) {
2732 $buildproductsdir = $1;
2733 } elsif (m/^--clean=(dpkg-source|git|none)$/s) {
2736 } elsif (m/^--clean=(.*)$/s) {
2737 badusage "unknown cleaning mode \`$1'";
2738 } elsif (m/^--quilt=($quilt_modes_re)$/s) {
2741 } elsif (m/^--quilt=(.*)$/s) {
2742 badusage "unknown quilt fixup mode \`$1'";
2743 } elsif (m/^--ignore-dirty$/s) {
2746 } elsif (m/^--no-quilt-fixup$/s) {
2748 $quilt_mode = 'nocheck';
2749 } elsif (m/^--no-rm-on-error$/s) {
2752 } elsif (m/^--deliberately-($suite_re)$/s) {
2754 push @deliberatelies, $&;
2756 badusage "unknown long option \`$_'";
2763 } elsif (s/^-L/-/) {
2766 } elsif (s/^-h/-/) {
2768 } elsif (s/^-D/-/) {
2770 open DEBUG, ">&STDERR" or die $!;
2773 } elsif (s/^-N/-/) {
2776 } elsif (s/^-v([^_]+|_)$//s) {
2778 $changes_since_version = $1;
2781 push @changesopts, $_;
2783 } elsif (s/^-c(.*=.*)//s) {
2785 push @git, '-c', $1;
2786 } elsif (s/^-d(.+)//s) {
2789 } elsif (s/^-C(.+)//s) {
2792 if ($changesfile =~ s#^(.*)/##) {
2793 $buildproductsdir = $1;
2795 } elsif (s/^-k(.+)//s) {
2797 } elsif (m/^-[vdCk]$/) {
2799 "option \`$_' requires an argument (and no space before the argument)";
2800 } elsif (s/^-wn$//s) {
2802 $cleanmode = 'none';
2803 } elsif (s/^-wg$//s) {
2806 } elsif (s/^-wd$//s) {
2808 $cleanmode = 'dpkg-source';
2810 badusage "unknown short option \`$_'";
2817 if ($ENV{$fakeeditorenv}) {
2818 quilt_fixup_editor();
2822 print STDERR "DRY RUN ONLY\n" if $dryrun_level > 1;
2823 print STDERR "DAMP RUN - WILL MAKE LOCAL (UNSIGNED) CHANGES\n"
2824 if $dryrun_level == 1;
2826 print STDERR $helpmsg or die $!;
2829 my $cmd = shift @ARGV;
2832 if (!defined $quilt_mode) {
2833 $quilt_mode = cfg('dgit.force.quilt-mode', 'RETURN-UNDEF')
2834 // access_cfg('quilt-mode', 'RETURN-UNDEF')
2836 $quilt_mode =~ m/^($quilt_modes_re)$/
2837 or badcfg "unknown quilt-mode \`$quilt_mode'";
2841 my $fn = ${*::}{"cmd_$cmd"};
2842 $fn or badusage "unknown operation $cmd";