chiark / gitweb /
123c2d513ae2cc05f3f3dd82a90c06a3b64202bd
[dgit.git] / dgit
1 #!/usr/bin/perl -w
2 # dgit
3 # Integration between git and Debian-style archives
4 #
5 # Copyright (C)2013 Ian Jackson
6 #
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.
11 #
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.
16 #
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/>.
19
20 use strict;
21
22 use IO::Handle;
23 use Data::Dumper;
24 use LWP::UserAgent;
25 use Dpkg::Control::Hash;
26 use File::Path;
27 use File::Basename;
28 use Dpkg::Version;
29 use POSIX;
30
31 our $our_version = 'UNRELEASED'; ###substituted###
32
33 our $isuite = 'unstable';
34 our $idistro;
35 our $package;
36
37 our $sign = 1;
38 our $dryrun = 0;
39 our $changesfile;
40 our $new_package = 0;
41 our $ignoredirty = 0;
42 our $noquilt = 0;
43 our $existing_package = 'dpkg';
44 our $cleanmode = 'dpkg-source';
45
46 our %format_ok = map { $_=>1 } ("1.0","3.0 (native)","3.0 (quilt)");
47
48 our (@git) = qw(git);
49 our (@dget) = qw(dget);
50 our (@dput) = qw(dput);
51 our (@debsign) = qw(debsign);
52 our (@sbuild) = qw(sbuild -A);
53 our (@dpkgbuildpackage) = qw(dpkg-buildpackage -i\.git/ -I.git);
54 our (@dpkgsource) = qw(dpkg-source -i\.git/ -I.git);
55 our (@dpkggenchanges) = qw(dpkg-genchanges);
56 our (@mergechanges) = qw(mergechanges -f);
57 our (@changesopts) = ('');
58
59 our %opts_opt_map = ('dget' => \@dget,
60                      'dput' => \@dput,
61                      'debsign' => \@debsign,
62                      'sbuild' => \@sbuild,
63                      'dpkg-source' => \@dpkgsource,
64                      'dpkg-buildpackage' => \@dpkgbuildpackage,
65                      'dpkg-genchanges' => \@dpkggenchanges,
66                      'ch' => \@changesopts,
67                      'mergechanges' => \@mergechanges);
68
69 our $keyid;
70
71 our $debug = 0;
72 open DEBUG, ">/dev/null" or die $!;
73
74 our $remotename = 'dgit';
75 our @ourdscfield = qw(Dgit Vcs-Dgit-Master);
76 our $branchprefix = 'dgit';
77 our $csuite;
78
79 sub lbranch () { return "$branchprefix/$csuite"; }
80 my $lbranch_re = '^refs/heads/'.$branchprefix.'/([^/.]+)$';
81 sub lref () { return "refs/heads/".lbranch(); }
82 sub lrref () { return "refs/remotes/$remotename/$branchprefix/$csuite"; }
83 sub rrref () { return "refs/$branchprefix/$csuite"; }
84 sub debiantag ($) { 
85     my ($v) = @_;
86     $v =~ y/~:/_%/;
87     return "debian/$v";
88 }
89
90 sub stripepoch ($) {
91     my ($vsn) = @_;
92     $vsn =~ s/^\d+\://;
93     return $vsn;
94 }
95
96 sub dscfn ($) {
97     my ($vsn) = @_;
98     return "${package}_".(stripepoch $vsn).".dsc";
99 }
100
101 sub changesopts () { return @changesopts[1..$#changesopts]; }
102
103 our $us = 'dgit';
104
105 sub fail { die "$us: @_\n"; }
106
107 sub badcfg { print STDERR "$us: invalid configuration: @_\n"; exit 12; }
108
109 sub no_such_package () {
110     print STDERR "$us: package $package does not exist in suite $isuite\n";
111     exit 4;
112 }
113
114 sub fetchspec () {
115     local $csuite = '*';
116     return  "+".rrref().":".lrref();
117 }
118
119 our $ua;
120
121 sub url_get {
122     if (!$ua) {
123         $ua = LWP::UserAgent->new();
124         $ua->env_proxy;
125     }
126     my $what = $_[$#_];
127     print "downloading $what...\n";
128     my $r = $ua->get(@_) or die $!;
129     return undef if $r->code == 404;
130     $r->is_success or fail "failed to fetch $what: ".$r->status_line;
131     return $r->decoded_content();
132 }
133
134 our ($dscdata,$dscurl,$dsc);
135
136 sub printcmd {
137     my $fh = shift @_;
138     my $intro = shift @_;
139     print $fh $intro or die $!;
140     local $_;
141     foreach my $a (@_) {
142         $_ = $a;
143         if (s{['\\]}{\\$&}g || m{\s} || m{[^-_./0-9a-z]}i) {
144             print $fh " '$_'" or die $!;
145         } else {
146             print $fh " $_" or die $!;
147         }
148     }
149     print $fh "\n" or die $!;
150 }
151
152 sub failedcmd {
153     { local ($!); printcmd \*STDERR, "$_[0]: failed command:", @_ or die $!; };
154     if ($!) {
155         fail "failed to fork/exec: $!";
156     } elsif (!($? & 0xff)) {
157         fail "subprocess failed with error exit status ".($?>>8);
158     } elsif ($?) {
159         fail "subprocess crashed (wait status $?)";
160     } else {
161         fail "subprocess produced invalid output";
162     }
163 }
164
165 sub runcmd {
166     printcmd(\*DEBUG,"+",@_) if $debug>0;
167     $!=0; $?=0;
168     failedcmd @_ if system @_;
169 }
170
171 sub printdone {
172     if (!$dryrun) {
173         print "dgit ok: @_\n";
174     } else {
175         print "would be ok: @_ (but dry run only)\n";
176     }
177 }
178
179 sub cmdoutput_errok {
180     die Dumper(\@_)." ?" if grep { !defined } @_;
181     printcmd(\*DEBUG,"|",@_) if $debug>0;
182     open P, "-|", @_ or die $!;
183     my $d;
184     $!=0; $?=0;
185     { local $/ = undef; $d = <P>; }
186     die $! if P->error;
187     if (!close P) { print DEBUG "=>!$?\n" if $debug>0; return undef; }
188     chomp $d;
189     $d =~ m/^.*/;
190     print DEBUG "=> \`$&'",(length $' ? '...' : ''),"\n" if $debug>0; #';
191     return $d;
192 }
193
194 sub cmdoutput {
195     my $d = cmdoutput_errok @_;
196     defined $d or failedcmd @_;
197     return $d;
198 }
199
200 sub dryrun_report {
201     printcmd(\*STDOUT,"#",@_);
202 }
203
204 sub runcmd_ordryrun {
205     if (!$dryrun) {
206         runcmd @_;
207     } else {
208         dryrun_report @_;
209     }
210 }
211
212 sub shell_cmd {
213     my ($first_shell, @cmd) = @_;
214     return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
215 }
216
217 our $helpmsg = <<END;
218 main usages:
219   dgit [dgit-opts] clone [dgit-opts] package [suite] [./dir|/dir]
220   dgit [dgit-opts] fetch|pull [dgit-opts] [suite]
221   dgit [dgit-opts] build [git-buildpackage-opts|dpkg-buildpackage-opts]
222   dgit [dgit-opts] push [dgit-opts] [suite]
223 important dgit options:
224   -k<keyid>           sign tag and package with <keyid> instead of default
225   --dry-run -n        do not change anything, but go through the motions
226   --new -N            allow introducing a new package
227   --debug -D          increase debug level
228   -c<name>=<value>    set git config option (used directly by dgit too)
229 END
230
231 our $later_warning_msg = <<END;
232 Perhaps the upload is stuck in incoming.  Using the version from git.
233 END
234
235 sub badusage {
236     print STDERR "$us: @_\n", $helpmsg or die $!;
237     exit 8;
238 }
239
240 sub cmd_help () {
241     print $helpmsg or die $!;
242     exit 0;
243 }
244
245 our %defcfg = ('dgit.default.distro' => 'debian',
246                'dgit.default.username' => '',
247                'dgit.default.archive-query-default-component' => 'main',
248                'dgit.default.ssh' => 'ssh',
249                'dgit-distro.debian.git-host' => 'git.debian.org',
250                'dgit-distro.debian.git-proto' => 'git+ssh://',
251                'dgit-distro.debian.git-path' => '/git/dgit-repos/repos',
252                'dgit-distro.debian.git-check' => 'ssh-cmd',
253                'dgit-distro.debian.git-create' => 'ssh-cmd',
254                'dgit-distro.debian.sshdakls-host' => 'coccia.debian.org',
255                'dgit-distro.debian.sshdakls-dir' =>
256                    '/srv/ftp-master.debian.org/ftp/dists',
257                'dgit-distro.debian.upload-host' => 'ftp-master', # for dput
258                'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/');
259
260 sub cfg {
261     foreach my $c (@_) {
262         return undef if $c =~ /RETURN-UNDEF/;
263         my @cmd = (@git, qw(config --), $c);
264         my $v;
265         {
266             local ($debug) = $debug-1;
267             $v = cmdoutput_errok @cmd;
268         };
269         if ($?==0) {
270             return $v;
271         } elsif ($?!=256) {
272             failedcmd @cmd;
273         }
274         my $dv = $defcfg{$c};
275         return $dv if defined $dv;
276     }
277     badcfg "need value for one of: @_";
278 }
279
280 sub access_distro () {
281     return cfg("dgit-suite.$isuite.distro",
282                "dgit.default.distro");
283 }
284
285 sub access_cfg (@) {
286     my (@keys) = @_;
287     my $distro = $idistro || access_distro();
288     my $value = cfg(map { ("dgit-distro.$distro.$_",
289                            "dgit.default.$_") } @keys);
290     return $value;
291 }
292
293 sub access_someuserhost ($) {
294     my ($some) = @_;
295     my $user = access_cfg("$some-user",'username');
296     my $host = access_cfg("$some-host");
297     return length($user) ? "$user\@$host" : $host;
298 }
299
300 sub access_gituserhost () {
301     return access_someuserhost('git');
302 }
303
304 sub access_giturl () {
305     my $url = access_cfg('git-url','RETURN-UNDEF');
306     if (!defined $url) {
307         $url =
308             access_cfg('git-proto').
309             access_gituserhost().
310             access_cfg('git-path');
311     }
312     return "$url/$package.git";
313 }              
314
315 sub parsecontrolfh ($$@) {
316     my ($fh, $desc, @opts) = @_;
317     my %opts = ('name' => $desc, @opts);
318     my $c = Dpkg::Control::Hash->new(%opts);
319     $c->parse($fh) or die "parsing of $desc failed";
320     return $c;
321 }
322
323 sub parsecontrol {
324     my ($file, $desc) = @_;
325     my $fh = new IO::Handle;
326     open $fh, '<', $file or die "$file: $!";
327     my $c = parsecontrolfh($fh,$desc);
328     $fh->error and die $!;
329     close $fh;
330     return $c;
331 }
332
333 sub getfield ($$) {
334     my ($dctrl,$field) = @_;
335     my $v = $dctrl->{$field};
336     return $v if defined $v;
337     fail "missing field $field in ".$v->get_option('name');
338 }
339
340 sub parsechangelog {
341     my $c = Dpkg::Control::Hash->new();
342     my $p = new IO::Handle;
343     my @cmd = (qw(dpkg-parsechangelog), @_);
344     open $p, '-|', @cmd or die $!;
345     $c->parse($p);
346     $?=0; $!=0; close $p or failedcmd @cmd;
347     return $c;
348 }
349
350 our %rmad;
351
352 sub archive_query ($) {
353     my ($method) = @_;
354     my $query = access_cfg('archive-query','RETURN-UNDEF');
355     if (!defined $query) {
356         my $distro = access_distro();
357         if ($distro eq 'debian') {
358             $query = "sshdakls:".
359                 access_someuserhost('sshdakls').':'.
360                 access_cfg('sshdakls-dir');
361         } else {
362             $query = "madison:$distro";
363         }
364     }
365     $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
366     my $proto = $1;
367     my $data = $'; #';
368     { no strict qw(refs); &{"${method}_${proto}"}($proto,$data); }
369 }
370
371 sub archive_query_madison ($$) {
372     my ($proto,$data) = @_;
373     die unless $proto eq 'madison';
374     $rmad{$package} ||= cmdoutput
375         qw(rmadison -asource),"-s$isuite","-u$data",$package;
376     my $rmad = $rmad{$package};
377     return madison_parse($rmad);
378 }
379
380 sub archive_query_sshdakls ($$) {
381     my ($proto,$data) = @_;
382     $data =~ s/:.*// or badcfg "invalid sshdakls method string \`$data'";
383     my $dakls = cmdoutput
384         access_cfg('ssh'), $data, qw(dak ls -asource),"-s$isuite",$package;
385     return madison_parse($dakls);
386 }
387
388 sub canonicalise_suite_sshdakls ($$) {
389     my ($proto,$data) = @_;
390     $data =~ m/:/ or badcfg "invalid sshdakls method string \`$data'";
391     my @cmd =
392         (access_cfg('ssh'), $`,
393          "set -e; cd $';".
394          " if test -h $isuite; then readlink $isuite; exit 0; fi;".
395          " if test -d $isuite; then echo $isuite; exit 0; fi;".
396          " exit 1");
397     my $dakls = cmdoutput @cmd;
398     failedcmd @cmd unless $dakls =~ m/^\w/;
399     return $dakls;
400 }
401
402 sub madison_parse ($) {
403     my ($rmad) = @_;
404     my @out;
405     foreach my $l (split /\n/, $rmad) {
406         $l =~ m{^ \s*( [^ \t|]+ )\s* \|
407                   \s*( [^ \t|]+ )\s* \|
408                   \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
409                   \s*( [^ \t|]+ )\s* }x or die "$rmad $?";
410         $1 eq $package or die "$rmad $package ?";
411         my $vsn = $2;
412         my $newsuite = $3;
413         my $component;
414         if (defined $4) {
415             $component = $4;
416         } else {
417             $component = access_cfg('archive-query-default-component');
418         }
419         $5 eq 'source' or die "$rmad ?";
420         my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
421         my $subpath = "/pool/$component/$prefix/$package/".dscfn($vsn);
422         push @out, [$vsn,$subpath,$newsuite];
423     }
424     return sort { -version_compare_string($a->[0],$b->[0]); } @out;
425 }
426
427 sub canonicalise_suite_madison ($$) {
428     my @r = archive_query_madison($_[0],$_[1]);
429     @r or fail
430         "unable to canonicalise suite using package $package".
431         " which does not appear to exist in suite $isuite;".
432         " --existing-package may help";
433     return $r[0][2];
434 }
435
436 sub canonicalise_suite () {
437     return if defined $csuite;
438     fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
439     $csuite = archive_query('canonicalise_suite');
440     if ($isuite ne $csuite) {
441         # madison canonicalises for us
442         print "canonical suite name for $isuite is $csuite\n";
443     }
444 }
445
446 sub get_archive_dsc () {
447     canonicalise_suite();
448     my @vsns = archive_query('archive_query');
449     foreach my $vinfo (@vsns) {
450         my ($vsn,$subpath) = @$vinfo;
451         $dscurl = access_cfg('mirror').$subpath;
452         $dscdata = url_get($dscurl);
453         next unless defined $dscdata;
454         my $dscfh = new IO::File \$dscdata, '<' or die $!;
455         print DEBUG Dumper($dscdata) if $debug>1;
456         $dsc = parsecontrolfh($dscfh,$dscurl, allow_pgp=>1);
457         print DEBUG Dumper($dsc) if $debug>1;
458         my $fmt = getfield $dsc, 'Format';
459         fail "unsupported source format $fmt, sorry" unless $format_ok{$fmt};
460         return;
461     }
462     $dsc = undef;
463 }
464
465 sub check_for_git () {
466     # returns 0 or 1
467     my $how = access_cfg('git-check');
468     if ($how eq 'ssh-cmd') {
469         my @cmd =
470             (access_cfg('ssh'),access_gituserhost(),
471              " set -e; cd ".access_cfg('git-path').";".
472              " if test -d $package.git; then echo 1; else echo 0; fi");
473         my $r= cmdoutput @cmd;
474         failedcmd @cmd unless $r =~ m/^[01]$/;
475         return $r+0;
476     } else {
477         badcfg "unknown git-check \`$how'";
478     }
479 }
480
481 sub create_remote_git_repo () {
482     my $how = access_cfg('git-create');
483     if ($how eq 'ssh-cmd') {
484         runcmd_ordryrun
485             (access_cfg('ssh'),access_gituserhost(),
486              "set -e; cd ".access_cfg('git-path').";".
487              " cp -a _template $package.git");
488     } else {
489         badcfg "unknown git-create \`$how'";
490     }
491 }
492
493 our ($dsc_hash,$lastpush_hash);
494
495 our $ud = '.git/dgit/unpack';
496
497 sub prep_ud () {
498     rmtree($ud);
499     mkpath '.git/dgit';
500     mkdir $ud or die $!;
501 }
502
503 sub mktree_in_ud_from_only_subdir () {
504     # changes into the subdir
505     my (@dirs) = <*/.>;
506     die unless @dirs==1;
507     $dirs[0] =~ m#^([^/]+)/\.$# or die;
508     my $dir = $1;
509     chdir $dir or die "$dir $!";
510     fail "source package contains .git directory" if stat '.git';
511     die $! unless $!==&ENOENT;
512     runcmd qw(git init -q);
513     rmtree('.git/objects');
514     symlink '../../../../objects','.git/objects' or die $!;
515     runcmd @git, qw(add -Af);
516     my $tree = cmdoutput @git, qw(write-tree);
517     $tree =~ m/^\w+$/ or die "$tree ?";
518     return ($tree,$dir);
519 }
520
521 sub dsc_files_info () {
522     foreach my $csumi (['Checksums-Sha256','Digest::SHA', 'new(256)'],
523                        ['Checksums-Sha1',  'Digest::SHA', 'new(1)'],
524                        ['Files',           'Digest::MD5', 'new()']) {
525         my ($fname, $module, $method) = @$csumi;
526         my $field = $dsc->{$fname};
527         next unless defined $field;
528         eval "use $module; 1;" or die $@;
529         my @out;
530         foreach (split /\n/, $field) {
531             next unless m/\S/;
532             m/^(\w+) (\d+) (\S+)$/ or
533                 fail "could not parse .dsc $fname line \`$_'";
534             my $digester = eval "$module"."->$method;" or die $@;
535             push @out, {
536                 Hash => $1,
537                 Bytes => $2,
538                 Filename => $3,
539                 Digester => $digester,
540             };
541         }
542         return @out;
543     }
544     fail "missing any supported Checksums-* or Files field in ".
545         $dsc->get_option('name');
546 }
547
548 sub dsc_files () {
549     map { $_->{Filename} } dsc_files_info();
550 }
551
552 sub is_orig_file ($) {
553     local ($_) = @_;
554     m/\.orig(?:-\w+)?\.tar\.\w+$/;
555 }
556
557 sub make_commit ($) {
558     my ($file) = @_;
559     return cmdoutput @git, qw(hash-object -w -t commit), $file;
560 }
561
562 sub generate_commit_from_dsc () {
563     prep_ud();
564     chdir $ud or die $!;
565     my @files;
566     foreach my $f (dsc_files()) {
567         die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
568         push @files, $f;
569         link "../../../$f", $f
570             or $!==&ENOENT
571             or die "$f $!";
572     }
573     runcmd @dget, qw(--), $dscurl;
574     foreach my $f (grep { is_orig_file($_) } @files) {
575         link $f, "../../../../$f"
576             or $!==&EEXIST
577             or die "$f $!";
578     }
579     my ($tree,$dir) = mktree_in_ud_from_only_subdir();
580     runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
581     my $clogp = parsecontrol('../changelog.tmp',"commit's changelog");
582     my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
583     my $author = getfield $clogp, 'Maintainer';
584     $author =~ s#,.*##ms;
585     my $authline = "$author $date";
586     $authline =~ m/^[^<>]+ \<\S+\> \d+ [-+]\d+$/ or
587         fail "unexpected commit author line format \`$authline'".
588             " (was generated from changelog Maintainer field)";
589     my $changes = getfield $clogp, 'Changes';
590     open C, ">../commit.tmp" or die $!;
591     print C <<END or die $!;
592 tree $tree
593 author $authline
594 committer $authline
595
596 $changes
597
598 # imported from the archive
599 END
600     close C or die $!;
601     my $outputhash = make_commit qw(../commit.tmp);
602     my $cversion = getfield $clogp, 'Version';
603     print "synthesised git commit from .dsc $cversion\n";
604     if ($lastpush_hash) {
605         runcmd @git, qw(reset --hard), $lastpush_hash;
606         runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
607         my $oldclogp = parsecontrol('../changelogold.tmp','previous changelog');
608         my $oversion = getfield $oldclogp, 'Version';
609         my $vcmp =
610             version_compare_string($oversion, $cversion);
611         if ($vcmp < 0) {
612             # git upload/ is earlier vsn than archive, use archive
613             open C, ">../commit2.tmp" or die $!;
614             print C <<END or die $!;
615 tree $tree
616 parent $lastpush_hash
617 parent $outputhash
618 author $authline
619 committer $authline
620
621 Record $package ($cversion) in archive suite $csuite
622 END
623             $outputhash = make_commit qw(../commit2.tmp);
624         } elsif ($vcmp > 0) {
625             print STDERR <<END or die $!;
626
627 Version actually in archive:    $cversion (older)
628 Last allegedly pushed/uploaded: $oversion (newer or same)
629 $later_warning_msg
630 END
631             $outputhash = $lastpush_hash;
632         } else {
633             $outputhash = $lastpush_hash;
634         }
635     }
636     chdir '../../../..' or die $!;
637     runcmd @git, qw(update-ref -m),"dgit fetch import $cversion",
638             'DGIT_ARCHIVE', $outputhash;
639     cmdoutput @git, qw(log -n2), $outputhash;
640     # ... gives git a chance to complain if our commit is malformed
641     rmtree($ud);
642     return $outputhash;
643 }
644
645 sub ensure_we_have_orig () {
646     foreach my $fi (dsc_files_info()) {
647         my $f = $fi->{Filename};
648         next unless is_orig_file($f);
649         if (open F, "<", "../$f") {
650             $fi->{Digester}->reset();
651             $fi->{Digester}->addfile(*F);
652             F->error and die $!;
653             my $got = $fi->{Digester}->hexdigest();
654             $got eq $fi->{Hash} or
655                 fail "existing file $f has hash $got but .dsc".
656                     " demands hash $fi->{Hash}".
657                     " (perhaps you should delete this file?)";
658             print "using existing $f\n";
659             next;
660         } else {
661             die "$f $!" unless $!==&ENOENT;
662         }
663         my $origurl = $dscurl;
664         $origurl =~ s{/[^/]+$}{};
665         $origurl .= "/$f";
666         die "$f ?" unless $f =~ m/^${package}_/;
667         die "$f ?" if $f =~ m#/#;
668         runcmd_ordryrun shell_cmd 'cd ..', @dget,'--',$origurl;
669     }
670 }
671
672 sub rev_parse ($) {
673     return cmdoutput @git, qw(rev-parse), "$_[0]~0";
674 }
675
676 sub is_fast_fwd ($$) {
677     my ($ancestor,$child) = @_;
678     my @cmd = (@git, qw(merge-base), $ancestor, $child);
679     my $mb = cmdoutput_errok @cmd;
680     if (defined $mb) {
681         return rev_parse($mb) eq rev_parse($ancestor);
682     } else {
683         $?==256 or failedcmd @cmd;
684         return 0;
685     }
686 }
687
688 sub git_fetch_us () {
689     runcmd_ordryrun @git, qw(fetch),access_giturl(),fetchspec();
690 }
691
692 sub fetch_from_archive () {
693     # ensures that lrref() is what is actually in the archive,
694     #  one way or another
695     get_archive_dsc();
696
697     if ($dsc) {
698         foreach my $field (@ourdscfield) {
699             $dsc_hash = $dsc->{$field};
700             last if defined $dsc_hash;
701         }
702         if (defined $dsc_hash) {
703             $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
704             $dsc_hash = $&;
705             print "last upload to archive specified git hash\n";
706         } else {
707             print "last upload to archive has NO git hash\n";
708         }
709     } else {
710         print "no version available from the archive\n";
711     }
712
713     my $lrref_fn = ".git/".lrref();
714     if (open H, $lrref_fn) {
715         $lastpush_hash = <H>;
716         chomp $lastpush_hash;
717         die "$lrref_fn $lastpush_hash ?" unless $lastpush_hash =~ m/^\w+$/;
718     } elsif ($! == &ENOENT) {
719         $lastpush_hash = '';
720     } else {
721         die "$lrref_fn $!";
722     }
723     print DEBUG "previous reference hash=$lastpush_hash\n";
724     my $hash;
725     if (defined $dsc_hash) {
726         fail "missing git history even though dsc has hash -".
727             " could not find commit $dsc_hash".
728             " (should be in ".access_giturl()."#".rrref().")"
729             unless $lastpush_hash;
730         $hash = $dsc_hash;
731         ensure_we_have_orig();
732         if ($dsc_hash eq $lastpush_hash) {
733         } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
734             print STDERR <<END or die $!;
735
736 Git commit in archive is behind the last version allegedly pushed/uploaded.
737 Commit referred to by archive:  $dsc_hash
738 Last allegedly pushed/uploaded: $lastpush_hash
739 $later_warning_msg
740 END
741             $hash = $lastpush_hash;
742         } else {
743             fail "archive's .dsc refers to ".$dsc_hash.
744                 " but this is an ancestor of ".$lastpush_hash;
745         }
746     } elsif ($dsc) {
747         $hash = generate_commit_from_dsc();
748     } elsif ($lastpush_hash) {
749         # only in git, not in the archive yet
750         $hash = $lastpush_hash;
751         print STDERR <<END or die $!;
752
753 Package not found in the archive, but has allegedly been
754 pushed/uploaded using dgit.
755 $later_warning_msg
756 END
757     } else {
758         print DEBUG "nothing found!\n";
759         return 0;
760     }
761     print DEBUG "current hash=$hash\n";
762     if ($lastpush_hash) {
763         fail "not fast forward on last upload branch!".
764             " (archive's version left in DGIT_ARCHIVE)"
765             unless is_fast_fwd($lastpush_hash, $hash);
766     }
767     if ($lastpush_hash ne $hash) {
768         my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
769         if (!$dryrun) {
770             cmdoutput @upd_cmd;
771         } else {
772             dryrun_report @upd_cmd;
773         }
774     }
775     return 1;
776 }
777
778 sub clone ($) {
779     my ($dstdir) = @_;
780     canonicalise_suite();
781     badusage "dry run makes no sense with clone" if $dryrun;
782     mkdir $dstdir or die "$dstdir $!";
783     chdir "$dstdir" or die "$dstdir $!";
784     runcmd @git, qw(init -q);
785     runcmd @git, qw(config), "remote.$remotename.fetch", fetchspec();
786     open H, "> .git/HEAD" or die $!;
787     print H "ref: ".lref()."\n" or die $!;
788     close H or die $!;
789     runcmd @git, qw(remote add), 'origin', access_giturl();
790     if (check_for_git()) {
791         print "fetching existing git history\n";
792         git_fetch_us();
793         runcmd_ordryrun @git, qw(fetch origin);
794     } else {
795         print "starting new git history\n";
796     }
797     fetch_from_archive() or no_such_package;
798     runcmd @git, qw(reset --hard), lrref();
799     printdone "ready for work in $dstdir";
800 }
801
802 sub fetch () {
803     if (check_for_git()) {
804         git_fetch_us();
805     }
806     fetch_from_archive() or no_such_package();
807     printdone "fetched into ".lrref();
808 }
809
810 sub pull () {
811     fetch();
812     runcmd_ordryrun @git, qw(merge -m),"Merge from $csuite [dgit]",
813         lrref();
814     printdone "fetched to ".lrref()." and merged into HEAD";
815 }
816
817 sub check_not_dirty () {
818     return if $ignoredirty;
819     my @cmd = (@git, qw(diff --quiet HEAD));
820     printcmd(\*DEBUG,"+",@cmd) if $debug>0;
821     $!=0; $?=0; system @cmd;
822     return if !$! && !$?;
823     if (!$! && $?==256) {
824         fail "working tree is dirty (does not match HEAD)";
825     } else {
826         failedcmd @cmd;
827     }
828 }
829
830 sub commit_quilty_patch () {
831     my $output = cmdoutput @git, qw(status --porcelain);
832     my %adds;
833     my $bad=0;
834     foreach my $l (split /\n/, $output) {
835         next unless $l =~ m/\S/;
836         if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
837             $adds{$1}++;
838         } else {
839             print STDERR "git status: $l\n";
840             $bad++;
841         }
842     }
843     fail "unexpected output from git status (is tree clean?)" if $bad;
844     if (!%adds) {
845         print "nothing quilty to commit, ok.\n";
846         return;
847     }
848     runcmd_ordryrun @git, qw(add), sort keys %adds;
849     my $m = "Commit Debian 3.0 (quilt) metadata";
850     print "$m\n";
851     runcmd_ordryrun @git, qw(commit -m), $m;
852 }
853
854 sub madformat ($) {
855     my ($format) = @_;
856     return 0 unless $format eq '3.0 (quilt)';
857     print "Format \`$format', urgh\n";
858     if ($noquilt) {
859         print "Not doing any fixup of \`$format' due to --no-quilt-fixup";
860         return 0;
861     }
862     return 1;
863 }
864
865 sub dopush () {
866     print DEBUG "actually entering push\n";
867     my $clogp = parsechangelog();
868     $package = getfield $clogp, 'Source';
869     my $cversion = getfield $clogp, 'Version';
870     my $dscfn = dscfn($cversion);
871     stat "../$dscfn" or
872         fail "looked for .dsc $dscfn, but $!;".
873             " maybe you forgot to build";
874     $dsc = parsecontrol("../$dscfn","$dscfn");
875     my $dscpackage = getfield $dsc, 'Source';
876     my $format = getfield $dsc, 'Format';
877     my $dversion = getfield $dsc, 'Version';
878     ($dscpackage eq $package && $dversion eq $cversion) or
879         fail "$dsc is for $dscpackage $dversion".
880             " but debian/changelog is for $package $cversion";
881     print DEBUG "format $format\n";
882     if (madformat($format)) {
883         commit_quilty_patch();
884     }
885     check_not_dirty();
886     prep_ud();
887     chdir $ud or die $!;
888     print "checking that $dscfn corresponds to HEAD\n";
889     runcmd qw(dpkg-source -x --), "../../../../$dscfn";
890     my ($tree,$dir) = mktree_in_ud_from_only_subdir();
891     chdir '../../../..' or die $!;
892     printcmd \*DEBUG,"+",@_;
893     my @diffcmd = (@git, qw(diff --exit-code), $tree);
894     $!=0; $?=0;
895     if (system @diffcmd) {
896         if ($! && $?==256) {
897             fail "$dscfn specifies a different tree to your HEAD commit;".
898                 " perhaps you forgot to build";
899         } else {
900             failedcmd @diffcmd;
901         }
902     }
903 #fetch from alioth
904 #do fast forward check and maybe fake merge
905 #    if (!is_fast_fwd(mainbranch
906 #    runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
907 #        map { lref($_).":".rref($_) }
908 #        (uploadbranch());
909     $dsc->{$ourdscfield[0]} = rev_parse('HEAD');
910     $dsc->save("../$dscfn.tmp") or die $!;
911     if (!$changesfile) {
912         my $multi = "../${package}_".(stripepoch $cversion)."_multi.changes";
913         if (stat "$multi") {
914             $changesfile = $multi;
915         } else {
916             $!==&ENOENT or die "$multi: $!";
917             my $pat = "${package}_".(stripepoch $cversion)."_*.changes";
918             my @cs = glob "../$pat";
919             fail "failed to find unique changes file".
920                 " (looked for $pat in .., or $multi);".
921                 " perhaps you need to use dgit -C"
922                 unless @cs==1;
923             ($changesfile) = @cs;
924         }
925     }
926     my $changes = parsecontrol($changesfile,$changesfile);
927     foreach my $field (qw(Source Distribution Version)) {
928         $changes->{$field} eq $clogp->{$field} or
929             fail "changes field $field \`$changes->{$field}'".
930                 " does not match changelog \`$clogp->{$field}'";
931     }
932     my $tag = debiantag($dversion);
933     if (!check_for_git()) {
934         create_remote_git_repo();
935     }
936     runcmd_ordryrun @git, qw(push),access_giturl(),"HEAD:".rrref();
937     runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), 'HEAD';
938     if (!$dryrun) {
939         rename "../$dscfn.tmp","../$dscfn" or die "$dscfn $!";
940     } else {
941         print "[new .dsc left in $dscfn.tmp]\n";
942     }
943     if ($sign) {
944         if (!defined $keyid) {
945             $keyid = access_cfg('keyid','RETURN-UNDEF');
946         }
947         my @tag_cmd = (@git, qw(tag -s -m),
948                        "$package release $dversion for $csuite [dgit]");
949         push @tag_cmd, qw(-u),$keyid if defined $keyid;
950         push @tag_cmd, $tag;
951         runcmd_ordryrun @tag_cmd;
952         my @debsign_cmd = @debsign;
953         push @debsign_cmd, "-k$keyid" if defined $keyid;
954         push @debsign_cmd, $changesfile;
955         runcmd_ordryrun @debsign_cmd;
956     }
957     runcmd_ordryrun @git, qw(push),access_giturl(),"refs/tags/$tag";
958     my $host = access_cfg('upload-host','RETURN-UNDEF');
959     my @hostarg = defined($host) ? ($host,) : ();
960     runcmd_ordryrun @dput, @hostarg, $changesfile;
961     printdone "pushed and uploaded $dversion";
962 }
963
964 sub cmd_clone {
965     parseopts();
966     my $dstdir;
967     badusage "-p is not allowed with clone; specify as argument instead"
968         if defined $package;
969     if (@ARGV==1) {
970         ($package) = @ARGV;
971     } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
972         ($package,$isuite) = @ARGV;
973     } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
974         ($package,$dstdir) = @ARGV;
975     } elsif (@ARGV==3) {
976         ($package,$isuite,$dstdir) = @ARGV;
977     } else {
978         badusage "incorrect arguments to dgit clone";
979     }
980     $dstdir ||= "$package";
981     clone($dstdir);
982 }
983
984 sub branchsuite () {
985     my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
986     if ($branch =~ m#$lbranch_re#o) {
987         return $1;
988     } else {
989         return undef;
990     }
991 }
992
993 sub fetchpullargs () {
994     if (!defined $package) {
995         my $sourcep = parsecontrol('debian/control','debian/control');
996         $package = getfield $sourcep, 'Source';
997     }
998     if (@ARGV==0) {
999 #       $isuite = branchsuite();  # this doesn't work because dak hates canons
1000         if (!$isuite) {
1001             my $clogp = parsechangelog();
1002             $isuite = getfield $clogp, 'Distribution';
1003         }
1004         canonicalise_suite();
1005         print "fetching from suite $csuite\n";
1006     } elsif (@ARGV==1) {
1007         ($isuite) = @ARGV;
1008         canonicalise_suite();
1009     } else {
1010         badusage "incorrect arguments to dgit fetch or dgit pull";
1011     }
1012 }
1013
1014 sub cmd_fetch {
1015     parseopts();
1016     fetchpullargs();
1017     fetch();
1018 }
1019
1020 sub cmd_pull {
1021     parseopts();
1022     fetchpullargs();
1023     pull();
1024 }
1025
1026 sub cmd_push {
1027     parseopts();
1028     badusage "-p is not allowed with dgit push" if defined $package;
1029     check_not_dirty();
1030     my $clogp = parsechangelog();
1031     $package = getfield $clogp, 'Source';
1032     if (@ARGV==0) {
1033         $isuite = getfield $clogp, 'Distribution';
1034         if ($new_package) {
1035             local ($package) = $existing_package; # this is a hack
1036             canonicalise_suite();
1037         }
1038     } else {
1039         badusage "incorrect arguments to dgit push";
1040     }
1041     if (check_for_git()) {
1042         git_fetch_us();
1043     }
1044     if (fetch_from_archive()) {
1045         is_fast_fwd(lrref(), 'HEAD') or
1046             fail "dgit push: HEAD is not a descendant".
1047                 " of the archive's version.\n".
1048                 "$us: To overwrite it, use git-merge -s ours ".lrref().".";
1049     } else {
1050         $new_package or
1051             fail "package appears to be new in this suite;".
1052                 " if this is intentional, use --new";
1053     }
1054     dopush();
1055 }
1056
1057 our $version;
1058 our $sourcechanges;
1059 our $dscfn;
1060
1061 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
1062
1063 sub build_maybe_quilt_fixup () {
1064     if (!open F, "debian/source/format") {
1065         die $! unless $!==&ENOENT;
1066         return;
1067     }
1068     $_ = <F>;
1069     F->error and die $!;
1070     chomp;
1071     return unless madformat($_);
1072     # sigh
1073     my $clogp = parsechangelog();
1074     my $version = getfield $clogp, 'Version';
1075     my $author = getfield $clogp, 'Maintainer';
1076     my $headref = rev_parse('HEAD');
1077     my $time = time;
1078     my $ncommits = 3;
1079     my $patchname = "auto-$version-$headref-$time";
1080     my $msg = cmdoutput @git, qw(log), "-n$ncommits";
1081     mkpath '.git/dgit';
1082     my $descfn = ".git/dgit/quilt-description.tmp";
1083     open O, '>', $descfn or die "$descfn: $!";
1084     $msg =~ s/\n/\n /g;
1085     $msg =~ s/^\s+$/ ./mg;
1086     print O <<END or die $!;
1087 Description: Automatically generated patch ($clogp->{Version})
1088  Last (up to) $ncommits git changes, FYI:
1089  .
1090  $msg
1091 Author: $author
1092
1093 ---
1094
1095 END
1096     close O or die $!;
1097     {
1098         local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
1099         local $ENV{'VISUAL'} = $ENV{'EDITOR'};
1100         local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
1101         runcmd_ordryrun @dpkgsource, qw(--commit .), $patchname;
1102     }
1103
1104     if (!open P, '>>', ".pc/applied-patches") {
1105         $!==&ENOENT or die $!;
1106     } else {
1107         close P;
1108     }
1109
1110     commit_quilty_patch();
1111 }
1112
1113 sub quilt_fixup_editor () {
1114     my $descfn = $ENV{$fakeeditorenv};
1115     my $editing = $ARGV[$#ARGV];
1116     open I1, '<', $descfn or die "$descfn: $!";
1117     open I2, '<', $editing or die "$editing: $!";
1118     unlink $editing or die "$editing: $!";
1119     open O, '>', $editing or die "$editing: $!";
1120     while (<I1>) { print O or die $!; } I1->error and die $!;
1121     my $copying = 0;
1122     while (<I2>) {
1123         $copying ||= m/^\-\-\- /;
1124         next unless $copying;
1125         print O or die $!;
1126     }
1127     I2->error and die $!;
1128     close O or die $1;
1129     exit 0;
1130 }
1131
1132 sub build_prep () {
1133     badusage "-p is not allowed when building" if defined $package;
1134     check_not_dirty();
1135     my $clogp = parsechangelog();
1136     $isuite = getfield $clogp, 'Distribution';
1137     $package = getfield $clogp, 'Source';
1138     $version = getfield $clogp, 'Version';
1139     build_maybe_quilt_fixup();
1140 }
1141
1142 sub cmd_build {
1143     badusage "dgit build implies --clean=dpkg-source"
1144         if $cleanmode ne 'dpkg-source';
1145     build_prep();
1146     runcmd_ordryrun @dpkgbuildpackage, qw(-us -uc), changesopts(), @ARGV;
1147     printdone "build successful\n";
1148 }
1149
1150 sub cmd_git_build {
1151     badusage "dgit git-build implies --clean=dpkg-source"
1152         if $cleanmode ne 'dpkg-source';
1153     build_prep();
1154     my @cmd =
1155         (qw(git-buildpackage -us -uc --git-no-sign-tags),
1156          "--git-builder=@dpkgbuildpackage");
1157     unless (grep { m/^--git-debian-branch|^--git-ignore-branch/ } @ARGV) {
1158         canonicalise_suite();
1159         push @cmd, "--git-debian-branch=".lbranch();
1160     }
1161     push @cmd, changesopts();
1162     runcmd_ordryrun @cmd, @ARGV;
1163     printdone "build successful\n";
1164 }
1165
1166 sub build_source {
1167     build_prep();
1168     $sourcechanges = "${package}_".(stripepoch $version)."_source.changes";
1169     $dscfn = dscfn($version);
1170     if ($cleanmode eq 'dpkg-source') {
1171         runcmd_ordryrun (@dpkgbuildpackage, qw(-us -uc -S)), changesopts();
1172     } else {
1173         if ($cleanmode eq 'git') {
1174             runcmd_ordryrun @git, qw(clean -xdf);
1175         } elsif ($cleanmode eq 'none') {
1176         } else {
1177             die "$cleanmode ?";
1178         }
1179         my $pwd = cmdoutput qw(env - pwd);
1180         my $leafdir = basename $pwd;
1181         chdir ".." or die $!;
1182         runcmd_ordryrun @dpkgsource, qw(-b --), $leafdir;
1183         chdir $pwd or die $!;
1184         runcmd_ordryrun qw(sh -ec),
1185             'exec >$1; shift; exec "$@"','x',
1186             "../$sourcechanges",
1187             @dpkggenchanges, qw(-S), changesopts();
1188     }
1189 }
1190
1191 sub cmd_build_source {
1192     badusage "build-source takes no additional arguments" if @ARGV;
1193     build_source();
1194     printdone "source built, results in $dscfn and $sourcechanges";
1195 }
1196
1197 sub cmd_sbuild {
1198     build_source();
1199     chdir ".." or die $!;
1200     my $pat = "${package}_".(stripepoch $version)."_*.changes";
1201     if (!$dryrun) {
1202         stat $dscfn or fail "$dscfn (in parent directory): $!";
1203         stat $sourcechanges or fail "$sourcechanges (in parent directory): $!";
1204         foreach my $cf (glob $pat) {
1205             next if $cf eq $sourcechanges;
1206             unlink $cf or fail "remove $cf: $!";
1207         }
1208     }
1209     runcmd_ordryrun @sbuild, @ARGV, qw(-d), $isuite, $dscfn;
1210     runcmd_ordryrun @mergechanges, glob $pat;
1211     my $multichanges = "${package}_".(stripepoch $version)."_multi.changes";
1212     if (!$dryrun) {
1213         stat $multichanges or fail "$multichanges: $!";
1214     }
1215     printdone "build successful, results in $multichanges\n" or die $!;
1216 }    
1217
1218 sub cmd_quilt_fixup {
1219     badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
1220     my $clogp = parsechangelog();
1221     $version = getfield $clogp, 'Version';
1222     build_maybe_quilt_fixup();
1223 }
1224
1225 sub cmd_version {
1226     print "dgit version $our_version\n" or die $!;
1227     exit 0;
1228 }
1229
1230 sub parseopts () {
1231     my $om;
1232     while (@ARGV) {
1233         last unless $ARGV[0] =~ m/^-/;
1234         $_ = shift @ARGV;
1235         last if m/^--?$/;
1236         if (m/^--/) {
1237             if (m/^--dry-run$/) {
1238                 $dryrun=1;
1239             } elsif (m/^--no-sign$/) {
1240                 $sign=0;
1241             } elsif (m/^--help$/) {
1242                 cmd_help();
1243             } elsif (m/^--version$/) {
1244                 cmd_version();
1245             } elsif (m/^--new$/) {
1246                 $new_package=1;
1247             } elsif (m/^--(\w+)=(.*)/s &&
1248                      ($om = $opts_opt_map{$1}) &&
1249                      length $om->[0]) {
1250                 $om->[0] = $2;
1251             } elsif (m/^--(\w+):(.*)/s &&
1252                      ($om = $opts_opt_map{$1})) {
1253                 push @$om, $2;
1254             } elsif (m/^--existing-package=(.*)/s) {
1255                 $existing_package = $1;
1256             } elsif (m/^--distro=(.*)/s) {
1257                 $idistro = $1;
1258             } elsif (m/^--clean=(dpkg-source|git|none)$/s) {
1259                 $cleanmode = $1;
1260             } elsif (m/^--clean=(.*)$/s) {
1261                 badusage "unknown cleaning mode \`$1'";
1262             } elsif (m/^--ignore-dirty$/s) {
1263                 $ignoredirty = 1;
1264             } elsif (m/^--no-quilt-fixup$/s) {
1265                 $noquilt = 1;
1266             } else {
1267                 badusage "unknown long option \`$_'";
1268             }
1269         } else {
1270             while (m/^-./s) {
1271                 if (s/^-n/-/) {
1272                     $dryrun=1;
1273                 } elsif (s/^-h/-/) {
1274                     cmd_help();
1275                 } elsif (s/^-D/-/) {
1276                     open DEBUG, ">&STDERR" or die $!;
1277                     $debug++;
1278                 } elsif (s/^-N/-/) {
1279                     $new_package=1;
1280                 } elsif (m/^-[vm]/) {
1281                     push @changesopts, $_;
1282                     $_ = '';
1283                 } elsif (s/^-c(.*=.*)//s) {
1284                     push @git, '-c', $1;
1285                 } elsif (s/^-d(.*)//s) {
1286                     $idistro = $1;
1287                 } elsif (s/^-C(.*)//s) {
1288                     $changesfile = $1;
1289                 } elsif (s/^-k(.*)//s) {
1290                     $keyid=$1;
1291                 } elsif (s/^-wn//s) {
1292                     $cleanmode = 'none';
1293                 } elsif (s/^-wg//s) {
1294                     $cleanmode = 'git';
1295                 } elsif (s/^-wd//s) {
1296                     $cleanmode = 'dpkg-source';
1297                 } else {
1298                     badusage "unknown short option \`$_'";
1299                 }
1300             }
1301         }
1302     }
1303 }
1304
1305 if ($ENV{$fakeeditorenv}) {
1306     quilt_fixup_editor();
1307 }
1308
1309 delete $ENV{'DGET_UNPACK'};
1310
1311 parseopts();
1312 print STDERR "DRY RUN ONLY\n" if $dryrun;
1313 if (!@ARGV) {
1314     print STDERR $helpmsg or die $!;
1315     exit 8;
1316 }
1317 my $cmd = shift @ARGV;
1318 $cmd =~ y/-/_/;
1319 { no strict qw(refs); &{"cmd_$cmd"}(); }