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