fast-import: fix option parser for no-arg options
[git/dscho.git] / git-cvsexportcommit.perl
blob39a426e067c76e01d3f2a0d63243ec494436da46
1 #!/usr/bin/perl
3 use 5.008;
4 use strict;
5 use warnings;
6 use Getopt::Std;
7 use File::Temp qw(tempdir);
8 use Data::Dumper;
9 use File::Basename qw(basename dirname);
10 use File::Spec;
11 use Git;
13 our ($opt_h, $opt_P, $opt_p, $opt_v, $opt_c, $opt_f, $opt_a, $opt_m, $opt_d, $opt_u, $opt_w, $opt_W, $opt_k);
15 getopts('uhPpvcfkam:d:w:W');
17 $opt_h && usage();
19 die "Need at least one commit identifier!" unless @ARGV;
21 # Get git-config settings
22 my $repo = Git->repository();
23 $opt_w = $repo->config('cvsexportcommit.cvsdir') unless defined $opt_w;
25 if ($opt_w || $opt_W) {
26 # Remember where GIT_DIR is before changing to CVS checkout
27 unless ($ENV{GIT_DIR}) {
28 # No GIT_DIR set. Figure it out for ourselves
29 my $gd =`git-rev-parse --git-dir`;
30 chomp($gd);
31 $ENV{GIT_DIR} = $gd;
33 # Make sure GIT_DIR is absolute
34 $ENV{GIT_DIR} = File::Spec->rel2abs($ENV{GIT_DIR});
37 if ($opt_w) {
38 if (! -d $opt_w."/CVS" ) {
39 die "$opt_w is not a CVS checkout";
41 chdir $opt_w or die "Cannot change to CVS checkout at $opt_w";
43 unless ($ENV{GIT_DIR} && -r $ENV{GIT_DIR}){
44 die "GIT_DIR is not defined or is unreadable";
48 my @cvs;
49 if ($opt_d) {
50 @cvs = ('cvs', '-d', $opt_d);
51 } else {
52 @cvs = ('cvs');
55 # resolve target commit
56 my $commit;
57 $commit = pop @ARGV;
58 $commit = safe_pipe_capture('git-rev-parse', '--verify', "$commit^0");
59 chomp $commit;
60 if ($?) {
61 die "The commit reference $commit did not resolve!";
64 # resolve what parent we want
65 my $parent;
66 if (@ARGV) {
67 $parent = pop @ARGV;
68 $parent = safe_pipe_capture('git-rev-parse', '--verify', "$parent^0");
69 chomp $parent;
70 if ($?) {
71 die "The parent reference did not resolve!";
75 # find parents from the commit itself
76 my @commit = safe_pipe_capture('git-cat-file', 'commit', $commit);
77 my @parents;
78 my $committer;
79 my $author;
80 my $stage = 'headers'; # headers, msg
81 my $title;
82 my $msg = '';
84 foreach my $line (@commit) {
85 chomp $line;
86 if ($stage eq 'headers' && $line eq '') {
87 $stage = 'msg';
88 next;
91 if ($stage eq 'headers') {
92 if ($line =~ m/^parent (\w{40})$/) { # found a parent
93 push @parents, $1;
94 } elsif ($line =~ m/^author (.+) \d+ [-+]\d+$/) {
95 $author = $1;
96 } elsif ($line =~ m/^committer (.+) \d+ [-+]\d+$/) {
97 $committer = $1;
99 } else {
100 $msg .= $line . "\n";
101 unless ($title) {
102 $title = $line;
107 my $noparent = "0000000000000000000000000000000000000000";
108 if ($parent) {
109 my $found;
110 # double check that it's a valid parent
111 foreach my $p (@parents) {
112 if ($p eq $parent) {
113 $found = 1;
114 last;
115 }; # found it
117 die "Did not find $parent in the parents for this commit!" if !$found and !$opt_P;
118 } else { # we don't have a parent from the cmdline...
119 if (@parents == 1) { # it's safe to get it from the commit
120 $parent = $parents[0];
121 } elsif (@parents == 0) { # there is no parent
122 $parent = $noparent;
123 } else { # cannot choose automatically from multiple parents
124 die "This commit has more than one parent -- please name the parent you want to use explicitly";
128 my $go_back_to = 0;
130 if ($opt_W) {
131 $opt_v && print "Resetting to $parent\n";
132 $go_back_to = `git symbolic-ref HEAD 2> /dev/null ||
133 git rev-parse HEAD` || die "Could not determine current branch";
134 system("git checkout -q $parent^0") && die "Could not check out $parent^0";
137 $opt_v && print "Applying to CVS commit $commit from parent $parent\n";
139 # grab the commit message
140 open(MSG, ">.msg") or die "Cannot open .msg for writing";
141 if ($opt_m) {
142 print MSG $opt_m;
144 print MSG $msg;
145 if ($opt_a) {
146 print MSG "\n\nAuthor: $author\n";
147 if ($author ne $committer) {
148 print MSG "Committer: $committer\n";
151 close MSG;
153 if ($parent eq $noparent) {
154 `git-diff-tree --binary -p --root $commit >.cvsexportcommit.diff`;# || die "Cannot diff";
155 } else {
156 `git-diff-tree --binary -p $parent $commit >.cvsexportcommit.diff`;# || die "Cannot diff";
159 ## apply non-binary changes
161 # In pedantic mode require all lines of context to match. In normal
162 # mode, be compatible with diff/patch: assume 3 lines of context and
163 # require at least one line match, i.e. ignore at most 2 lines of
164 # context, like diff/patch do by default.
165 my $context = $opt_p ? '' : '-C1';
167 print "Checking if patch will apply\n";
169 my @stat;
170 open APPLY, "GIT_DIR= git-apply $context --summary --numstat<.cvsexportcommit.diff|" || die "cannot patch";
171 @stat=<APPLY>;
172 close APPLY || die "Cannot patch";
173 my (@bfiles,@files,@afiles,@dfiles);
174 chomp @stat;
175 foreach (@stat) {
176 push (@bfiles,$1) if m/^-\t-\t(.*)$/;
177 push (@files, $1) if m/^-\t-\t(.*)$/;
178 push (@files, $1) if m/^\d+\t\d+\t(.*)$/;
179 push (@afiles,$1) if m/^ create mode [0-7]+ (.*)$/;
180 push (@dfiles,$1) if m/^ delete mode [0-7]+ (.*)$/;
182 map { s/^"(.*)"$/$1/g } @bfiles,@files;
183 map { s/\\([0-7]{3})/sprintf('%c',oct $1)/eg } @bfiles,@files;
185 # check that the files are clean and up to date according to cvs
186 my $dirty;
187 my @dirs;
188 foreach my $p (@afiles) {
189 my $path = dirname $p;
190 while (!-d $path and ! grep { $_ eq $path } @dirs) {
191 unshift @dirs, $path;
192 $path = dirname $path;
196 # ... check dirs,
197 foreach my $d (@dirs) {
198 if (-e $d) {
199 $dirty = 1;
200 warn "$d exists and is not a directory!\n";
204 # ... query status of all files that we have a directory for and parse output of 'cvs status' to %cvsstat.
205 my @canstatusfiles;
206 foreach my $f (@files) {
207 my $path = dirname $f;
208 next if (grep { $_ eq $path } @dirs);
209 push @canstatusfiles, $f;
212 my %cvsstat;
213 if (@canstatusfiles) {
214 if ($opt_u) {
215 my @updated = xargs_safe_pipe_capture([@cvs, 'update'], @canstatusfiles);
216 print @updated;
218 # "cvs status" reorders the parameters, notably when there are multiple
219 # arguments with the same basename. So be precise here.
221 my %added = map { $_ => 1 } @afiles;
222 my %todo = map { $_ => 1 } @canstatusfiles;
224 while (%todo) {
225 my @canstatusfiles2 = ();
226 my %fullname = ();
227 foreach my $name (keys %todo) {
228 my $basename = basename($name);
230 # CVS reports files that don't exist in the current revision as
231 # "no file $basename" in its "status" output, so we should
232 # anticipate that. Totally unknown files will have a status
233 # "Unknown". However, if they exist in the Attic, their status
234 # will be "Up-to-date" (this means they were added once but have
235 # been removed).
236 $basename = "no file $basename" if $added{$basename};
238 $basename =~ s/^\s+//;
239 $basename =~ s/\s+$//;
241 if (!exists($fullname{$basename})) {
242 $fullname{$basename} = $name;
243 push (@canstatusfiles2, $name);
244 delete($todo{$name});
247 my @cvsoutput;
248 @cvsoutput = xargs_safe_pipe_capture([@cvs, 'status'], @canstatusfiles2);
249 foreach my $l (@cvsoutput) {
250 chomp $l;
251 next unless
252 my ($file, $status) = $l =~ /^File:\s+(.*\S)\s+Status: (.*)$/;
254 my $fullname = $fullname{$file};
255 print STDERR "Huh? Status '$status' reported for unexpected file '$file'\n"
256 unless defined $fullname;
258 # This response means the file does not exist except in
259 # CVS's attic, so set the status accordingly
260 $status = "In-attic"
261 if $file =~ /^no file /
262 && $status eq 'Up-to-date';
264 $cvsstat{$fullname{$file}} = $status
265 if defined $fullname{$file};
270 # ... Validate that new files have the correct status
271 foreach my $f (@afiles) {
272 next unless defined(my $stat = $cvsstat{$f});
274 # This means the file has never been seen before
275 next if $stat eq 'Unknown';
277 # This means the file has been seen before but was removed
278 next if $stat eq 'In-attic';
280 $dirty = 1;
281 warn "File $f is already known in your CVS checkout -- perhaps it has been added by another user. Or this may indicate that it exists on a different branch. If this is the case, use -f to force the merge.\n";
282 warn "Status was: $cvsstat{$f}\n";
285 # ... validate known files.
286 foreach my $f (@files) {
287 next if grep { $_ eq $f } @afiles;
288 # TODO:we need to handle removed in cvs
289 unless (defined ($cvsstat{$f}) and $cvsstat{$f} eq "Up-to-date") {
290 $dirty = 1;
291 warn "File $f not up to date but has status '$cvsstat{$f}' in your CVS checkout!\n";
294 # Depending on how your GIT tree got imported from CVS you may
295 # have a conflict between expanded keywords in your CVS tree and
296 # unexpanded keywords in the patch about to be applied.
297 if ($opt_k) {
298 my $orig_file ="$f.orig";
299 rename $f, $orig_file;
300 open(FILTER_IN, "<$orig_file") or die "Cannot open $orig_file\n";
301 open(FILTER_OUT, ">$f") or die "Cannot open $f\n";
302 while (<FILTER_IN>)
304 my $line = $_;
305 $line =~ s/\$([A-Z][a-z]+):[^\$]+\$/\$$1\$/g;
306 print FILTER_OUT $line;
308 close FILTER_IN;
309 close FILTER_OUT;
313 if ($dirty) {
314 if ($opt_f) { warn "The tree is not clean -- forced merge\n";
315 $dirty = 0;
316 } else {
317 die "Exiting: your CVS tree is not clean for this merge.";
321 print "Applying\n";
322 if ($opt_W) {
323 system("git checkout -q $commit^0") && die "cannot patch";
324 } else {
325 `GIT_DIR= git-apply $context --summary --numstat --apply <.cvsexportcommit.diff` || die "cannot patch";
328 print "Patch applied successfully. Adding new files and directories to CVS\n";
329 my $dirtypatch = 0;
332 # We have to add the directories in order otherwise we will have
333 # problems when we try and add the sub-directory of a directory we
334 # have not added yet.
336 # Luckily this is easy to deal with by sorting the directories and
337 # dealing with the shortest ones first.
339 @dirs = sort { length $a <=> length $b} @dirs;
341 foreach my $d (@dirs) {
342 if (system(@cvs,'add',$d)) {
343 $dirtypatch = 1;
344 warn "Failed to cvs add directory $d -- you may need to do it manually";
348 foreach my $f (@afiles) {
349 if (grep { $_ eq $f } @bfiles) {
350 system(@cvs, 'add','-kb',$f);
351 } else {
352 system(@cvs, 'add', $f);
354 if ($?) {
355 $dirtypatch = 1;
356 warn "Failed to cvs add $f -- you may need to do it manually";
360 foreach my $f (@dfiles) {
361 system(@cvs, 'rm', '-f', $f);
362 if ($?) {
363 $dirtypatch = 1;
364 warn "Failed to cvs rm -f $f -- you may need to do it manually";
368 print "Commit to CVS\n";
369 print "Patch title (first comment line): $title\n";
370 my @commitfiles = map { unless (m/\s/) { '\''.$_.'\''; } else { $_; }; } (@files);
371 my $cmd = join(' ', @cvs)." commit -F .msg @commitfiles";
373 if ($dirtypatch) {
374 print "NOTE: One or more hunks failed to apply cleanly.\n";
375 print "You'll need to apply the patch in .cvsexportcommit.diff manually\n";
376 print "using a patch program. After applying the patch and resolving the\n";
377 print "problems you may commit using:";
378 print "\n cd \"$opt_w\"" if $opt_w;
379 print "\n $cmd\n";
380 print "\n git checkout $go_back_to\n" if $go_back_to;
381 print "\n";
382 exit(1);
385 if ($opt_c) {
386 print "Autocommit\n $cmd\n";
387 print xargs_safe_pipe_capture([@cvs, 'commit', '-F', '.msg'], @files);
388 if ($?) {
389 die "Exiting: The commit did not succeed";
391 print "Committed successfully to CVS\n";
392 # clean up
393 unlink(".msg");
394 } else {
395 print "Ready for you to commit, just run:\n\n $cmd\n";
398 # clean up
399 unlink(".cvsexportcommit.diff");
401 if ($opt_W) {
402 system("git checkout $go_back_to") && die "cannot move back to $go_back_to";
403 if (!($go_back_to =~ /^[0-9a-fA-F]{40}$/)) {
404 system("git symbolic-ref HEAD $go_back_to") &&
405 die "cannot move back to $go_back_to";
409 # CVS version 1.11.x and 1.12.x sleeps the wrong way to ensure the timestamp
410 # used by CVS and the one set by subsequence file modifications are different.
411 # If they are not different CVS will not detect changes.
412 sleep(1);
414 sub usage {
415 print STDERR <<END;
416 Usage: GIT_DIR=/path/to/.git git cvsexportcommit [-h] [-p] [-v] [-c] [-f] [-u] [-k] [-w cvsworkdir] [-m msgprefix] [ parent ] commit
418 exit(1);
421 # An alternative to `command` that allows input to be passed as an array
422 # to work around shell problems with weird characters in arguments
423 # if the exec returns non-zero we die
424 sub safe_pipe_capture {
425 my @output;
426 if (my $pid = open my $child, '-|') {
427 @output = (<$child>);
428 close $child or die join(' ',@_).": $! $?";
429 } else {
430 exec(@_) or die "$! $?"; # exec() can fail the executable can't be found
432 return wantarray ? @output : join('',@output);
435 sub xargs_safe_pipe_capture {
436 my $MAX_ARG_LENGTH = 65536;
437 my $cmd = shift;
438 my @output;
439 my $output;
440 while(@_) {
441 my @args;
442 my $length = 0;
443 while(@_ && $length < $MAX_ARG_LENGTH) {
444 push @args, shift;
445 $length += length($args[$#args]);
447 if (wantarray) {
448 push @output, safe_pipe_capture(@$cmd, @args);
450 else {
451 $output .= safe_pipe_capture(@$cmd, @args);
454 return wantarray ? @output : $output;