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