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