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