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