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