perl: bump the required Perl version to 5.8 from 5.6.[21]
[git/jnareb-git.git] / git-cvsexportcommit.perl
blob9a8188bba785ad68d47ec7b277b016ee76e46f4c
1 #!/usr/bin/perl -w
3 use 5.008;
4 use strict;
5 use Getopt::Std;
6 use File::Temp qw(tempdir);
7 use Data::Dumper;
8 use File::Basename qw(basename dirname);
9 use File::Spec;
10 use Git;
12 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);
14 getopts('uhPpvcfkam:d:w:W');
16 $opt_h && usage();
18 die "Need at least one commit identifier!" unless @ARGV;
20 # Get git-config settings
21 my $repo = Git->repository();
22 $opt_w = $repo->config('cvsexportcommit.cvsdir') unless defined $opt_w;
24 if ($opt_w || $opt_W) {
25 # Remember where GIT_DIR is before changing to CVS checkout
26 unless ($ENV{GIT_DIR}) {
27 # No GIT_DIR set. Figure it out for ourselves
28 my $gd =`git-rev-parse --git-dir`;
29 chomp($gd);
30 $ENV{GIT_DIR} = $gd;
32 # Make sure GIT_DIR is absolute
33 $ENV{GIT_DIR} = File::Spec->rel2abs($ENV{GIT_DIR});
36 if ($opt_w) {
37 if (! -d $opt_w."/CVS" ) {
38 die "$opt_w is not a CVS checkout";
40 chdir $opt_w or die "Cannot change to CVS checkout at $opt_w";
42 unless ($ENV{GIT_DIR} && -r $ENV{GIT_DIR}){
43 die "GIT_DIR is not defined or is unreadable";
47 my @cvs;
48 if ($opt_d) {
49 @cvs = ('cvs', '-d', $opt_d);
50 } else {
51 @cvs = ('cvs');
54 # resolve target commit
55 my $commit;
56 $commit = pop @ARGV;
57 $commit = safe_pipe_capture('git-rev-parse', '--verify', "$commit^0");
58 chomp $commit;
59 if ($?) {
60 die "The commit reference $commit did not resolve!";
63 # resolve what parent we want
64 my $parent;
65 if (@ARGV) {
66 $parent = pop @ARGV;
67 $parent = safe_pipe_capture('git-rev-parse', '--verify', "$parent^0");
68 chomp $parent;
69 if ($?) {
70 die "The parent reference did not resolve!";
74 # find parents from the commit itself
75 my @commit = safe_pipe_capture('git-cat-file', 'commit', $commit);
76 my @parents;
77 my $committer;
78 my $author;
79 my $stage = 'headers'; # headers, msg
80 my $title;
81 my $msg = '';
83 foreach my $line (@commit) {
84 chomp $line;
85 if ($stage eq 'headers' && $line eq '') {
86 $stage = 'msg';
87 next;
90 if ($stage eq 'headers') {
91 if ($line =~ m/^parent (\w{40})$/) { # found a parent
92 push @parents, $1;
93 } elsif ($line =~ m/^author (.+) \d+ [-+]\d+$/) {
94 $author = $1;
95 } elsif ($line =~ m/^committer (.+) \d+ [-+]\d+$/) {
96 $committer = $1;
98 } else {
99 $msg .= $line . "\n";
100 unless ($title) {
101 $title = $line;
106 my $noparent = "0000000000000000000000000000000000000000";
107 if ($parent) {
108 my $found;
109 # double check that it's a valid parent
110 foreach my $p (@parents) {
111 if ($p eq $parent) {
112 $found = 1;
113 last;
114 }; # found it
116 die "Did not find $parent in the parents for this commit!" if !$found and !$opt_P;
117 } else { # we don't have a parent from the cmdline...
118 if (@parents == 1) { # it's safe to get it from the commit
119 $parent = $parents[0];
120 } elsif (@parents == 0) { # there is no parent
121 $parent = $noparent;
122 } else { # cannot choose automatically from multiple parents
123 die "This commit has more than one parent -- please name the parent you want to use explicitly";
127 my $go_back_to = 0;
129 if ($opt_W) {
130 $opt_v && print "Resetting to $parent\n";
131 $go_back_to = `git symbolic-ref HEAD 2> /dev/null ||
132 git rev-parse HEAD` || die "Could not determine current branch";
133 system("git checkout -q $parent^0") && die "Could not check out $parent^0";
136 $opt_v && print "Applying to CVS commit $commit from parent $parent\n";
138 # grab the commit message
139 open(MSG, ">.msg") or die "Cannot open .msg for writing";
140 if ($opt_m) {
141 print MSG $opt_m;
143 print MSG $msg;
144 if ($opt_a) {
145 print MSG "\n\nAuthor: $author\n";
146 if ($author ne $committer) {
147 print MSG "Committer: $committer\n";
150 close MSG;
152 if ($parent eq $noparent) {
153 `git-diff-tree --binary -p --root $commit >.cvsexportcommit.diff`;# || die "Cannot diff";
154 } else {
155 `git-diff-tree --binary -p $parent $commit >.cvsexportcommit.diff`;# || die "Cannot diff";
158 ## apply non-binary changes
160 # In pedantic mode require all lines of context to match. In normal
161 # mode, be compatible with diff/patch: assume 3 lines of context and
162 # require at least one line match, i.e. ignore at most 2 lines of
163 # context, like diff/patch do by default.
164 my $context = $opt_p ? '' : '-C1';
166 print "Checking if patch will apply\n";
168 my @stat;
169 open APPLY, "GIT_DIR= git-apply $context --summary --numstat<.cvsexportcommit.diff|" || die "cannot patch";
170 @stat=<APPLY>;
171 close APPLY || die "Cannot patch";
172 my (@bfiles,@files,@afiles,@dfiles);
173 chomp @stat;
174 foreach (@stat) {
175 push (@bfiles,$1) if m/^-\t-\t(.*)$/;
176 push (@files, $1) if m/^-\t-\t(.*)$/;
177 push (@files, $1) if m/^\d+\t\d+\t(.*)$/;
178 push (@afiles,$1) if m/^ create mode [0-7]+ (.*)$/;
179 push (@dfiles,$1) if m/^ delete mode [0-7]+ (.*)$/;
181 map { s/^"(.*)"$/$1/g } @bfiles,@files;
182 map { s/\\([0-7]{3})/sprintf('%c',oct $1)/eg } @bfiles,@files;
184 # check that the files are clean and up to date according to cvs
185 my $dirty;
186 my @dirs;
187 foreach my $p (@afiles) {
188 my $path = dirname $p;
189 while (!-d $path and ! grep { $_ eq $path } @dirs) {
190 unshift @dirs, $path;
191 $path = dirname $path;
195 # ... check dirs,
196 foreach my $d (@dirs) {
197 if (-e $d) {
198 $dirty = 1;
199 warn "$d exists and is not a directory!\n";
203 # ... query status of all files that we have a directory for and parse output of 'cvs status' to %cvsstat.
204 my @canstatusfiles;
205 foreach my $f (@files) {
206 my $path = dirname $f;
207 next if (grep { $_ eq $path } @dirs);
208 push @canstatusfiles, $f;
211 my %cvsstat;
212 if (@canstatusfiles) {
213 if ($opt_u) {
214 my @updated = xargs_safe_pipe_capture([@cvs, 'update'], @canstatusfiles);
215 print @updated;
217 # "cvs status" reorders the parameters, notably when there are multiple
218 # arguments with the same basename. So be precise here.
220 my %added = map { $_ => 1 } @afiles;
221 my %todo = map { $_ => 1 } @canstatusfiles;
223 while (%todo) {
224 my @canstatusfiles2 = ();
225 my %fullname = ();
226 foreach my $name (keys %todo) {
227 my $basename = basename($name);
229 # CVS reports files that don't exist in the current revision as
230 # "no file $basename" in its "status" output, so we should
231 # anticipate that. Totally unknown files will have a status
232 # "Unknown". However, if they exist in the Attic, their status
233 # will be "Up-to-date" (this means they were added once but have
234 # been removed).
235 $basename = "no file $basename" if $added{$basename};
237 $basename =~ s/^\s+//;
238 $basename =~ s/\s+$//;
240 if (!exists($fullname{$basename})) {
241 $fullname{$basename} = $name;
242 push (@canstatusfiles2, $name);
243 delete($todo{$name});
246 my @cvsoutput;
247 @cvsoutput = xargs_safe_pipe_capture([@cvs, 'status'], @canstatusfiles2);
248 foreach my $l (@cvsoutput) {
249 chomp $l;
250 next unless
251 my ($file, $status) = $l =~ /^File:\s+(.*\S)\s+Status: (.*)$/;
253 my $fullname = $fullname{$file};
254 print STDERR "Huh? Status '$status' reported for unexpected file '$file'\n"
255 unless defined $fullname;
257 # This response means the file does not exist except in
258 # CVS's attic, so set the status accordingly
259 $status = "In-attic"
260 if $file =~ /^no file /
261 && $status eq 'Up-to-date';
263 $cvsstat{$fullname{$file}} = $status
264 if defined $fullname{$file};
269 # ... Validate that new files have the correct status
270 foreach my $f (@afiles) {
271 next unless defined(my $stat = $cvsstat{$f});
273 # This means the file has never been seen before
274 next if $stat eq 'Unknown';
276 # This means the file has been seen before but was removed
277 next if $stat eq 'In-attic';
279 $dirty = 1;
280 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";
281 warn "Status was: $cvsstat{$f}\n";
284 # ... validate known files.
285 foreach my $f (@files) {
286 next if grep { $_ eq $f } @afiles;
287 # TODO:we need to handle removed in cvs
288 unless (defined ($cvsstat{$f}) and $cvsstat{$f} eq "Up-to-date") {
289 $dirty = 1;
290 warn "File $f not up to date but has status '$cvsstat{$f}' in your CVS checkout!\n";
293 # Depending on how your GIT tree got imported from CVS you may
294 # have a conflict between expanded keywords in your CVS tree and
295 # unexpanded keywords in the patch about to be applied.
296 if ($opt_k) {
297 my $orig_file ="$f.orig";
298 rename $f, $orig_file;
299 open(FILTER_IN, "<$orig_file") or die "Cannot open $orig_file\n";
300 open(FILTER_OUT, ">$f") or die "Cannot open $f\n";
301 while (<FILTER_IN>)
303 my $line = $_;
304 $line =~ s/\$([A-Z][a-z]+):[^\$]+\$/\$$1\$/g;
305 print FILTER_OUT $line;
307 close FILTER_IN;
308 close FILTER_OUT;
312 if ($dirty) {
313 if ($opt_f) { warn "The tree is not clean -- forced merge\n";
314 $dirty = 0;
315 } else {
316 die "Exiting: your CVS tree is not clean for this merge.";
320 print "Applying\n";
321 if ($opt_W) {
322 system("git checkout -q $commit^0") && die "cannot patch";
323 } else {
324 `GIT_DIR= git-apply $context --summary --numstat --apply <.cvsexportcommit.diff` || die "cannot patch";
327 print "Patch applied successfully. Adding new files and directories to CVS\n";
328 my $dirtypatch = 0;
331 # We have to add the directories in order otherwise we will have
332 # problems when we try and add the sub-directory of a directory we
333 # have not added yet.
335 # Luckily this is easy to deal with by sorting the directories and
336 # dealing with the shortest ones first.
338 @dirs = sort { length $a <=> length $b} @dirs;
340 foreach my $d (@dirs) {
341 if (system(@cvs,'add',$d)) {
342 $dirtypatch = 1;
343 warn "Failed to cvs add directory $d -- you may need to do it manually";
347 foreach my $f (@afiles) {
348 if (grep { $_ eq $f } @bfiles) {
349 system(@cvs, 'add','-kb',$f);
350 } else {
351 system(@cvs, 'add', $f);
353 if ($?) {
354 $dirtypatch = 1;
355 warn "Failed to cvs add $f -- you may need to do it manually";
359 foreach my $f (@dfiles) {
360 system(@cvs, 'rm', '-f', $f);
361 if ($?) {
362 $dirtypatch = 1;
363 warn "Failed to cvs rm -f $f -- you may need to do it manually";
367 print "Commit to CVS\n";
368 print "Patch title (first comment line): $title\n";
369 my @commitfiles = map { unless (m/\s/) { '\''.$_.'\''; } else { $_; }; } (@files);
370 my $cmd = join(' ', @cvs)." commit -F .msg @commitfiles";
372 if ($dirtypatch) {
373 print "NOTE: One or more hunks failed to apply cleanly.\n";
374 print "You'll need to apply the patch in .cvsexportcommit.diff manually\n";
375 print "using a patch program. After applying the patch and resolving the\n";
376 print "problems you may commit using:";
377 print "\n cd \"$opt_w\"" if $opt_w;
378 print "\n $cmd\n";
379 print "\n git checkout $go_back_to\n" if $go_back_to;
380 print "\n";
381 exit(1);
384 if ($opt_c) {
385 print "Autocommit\n $cmd\n";
386 print xargs_safe_pipe_capture([@cvs, 'commit', '-F', '.msg'], @files);
387 if ($?) {
388 die "Exiting: The commit did not succeed";
390 print "Committed successfully to CVS\n";
391 # clean up
392 unlink(".msg");
393 } else {
394 print "Ready for you to commit, just run:\n\n $cmd\n";
397 # clean up
398 unlink(".cvsexportcommit.diff");
400 if ($opt_W) {
401 system("git checkout $go_back_to") && die "cannot move back to $go_back_to";
402 if (!($go_back_to =~ /^[0-9a-fA-F]{40}$/)) {
403 system("git symbolic-ref HEAD $go_back_to") &&
404 die "cannot move back to $go_back_to";
408 # CVS version 1.11.x and 1.12.x sleeps the wrong way to ensure the timestamp
409 # used by CVS and the one set by subsequence file modifications are different.
410 # If they are not different CVS will not detect changes.
411 sleep(1);
413 sub usage {
414 print STDERR <<END;
415 Usage: GIT_DIR=/path/to/.git git cvsexportcommit [-h] [-p] [-v] [-c] [-f] [-u] [-k] [-w cvsworkdir] [-m msgprefix] [ parent ] commit
417 exit(1);
420 # An alternative to `command` that allows input to be passed as an array
421 # to work around shell problems with weird characters in arguments
422 # if the exec returns non-zero we die
423 sub safe_pipe_capture {
424 my @output;
425 if (my $pid = open my $child, '-|') {
426 @output = (<$child>);
427 close $child or die join(' ',@_).": $! $?";
428 } else {
429 exec(@_) or die "$! $?"; # exec() can fail the executable can't be found
431 return wantarray ? @output : join('',@output);
434 sub xargs_safe_pipe_capture {
435 my $MAX_ARG_LENGTH = 65536;
436 my $cmd = shift;
437 my @output;
438 my $output;
439 while(@_) {
440 my @args;
441 my $length = 0;
442 while(@_ && $length < $MAX_ARG_LENGTH) {
443 push @args, shift;
444 $length += length($args[$#args]);
446 if (wantarray) {
447 push @output, safe_pipe_capture(@$cmd, @args);
449 else {
450 $output .= safe_pipe_capture(@$cmd, @args);
453 return wantarray ? @output : $output;