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