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