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