cvsexportcommit: introduce -W for shared working trees (between Git and CVS)
[git.git] / git-cvsexportcommit.perl
1 #!/usr/bin/perl -w
2
3 use strict;
4 use Getopt::Std;
5 use File::Temp qw(tempdir);
6 use Data::Dumper;
7 use File::Basename qw(basename dirname);
8 use File::Spec;
9
10 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);
11
12 getopts('uhPpvcfam:d:w:W');
13
14 $opt_h && usage();
15
16 die "Need at least one commit identifier!" unless @ARGV;
17
18 if ($opt_w || $opt_W) {
19         # Remember where GIT_DIR is before changing to CVS checkout
20         unless ($ENV{GIT_DIR}) {
21                 # No GIT_DIR set. Figure it out for ourselves
22                 my $gd =`git-rev-parse --git-dir`;
23                 chomp($gd);
24                 $ENV{GIT_DIR} = $gd;
25         }
26         # Make sure GIT_DIR is absolute
27         $ENV{GIT_DIR} = File::Spec->rel2abs($ENV{GIT_DIR});
28 }
29
30 if ($opt_w) {
31         if (! -d $opt_w."/CVS" ) {
32                 die "$opt_w is not a CVS checkout";
33         }
34         chdir $opt_w or die "Cannot change to CVS checkout at $opt_w";
35 }
36 unless ($ENV{GIT_DIR} && -r $ENV{GIT_DIR}){
37     die "GIT_DIR is not defined or is unreadable";
38 }
39
40
41 my @cvs;
42 if ($opt_d) {
43         @cvs = ('cvs', '-d', $opt_d);
44 } else {
45         @cvs = ('cvs');
46 }
47
48 # resolve target commit
49 my $commit;
50 $commit = pop @ARGV;
51 $commit = safe_pipe_capture('git-rev-parse', '--verify', "$commit^0");
52 chomp $commit;
53 if ($?) {
54     die "The commit reference $commit did not resolve!";
55 }
56
57 # resolve what parent we want
58 my $parent;
59 if (@ARGV) {
60     $parent = pop @ARGV;
61     $parent =  safe_pipe_capture('git-rev-parse', '--verify', "$parent^0");
62     chomp $parent;
63     if ($?) {
64         die "The parent reference did not resolve!";
65     }
66 }
67
68 # find parents from the commit itself
69 my @commit  = safe_pipe_capture('git-cat-file', 'commit', $commit);
70 my @parents;
71 my $committer;
72 my $author;
73 my $stage = 'headers'; # headers, msg
74 my $title;
75 my $msg = '';
76
77 foreach my $line (@commit) {
78     chomp $line;
79     if ($stage eq 'headers' && $line eq '') {
80         $stage = 'msg';
81         next;
82     }
83
84     if ($stage eq 'headers') {
85         if ($line =~ m/^parent (\w{40})$/) { # found a parent
86             push @parents, $1;
87         } elsif ($line =~ m/^author (.+) \d+ [-+]\d+$/) {
88             $author = $1;
89         } elsif ($line =~ m/^committer (.+) \d+ [-+]\d+$/) {
90             $committer = $1;
91         }
92     } else {
93         $msg .= $line . "\n";
94         unless ($title) {
95             $title = $line;
96         }
97     }
98 }
99
100 my $noparent = "0000000000000000000000000000000000000000";
101 if ($parent) {
102     my $found;
103     # double check that it's a valid parent
104     foreach my $p (@parents) {
105         if ($p eq $parent) {
106             $found = 1;
107             last;
108         }; # found it
109     }
110     die "Did not find $parent in the parents for this commit!" if !$found and !$opt_P;
111 } else { # we don't have a parent from the cmdline...
112     if (@parents == 1) { # it's safe to get it from the commit
113         $parent = $parents[0];
114     } elsif (@parents == 0) { # there is no parent
115         $parent = $noparent;
116     } else { # cannot choose automatically from multiple parents
117         die "This commit has more than one parent -- please name the parent you want to use explicitly";
118     }
119 }
120
121 my $go_back_to = 0;
122
123 if ($opt_W) {
124     $opt_v && print "Resetting to $parent\n";
125     $go_back_to = `git symbolic-ref HEAD 2> /dev/null ||
126         git rev-parse HEAD` || die "Could not determine current branch";
127     system("git checkout -q $parent^0") && die "Could not check out $parent^0";
128 }
129
130 $opt_v && print "Applying to CVS commit $commit from parent $parent\n";
131
132 # grab the commit message
133 open(MSG, ">.msg") or die "Cannot open .msg for writing";
134 if ($opt_m) {
135     print MSG $opt_m;
136 }
137 print MSG $msg;
138 if ($opt_a) {
139     print MSG "\n\nAuthor: $author\n";
140     if ($author ne $committer) {
141         print MSG "Committer: $committer\n";
142     }
143 }
144 close MSG;
145
146 if ($parent eq $noparent) {
147     `git-diff-tree --binary -p --root $commit >.cvsexportcommit.diff`;# || die "Cannot diff";
148 } else {
149     `git-diff-tree --binary -p $parent $commit >.cvsexportcommit.diff`;# || die "Cannot diff";
150 }
151
152 ## apply non-binary changes
153
154 # In pedantic mode require all lines of context to match.  In normal
155 # mode, be compatible with diff/patch: assume 3 lines of context and
156 # require at least one line match, i.e. ignore at most 2 lines of
157 # context, like diff/patch do by default.
158 my $context = $opt_p ? '' : '-C1';
159
160 print "Checking if patch will apply\n";
161
162 my @stat;
163 open APPLY, "GIT_DIR= git-apply $context --summary --numstat<.cvsexportcommit.diff|" || die "cannot patch";
164 @stat=<APPLY>;
165 close APPLY || die "Cannot patch";
166 my (@bfiles,@files,@afiles,@dfiles);
167 chomp @stat;
168 foreach (@stat) {
169         push (@bfiles,$1) if m/^-\t-\t(.*)$/;
170         push (@files, $1) if m/^-\t-\t(.*)$/;
171         push (@files, $1) if m/^\d+\t\d+\t(.*)$/;
172         push (@afiles,$1) if m/^ create mode [0-7]+ (.*)$/;
173         push (@dfiles,$1) if m/^ delete mode [0-7]+ (.*)$/;
174 }
175 map { s/^"(.*)"$/$1/g } @bfiles,@files;
176 map { s/\\([0-7]{3})/sprintf('%c',oct $1)/eg } @bfiles,@files;
177
178 # check that the files are clean and up to date according to cvs
179 my $dirty;
180 my @dirs;
181 foreach my $p (@afiles) {
182     my $path = dirname $p;
183     while (!-d $path and ! grep { $_ eq $path } @dirs) {
184         unshift @dirs, $path;
185         $path = dirname $path;
186     }
187 }
188
189 # ... check dirs,
190 foreach my $d (@dirs) {
191     if (-e $d) {
192         $dirty = 1;
193         warn "$d exists and is not a directory!\n";
194     }
195 }
196
197 # ... query status of all files that we have a directory for and parse output of 'cvs status' to %cvsstat.
198 my @canstatusfiles;
199 foreach my $f (@files) {
200     my $path = dirname $f;
201     next if (grep { $_ eq $path } @dirs);
202     push @canstatusfiles, $f;
203 }
204
205 my %cvsstat;
206 if (@canstatusfiles) {
207     if ($opt_u) {
208       my @updated = xargs_safe_pipe_capture([@cvs, 'update'], @canstatusfiles);
209       print @updated;
210     }
211     # "cvs status" reorders the parameters, notably when there are multiple
212     # arguments with the same basename.  So be precise here.
213
214     my %added = map { $_ => 1 } @afiles;
215     my %todo = map { $_ => 1 } @canstatusfiles;
216
217     while (%todo) {
218       my @canstatusfiles2 = ();
219       my %fullname = ();
220       foreach my $name (keys %todo) {
221         my $basename = basename($name);
222
223         $basename = "no file " . $basename if (exists($added{$basename}));
224         $basename =~ s/^\s+//;
225         $basename =~ s/\s+$//;
226
227         if (!exists($fullname{$basename})) {
228           $fullname{$basename} = $name;
229           push (@canstatusfiles2, $name);
230           delete($todo{$name});
231         }
232       }
233       my @cvsoutput;
234       @cvsoutput = xargs_safe_pipe_capture([@cvs, 'status'], @canstatusfiles2);
235       foreach my $l (@cvsoutput) {
236         chomp $l;
237         if ($l =~ /^File:\s+(.*\S)\s+Status: (.*)$/) {
238           if (!exists($fullname{$1})) {
239             print STDERR "Huh? Status reported for unexpected file '$1'\n";
240           } else {
241             $cvsstat{$fullname{$1}} = $2;
242           }
243         }
244       }
245     }
246 }
247
248 # ... validate new files,
249 foreach my $f (@afiles) {
250     if (defined ($cvsstat{$f}) and $cvsstat{$f} ne "Unknown") {
251         $dirty = 1;
252         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";
253         warn "Status was: $cvsstat{$f}\n";
254     }
255 }
256 # ... validate known files.
257 foreach my $f (@files) {
258     next if grep { $_ eq $f } @afiles;
259     # TODO:we need to handle removed in cvs
260     unless (defined ($cvsstat{$f}) and $cvsstat{$f} eq "Up-to-date") {
261         $dirty = 1;
262         warn "File $f not up to date but has status '$cvsstat{$f}' in your CVS checkout!\n";
263     }
264 }
265 if ($dirty) {
266     if ($opt_f) {       warn "The tree is not clean -- forced merge\n";
267         $dirty = 0;
268     } else {
269         die "Exiting: your CVS tree is not clean for this merge.";
270     }
271 }
272
273 print "Applying\n";
274 if ($opt_W) {
275     system("git checkout -q $commit^0") && die "cannot patch";
276 } else {
277     `GIT_DIR= git-apply $context --summary --numstat --apply <.cvsexportcommit.diff` || die "cannot patch";
278 }
279
280 print "Patch applied successfully. Adding new files and directories to CVS\n";
281 my $dirtypatch = 0;
282
283 #
284 # We have to add the directories in order otherwise we will have
285 # problems when we try and add the sub-directory of a directory we
286 # have not added yet.
287 #
288 # Luckily this is easy to deal with by sorting the directories and
289 # dealing with the shortest ones first.
290 #
291 @dirs = sort { length $a <=> length $b} @dirs;
292
293 foreach my $d (@dirs) {
294     if (system(@cvs,'add',$d)) {
295         $dirtypatch = 1;
296         warn "Failed to cvs add directory $d -- you may need to do it manually";
297     }
298 }
299
300 foreach my $f (@afiles) {
301     if (grep { $_ eq $f } @bfiles) {
302       system(@cvs, 'add','-kb',$f);
303     } else {
304       system(@cvs, 'add', $f);
305     }
306     if ($?) {
307         $dirtypatch = 1;
308         warn "Failed to cvs add $f -- you may need to do it manually";
309     }
310 }
311
312 foreach my $f (@dfiles) {
313     system(@cvs, 'rm', '-f', $f);
314     if ($?) {
315         $dirtypatch = 1;
316         warn "Failed to cvs rm -f $f -- you may need to do it manually";
317     }
318 }
319
320 print "Commit to CVS\n";
321 print "Patch title (first comment line): $title\n";
322 my @commitfiles = map { unless (m/\s/) { '\''.$_.'\''; } else { $_; }; } (@files);
323 my $cmd = join(' ', @cvs)." commit -F .msg @commitfiles";
324
325 if ($dirtypatch) {
326     print "NOTE: One or more hunks failed to apply cleanly.\n";
327     print "You'll need to apply the patch in .cvsexportcommit.diff manually\n";
328     print "using a patch program. After applying the patch and resolving the\n";
329     print "problems you may commit using:";
330     print "\n    cd \"$opt_w\"" if $opt_w;
331     print "\n    $cmd\n";
332     print "\n    git checkout $go_back_to\n" if $go_back_to;
333     print "\n";
334     exit(1);
335 }
336
337 if ($opt_c) {
338     print "Autocommit\n  $cmd\n";
339     print xargs_safe_pipe_capture([@cvs, 'commit', '-F', '.msg'], @files);
340     if ($?) {
341         die "Exiting: The commit did not succeed";
342     }
343     print "Committed successfully to CVS\n";
344     # clean up
345     unlink(".msg");
346 } else {
347     print "Ready for you to commit, just run:\n\n   $cmd\n";
348 }
349
350 # clean up
351 unlink(".cvsexportcommit.diff");
352
353 if ($opt_W) {
354     system("git checkout $go_back_to") && die "cannot move back to $go_back_to";
355     if (!($go_back_to =~ /^[0-9a-fA-F]{40}$/)) {
356         system("git symbolic-ref HEAD $go_back_to") &&
357             die "cannot move back to $go_back_to";
358     }
359 }
360
361 # CVS version 1.11.x and 1.12.x sleeps the wrong way to ensure the timestamp
362 # used by CVS and the one set by subsequence file modifications are different.
363 # If they are not different CVS will not detect changes.
364 sleep(1);
365
366 sub usage {
367         print STDERR <<END;
368 Usage: GIT_DIR=/path/to/.git ${\basename $0} [-h] [-p] [-v] [-c] [-f] [-u] [-w cvsworkdir] [-m msgprefix] [ parent ] commit
369 END
370         exit(1);
371 }
372
373 # An alternative to `command` that allows input to be passed as an array
374 # to work around shell problems with weird characters in arguments
375 # if the exec returns non-zero we die
376 sub safe_pipe_capture {
377     my @output;
378     if (my $pid = open my $child, '-|') {
379         @output = (<$child>);
380         close $child or die join(' ',@_).": $! $?";
381     } else {
382         exec(@_) or die "$! $?"; # exec() can fail the executable can't be found
383     }
384     return wantarray ? @output : join('',@output);
385 }
386
387 sub xargs_safe_pipe_capture {
388         my $MAX_ARG_LENGTH = 65536;
389         my $cmd = shift;
390         my @output;
391         my $output;
392         while(@_) {
393                 my @args;
394                 my $length = 0;
395                 while(@_ && $length < $MAX_ARG_LENGTH) {
396                         push @args, shift;
397                         $length += length($args[$#args]);
398                 }
399                 if (wantarray) {
400                         push @output, safe_pipe_capture(@$cmd, @args);
401                 }
402                 else {
403                         $output .= safe_pipe_capture(@$cmd, @args);
404                 }
405         }
406         return wantarray ? @output : $output;
407 }