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