]> git.ipfire.org Git - thirdparty/git.git/blame - contrib/git-svn/git-svn.perl
git-svn: add the commit-diff command
[thirdparty/git.git] / contrib / git-svn / git-svn.perl
CommitLineData
3397f9df 1#!/usr/bin/env perl
551ce28f
EW
2# Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3# License: GPL v2 or later
3397f9df
EW
4use warnings;
5use strict;
6use vars qw/ $AUTHOR $VERSION
1ca72aef 7 $SVN_URL $SVN_INFO $SVN_WC $SVN_UUID
3397f9df 8 $GIT_SVN_INDEX $GIT_SVN
42d32870 9 $GIT_DIR $GIT_SVN_DIR $REVDB/;
3397f9df 10$AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
42d32870 11$VERSION = '1.1.1-broken';
13ccd6d4
EW
12
13use Cwd qw/abs_path/;
14$GIT_DIR = abs_path($ENV{GIT_DIR} || '.git');
15$ENV{GIT_DIR} = $GIT_DIR;
16
ce475dfc 17my $LC_ALL = $ENV{LC_ALL};
79bb8d88 18my $TZ = $ENV{TZ};
3397f9df
EW
19# make sure the svn binary gives consistent output between locales and TZs:
20$ENV{TZ} = 'UTC';
21$ENV{LC_ALL} = 'C';
22
23# If SVN:: library support is added, please make the dependencies
24# optional and preserve the capability to use the command-line client.
ce6f3519 25# use eval { require SVN::... } to make it lazy load
eeb0abe0 26# We don't use any modules not in the standard Perl distribution:
3397f9df
EW
27use Carp qw/croak/;
28use IO::File qw//;
29use File::Basename qw/dirname basename/;
30use File::Path qw/mkpath/;
79bb8d88 31use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev pass_through/;
3397f9df 32use File::Spec qw//;
e17512f3 33use POSIX qw/strftime/;
968bdf1f 34use IPC::Open3;
42d32870
EW
35use Memoize;
36memoize('revisions_eq');
c1927a85
EW
37memoize('cmt_metadata');
38memoize('get_commit_time');
a5e0cedc
EW
39
40my ($SVN_PATH, $SVN, $SVN_LOG, $_use_lib);
41$_use_lib = 1 unless $ENV{GIT_SVN_NO_LIB};
42libsvn_load();
42d32870 43my $_optimize_commits = 1 unless $ENV{GIT_SVN_NO_OPTIMIZE_COMMITS};
3397f9df 44my $sha1 = qr/[a-f\d]{40}/;
ac8e0b91 45my $sha1_short = qr/[a-f\d]{4,40}/;
72942938 46my ($_revision,$_stdin,$_no_ignore_ext,$_no_stop_copy,$_help,$_rmdir,$_edit,
1a82e793 47 $_find_copies_harder, $_l, $_cp_similarity, $_cp_remote,
dc5869c0 48 $_repack, $_repack_nr, $_repack_flags,
27e9fb8d 49 $_message, $_file,
9d55b41a 50 $_template, $_shared, $_no_default_regex, $_no_graft_copy,
79bb8d88 51 $_limit, $_verbose, $_incremental, $_oneline, $_l_fmt, $_show_commit,
9d55b41a 52 $_version, $_upgrade, $_authors, $_branch_all_refs, @_opt_m);
42d32870 53my (@_branch_from, %tree_map, %users, %rusers, %equiv);
8a97e368 54my ($_svn_co_url_revs, $_svn_pg_peg_revs);
883d0a78 55my @repo_path_split_cache;
3397f9df 56
eeb0abe0 57my %fc_opts = ( 'no-ignore-externals' => \$_no_ignore_ext,
69f0d91e 58 'branch|b=s' => \@_branch_from,
bf78b1d8 59 'branch-all-refs|B' => \$_branch_all_refs,
dc5869c0
EW
60 'authors-file|A=s' => \$_authors,
61 'repack:i' => \$_repack,
62 'repack-flags|repack-args|repack-opts=s' => \$_repack_flags);
36f5b1f0 63
9d55b41a
EW
64my ($_trunk, $_tags, $_branches);
65my %multi_opts = ( 'trunk|T=s' => \$_trunk,
66 'tags|t=s' => \$_tags,
67 'branches|b=s' => \$_branches );
68my %init_opts = ( 'template=s' => \$_template, 'shared' => \$_shared );
27e9fb8d
EW
69my %cmt_opts = ( 'edit|e' => \$_edit,
70 'rmdir' => \$_rmdir,
71 'find-copies-harder' => \$_find_copies_harder,
72 'l=i' => \$_l,
73 'copy-similarity|C=i'=> \$_cp_similarity
74);
9d55b41a 75
36f5b1f0
EW
76# yes, 'native' sets "\n". Patches to fix this for non-*nix systems welcome:
77my %EOL = ( CR => "\015", LF => "\012", CRLF => "\015\012", native => "\012" );
78
3397f9df 79my %cmd = (
eeb0abe0
EW
80 fetch => [ \&fetch, "Download new revisions from SVN",
81 { 'revision|r=s' => \$_revision, %fc_opts } ],
81c5a0e6 82 init => [ \&init, "Initialize a repo for tracking" .
f8ab6b73 83 " (requires URL argument)",
9d55b41a 84 \%init_opts ],
eeb0abe0 85 commit => [ \&commit, "Commit git revisions to SVN",
27e9fb8d 86 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
a5e0cedc
EW
87 'show-ignore' => [ \&show_ignore, "Show svn:ignore listings",
88 { 'revision|r=i' => \$_revision } ],
eeb0abe0
EW
89 rebuild => [ \&rebuild, "Rebuild git-svn metadata (after git clone)",
90 { 'no-ignore-externals' => \$_no_ignore_ext,
1a82e793 91 'copy-remote|remote=s' => \$_cp_remote,
eeb0abe0 92 'upgrade' => \$_upgrade } ],
9d55b41a
EW
93 'graft-branches' => [ \&graft_branches,
94 'Detect merges/branches from already imported history',
95 { 'merge-rx|m' => \@_opt_m,
c1927a85
EW
96 'branch|b=s' => \@_branch_from,
97 'branch-all-refs|B' => \$_branch_all_refs,
9d55b41a
EW
98 'no-default-regex' => \$_no_default_regex,
99 'no-graft-copy' => \$_no_graft_copy } ],
100 'multi-init' => [ \&multi_init,
101 'Initialize multiple trees (like git-svnimport)',
102 { %multi_opts, %fc_opts } ],
103 'multi-fetch' => [ \&multi_fetch,
104 'Fetch multiple trees (like git-svnimport)',
105 \%fc_opts ],
79bb8d88
EW
106 'log' => [ \&show_log, 'Show commit logs',
107 { 'limit=i' => \$_limit,
108 'revision|r=s' => \$_revision,
109 'verbose|v' => \$_verbose,
110 'incremental' => \$_incremental,
111 'oneline' => \$_oneline,
112 'show-commit' => \$_show_commit,
113 'authors-file|A=s' => \$_authors,
114 } ],
27e9fb8d
EW
115 'commit-diff' => [ \&commit_diff, 'Commit a diff between two trees',
116 { 'message|m=s' => \$_message,
117 'file|F=s' => \$_file,
118 %cmt_opts } ],
3397f9df 119);
9d55b41a 120
3397f9df
EW
121my $cmd;
122for (my $i = 0; $i < @ARGV; $i++) {
123 if (defined $cmd{$ARGV[$i]}) {
124 $cmd = $ARGV[$i];
125 splice @ARGV, $i, 1;
126 last;
127 }
128};
129
448c81b4 130my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
a9612be2 131
b8c92cad 132read_repo_config(\%opts);
79bb8d88
EW
133my $rv = GetOptions(%opts, 'help|H|h' => \$_help,
134 'version|V' => \$_version,
135 'id|i=s' => \$GIT_SVN);
136exit 1 if (!$rv && $cmd ne 'log');
6f0783cf 137
dc5869c0 138set_default_vals();
3397f9df 139usage(0) if $_help;
551ce28f 140version() if $_version;
eeb0abe0 141usage(1) unless defined $cmd;
b8c92cad 142init_vars();
eeb0abe0 143load_authors() if $_authors;
bf78b1d8 144load_all_refs() if $_branch_all_refs;
dc62e25c 145svn_compat_check() unless $_use_lib;
1a82e793 146migration_check() unless $cmd =~ /^(?:init|rebuild|multi-init)$/;
3397f9df
EW
147$cmd{$cmd}->[0]->(@ARGV);
148exit 0;
149
150####################### primary functions ######################
151sub usage {
152 my $exit = shift || 0;
153 my $fd = $exit ? \*STDERR : \*STDOUT;
154 print $fd <<"";
155git-svn - bidirectional operations between a single Subversion tree and git
156Usage: $0 <command> [options] [arguments]\n
448c81b4
EW
157
158 print $fd "Available commands:\n" unless $cmd;
3397f9df
EW
159
160 foreach (sort keys %cmd) {
448c81b4 161 next if $cmd && $cmd ne $_;
ac8e0b91 162 print $fd ' ',pack('A13',$_),$cmd{$_}->[1],"\n";
448c81b4
EW
163 foreach (keys %{$cmd{$_}->[2]}) {
164 # prints out arguments as they should be passed:
b8c92cad 165 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
448c81b4
EW
166 print $fd ' ' x 17, join(', ', map { length $_ > 1 ?
167 "--$_" : "-$_" }
168 split /\|/,$_)," $x\n";
169 }
3397f9df
EW
170 }
171 print $fd <<"";
448c81b4
EW
172\nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
173arbitrary identifier if you're tracking multiple SVN branches/repositories in
174one git repository and want to keep them separate. See git-svn(1) for more
175information.
3397f9df
EW
176
177 exit $exit;
178}
179
551ce28f
EW
180sub version {
181 print "git-svn version $VERSION\n";
182 exit 0;
183}
184
3397f9df 185sub rebuild {
1a82e793
EW
186 if (quiet_run(qw/git-rev-parse --verify/,"refs/remotes/$GIT_SVN^0")) {
187 copy_remote_ref();
188 }
3397f9df 189 $SVN_URL = shift or undef;
3397f9df 190 my $newest_rev = 0;
2beb3cdd
EW
191 if ($_upgrade) {
192 sys('git-update-ref',"refs/remotes/$GIT_SVN","$GIT_SVN-HEAD");
193 } else {
194 check_upgrade_needed();
195 }
3397f9df
EW
196
197 my $pid = open(my $rev_list,'-|');
198 defined $pid or croak $!;
199 if ($pid == 0) {
2beb3cdd 200 exec("git-rev-list","refs/remotes/$GIT_SVN") or croak $!;
3397f9df 201 }
2beb3cdd 202 my $latest;
3397f9df
EW
203 while (<$rev_list>) {
204 chomp;
205 my $c = $_;
206 croak "Non-SHA1: $c\n" unless $c =~ /^$sha1$/o;
207 my @commit = grep(/^git-svn-id: /,`git-cat-file commit $c`);
208 next if (!@commit); # skip merges
79bb8d88
EW
209 my ($url, $rev, $uuid) = extract_metadata($commit[$#commit]);
210 if (!$rev || !$uuid) {
211 croak "Unable to extract revision or UUID from ",
212 "$c, $commit[$#commit]\n";
3397f9df 213 }
2beb3cdd
EW
214
215 # if we merged or otherwise started elsewhere, this is
216 # how we break out of it
1ca72aef 217 next if (defined $SVN_UUID && ($uuid ne $SVN_UUID));
779b1446 218 next if (defined $SVN_URL && defined $url && ($url ne $SVN_URL));
2beb3cdd 219
2beb3cdd 220 unless (defined $latest) {
3397f9df
EW
221 if (!$SVN_URL && !$url) {
222 croak "SVN repository location required: $url\n";
223 }
224 $SVN_URL ||= $url;
1d52aba8
EW
225 $SVN_UUID ||= $uuid;
226 setup_git_svn();
2beb3cdd 227 $latest = $rev;
3397f9df 228 }
42d32870
EW
229 revdb_set($REVDB, $rev, $c);
230 print "r$rev = $c\n";
3397f9df
EW
231 $newest_rev = $rev if ($rev > $newest_rev);
232 }
233 close $rev_list or croak $?;
a5e0cedc
EW
234
235 goto out if $_use_lib;
3397f9df 236 if (!chdir $SVN_WC) {
1d52aba8 237 svn_cmd_checkout($SVN_URL, $latest, $SVN_WC);
3397f9df
EW
238 chdir $SVN_WC or croak $!;
239 }
240
241 $pid = fork;
242 defined $pid or croak $!;
243 if ($pid == 0) {
244 my @svn_up = qw(svn up);
245 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
246 sys(@svn_up,"-r$newest_rev");
247 $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
36f5b1f0 248 index_changes();
b8c92cad 249 exec('git-write-tree') or croak $!;
3397f9df
EW
250 }
251 waitpid $pid, 0;
b8c92cad 252 croak $? if $?;
a5e0cedc 253out:
2beb3cdd
EW
254 if ($_upgrade) {
255 print STDERR <<"";
256Keeping deprecated refs/head/$GIT_SVN-HEAD for now. Please remove it
257when you have upgraded your tools and habits to use refs/remotes/$GIT_SVN
258
259 }
3397f9df
EW
260}
261
262sub init {
81c5a0e6
EW
263 $SVN_URL = shift or die "SVN repository location required " .
264 "as a command-line argument\n";
9d55b41a 265 $SVN_URL =~ s!/+$!!; # strip trailing slash
3397f9df 266 unless (-d $GIT_DIR) {
f8ab6b73
EW
267 my @init_db = ('git-init-db');
268 push @init_db, "--template=$_template" if defined $_template;
269 push @init_db, "--shared" if defined $_shared;
270 sys(@init_db);
3397f9df
EW
271 }
272 setup_git_svn();
273}
274
275sub fetch {
2beb3cdd 276 check_upgrade_needed();
883d0a78 277 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
a5e0cedc
EW
278 my $ret = $_use_lib ? fetch_lib(@_) : fetch_cmd(@_);
279 if ($ret->{commit} && quiet_run(qw(git-rev-parse --verify
280 refs/heads/master^0))) {
281 sys(qw(git-update-ref refs/heads/master),$ret->{commit});
282 }
283 return $ret;
284}
285
286sub fetch_cmd {
287 my (@parents) = @_;
3397f9df 288 my @log_args = -d $SVN_WC ? ($SVN_WC) : ($SVN_URL);
defc6492
EW
289 unless ($_revision) {
290 $_revision = -d $SVN_WC ? 'BASE:HEAD' : '0:HEAD';
3397f9df 291 }
defc6492 292 push @log_args, "-r$_revision";
3397f9df
EW
293 push @log_args, '--stop-on-copy' unless $_no_stop_copy;
294
ce6f3519 295 my $svn_log = svn_log_raw(@log_args);
3397f9df 296
03823184 297 my $base = next_log_entry($svn_log) or croak "No base revision!\n";
42d32870
EW
298 # don't need last_revision from grab_base_rev() because
299 # user could've specified a different revision to skip (they
300 # didn't want to import certain revisions into git for whatever
301 # reason, so trust $base->{revision} instead.
302 my (undef, $last_commit) = svn_grab_base_rev();
3397f9df 303 unless (-d $SVN_WC) {
1d52aba8 304 svn_cmd_checkout($SVN_URL,$base->{revision},$SVN_WC);
3397f9df 305 chdir $SVN_WC or croak $!;
1d52aba8 306 read_uuid();
3397f9df 307 $last_commit = git_commit($base, @parents);
36f5b1f0 308 assert_tree($last_commit);
3397f9df
EW
309 } else {
310 chdir $SVN_WC or croak $!;
1d52aba8 311 read_uuid();
6dfbe516
EW
312 # looks like a user manually cp'd and svn switch'ed
313 unless ($last_commit) {
314 sys(qw/svn revert -R ./);
315 assert_svn_wc_clean($base->{revision});
316 $last_commit = git_commit($base, @parents);
317 assert_tree($last_commit);
318 }
3397f9df
EW
319 }
320 my @svn_up = qw(svn up);
321 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
03823184
EW
322 my $last = $base;
323 while (my $log_msg = next_log_entry($svn_log)) {
03823184
EW
324 if ($last->{revision} >= $log_msg->{revision}) {
325 croak "Out of order: last >= current: ",
326 "$last->{revision} >= $log_msg->{revision}\n";
327 }
36f5b1f0
EW
328 # Revert is needed for cases like:
329 # https://svn.musicpd.org/Jamming/trunk (r166:167), but
330 # I can't seem to reproduce something like that on a test...
331 sys(qw/svn revert -R ./);
332 assert_svn_wc_clean($last->{revision});
03823184 333 sys(@svn_up,"-r$log_msg->{revision}");
3397f9df 334 $last_commit = git_commit($log_msg, $last_commit, @parents);
03823184 335 $last = $log_msg;
3397f9df 336 }
b8c92cad 337 close $svn_log->{fh};
a5e0cedc 338 $last->{commit} = $last_commit;
03823184 339 return $last;
3397f9df
EW
340}
341
a5e0cedc
EW
342sub fetch_lib {
343 my (@parents) = @_;
344 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
345 my $repo;
346 ($repo, $SVN_PATH) = repo_path_split($SVN_URL);
347 $SVN_LOG ||= libsvn_connect($repo);
348 $SVN ||= libsvn_connect($repo);
349 my ($last_rev, $last_commit) = svn_grab_base_rev();
350 my ($base, $head) = libsvn_parse_revision($last_rev);
351 if ($base > $head) {
352 return { revision => $last_rev, commit => $last_commit }
353 }
354 my $index = set_index($GIT_SVN_INDEX);
355
356 # limit ourselves and also fork() since get_log won't release memory
357 # after processing a revision and SVN stuff seems to leak
358 my $inc = 1000;
359 my ($min, $max) = ($base, $head < $base+$inc ? $head : $base+$inc);
360 read_uuid();
361 if (defined $last_commit) {
362 unless (-e $GIT_SVN_INDEX) {
363 sys(qw/git-read-tree/, $last_commit);
364 }
365 chomp (my $x = `git-write-tree`);
366 my ($y) = (`git-cat-file commit $last_commit`
367 =~ /^tree ($sha1)/m);
368 if ($y ne $x) {
369 unlink $GIT_SVN_INDEX or croak $!;
370 sys(qw/git-read-tree/, $last_commit);
371 }
372 chomp ($x = `git-write-tree`);
373 if ($y ne $x) {
374 print STDERR "trees ($last_commit) $y != $x\n",
375 "Something is seriously wrong...\n";
376 }
377 }
378 while (1) {
379 # fork, because using SVN::Pool with get_log() still doesn't
380 # seem to help enough to keep memory usage down.
381 defined(my $pid = fork) or croak $!;
382 if (!$pid) {
383 $SVN::Error::handler = \&libsvn_skip_unknown_revs;
a5e0cedc
EW
384
385 # Yes I'm perfectly aware that the fourth argument
386 # below is the limit revisions number. Unfortunately
387 # performance sucks with it enabled, so it's much
388 # faster to fetch revision ranges instead of relying
389 # on the limiter.
dc62e25c
EW
390 libsvn_get_log($SVN_LOG, '/'.$SVN_PATH,
391 $min, $max, 0, 1, 1,
a5e0cedc
EW
392 sub {
393 my $log_msg;
394 if ($last_commit) {
395 $log_msg = libsvn_fetch(
396 $last_commit, @_);
397 $last_commit = git_commit(
398 $log_msg,
399 $last_commit,
400 @parents);
401 } else {
402 $log_msg = libsvn_new_tree(@_);
403 $last_commit = git_commit(
404 $log_msg, @parents);
405 }
406 });
a5e0cedc
EW
407 exit 0;
408 }
409 waitpid $pid, 0;
410 croak $? if $?;
411 ($last_rev, $last_commit) = svn_grab_base_rev();
412 last if ($max >= $head);
413 $min = $max + 1;
414 $max += $inc;
415 $max = $head if ($max > $head);
416 }
417 restore_index($index);
418 return { revision => $last_rev, commit => $last_commit };
419}
420
3397f9df
EW
421sub commit {
422 my (@commits) = @_;
2beb3cdd 423 check_upgrade_needed();
3397f9df
EW
424 if ($_stdin || !@commits) {
425 print "Reading from stdin...\n";
426 @commits = ();
427 while (<STDIN>) {
1ca72aef 428 if (/\b($sha1_short)\b/o) {
3397f9df
EW
429 unshift @commits, $1;
430 }
431 }
432 }
433 my @revs;
8de010ad
EW
434 foreach my $c (@commits) {
435 chomp(my @tmp = safe_qx('git-rev-parse',$c));
436 if (scalar @tmp == 1) {
437 push @revs, $tmp[0];
438 } elsif (scalar @tmp > 1) {
439 push @revs, reverse (safe_qx('git-rev-list',@tmp));
440 } else {
441 die "Failed to rev-parse $c\n";
442 }
3397f9df
EW
443 }
444 chomp @revs;
a5e0cedc
EW
445 $_use_lib ? commit_lib(@revs) : commit_cmd(@revs);
446 print "Done committing ",scalar @revs," revisions to SVN\n";
447}
448
449sub commit_cmd {
450 my (@revs) = @_;
3397f9df 451
b63af9b3 452 chdir $SVN_WC or croak "Unable to chdir $SVN_WC: $!\n";
1d52aba8 453 my $info = svn_info('.');
b63af9b3
EW
454 my $fetched = fetch();
455 if ($info->{Revision} != $fetched->{revision}) {
456 print STDERR "There are new revisions that were fetched ",
457 "and need to be merged (or acknowledged) ",
458 "before committing.\n";
459 exit 1;
460 }
461 $info = svn_info('.');
1d52aba8 462 read_uuid($info);
42d32870 463 my $last = $fetched;
3397f9df 464 foreach my $c (@revs) {
42d32870 465 my $mods = svn_checkout_tree($last, $c);
cf52b8f0
EW
466 if (scalar @$mods == 0) {
467 print "Skipping, no changes detected\n";
468 next;
469 }
42d32870 470 $last = svn_commit_tree($last, $c);
3397f9df 471 }
3397f9df
EW
472}
473
a5e0cedc
EW
474sub commit_lib {
475 my (@revs) = @_;
476 my ($r_last, $cmt_last) = svn_grab_base_rev();
477 defined $r_last or die "Must have an existing revision to commit\n";
cf7424b0 478 my $fetched = fetch();
a5e0cedc
EW
479 if ($r_last != $fetched->{revision}) {
480 print STDERR "There are new revisions that were fetched ",
481 "and need to be merged (or acknowledged) ",
482 "before committing.\n",
483 "last rev: $r_last\n",
484 " current: $fetched->{revision}\n";
485 exit 1;
486 }
487 read_uuid();
488 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
489 my $commit_msg = "$GIT_SVN_DIR/.svn-commit.tmp.$$";
490
27e9fb8d 491 set_svn_commit_env();
a5e0cedc 492 foreach my $c (@revs) {
ec9d00d0
EW
493 my $log_msg = get_commit_message($c, $commit_msg);
494
a5e0cedc
EW
495 # fork for each commit because there's a memory leak I
496 # can't track down... (it's probably in the SVN code)
497 defined(my $pid = open my $fh, '-|') or croak $!;
498 if (!$pid) {
a5e0cedc
EW
499 my $ed = SVN::Git::Editor->new(
500 { r => $r_last,
501 ra => $SVN,
502 c => $c,
503 svn_path => $SVN_PATH
504 },
505 $SVN->get_commit_editor(
506 $log_msg->{msg},
507 sub {
508 libsvn_commit_cb(
509 @_, $c,
510 $log_msg->{msg},
511 $r_last,
512 $cmt_last)
513 },
514 @lock)
515 );
42d32870 516 my $mods = libsvn_checkout_tree($cmt_last, $c, $ed);
a5e0cedc
EW
517 if (@$mods == 0) {
518 print "No changes\nr$r_last = $cmt_last\n";
519 $ed->abort_edit;
520 } else {
521 $ed->close_edit;
522 }
523 exit 0;
524 }
525 my ($r_new, $cmt_new, $no);
526 while (<$fh>) {
527 print $_;
528 chomp;
529 if (/^r(\d+) = ($sha1)$/o) {
530 ($r_new, $cmt_new) = ($1, $2);
531 } elsif ($_ eq 'No changes') {
532 $no = 1;
533 }
534 }
cf7424b0 535 close $fh or croak $?;
a5e0cedc
EW
536 if (! defined $r_new && ! defined $cmt_new) {
537 unless ($no) {
538 die "Failed to parse revision information\n";
539 }
540 } else {
541 ($r_last, $cmt_last) = ($r_new, $cmt_new);
542 }
543 }
ec9d00d0 544 $ENV{LC_ALL} = 'C';
a5e0cedc
EW
545 unlink $commit_msg;
546}
8f22562c 547
a5e0cedc 548sub show_ignore {
883d0a78 549 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
a5e0cedc
EW
550 $_use_lib ? show_ignore_lib() : show_ignore_cmd();
551}
552
553sub show_ignore_cmd {
554 require File::Find or die $!;
555 if (defined $_revision) {
556 die "-r/--revision option doesn't work unless the Perl SVN ",
557 "libraries are used\n";
558 }
8f22562c
EW
559 chdir $SVN_WC or croak $!;
560 my %ign;
561 File::Find::find({wanted=>sub{if(lstat $_ && -d _ && -d "$_/.svn"){
562 s#^\./##;
8a97e368 563 @{$ign{$_}} = svn_propget_base('svn:ignore', $_);
8f22562c
EW
564 }}, no_chdir=>1},'.');
565
566 print "\n# /\n";
567 foreach (@{$ign{'.'}}) { print '/',$_ if /\S/ }
568 delete $ign{'.'};
569 foreach my $i (sort keys %ign) {
570 print "\n# ",$i,"\n";
571 foreach (@{$ign{$i}}) { print '/',$i,'/',$_ if /\S/ }
572 }
573}
574
a5e0cedc
EW
575sub show_ignore_lib {
576 my $repo;
577 ($repo, $SVN_PATH) = repo_path_split($SVN_URL);
578 $SVN ||= libsvn_connect($repo);
579 my $r = defined $_revision ? $_revision : $SVN->get_latest_revnum;
580 libsvn_traverse_ignore(\*STDOUT, $SVN_PATH, $r);
581}
582
9d55b41a
EW
583sub graft_branches {
584 my $gr_file = "$GIT_DIR/info/grafts";
585 my ($grafts, $comments) = read_grafts($gr_file);
586 my $gr_sha1;
587
588 if (%$grafts) {
589 # temporarily disable our grafts file to make this idempotent
590 chomp($gr_sha1 = safe_qx(qw/git-hash-object -w/,$gr_file));
591 rename $gr_file, "$gr_file~$gr_sha1" or croak $!;
592 }
593
594 my $l_map = read_url_paths();
595 my @re = map { qr/$_/is } @_opt_m if @_opt_m;
596 unless ($_no_default_regex) {
c1927a85
EW
597 push @re, (qr/\b(?:merge|merging|merged)\s+with\s+([\w\.\-]+)/i,
598 qr/\b(?:merge|merging|merged)\s+([\w\.\-]+)/i,
599 qr/\b(?:from|of)\s+([\w\.\-]+)/i );
9d55b41a
EW
600 }
601 foreach my $u (keys %$l_map) {
602 if (@re) {
603 foreach my $p (keys %{$l_map->{$u}}) {
c1927a85 604 graft_merge_msg($grafts,$l_map,$u,$p,@re);
9d55b41a
EW
605 }
606 }
a5e0cedc
EW
607 unless ($_no_graft_copy) {
608 if ($_use_lib) {
609 graft_file_copy_lib($grafts,$l_map,$u);
610 } else {
611 graft_file_copy_cmd($grafts,$l_map,$u);
612 }
613 }
9d55b41a 614 }
c1927a85 615 graft_tree_joins($grafts);
9d55b41a
EW
616
617 write_grafts($grafts, $comments, $gr_file);
618 unlink "$gr_file~$gr_sha1" if $gr_sha1;
619}
620
621sub multi_init {
622 my $url = shift;
623 $_trunk ||= 'trunk';
624 $_trunk =~ s#/+$##;
625 $url =~ s#/+$## if $url;
626 if ($_trunk !~ m#^[a-z\+]+://#) {
627 $_trunk = '/' . $_trunk if ($_trunk !~ m#^/#);
628 unless ($url) {
629 print STDERR "E: '$_trunk' is not a complete URL ",
630 "and a separate URL is not specified\n";
631 exit 1;
632 }
633 $_trunk = $url . $_trunk;
634 }
635 if ($GIT_SVN eq 'git-svn') {
636 print "GIT_SVN_ID set to 'trunk' for $_trunk\n";
637 $GIT_SVN = $ENV{GIT_SVN_ID} = 'trunk';
638 }
639 init_vars();
640 init($_trunk);
641 complete_url_ls_init($url, $_branches, '--branches/-b', '');
642 complete_url_ls_init($url, $_tags, '--tags/-t', 'tags/');
643}
644
645sub multi_fetch {
646 # try to do trunk first, since branches/tags
647 # may be descended from it.
cf7424b0
EW
648 if (-e "$GIT_DIR/svn/trunk/info/url") {
649 fetch_child_id('trunk', @_);
9d55b41a
EW
650 }
651 rec_fetch('', "$GIT_DIR/svn", @_);
652}
653
79bb8d88
EW
654sub show_log {
655 my (@args) = @_;
656 my ($r_min, $r_max);
657 my $r_last = -1; # prevent dupes
658 rload_authors() if $_authors;
659 if (defined $TZ) {
660 $ENV{TZ} = $TZ;
661 } else {
662 delete $ENV{TZ};
663 }
664 if (defined $_revision) {
665 if ($_revision =~ /^(\d+):(\d+)$/) {
666 ($r_min, $r_max) = ($1, $2);
667 } elsif ($_revision =~ /^\d+$/) {
668 $r_min = $r_max = $_revision;
669 } else {
670 print STDERR "-r$_revision is not supported, use ",
671 "standard \'git log\' arguments instead\n";
672 exit 1;
673 }
674 }
675
676 my $pid = open(my $log,'-|');
677 defined $pid or croak $!;
678 if (!$pid) {
c0d48222 679 exec(git_svn_log_cmd($r_min,$r_max), @args) or croak $!;
79bb8d88
EW
680 }
681 setup_pager();
682 my (@k, $c, $d);
c0d48222 683
79bb8d88
EW
684 while (<$log>) {
685 if (/^commit ($sha1_short)/o) {
686 my $cmt = $1;
c0d48222 687 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
79bb8d88
EW
688 $r_last = $c->{r};
689 process_commit($c, $r_min, $r_max, \@k) or
690 goto out;
691 }
692 $d = undef;
693 $c = { c => $cmt };
694 } elsif (/^author (.+) (\d+) ([\-\+]?\d+)$/) {
695 get_author_info($c, $1, $2, $3);
696 } elsif (/^(?:tree|parent|committer) /) {
697 # ignore
698 } elsif (/^:\d{6} \d{6} $sha1_short/o) {
699 push @{$c->{raw}}, $_;
700 } elsif (/^diff /) {
701 $d = 1;
702 push @{$c->{diff}}, $_;
703 } elsif ($d) {
704 push @{$c->{diff}}, $_;
705 } elsif (/^ (git-svn-id:.+)$/) {
c0d48222 706 (undef, $c->{r}, undef) = extract_metadata($1);
79bb8d88
EW
707 } elsif (s/^ //) {
708 push @{$c->{l}}, $_;
709 }
710 }
711 if ($c && defined $c->{r} && $c->{r} != $r_last) {
712 $r_last = $c->{r};
713 process_commit($c, $r_min, $r_max, \@k);
714 }
715 if (@k) {
716 my $swap = $r_max;
717 $r_max = $r_min;
718 $r_min = $swap;
719 process_commit($_, $r_min, $r_max) foreach reverse @k;
720 }
721out:
722 close $log;
723 print '-' x72,"\n" unless $_incremental || $_oneline;
724}
725
27e9fb8d
EW
726sub commit_diff_usage {
727 print STDERR "Usage: $0 commit-diff <tree-ish> <tree-ish> [<URL>]\n";
728 exit 1
729}
730
731sub commit_diff {
732 if (!$_use_lib) {
733 print STDERR "commit-diff must be used with SVN libraries\n";
734 exit 1;
735 }
736 my $ta = shift or commit_diff_usage();
737 my $tb = shift or commit_diff_usage();
738 if (!eval { $SVN_URL = shift || file_to_s("$GIT_SVN_DIR/info/url") }) {
739 print STDERR "Needed URL or usable git-svn id command-line\n";
740 commit_diff_usage();
741 }
742 if (defined $_message && defined $_file) {
743 print STDERR "Both --message/-m and --file/-F specified ",
744 "for the commit message.\n",
745 "I have no idea what you mean\n";
746 exit 1;
747 }
748 if (defined $_file) {
749 $_message = file_to_s($_message);
750 } else {
751 $_message ||= get_commit_message($tb,
752 "$GIT_DIR/.svn-commit.tmp.$$")->{msg};
753 }
754 my $repo;
755 ($repo, $SVN_PATH) = repo_path_split($SVN_URL);
756 $SVN_LOG ||= libsvn_connect($repo);
757 $SVN ||= libsvn_connect($repo);
758 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
759 my $ed = SVN::Git::Editor->new({ r => $SVN->get_latest_revnum,
760 ra => $SVN, c => $tb,
761 svn_path => $SVN_PATH
762 },
763 $SVN->get_commit_editor($_message,
764 sub {print "Committed $_[0]\n"},@lock)
765 );
766 my $mods = libsvn_checkout_tree($ta, $tb, $ed);
767 if (@$mods == 0) {
768 print "No changes\n$ta == $tb\n";
769 $ed->abort_edit;
770 } else {
771 $ed->close_edit;
772 }
773}
774
3397f9df
EW
775########################### utility functions #########################
776
c0d48222
EW
777sub cmt_showable {
778 my ($c) = @_;
779 return 1 if defined $c->{r};
780 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
781 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
782 my @msg = safe_qx(qw/git-cat-file commit/, $c->{c});
783 shift @msg while ($msg[0] ne "\n");
784 shift @msg;
785 @{$c->{l}} = grep !/^git-svn-id: /, @msg;
786
787 (undef, $c->{r}, undef) = extract_metadata(
788 (grep(/^git-svn-id: /, @msg))[-1]);
789 }
790 return defined $c->{r};
791}
792
793sub git_svn_log_cmd {
794 my ($r_min, $r_max) = @_;
795 my @cmd = (qw/git-log --abbrev-commit --pretty=raw
796 --default/, "refs/remotes/$GIT_SVN");
797 push @cmd, '--summary' if $_verbose;
798 return @cmd unless defined $r_max;
799 if ($r_max == $r_min) {
800 push @cmd, '--max-count=1';
801 if (my $c = revdb_get($REVDB, $r_max)) {
802 push @cmd, $c;
803 }
804 } else {
805 my ($c_min, $c_max);
806 $c_max = revdb_get($REVDB, $r_max);
807 $c_min = revdb_get($REVDB, $r_min);
808 if ($c_min && $c_max) {
809 if ($r_max > $r_max) {
810 push @cmd, "$c_min..$c_max";
811 } else {
812 push @cmd, "$c_max..$c_min";
813 }
814 } elsif ($r_max > $r_min) {
815 push @cmd, $c_max;
816 } else {
817 push @cmd, $c_min;
818 }
819 }
820 return @cmd;
821}
822
cf7424b0
EW
823sub fetch_child_id {
824 my $id = shift;
825 print "Fetching $id\n";
826 my $ref = "$GIT_DIR/refs/remotes/$id";
827 my $ca = file_to_s($ref) if (-r $ref);
828 defined(my $pid = fork) or croak $!;
829 if (!$pid) {
830 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
831 init_vars();
832 fetch(@_);
833 exit 0;
834 }
835 waitpid $pid, 0;
836 croak $? if $?;
837 return unless $_repack || -r $ref;
838
839 my $cb = file_to_s($ref);
840
841 defined($pid = open my $fh, '-|') or croak $!;
842 my $url = file_to_s("$GIT_DIR/svn/$id/info/url");
843 $url = qr/\Q$url\E/;
844 if (!$pid) {
845 exec qw/git-rev-list --pretty=raw/,
846 $ca ? "$ca..$cb" : $cb or croak $!;
847 }
848 while (<$fh>) {
849 if (/^ git-svn-id: $url\@\d+ [a-f0-9\-]+$/) {
850 check_repack();
851 } elsif (/^ git-svn-id: \S+\@\d+ [a-f0-9\-]+$/) {
852 last;
853 }
854 }
855 close $fh;
856}
857
9d55b41a
EW
858sub rec_fetch {
859 my ($pfx, $p, @args) = @_;
860 my @dir;
861 foreach (sort <$p/*>) {
862 if (-r "$_/info/url") {
863 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
864 my $id = $pfx . basename $_;
865 next if $id eq 'trunk';
cf7424b0 866 fetch_child_id($id, @args);
9d55b41a
EW
867 } elsif (-d $_) {
868 push @dir, $_;
869 }
870 }
871 foreach (@dir) {
872 my $x = $_;
873 $x =~ s!^\Q$GIT_DIR\E/svn/!!;
874 rec_fetch($x, $_);
875 }
876}
877
878sub complete_url_ls_init {
879 my ($url, $var, $switch, $pfx) = @_;
880 unless ($var) {
881 print STDERR "W: $switch not specified\n";
882 return;
883 }
884 $var =~ s#/+$##;
885 if ($var !~ m#^[a-z\+]+://#) {
886 $var = '/' . $var if ($var !~ m#^/#);
887 unless ($url) {
888 print STDERR "E: '$var' is not a complete URL ",
889 "and a separate URL is not specified\n";
890 exit 1;
891 }
892 $var = $url . $var;
893 }
a5e0cedc
EW
894 chomp(my @ls = $_use_lib ? libsvn_ls_fullurl($var)
895 : safe_qx(qw/svn ls --non-interactive/, $var));
9d55b41a
EW
896 my $old = $GIT_SVN;
897 defined(my $pid = fork) or croak $!;
898 if (!$pid) {
899 foreach my $u (map { "$var/$_" } (grep m!/$!, @ls)) {
900 $u =~ s#/+$##;
901 if ($u !~ m!\Q$var\E/(.+)$!) {
902 print STDERR "W: Unrecognized URL: $u\n";
903 die "This should never happen\n";
904 }
905 my $id = $pfx.$1;
906 print "init $u => $id\n";
907 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
908 init_vars();
909 init($u);
910 }
911 exit 0;
912 }
913 waitpid $pid, 0;
914 croak $? if $?;
915}
916
917sub common_prefix {
918 my $paths = shift;
919 my %common;
920 foreach (@$paths) {
921 my @tmp = split m#/#, $_;
922 my $p = '';
923 while (my $x = shift @tmp) {
924 $p .= "/$x";
925 $common{$p} ||= 0;
926 $common{$p}++;
927 }
928 }
929 foreach (sort {length $b <=> length $a} keys %common) {
930 if ($common{$_} == @$paths) {
931 return $_;
932 }
933 }
934 return '';
935}
936
c1927a85
EW
937# grafts set here are 'stronger' in that they're based on actual tree
938# matches, and won't be deleted from merge-base checking in write_grafts()
939sub graft_tree_joins {
940 my $grafts = shift;
941 map_tree_joins() if (@_branch_from && !%tree_map);
942 return unless %tree_map;
943
944 git_svn_each(sub {
945 my $i = shift;
946 defined(my $pid = open my $fh, '-|') or croak $!;
947 if (!$pid) {
948 exec qw/git-rev-list --pretty=raw/,
949 "refs/remotes/$i" or croak $!;
950 }
951 while (<$fh>) {
952 next unless /^commit ($sha1)$/o;
953 my $c = $1;
954 my ($t) = (<$fh> =~ /^tree ($sha1)$/o);
955 next unless $tree_map{$t};
956
957 my $l;
958 do {
959 $l = readline $fh;
960 } until ($l =~ /^committer (?:.+) (\d+) ([\-\+]?\d+)$/);
961
962 my ($s, $tz) = ($1, $2);
963 if ($tz =~ s/^\+//) {
964 $s += tz_to_s_offset($tz);
965 } elsif ($tz =~ s/^\-//) {
966 $s -= tz_to_s_offset($tz);
967 }
968
969 my ($url_a, $r_a, $uuid_a) = cmt_metadata($c);
970
971 foreach my $p (@{$tree_map{$t}}) {
972 next if $p eq $c;
973 my $mb = eval {
974 safe_qx('git-merge-base', $c, $p)
975 };
976 next unless ($@ || $?);
977 if (defined $r_a) {
978 # see if SVN says it's a relative
979 my ($url_b, $r_b, $uuid_b) =
980 cmt_metadata($p);
981 next if (defined $url_b &&
982 defined $url_a &&
983 ($url_a eq $url_b) &&
984 ($uuid_a eq $uuid_b));
985 if ($uuid_a eq $uuid_b) {
986 if ($r_b < $r_a) {
987 $grafts->{$c}->{$p} = 2;
988 next;
989 } elsif ($r_b > $r_a) {
990 $grafts->{$p}->{$c} = 2;
991 next;
992 }
993 }
994 }
995 my $ct = get_commit_time($p);
996 if ($ct < $s) {
997 $grafts->{$c}->{$p} = 2;
998 } elsif ($ct > $s) {
999 $grafts->{$p}->{$c} = 2;
1000 }
1001 # what should we do when $ct == $s ?
1002 }
1003 }
1004 close $fh or croak $?;
1005 });
1006}
1007
9d55b41a 1008# this isn't funky-filename safe, but good enough for now...
a5e0cedc 1009sub graft_file_copy_cmd {
9d55b41a
EW
1010 my ($grafts, $l_map, $u) = @_;
1011 my $paths = $l_map->{$u};
1012 my $pfx = common_prefix([keys %$paths]);
42d32870 1013 $SVN_URL ||= $u.$pfx;
9d55b41a
EW
1014 my $pid = open my $fh, '-|';
1015 defined $pid or croak $!;
1016 unless ($pid) {
a5e0cedc
EW
1017 my @exec = qw/svn log -v/;
1018 push @exec, "-r$_revision" if defined $_revision;
1019 exec @exec, $u.$pfx or croak $!;
9d55b41a
EW
1020 }
1021 my ($r, $mp) = (undef, undef);
1022 while (<$fh>) {
1023 chomp;
1024 if (/^\-{72}$/) {
1025 $mp = $r = undef;
1026 } elsif (/^r(\d+) \| /) {
1027 $r = $1 unless defined $r;
1028 } elsif (/^Changed paths:/) {
1029 $mp = 1;
1030 } elsif ($mp && m#^ [AR] /(\S.*?) \(from /(\S+?):(\d+)\)$#) {
9d55b41a 1031 my ($p1, $p0, $r0) = ($1, $2, $3);
a5e0cedc 1032 my $c = find_graft_path_commit($paths, $p1, $r);
9d55b41a 1033 next unless $c;
a5e0cedc 1034 find_graft_path_parents($grafts, $paths, $c, $p0, $r0);
9d55b41a
EW
1035 }
1036 }
1037}
1038
a5e0cedc
EW
1039sub graft_file_copy_lib {
1040 my ($grafts, $l_map, $u) = @_;
1041 my $tree_paths = $l_map->{$u};
1042 my $pfx = common_prefix([keys %$tree_paths]);
1043 my ($repo, $path) = repo_path_split($u.$pfx);
1044 $SVN_LOG ||= libsvn_connect($repo);
1045 $SVN ||= libsvn_connect($repo);
1046
1047 my ($base, $head) = libsvn_parse_revision();
1048 my $inc = 1000;
1049 my ($min, $max) = ($base, $head < $base+$inc ? $head : $base+$inc);
42d32870
EW
1050 my $eh = $SVN::Error::handler;
1051 $SVN::Error::handler = \&libsvn_skip_unknown_revs;
a5e0cedc
EW
1052 while (1) {
1053 my $pool = SVN::Pool->new;
dc62e25c 1054 libsvn_get_log($SVN_LOG, "/$path", $min, $max, 0, 1, 1,
a5e0cedc
EW
1055 sub {
1056 libsvn_graft_file_copies($grafts, $tree_paths,
1057 $path, @_);
1058 }, $pool);
1059 $pool->clear;
1060 last if ($max >= $head);
1061 $min = $max + 1;
1062 $max += $inc;
1063 $max = $head if ($max > $head);
1064 }
42d32870 1065 $SVN::Error::handler = $eh;
a5e0cedc
EW
1066}
1067
9d55b41a
EW
1068sub process_merge_msg_matches {
1069 my ($grafts, $l_map, $u, $p, $c, @matches) = @_;
1070 my (@strong, @weak);
1071 foreach (@matches) {
1072 # merging with ourselves is not interesting
1073 next if $_ eq $p;
1074 if ($l_map->{$u}->{$_}) {
1075 push @strong, $_;
1076 } else {
1077 push @weak, $_;
1078 }
1079 }
1080 foreach my $w (@weak) {
1081 last if @strong;
1082 # no exact match, use branch name as regexp.
1083 my $re = qr/\Q$w\E/i;
1084 foreach (keys %{$l_map->{$u}}) {
1085 if (/$re/) {
c1927a85 1086 push @strong, $l_map->{$u}->{$_};
9d55b41a
EW
1087 last;
1088 }
1089 }
1090 last if @strong;
1091 $w = basename($w);
1092 $re = qr/\Q$w\E/i;
1093 foreach (keys %{$l_map->{$u}}) {
1094 if (/$re/) {
c1927a85 1095 push @strong, $l_map->{$u}->{$_};
9d55b41a
EW
1096 last;
1097 }
1098 }
1099 }
1100 my ($rev) = ($c->{m} =~ /^git-svn-id:\s(?:\S+?)\@(\d+)
1101 \s(?:[a-f\d\-]+)$/xsm);
1102 unless (defined $rev) {
1103 ($rev) = ($c->{m} =~/^git-svn-id:\s(\d+)
1104 \@(?:[a-f\d\-]+)/xsm);
1105 return unless defined $rev;
1106 }
1107 foreach my $m (@strong) {
c1927a85 1108 my ($r0, $s0) = find_rev_before($rev, $m, 1);
9d55b41a
EW
1109 $grafts->{$c->{c}}->{$s0} = 1 if defined $s0;
1110 }
1111}
1112
1113sub graft_merge_msg {
1114 my ($grafts, $l_map, $u, $p, @re) = @_;
1115
1116 my $x = $l_map->{$u}->{$p};
1117 my $rl = rev_list_raw($x);
1118 while (my $c = next_rev_list_entry($rl)) {
1119 foreach my $re (@re) {
1120 my (@br) = ($c->{m} =~ /$re/g);
1121 next unless @br;
1122 process_merge_msg_matches($grafts,$l_map,$u,$p,$c,@br);
1123 }
1124 }
1125}
1126
1d52aba8
EW
1127sub read_uuid {
1128 return if $SVN_UUID;
a5e0cedc
EW
1129 if ($_use_lib) {
1130 my $pool = SVN::Pool->new;
1131 $SVN_UUID = $SVN->get_uuid($pool);
1132 $pool->clear;
1133 } else {
1134 my $info = shift || svn_info('.');
1135 $SVN_UUID = $info->{'Repository UUID'} or
1d52aba8 1136 croak "Repository UUID unreadable\n";
a5e0cedc 1137 }
883d0a78
EW
1138}
1139
1140sub quiet_run {
1141 my $pid = fork;
1142 defined $pid or croak $!;
1143 if (!$pid) {
1144 open my $null, '>', '/dev/null' or croak $!;
1145 open STDERR, '>&', $null or croak $!;
1146 open STDOUT, '>&', $null or croak $!;
1147 exec @_ or croak $!;
1148 }
1149 waitpid $pid, 0;
1150 return $?;
1151}
1152
1153sub repo_path_split {
1154 my $full_url = shift;
1155 $full_url =~ s#/+$##;
1156
1157 foreach (@repo_path_split_cache) {
1158 if ($full_url =~ s#$_##) {
1159 my $u = $1;
1160 $full_url =~ s#^/+##;
1161 return ($u, $full_url);
1162 }
1163 }
1164
1165 my ($url, $path) = ($full_url =~ m!^([a-z\+]+://[^/]*)(.*)$!i);
1166 $path =~ s#^/+##;
1167 my @paths = split(m#/+#, $path);
1168
a5e0cedc
EW
1169 if ($_use_lib) {
1170 while (1) {
1171 $SVN = libsvn_connect($url);
1172 last if (defined $SVN &&
1173 defined eval { $SVN->get_latest_revnum });
1174 my $n = shift @paths || last;
1175 $url .= "/$n";
1176 }
1177 } else {
1178 while (quiet_run(qw/svn ls --non-interactive/, $url)) {
1179 my $n = shift @paths || last;
1180 $url .= "/$n";
1181 }
883d0a78
EW
1182 }
1183 push @repo_path_split_cache, qr/^(\Q$url\E)/;
9d55b41a 1184 $path = join('/',@paths);
883d0a78 1185 return ($url, $path);
1d52aba8
EW
1186}
1187
3397f9df
EW
1188sub setup_git_svn {
1189 defined $SVN_URL or croak "SVN repository location required\n";
1190 unless (-d $GIT_DIR) {
1191 croak "GIT_DIR=$GIT_DIR does not exist!\n";
1192 }
883d0a78
EW
1193 mkpath([$GIT_SVN_DIR]);
1194 mkpath(["$GIT_SVN_DIR/info"]);
42d32870
EW
1195 open my $fh, '>>',$REVDB or croak $!;
1196 close $fh;
883d0a78 1197 s_to_file($SVN_URL,"$GIT_SVN_DIR/info/url");
3397f9df 1198
3397f9df
EW
1199}
1200
1201sub assert_svn_wc_clean {
a5e0cedc 1202 return if $_use_lib;
36f5b1f0 1203 my ($svn_rev) = @_;
3397f9df 1204 croak "$svn_rev is not an integer!\n" unless ($svn_rev =~ /^\d+$/);
ce4c8b24
EW
1205 my $lcr = svn_info('.')->{'Last Changed Rev'};
1206 if ($svn_rev != $lcr) {
1207 print STDERR "Checking for copy-tree ... ";
ce4c8b24
EW
1208 my @diff = grep(/^Index: /,(safe_qx(qw(svn diff),
1209 "-r$lcr:$svn_rev")));
1210 if (@diff) {
1211 croak "Nope! Expected r$svn_rev, got r$lcr\n";
1212 } else {
1213 print STDERR "OK!\n";
1214 }
3397f9df
EW
1215 }
1216 my @status = grep(!/^Performing status on external/,(`svn status`));
1217 @status = grep(!/^\s*$/,@status);
1218 if (scalar @status) {
1219 print STDERR "Tree ($SVN_WC) is not clean:\n";
1220 print STDERR $_ foreach @status;
1221 croak;
1222 }
cf52b8f0
EW
1223}
1224
a5e0cedc 1225sub get_tree_from_treeish {
cf52b8f0
EW
1226 my ($treeish) = @_;
1227 croak "Not a sha1: $treeish\n" unless $treeish =~ /^$sha1$/o;
1228 chomp(my $type = `git-cat-file -t $treeish`);
1229 my $expected;
1230 while ($type eq 'tag') {
1231 chomp(($treeish, $type) = `git-cat-file tag $treeish`);
1232 }
1233 if ($type eq 'commit') {
1234 $expected = (grep /^tree /,`git-cat-file commit $treeish`)[0];
1235 ($expected) = ($expected =~ /^tree ($sha1)$/);
1236 die "Unable to get tree from $treeish\n" unless $expected;
1237 } elsif ($type eq 'tree') {
1238 $expected = $treeish;
1239 } else {
1240 die "$treeish is a $type, expected tree, tag or commit\n";
1241 }
a5e0cedc
EW
1242 return $expected;
1243}
1244
1245sub assert_tree {
1246 return if $_use_lib;
1247 my ($treeish) = @_;
1248 my $expected = get_tree_from_treeish($treeish);
cf52b8f0 1249
cf52b8f0
EW
1250 my $tmpindex = $GIT_SVN_INDEX.'.assert-tmp';
1251 if (-e $tmpindex) {
1252 unlink $tmpindex or croak $!;
1253 }
a5e0cedc 1254 my $old_index = set_index($tmpindex);
36f5b1f0 1255 index_changes(1);
cf52b8f0 1256 chomp(my $tree = `git-write-tree`);
a5e0cedc 1257 restore_index($old_index);
cf52b8f0
EW
1258 if ($tree ne $expected) {
1259 croak "Tree mismatch, Got: $tree, Expected: $expected\n";
3397f9df 1260 }
36f5b1f0 1261 unlink $tmpindex;
3397f9df
EW
1262}
1263
1264sub parse_diff_tree {
1265 my $diff_fh = shift;
1266 local $/ = "\0";
1267 my $state = 'meta';
1268 my @mods;
1269 while (<$diff_fh>) {
1270 chomp $_; # this gets rid of the trailing "\0"
3397f9df
EW
1271 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
1272 $sha1\s($sha1)\s([MTCRAD])\d*$/xo) {
1273 push @mods, { mode_a => $1, mode_b => $2,
1274 sha1_b => $3, chg => $4 };
1275 if ($4 =~ /^(?:C|R)$/) {
1276 $state = 'file_a';
1277 } else {
1278 $state = 'file_b';
1279 }
1280 } elsif ($state eq 'file_a') {
cf52b8f0 1281 my $x = $mods[$#mods] or croak "Empty array\n";
3397f9df 1282 if ($x->{chg} !~ /^(?:C|R)$/) {
cf52b8f0 1283 croak "Error parsing $_, $x->{chg}\n";
3397f9df
EW
1284 }
1285 $x->{file_a} = $_;
1286 $state = 'file_b';
1287 } elsif ($state eq 'file_b') {
cf52b8f0 1288 my $x = $mods[$#mods] or croak "Empty array\n";
3397f9df 1289 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
cf52b8f0 1290 croak "Error parsing $_, $x->{chg}\n";
3397f9df
EW
1291 }
1292 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
cf52b8f0 1293 croak "Error parsing $_, $x->{chg}\n";
3397f9df
EW
1294 }
1295 $x->{file_b} = $_;
1296 $state = 'meta';
1297 } else {
cf52b8f0 1298 croak "Error parsing $_\n";
3397f9df
EW
1299 }
1300 }
cf7424b0 1301 close $diff_fh or croak $?;
cf52b8f0 1302
3397f9df
EW
1303 return \@mods;
1304}
1305
1306sub svn_check_prop_executable {
1307 my $m = shift;
cf52b8f0
EW
1308 return if -l $m->{file_b};
1309 if ($m->{mode_b} =~ /755$/) {
1310 chmod((0755 &~ umask),$m->{file_b}) or croak $!;
1311 if ($m->{mode_a} !~ /755$/) {
1312 sys(qw(svn propset svn:executable 1), $m->{file_b});
1313 }
1314 -x $m->{file_b} or croak "$m->{file_b} is not executable!\n";
3397f9df
EW
1315 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
1316 sys(qw(svn propdel svn:executable), $m->{file_b});
cf52b8f0
EW
1317 chmod((0644 &~ umask),$m->{file_b}) or croak $!;
1318 -x $m->{file_b} and croak "$m->{file_b} is executable!\n";
3397f9df
EW
1319 }
1320}
1321
1322sub svn_ensure_parent_path {
1323 my $dir_b = dirname(shift);
1324 svn_ensure_parent_path($dir_b) if ($dir_b ne File::Spec->curdir);
1325 mkpath([$dir_b]) unless (-d $dir_b);
1326 sys(qw(svn add -N), $dir_b) unless (-d "$dir_b/.svn");
1327}
1328
cf52b8f0
EW
1329sub precommit_check {
1330 my $mods = shift;
1331 my (%rm_file, %rmdir_check, %added_check);
1332
1333 my %o = ( D => 0, R => 1, C => 2, A => 3, M => 3, T => 3 );
1334 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1335 if ($m->{chg} eq 'R') {
1336 if (-d $m->{file_b}) {
1337 err_dir_to_file("$m->{file_a} => $m->{file_b}");
1338 }
1339 # dir/$file => dir/file/$file
1340 my $dirname = dirname($m->{file_b});
1341 while ($dirname ne File::Spec->curdir) {
1342 if ($dirname ne $m->{file_a}) {
1343 $dirname = dirname($dirname);
1344 next;
1345 }
1346 err_file_to_dir("$m->{file_a} => $m->{file_b}");
1347 }
1348 # baz/zzz => baz (baz is a file)
1349 $dirname = dirname($m->{file_a});
1350 while ($dirname ne File::Spec->curdir) {
1351 if ($dirname ne $m->{file_b}) {
1352 $dirname = dirname($dirname);
1353 next;
1354 }
1355 err_dir_to_file("$m->{file_a} => $m->{file_b}");
1356 }
1357 }
1358 if ($m->{chg} =~ /^(D|R)$/) {
1359 my $t = $1 eq 'D' ? 'file_b' : 'file_a';
1360 $rm_file{ $m->{$t} } = 1;
1361 my $dirname = dirname( $m->{$t} );
1362 my $basename = basename( $m->{$t} );
1363 $rmdir_check{$dirname}->{$basename} = 1;
1364 } elsif ($m->{chg} =~ /^(?:A|C)$/) {
1365 if (-d $m->{file_b}) {
1366 err_dir_to_file($m->{file_b});
1367 }
1368 my $dirname = dirname( $m->{file_b} );
1369 my $basename = basename( $m->{file_b} );
1370 $added_check{$dirname}->{$basename} = 1;
1371 while ($dirname ne File::Spec->curdir) {
1372 if ($rm_file{$dirname}) {
1373 err_file_to_dir($m->{file_b});
1374 }
1375 $dirname = dirname $dirname;
1376 }
1377 }
1378 }
1379 return (\%rmdir_check, \%added_check);
1380
1381 sub err_dir_to_file {
1382 my $file = shift;
1383 print STDERR "Node change from directory to file ",
1384 "is not supported by Subversion: ",$file,"\n";
1385 exit 1;
1386 }
1387 sub err_file_to_dir {
1388 my $file = shift;
1389 print STDERR "Node change from file to directory ",
1390 "is not supported by Subversion: ",$file,"\n";
1391 exit 1;
1392 }
1393}
1394
a5e0cedc
EW
1395
1396sub get_diff {
42d32870 1397 my ($from, $treeish) = @_;
36f5b1f0 1398 assert_tree($from);
ac8e0b91 1399 print "diff-tree $from $treeish\n";
3397f9df
EW
1400 my $pid = open my $diff_fh, '-|';
1401 defined $pid or croak $!;
1402 if ($pid == 0) {
162f4129
EW
1403 my @diff_tree = qw(git-diff-tree -z -r);
1404 if ($_cp_similarity) {
1405 push @diff_tree, "-C$_cp_similarity";
1406 } else {
1407 push @diff_tree, '-C';
1408 }
72942938
EW
1409 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
1410 push @diff_tree, "-l$_l" if defined $_l;
cf52b8f0 1411 exec(@diff_tree, $from, $treeish) or croak $!;
3397f9df 1412 }
a5e0cedc
EW
1413 return parse_diff_tree($diff_fh);
1414}
1415
1416sub svn_checkout_tree {
42d32870
EW
1417 my ($from, $treeish) = @_;
1418 my $mods = get_diff($from->{commit}, $treeish);
a5e0cedc 1419 return $mods unless (scalar @$mods);
cf52b8f0
EW
1420 my ($rm, $add) = precommit_check($mods);
1421
1422 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
1423 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
3397f9df
EW
1424 if ($m->{chg} eq 'C') {
1425 svn_ensure_parent_path( $m->{file_b} );
1426 sys(qw(svn cp), $m->{file_a}, $m->{file_b});
cf52b8f0 1427 apply_mod_line_blob($m);
3397f9df
EW
1428 svn_check_prop_executable($m);
1429 } elsif ($m->{chg} eq 'D') {
3397f9df
EW
1430 sys(qw(svn rm --force), $m->{file_b});
1431 } elsif ($m->{chg} eq 'R') {
1432 svn_ensure_parent_path( $m->{file_b} );
1433 sys(qw(svn mv --force), $m->{file_a}, $m->{file_b});
cf52b8f0 1434 apply_mod_line_blob($m);
3397f9df 1435 svn_check_prop_executable($m);
3397f9df 1436 } elsif ($m->{chg} eq 'M') {
cf52b8f0 1437 apply_mod_line_blob($m);
3397f9df
EW
1438 svn_check_prop_executable($m);
1439 } elsif ($m->{chg} eq 'T') {
1440 sys(qw(svn rm --force),$m->{file_b});
cf52b8f0 1441 apply_mod_line_blob($m);
0e8a002c 1442 sys(qw(svn add), $m->{file_b});
cf52b8f0 1443 svn_check_prop_executable($m);
3397f9df
EW
1444 } elsif ($m->{chg} eq 'A') {
1445 svn_ensure_parent_path( $m->{file_b} );
cf52b8f0 1446 apply_mod_line_blob($m);
0e8a002c 1447 sys(qw(svn add), $m->{file_b});
cf52b8f0 1448 svn_check_prop_executable($m);
3397f9df
EW
1449 } else {
1450 croak "Invalid chg: $m->{chg}\n";
1451 }
1452 }
cf52b8f0
EW
1453
1454 assert_tree($treeish);
1455 if ($_rmdir) { # remove empty directories
1456 handle_rmdir($rm, $add);
1457 }
1458 assert_tree($treeish);
1459 return $mods;
1460}
1461
a5e0cedc 1462sub libsvn_checkout_tree {
42d32870
EW
1463 my ($from, $treeish, $ed) = @_;
1464 my $mods = get_diff($from, $treeish);
a5e0cedc
EW
1465 return $mods unless (scalar @$mods);
1466 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
1467 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1468 my $f = $m->{chg};
1469 if (defined $o{$f}) {
1470 $ed->$f($m);
1471 } else {
1472 croak "Invalid change type: $f\n";
1473 }
1474 }
1475 $ed->rmdirs if $_rmdir;
1476 return $mods;
1477}
1478
cf52b8f0
EW
1479# svn ls doesn't work with respect to the current working tree, but what's
1480# in the repository. There's not even an option for it... *sigh*
1481# (added files don't show up and removed files remain in the ls listing)
1482sub svn_ls_current {
1483 my ($dir, $rm, $add) = @_;
1484 chomp(my @ls = safe_qx('svn','ls',$dir));
1485 my @ret = ();
1486 foreach (@ls) {
1487 s#/$##; # trailing slashes are evil
1488 push @ret, $_ unless $rm->{$dir}->{$_};
1489 }
1490 if (exists $add->{$dir}) {
1491 push @ret, keys %{$add->{$dir}};
1492 }
1493 return \@ret;
1494}
1495
1496sub handle_rmdir {
1497 my ($rm, $add) = @_;
1498
1499 foreach my $dir (sort {length $b <=> length $a} keys %$rm) {
1500 my $ls = svn_ls_current($dir, $rm, $add);
1501 next if (scalar @$ls);
1502 sys(qw(svn rm --force),$dir);
1503
1504 my $dn = dirname $dir;
1505 $rm->{ $dn }->{ basename $dir } = 1;
1506 $ls = svn_ls_current($dn, $rm, $add);
1507 while (scalar @$ls == 0 && $dn ne File::Spec->curdir) {
1508 sys(qw(svn rm --force),$dn);
1509 $dir = basename $dn;
1510 $dn = dirname $dn;
1511 $rm->{ $dn }->{ $dir } = 1;
1512 $ls = svn_ls_current($dn, $rm, $add);
3397f9df
EW
1513 }
1514 }
1515}
1516
a5e0cedc
EW
1517sub get_commit_message {
1518 my ($commit, $commit_msg) = (@_);
e17512f3 1519 my %log_msg = ( msg => '' );
ac8e0b91 1520 open my $msg, '>', $commit_msg or croak $!;
3397f9df
EW
1521
1522 chomp(my $type = `git-cat-file -t $commit`);
1523 if ($type eq 'commit') {
1524 my $pid = open my $msg_fh, '-|';
1525 defined $pid or croak $!;
1526
1527 if ($pid == 0) {
1528 exec(qw(git-cat-file commit), $commit) or croak $!;
1529 }
1530 my $in_msg = 0;
1531 while (<$msg_fh>) {
1532 if (!$in_msg) {
1533 $in_msg = 1 if (/^\s*$/);
df746c5a
EW
1534 } elsif (/^git-svn-id: /) {
1535 # skip this, we regenerate the correct one
1536 # on re-fetch anyways
3397f9df
EW
1537 } else {
1538 print $msg $_ or croak $!;
1539 }
1540 }
cf7424b0 1541 close $msg_fh or croak $?;
3397f9df
EW
1542 }
1543 close $msg or croak $!;
1544
1545 if ($_edit || ($type eq 'tree')) {
1546 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1547 system($editor, $commit_msg);
1548 }
ac8e0b91
EW
1549
1550 # file_to_s removes all trailing newlines, so just use chomp() here:
1551 open $msg, '<', $commit_msg or croak $!;
1552 { local $/; chomp($log_msg{msg} = <$msg>); }
1553 close $msg or croak $!;
1554
a5e0cedc
EW
1555 return \%log_msg;
1556}
1557
27e9fb8d
EW
1558sub set_svn_commit_env {
1559 if (defined $LC_ALL) {
1560 $ENV{LC_ALL} = $LC_ALL;
1561 } else {
1562 delete $ENV{LC_ALL};
1563 }
1564}
1565
a5e0cedc 1566sub svn_commit_tree {
42d32870 1567 my ($last, $commit) = @_;
a5e0cedc
EW
1568 my $commit_msg = "$GIT_SVN_DIR/.svn-commit.tmp.$$";
1569 my $log_msg = get_commit_message($commit, $commit_msg);
1570 my ($oneline) = ($log_msg->{msg} =~ /([^\n\r]+)/);
ac8e0b91
EW
1571 print "Committing $commit: $oneline\n";
1572
27e9fb8d 1573 set_svn_commit_env();
3397f9df 1574 my @ci_output = safe_qx(qw(svn commit -F),$commit_msg);
ce475dfc 1575 $ENV{LC_ALL} = 'C';
3397f9df 1576 unlink $commit_msg;
ce475dfc
EW
1577 my ($committed) = ($ci_output[$#ci_output] =~ /(\d+)/);
1578 if (!defined $committed) {
1579 my $out = join("\n",@ci_output);
1580 print STDERR "W: Trouble parsing \`svn commit' output:\n\n",
1581 $out, "\n\nAssuming English locale...";
1582 ($committed) = ($out =~ /^Committed revision \d+\./sm);
1583 defined $committed or die " FAILED!\n",
3397f9df 1584 "Commit output failed to parse committed revision!\n",
ce475dfc
EW
1585 print STDERR " OK\n";
1586 }
3397f9df 1587
e17512f3 1588 my @svn_up = qw(svn up);
3397f9df 1589 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
42d32870 1590 if ($_optimize_commits && ($committed == ($last->{revision} + 1))) {
ce475dfc 1591 push @svn_up, "-r$committed";
e17512f3
EW
1592 sys(@svn_up);
1593 my $info = svn_info('.');
1594 my $date = $info->{'Last Changed Date'} or die "Missing date\n";
ce475dfc
EW
1595 if ($info->{'Last Changed Rev'} != $committed) {
1596 croak "$info->{'Last Changed Rev'} != $committed\n"
e17512f3
EW
1597 }
1598 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
1599 /(\d{4})\-(\d\d)\-(\d\d)\s
1600 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
1601 or croak "Failed to parse date: $date\n";
a5e0cedc
EW
1602 $log_msg->{date} = "$tz $Y-$m-$d $H:$M:$S";
1603 $log_msg->{author} = $info->{'Last Changed Author'};
1604 $log_msg->{revision} = $committed;
1605 $log_msg->{msg} .= "\n";
42d32870
EW
1606 $log_msg->{parents} = [ $last->{commit} ];
1607 $log_msg->{commit} = git_commit($log_msg, $commit);
1608 return $log_msg;
e17512f3
EW
1609 }
1610 # resync immediately
42d32870 1611 push @svn_up, "-r$last->{revision}";
3397f9df 1612 sys(@svn_up);
42d32870 1613 return fetch("$committed=$commit");
3397f9df
EW
1614}
1615
9d55b41a
EW
1616sub rev_list_raw {
1617 my (@args) = @_;
1618 my $pid = open my $fh, '-|';
1619 defined $pid or croak $!;
1620 if (!$pid) {
1621 exec(qw/git-rev-list --pretty=raw/, @args) or croak $!;
1622 }
1623 return { fh => $fh, t => { } };
1624}
1625
1626sub next_rev_list_entry {
1627 my $rl = shift;
1628 my $fh = $rl->{fh};
1629 my $x = $rl->{t};
1630 while (<$fh>) {
1631 if (/^commit ($sha1)$/o) {
1632 if ($x->{c}) {
1633 $rl->{t} = { c => $1 };
1634 return $x;
1635 } else {
1636 $x->{c} = $1;
1637 }
1638 } elsif (/^parent ($sha1)$/o) {
1639 $x->{p}->{$1} = 1;
1640 } elsif (s/^ //) {
1641 $x->{m} ||= '';
1642 $x->{m} .= $_;
1643 }
1644 }
1645 return ($x != $rl->{t}) ? $x : undef;
1646}
1647
03823184
EW
1648# read the entire log into a temporary file (which is removed ASAP)
1649# and store the file handle + parser state
3397f9df
EW
1650sub svn_log_raw {
1651 my (@log_args) = @_;
03823184
EW
1652 my $log_fh = IO::File->new_tmpfile or croak $!;
1653 my $pid = fork;
3397f9df 1654 defined $pid or croak $!;
03823184
EW
1655 if (!$pid) {
1656 open STDOUT, '>&', $log_fh or croak $!;
3397f9df
EW
1657 exec (qw(svn log), @log_args) or croak $!
1658 }
03823184 1659 waitpid $pid, 0;
b8c92cad 1660 croak $? if $?;
03823184
EW
1661 seek $log_fh, 0, 0 or croak $!;
1662 return { state => 'sep', fh => $log_fh };
1663}
1664
1665sub next_log_entry {
1666 my $log = shift; # retval of svn_log_raw()
1667 my $ret = undef;
1668 my $fh = $log->{fh};
3397f9df 1669
03823184 1670 while (<$fh>) {
3397f9df
EW
1671 chomp;
1672 if (/^\-{72}$/) {
03823184
EW
1673 if ($log->{state} eq 'msg') {
1674 if ($ret->{lines}) {
1675 $ret->{msg} .= $_."\n";
1676 unless(--$ret->{lines}) {
1677 $log->{state} = 'sep';
ce6f3519
EW
1678 }
1679 } else {
1680 croak "Log parse error at: $_\n",
03823184 1681 $ret->{revision},
ce6f3519
EW
1682 "\n";
1683 }
1684 next;
1685 }
03823184 1686 if ($log->{state} ne 'sep') {
ce6f3519 1687 croak "Log parse error at: $_\n",
03823184
EW
1688 "state: $log->{state}\n",
1689 $ret->{revision},
ce6f3519
EW
1690 "\n";
1691 }
03823184 1692 $log->{state} = 'rev';
3397f9df
EW
1693
1694 # if we have an empty log message, put something there:
03823184
EW
1695 if ($ret) {
1696 $ret->{msg} ||= "\n";
1697 delete $ret->{lines};
1698 return $ret;
3397f9df
EW
1699 }
1700 next;
1701 }
03823184 1702 if ($log->{state} eq 'rev' && s/^r(\d+)\s*\|\s*//) {
3397f9df 1703 my $rev = $1;
ce6f3519
EW
1704 my ($author, $date, $lines) = split(/\s*\|\s*/, $_, 3);
1705 ($lines) = ($lines =~ /(\d+)/);
3397f9df
EW
1706 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
1707 /(\d{4})\-(\d\d)\-(\d\d)\s
1708 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
1709 or croak "Failed to parse date: $date\n";
03823184 1710 $ret = { revision => $rev,
3397f9df
EW
1711 date => "$tz $Y-$m-$d $H:$M:$S",
1712 author => $author,
ce6f3519 1713 lines => $lines,
03823184 1714 msg => '' };
a9612be2
EW
1715 if (defined $_authors && ! defined $users{$author}) {
1716 die "Author: $author not defined in ",
1717 "$_authors file\n";
1718 }
03823184 1719 $log->{state} = 'msg_start';
3397f9df
EW
1720 next;
1721 }
1722 # skip the first blank line of the message:
03823184
EW
1723 if ($log->{state} eq 'msg_start' && /^$/) {
1724 $log->{state} = 'msg';
1725 } elsif ($log->{state} eq 'msg') {
1726 if ($ret->{lines}) {
1727 $ret->{msg} .= $_."\n";
1728 unless (--$ret->{lines}) {
1729 $log->{state} = 'sep';
ce6f3519
EW
1730 }
1731 } else {
1732 croak "Log parse error at: $_\n",
03823184 1733 $ret->{revision},"\n";
ce6f3519 1734 }
3397f9df
EW
1735 }
1736 }
03823184 1737 return $ret;
3397f9df
EW
1738}
1739
1740sub svn_info {
1741 my $url = shift || $SVN_URL;
1742
1743 my $pid = open my $info_fh, '-|';
1744 defined $pid or croak $!;
1745
1746 if ($pid == 0) {
1747 exec(qw(svn info),$url) or croak $!;
1748 }
1749
1750 my $ret = {};
1751 # only single-lines seem to exist in svn info output
1752 while (<$info_fh>) {
1753 chomp $_;
e17512f3 1754 if (m#^([^:]+)\s*:\s*(\S.*)$#) {
3397f9df
EW
1755 $ret->{$1} = $2;
1756 push @{$ret->{-order}}, $1;
1757 }
1758 }
cf7424b0 1759 close $info_fh or croak $?;
3397f9df
EW
1760 return $ret;
1761}
1762
1763sub sys { system(@_) == 0 or croak $? }
1764
36f5b1f0
EW
1765sub eol_cp {
1766 my ($from, $to) = @_;
8a97e368 1767 my $es = svn_propget_base('svn:eol-style', $to);
36f5b1f0
EW
1768 open my $rfd, '<', $from or croak $!;
1769 binmode $rfd or croak $!;
1770 open my $wfd, '>', $to or croak $!;
1771 binmode $wfd or croak $!;
a5e0cedc
EW
1772 eol_cp_fd($rfd, $wfd, $es);
1773 close $rfd or croak $!;
1774 close $wfd or croak $!;
1775}
36f5b1f0 1776
a5e0cedc
EW
1777sub eol_cp_fd {
1778 my ($rfd, $wfd, $es) = @_;
1779 my $eol = defined $es ? $EOL{$es} : undef;
36f5b1f0 1780 my $buf;
4a393f2b 1781 use bytes;
36f5b1f0
EW
1782 while (1) {
1783 my ($r, $w, $t);
1784 defined($r = sysread($rfd, $buf, 4096)) or croak $!;
1785 return unless $r;
4a393f2b
EW
1786 if ($eol) {
1787 if ($buf =~ /\015$/) {
1788 my $c;
1789 defined($r = sysread($rfd,$c,1)) or croak $!;
1790 $buf .= $c if $r > 0;
1791 }
1792 $buf =~ s/(?:\015\012|\015|\012)/$eol/gs;
1793 $r = length($buf);
1794 }
36f5b1f0
EW
1795 for ($w = 0; $w < $r; $w += $t) {
1796 $t = syswrite($wfd, $buf, $r - $w, $w) or croak $!;
1797 }
1798 }
4a393f2b 1799 no bytes;
36f5b1f0
EW
1800}
1801
1802sub do_update_index {
1803 my ($z_cmd, $cmd, $no_text_base) = @_;
1804
1805 my $z = open my $p, '-|';
1806 defined $z or croak $!;
1807 unless ($z) { exec @$z_cmd or croak $! }
1808
1809 my $pid = open my $ui, '|-';
1810 defined $pid or croak $!;
1811 unless ($pid) {
1812 exec('git-update-index',"--$cmd",'-z','--stdin') or croak $!;
1813 }
1814 local $/ = "\0";
1815 while (my $x = <$p>) {
1816 chomp $x;
1817 if (!$no_text_base && lstat $x && ! -l _ &&
8a97e368 1818 svn_propget_base('svn:keywords', $x)) {
36f5b1f0
EW
1819 my $mode = -x _ ? 0755 : 0644;
1820 my ($v,$d,$f) = File::Spec->splitpath($x);
1821 my $tb = File::Spec->catfile($d, '.svn', 'tmp',
1822 'text-base',"$f.svn-base");
1823 $tb =~ s#^/##;
1824 unless (-f $tb) {
1825 $tb = File::Spec->catfile($d, '.svn',
1826 'text-base',"$f.svn-base");
1827 $tb =~ s#^/##;
1828 }
1829 unlink $x or croak $!;
1830 eol_cp($tb, $x);
1831 chmod(($mode &~ umask), $x) or croak $!;
1832 }
1833 print $ui $x,"\0";
1834 }
cf7424b0 1835 close $ui or croak $?;
36f5b1f0
EW
1836}
1837
1838sub index_changes {
a5e0cedc 1839 return if $_use_lib;
6c5cda89
EW
1840
1841 if (!-f "$GIT_SVN_DIR/info/exclude") {
1842 open my $fd, '>>', "$GIT_SVN_DIR/info/exclude" or croak $!;
1843 print $fd '.svn',"\n";
1844 close $fd or croak $!;
1845 }
36f5b1f0
EW
1846 my $no_text_base = shift;
1847 do_update_index([qw/git-diff-files --name-only -z/],
1848 'remove',
1849 $no_text_base);
1850 do_update_index([qw/git-ls-files -z --others/,
883d0a78 1851 "--exclude-from=$GIT_SVN_DIR/info/exclude"],
36f5b1f0
EW
1852 'add',
1853 $no_text_base);
3397f9df
EW
1854}
1855
1856sub s_to_file {
1857 my ($str, $file, $mode) = @_;
1858 open my $fd,'>',$file or croak $!;
1859 print $fd $str,"\n" or croak $!;
1860 close $fd or croak $!;
1861 chmod ($mode &~ umask, $file) if (defined $mode);
1862}
1863
1864sub file_to_s {
1865 my $file = shift;
1866 open my $fd,'<',$file or croak "$!: file: $file\n";
1867 local $/;
1868 my $ret = <$fd>;
1869 close $fd or croak $!;
1870 $ret =~ s/\s*$//s;
1871 return $ret;
1872}
1873
1874sub assert_revision_unknown {
42d32870
EW
1875 my $r = shift;
1876 if (my $c = revdb_get($REVDB, $r)) {
1877 croak "$r = $c already exists! Why are we refetching it?";
3397f9df
EW
1878 }
1879}
1880
ac749050
EW
1881sub trees_eq {
1882 my ($x, $y) = @_;
1883 my @x = safe_qx('git-cat-file','commit',$x);
1884 my @y = safe_qx('git-cat-file','commit',$y);
1885 if (($y[0] ne $x[0]) || $x[0] !~ /^tree $sha1\n$/
1886 || $y[0] !~ /^tree $sha1\n$/) {
1887 print STDERR "Trees not equal: $y[0] != $x[0]\n";
1888 return 0
1889 }
1890 return 1;
1891}
1892
3397f9df
EW
1893sub git_commit {
1894 my ($log_msg, @parents) = @_;
1895 assert_revision_unknown($log_msg->{revision});
69f0d91e
EW
1896 map_tree_joins() if (@_branch_from && !%tree_map);
1897
a5e0cedc
EW
1898 my (@tmp_parents, @exec_parents, %seen_parent);
1899 if (my $lparents = $log_msg->{parents}) {
1900 @tmp_parents = @$lparents
1901 }
3397f9df
EW
1902 # commit parents can be conditionally bound to a particular
1903 # svn revision via: "svn_revno=commit_sha1", filter them out here:
3397f9df
EW
1904 foreach my $p (@parents) {
1905 next unless defined $p;
1906 if ($p =~ /^(\d+)=($sha1_short)$/o) {
1907 if ($1 == $log_msg->{revision}) {
a5e0cedc 1908 push @tmp_parents, $2;
3397f9df
EW
1909 }
1910 } else {
a5e0cedc 1911 push @tmp_parents, $p if $p =~ /$sha1_short/o;
3397f9df
EW
1912 }
1913 }
a5e0cedc
EW
1914 my $tree = $log_msg->{tree};
1915 if (!defined $tree) {
1916 my $index = set_index($GIT_SVN_INDEX);
36f5b1f0 1917 index_changes();
a5e0cedc 1918 chomp($tree = `git-write-tree`);
b8c92cad 1919 croak $? if $?;
a5e0cedc
EW
1920 restore_index($index);
1921 }
1922 if (exists $tree_map{$tree}) {
c1927a85
EW
1923 foreach my $p (@{$tree_map{$tree}}) {
1924 my $skip;
1925 foreach (@tmp_parents) {
1926 # see if a common parent is found
1927 my $mb = eval {
1928 safe_qx('git-merge-base', $_, $p)
1929 };
1930 next if ($@ || $?);
1931 $skip = 1;
1932 last;
1933 }
1934 next if $skip;
1935 my ($url_p, $r_p, $uuid_p) = cmt_metadata($p);
1936 next if (($SVN_UUID eq $uuid_p) &&
1937 ($log_msg->{revision} > $r_p));
1938 next if (defined $url_p && defined $SVN_URL &&
1939 ($SVN_UUID eq $uuid_p) &&
1940 ($url_p eq $SVN_URL));
1941 push @tmp_parents, $p;
1942 }
a5e0cedc
EW
1943 }
1944 foreach (@tmp_parents) {
1945 next if $seen_parent{$_};
1946 $seen_parent{$_} = 1;
1947 push @exec_parents, $_;
1948 # MAXPARENT is defined to 16 in commit-tree.c:
1949 last if @exec_parents > 16;
1950 }
1951
1952 defined(my $pid = open my $out_fh, '-|') or croak $!;
1953 if ($pid == 0) {
3397f9df
EW
1954 my $msg_fh = IO::File->new_tmpfile or croak $!;
1955 print $msg_fh $log_msg->{msg}, "\ngit-svn-id: ",
1956 "$SVN_URL\@$log_msg->{revision}",
1ca72aef 1957 " $SVN_UUID\n" or croak $!;
3397f9df
EW
1958 $msg_fh->flush == 0 or croak $!;
1959 seek $msg_fh, 0, 0 or croak $!;
1ca72aef 1960 set_commit_env($log_msg);
3397f9df
EW
1961 my @exec = ('git-commit-tree',$tree);
1962 push @exec, '-p', $_ foreach @exec_parents;
1963 open STDIN, '<&', $msg_fh or croak $!;
3397f9df
EW
1964 exec @exec or croak $!;
1965 }
3397f9df 1966 chomp(my $commit = do { local $/; <$out_fh> });
a5e0cedc 1967 close $out_fh or croak $?;
3397f9df
EW
1968 if ($commit !~ /^$sha1$/o) {
1969 croak "Failed to commit, invalid sha1: $commit\n";
1970 }
2beb3cdd 1971 my @update_ref = ('git-update-ref',"refs/remotes/$GIT_SVN",$commit);
3397f9df 1972 if (my $primary_parent = shift @exec_parents) {
42d32870 1973 quiet_run(qw/git-rev-parse --verify/,"refs/remotes/$GIT_SVN^0");
1d52aba8 1974 push @update_ref, $primary_parent unless $?;
3397f9df
EW
1975 }
1976 sys(@update_ref);
42d32870
EW
1977 revdb_set($REVDB, $log_msg->{revision}, $commit);
1978
a5e0cedc 1979 # this output is read via pipe, do not change:
3397f9df 1980 print "r$log_msg->{revision} = $commit\n";
cf7424b0
EW
1981 check_repack();
1982 return $commit;
1983}
1984
1985sub check_repack {
dc5869c0
EW
1986 if ($_repack && (--$_repack_nr == 0)) {
1987 $_repack_nr = $_repack;
1988 sys("git repack $_repack_flags");
1989 }
3397f9df
EW
1990}
1991
a9612be2 1992sub set_commit_env {
1ca72aef 1993 my ($log_msg) = @_;
a9612be2 1994 my $author = $log_msg->{author};
a5e0cedc
EW
1995 if (!defined $author || length $author == 0) {
1996 $author = '(no author)';
1997 }
a9612be2 1998 my ($name,$email) = defined $users{$author} ? @{$users{$author}}
1ca72aef 1999 : ($author,"$author\@$SVN_UUID");
a9612be2
EW
2000 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
2001 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
2002 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_msg->{date};
2003}
2004
cf52b8f0
EW
2005sub apply_mod_line_blob {
2006 my $m = shift;
2007 if ($m->{mode_b} =~ /^120/) {
2008 blob_to_symlink($m->{sha1_b}, $m->{file_b});
2009 } else {
2010 blob_to_file($m->{sha1_b}, $m->{file_b});
2011 }
2012}
2013
3397f9df
EW
2014sub blob_to_symlink {
2015 my ($blob, $link) = @_;
2016 defined $link or croak "\$link not defined!\n";
2017 croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
cf52b8f0
EW
2018 if (-l $link || -f _) {
2019 unlink $link or croak $!;
2020 }
2021
3397f9df
EW
2022 my $dest = `git-cat-file blob $blob`; # no newline, so no chomp
2023 symlink $dest, $link or croak $!;
2024}
2025
2026sub blob_to_file {
2027 my ($blob, $file) = @_;
2028 defined $file or croak "\$file not defined!\n";
2029 croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
cf52b8f0
EW
2030 if (-l $file || -f _) {
2031 unlink $file or croak $!;
2032 }
2033
3397f9df
EW
2034 open my $blob_fh, '>', $file or croak "$!: $file\n";
2035 my $pid = fork;
2036 defined $pid or croak $!;
2037
2038 if ($pid == 0) {
2039 open STDOUT, '>&', $blob_fh or croak $!;
b8c92cad 2040 exec('git-cat-file','blob',$blob) or croak $!;
3397f9df
EW
2041 }
2042 waitpid $pid, 0;
2043 croak $? if $?;
2044
2045 close $blob_fh or croak $!;
2046}
2047
2048sub safe_qx {
2049 my $pid = open my $child, '-|';
2050 defined $pid or croak $!;
2051 if ($pid == 0) {
b8c92cad 2052 exec(@_) or croak $!;
3397f9df
EW
2053 }
2054 my @ret = (<$child>);
2055 close $child or croak $?;
2056 die $? if $?; # just in case close didn't error out
2057 return wantarray ? @ret : join('',@ret);
2058}
2059
1d52aba8
EW
2060sub svn_compat_check {
2061 my @co_help = safe_qx(qw(svn co -h));
2062 unless (grep /ignore-externals/,@co_help) {
3397f9df
EW
2063 print STDERR "W: Installed svn version does not support ",
2064 "--ignore-externals\n";
2065 $_no_ignore_ext = 1;
2066 }
1d52aba8
EW
2067 if (grep /usage: checkout URL\[\@REV\]/,@co_help) {
2068 $_svn_co_url_revs = 1;
2069 }
8a97e368
EW
2070 if (grep /\[TARGET\[\@REV\]\.\.\.\]/, `svn propget -h`) {
2071 $_svn_pg_peg_revs = 1;
2072 }
7317ed90
EW
2073
2074 # I really, really hope nobody hits this...
2075 unless (grep /stop-on-copy/, (safe_qx(qw(svn log -h)))) {
2076 print STDERR <<'';
2077W: The installed svn version does not support the --stop-on-copy flag in
2078 the log command.
2079 Lets hope the directory you're tracking is not a branch or tag
2080 and was never moved within the repository...
2081
2082 $_no_stop_copy = 1;
2083 }
1d52aba8
EW
2084}
2085
2086# *sigh*, new versions of svn won't honor -r<rev> without URL@<rev>,
2087# (and they won't honor URL@<rev> without -r<rev>, too!)
2088sub svn_cmd_checkout {
2089 my ($url, $rev, $dir) = @_;
2090 my @cmd = ('svn','co', "-r$rev");
2091 push @cmd, '--ignore-externals' unless $_no_ignore_ext;
2092 $url .= "\@$rev" if $_svn_co_url_revs;
2093 sys(@cmd, $url, $dir);
3397f9df 2094}
2beb3cdd
EW
2095
2096sub check_upgrade_needed {
cf7424b0 2097 if (!-r $REVDB) {
1a82e793 2098 -d $GIT_SVN_DIR or mkpath([$GIT_SVN_DIR]);
cf7424b0
EW
2099 open my $fh, '>>',$REVDB or croak $!;
2100 close $fh;
2101 }
2beb3cdd
EW
2102 my $old = eval {
2103 my $pid = open my $child, '-|';
2104 defined $pid or croak $!;
2105 if ($pid == 0) {
2106 close STDERR;
b8c92cad 2107 exec('git-rev-parse',"$GIT_SVN-HEAD") or croak $!;
2beb3cdd
EW
2108 }
2109 my @ret = (<$child>);
2110 close $child or croak $?;
2111 die $? if $?; # just in case close didn't error out
2112 return wantarray ? @ret : join('',@ret);
2113 };
2114 return unless $old;
2115 my $head = eval { safe_qx('git-rev-parse',"refs/remotes/$GIT_SVN") };
2116 if ($@ || !$head) {
2117 print STDERR "Please run: $0 rebuild --upgrade\n";
2118 exit 1;
2119 }
2120}
2121
69f0d91e
EW
2122# fills %tree_map with a reverse mapping of trees to commits. Useful
2123# for finding parents to commit on.
2124sub map_tree_joins {
098749d9 2125 my %seen;
69f0d91e
EW
2126 foreach my $br (@_branch_from) {
2127 my $pid = open my $pipe, '-|';
2128 defined $pid or croak $!;
2129 if ($pid == 0) {
098749d9 2130 exec(qw(git-rev-list --topo-order --pretty=raw), $br)
b8c92cad 2131 or croak $!;
69f0d91e
EW
2132 }
2133 while (<$pipe>) {
2134 if (/^commit ($sha1)$/o) {
2135 my $commit = $1;
098749d9
EW
2136
2137 # if we've seen a commit,
2138 # we've seen its parents
2139 last if $seen{$commit};
69f0d91e
EW
2140 my ($tree) = (<$pipe> =~ /^tree ($sha1)$/o);
2141 unless (defined $tree) {
2142 die "Failed to parse commit $commit\n";
2143 }
2144 push @{$tree_map{$tree}}, $commit;
098749d9 2145 $seen{$commit} = 1;
69f0d91e
EW
2146 }
2147 }
098749d9 2148 close $pipe; # we could be breaking the pipe early
69f0d91e
EW
2149 }
2150}
2151
bf78b1d8
EW
2152sub load_all_refs {
2153 if (@_branch_from) {
2154 print STDERR '--branch|-b parameters are ignored when ',
2155 "--branch-all-refs|-B is passed\n";
2156 }
2157
2158 # don't worry about rev-list on non-commit objects/tags,
2159 # it shouldn't blow up if a ref is a blob or tree...
2160 chomp(@_branch_from = `git-rev-parse --symbolic --all`);
2161}
2162
eeb0abe0
EW
2163# '<svn username> = real-name <email address>' mapping based on git-svnimport:
2164sub load_authors {
2165 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
2166 while (<$authors>) {
2167 chomp;
2168 next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
2169 my ($user, $name, $email) = ($1, $2, $3);
2170 $users{$user} = [$name, $email];
2171 }
2172 close $authors or croak $!;
2173}
2174
79bb8d88
EW
2175sub rload_authors {
2176 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
2177 while (<$authors>) {
2178 chomp;
2179 next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
2180 my ($user, $name, $email) = ($1, $2, $3);
2181 $rusers{"$name <$email>"} = $user;
2182 }
2183 close $authors or croak $!;
2184}
2185
8a97e368
EW
2186sub svn_propget_base {
2187 my ($p, $f) = @_;
2188 $f .= '@BASE' if $_svn_pg_peg_revs;
2189 return safe_qx(qw/svn propget/, $p, $f);
2190}
2191
9d55b41a
EW
2192sub git_svn_each {
2193 my $sub = shift;
2194 foreach (`git-rev-parse --symbolic --all`) {
2195 next unless s#^refs/remotes/##;
2196 chomp $_;
2197 next unless -f "$GIT_DIR/svn/$_/info/url";
2198 &$sub($_);
2199 }
2200}
2201
42d32870
EW
2202sub migrate_revdb {
2203 git_svn_each(sub {
2204 my $id = shift;
2205 defined(my $pid = fork) or croak $!;
2206 if (!$pid) {
2207 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
2208 init_vars();
2209 exit 0 if -r $REVDB;
2210 print "Upgrading svn => git mapping...\n";
1a82e793 2211 -d $GIT_SVN_DIR or mkpath([$GIT_SVN_DIR]);
42d32870
EW
2212 open my $fh, '>>',$REVDB or croak $!;
2213 close $fh;
2214 rebuild();
2215 print "Done upgrading. You may now delete the ",
2216 "deprecated $GIT_SVN_DIR/revs directory\n";
2217 exit 0;
2218 }
2219 waitpid $pid, 0;
2220 croak $? if $?;
2221 });
2222}
2223
883d0a78 2224sub migration_check {
42d32870 2225 migrate_revdb() unless (-e $REVDB);
883d0a78
EW
2226 return if (-d "$GIT_DIR/svn" || !-d $GIT_DIR);
2227 print "Upgrading repository...\n";
2228 unless (-d "$GIT_DIR/svn") {
2229 mkdir "$GIT_DIR/svn" or croak $!;
2230 }
2231 print "Data from a previous version of git-svn exists, but\n\t",
2232 "$GIT_SVN_DIR\n\t(required for this version ",
2233 "($VERSION) of git-svn) does not.\n";
2234
2235 foreach my $x (`git-rev-parse --symbolic --all`) {
2236 next unless $x =~ s#^refs/remotes/##;
2237 chomp $x;
2238 next unless -f "$GIT_DIR/$x/info/url";
2239 my $u = eval { file_to_s("$GIT_DIR/$x/info/url") };
2240 next unless $u;
2241 my $dn = dirname("$GIT_DIR/svn/$x");
2242 mkpath([$dn]) unless -d $dn;
2243 rename "$GIT_DIR/$x", "$GIT_DIR/svn/$x" or croak "$!: $x";
883d0a78 2244 }
42d32870 2245 migrate_revdb() if (-d $GIT_SVN_DIR && !-w $REVDB);
883d0a78
EW
2246 print "Done upgrading.\n";
2247}
2248
9d55b41a 2249sub find_rev_before {
42d32870
EW
2250 my ($r, $id, $eq_ok) = @_;
2251 my $f = "$GIT_DIR/svn/$id/.rev_db";
cf7424b0
EW
2252 return (undef,undef) unless -r $f;
2253 --$r unless $eq_ok;
42d32870
EW
2254 while ($r > 0) {
2255 if (my $c = revdb_get($f, $r)) {
2256 return ($r, $c);
2257 }
2258 --$r;
9d55b41a
EW
2259 }
2260 return (undef, undef);
2261}
2262
b8c92cad
EW
2263sub init_vars {
2264 $GIT_SVN ||= $ENV{GIT_SVN_ID} || 'git-svn';
2265 $GIT_SVN_DIR = "$GIT_DIR/svn/$GIT_SVN";
42d32870 2266 $REVDB = "$GIT_SVN_DIR/.rev_db";
b8c92cad
EW
2267 $GIT_SVN_INDEX = "$GIT_SVN_DIR/index";
2268 $SVN_URL = undef;
b8c92cad 2269 $SVN_WC = "$GIT_SVN_DIR/tree";
c1927a85 2270 %tree_map = ();
b8c92cad
EW
2271}
2272
2273# convert GetOpt::Long specs for use by git-repo-config
2274sub read_repo_config {
2275 return unless -d $GIT_DIR;
2276 my $opts = shift;
2277 foreach my $o (keys %$opts) {
2278 my $v = $opts->{$o};
2279 my ($key) = ($o =~ /^([a-z\-]+)/);
2280 $key =~ s/-//g;
2281 my $arg = 'git-repo-config';
2282 $arg .= ' --int' if ($o =~ /[:=]i$/);
2283 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
2284 if (ref $v eq 'ARRAY') {
2285 chomp(my @tmp = `$arg --get-all svn.$key`);
2286 @$v = @tmp if @tmp;
2287 } else {
2288 chomp(my $tmp = `$arg --get svn.$key`);
2289 if ($tmp && !($arg =~ / --bool / && $tmp eq 'false')) {
2290 $$v = $tmp;
2291 }
2292 }
2293 }
2294}
2295
dc5869c0
EW
2296sub set_default_vals {
2297 if (defined $_repack) {
2298 $_repack = 1000 if ($_repack <= 0);
2299 $_repack_nr = $_repack;
cf7424b0 2300 $_repack_flags ||= '-d';
dc5869c0
EW
2301 }
2302}
2303
9d55b41a
EW
2304sub read_grafts {
2305 my $gr_file = shift;
2306 my ($grafts, $comments) = ({}, {});
2307 if (open my $fh, '<', $gr_file) {
2308 my @tmp;
2309 while (<$fh>) {
2310 if (/^($sha1)\s+/) {
2311 my $c = $1;
2312 if (@tmp) {
2313 @{$comments->{$c}} = @tmp;
2314 @tmp = ();
2315 }
2316 foreach my $p (split /\s+/, $_) {
2317 $grafts->{$c}->{$p} = 1;
2318 }
2319 } else {
2320 push @tmp, $_;
2321 }
2322 }
2323 close $fh or croak $!;
2324 @{$comments->{'END'}} = @tmp if @tmp;
2325 }
2326 return ($grafts, $comments);
2327}
2328
2329sub write_grafts {
2330 my ($grafts, $comments, $gr_file) = @_;
2331
2332 open my $fh, '>', $gr_file or croak $!;
2333 foreach my $c (sort keys %$grafts) {
2334 if ($comments->{$c}) {
2335 print $fh $_ foreach @{$comments->{$c}};
2336 }
2337 my $p = $grafts->{$c};
c1927a85 2338 my %x; # real parents
9d55b41a
EW
2339 delete $p->{$c}; # commits are not self-reproducing...
2340 my $pid = open my $ch, '-|';
2341 defined $pid or croak $!;
2342 if (!$pid) {
2343 exec(qw/git-cat-file commit/, $c) or croak $!;
2344 }
2345 while (<$ch>) {
c1927a85
EW
2346 if (/^parent ($sha1)/) {
2347 $x{$1} = $p->{$1} = 1;
9d55b41a 2348 } else {
c1927a85 2349 last unless /^\S/;
9d55b41a
EW
2350 }
2351 }
2352 close $ch; # breaking the pipe
c1927a85
EW
2353
2354 # if real parents are the only ones in the grafts, drop it
2355 next if join(' ',sort keys %$p) eq join(' ',sort keys %x);
2356
2357 my (@ip, @jp, $mb);
2358 my %del = %x;
2359 @ip = @jp = keys %$p;
2360 foreach my $i (@ip) {
2361 next if $del{$i} || $p->{$i} == 2;
2362 foreach my $j (@jp) {
2363 next if $i eq $j || $del{$j} || $p->{$j} == 2;
2364 $mb = eval { safe_qx('git-merge-base',$i,$j) };
2365 next unless $mb;
2366 chomp $mb;
2367 next if $x{$mb};
2368 if ($mb eq $j) {
2369 delete $p->{$i};
2370 $del{$i} = 1;
2371 } elsif ($mb eq $i) {
2372 delete $p->{$j};
2373 $del{$j} = 1;
2374 }
2375 }
2376 }
2377
2378 # if real parents are the only ones in the grafts, drop it
2379 next if join(' ',sort keys %$p) eq join(' ',sort keys %x);
2380
9d55b41a
EW
2381 print $fh $c, ' ', join(' ', sort keys %$p),"\n";
2382 }
2383 if ($comments->{'END'}) {
2384 print $fh $_ foreach @{$comments->{'END'}};
2385 }
2386 close $fh or croak $!;
2387}
2388
2389sub read_url_paths {
2390 my $l_map = {};
2391 git_svn_each(sub { my $x = shift;
6c5cda89
EW
2392 my $url = file_to_s("$GIT_DIR/svn/$x/info/url");
2393 my ($u, $p) = repo_path_split($url);
9d55b41a
EW
2394 $l_map->{$u}->{$p} = $x;
2395 });
2396 return $l_map;
2397}
2398
79bb8d88 2399sub extract_metadata {
c1927a85 2400 my $id = shift or return (undef, undef, undef);
79bb8d88
EW
2401 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
2402 \s([a-f\d\-]+)$/x);
2403 if (!$rev || !$uuid || !$url) {
2404 # some of the original repositories I made had
2405 # indentifiers like this:
2406 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
2407 }
2408 return ($url, $rev, $uuid);
2409}
2410
c1927a85
EW
2411sub cmt_metadata {
2412 return extract_metadata((grep(/^git-svn-id: /,
2413 safe_qx(qw/git-cat-file commit/, shift)))[-1]);
2414}
2415
2416sub get_commit_time {
2417 my $cmt = shift;
2418 defined(my $pid = open my $fh, '-|') or croak $!;
2419 if (!$pid) {
2420 exec qw/git-rev-list --pretty=raw -n1/, $cmt or croak $!;
2421 }
2422 while (<$fh>) {
2423 /^committer\s(?:.+) (\d+) ([\-\+]?\d+)$/ or next;
2424 my ($s, $tz) = ($1, $2);
2425 if ($tz =~ s/^\+//) {
2426 $s += tz_to_s_offset($tz);
2427 } elsif ($tz =~ s/^\-//) {
2428 $s -= tz_to_s_offset($tz);
2429 }
2430 close $fh;
2431 return $s;
2432 }
2433 die "Can't get commit time for commit: $cmt\n";
2434}
2435
79bb8d88
EW
2436sub tz_to_s_offset {
2437 my ($tz) = @_;
2438 $tz =~ s/(\d\d)$//;
2439 return ($1 * 60) + ($tz * 3600);
2440}
2441
2442sub setup_pager { # translated to Perl from pager.c
2443 return unless (-t *STDOUT);
2444 my $pager = $ENV{PAGER};
2445 if (!defined $pager) {
2446 $pager = 'less';
2447 } elsif (length $pager == 0 || $pager eq 'cat') {
2448 return;
2449 }
2450 pipe my $rfd, my $wfd or return;
2451 defined(my $pid = fork) or croak $!;
2452 if (!$pid) {
2453 open STDOUT, '>&', $wfd or croak $!;
2454 return;
2455 }
2456 open STDIN, '<&', $rfd or croak $!;
2457 $ENV{LESS} ||= '-S';
2458 exec $pager or croak "Can't run pager: $!\n";;
2459}
2460
2461sub get_author_info {
2462 my ($dest, $author, $t, $tz) = @_;
2463 $author =~ s/(?:^\s*|\s*$)//g;
c0d48222 2464 $dest->{a_raw} = $author;
79bb8d88
EW
2465 my $_a;
2466 if ($_authors) {
2467 $_a = $rusers{$author} || undef;
2468 }
2469 if (!$_a) {
2470 ($_a) = ($author =~ /<([^>]+)\@[^>]+>$/);
2471 }
2472 $dest->{t} = $t;
2473 $dest->{tz} = $tz;
2474 $dest->{a} = $_a;
2475 # Date::Parse isn't in the standard Perl distro :(
2476 if ($tz =~ s/^\+//) {
2477 $t += tz_to_s_offset($tz);
2478 } elsif ($tz =~ s/^\-//) {
2479 $t -= tz_to_s_offset($tz);
2480 }
2481 $dest->{t_utc} = $t;
2482}
2483
2484sub process_commit {
2485 my ($c, $r_min, $r_max, $defer) = @_;
2486 if (defined $r_min && defined $r_max) {
2487 if ($r_min == $c->{r} && $r_min == $r_max) {
2488 show_commit($c);
2489 return 0;
2490 }
2491 return 1 if $r_min == $r_max;
2492 if ($r_min < $r_max) {
2493 # we need to reverse the print order
2494 return 0 if (defined $_limit && --$_limit < 0);
2495 push @$defer, $c;
2496 return 1;
2497 }
2498 if ($r_min != $r_max) {
2499 return 1 if ($r_min < $c->{r});
2500 return 1 if ($r_max > $c->{r});
2501 }
2502 }
2503 return 0 if (defined $_limit && --$_limit < 0);
2504 show_commit($c);
2505 return 1;
2506}
2507
2508sub show_commit {
2509 my $c = shift;
2510 if ($_oneline) {
2511 my $x = "\n";
2512 if (my $l = $c->{l}) {
2513 while ($l->[0] =~ /^\s*$/) { shift @$l }
2514 $x = $l->[0];
2515 }
2516 $_l_fmt ||= 'A' . length($c->{r});
2517 print 'r',pack($_l_fmt, $c->{r}),' | ';
2518 print "$c->{c} | " if $_show_commit;
2519 print $x;
2520 } else {
2521 show_commit_normal($c);
2522 }
2523}
2524
2525sub show_commit_normal {
2526 my ($c) = @_;
2527 print '-' x72, "\nr$c->{r} | ";
2528 print "$c->{c} | " if $_show_commit;
2529 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
2530 localtime($c->{t_utc})), ' | ';
2531 my $nr_line = 0;
2532
2533 if (my $l = $c->{l}) {
2534 while ($l->[$#$l] eq "\n" && $l->[($#$l - 1)] eq "\n") {
2535 pop @$l;
2536 }
2537 $nr_line = scalar @$l;
2538 if (!$nr_line) {
2539 print "1 line\n\n\n";
2540 } else {
2541 if ($nr_line == 1) {
2542 $nr_line = '1 line';
2543 } else {
2544 $nr_line .= ' lines';
2545 }
2546 print $nr_line, "\n\n";
2547 print $_ foreach @$l;
2548 }
2549 } else {
2550 print "1 line\n\n";
2551
2552 }
2553 foreach my $x (qw/raw diff/) {
2554 if ($c->{$x}) {
2555 print "\n";
2556 print $_ foreach @{$c->{$x}}
2557 }
2558 }
2559}
2560
a5e0cedc
EW
2561sub libsvn_load {
2562 return unless $_use_lib;
2563 $_use_lib = eval {
2564 require SVN::Core;
dc62e25c
EW
2565 if ($SVN::Core::VERSION lt '1.1.0') {
2566 die "Need SVN::Core 1.1.0 or better ",
a5e0cedc
EW
2567 "(got $SVN::Core::VERSION) ",
2568 "Falling back to command-line svn\n";
2569 }
2570 require SVN::Ra;
2571 require SVN::Delta;
2572 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
2573 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2574 $SVN::Node::dir.$SVN::Node::unknown.
2575 $SVN::Node::none.$SVN::Node::file.
2576 $SVN::Node::dir.$SVN::Node::unknown;
2577 1;
2578 };
2579}
2580
2581sub libsvn_connect {
2582 my ($url) = @_;
2583 my $auth = SVN::Core::auth_open([SVN::Client::get_simple_provider(),
2584 SVN::Client::get_ssl_server_trust_file_provider(),
2585 SVN::Client::get_username_provider()]);
2586 my $s = eval { SVN::Ra->new(url => $url, auth => $auth) };
2587 return $s;
2588}
2589
2590sub libsvn_get_file {
2591 my ($gui, $f, $rev) = @_;
2592 my $p = $f;
2593 return unless ($p =~ s#^\Q$SVN_PATH\E/?##);
2594
968bdf1f 2595 my ($hash, $pid, $in, $out);
a5e0cedc 2596 my $pool = SVN::Pool->new;
968bdf1f
EW
2597 defined($pid = open3($in, $out, '>&STDERR',
2598 qw/git-hash-object -w --stdin/)) or croak $!;
dc62e25c
EW
2599 # redirect STDOUT for SVN 1.1.x compatibility
2600 open my $stdout, '>&', \*STDOUT or croak $!;
2601 open STDOUT, '>&', $in or croak $!;
2602 $| = 1; # not sure if this is necessary, better safe than sorry...
2603 my ($r, $props) = $SVN->get_file($f, $rev, \*STDOUT, $pool);
968bdf1f 2604 $in->flush == 0 or croak $!;
dc62e25c 2605 open STDOUT, '>&', $stdout or croak $!;
968bdf1f 2606 close $in or croak $!;
dc62e25c 2607 close $stdout or croak $!;
a5e0cedc 2608 $pool->clear;
968bdf1f
EW
2609 chomp($hash = do { local $/; <$out> });
2610 close $out or croak $!;
2611 waitpid $pid, 0;
2612 $hash =~ /^$sha1$/o or die "not a sha1: $hash\n";
2613
2614 my $mode = exists $props->{'svn:executable'} ? '100755' : '100644';
a5e0cedc
EW
2615 if (exists $props->{'svn:special'}) {
2616 $mode = '120000';
968bdf1f 2617 my $link = `git-cat-file blob $hash`;
a5e0cedc
EW
2618 $link =~ s/^link // or die "svn:special file with contents: <",
2619 $link, "> is not understood\n";
968bdf1f
EW
2620 defined($pid = open3($in, $out, '>&STDERR',
2621 qw/git-hash-object -w --stdin/)) or croak $!;
2622 print $in $link;
2623 $in->flush == 0 or croak $!;
2624 close $in or croak $!;
2625 chomp($hash = do { local $/; <$out> });
2626 close $out or croak $!;
2627 waitpid $pid, 0;
2628 $hash =~ /^$sha1$/o or die "not a sha1: $hash\n";
a5e0cedc 2629 }
a5e0cedc 2630 print $gui $mode,' ',$hash,"\t",$p,"\0" or croak $!;
a5e0cedc
EW
2631}
2632
2633sub libsvn_log_entry {
2634 my ($rev, $author, $date, $msg, $parents) = @_;
2635 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2636 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x)
2637 or die "Unable to parse date: $date\n";
2638 if (defined $_authors && ! defined $users{$author}) {
2639 die "Author: $author not defined in $_authors file\n";
2640 }
2641 return { revision => $rev, date => "+0000 $Y-$m-$d $H:$M:$S",
2642 author => $author, msg => $msg."\n", parents => $parents || [] }
2643}
2644
2645sub process_rm {
2646 my ($gui, $last_commit, $f) = @_;
2647 $f =~ s#^\Q$SVN_PATH\E/?## or return;
2648 # remove entire directories.
2649 if (safe_qx('git-ls-tree',$last_commit,'--',$f) =~ /^040000 tree/) {
2650 defined(my $pid = open my $ls, '-|') or croak $!;
2651 if (!$pid) {
2652 exec(qw/git-ls-tree -r --name-only -z/,
2653 $last_commit,'--',$f) or croak $!;
2654 }
2655 local $/ = "\0";
2656 while (<$ls>) {
2657 print $gui '0 ',0 x 40,"\t",$_ or croak $!;
2658 }
cf7424b0 2659 close $ls or croak $?;
a5e0cedc
EW
2660 } else {
2661 print $gui '0 ',0 x 40,"\t",$f,"\0" or croak $!;
2662 }
2663}
2664
2665sub libsvn_fetch {
2666 my ($last_commit, $paths, $rev, $author, $date, $msg) = @_;
2667 open my $gui, '| git-update-index -z --index-info' or croak $!;
2668 my @amr;
2669 foreach my $f (keys %$paths) {
2670 my $m = $paths->{$f}->action();
2671 $f =~ s#^/+##;
2672 if ($m =~ /^[DR]$/) {
2673 process_rm($gui, $last_commit, $f);
2674 next if $m eq 'D';
2675 # 'R' can be file replacements, too, right?
2676 }
2677 my $pool = SVN::Pool->new;
2678 my $t = $SVN->check_path($f, $rev, $pool);
2679 if ($t == $SVN::Node::file) {
2680 if ($m =~ /^[AMR]$/) {
2681 push @amr, $f;
2682 } else {
2683 die "Unrecognized action: $m, ($f r$rev)\n";
2684 }
2685 }
2686 $pool->clear;
2687 }
2688 libsvn_get_file($gui, $_, $rev) foreach (@amr);
cf7424b0 2689 close $gui or croak $?;
a5e0cedc
EW
2690 return libsvn_log_entry($rev, $author, $date, $msg, [$last_commit]);
2691}
2692
2693sub svn_grab_base_rev {
2694 defined(my $pid = open my $fh, '-|') or croak $!;
2695 if (!$pid) {
2696 open my $null, '>', '/dev/null' or croak $!;
2697 open STDERR, '>&', $null or croak $!;
2698 exec qw/git-rev-parse --verify/,"refs/remotes/$GIT_SVN^0"
2699 or croak $!;
2700 }
2701 chomp(my $c = do { local $/; <$fh> });
2702 close $fh;
2703 if (defined $c && length $c) {
c1927a85 2704 my ($url, $rev, $uuid) = cmt_metadata($c);
a5e0cedc
EW
2705 return ($rev, $c);
2706 }
2707 return (undef, undef);
2708}
2709
2710sub libsvn_parse_revision {
2711 my $base = shift;
2712 my $head = $SVN->get_latest_revnum();
2713 if (!defined $_revision || $_revision eq 'BASE:HEAD') {
2714 return ($base + 1, $head) if (defined $base);
2715 return (0, $head);
2716 }
2717 return ($1, $2) if ($_revision =~ /^(\d+):(\d+)$/);
2718 return ($_revision, $_revision) if ($_revision =~ /^\d+$/);
2719 if ($_revision =~ /^BASE:(\d+)$/) {
2720 return ($base + 1, $1) if (defined $base);
2721 return (0, $head);
2722 }
2723 return ($1, $head) if ($_revision =~ /^(\d+):HEAD$/);
2724 die "revision argument: $_revision not understood by git-svn\n",
2725 "Try using the command-line svn client instead\n";
2726}
2727
2728sub libsvn_traverse {
2729 my ($gui, $pfx, $path, $rev) = @_;
2730 my $cwd = "$pfx/$path";
2731 my $pool = SVN::Pool->new;
2732 $cwd =~ s#^/+##g;
2733 my ($dirent, $r, $props) = $SVN->get_dir($cwd, $rev, $pool);
2734 foreach my $d (keys %$dirent) {
2735 my $t = $dirent->{$d}->kind;
2736 if ($t == $SVN::Node::dir) {
2737 libsvn_traverse($gui, $cwd, $d, $rev);
2738 } elsif ($t == $SVN::Node::file) {
2739 libsvn_get_file($gui, "$cwd/$d", $rev);
2740 }
2741 }
2742 $pool->clear;
2743}
2744
2745sub libsvn_traverse_ignore {
2746 my ($fh, $path, $r) = @_;
2747 $path =~ s#^/+##g;
2748 my $pool = SVN::Pool->new;
2749 my ($dirent, undef, $props) = $SVN->get_dir($path, $r, $pool);
2750 my $p = $path;
2751 $p =~ s#^\Q$SVN_PATH\E/?##;
2752 print $fh length $p ? "\n# $p\n" : "\n# /\n";
2753 if (my $s = $props->{'svn:ignore'}) {
2754 $s =~ s/[\r\n]+/\n/g;
2755 chomp $s;
2756 if (length $p == 0) {
2757 $s =~ s#\n#\n/$p#g;
2758 print $fh "/$s\n";
2759 } else {
2760 $s =~ s#\n#\n/$p/#g;
2761 print $fh "/$p/$s\n";
2762 }
2763 }
2764 foreach (sort keys %$dirent) {
2765 next if $dirent->{$_}->kind != $SVN::Node::dir;
2766 libsvn_traverse_ignore($fh, "$path/$_", $r);
2767 }
2768 $pool->clear;
2769}
2770
42d32870
EW
2771sub revisions_eq {
2772 my ($path, $r0, $r1) = @_;
2773 return 1 if $r0 == $r1;
2774 my $nr = 0;
2775 if ($_use_lib) {
2776 # should be OK to use Pool here (r1 - r0) should be small
2777 my $pool = SVN::Pool->new;
dc62e25c
EW
2778 libsvn_get_log($SVN, "/$path", $r0, $r1,
2779 0, 1, 1, sub {$nr++}, $pool);
42d32870
EW
2780 $pool->clear;
2781 } else {
2782 my ($url, undef) = repo_path_split($SVN_URL);
2783 my $svn_log = svn_log_raw("$url/$path","-r$r0:$r1");
2784 while (next_log_entry($svn_log)) { $nr++ }
2785 close $svn_log->{fh};
2786 }
2787 return 0 if ($nr > 1);
2788 return 1;
2789}
2790
2791sub libsvn_find_parent_branch {
a5e0cedc
EW
2792 my ($paths, $rev, $author, $date, $msg) = @_;
2793 my $svn_path = '/'.$SVN_PATH;
2794
2795 # look for a parent from another branch:
cf7424b0
EW
2796 my $i = $paths->{$svn_path} or return;
2797 my $branch_from = $i->copyfrom_path or return;
2798 my $r = $i->copyfrom_rev;
2799 print STDERR "Found possible branch point: ",
2800 "$branch_from => $svn_path, $r\n";
2801 $branch_from =~ s#^/##;
2802 my $l_map = read_url_paths();
2803 my $url = $SVN->{url};
2804 defined $l_map->{$url} or return;
2805 my $id = $l_map->{$url}->{$branch_from} or return;
2806 my ($r0, $parent) = find_rev_before($r,$id,1);
2807 return unless (defined $r0 && defined $parent);
2808 if (revisions_eq($branch_from, $r0, $r)) {
2809 unlink $GIT_SVN_INDEX;
2810 print STDERR "Found branch parent: $parent\n";
2811 sys(qw/git-read-tree/, $parent);
2812 return libsvn_fetch($parent, $paths, $rev,
2813 $author, $date, $msg);
2814 }
2815 print STDERR "Nope, branch point not imported or unknown\n";
42d32870
EW
2816 return undef;
2817}
2818
dc62e25c
EW
2819sub libsvn_get_log {
2820 my ($ra, @args) = @_;
2821 if ($SVN::Core::VERSION le '1.2.0') {
2822 splice(@args, 3, 1);
2823 }
2824 $ra->get_log(@args);
2825}
2826
42d32870
EW
2827sub libsvn_new_tree {
2828 if (my $log_entry = libsvn_find_parent_branch(@_)) {
2829 return $log_entry;
2830 }
2831 my ($paths, $rev, $author, $date, $msg) = @_;
a5e0cedc
EW
2832 open my $gui, '| git-update-index -z --index-info' or croak $!;
2833 my $pool = SVN::Pool->new;
2834 libsvn_traverse($gui, '', $SVN_PATH, $rev, $pool);
2835 $pool->clear;
cf7424b0 2836 close $gui or croak $?;
a5e0cedc
EW
2837 return libsvn_log_entry($rev, $author, $date, $msg);
2838}
2839
2840sub find_graft_path_commit {
2841 my ($tree_paths, $p1, $r1) = @_;
2842 foreach my $x (keys %$tree_paths) {
2843 next unless ($p1 =~ /^\Q$x\E/);
2844 my $i = $tree_paths->{$x};
42d32870
EW
2845 my ($r0, $parent) = find_rev_before($r1,$i,1);
2846 return $parent if (defined $r0 && $r0 == $r1);
a5e0cedc
EW
2847 print STDERR "r$r1 of $i not imported\n";
2848 next;
2849 }
2850 return undef;
2851}
2852
2853sub find_graft_path_parents {
2854 my ($grafts, $tree_paths, $c, $p0, $r0) = @_;
2855 foreach my $x (keys %$tree_paths) {
2856 next unless ($p0 =~ /^\Q$x\E/);
2857 my $i = $tree_paths->{$x};
42d32870
EW
2858 my ($r, $parent) = find_rev_before($r0, $i, 1);
2859 if (defined $r && defined $parent && revisions_eq($x,$r,$r0)) {
c1927a85
EW
2860 my ($url_b, undef, $uuid_b) = cmt_metadata($c);
2861 my ($url_a, undef, $uuid_a) = cmt_metadata($parent);
2862 next if ($url_a && $url_b && $url_a eq $url_b &&
2863 $uuid_b eq $uuid_a);
42d32870 2864 $grafts->{$c}->{$parent} = 1;
a5e0cedc 2865 }
a5e0cedc
EW
2866 }
2867}
2868
2869sub libsvn_graft_file_copies {
2870 my ($grafts, $tree_paths, $path, $paths, $rev) = @_;
2871 foreach (keys %$paths) {
2872 my $i = $paths->{$_};
2873 my ($m, $p0, $r0) = ($i->action, $i->copyfrom_path,
2874 $i->copyfrom_rev);
2875 next unless (defined $p0 && defined $r0);
2876
2877 my $p1 = $_;
2878 $p1 =~ s#^/##;
2879 $p0 =~ s#^/##;
2880 my $c = find_graft_path_commit($tree_paths, $p1, $rev);
2881 next unless $c;
2882 find_graft_path_parents($grafts, $tree_paths, $c, $p0, $r0);
2883 }
2884}
2885
2886sub set_index {
2887 my $old = $ENV{GIT_INDEX_FILE};
2888 $ENV{GIT_INDEX_FILE} = shift;
2889 return $old;
2890}
2891
2892sub restore_index {
2893 my ($old) = @_;
2894 if (defined $old) {
2895 $ENV{GIT_INDEX_FILE} = $old;
2896 } else {
2897 delete $ENV{GIT_INDEX_FILE};
2898 }
2899}
2900
2901sub libsvn_commit_cb {
2902 my ($rev, $date, $committer, $c, $msg, $r_last, $cmt_last) = @_;
42d32870 2903 if ($_optimize_commits && $rev == ($r_last + 1)) {
a5e0cedc
EW
2904 my $log = libsvn_log_entry($rev,$committer,$date,$msg);
2905 $log->{tree} = get_tree_from_treeish($c);
2906 my $cmt = git_commit($log, $cmt_last, $c);
2907 my @diff = safe_qx('git-diff-tree', $cmt, $c);
2908 if (@diff) {
2909 print STDERR "Trees differ: $cmt $c\n",
2910 join('',@diff),"\n";
2911 exit 1;
2912 }
2913 } else {
cf7424b0 2914 fetch("$rev=$c");
a5e0cedc
EW
2915 }
2916}
2917
2918sub libsvn_ls_fullurl {
2919 my $fullurl = shift;
2920 my ($repo, $path) = repo_path_split($fullurl);
2921 $SVN ||= libsvn_connect($repo);
2922 my @ret;
2923 my $pool = SVN::Pool->new;
2924 my ($dirent, undef, undef) = $SVN->get_dir($path,
2925 $SVN->get_latest_revnum, $pool);
2926 foreach my $d (keys %$dirent) {
2927 if ($dirent->{$d}->kind == $SVN::Node::dir) {
2928 push @ret, "$d/"; # add '/' for compat with cli svn
2929 }
2930 }
2931 $pool->clear;
2932 return @ret;
2933}
2934
2935
2936sub libsvn_skip_unknown_revs {
2937 my $err = shift;
2938 my $errno = $err->apr_err();
2939 # Maybe the branch we're tracking didn't
2940 # exist when the repo started, so it's
2941 # not an error if it doesn't, just continue
2942 #
2943 # Wonderfully consistent library, eh?
2944 # 160013 - svn:// and file://
2945 # 175002 - http(s)://
2946 # More codes may be discovered later...
2947 if ($errno == 175002 || $errno == 160013) {
a5e0cedc
EW
2948 return;
2949 }
2950 croak "Error from SVN, ($errno): ", $err->expanded_message,"\n";
2951};
2952
42d32870
EW
2953# Tie::File seems to be prone to offset errors if revisions get sparse,
2954# it's not that fast, either. Tie::File is also not in Perl 5.6. So
2955# one of my favorite modules is out :< Next up would be one of the DBM
2956# modules, but I'm not sure which is most portable... So I'll just
2957# go with something that's plain-text, but still capable of
2958# being randomly accessed. So here's my ultra-simple fixed-width
2959# database. All records are 40 characters + "\n", so it's easy to seek
2960# to a revision: (41 * rev) is the byte offset.
2961# A record of 40 0s denotes an empty revision.
2962# And yes, it's still pretty fast (faster than Tie::File).
2963sub revdb_set {
2964 my ($file, $rev, $commit) = @_;
2965 length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
2966 open my $fh, '+<', $file or croak $!;
2967 my $offset = $rev * 41;
2968 # assume that append is the common case:
2969 seek $fh, 0, 2 or croak $!;
2970 my $pos = tell $fh;
2971 if ($pos < $offset) {
2972 print $fh (('0' x 40),"\n") x (($offset - $pos) / 41);
2973 }
2974 seek $fh, $offset, 0 or croak $!;
2975 print $fh $commit,"\n";
2976 close $fh or croak $!;
2977}
2978
2979sub revdb_get {
2980 my ($file, $rev) = @_;
2981 my $ret;
2982 my $offset = $rev * 41;
2983 open my $fh, '<', $file or croak $!;
2984 seek $fh, $offset, 0;
2985 if (tell $fh == $offset) {
2986 $ret = readline $fh;
2987 if (defined $ret) {
2988 chomp $ret;
2989 $ret = undef if ($ret =~ /^0{40}$/);
2990 }
2991 }
2992 close $fh or croak $!;
2993 return $ret;
2994}
2995
1a82e793
EW
2996sub copy_remote_ref {
2997 my $origin = $_cp_remote ? $_cp_remote : 'origin';
2998 my $ref = "refs/remotes/$GIT_SVN";
2999 if (safe_qx('git-ls-remote', $origin, $ref)) {
3000 sys(qw/git fetch/, $origin, "$ref:$ref");
3001 } else {
3002 die "Unable to find remote reference: ",
3003 "refs/remotes/$GIT_SVN on $origin\n";
3004 }
3005}
3006
a5e0cedc
EW
3007package SVN::Git::Editor;
3008use vars qw/@ISA/;
3009use strict;
3010use warnings;
3011use Carp qw/croak/;
3012use IO::File;
3013
3014sub new {
3015 my $class = shift;
3016 my $git_svn = shift;
3017 my $self = SVN::Delta::Editor->new(@_);
3018 bless $self, $class;
3019 foreach (qw/svn_path c r ra /) {
3020 die "$_ required!\n" unless (defined $git_svn->{$_});
3021 $self->{$_} = $git_svn->{$_};
3022 }
3023 $self->{pool} = SVN::Pool->new;
3024 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3025 $self->{rm} = { };
3026 require Digest::MD5;
3027 return $self;
3028}
3029
3030sub split_path {
3031 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3032}
3033
3034sub repo_path {
3035 (defined $_[1] && length $_[1]) ? "$_[0]->{svn_path}/$_[1]"
3036 : $_[0]->{svn_path}
3037}
3038
3039sub url_path {
3040 my ($self, $path) = @_;
3041 $self->{ra}->{url} . '/' . $self->repo_path($path);
3042}
3043
3044sub rmdirs {
3045 my ($self) = @_;
3046 my $rm = $self->{rm};
3047 delete $rm->{''}; # we never delete the url we're tracking
3048 return unless %$rm;
3049
3050 foreach (keys %$rm) {
3051 my @d = split m#/#, $_;
3052 my $c = shift @d;
3053 $rm->{$c} = 1;
3054 while (@d) {
3055 $c .= '/' . shift @d;
3056 $rm->{$c} = 1;
3057 }
3058 }
3059 delete $rm->{$self->{svn_path}};
3060 delete $rm->{''}; # we never delete the url we're tracking
3061 return unless %$rm;
3062
3063 defined(my $pid = open my $fh,'-|') or croak $!;
3064 if (!$pid) {
3065 exec qw/git-ls-tree --name-only -r -z/, $self->{c} or croak $!;
3066 }
3067 local $/ = "\0";
c07eee1f 3068 my @svn_path = split m#/#, $self->{svn_path};
a5e0cedc
EW
3069 while (<$fh>) {
3070 chomp;
c07eee1f
EW
3071 my @dn = (@svn_path, (split m#/#, $_));
3072 while (pop @dn) {
3073 delete $rm->{join '/', @dn};
3074 }
3075 unless (%$rm) {
3076 close $fh;
3077 return;
3078 }
a5e0cedc 3079 }
c07eee1f
EW
3080 close $fh;
3081
a5e0cedc
EW
3082 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3083 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3084 $self->close_directory($bat->{$d}, $p);
3085 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
3086 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3087 delete $bat->{$d};
3088 }
3089}
3090
3091sub open_or_add_dir {
3092 my ($self, $full_path, $baton) = @_;
3093 my $p = SVN::Pool->new;
3094 my $t = $self->{ra}->check_path($full_path, $self->{r}, $p);
3095 $p->clear;
3096 if ($t == $SVN::Node::none) {
3097 return $self->add_directory($full_path, $baton,
3098 undef, -1, $self->{pool});
3099 } elsif ($t == $SVN::Node::dir) {
3100 return $self->open_directory($full_path, $baton,
3101 $self->{r}, $self->{pool});
3102 }
3103 print STDERR "$full_path already exists in repository at ",
3104 "r$self->{r} and it is not a directory (",
3105 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3106 exit 1;
3107}
3108
3109sub ensure_path {
3110 my ($self, $path) = @_;
3111 my $bat = $self->{bat};
3112 $path = $self->repo_path($path);
3113 return $bat->{''} unless (length $path);
3114 my @p = split m#/+#, $path;
3115 my $c = shift @p;
3116 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3117 while (@p) {
3118 my $c0 = $c;
3119 $c .= '/' . shift @p;
3120 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3121 }
3122 return $bat->{$c};
3123}
3124
3125sub A {
3126 my ($self, $m) = @_;
3127 my ($dir, $file) = split_path($m->{file_b});
3128 my $pbat = $self->ensure_path($dir);
3129 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3130 undef, -1);
3131 $self->chg_file($fbat, $m);
3132 $self->close_file($fbat,undef,$self->{pool});
3133}
3134
3135sub C {
3136 my ($self, $m) = @_;
3137 my ($dir, $file) = split_path($m->{file_b});
3138 my $pbat = $self->ensure_path($dir);
3139 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3140 $self->url_path($m->{file_a}), $self->{r});
3141 $self->chg_file($fbat, $m);
3142 $self->close_file($fbat,undef,$self->{pool});
3143}
3144
3145sub delete_entry {
3146 my ($self, $path, $pbat) = @_;
3147 my $rpath = $self->repo_path($path);
3148 my ($dir, $file) = split_path($rpath);
3149 $self->{rm}->{$dir} = 1;
3150 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3151}
3152
3153sub R {
3154 my ($self, $m) = @_;
3155 my ($dir, $file) = split_path($m->{file_b});
3156 my $pbat = $self->ensure_path($dir);
3157 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3158 $self->url_path($m->{file_a}), $self->{r});
3159 $self->chg_file($fbat, $m);
3160 $self->close_file($fbat,undef,$self->{pool});
3161
3162 ($dir, $file) = split_path($m->{file_a});
3163 $pbat = $self->ensure_path($dir);
3164 $self->delete_entry($m->{file_a}, $pbat);
3165}
3166
3167sub M {
3168 my ($self, $m) = @_;
3169 my ($dir, $file) = split_path($m->{file_b});
3170 my $pbat = $self->ensure_path($dir);
3171 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
3172 $pbat,$self->{r},$self->{pool});
3173 $self->chg_file($fbat, $m);
3174 $self->close_file($fbat,undef,$self->{pool});
3175}
3176
3177sub T { shift->M(@_) }
3178
3179sub change_file_prop {
3180 my ($self, $fbat, $pname, $pval) = @_;
3181 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
3182}
3183
3184sub chg_file {
3185 my ($self, $fbat, $m) = @_;
3186 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
3187 $self->change_file_prop($fbat,'svn:executable','*');
3188 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
3189 $self->change_file_prop($fbat,'svn:executable',undef);
3190 }
3191 my $fh = IO::File->new_tmpfile or croak $!;
3192 if ($m->{mode_b} =~ /^120/) {
3193 print $fh 'link ' or croak $!;
3194 $self->change_file_prop($fbat,'svn:special','*');
3195 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
3196 $self->change_file_prop($fbat,'svn:special',undef);
3197 }
3198 defined(my $pid = fork) or croak $!;
3199 if (!$pid) {
3200 open STDOUT, '>&', $fh or croak $!;
3201 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
3202 }
3203 waitpid $pid, 0;
3204 croak $? if $?;
3205 $fh->flush == 0 or croak $!;
3206 seek $fh, 0, 0 or croak $!;
3207
3208 my $md5 = Digest::MD5->new;
3209 $md5->addfile($fh) or croak $!;
3210 seek $fh, 0, 0 or croak $!;
3211
3212 my $exp = $md5->hexdigest;
3213 my $atd = $self->apply_textdelta($fbat, undef, $self->{pool});
3214 my $got = SVN::TxDelta::send_stream($fh, @$atd, $self->{pool});
3215 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
3216
3217 close $fh or croak $!;
3218}
3219
3220sub D {
3221 my ($self, $m) = @_;
3222 my ($dir, $file) = split_path($m->{file_b});
3223 my $pbat = $self->ensure_path($dir);
3224 $self->delete_entry($m->{file_b}, $pbat);
3225}
3226
3227sub close_edit {
3228 my ($self) = @_;
3229 my ($p,$bat) = ($self->{pool}, $self->{bat});
3230 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
3231 $self->close_directory($bat->{$_}, $p);
3232 }
3233 $self->SUPER::close_edit($p);
3234 $p->clear;
3235}
3236
3237sub abort_edit {
3238 my ($self) = @_;
3239 $self->SUPER::abort_edit($self->{pool});
3240 $self->{pool}->clear;
3241}
3242
3397f9df
EW
3243__END__
3244
3245Data structures:
3246
03823184
EW
3247$svn_log hashref (as returned by svn_log_raw)
3248{
3249 fh => file handle of the log file,
3250 state => state of the log file parser (sep/msg/rev/msg_start...)
3251}
3397f9df 3252
03823184 3253$log_msg hashref as returned by next_log_entry($svn_log)
3397f9df
EW
3254{
3255 msg => 'whitespace-formatted log entry
3256', # trailing newline is preserved
3257 revision => '8', # integer
3258 date => '2004-02-24T17:01:44.108345Z', # commit date
3259 author => 'committer name'
3260};
3261
3262
3263@mods = array of diff-index line hashes, each element represents one line
3264 of diff-index output
3265
3266diff-index line ($m hash)
3267{
3268 mode_a => first column of diff-index output, no leading ':',
3269 mode_b => second column of diff-index output,
3270 sha1_b => sha1sum of the final blob,
ac8e0b91 3271 chg => change type [MCRADT],
3397f9df
EW
3272 file_a => original file name of a file (iff chg is 'C' or 'R')
3273 file_b => new/current file name of a file (any chg)
3274}
3275;
a5e0cedc
EW
3276
3277Notes:
3278 I don't trust the each() function on unless I created %hash myself
3279 because the internal iterator may not have started at base.