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