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' => 'ftpmasterapi:',
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.upload-host' => 'ftp-master', # for dput
537 'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/',
538 'dgit-distro.debian.backports-quirk' => '(squeeze)-backports*',
539 'dgit-distro.debian-backports.mirror' => 'http://backports.debian.org/debian-backports/',
540 'dgit-distro.ubuntu.git-check' => 'false',
541 'dgit-distro.ubuntu.mirror' => 'http://archive.ubuntu.com/ubuntu',
542 'dgit-distro.test-dummy.ssh' => "$td/ssh",
543 'dgit-distro.test-dummy.username' => "alice",
544 'dgit-distro.test-dummy.git-check' => "ssh-cmd",
545 'dgit-distro.test-dummy.git-create' => "ssh-cmd",
546 'dgit-distro.test-dummy.git-url' => "$td/git",
547 'dgit-distro.test-dummy.git-host' => "git",
548 'dgit-distro.test-dummy.git-path' => "$td/git",
549 'dgit-distro.test-dummy.archive-query' => "dummycat:$td/aq",
550 'dgit-distro.test-dummy.mirror' => "file://$td/mirror/",
551 'dgit-distro.test-dummy.upload-host' => 'test-dummy',
556 return undef if $c =~ /RETURN-UNDEF/;
557 my @cmd = (@git, qw(config --), $c);
560 local ($debug) = $debug-1;
561 $v = cmdoutput_errok @cmd;
568 my $dv = $defcfg{$c};
569 return $dv if defined $dv;
571 badcfg "need value for one of: @_\n".
572 "$us: distro or suite appears not to be (properly) supported";
575 sub access_basedistro () {
576 if (defined $idistro) {
579 return cfg("dgit-suite.$isuite.distro",
580 "dgit.default.distro");
584 sub access_quirk () {
585 # returns (quirk name, distro to use instead or undef, quirk-specific info)
586 my $basedistro = access_basedistro();
587 my $backports_quirk = cfg("dgit-distro.$basedistro.backports-quirk",
589 if (defined $backports_quirk) {
590 my $re = $backports_quirk;
591 $re =~ s/[^-0-9a-z_\%*()]/\\$&/ig;
593 $re =~ s/\%/([-0-9a-z_]+)/
594 or $re =~ m/[()]/ or badcfg "backports-quirk needs \% or ( )";
595 if ($isuite =~ m/^$re$/) {
596 return ('backports',"$basedistro-backports",$1);
599 return ('none',undef);
602 sub access_distros () {
603 # Returns list of distros to try, in order
606 # 0. `instead of' distro name(s) we have been pointed to
607 # 1. the access_quirk distro, if any
608 # 2a. the user's specified distro, or failing that } basedistro
609 # 2b. the distro calculated from the suite }
610 my @l = access_basedistro();
612 my (undef,$quirkdistro) = access_quirk();
613 unshift @l, $quirkdistro;
614 unshift @l, $instead_distro;
615 return grep { defined } @l;
621 # The nesting of these loops determines the search order. We put
622 # the key loop on the outside so that we search all the distros
623 # for each key, before going on to the next key. That means that
624 # if access_cfg is called with a more specific, and then a less
625 # specific, key, an earlier distro can override the less specific
626 # without necessarily overriding any more specific keys. (If the
627 # distro wants to override the more specific keys it can simply do
628 # so; whereas if we did the loop the other way around, it would be
629 # impossible to for an earlier distro to override a less specific
630 # key but not the more specific ones without restating the unknown
631 # values of the more specific keys.
634 # We have to deal with RETURN-UNDEF specially, so that we don't
635 # terminate the search prematurely.
637 if (m/RETURN-UNDEF/) { push @rundef, $_; last; }
640 foreach my $d (access_distros()) {
641 push @cfgs, map { "dgit-distro.$d.$_" } @realkeys;
643 push @cfgs, map { "dgit.default.$_" } @realkeys;
645 my $value = cfg(@cfgs);
649 sub string_to_ssh ($) {
651 if ($spec =~ m/\s/) {
652 return qw(sh -ec), 'exec '.$spec.' "$@"', 'x';
658 sub access_cfg_ssh () {
659 my $gitssh = access_cfg('ssh', 'RETURN-UNDEF');
660 if (!defined $gitssh) {
663 return string_to_ssh $gitssh;
667 sub access_runeinfo ($) {
669 return ": dgit ".access_basedistro()." $info ;";
672 sub access_someuserhost ($) {
674 my $user = access_cfg("$some-user-force", 'RETURN-UNDEF');
675 defined($user) && length($user) or
676 $user = access_cfg("$some-user",'username');
677 my $host = access_cfg("$some-host");
678 return length($user) ? "$user\@$host" : $host;
681 sub access_gituserhost () {
682 return access_someuserhost('git');
685 sub access_giturl (;$) {
687 my $url = access_cfg('git-url','RETURN-UNDEF');
689 my $proto = access_cfg('git-proto', 'RETURN-UNDEF');
690 return undef unless defined $proto;
693 access_gituserhost().
694 access_cfg('git-path');
696 return "$url/$package.git";
699 sub parsecontrolfh ($$;$) {
700 my ($fh, $desc, $allowsigned) = @_;
701 our $dpkgcontrolhash_noissigned;
704 my %opts = ('name' => $desc);
705 $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
706 $c = Dpkg::Control::Hash->new(%opts);
707 $c->parse($fh,$desc) or die "parsing of $desc failed";
708 last if $allowsigned;
709 last if $dpkgcontrolhash_noissigned;
710 my $issigned= $c->get_option('is_pgp_signed');
711 if (!defined $issigned) {
712 $dpkgcontrolhash_noissigned= 1;
713 seek $fh, 0,0 or die "seek $desc: $!";
714 } elsif ($issigned) {
715 fail "control file $desc is (already) PGP-signed. ".
716 " Note that dgit push needs to modify the .dsc and then".
717 " do the signature itself";
726 my ($file, $desc) = @_;
727 my $fh = new IO::Handle;
728 open $fh, '<', $file or die "$file: $!";
729 my $c = parsecontrolfh($fh,$desc);
730 $fh->error and die $!;
736 my ($dctrl,$field) = @_;
737 my $v = $dctrl->{$field};
738 return $v if defined $v;
739 fail "missing field $field in ".$v->get_option('name');
743 my $c = Dpkg::Control::Hash->new();
744 my $p = new IO::Handle;
745 my @cmd = (qw(dpkg-parsechangelog), @_);
746 open $p, '-|', @cmd or die $!;
748 $?=0; $!=0; close $p or failedcmd @cmd;
752 sub git_get_ref ($) {
754 my $got = cmdoutput_errok @git, qw(show-ref --), $refname;
756 $?==256 or fail "git show-ref failed (status $?)";
757 printdebug "ref $refname= [show-ref exited 1]\n";
760 if ($got =~ m/^(\w+) \Q$refname\E$/m) {
761 printdebug "ref $refname=$1\n";
764 printdebug "ref $refname= [no match]\n";
771 defined $d or fail "getcwd failed: $!";
777 sub archive_query ($) {
779 my $query = access_cfg('archive-query','RETURN-UNDEF');
780 $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
783 { no strict qw(refs); &{"${method}_${proto}"}($proto,$data); }
786 sub pool_dsc_subpath ($$) {
787 my ($vsn,$component) = @_; # $package is implict arg
788 my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
789 return "/pool/$component/$prefix/$package/".dscfn($vsn);
792 #---------- `ftpmasterapi' archive query method (nascent) ----------
794 sub archive_api_query_cmd ($) {
796 my @cmd = qw(curl -sS);
797 my $url = access_cfg('archive-query-url');
798 if ($url =~ m#^https://([-.0-9a-z]+)/#) {
800 my $keys = access_cfg('archive-query-tls-key','RETURN-UNDEF');
801 foreach my $key (split /\:/, $keys) {
802 $key =~ s/\%HOST\%/$host/g;
804 fail "for $url: stat $key: $!" unless $!==ENOENT;
807 push @cmd, "--ca-certificate=$key", "--ca-directory=/dev/enoent";
811 push @cmd, $url.$subpath;
817 my ($data, $subpath) = @_;
818 badcfg "ftpmasterapi archive query method takes no data part"
820 my @cmd = archive_api_query_cmd($subpath);
821 my $json = cmdoutput @cmd;
822 return decode_json($json);
825 sub canonicalise_suite_ftpmasterapi () {
826 my ($proto,$data) = @_;
827 my $suites = api_query($data, 'suites');
829 foreach my $entry (@$suites) {
831 my $v = $entry->{$_};
832 defined $v && $v eq $isuite;
834 push @matched, $entry;
836 fail "unknown suite $isuite" unless @matched;
839 @matched==1 or die "multiple matches for suite $isuite\n";
840 $cn = "$matched[0]{codename}";
841 defined $cn or die "suite $isuite info has no codename\n";
842 $cn =~ m/^$suite_re$/ or die "suite $isuite maps to bad codename\n";
844 die "bad ftpmaster api response: $@\n".Dumper(\@matched)
849 sub archive_query_ftpmasterapi () {
850 my ($proto,$data) = @_;
851 my $info = api_query($data, "dsc_in_suite/$isuite/$package");
853 my $digester = Digest::SHA->new(256);
854 foreach my $entry (@$info) {
856 my $vsn = "$entry->{version}";
857 my ($ok,$msg) = version_check $vsn;
858 die "bad version: $msg\n" unless $ok;
859 my $component = "$entry->{component}";
860 $component =~ m/^$component_re$/ or die "bad component";
861 my $filename = "$entry->{filename}";
862 $filename && $filename !~ m#[^-+:._~0-9a-zA-Z/]|^[/.]|/[/.]#
863 or die "bad filename";
864 my $sha256sum = "$entry->{sha256sum}";
865 $sha256sum =~ m/^[0-9a-f]+$/ or die "bad sha256sum";
866 push @rows, [ $vsn, "/pool/$component/$filename",
867 $digester, $sha256sum ];
869 die "bad ftpmaster api response: $@\n".Dumper($entry)
872 @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
876 #---------- `madison' archive query method ----------
878 sub archive_query_madison {
879 return map { [ @$_[0..1] ] } madison_get_parse(@_);
882 sub madison_get_parse {
883 my ($proto,$data) = @_;
884 die unless $proto eq 'madison';
886 $data= access_cfg('madison-distro','RETURN-UNDEF');
887 $data //= access_basedistro();
889 $rmad{$proto,$data,$package} ||= cmdoutput
890 qw(rmadison -asource),"-s$isuite","-u$data",$package;
891 my $rmad = $rmad{$proto,$data,$package};
894 foreach my $l (split /\n/, $rmad) {
895 $l =~ m{^ \s*( [^ \t|]+ )\s* \|
896 \s*( [^ \t|]+ )\s* \|
897 \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
898 \s*( [^ \t|]+ )\s* }x or die "$rmad ?";
899 $1 eq $package or die "$rmad $package ?";
906 $component = access_cfg('archive-query-default-component');
908 $5 eq 'source' or die "$rmad ?";
909 push @out, [$vsn,pool_dsc_subpath($vsn,$component),$newsuite];
911 return sort { -version_compare($a->[0],$b->[0]); } @out;
914 sub canonicalise_suite_madison {
915 # madison canonicalises for us
916 my @r = madison_get_parse(@_);
918 "unable to canonicalise suite using package $package".
919 " which does not appear to exist in suite $isuite;".
920 " --existing-package may help";
924 #---------- `sshpsql' archive query method ----------
927 my ($data,$runeinfo,$sql) = @_;
929 $data= access_someuserhost('sshpsql').':'.
930 access_cfg('sshpsql-dbname');
932 $data =~ m/:/ or badcfg "invalid sshpsql method string \`$data'";
933 my ($userhost,$dbname) = ($`,$'); #';
935 my @cmd = (access_cfg_ssh, $userhost,
936 access_runeinfo("ssh-psql $runeinfo").
938 " ".shellquote qw(psql -A), $dbname, qw(-c), $sql);
939 printcmd(\*DEBUG,$debugprefix."|",@cmd) if $debug>0;
940 open P, "-|", @cmd or die $!;
943 printdebug("$debugprefix>|$_|\n");
946 $!=0; $?=0; close P or failedcmd @cmd;
948 my $nrows = pop @rows;
949 $nrows =~ s/^\((\d+) rows?\)$/$1/ or die "$nrows ?";
950 @rows == $nrows+1 or die "$nrows ".(scalar @rows)." ?";
951 @rows = map { [ split /\|/, $_ ] } @rows;
952 my $ncols = scalar @{ shift @rows };
953 die if grep { scalar @$_ != $ncols } @rows;
957 sub sql_injection_check {
958 foreach (@_) { die "$_ $& ?" if m{[^-+=:_.,/0-9a-zA-Z]}; }
961 sub archive_query_sshpsql ($$) {
962 my ($proto,$data) = @_;
963 sql_injection_check $isuite, $package;
964 my @rows = sshpsql($data, "archive-query $isuite $package", <<END);
965 SELECT source.version, component.name, files.filename, files.sha256sum
967 JOIN src_associations ON source.id = src_associations.source
968 JOIN suite ON suite.id = src_associations.suite
969 JOIN dsc_files ON dsc_files.source = source.id
970 JOIN files_archive_map ON files_archive_map.file_id = dsc_files.file
971 JOIN component ON component.id = files_archive_map.component_id
972 JOIN files ON files.id = dsc_files.file
973 WHERE ( suite.suite_name='$isuite' OR suite.codename='$isuite' )
974 AND source.source='$package'
975 AND files.filename LIKE '%.dsc';
977 @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
978 my $digester = Digest::SHA->new(256);
980 my ($vsn,$component,$filename,$sha256sum) = @$_;
981 [ $vsn, "/pool/$component/$filename",$digester,$sha256sum ];
986 sub canonicalise_suite_sshpsql ($$) {
987 my ($proto,$data) = @_;
988 sql_injection_check $isuite;
989 my @rows = sshpsql($data, "canonicalise-suite $isuite", <<END);
990 SELECT suite.codename
991 FROM suite where suite_name='$isuite' or codename='$isuite';
993 @rows = map { $_->[0] } @rows;
994 fail "unknown suite $isuite" unless @rows;
995 die "ambiguous $isuite: @rows ?" if @rows>1;
999 #---------- `dummycat' archive query method ----------
1001 sub canonicalise_suite_dummycat ($$) {
1002 my ($proto,$data) = @_;
1003 my $dpath = "$data/suite.$isuite";
1004 if (!open C, "<", $dpath) {
1005 $!==ENOENT or die "$dpath: $!";
1006 printdebug "dummycat canonicalise_suite $isuite $dpath ENOENT\n";
1010 chomp or die "$dpath: $!";
1012 printdebug "dummycat canonicalise_suite $isuite $dpath = $_\n";
1016 sub archive_query_dummycat ($$) {
1017 my ($proto,$data) = @_;
1018 canonicalise_suite();
1019 my $dpath = "$data/package.$csuite.$package";
1020 if (!open C, "<", $dpath) {
1021 $!==ENOENT or die "$dpath: $!";
1022 printdebug "dummycat query $csuite $package $dpath ENOENT\n";
1030 printdebug "dummycat query $csuite $package $dpath | $_\n";
1031 my @row = split /\s+/, $_;
1032 @row==2 or die "$dpath: $_ ?";
1035 C->error and die "$dpath: $!";
1037 return sort { -version_compare($a->[0],$b->[0]); } @rows;
1040 #---------- archive query entrypoints and rest of program ----------
1042 sub canonicalise_suite () {
1043 return if defined $csuite;
1044 fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
1045 $csuite = archive_query('canonicalise_suite');
1046 if ($isuite ne $csuite) {
1047 progress "canonical suite name for $isuite is $csuite";
1051 sub get_archive_dsc () {
1052 canonicalise_suite();
1053 my @vsns = archive_query('archive_query');
1054 foreach my $vinfo (@vsns) {
1055 my ($vsn,$subpath,$digester,$digest) = @$vinfo;
1056 $dscurl = access_cfg('mirror').$subpath;
1057 $dscdata = url_get($dscurl);
1059 $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
1064 $digester->add($dscdata);
1065 my $got = $digester->hexdigest();
1067 fail "$dscurl has hash $got but".
1068 " archive told us to expect $digest";
1070 my $dscfh = new IO::File \$dscdata, '<' or die $!;
1071 printdebug Dumper($dscdata) if $debug>1;
1072 $dsc = parsecontrolfh($dscfh,$dscurl,1);
1073 printdebug Dumper($dsc) if $debug>1;
1074 my $fmt = getfield $dsc, 'Format';
1075 fail "unsupported source format $fmt, sorry" unless $format_ok{$fmt};
1076 $dsc_checked = !!$digester;
1082 sub check_for_git ();
1083 sub check_for_git () {
1085 my $how = access_cfg('git-check');
1086 if ($how eq 'ssh-cmd') {
1088 (access_cfg_ssh, access_gituserhost(),
1089 access_runeinfo("git-check $package").
1090 " set -e; cd ".access_cfg('git-path').";".
1091 " if test -d $package.git; then echo 1; else echo 0; fi");
1092 my $r= cmdoutput @cmd;
1093 if ($r =~ m/^divert (\w+)$/) {
1095 my ($usedistro,) = access_distros();
1096 $instead_distro= cfg("dgit-distro.$usedistro.diverts.$divert");
1097 $instead_distro =~ s{^/}{ access_basedistro()."/" }e;
1098 printdebug "diverting $divert so using distro $instead_distro\n";
1099 return check_for_git();
1101 failedcmd @cmd unless $r =~ m/^[01]$/;
1103 } elsif ($how eq 'true') {
1105 } elsif ($how eq 'false') {
1108 badcfg "unknown git-check \`$how'";
1112 sub create_remote_git_repo () {
1113 my $how = access_cfg('git-create');
1114 if ($how eq 'ssh-cmd') {
1116 (access_cfg_ssh, access_gituserhost(),
1117 access_runeinfo("git-create $package").
1118 "set -e; cd ".access_cfg('git-path').";".
1119 " cp -a _template $package.git");
1120 } elsif ($how eq 'true') {
1123 badcfg "unknown git-create \`$how'";
1127 our ($dsc_hash,$lastpush_hash);
1129 our $ud = '.git/dgit/unpack';
1134 mkdir $ud or die $!;
1137 sub mktree_in_ud_here () {
1138 runcmd qw(git init -q);
1139 rmtree('.git/objects');
1140 symlink '../../../../objects','.git/objects' or die $!;
1143 sub git_write_tree () {
1144 my $tree = cmdoutput @git, qw(write-tree);
1145 $tree =~ m/^\w+$/ or die "$tree ?";
1149 sub mktree_in_ud_from_only_subdir () {
1150 # changes into the subdir
1152 die unless @dirs==1;
1153 $dirs[0] =~ m#^([^/]+)/\.$# or die;
1156 fail "source package contains .git directory" if stat_exists '.git';
1157 mktree_in_ud_here();
1158 my $format=get_source_format();
1159 if (madformat($format)) {
1162 runcmd @git, qw(add -Af);
1163 my $tree=git_write_tree();
1164 return ($tree,$dir);
1167 sub dsc_files_info () {
1168 foreach my $csumi (['Checksums-Sha256','Digest::SHA', 'new(256)'],
1169 ['Checksums-Sha1', 'Digest::SHA', 'new(1)'],
1170 ['Files', 'Digest::MD5', 'new()']) {
1171 my ($fname, $module, $method) = @$csumi;
1172 my $field = $dsc->{$fname};
1173 next unless defined $field;
1174 eval "use $module; 1;" or die $@;
1176 foreach (split /\n/, $field) {
1178 m/^(\w+) (\d+) (\S+)$/ or
1179 fail "could not parse .dsc $fname line \`$_'";
1180 my $digester = eval "$module"."->$method;" or die $@;
1185 Digester => $digester,
1190 fail "missing any supported Checksums-* or Files field in ".
1191 $dsc->get_option('name');
1195 map { $_->{Filename} } dsc_files_info();
1198 sub is_orig_file ($;$) {
1201 m/\.orig(?:-\w+)?\.tar\.\w+$/ or return 0;
1202 defined $base or return 1;
1206 sub make_commit ($) {
1208 return cmdoutput @git, qw(hash-object -w -t commit), $file;
1211 sub clogp_authline ($) {
1213 my $author = getfield $clogp, 'Maintainer';
1214 $author =~ s#,.*##ms;
1215 my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
1216 my $authline = "$author $date";
1217 $authline =~ m/^[^<>]+ \<\S+\> \d+ [-+]\d+$/ or
1218 fail "unexpected commit author line format \`$authline'".
1219 " (was generated from changelog Maintainer field)";
1223 sub generate_commit_from_dsc () {
1227 foreach my $fi (dsc_files_info()) {
1228 my $f = $fi->{Filename};
1229 die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
1231 link "../../../$f", $f
1235 complete_file_from_dsc('.', $fi);
1237 if (is_orig_file($f)) {
1238 link $f, "../../../../$f"
1244 my $dscfn = "$package.dsc";
1246 open D, ">", $dscfn or die "$dscfn: $!";
1247 print D $dscdata or die "$dscfn: $!";
1248 close D or die "$dscfn: $!";
1249 my @cmd = qw(dpkg-source);
1250 push @cmd, '--no-check' if $dsc_checked;
1251 push @cmd, qw(-x --), $dscfn;
1254 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1255 runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
1256 my $clogp = parsecontrol('../changelog.tmp',"commit's changelog");
1257 my $authline = clogp_authline $clogp;
1258 my $changes = getfield $clogp, 'Changes';
1259 open C, ">../commit.tmp" or die $!;
1260 print C <<END or die $!;
1267 # imported from the archive
1270 my $outputhash = make_commit qw(../commit.tmp);
1271 my $cversion = getfield $clogp, 'Version';
1272 progress "synthesised git commit from .dsc $cversion";
1273 if ($lastpush_hash) {
1274 runcmd @git, qw(reset --hard), $lastpush_hash;
1275 runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
1276 my $oldclogp = parsecontrol('../changelogold.tmp','previous changelog');
1277 my $oversion = getfield $oldclogp, 'Version';
1279 version_compare($oversion, $cversion);
1281 # git upload/ is earlier vsn than archive, use archive
1282 open C, ">../commit2.tmp" or die $!;
1283 print C <<END or die $!;
1285 parent $lastpush_hash
1290 Record $package ($cversion) in archive suite $csuite
1292 $outputhash = make_commit qw(../commit2.tmp);
1293 } elsif ($vcmp > 0) {
1294 print STDERR <<END or die $!;
1296 Version actually in archive: $cversion (older)
1297 Last allegedly pushed/uploaded: $oversion (newer or same)
1300 $outputhash = $lastpush_hash;
1302 $outputhash = $lastpush_hash;
1305 changedir '../../../..';
1306 runcmd @git, qw(update-ref -m),"dgit fetch import $cversion",
1307 'DGIT_ARCHIVE', $outputhash;
1308 cmdoutput @git, qw(log -n2), $outputhash;
1309 # ... gives git a chance to complain if our commit is malformed
1314 sub complete_file_from_dsc ($$) {
1315 our ($dstdir, $fi) = @_;
1316 # Ensures that we have, in $dir, the file $fi, with the correct
1317 # contents. (Downloading it from alongside $dscurl if necessary.)
1319 my $f = $fi->{Filename};
1320 my $tf = "$dstdir/$f";
1323 if (stat_exists $tf) {
1324 progress "using existing $f";
1327 $furl =~ s{/[^/]+$}{};
1329 die "$f ?" unless $f =~ m/^${package}_/;
1330 die "$f ?" if $f =~ m#/#;
1331 runcmd_ordryrun_local @curl,qw(-o),$tf,'--',"$furl";
1332 next if !act_local();
1336 open F, "<", "$tf" or die "$tf: $!";
1337 $fi->{Digester}->reset();
1338 $fi->{Digester}->addfile(*F);
1339 F->error and die $!;
1340 my $got = $fi->{Digester}->hexdigest();
1341 $got eq $fi->{Hash} or
1342 fail "file $f has hash $got but .dsc".
1343 " demands hash $fi->{Hash} ".
1344 ($downloaded ? "(got wrong file from archive!)"
1345 : "(perhaps you should delete this file?)");
1348 sub ensure_we_have_orig () {
1349 foreach my $fi (dsc_files_info()) {
1350 my $f = $fi->{Filename};
1351 next unless is_orig_file($f);
1352 complete_file_from_dsc('..', $fi);
1357 return cmdoutput @git, qw(rev-parse), "$_[0]~0";
1360 sub is_fast_fwd ($$) {
1361 my ($ancestor,$child) = @_;
1362 my @cmd = (@git, qw(merge-base), $ancestor, $child);
1363 my $mb = cmdoutput_errok @cmd;
1365 return rev_parse($mb) eq rev_parse($ancestor);
1367 $?==256 or failedcmd @cmd;
1372 sub git_fetch_us () {
1373 runcmd_ordryrun_local @git, qw(fetch),access_giturl(),fetchspec();
1376 sub fetch_from_archive () {
1377 # ensures that lrref() is what is actually in the archive,
1378 # one way or another
1382 foreach my $field (@ourdscfield) {
1383 $dsc_hash = $dsc->{$field};
1384 last if defined $dsc_hash;
1386 if (defined $dsc_hash) {
1387 $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
1389 progress "last upload to archive specified git hash";
1391 progress "last upload to archive has NO git hash";
1394 progress "no version available from the archive";
1397 $lastpush_hash = git_get_ref(lrref());
1398 printdebug "previous reference hash=$lastpush_hash\n";
1400 if (defined $dsc_hash) {
1401 fail "missing remote git history even though dsc has hash -".
1402 " could not find ref ".lrref().
1403 " (should have been fetched from ".access_giturl()."#".rrref().")"
1404 unless $lastpush_hash;
1406 ensure_we_have_orig();
1407 if ($dsc_hash eq $lastpush_hash) {
1408 } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
1409 print STDERR <<END or die $!;
1411 Git commit in archive is behind the last version allegedly pushed/uploaded.
1412 Commit referred to by archive: $dsc_hash
1413 Last allegedly pushed/uploaded: $lastpush_hash
1416 $hash = $lastpush_hash;
1418 fail "git head (".lrref()."=$lastpush_hash) is not a ".
1419 "descendant of archive's .dsc hash ($dsc_hash)";
1422 $hash = generate_commit_from_dsc();
1423 } elsif ($lastpush_hash) {
1424 # only in git, not in the archive yet
1425 $hash = $lastpush_hash;
1426 print STDERR <<END or die $!;
1428 Package not found in the archive, but has allegedly been pushed using dgit.
1432 printdebug "nothing found!\n";
1433 if (defined $skew_warning_vsn) {
1434 print STDERR <<END or die $!;
1436 Warning: relevant archive skew detected.
1437 Archive allegedly contains $skew_warning_vsn
1438 But we were not able to obtain any version from the archive or git.
1444 printdebug "current hash=$hash\n";
1445 if ($lastpush_hash) {
1446 fail "not fast forward on last upload branch!".
1447 " (archive's version left in DGIT_ARCHIVE)"
1448 unless is_fast_fwd($lastpush_hash, $hash);
1450 if (defined $skew_warning_vsn) {
1452 printdebug "SKEW CHECK WANT $skew_warning_vsn\n";
1453 my $clogf = ".git/dgit/changelog.tmp";
1454 runcmd shell_cmd "exec >$clogf",
1455 @git, qw(cat-file blob), "$hash:debian/changelog";
1456 my $gotclogp = parsechangelog("-l$clogf");
1457 my $got_vsn = getfield $gotclogp, 'Version';
1458 printdebug "SKEW CHECK GOT $got_vsn\n";
1459 if (version_compare($got_vsn, $skew_warning_vsn) < 0) {
1460 print STDERR <<END or die $!;
1462 Warning: archive skew detected. Using the available version:
1463 Archive allegedly contains $skew_warning_vsn
1464 We were able to obtain only $got_vsn
1469 if ($lastpush_hash ne $hash) {
1470 my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
1474 dryrun_report @upd_cmd;
1482 canonicalise_suite();
1483 badusage "dry run makes no sense with clone" unless act_local();
1484 my $hasgit = check_for_git();
1485 mkdir $dstdir or die "$dstdir $!";
1487 runcmd @git, qw(init -q);
1488 my $giturl = access_giturl(1);
1489 if (defined $giturl) {
1490 runcmd @git, qw(config), "remote.$remotename.fetch", fetchspec();
1491 open H, "> .git/HEAD" or die $!;
1492 print H "ref: ".lref()."\n" or die $!;
1494 runcmd @git, qw(remote add), 'origin', $giturl;
1497 progress "fetching existing git history";
1499 runcmd_ordryrun_local @git, qw(fetch origin);
1501 progress "starting new git history";
1503 fetch_from_archive() or no_such_package;
1504 my $vcsgiturl = $dsc->{'Vcs-Git'};
1505 $vcsgiturl =~ s/\s+-b\s+\S+//g;
1506 if (length $vcsgiturl) {
1507 runcmd @git, qw(remote add vcs-git), $vcsgiturl;
1509 runcmd @git, qw(reset --hard), lrref();
1510 printdone "ready for work in $dstdir";
1514 if (check_for_git()) {
1517 fetch_from_archive() or no_such_package();
1518 printdone "fetched into ".lrref();
1523 runcmd_ordryrun_local @git, qw(merge -m),"Merge from $csuite [dgit]",
1525 printdone "fetched to ".lrref()." and merged into HEAD";
1528 sub check_not_dirty () {
1529 return if $ignoredirty;
1530 my @cmd = (@git, qw(diff --quiet HEAD));
1531 printcmd(\*DEBUG,$debugprefix."+",@cmd) if $debug>0;
1532 $!=0; $?=0; system @cmd;
1533 return if !$! && !$?;
1534 if (!$! && $?==256) {
1535 fail "working tree is dirty (does not match HEAD)";
1541 sub commit_admin ($) {
1544 runcmd_ordryrun_local @git, qw(commit -m), $m;
1547 sub commit_quilty_patch () {
1548 my $output = cmdoutput @git, qw(status --porcelain);
1550 foreach my $l (split /\n/, $output) {
1551 next unless $l =~ m/\S/;
1552 if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
1556 delete $adds{'.pc'}; # if there wasn't one before, don't add it
1558 progress "nothing quilty to commit, ok.";
1561 runcmd_ordryrun_local @git, qw(add), sort keys %adds;
1562 commit_admin "Commit Debian 3.0 (quilt) metadata";
1565 sub get_source_format () {
1566 if (!open F, "debian/source/format") {
1567 die $! unless $!==&ENOENT;
1571 F->error and die $!;
1578 return 0 unless $format eq '3.0 (quilt)';
1579 if ($quilt_mode eq 'nocheck') {
1580 progress "Not doing any fixup of \`$format' due to --no-quilt-fixup";
1583 progress "Format \`$format', checking/updating patch stack";
1587 sub push_parse_changelog ($) {
1590 my $clogp = Dpkg::Control::Hash->new();
1591 $clogp->load($clogpfn) or die;
1593 $package = getfield $clogp, 'Source';
1594 my $cversion = getfield $clogp, 'Version';
1595 my $tag = debiantag($cversion);
1596 runcmd @git, qw(check-ref-format), $tag;
1598 my $dscfn = dscfn($cversion);
1600 return ($clogp, $cversion, $tag, $dscfn);
1603 sub push_parse_dsc ($$$) {
1604 my ($dscfn,$dscfnwhat, $cversion) = @_;
1605 $dsc = parsecontrol($dscfn,$dscfnwhat);
1606 my $dversion = getfield $dsc, 'Version';
1607 my $dscpackage = getfield $dsc, 'Source';
1608 ($dscpackage eq $package && $dversion eq $cversion) or
1609 fail "$dscfn is for $dscpackage $dversion".
1610 " but debian/changelog is for $package $cversion";
1613 sub push_mktag ($$$$$$$) {
1614 my ($head,$clogp,$tag,
1616 $changesfile,$changesfilewhat,
1619 $dsc->{$ourdscfield[0]} = $head;
1620 $dsc->save("$dscfn.tmp") or die $!;
1622 my $changes = parsecontrol($changesfile,$changesfilewhat);
1623 foreach my $field (qw(Source Distribution Version)) {
1624 $changes->{$field} eq $clogp->{$field} or
1625 fail "changes field $field \`$changes->{$field}'".
1626 " does not match changelog \`$clogp->{$field}'";
1629 my $cversion = getfield $clogp, 'Version';
1630 my $clogsuite = getfield $clogp, 'Distribution';
1632 # We make the git tag by hand because (a) that makes it easier
1633 # to control the "tagger" (b) we can do remote signing
1634 my $authline = clogp_authline $clogp;
1635 my $delibs = join(" ", "",@deliberatelies);
1636 my $declaredistro = access_basedistro();
1637 open TO, '>', $tfn->('.tmp') or die $!;
1638 print TO <<END or die $!;
1644 $package release $cversion for $clogsuite ($csuite) [dgit]
1645 [dgit distro=$declaredistro$delibs]
1647 foreach my $ref (sort keys %supersedes) {
1648 print TO <<END or die $!;
1649 [dgit supersede:$ref=$supersedes{$ref}]
1655 my $tagobjfn = $tfn->('.tmp');
1657 if (!defined $keyid) {
1658 $keyid = access_cfg('keyid','RETURN-UNDEF');
1660 unlink $tfn->('.tmp.asc') or $!==&ENOENT or die $!;
1661 my @sign_cmd = (@gpg, qw(--detach-sign --armor));
1662 push @sign_cmd, qw(-u),$keyid if defined $keyid;
1663 push @sign_cmd, $tfn->('.tmp');
1664 runcmd_ordryrun @sign_cmd;
1666 $tagobjfn = $tfn->('.signed.tmp');
1667 runcmd shell_cmd "exec >$tagobjfn", qw(cat --),
1668 $tfn->('.tmp'), $tfn->('.tmp.asc');
1675 sub sign_changes ($) {
1676 my ($changesfile) = @_;
1678 my @debsign_cmd = @debsign;
1679 push @debsign_cmd, "-k$keyid" if defined $keyid;
1680 push @debsign_cmd, "-p$gpg[0]" if $gpg[0] ne 'gpg';
1681 push @debsign_cmd, $changesfile;
1682 runcmd_ordryrun @debsign_cmd;
1687 printdebug "actually entering push\n";
1690 access_giturl(); # check that success is vaguely likely
1692 my $clogpfn = ".git/dgit/changelog.822.tmp";
1693 runcmd shell_cmd "exec >$clogpfn", qw(dpkg-parsechangelog);
1695 responder_send_file('parsed-changelog', $clogpfn);
1697 my ($clogp, $cversion, $tag, $dscfn) =
1698 push_parse_changelog("$clogpfn");
1700 my $dscpath = "$buildproductsdir/$dscfn";
1701 stat_exists $dscpath or
1702 fail "looked for .dsc $dscfn, but $!;".
1703 " maybe you forgot to build";
1705 responder_send_file('dsc', $dscpath);
1707 push_parse_dsc($dscpath, $dscfn, $cversion);
1709 my $format = getfield $dsc, 'Format';
1710 printdebug "format $format\n";
1711 if (madformat($format)) {
1712 commit_quilty_patch();
1716 progress "checking that $dscfn corresponds to HEAD";
1717 runcmd qw(dpkg-source -x --),
1718 $dscpath =~ m#^/# ? $dscpath : "../../../$dscpath";
1719 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1720 changedir '../../../..';
1721 my $diffopt = $debug>0 ? '--exit-code' : '--quiet';
1722 my @diffcmd = (@git, qw(diff), $diffopt, $tree);
1723 printcmd \*DEBUG,$debugprefix."+",@diffcmd;
1725 my $r = system @diffcmd;
1728 fail "$dscfn specifies a different tree to your HEAD commit;".
1729 " perhaps you forgot to build".
1730 ($diffopt eq '--exit-code' ? "" :
1731 " (run with -D to see full diff output)");
1737 #do fast forward check and maybe fake merge
1738 # if (!is_fast_fwd(mainbranch
1739 # runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
1740 # map { lref($_).":".rref($_) }
1742 my $head = rev_parse('HEAD');
1743 if (!$changesfile) {
1744 my $multi = "$buildproductsdir/".
1745 "${package}_".(stripepoch $cversion)."_multi.changes";
1746 if (stat_exists "$multi") {
1747 $changesfile = $multi;
1749 my $pat = "${package}_".(stripepoch $cversion)."_*.changes";
1750 my @cs = glob "$buildproductsdir/$pat";
1751 fail "failed to find unique changes file".
1752 " (looked for $pat in $buildproductsdir, or $multi);".
1753 " perhaps you need to use dgit -C"
1755 ($changesfile) = @cs;
1758 $changesfile = "$buildproductsdir/$changesfile";
1761 responder_send_file('changes',$changesfile);
1762 responder_send_command("param head $head");
1763 responder_send_command("param csuite $csuite");
1765 my $forceflag = deliberately('not-fast-forward') ? '+' : '';
1766 if ($forceflag && defined $lastpush_hash) {
1767 git_for_each_tag_referring($lastpush_hash, sub {
1768 my ($objid,$fullrefname,$tagname) = @_;
1769 responder_send_command("supersedes $fullrefname=$objid");
1770 $supersedes{$fullrefname} = $objid;
1774 my $tfn = sub { ".git/dgit/tag$_[0]"; };
1777 if ($we_are_responder) {
1778 $tagobjfn = $tfn->('.signed.tmp');
1779 responder_receive_files('signed-tag', $tagobjfn);
1782 push_mktag($head,$clogp,$tag,
1784 $changesfile,$changesfile,
1788 my $tag_obj_hash = cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
1789 runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
1790 runcmd_ordryrun_local @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
1791 runcmd_ordryrun @git, qw(tag -v --), $tag;
1793 if (!check_for_git()) {
1794 create_remote_git_repo();
1796 runcmd_ordryrun @git, qw(push),access_giturl(),
1797 $forceflag."HEAD:".rrref(), "refs/tags/$tag";
1798 runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), 'HEAD';
1800 if ($we_are_responder) {
1801 my $dryrunsuffix = act_local() ? "" : ".tmp";
1802 responder_receive_files('signed-dsc-changes',
1803 "$dscpath$dryrunsuffix",
1804 "$changesfile$dryrunsuffix");
1807 rename "$dscpath.tmp",$dscpath or die "$dscfn $!";
1809 progress "[new .dsc left in $dscpath.tmp]";
1811 sign_changes $changesfile;
1814 my $host = access_cfg('upload-host','RETURN-UNDEF');
1815 my @hostarg = defined($host) ? ($host,) : ();
1816 runcmd_ordryrun @dput, @hostarg, $changesfile;
1817 printdone "pushed and uploaded $cversion";
1819 responder_send_command("complete");
1825 badusage "-p is not allowed with clone; specify as argument instead"
1826 if defined $package;
1829 } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
1830 ($package,$isuite) = @ARGV;
1831 } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
1832 ($package,$dstdir) = @ARGV;
1833 } elsif (@ARGV==3) {
1834 ($package,$isuite,$dstdir) = @ARGV;
1836 badusage "incorrect arguments to dgit clone";
1838 $dstdir ||= "$package";
1840 if (stat_exists $dstdir) {
1841 fail "$dstdir already exists";
1845 if ($rmonerror && !$dryrun_level) {
1846 $cwd_remove= getcwd();
1848 return unless defined $cwd_remove;
1849 if (!chdir "$cwd_remove") {
1850 return if $!==&ENOENT;
1851 die "chdir $cwd_remove: $!";
1853 rmtree($dstdir) or die "remove $dstdir: $!\n";
1858 $cwd_remove = undef;
1861 sub branchsuite () {
1862 my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
1863 if ($branch =~ m#$lbranch_re#o) {
1870 sub fetchpullargs () {
1871 if (!defined $package) {
1872 my $sourcep = parsecontrol('debian/control','debian/control');
1873 $package = getfield $sourcep, 'Source';
1876 # $isuite = branchsuite(); # this doesn't work because dak hates canons
1878 my $clogp = parsechangelog();
1879 $isuite = getfield $clogp, 'Distribution';
1881 canonicalise_suite();
1882 progress "fetching from suite $csuite";
1883 } elsif (@ARGV==1) {
1885 canonicalise_suite();
1887 badusage "incorrect arguments to dgit fetch or dgit pull";
1905 badusage "-p is not allowed with dgit push" if defined $package;
1907 my $clogp = parsechangelog();
1908 $package = getfield $clogp, 'Source';
1911 } elsif (@ARGV==1) {
1912 ($specsuite) = (@ARGV);
1914 badusage "incorrect arguments to dgit push";
1916 $isuite = getfield $clogp, 'Distribution';
1918 local ($package) = $existing_package; # this is a hack
1919 canonicalise_suite();
1921 if (defined $specsuite && $specsuite ne $isuite) {
1922 canonicalise_suite();
1923 $csuite eq $specsuite or
1924 fail "dgit push: changelog specifies $isuite ($csuite)".
1925 " but command line specifies $specsuite";
1927 if (check_for_git()) {
1930 if (fetch_from_archive()) {
1931 is_fast_fwd(lrref(), 'HEAD') or
1932 fail "dgit push: HEAD is not a descendant".
1933 " of the archive's version.\n".
1934 "$us: To overwrite it, use git merge -s ours ".lrref().".";
1937 fail "package appears to be new in this suite;".
1938 " if this is intentional, use --new";
1943 #---------- remote commands' implementation ----------
1945 sub cmd_remote_push_build_host {
1946 my ($nrargs) = shift @ARGV;
1947 my (@rargs) = @ARGV[0..$nrargs-1];
1948 @ARGV = @ARGV[$nrargs..$#ARGV];
1950 my ($dir,$vsnwant) = @rargs;
1951 # vsnwant is a comma-separated list; we report which we have
1952 # chosen in our ready response (so other end can tell if they
1955 $we_are_responder = 1;
1957 open PI, "<&STDIN" or die $!;
1958 open STDIN, "/dev/null" or die $!;
1959 open PO, ">&STDOUT" or die $!;
1961 open STDOUT, ">&STDERR" or die $!;
1965 fail "build host has dgit rpush protocol version".
1966 " $rpushprotovsn but invocation host has $vsnwant"
1967 unless grep { $rpushprotovsn eq $_ } split /,/, $vsnwant;
1969 responder_send_command("dgit-remote-push-ready $rpushprotovsn");
1975 sub cmd_remote_push_responder { cmd_remote_push_build_host(); }
1976 # ... for compatibility with proto vsn.1 dgit (just so that user gets
1977 # a good error message)
1983 my $report = i_child_report();
1984 if (defined $report) {
1985 printdebug "($report)\n";
1986 } elsif ($i_child_pid) {
1987 printdebug "(killing build host child $i_child_pid)\n";
1988 kill 15, $i_child_pid;
1990 if (defined $i_tmp && !defined $initiator_tempdir) {
1992 eval { rmtree $i_tmp; };
1996 END { i_cleanup(); }
1999 my ($base,$selector,@args) = @_;
2000 $selector =~ s/\-/_/g;
2001 { no strict qw(refs); &{"${base}_${selector}"}(@args); }
2007 if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
2014 my @rargs = ($dir,$rpushprotovsn);
2017 push @rdgit, @ropts;
2018 push @rdgit, qw(remote-push-build-host), (scalar @rargs), @rargs;
2020 my @cmd = (@ssh, $host, shellquote @rdgit);
2021 printcmd \*DEBUG,$debugprefix."+",@cmd;
2023 if (defined $initiator_tempdir) {
2024 rmtree $initiator_tempdir;
2025 mkdir $initiator_tempdir, 0700 or die "$initiator_tempdir: $!";
2026 $i_tmp = $initiator_tempdir;
2030 $i_child_pid = open2(\*RO, \*RI, @cmd);
2032 initiator_expect { m/^dgit-remote-push-ready/ };
2034 my ($icmd,$iargs) = initiator_expect {
2035 m/^(\S+)(?: (.*))?$/;
2038 i_method "i_resp", $icmd, $iargs;
2042 sub i_resp_progress ($) {
2044 my $msg = protocol_read_bytes \*RO, $rhs;
2048 sub i_resp_complete {
2049 my $pid = $i_child_pid;
2050 $i_child_pid = undef; # prevents killing some other process with same pid
2051 printdebug "waiting for build host child $pid...\n";
2052 my $got = waitpid $pid, 0;
2053 die $! unless $got == $pid;
2054 die "build host child failed $?" if $?;
2057 printdebug "all done\n";
2061 sub i_resp_file ($) {
2063 my $localname = i_method "i_localname", $keyword;
2064 my $localpath = "$i_tmp/$localname";
2065 stat_exists $localpath and
2066 badproto \*RO, "file $keyword ($localpath) twice";
2067 protocol_receive_file \*RO, $localpath;
2068 i_method "i_file", $keyword;
2073 sub i_resp_param ($) {
2074 $_[0] =~ m/^(\S+) (.*)$/ or badproto \*RO, "bad param spec";
2078 sub i_resp_supersedes ($) {
2079 $_[0] =~ m#^(refs/tags/\S+)=(\w+)$#
2080 or badproto \*RO, "bad supersedes spec";
2081 my $r = system qw(git check-ref-format), $1;
2082 die "bad supersedes ref spec ($r)" if $r;
2083 $supersedes{$1} = $2;
2088 sub i_resp_want ($) {
2090 die "$keyword ?" if $i_wanted{$keyword}++;
2091 my @localpaths = i_method "i_want", $keyword;
2092 printdebug "[[ $keyword @localpaths\n";
2093 foreach my $localpath (@localpaths) {
2094 protocol_send_file \*RI, $localpath;
2096 print RI "files-end\n" or die $!;
2099 our ($i_clogp, $i_version, $i_tag, $i_dscfn, $i_changesfn);
2101 sub i_localname_parsed_changelog {
2102 return "remote-changelog.822";
2104 sub i_file_parsed_changelog {
2105 ($i_clogp, $i_version, $i_tag, $i_dscfn) =
2106 push_parse_changelog "$i_tmp/remote-changelog.822";
2107 die if $i_dscfn =~ m#/|^\W#;
2110 sub i_localname_dsc {
2111 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
2116 sub i_localname_changes {
2117 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
2118 $i_changesfn = $i_dscfn;
2119 $i_changesfn =~ s/\.dsc$/_dgit.changes/ or die;
2120 return $i_changesfn;
2122 sub i_file_changes { }
2124 sub i_want_signed_tag {
2125 printdebug Dumper(\%i_param, $i_dscfn);
2126 defined $i_param{'head'} && defined $i_dscfn && defined $i_clogp
2127 && defined $i_param{'csuite'}
2128 or badproto \*RO, "premature desire for signed-tag";
2129 my $head = $i_param{'head'};
2130 die if $head =~ m/[^0-9a-f]/ || $head !~ m/^../;
2132 die unless $i_param{'csuite'} =~ m/^$suite_re$/;
2134 push_parse_dsc $i_dscfn, 'remote dsc', $i_version;
2137 push_mktag $head, $i_clogp, $i_tag,
2139 $i_changesfn, 'remote changes',
2140 sub { "tag$_[0]"; };
2145 sub i_want_signed_dsc_changes {
2146 rename "$i_dscfn.tmp","$i_dscfn" or die "$i_dscfn $!";
2147 sign_changes $i_changesfn;
2148 return ($i_dscfn, $i_changesfn);
2151 #---------- building etc. ----------
2157 #----- `3.0 (quilt)' handling -----
2159 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
2161 sub quiltify_dpkg_commit ($$$;$) {
2162 my ($patchname,$author,$msg, $xinfo) = @_;
2166 my $descfn = ".git/dgit/quilt-description.tmp";
2167 open O, '>', $descfn or die "$descfn: $!";
2170 $msg =~ s/^\s+$/ ./mg;
2171 print O <<END or die $!;
2181 local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
2182 local $ENV{'VISUAL'} = $ENV{'EDITOR'};
2183 local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
2184 runcmd_ordryrun_local @dpkgsource, qw(--commit .), $patchname;
2188 sub quiltify_trees_differ ($$) {
2190 # returns 1 iff the two tree objects differ other than in debian/
2192 my @cmd = (@git, qw(diff-tree --name-only -z), $x, $y);
2193 my $diffs= cmdoutput @cmd;
2194 foreach my $f (split /\0/, $diffs) {
2195 next if $f eq 'debian';
2201 sub quiltify_tree_sentinelfiles ($) {
2202 # lists the `sentinel' files present in the tree
2204 my $r = cmdoutput @git, qw(ls-tree --name-only), $x,
2205 qw(-- debian/rules debian/control);
2211 my ($clogp,$target) = @_;
2213 # Quilt patchification algorithm
2215 # We search backwards through the history of the main tree's HEAD
2216 # (T) looking for a start commit S whose tree object is identical
2217 # to to the patch tip tree (ie the tree corresponding to the
2218 # current dpkg-committed patch series). For these purposes
2219 # `identical' disregards anything in debian/ - this wrinkle is
2220 # necessary because dpkg-source treates debian/ specially.
2222 # We can only traverse edges where at most one of the ancestors'
2223 # trees differs (in changes outside in debian/). And we cannot
2224 # handle edges which change .pc/ or debian/patches. To avoid
2225 # going down a rathole we avoid traversing edges which introduce
2226 # debian/rules or debian/control. And we set a limit on the
2227 # number of edges we are willing to look at.
2229 # If we succeed, we walk forwards again. For each traversed edge
2230 # PC (with P parent, C child) (starting with P=S and ending with
2231 # C=T) to we do this:
2233 # - dpkg-source --commit with a patch name and message derived from C
2234 # After traversing PT, we git commit the changes which
2235 # should be contained within debian/patches.
2237 changedir '../fake';
2238 mktree_in_ud_here();
2240 runcmd @git, 'add', '.';
2241 my $oldtiptree=git_write_tree();
2242 changedir '../work';
2244 # The search for the path S..T is breadth-first. We maintain a
2245 # todo list containing search nodes. A search node identifies a
2246 # commit, and looks something like this:
2248 # Commit => $git_commit_id,
2249 # Child => $c, # or undef if P=T
2250 # Whynot => $reason_edge_PC_unsuitable, # in @nots only
2251 # Nontrivial => true iff $p..$c has relevant changes
2258 my %considered; # saves being exponential on some weird graphs
2260 my $t_sentinels = quiltify_tree_sentinelfiles $target;
2263 my ($search,$whynot) = @_;
2264 printdebug " search NOT $search->{Commit} $whynot\n";
2265 $search->{Whynot} = $whynot;
2266 push @nots, $search;
2267 no warnings qw(exiting);
2276 my $c = shift @todo;
2277 next if $considered{$c->{Commit}}++;
2279 $not->($c, "maximum search space exceeded") if --$max_work <= 0;
2281 printdebug "quiltify investigate $c->{Commit}\n";
2284 if (!quiltify_trees_differ $c->{Commit}, $oldtiptree) {
2285 printdebug " search finished hooray!\n";
2290 if ($quilt_mode eq 'nofix') {
2291 fail "quilt fixup required but quilt mode is \`nofix'\n".
2292 "HEAD commit $c->{Commit} differs from tree implied by ".
2293 " debian/patches (tree object $oldtiptree)";
2295 if ($quilt_mode eq 'smash') {
2296 printdebug " search quitting smash\n";
2300 my $c_sentinels = quiltify_tree_sentinelfiles $c->{Commit};
2301 $not->($c, "has $c_sentinels not $t_sentinels")
2302 if $c_sentinels ne $t_sentinels;
2304 my $commitdata = cmdoutput @git, qw(cat-file commit), $c->{Commit};
2305 $commitdata =~ m/\n\n/;
2307 my @parents = ($commitdata =~ m/^parent (\w+)$/gm);
2308 @parents = map { { Commit => $_, Child => $c } } @parents;
2310 $not->($c, "root commit") if !@parents;
2312 foreach my $p (@parents) {
2313 $p->{Nontrivial}= quiltify_trees_differ $p->{Commit},$c->{Commit};
2315 my $ndiffers = grep { $_->{Nontrivial} } @parents;
2316 $not->($c, "merge ($ndiffers nontrivial parents)") if $ndiffers > 1;
2318 foreach my $p (@parents) {
2319 printdebug "considering C=$c->{Commit} P=$p->{Commit}\n";
2321 my @cmd= (@git, qw(diff-tree -r --name-only),
2322 $p->{Commit},$c->{Commit}, qw(-- debian/patches .pc));
2323 my $patchstackchange = cmdoutput @cmd;
2324 if (length $patchstackchange) {
2325 $patchstackchange =~ s/\n/,/g;
2326 $not->($p, "changed $patchstackchange");
2329 printdebug " search queue P=$p->{Commit} ",
2330 ($p->{Nontrivial} ? "NT" : "triv"),"\n";
2336 printdebug "quiltify want to smash\n";
2339 my $x = $_[0]{Commit};
2340 $x =~ s/(.*?[0-9a-z]{8})[0-9a-z]*$/$1/;
2343 my $reportnot = sub {
2345 my $s = $abbrev->($notp);
2346 my $c = $notp->{Child};
2347 $s .= "..".$abbrev->($c) if $c;
2348 $s .= ": ".$c->{Whynot};
2351 if ($quilt_mode eq 'linear') {
2352 print STDERR "$us: quilt fixup cannot be linear. Stopped at:\n";
2353 foreach my $notp (@nots) {
2354 print STDERR "$us: ", $reportnot->($notp), "\n";
2356 fail "quilt fixup naive history linearisation failed.\n".
2357 "Use dpkg-source --commit by hand; or, --quilt=smash for one ugly patch";
2358 } elsif ($quilt_mode eq 'smash') {
2359 } elsif ($quilt_mode eq 'auto') {
2360 progress "quilt fixup cannot be linear, smashing...";
2362 die "$quilt_mode ?";
2367 my $msg = cmdoutput @git, qw(log), "-n$ncommits";
2369 quiltify_dpkg_commit "auto-$version-$target-$time",
2370 (getfield $clogp, 'Maintainer'),
2371 "Automatically generated patch ($clogp->{Version})\n".
2372 "Last (up to) $ncommits git changes, FYI:\n\n". $msg;
2376 progress "quiltify linearisation planning successful, executing...";
2378 for (my $p = $sref_S;
2379 my $c = $p->{Child};
2381 printdebug "quiltify traverse $p->{Commit}..$c->{Commit}\n";
2382 next unless $p->{Nontrivial};
2384 my $cc = $c->{Commit};
2386 my $commitdata = cmdoutput @git, qw(cat-file commit), $cc;
2387 $commitdata =~ m/\n\n/ or die "$c ?";
2390 $commitdata =~ m/^author (.*) \d+ [-+0-9]+$/m or die "$cc ?";
2393 $msg =~ s/^(.*)\n*/$1\n/ or die "$cc $msg ?";
2396 my $patchname = $title;
2397 $patchname =~ s/[.:]$//;
2398 $patchname =~ y/ A-Z/-a-z/;
2399 $patchname =~ y/-a-z0-9_.+=~//cd;
2400 $patchname =~ s/^\W/x-$&/;
2401 $patchname = substr($patchname,0,40);
2404 stat "debian/patches/$patchname$index";
2406 $!==ENOENT or die "$patchname$index $!";
2408 runcmd @git, qw(checkout -q), $cc;
2410 # We use the tip's changelog so that dpkg-source doesn't
2411 # produce complaining messages from dpkg-parsechangelog. None
2412 # of the information dpkg-source gets from the changelog is
2413 # actually relevant - it gets put into the original message
2414 # which dpkg-source provides our stunt editor, and then
2416 runcmd @git, qw(checkout -q), $target, qw(debian/changelog);
2418 quiltify_dpkg_commit "$patchname$index", $author, $msg,
2419 "X-Dgit-Generated: $clogp->{Version} $cc\n";
2421 runcmd @git, qw(checkout -q), $cc, qw(debian/changelog);
2424 runcmd @git, qw(checkout -q master);
2427 sub build_maybe_quilt_fixup () {
2428 my $format=get_source_format;
2429 return unless madformat $format;
2433 # - honour any existing .pc in case it has any strangeness
2434 # - determine the git commit corresponding to the tip of
2435 # the patch stack (if there is one)
2436 # - if there is such a git commit, convert each subsequent
2437 # git commit into a quilt patch with dpkg-source --commit
2438 # - otherwise convert all the differences in the tree into
2439 # a single git commit
2443 # Our git tree doesn't necessarily contain .pc. (Some versions of
2444 # dgit would include the .pc in the git tree.) If there isn't
2445 # one, we need to generate one by unpacking the patches that we
2448 # We first look for a .pc in the git tree. If there is one, we
2449 # will use it. (This is not the normal case.)
2451 # Otherwise need to regenerate .pc so that dpkg-source --commit
2452 # can work. We do this as follows:
2453 # 1. Collect all relevant .orig from parent directory
2454 # 2. Generate a debian.tar.gz out of
2455 # debian/{patches,rules,source/format}
2456 # 3. Generate a fake .dsc containing just these fields:
2457 # Format Source Version Files
2458 # 4. Extract the fake .dsc
2459 # Now the fake .dsc has a .pc directory.
2460 # (In fact we do this in every case, because in future we will
2461 # want to search for a good base commit for generating patches.)
2463 # Then we can actually do the dpkg-source --commit
2464 # 1. Make a new working tree with the same object
2465 # store as our main tree and check out the main
2467 # 2. Copy .pc from the fake's extraction, if necessary
2468 # 3. Run dpkg-source --commit
2469 # 4. If the result has changes to debian/, then
2470 # - git-add them them
2471 # - git-add .pc if we had a .pc in-tree
2473 # 5. If we had a .pc in-tree, delete it, and git-commit
2474 # 6. Back in the main tree, fast forward to the new HEAD
2476 my $clogp = parsechangelog();
2477 my $headref = rev_parse('HEAD');
2482 my $upstreamversion=$version;
2483 $upstreamversion =~ s/-[^-]*$//;
2485 my $fakeversion="$upstreamversion-~~DGITFAKE";
2487 my $fakedsc=new IO::File 'fake.dsc', '>' or die $!;
2488 print $fakedsc <<END or die $!;
2491 Version: $fakeversion
2495 my $dscaddfile=sub {
2498 my $md = new Digest::MD5;
2500 my $fh = new IO::File $b, '<' or die "$b $!";
2505 print $fakedsc " ".$md->hexdigest." $size $b\n" or die $!;
2508 foreach my $f (<../../../../*>) { #/){
2509 my $b=$f; $b =~ s{.*/}{};
2510 next unless is_orig_file $b, srcfn $upstreamversion,'';
2511 link $f, $b or die "$b $!";
2515 my @files=qw(debian/source/format debian/rules);
2516 if (stat_exists '../../../debian/patches') {
2517 push @files, 'debian/patches';
2520 my $debtar= srcfn $fakeversion,'.debian.tar.gz';
2521 runcmd qw(env GZIP=-1 tar -zcf), "./$debtar", qw(-C ../../..), @files;
2523 $dscaddfile->($debtar);
2524 close $fakedsc or die $!;
2526 runcmd qw(sh -ec), 'exec dpkg-source --no-check -x fake.dsc >/dev/null';
2528 my $fakexdir= $package.'-'.(stripepoch $upstreamversion);
2529 rename $fakexdir, "fake" or die "$fakexdir $!";
2531 mkdir "work" or die $!;
2533 mktree_in_ud_here();
2534 runcmd @git, qw(reset --hard), $headref;
2537 if (stat_exists ".pc") {
2539 progress "Tree already contains .pc - will use it then delete it.";
2542 rename '../fake/.pc','.pc' or die $!;
2545 quiltify($clogp,$headref);
2547 if (!open P, '>>', ".pc/applied-patches") {
2548 $!==&ENOENT or die $!;
2553 commit_quilty_patch();
2555 if ($mustdeletepc) {
2556 runcmd @git, qw(rm -rq .pc);
2557 commit_admin "Commit removal of .pc (quilt series tracking data)";
2560 changedir '../../../..';
2561 runcmd @git, qw(pull --ff-only -q .git/dgit/unpack/work master);
2564 sub quilt_fixup_editor () {
2565 my $descfn = $ENV{$fakeeditorenv};
2566 my $editing = $ARGV[$#ARGV];
2567 open I1, '<', $descfn or die "$descfn: $!";
2568 open I2, '<', $editing or die "$editing: $!";
2569 unlink $editing or die "$editing: $!";
2570 open O, '>', $editing or die "$editing: $!";
2571 while (<I1>) { print O or die $!; } I1->error and die $!;
2574 $copying ||= m/^\-\-\- /;
2575 next unless $copying;
2578 I2->error and die $!;
2583 #----- other building -----
2586 if ($cleanmode eq 'dpkg-source') {
2587 runcmd_ordryrun_local @dpkgbuildpackage, qw(-T clean);
2588 } elsif ($cleanmode eq 'git') {
2589 runcmd_ordryrun_local @git, qw(clean -xdf);
2590 } elsif ($cleanmode eq 'none') {
2597 badusage "clean takes no additional arguments" if @ARGV;
2602 badusage "-p is not allowed when building" if defined $package;
2605 my $clogp = parsechangelog();
2606 $isuite = getfield $clogp, 'Distribution';
2607 $package = getfield $clogp, 'Source';
2608 $version = getfield $clogp, 'Version';
2609 build_maybe_quilt_fixup();
2612 sub changesopts () {
2613 my @opts =@changesopts[1..$#changesopts];
2614 if (!defined $changes_since_version) {
2615 my @vsns = archive_query('archive_query');
2616 my @quirk = access_quirk();
2617 if ($quirk[0] eq 'backports') {
2618 local $isuite = $quirk[2];
2620 canonicalise_suite();
2621 push @vsns, archive_query('archive_query');
2624 @vsns = map { $_->[0] } @vsns;
2625 @vsns = sort { -version_compare($a, $b) } @vsns;
2626 $changes_since_version = $vsns[0];
2627 progress "changelog will contain changes since $vsns[0]";
2629 $changes_since_version = '_';
2630 progress "package seems new, not specifying -v<version>";
2633 if ($changes_since_version ne '_') {
2634 unshift @opts, "-v$changes_since_version";
2641 runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc), changesopts(), @ARGV;
2642 printdone "build successful\n";
2648 (qw(git-buildpackage -us -uc --git-no-sign-tags),
2649 "--git-builder=@dpkgbuildpackage");
2650 unless (grep { m/^--git-debian-branch|^--git-ignore-branch/ } @ARGV) {
2651 canonicalise_suite();
2652 push @cmd, "--git-debian-branch=".lbranch();
2654 push @cmd, changesopts();
2655 runcmd_ordryrun_local @cmd, @ARGV;
2656 printdone "build successful\n";
2661 $sourcechanges = "${package}_".(stripepoch $version)."_source.changes";
2662 $dscfn = dscfn($version);
2663 if ($cleanmode eq 'dpkg-source') {
2664 runcmd_ordryrun_local (@dpkgbuildpackage, qw(-us -uc -S)),
2667 my $pwd = must_getcwd();
2668 my $leafdir = basename $pwd;
2670 runcmd_ordryrun_local @dpkgsource, qw(-b --), $leafdir;
2672 runcmd_ordryrun_local qw(sh -ec),
2673 'exec >$1; shift; exec "$@"','x',
2674 "../$sourcechanges",
2675 @dpkggenchanges, qw(-S), changesopts();
2679 sub cmd_build_source {
2680 badusage "build-source takes no additional arguments" if @ARGV;
2682 printdone "source built, results in $dscfn and $sourcechanges";
2688 my $pat = "${package}_".(stripepoch $version)."_*.changes";
2690 stat_exist $dscfn or fail "$dscfn (in parent directory): $!";
2691 stat_exists $sourcechanges
2692 or fail "$sourcechanges (in parent directory): $!";
2693 foreach my $cf (glob $pat) {
2694 next if $cf eq $sourcechanges;
2695 unlink $cf or fail "remove $cf: $!";
2698 runcmd_ordryrun_local @sbuild, @ARGV, qw(-d), $isuite, $dscfn;
2699 my @changesfiles = glob $pat;
2700 @changesfiles = sort {
2701 ($b =~ m/_source\.changes$/ <=> $a =~ m/_source\.changes$/)
2704 fail "wrong number of different changes files (@changesfiles)"
2705 unless @changesfiles;
2706 runcmd_ordryrun_local @mergechanges, @changesfiles;
2707 my $multichanges = "${package}_".(stripepoch $version)."_multi.changes";
2709 stat_exists $multichanges or fail "$multichanges: $!";
2711 printdone "build successful, results in $multichanges\n" or die $!;
2714 sub cmd_quilt_fixup {
2715 badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
2716 my $clogp = parsechangelog();
2717 $version = getfield $clogp, 'Version';
2718 $package = getfield $clogp, 'Source';
2719 build_maybe_quilt_fixup();
2722 sub cmd_archive_api_query {
2723 badusage "need only 1 subpath argument" unless @ARGV==1;
2724 my ($subpath) = @ARGV;
2725 my @cmd = archive_api_query_cmd($subpath);
2726 exec @cmd or fail "exec curl: $!\n";
2729 #---------- argument parsing and main program ----------
2732 print "dgit version $our_version\n" or die $!;
2739 if (defined $ENV{'DGIT_SSH'}) {
2740 @ssh = string_to_ssh $ENV{'DGIT_SSH'};
2741 } elsif (defined $ENV{'GIT_SSH'}) {
2742 @ssh = ($ENV{'GIT_SSH'});
2746 last unless $ARGV[0] =~ m/^-/;
2750 if (m/^--dry-run$/) {
2753 } elsif (m/^--damp-run$/) {
2756 } elsif (m/^--no-sign$/) {
2759 } elsif (m/^--help$/) {
2761 } elsif (m/^--version$/) {
2763 } elsif (m/^--new$/) {
2766 } elsif (m/^--since-version=([^_]+|_)$/) {
2768 $changes_since_version = $1;
2769 } elsif (m/^--([-0-9a-z]+)=(.*)/s &&
2770 ($om = $opts_opt_map{$1}) &&
2774 } elsif (m/^--([-0-9a-z]+):(.*)/s &&
2775 !$opts_opt_cmdonly{$1} &&
2776 ($om = $opts_opt_map{$1})) {
2779 } elsif (m/^--existing-package=(.*)/s) {
2781 $existing_package = $1;
2782 } elsif (m/^--initiator-tempdir=(.*)/s) {
2783 $initiator_tempdir = $1;
2784 $initiator_tempdir =~ m#^/# or
2785 badusage "--initiator-tempdir must be used specify an".
2786 " absolute, not relative, directory."
2787 } elsif (m/^--distro=(.*)/s) {
2790 } elsif (m/^--build-products-dir=(.*)/s) {
2792 $buildproductsdir = $1;
2793 } elsif (m/^--clean=(dpkg-source|git|none)$/s) {
2796 } elsif (m/^--clean=(.*)$/s) {
2797 badusage "unknown cleaning mode \`$1'";
2798 } elsif (m/^--quilt=($quilt_modes_re)$/s) {
2801 } elsif (m/^--quilt=(.*)$/s) {
2802 badusage "unknown quilt fixup mode \`$1'";
2803 } elsif (m/^--ignore-dirty$/s) {
2806 } elsif (m/^--no-quilt-fixup$/s) {
2808 $quilt_mode = 'nocheck';
2809 } elsif (m/^--no-rm-on-error$/s) {
2812 } elsif (m/^--deliberately-($suite_re)$/s) {
2814 push @deliberatelies, $&;
2816 badusage "unknown long option \`$_'";
2823 } elsif (s/^-L/-/) {
2826 } elsif (s/^-h/-/) {
2828 } elsif (s/^-D/-/) {
2830 open DEBUG, ">&STDERR" or die $!;
2833 } elsif (s/^-N/-/) {
2836 } elsif (s/^-v([^_]+|_)$//s) {
2838 $changes_since_version = $1;
2841 push @changesopts, $_;
2843 } elsif (s/^-c(.*=.*)//s) {
2845 push @git, '-c', $1;
2846 } elsif (s/^-d(.+)//s) {
2849 } elsif (s/^-C(.+)//s) {
2852 if ($changesfile =~ s#^(.*)/##) {
2853 $buildproductsdir = $1;
2855 } elsif (s/^-k(.+)//s) {
2857 } elsif (m/^-[vdCk]$/) {
2859 "option \`$_' requires an argument (and no space before the argument)";
2860 } elsif (s/^-wn$//s) {
2862 $cleanmode = 'none';
2863 } elsif (s/^-wg$//s) {
2866 } elsif (s/^-wd$//s) {
2868 $cleanmode = 'dpkg-source';
2870 badusage "unknown short option \`$_'";
2877 if ($ENV{$fakeeditorenv}) {
2878 quilt_fixup_editor();
2882 print STDERR "DRY RUN ONLY\n" if $dryrun_level > 1;
2883 print STDERR "DAMP RUN - WILL MAKE LOCAL (UNSIGNED) CHANGES\n"
2884 if $dryrun_level == 1;
2886 print STDERR $helpmsg or die $!;
2889 my $cmd = shift @ARGV;
2892 if (!defined $quilt_mode) {
2893 $quilt_mode = cfg('dgit.force.quilt-mode', 'RETURN-UNDEF')
2894 // access_cfg('quilt-mode', 'RETURN-UNDEF')
2896 $quilt_mode =~ m/^($quilt_modes_re)$/
2897 or badcfg "unknown quilt-mode \`$quilt_mode'";
2901 my $fn = ${*::}{"cmd_$cmd"};
2902 $fn or badusage "unknown operation $cmd";