chiark / gitweb /
Better error message for use of UNRELEASED suite. Closes: #720523.
[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/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://ftp.debian.org/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     return if defined $csuite;
419     fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
420     $csuite = archive_query('canonicalise_suite');
421     if ($isuite ne $csuite) {
422         # madison canonicalises for us
423         print "canonical suite name for $isuite is $csuite\n";
424     }
425 }
426
427 sub get_archive_dsc () {
428     canonicalise_suite();
429     my @vsns = archive_query('archive_query');
430     foreach my $vinfo (@vsns) {
431         my ($vsn,$subpath) = @$vinfo;
432         $dscurl = access_cfg('mirror').$subpath;
433         $dscdata = url_get($dscurl);
434         next unless defined $dscdata;
435         $dscurl = access_cfg('mirror').$subpath;
436         $dscdata = url_get($dscurl);
437         my $dscfh = new IO::File \$dscdata, '<' or die $!;
438         print DEBUG Dumper($dscdata) if $debug>1;
439         $dsc = parsecontrolfh($dscfh,$dscurl, allow_pgp=>1);
440         print DEBUG Dumper($dsc) if $debug>1;
441         my $fmt = getfield $dsc, 'Format';
442         fail "unsupported source format $fmt, sorry" unless $format_ok{$fmt};
443         return $dsc;
444     }
445     return undef;
446 }
447
448 sub check_for_git () {
449     # returns 0 or 1
450     my $how = access_cfg('git-check');
451     if ($how eq 'ssh-cmd') {
452         my @cmd =
453             (access_cfg('ssh'),access_gituserhost(),
454              " set -e; cd ".access_cfg('git-path').";".
455              " if test -d $package.git; then echo 1; else echo 0; fi");
456         my $r= cmdoutput @cmd;
457         failedcmd @cmd unless $r =~ m/^[01]$/;
458         return $r+0;
459     } else {
460         badcfg "unknown git-check \`$how'";
461     }
462 }
463
464 sub create_remote_git_repo () {
465     my $how = access_cfg('git-create');
466     if ($how eq 'ssh-cmd') {
467         runcmd_ordryrun
468             (access_cfg('ssh'),access_gituserhost(),
469              "set -e; cd ".access_cfg('git-path').";".
470              " cp -a _template $package.git");
471     } else {
472         badcfg "unknown git-create \`$how'";
473     }
474 }
475
476 our ($dsc_hash,$upload_hash);
477
478 our $ud = '.git/dgit/unpack';
479
480 sub prep_ud () {
481     rmtree($ud);
482     mkpath '.git/dgit';
483     mkdir $ud or die $!;
484 }
485
486 sub mktree_in_ud_from_only_subdir () {
487     # changes into the subdir
488     my (@dirs) = <*/.>;
489     die unless @dirs==1;
490     $dirs[0] =~ m#^([^/]+)/\.$# or die;
491     my $dir = $1;
492     chdir $dir or die "$dir $!";
493     fail "source package contains .git directory" if stat '.git';
494     die $! unless $!==&ENOENT;
495     runcmd qw(git init -q);
496     rmtree('.git/objects');
497     symlink '../../../../objects','.git/objects' or die $!;
498     runcmd @git, qw(add -Af);
499     my $tree = cmdoutput @git, qw(write-tree);
500     $tree =~ m/^\w+$/ or die "$tree ?";
501     return ($tree,$dir);
502 }
503
504 sub dsc_files () {
505     my $field = $dsc->{'Checksums-Sha256'} || $dsc->{Files};
506     defined $field or
507         fail "missing both Checksums-Sha256 and Files in ".
508         $dsc->get_option('name');
509     map {
510         m/^\w+ \d+ (\S+)$/ or
511             fail "could not parse .dsc Files/Checksums line \`$_'";
512         $1;
513     } grep m/\S/, split /\n/, $field;
514 }
515
516 sub is_orig_file ($) {
517     local ($_) = @_;
518     m/\.orig(?:-\w+)?\.tar\.\w+$/;
519 }
520
521 sub make_commit ($) {
522     my ($file) = @_;
523     return cmdoutput @git, qw(hash-object -w -t commit), $file;
524 }
525
526 sub generate_commit_from_dsc () {
527     prep_ud();
528     chdir $ud or die $!;
529     my @files;
530     foreach my $f (dsc_files()) {
531         die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
532         push @files, $f;
533         link "../../../$f", $f
534             or $!==&ENOENT
535             or die "$f $!";
536     }
537     runcmd @dget, qw(--), $dscurl;
538     foreach my $f (grep { is_orig_file($_) } @files) {
539         link $f, "../../../../$f"
540             or $!==&EEXIST
541             or die "$f $!";
542     }
543     my ($tree,$dir) = mktree_in_ud_from_only_subdir();
544     runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
545     my $clogp = parsecontrol('../changelog.tmp',"commit's changelog");
546     my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
547     my $author = getfield $clogp, 'Maintainer';
548     $author =~ s#,.*##ms;
549     my $authline = "$author $date";
550     $authline =~ m/^[^<>]+ \<\S+\> \d+ [-+]\d+$/ or
551         fail "unexpected commit author line format \`$authline'".
552             " (was generated from changelog Maintainer field)";
553     my $changes = getfield $clogp, 'Changes';
554     open C, ">../commit.tmp" or die $!;
555     print C <<END or die $!;
556 tree $tree
557 author $authline
558 committer $authline
559
560 $changes
561
562 # imported from the archive
563 END
564     close C or die $!;
565     my $outputhash = make_commit qw(../commit.tmp);
566     my $cversion = getfield $clogp, 'Version';
567     print "synthesised git commit from .dsc $cversion\n";
568     if ($upload_hash) {
569         runcmd @git, qw(reset --hard), $upload_hash;
570         runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
571         my $oldclogp = parsecontrol('../changelogold.tmp','previous changelog');
572         my $oversion = getfield $oldclogp, 'Version';
573         my $vcmp =
574             version_compare_string($oversion, $cversion);
575         if ($vcmp < 0) {
576             # git upload/ is earlier vsn than archive, use archive
577             open C, ">../commit2.tmp" or die $!;
578             print C <<END or die $!;
579 tree $tree
580 parent $upload_hash
581 parent $outputhash
582 author $authline
583 committer $authline
584
585 Record $package ($cversion) in archive suite $csuite
586 END
587             $outputhash = make_commit qw(../commit2.tmp);
588         } elsif ($vcmp > 0) {
589             print STDERR <<END or die $!;
590
591 Version actually in archive:    $cversion (older)
592 Last allegedly pushed/uploaded: $oversion (newer or same)
593 $later_warning_msg
594 END
595             $outputhash = $upload_hash;
596         } else {
597             $outputhash = $upload_hash;
598         }
599     }
600     chdir '../../../..' or die $!;
601     runcmd @git, qw(update-ref -m),"dgit fetch import $cversion",
602             'DGIT_ARCHIVE', $outputhash;
603     cmdoutput @git, qw(log -n2), $outputhash;
604     # ... gives git a chance to complain if our commit is malformed
605     rmtree($ud);
606     return $outputhash;
607 }
608
609 sub ensure_we_have_orig () {
610     foreach my $f (dsc_files()) {
611         next unless is_orig_file($f);
612         if (stat "../$f") {
613             die "$f ?" unless -f _;
614         } else {
615             die "$f $!" unless $!==&ENOENT;
616         }
617         my $origurl = $dscurl;
618         $origurl =~ s{/[^/]+$}{};
619         $origurl .= "/$f";
620         die "$f ?" unless $f =~ m/^${package}_/;
621         die "$f ?" if $f =~ m#/#;
622         runcmd_ordryrun qw(sh -ec),'cd ..; exec "$@"','x',
623             @dget,'--',$origurl;
624     }
625 }
626
627 sub rev_parse ($) {
628     return cmdoutput @git, qw(rev-parse), "$_[0]~0";
629 }
630
631 sub is_fast_fwd ($$) {
632     my ($ancestor,$child) = @_;
633     my $mb = cmdoutput @git, qw(merge-base), $ancestor, $child;
634     return rev_parse($mb) eq rev_parse($ancestor);
635 }
636
637 sub git_fetch_us () {
638     badusage "cannot dry run with fetch" if $dryrun;
639     runcmd @git, qw(fetch),access_giturl(),fetchspec();
640 }
641
642 sub fetch_from_archive () {
643     # ensures that lrref() is what is actually in the archive,
644     #  one way or another
645     get_archive_dsc() or return 0;
646     foreach my $field (@ourdscfield) {
647         $dsc_hash = $dsc->{$field};
648         last if defined $dsc_hash;
649     }
650     if (defined $dsc_hash) {
651         $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
652         $dsc_hash = $&;
653         print "last upload to archive specified git hash\n";
654     } else {
655         print "last upload to archive has NO git hash\n";
656     }
657
658     my $lrref_fn = ".git/".lrref();
659     if (open H, $lrref_fn) {
660         $upload_hash = <H>;
661         chomp $upload_hash;
662         die "$lrref_fn $upload_hash ?" unless $upload_hash =~ m/^\w+$/;
663     } elsif ($! == &ENOENT) {
664         $upload_hash = '';
665     } else {
666         die "$lrref_fn $!";
667     }
668     print DEBUG "previous reference hash=$upload_hash\n";
669     my $hash;
670     if (defined $dsc_hash) {
671         fail "missing git history even though dsc has hash -".
672             " could not find commit $dsc_hash".
673             " (should be in ".access_giturl()."#".rrref().")"
674             unless $upload_hash;
675         $hash = $dsc_hash;
676         ensure_we_have_orig();
677         if ($dsc_hash eq $upload_hash) {
678         } elsif (is_fast_fwd($dsc_hash,$upload_hash)) {
679             print STDERR <<END or die $!;
680
681 Git commit in archive is behind the last version allegedly pushed/uploaded.
682 Commit referred to by archive:  $dsc_hash
683 Last allegedly pushed/uploaded: $upload_hash
684 $later_warning_msg
685 END
686             $hash = $upload_hash;
687         } else {
688             fail "archive's .dsc refers to ".$dsc_hash.
689                 " but this is an ancestor of ".$upload_hash;
690         }
691     } else {
692         $hash = generate_commit_from_dsc();
693     }
694     print DEBUG "current hash=$hash\n";
695     if ($upload_hash) {
696         fail "not fast forward on last upload branch!".
697             " (archive's version left in DGIT_ARCHIVE)"
698             unless is_fast_fwd($upload_hash, $hash);
699     }
700     if ($upload_hash ne $hash) {
701         my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
702         if (!$dryrun) {
703             cmdoutput @upd_cmd;
704         } else {
705             dryrun_report @upd_cmd;
706         }
707     }
708     return 1;
709 }
710
711 sub clone ($) {
712     my ($dstdir) = @_;
713     canonicalise_suite();
714     badusage "dry run makes no sense with clone" if $dryrun;
715     mkdir $dstdir or die "$dstdir $!";
716     chdir "$dstdir" or die "$dstdir $!";
717     runcmd @git, qw(init -q);
718     runcmd @git, qw(config), "remote.$remotename.fetch", fetchspec();
719     open H, "> .git/HEAD" or die $!;
720     print H "ref: ".lref()."\n" or die $!;
721     close H or die $!;
722     runcmd @git, qw(remote add), 'origin', access_giturl();
723     if (check_for_git()) {
724         print "fetching existing git history\n";
725         git_fetch_us();
726         runcmd @git, qw(fetch origin);
727     } else {
728         print "starting new git history\n";
729     }
730     fetch_from_archive() or no_such_package;
731     runcmd @git, qw(reset --hard), lrref();
732     printdone "ready for work in $dstdir";
733 }
734
735 sub fetch () {
736     if (check_for_git()) {
737         git_fetch_us();
738     }
739     fetch_from_archive() or no_such_package();
740     printdone "fetched into ".lrref();
741 }
742
743 sub pull () {
744     fetch();
745     runcmd_ordryrun @git, qw(merge -m),"Merge from $csuite [dgit]",
746         lrref();
747     printdone "fetched to ".lrref()." and merged into HEAD";
748 }
749
750 sub check_not_dirty () {
751     my @cmd = (@git, qw(diff --quiet HEAD));
752     printcmd(\*DEBUG,"+",@cmd) if $debug>0;
753     $!=0; $?=0; system @cmd;
754     return if !$! && !$?;
755     if (!$! && $?==256) {
756         fail "working tree is dirty (does not match HEAD)";
757     } else {
758         failedcmd @cmd;
759     }
760 }
761
762 sub commit_quilty_patch () {
763     my $output = cmdoutput @git, qw(status --porcelain);
764     my %adds;
765     my $bad=0;
766     foreach my $l (split /\n/, $output) {
767         next unless $l =~ m/\S/;
768         if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
769             $adds{$1}++;
770         } else {
771             print STDERR "git status: $l\n";
772             $bad++;
773         }
774     }
775     fail "unexpected output from git status (is tree clean?)" if $bad;
776     if (!%adds) {
777         print "nothing quilty to commit, ok.\n";
778         return;
779     }
780     runcmd_ordryrun @git, qw(add), sort keys %adds;
781     my $m = "Commit Debian 3.0 (quilt) metadata";
782     print "$m\n";
783     runcmd_ordryrun @git, qw(commit -m), $m;
784 }
785
786 sub madformat ($) {
787     my ($format) = @_;
788     return 0 unless $format eq '3.0 (quilt)';
789     print "Format \`$format', urgh\n";
790     return 1;
791 }
792
793 sub dopush () {
794     print DEBUG "actually entering push\n";
795     my $clogp = parsechangelog();
796     $package = getfield $clogp, 'Source';
797     my $cversion = getfield $clogp, 'Version';
798     my $dscfn = dscfn($cversion);
799     stat "../$dscfn" or
800         fail "looked for .dsc $dscfn, but $!;".
801             " maybe you forgot to build";
802     $dsc = parsecontrol("../$dscfn","$dscfn");
803     my $dscpackage = getfield $dsc, 'Source';
804     my $format = getfield $dsc, 'Format';
805     my $dversion = getfield $dsc, 'Version';
806     ($dscpackage eq $package && $dversion eq $cversion) or
807         fail "$dsc is for $dscpackage $dversion".
808             " but debian/changelog is for $package $cversion";
809     print DEBUG "format $format\n";
810     if (madformat($format)) {
811         commit_quilty_patch();
812     }
813     check_not_dirty();
814     prep_ud();
815     chdir $ud or die $!;
816     print "checking that $dscfn corresponds to HEAD\n";
817     runcmd qw(dpkg-source -x --), "../../../../$dscfn";
818     my ($tree,$dir) = mktree_in_ud_from_only_subdir();
819     chdir '../../../..' or die $!;
820     printcmd \*DEBUG,"+",@_;
821     my @diffcmd = (@git, qw(diff --exit-code), $tree);
822     $!=0; $?=0;
823     if (system @diffcmd) {
824         if ($! && $?==256) {
825             fail "$dscfn specifies a different tree to your HEAD commit;".
826                 " perhaps you forgot to build";
827         } else {
828             failedcmd @diffcmd;
829         }
830     }
831 #fetch from alioth
832 #do fast forward check and maybe fake merge
833 #    if (!is_fast_fwd(mainbranch
834 #    runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
835 #        map { lref($_).":".rref($_) }
836 #        (uploadbranch());
837     $dsc->{$ourdscfield[0]} = rev_parse('HEAD');
838     $dsc->save("../$dscfn.tmp") or die $!;
839     if (!$changesfile) {
840         my $multi = "../${package}_${cversion}_multi.changes";
841         if (stat "$multi") {
842             $changesfile = $multi;
843         } else {
844             $!==&ENOENT or die "$multi: $!";
845             my $pat = "${package}_${cversion}_*.changes";
846             my @cs = glob "../$pat";
847             fail "failed to find unique changes file".
848                 " (looked for $pat in .., or $multi);".
849                 " perhaps you need to use dgit -C"
850                 unless @cs==1;
851             ($changesfile) = @cs;
852         }
853     }
854     my $changes = parsecontrol($changesfile,$changesfile);
855     foreach my $field (qw(Source Distribution Version)) {
856         $changes->{$field} eq $clogp->{$field} or
857             fail "changes field $field \`$changes->{$field}'".
858                 " does not match changelog \`$clogp->{$field}'";
859     }
860     my $tag = debiantag($dversion);
861     if (!check_for_git()) {
862         create_remote_git_repo();
863     }
864     runcmd_ordryrun @git, qw(push),access_giturl(),"HEAD:".rrref();
865     if (!$dryrun) {
866         rename "../$dscfn.tmp","../$dscfn" or die "$dscfn $!";
867     } else {
868         print "[new .dsc left in $dscfn.tmp]\n";
869     }
870     if ($sign) {
871         if (!defined $keyid) {
872             $keyid = access_cfg('keyid','RETURN-UNDEF');
873         }
874         my @tag_cmd = (@git, qw(tag -s -m),
875                        "Release $dversion for $csuite [dgit]");
876         push @tag_cmd, qw(-u),$keyid if defined $keyid;
877         push @tag_cmd, $tag;
878         runcmd_ordryrun @tag_cmd;
879         my @debsign_cmd = @debsign;
880         push @debsign_cmd, "-k$keyid" if defined $keyid;
881         push @debsign_cmd, $changesfile;
882         runcmd_ordryrun @debsign_cmd;
883     }
884     runcmd_ordryrun @git, qw(push),access_giturl(),"refs/tags/$tag";
885     my $host = access_cfg('upload-host','RETURN-UNDEF');
886     my @hostarg = defined($host) ? ($host,) : ();
887     runcmd_ordryrun @dput, @hostarg, $changesfile;
888     printdone "pushed and uploaded $dversion";
889 }
890
891 sub cmd_clone {
892     parseopts();
893     my $dstdir;
894     badusage "-p is not allowed with clone; specify as argument instead"
895         if defined $package;
896     if (@ARGV==1) {
897         ($package) = @ARGV;
898     } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
899         ($package,$isuite) = @ARGV;
900     } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
901         ($package,$dstdir) = @ARGV;
902     } elsif (@ARGV==3) {
903         ($package,$isuite,$dstdir) = @ARGV;
904     } else {
905         badusage "incorrect arguments to dgit clone";
906     }
907     $dstdir ||= "$package";
908     clone($dstdir);
909 }
910
911 sub branchsuite () {
912     my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
913     if ($branch =~ m#$lbranch_re#o) {
914         return $1;
915     } else {
916         return undef;
917     }
918 }
919
920 sub fetchpullargs () {
921     if (!defined $package) {
922         my $sourcep = parsecontrol('debian/control','debian/control');
923         $package = getfield $sourcep, 'Source';
924     }
925     if (@ARGV==0) {
926 #       $isuite = branchsuite();  # this doesn't work because dak hates canons
927         if (!$isuite) {
928             my $clogp = parsechangelog();
929             $isuite = getfield $clogp, 'Distribution';
930         }
931         canonicalise_suite();
932         print "fetching from suite $csuite\n";
933     } elsif (@ARGV==1) {
934         ($isuite) = @ARGV;
935         canonicalise_suite();
936     } else {
937         badusage "incorrect arguments to dgit fetch or dgit pull";
938     }
939 }
940
941 sub cmd_fetch {
942     parseopts();
943     fetchpullargs();
944     fetch();
945 }
946
947 sub cmd_pull {
948     parseopts();
949     fetchpullargs();
950     pull();
951 }
952
953 sub cmd_push {
954     parseopts();
955     badusage "-p is not allowed with dgit push" if defined $package;
956     runcmd @git, qw(diff --quiet HEAD);
957     my $clogp = parsechangelog();
958     $package = getfield $clogp, 'Source';
959     if (@ARGV==0) {
960         $isuite = getfield $clogp, 'Distribution';
961         if ($new_package) {
962             local ($package) = $existing_package; # this is a hack
963             canonicalise_suite();
964         }
965     } else {
966         badusage "incorrect arguments to dgit push";
967     }
968     if (check_for_git()) {
969         git_fetch_us();
970     }
971     if (fetch_from_archive()) {
972         is_fast_fwd(lrref(), 'HEAD') or die;
973     } else {
974         $new_package or
975             fail "package appears to be new in this suite;".
976                 " if this is intentional, use --new";
977     }
978     dopush();
979 }
980
981 our $version;
982 our $sourcechanges;
983 our $dscfn;
984
985 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
986
987 sub build_maybe_quilt_fixup () {
988     if (!open F, "debian/source/format") {
989         die $! unless $!==&ENOENT;
990         return;
991     }
992     $_ = <F>;
993     F->error and die $!;
994     chomp;
995     return unless madformat($_);
996     # sigh
997     my $clogp = parsechangelog();
998     my $version = getfield $clogp, 'Version';
999     my $author = getfield $clogp, 'Maintainer';
1000     my $headref = rev_parse('HEAD');
1001     my $time = time;
1002     my $ncommits = 3;
1003     my $patchname = "auto-$version-$headref-$time";
1004     my $msg = cmdoutput @git, qw(log), "-n$ncommits";
1005     my $descfn = ".git/dgit/quilt-description.tmp";
1006     open O, '>', $descfn or die "$descfn: $!";
1007     $msg =~ s/\n/\n /g;
1008     $msg =~ s/^\s+$/ ./mg;
1009     print O <<END or die $!;
1010 Description: Automatically generated patch ($clogp->{Version})
1011  Last (up to) $ncommits git changes, FYI:
1012  .
1013  $msg
1014 Author: $author
1015
1016 ---
1017
1018 END
1019     close O or die $!;
1020     {
1021         local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
1022         local $ENV{'VISUAL'} = $ENV{'EDITOR'};
1023         local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
1024         runcmd_ordryrun @dpkgsource, qw(--commit .), $patchname;
1025     }
1026
1027     if (!open P, '>>', ".pc/applied-patches") {
1028         $!==&ENOENT or die $!;
1029     } else {
1030         close P;
1031     }
1032
1033     commit_quilty_patch();
1034 }
1035
1036 sub quilt_fixup_editor () {
1037     my $descfn = $ENV{$fakeeditorenv};
1038     my $editing = $ARGV[$#ARGV];
1039     open I1, '<', $descfn or die "$descfn: $!";
1040     open I2, '<', $editing or die "$editing: $!";
1041     unlink $editing or die "$editing: $!";
1042     open O, '>', $editing or die "$editing: $!";
1043     while (<I1>) { print O or die $!; } I1->error and die $!;
1044     my $copying = 0;
1045     while (<I2>) {
1046         $copying ||= m/^\-\-\- /;
1047         next unless $copying;
1048         print O or die $!;
1049     }
1050     I2->error and die $!;
1051     close O or die $1;
1052     exit 0;
1053 }
1054
1055 sub cmd_build {
1056     # we pass further options and args to git-buildpackage
1057     badusage "-p is not allowed with dgit build" if defined $package;
1058     badusage "dgit build implies --clean=dpkg-source" if defined $package;
1059     my $clogp = parsechangelog();
1060     $isuite = getfield $clogp, 'Distribution';
1061     $package = getfield $clogp, 'Source';
1062     $version = getfield $clogp, 'Version';
1063     build_maybe_quilt_fixup();
1064     my @cmd =
1065         (qw(git-buildpackage -us -uc --git-no-sign-tags),
1066          "--git-builder=@dpkgbuildpackage");
1067     unless (grep { m/^--git-debian-branch/ } @ARGV) {
1068         canonicalise_suite();
1069         push @cmd, "--git-debian-branch=".lbranch();
1070     }
1071     push @cmd, changesopts();
1072     runcmd_ordryrun @cmd, @ARGV;
1073     printdone "build successful\n";
1074 }
1075
1076 sub build_source {
1077     badusage "-p is not allowed with this action" if defined $package;
1078     check_not_dirty();
1079     my $clogp = parsechangelog();
1080     $package = getfield $clogp, 'Source';
1081     $isuite = getfield $clogp, 'Distribution';
1082     $version = getfield $clogp, 'Version';
1083     $sourcechanges = "${package}_${version}_source.changes";
1084     $dscfn = dscfn($version);
1085     build_maybe_quilt_fixup();
1086     if ($cleanmode eq 'dpkg-source') {
1087         runcmd_ordryrun (@dpkgbuildpackage, qw(-us -uc -S)), changesopts();
1088     } else {
1089         if ($cleanmode eq 'git') {
1090             runcmd_ordryrun @git, qw(clean -xdf);
1091         } elsif ($cleanmode eq 'none') {
1092         } else {
1093             die "$cleanmode ?";
1094         }
1095         my $pwd = cmdoutput qw(env - pwd);
1096         my $leafdir = basename $pwd;
1097         chdir ".." or die $!;
1098         runcmd_ordryrun @dpkgsource, qw(-b --), $leafdir;
1099         chdir $pwd or die $!;
1100         runcmd_ordryrun qw(sh -ec),
1101             'exec >$1; shift; exec "$@"','x',
1102             "../$sourcechanges",
1103             @dpkggenchanges, qw(-S), changesopts();
1104     }
1105 }
1106
1107 sub cmd_build_source {
1108     badusage "build-source takes no additional arguments" if @ARGV;
1109     build_source();
1110     printdone "source built, results in $dscfn and $sourcechanges";
1111 }
1112
1113 sub cmd_sbuild {
1114     build_source();
1115     chdir ".." or die $!;
1116     my $pat = "${package}_${version}_*.changes";
1117     if (!$dryrun) {
1118         stat $dscfn or fail "$dscfn (in parent directory): $!";
1119         stat $sourcechanges or fail "$sourcechanges (in parent directory): $!";
1120         foreach my $cf (glob $pat) {
1121             next if $cf eq $sourcechanges;
1122             unlink $cf or fail "remove $cf: $!";
1123         }
1124     }
1125     runcmd_ordryrun @sbuild, @ARGV, qw(-d), $isuite, $dscfn;
1126     runcmd_ordryrun @mergechanges, glob $pat;
1127     my $multichanges = "${package}_${version}_multi.changes";
1128     if (!$dryrun) {
1129         stat $multichanges or fail "$multichanges: $!";
1130     }
1131     printdone "build successful, results in $multichanges\n" or die $!;
1132 }    
1133
1134 sub cmd_quilt_fixup {
1135     badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
1136     my $clogp = parsechangelog();
1137     $version = getfield $clogp, 'Version';
1138     build_maybe_quilt_fixup();
1139 }
1140
1141 sub parseopts () {
1142     my $om;
1143     while (@ARGV) {
1144         last unless $ARGV[0] =~ m/^-/;
1145         $_ = shift @ARGV;
1146         last if m/^--?$/;
1147         if (m/^--/) {
1148             if (m/^--dry-run$/) {
1149                 $dryrun=1;
1150             } elsif (m/^--no-sign$/) {
1151                 $sign=0;
1152             } elsif (m/^--help$/) {
1153                 helponly();
1154             } elsif (m/^--new$/) {
1155                 $new_package=1;
1156             } elsif (m/^--(\w+)=(.*)/s &&
1157                      ($om = $opts_opt_map{$1}) &&
1158                      length $om->[0]) {
1159                 $om->[0] = $2;
1160             } elsif (m/^--(\w+):(.*)/s &&
1161                      ($om = $opts_opt_map{$1})) {
1162                 push @$om, $2;
1163             } elsif (m/^--existing-package=(.*)/s) {
1164                 $existing_package = $1;
1165             } elsif (m/^--distro=(.*)/s) {
1166                 $idistro = $1;
1167             } elsif (m/^--clean=(dpkg-source|git|none)$/s) {
1168                 $cleanmode = $1;
1169             } elsif (m/^--clean=(.*)$/s) {
1170                 badusage "unknown cleaning mode \`$1'";
1171             } else {
1172                 badusage "unknown long option \`$_'";
1173             }
1174         } else {
1175             while (m/^-./s) {
1176                 if (s/^-n/-/) {
1177                     $dryrun=1;
1178                 } elsif (s/^-h/-/) {
1179                     helponly();
1180                 } elsif (s/^-D/-/) {
1181                     open DEBUG, ">&STDERR" or die $!;
1182                     $debug++;
1183                 } elsif (s/^-N/-/) {
1184                     $new_package=1;
1185                 } elsif (m/^-[vm]/) {
1186                     push @changesopts, $_;
1187                     $_ = '';
1188                 } elsif (s/^-c(.*=.*)//s) {
1189                     push @git, '-c', $1;
1190                 } elsif (s/^-d(.*)//s) {
1191                     $idistro = $1;
1192                 } elsif (s/^-C(.*)//s) {
1193                     $changesfile = $1;
1194                 } elsif (s/^-k(.*)//s) {
1195                     $keyid=$1;
1196                 } elsif (s/^-wn//s) {
1197                     $cleanmode = 'none';
1198                 } elsif (s/^-wg//s) {
1199                     $cleanmode = 'git';
1200                 } elsif (s/^-wd//s) {
1201                     $cleanmode = 'dpkg-source';
1202                 } else {
1203                     badusage "unknown short option \`$_'";
1204                 }
1205             }
1206         }
1207     }
1208 }
1209
1210 if ($ENV{$fakeeditorenv}) {
1211     quilt_fixup_editor();
1212 }
1213
1214 parseopts();
1215 print STDERR "DRY RUN ONLY\n" if $dryrun;
1216 if (!@ARGV) {
1217     print STDERR $helpmsg or die $!;
1218     exit 8;
1219 }
1220 my $cmd = shift @ARGV;
1221 $cmd =~ y/-/_/;
1222 { no strict qw(refs); &{"cmd_$cmd"}(); }