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