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