2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
6 use vars qw
/ $AUTHOR $VERSION
7 $sha1 $sha1_short $_revision $_repository
8 $_q $_authors $_authors_prog %users/;
9 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
10 $VERSION = '@@GIT_VERSION@@';
12 # From which subdir have we been invoked?
13 my $cmd_dir_prefix = eval {
14 command_oneline
([qw
/rev-parse --show-prefix/], STDERR
=> 0)
17 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR
};
18 $ENV{GIT_DIR
} ||= '.git';
19 $Git::SVN
::default_repo_id
= 'svn';
20 $Git::SVN
::default_ref_id
= $ENV{GIT_SVN_ID
} || 'git-svn';
21 $Git::SVN
::Ra
::_log_window_size
= 100;
23 $Git::SVN
::Log
::TZ
= $ENV{TZ
};
25 $| = 1; # unbuffer STDOUT
27 sub fatal
(@
) { print STDERR
"@_\n"; exit 1 }
28 require SVN
::Core
; # use()-ing this causes segfaults for me... *shrug*
31 if ($SVN::Core
::VERSION
lt '1.1.0') {
32 fatal
"Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
34 my $can_compress = eval { require Compress
::Zlib
; 1};
35 push @Git::SVN
::Ra
::ISA
, 'SVN::Ra';
36 push @SVN::Git
::Editor
::ISA
, 'SVN::Delta::Editor';
37 push @SVN::Git
::Fetcher
::ISA
, 'SVN::Delta::Editor';
41 use File
::Basename qw
/dirname basename/;
42 use File
::Path qw
/mkpath/;
45 use Getopt
::Long qw
/:config gnu_getopt no_ignore_case auto_abbrev/;
50 # import functions from Git into our packages, en masse
52 foreach (qw
/command command_oneline command_noisy command_output_pipe
53 command_input_pipe command_close_pipe
54 command_bidi_pipe command_close_bidi_pipe
/) {
55 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
56 Git::SVN::Migration Git::SVN::Log Git::SVN),
58 *{"${package}::$_"} = \
&{"Git::$_"};
65 $sha1 = qr/[a-f\d]{40}/;
66 $sha1_short = qr/[a-f\d]{4,40}/;
67 my ($_stdin, $_help, $_edit,
68 $_message, $_file, $_branch_dest,
70 $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
71 $_merge, $_strategy, $_dry_run, $_local,
72 $_prefix, $_no_checkout, $_url, $_verbose,
73 $_git_format, $_commit_url, $_tag);
74 $Git::SVN
::_follow_parent
= 1;
76 my %remote_opts = ( 'username=s' => \
$Git::SVN
::Prompt
::_username
,
77 'config-dir=s' => \
$Git::SVN
::Ra
::config_dir
,
78 'no-auth-cache' => \
$Git::SVN
::Prompt
::_no_auth_cache
,
79 'ignore-paths=s' => \
$SVN::Git
::Fetcher
::_ignore_regex
);
80 my %fc_opts = ( 'follow-parent|follow!' => \
$Git::SVN
::_follow_parent
,
81 'authors-file|A=s' => \
$_authors,
82 'authors-prog=s' => \
$_authors_prog,
83 'repack:i' => \
$Git::SVN
::_repack
,
84 'noMetadata' => \
$Git::SVN
::_no_metadata
,
85 'useSvmProps' => \
$Git::SVN
::_use_svm_props
,
86 'useSvnsyncProps' => \
$Git::SVN
::_use_svnsync_props
,
87 'log-window-size=i' => \
$Git::SVN
::Ra
::_log_window_size
,
88 'no-checkout' => \
$_no_checkout,
90 'repack-flags|repack-args|repack-opts=s' =>
91 \
$Git::SVN
::_repack_flags
,
92 'use-log-author' => \
$Git::SVN
::_use_log_author
,
93 'add-author-from' => \
$Git::SVN
::_add_author_from
,
94 'localtime' => \
$Git::SVN
::_localtime
,
97 my ($_trunk, @_tags, @_branches, $_stdlayout);
99 my %init_opts = ( 'template=s' => \
$_template, 'shared:s' => \
$_shared,
100 'trunk|T=s' => \
$_trunk, 'tags|t=s@' => \
@_tags,
101 'branches|b=s@' => \
@_branches, 'prefix=s' => \
$_prefix,
102 'stdlayout|s' => \
$_stdlayout,
103 'minimize-url|m' => \
$Git::SVN
::_minimize_url
,
104 'no-metadata' => sub { $icv{noMetadata
} = 1 },
105 'use-svm-props' => sub { $icv{useSvmProps
} = 1 },
106 'use-svnsync-props' => sub { $icv{useSvnsyncProps
} = 1 },
107 'rewrite-root=s' => sub { $icv{rewriteRoot
} = $_[1] },
109 my %cmt_opts = ( 'edit|e' => \
$_edit,
110 'rmdir' => \
$SVN::Git
::Editor
::_rmdir
,
111 'find-copies-harder' => \
$SVN::Git
::Editor
::_find_copies_harder
,
112 'l=i' => \
$SVN::Git
::Editor
::_rename_limit
,
113 'copy-similarity|C=i'=> \
$SVN::Git
::Editor
::_cp_similarity
117 fetch
=> [ \
&cmd_fetch
, "Download new revisions from SVN",
118 { 'revision|r=s' => \
$_revision,
119 'fetch-all|all' => \
$_fetch_all,
120 'parent|p' => \
$_fetch_parent,
122 clone
=> [ \
&cmd_clone
, "Initialize and fetch revisions",
123 { 'revision|r=s' => \
$_revision,
124 %fc_opts, %init_opts } ],
125 init
=> [ \
&cmd_init
, "Initialize a repo for tracking" .
126 " (requires URL argument)",
128 'multi-init' => [ \
&cmd_multi_init
,
129 "Deprecated alias for ".
130 "'$0 init -T<trunk> -b<branches> -t<tags>'",
132 dcommit
=> [ \
&cmd_dcommit
,
133 'Commit several diffs to merge with upstream',
134 { 'merge|m|M' => \
$_merge,
135 'strategy|s=s' => \
$_strategy,
136 'verbose|v' => \
$_verbose,
137 'dry-run|n' => \
$_dry_run,
138 'fetch-all|all' => \
$_fetch_all,
139 'commit-url=s' => \
$_commit_url,
140 'revision|r=i' => \
$_revision,
141 'no-rebase' => \
$_no_rebase,
142 %cmt_opts, %fc_opts } ],
143 branch
=> [ \
&cmd_branch
,
144 'Create a branch in the SVN repository',
145 { 'message|m=s' => \
$_message,
146 'destination|d=s' => \
$_branch_dest,
147 'dry-run|n' => \
$_dry_run,
148 'tag|t' => \
$_tag } ],
149 tag
=> [ sub { $_tag = 1; cmd_branch
(@_) },
150 'Create a tag in the SVN repository',
151 { 'message|m=s' => \
$_message,
152 'destination|d=s' => \
$_branch_dest,
153 'dry-run|n' => \
$_dry_run } ],
154 'set-tree' => [ \
&cmd_set_tree
,
155 "Set an SVN repository to a git tree-ish",
156 { 'stdin' => \
$_stdin, %cmt_opts, %fc_opts, } ],
157 'create-ignore' => [ \
&cmd_create_ignore
,
158 'Create a .gitignore per svn:ignore',
159 { 'revision|r=i' => \
$_revision
161 'propget' => [ \
&cmd_propget
,
162 'Print the value of a property on a file or directory',
163 { 'revision|r=i' => \
$_revision } ],
164 'proplist' => [ \
&cmd_proplist
,
165 'List all properties of a file or directory',
166 { 'revision|r=i' => \
$_revision } ],
167 'show-ignore' => [ \
&cmd_show_ignore
, "Show svn:ignore listings",
168 { 'revision|r=i' => \
$_revision
170 'show-externals' => [ \
&cmd_show_externals
, "Show svn:externals listings",
171 { 'revision|r=i' => \
$_revision
173 'multi-fetch' => [ \
&cmd_multi_fetch
,
174 "Deprecated alias for $0 fetch --all",
175 { 'revision|r=s' => \
$_revision, %fc_opts } ],
176 'migrate' => [ sub { },
177 # no-op, we automatically run this anyways,
178 'Migrate configuration/metadata/layout from
179 previous versions of git-svn',
180 { 'minimize' => \
$Git::SVN
::Migration
::_minimize
,
182 'log' => [ \
&Git
::SVN
::Log
::cmd_show_log
, 'Show commit logs',
183 { 'limit=i' => \
$Git::SVN
::Log
::limit
,
184 'revision|r=s' => \
$_revision,
185 'verbose|v' => \
$Git::SVN
::Log
::verbose
,
186 'incremental' => \
$Git::SVN
::Log
::incremental
,
187 'oneline' => \
$Git::SVN
::Log
::oneline
,
188 'show-commit' => \
$Git::SVN
::Log
::show_commit
,
189 'non-recursive' => \
$Git::SVN
::Log
::non_recursive
,
190 'authors-file|A=s' => \
$_authors,
191 'color' => \
$Git::SVN
::Log
::color
,
192 'pager=s' => \
$Git::SVN
::Log
::pager
194 'find-rev' => [ \
&cmd_find_rev
,
195 "Translate between SVN revision numbers and tree-ish",
197 'rebase' => [ \
&cmd_rebase
, "Fetch and rebase your working directory",
198 { 'merge|m|M' => \
$_merge,
199 'verbose|v' => \
$_verbose,
200 'strategy|s=s' => \
$_strategy,
201 'local|l' => \
$_local,
202 'fetch-all|all' => \
$_fetch_all,
203 'dry-run|n' => \
$_dry_run,
205 'commit-diff' => [ \
&cmd_commit_diff
,
206 'Commit a diff between two trees',
207 { 'message|m=s' => \
$_message,
208 'file|F=s' => \
$_file,
209 'revision|r=s' => \
$_revision,
211 'info' => [ \
&cmd_info
,
212 "Show info about the latest SVN revision
213 on the current branch",
214 { 'url' => \
$_url, } ],
215 'blame' => [ \
&Git
::SVN
::Log
::cmd_blame
,
216 "Show what revision and author last modified each line of a file",
217 { 'git-format' => \
$_git_format } ],
218 'reset' => [ \
&cmd_reset
,
219 "Undo fetches back to the specified SVN revision",
220 { 'revision|r=s' => \
$_revision,
221 'parent|p' => \
$_fetch_parent } ],
223 "Compress unhandled.log files in .git/svn and remove " .
224 "index files in .git/svn",
229 for (my $i = 0; $i < @ARGV; $i++) {
230 if (defined $cmd{$ARGV[$i]}) {
234 } elsif ($ARGV[$i] eq 'help') {
240 # make sure we're always running at the top-level working directory
241 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
242 unless (-d
$ENV{GIT_DIR
}) {
243 if ($git_dir_user_set) {
244 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
245 "but it is not a directory\n";
247 my $git_dir = delete $ENV{GIT_DIR
};
250 $cdup = command_oneline
(qw
/rev-parse --show-cdup/);
251 $git_dir = '.' unless ($cdup);
252 chomp $cdup if ($cdup);
253 $cdup = "." unless ($cdup && length $cdup);
254 } "Already at toplevel, but $git_dir not found\n";
255 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
256 unless (-d
$git_dir) {
257 die "$git_dir still not found after going to ",
260 $ENV{GIT_DIR
} = $git_dir;
262 $_repository = Git
->repository(Repository
=> $ENV{GIT_DIR
});
265 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
267 read_repo_config
(\
%opts);
268 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
269 Getopt
::Long
::Configure
('pass_through');
271 my $rv = GetOptions
(%opts, 'help|H|h' => \
$_help, 'version|V' => \
$_version,
272 'minimize-connections' => \
$Git::SVN
::Migration
::_minimize
,
273 'id|i=s' => \
$Git::SVN
::default_ref_id
,
274 'svn-remote|remote|R=s' => sub {
275 $Git::SVN
::no_reuse_existing
= 1;
276 $Git::SVN
::default_repo_id
= $_[1] });
277 exit 1 if (!$rv && $cmd && $cmd ne 'log');
280 version
() if $_version;
281 usage
(1) unless defined $cmd;
282 load_authors
() if $_authors;
283 if (defined $_authors_prog) {
284 $_authors_prog = "'" . File
::Spec
->rel2abs($_authors_prog) . "'";
287 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
288 Git
::SVN
::Migration
::migration_check
();
290 Git
::SVN
::init_vars
();
292 Git
::SVN
::verify_remotes_sanity
();
293 $cmd{$cmd}->[0]->(@ARGV);
296 post_fetch_checkout
();
299 ####################### primary functions ######################
301 my $exit = shift || 0;
302 my $fd = $exit ? \
*STDERR
: \
*STDOUT
;
304 git
-svn
- bidirectional operations between a single Subversion tree
and git
305 Usage
: git svn
<command
> [options
] [arguments
]\n
307 print $fd "Available commands:\n" unless $cmd;
309 foreach (sort keys %cmd) {
310 next if $cmd && $cmd ne $_;
311 next if /^multi-/; # don't show deprecated commands
312 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
313 foreach (sort keys %{$cmd{$_}->[2]}) {
314 # mixed-case options are for .git/config only
315 next if /[A-Z]/ && /^[a-z]+$/i;
316 # prints out arguments as they should be passed:
317 my $x = s
#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
318 print $fd ' ' x
21, join(', ', map { length $_ > 1 ?
320 split /\|/,$_)," $x\n";
324 \nGIT_SVN_ID may be set
in the environment
or via the
--id
/-i switch to an
325 arbitrary identifier
if you
're tracking multiple SVN branches/repositories in
326 one git repository and want to keep them separate. See git-svn(1) for more
333 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
338 unless (-d $ENV{GIT_DIR}) {
339 my @init_db = ('init
');
340 push @init_db, "--template=$_template" if defined $_template;
341 if (defined $_shared) {
342 if ($_shared =~ /[a-z]/) {
343 push @init_db, "--shared=$_shared";
345 push @init_db, "--shared";
348 command_noisy(@init_db);
349 $_repository = Git->repository(Repository => ".git");
351 command_noisy('config
', 'core
.autocrlf
', 'false
');
353 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
354 foreach my $i (keys %icv) {
355 die "'$set' and '$i' cannot both be set\n" if $set;
356 next unless defined $icv{$i};
357 command_noisy('config
', "$pfx.$i", $icv{$i});
360 my $ignore_regex = \$SVN::Git::Fetcher::_ignore_regex;
361 command_noisy('config
', "$pfx.ignore-paths", $$ignore_regex)
362 if defined $$ignore_regex;
366 my $repo_path = shift or return;
367 mkpath([$repo_path]) unless -d $repo_path;
368 chdir $repo_path or die "Couldn't
chdir to
$repo_path: $!\n";
369 $ENV{GIT_DIR} = '.git';
370 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
374 my ($url, $path) = @_;
375 if (!defined $path &&
376 (defined $_trunk || @_branches || @_tags ||
377 defined $_stdlayout) &&
378 $url !~ m#^[a-z\+]+://#) {
381 $path = basename($url) if !defined $path || !length $path;
382 cmd_init($url, $path);
383 Git::SVN::fetch_all($Git::SVN::default_repo_id);
384 command_oneline('config', 'svn.authorsfile', $_authors) if $_authors;
388 if (defined $_stdlayout) {
389 $_trunk = 'trunk' if (!defined $_trunk);
390 @_tags = 'tags' if (! @_tags);
391 @_branches = 'branches' if (! @_branches);
393 if (defined $_trunk || @_branches || @_tags) {
394 return cmd_multi_init(@_);
396 my $url = shift or die "SVN repository location required
",
397 "as a command
-line argument
\n";
398 $url = canonicalize_url($url);
402 Git::SVN->init($url);
406 if (grep /^\d+=./, @_) {
407 die "'<rev>=<commit>' fetch arguments are
",
408 "no longer supported
.\n";
412 die "Usage
: $0 fetch
[--all
] [--parent
] [svn
-remote
]\n";
414 if ($_fetch_parent) {
415 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
417 die "Unable to determine upstream SVN information from
",
418 "working tree history
\n";
420 # just fetch, don't checkout.
421 $_no_checkout = 'true';
422 $_fetch_all ? $gs->fetch_all : $gs->fetch;
423 } elsif ($_fetch_all) {
426 $remote ||= $Git::SVN::default_repo_id;
427 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
433 if ($_stdin || !@commits) {
434 print "Reading from stdin
...\n";
437 if (/\b($sha1_short)\b/o) {
438 unshift @commits, $1;
443 foreach my $c (@commits) {
444 my @tmp = command('rev-parse',$c);
445 if (scalar @tmp == 1) {
447 } elsif (scalar @tmp > 1) {
448 push @revs, reverse(command('rev-list',@tmp));
450 fatal "Failed to rev
-parse
$c";
453 my $gs = Git::SVN->new;
454 my ($r_last, $cmt_last) = $gs->last_rev_commit;
456 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
457 fatal "There are new revisions that were fetched
",
458 "and need to be merged
(or acknowledged
) ",
459 "before committing
.\nlast rev
: $r_last\n",
460 " current
: $gs->{last_rev
}";
462 $gs->set_tree($_) foreach @revs;
463 print "Done committing
",scalar @revs," revisions to SVN
\n";
469 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
470 'Cannot dcommit with a dirty index. Commit your changes first, '
471 . "or stash them with
`git stash'.\n";
475 if ($head ne 'HEAD') {
477 command_oneline([qw/symbolic-ref -q HEAD/])
480 $old_head =~ s{^refs/heads/}{};
482 $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
484 command(['checkout', $head], STDERR => 0);
488 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
490 die "Unable to determine upstream SVN information from ",
491 "$head history.\nPerhaps the repository is empty.";
494 if (defined $_commit_url) {
497 $url = eval { command_oneline('config', '--get',
498 "svn-remote.$gs->{repo_id}.commiturl") };
504 my $last_rev = $_revision if defined $_revision;
506 print "Committing to $url ...\n";
508 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
509 if ($_no_rebase && scalar(@$linear_refs) > 1) {
510 warn "Attempting to commit more than one change while ",
511 "--no-rebase is enabled.\n",
512 "If these changes depend on each other, re-running ",
513 "without --no-rebase may be required."
515 my $expect_url = $url;
516 Git::SVN::remove_username($expect_url);
518 my $d = shift @$linear_refs or last;
519 unless (defined $last_rev) {
520 (undef, $last_rev, undef) = cmt_metadata("$d~1");
521 unless (defined $last_rev) {
522 fatal "Unable to extract revision information ",
527 print "diff-tree $d~1 $d\n";
530 my %ed_opts = ( r => $last_rev,
531 log => get_commit_entry($d)->{log},
532 ra => Git::SVN::Ra->new($url),
533 config => SVN::Core::config_get_config(
534 $Git::SVN::Ra::config_dir
539 print "Committed r$_[0]\n";
543 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
544 print "No changes\n$d~1 == $d\n";
545 } elsif ($parents->{$d} && @{$parents->{$d}}) {
546 $gs->{inject_parents_dcommit}->{$cmt_rev} =
549 $_fetch_all ? $gs->fetch_all : $gs->fetch;
550 $last_rev = $cmt_rev;
553 # we always want to rebase against the current HEAD,
554 # not any head that was passed to us
555 my @diff = command('diff-tree', $d,
559 @finish = rebase_cmd();
560 print STDERR "W: $d and ", $gs->refname,
561 " differ, using @finish:\n",
562 join("\n", @diff), "\n";
564 print "No changes between current HEAD and ",
566 "\nResetting to the latest ",
568 @finish = qw/reset --mixed/;
570 command_noisy(@finish, $gs->refname);
573 my ($url_, $rev_, $uuid_, $gs_) =
574 working_head_info('HEAD', \@refs);
575 my ($linear_refs_, $parents_) =
576 linearize_history($gs_, \@refs);
577 if (scalar(@$linear_refs) !=
578 scalar(@$linear_refs_)) {
579 fatal "# of revisions changed ",
581 join("\n", @$linear_refs),
583 join("\n", @$linear_refs_), "\n",
584 'If you are attempting to commit ',
585 "merges, try running:\n\t",
586 'git rebase --interactive',
587 '--preserve-merges ',
589 "\nBefore dcommitting";
591 if ($url_ ne $expect_url) {
592 fatal "URL mismatch after rebase: ",
593 "$url_ != $expect_url";
595 if ($uuid_ ne $uuid) {
596 fatal "uuid mismatch after rebase: ",
601 for ($i = 0; $i < scalar @$linear_refs; $i++) {
602 my $new = $linear_refs_->[$i] or next;
604 $parents->{$linear_refs->[$i]};
614 my $new_head = command_oneline(qw/rev-parse HEAD/);
615 my $new_is_symbolic = eval {
616 command_oneline(qw/symbolic-ref -q HEAD/);
618 if ($new_is_symbolic) {
619 print "dcommitted the branch ", $head, "\n";
621 print "dcommitted on a detached HEAD because you gave ",
622 "a revision argument.\n",
623 "The rewritten commit is: ", $new_head, "\n";
625 command(['checkout', $old_head], STDERR => 0);
632 my ($branch_name, $head) = @_;
634 unless (defined $branch_name && length $branch_name) {
635 die(($_tag ? "tag" : "branch") . " name required\n");
639 my ($src, $rev, undef, $gs) = working_head_info($head);
641 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
642 my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
644 if ($#{$allglobs} == 0) {
645 $glob = $allglobs->[0];
647 unless(defined $_branch_dest) {
649 $_tag ? "tag" : "branch",
650 " paths defined for Subversion repository.\n",
651 "You must specify where you want to create the ",
652 $_tag ? "tag" : "branch",
653 " with the --destination argument.\n";
655 foreach my $g (@{$allglobs}) {
656 # SVN::Git::Editor could probably be moved to Git.pm..
657 my $re = SVN::Git::Editor::glob2pat($g->{path}->{left});
658 if ($_branch_dest =~ /$re/) {
663 unless (defined $glob) {
665 $_tag ? "tag" : "branch",
666 " destination $_branch_dest\n";
669 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
670 my $dst = join '/', $remote->{url}, $lft, $branch_name, ($rgt || ());
672 my $ctx = SVN::Client->new(
673 auth => Git::SVN::Ra::_auth_providers(),
675 ${ $_[0] } = defined $_message
677 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
683 $ctx->ls($dst, 'HEAD', 0);
684 } and die "branch ${branch_name} already exists\n";
686 print "Copying ${src} at r${rev} to ${dst}...\n";
687 $ctx->copy($src, $rev, $dst)
694 my $revision_or_hash = shift or die "SVN or git revision required ",
695 "as a command-line argument\n";
697 if ($revision_or_hash =~ /^r\d+$/) {
701 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
703 die "Unable to determine upstream SVN information from ",
706 my $desired_revision = substr($revision_or_hash, 1);
707 $result = $gs->rev_map_get($desired_revision, $uuid);
709 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
712 print "$result\n" if $result;
716 command_noisy(qw/update-index --refresh/);
717 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
719 die "Unable to determine upstream SVN information from ",
720 "working tree history\n";
723 print "Remote Branch: " . $gs->refname . "\n";
724 print "SVN URL: " . $url . "\n";
727 if (command(qw/diff-index HEAD --/)) {
728 print STDERR "Cannot rebase with uncommited changes:\n";
729 command_noisy('status');
733 # rebase will checkout for us, so no need to do it explicitly
734 $_no_checkout = 'true';
735 $_fetch_all ? $gs->fetch_all : $gs->fetch;
737 command_noisy(rebase_cmd(), $gs->refname);
740 sub cmd_show_ignore {
741 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
742 $gs ||= Git::SVN->new;
743 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
744 $gs->prop_walk($gs->{path}, $r, sub {
745 my ($gs, $path, $props) = @_;
746 print STDOUT "\n# $path\n";
747 my $s = $props->{'svn:ignore'} or return;
748 $s =~ s/[\r\n]+/\n/g;
755 sub cmd_show_externals {
756 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
757 $gs ||= Git::SVN->new;
758 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
759 $gs->prop_walk($gs->{path}, $r, sub {
760 my ($gs, $path, $props) = @_;
761 print STDOUT "\n# $path\n";
762 my $s = $props->{'svn:externals'} or return;
763 $s =~ s/[\r\n]+/\n/g;
770 sub cmd_create_ignore {
771 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
772 $gs ||= Git::SVN->new;
773 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
774 $gs->prop_walk($gs->{path}, $r, sub {
775 my ($gs, $path, $props) = @_;
776 # $path is of the form /path/to/dir/
778 # SVN can have attributes on empty directories,
779 # which git won't track
780 mkpath([$path]) unless -d $path;
781 my $ignore = $path . '.gitignore';
782 my $s = $props->{'svn:ignore'} or return;
783 open(GITIGNORE, '>', $ignore)
784 or fatal("Failed to open `$ignore' for writing: $!");
785 $s =~ s/[\r\n]+/\n/g;
787 # Prefix all patterns so that the ignore doesn't apply
788 # to sub-directories.
790 print GITIGNORE
"$s\n";
792 or fatal
("Failed to close `$ignore': $!");
793 command_noisy
('add', '-f', $ignore);
797 sub canonicalize_path
{
799 my $dot_slash_added = 0;
800 if (substr($path, 0, 1) ne "/") {
801 $path = "./" . $path;
802 $dot_slash_added = 1;
804 # File::Spec->canonpath doesn't collapse x/../y into y (for a
805 # good reason), so let's do this manually.
807 $path =~ s
#/\.(?:/|$)#/#g;
808 $path =~ s
#/[^/]+/\.\.##g;
810 $path =~ s
#^\./## if $dot_slash_added;
816 sub canonicalize_url
{
818 $url =~ s
#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
824 # Helper for cmd_propget and cmd_proplist below.
827 my ($url, $rev, $uuid, $gs) = working_head_info
('HEAD');
828 $gs ||= Git
::SVN
->new;
830 # prefix THE PATH by the sub-directory from which the user
832 $path = $cmd_dir_prefix . $path;
833 fatal
("No such file or directory: $path") unless -e
$path;
834 my $is_dir = -d
$path ?
1 : 0;
835 $path = $gs->{path
} . '/' . $path;
837 # canonicalize the path (otherwise libsvn will abort or fail to
839 $path = canonicalize_path
($path);
841 my $r = (defined $_revision ?
$_revision : $gs->ra->get_latest_revnum);
844 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
847 (undef, $props) = $gs->ra->get_file($path, $r, undef);
852 # cmd_propget (PROP, PATH)
853 # ------------------------
854 # Print the SVN property PROP for PATH.
856 my ($prop, $path) = @_;
857 $path = '.' if not defined $path;
858 usage
(1) if not defined $prop;
859 my $props = get_svnprops
($path);
860 if (not defined $props->{$prop}) {
861 fatal
("`$path' does not have a `$prop' SVN property.");
863 print $props->{$prop} . "\n";
866 # cmd_proplist (PATH)
867 # -------------------
868 # Print the list of SVN properties for PATH.
871 $path = '.' if not defined $path;
872 my $props = get_svnprops
($path);
873 print "Properties on '$path':\n";
874 foreach (sort keys %{$props}) {
881 unless (defined $_trunk || @_branches || @_tags) {
885 $_prefix = '' unless defined $_prefix;
887 $url = canonicalize_url
($url);
891 if (defined $_trunk) {
892 my $trunk_ref = $_prefix . 'trunk';
893 # try both old-style and new-style lookups:
894 my $gs_trunk = eval { Git
::SVN
->new($trunk_ref) };
896 my ($trunk_url, $trunk_path) =
897 complete_svn_url
($url, $_trunk);
898 $gs_trunk = Git
::SVN
->init($trunk_url, $trunk_path,
902 return unless @_branches || @_tags;
903 my $ra = $url ? Git
::SVN
::Ra
->new($url) : undef;
904 foreach my $path (@_branches) {
905 complete_url_ls_init
($ra, $path, '--branches/-b', $_prefix);
907 foreach my $path (@_tags) {
908 complete_url_ls_init
($ra, $path, '--tags/-t', $_prefix.'tags/');
912 sub cmd_multi_fetch
{
913 my $remotes = Git
::SVN
::read_all_remotes
();
914 foreach my $repo_id (sort keys %$remotes) {
915 if ($remotes->{$repo_id}->{url
}) {
916 Git
::SVN
::fetch_all
($repo_id, $remotes);
921 # this command is special because it requires no metadata
922 sub cmd_commit_diff
{
923 my ($ta, $tb, $url) = @_;
924 my $usage = "Usage: $0 commit-diff -r<revision> ".
925 "<tree-ish> <tree-ish> [<URL>]";
926 fatal
($usage) if (!defined $ta || !defined $tb);
929 my $gs = eval { Git
::SVN
->new };
931 fatal
("Needed URL or usable git-svn --id in ",
932 "the command-line\n", $usage);
935 $svn_path = $gs->{path
};
937 unless (defined $_revision) {
938 fatal
("-r|--revision is a required argument\n", $usage);
940 if (defined $_message && defined $_file) {
941 fatal
("Both --message/-m and --file/-F specified ",
942 "for the commit message.\n",
943 "I have no idea what you mean");
945 if (defined $_file) {
946 $_message = file_to_s
($_file);
948 $_message ||= get_commit_entry
($tb)->{log};
950 my $ra ||= Git
::SVN
::Ra
->new($url);
953 $r = $ra->get_latest_revnum;
954 } elsif ($r !~ /^\d+$/) {
955 die "revision argument: $r not understood by git-svn\n";
957 my %ed_opts = ( r
=> $r,
962 editor_cb
=> sub { print "Committed r$_[0]\n" },
963 svn_path
=> $svn_path );
964 if (!SVN
::Git
::Editor
->new(\
%ed_opts)->apply_diff) {
965 print "No changes\n$ta == $tb\n";
969 sub escape_uri_only
{
972 foreach (split m{/}, $uri) {
973 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
981 if ($url =~ m
#^([^:]+)://([^/]*)(.*)$#) {
982 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only
($3));
983 $url = "$scheme://$domain$uri";
989 my $path = canonicalize_path
(defined($_[0]) ?
$_[0] : ".");
990 my $fullpath = canonicalize_path
($cmd_dir_prefix . $path);
992 die "Too many arguments specified\n";
995 my ($file_type, $diff_status) = find_file_type_and_diff_status
($path);
997 if (!$file_type && !$diff_status) {
998 print STDERR
"svn: '$path' is not under version control\n";
1002 my ($url, $rev, $uuid, $gs) = working_head_info
('HEAD');
1004 die "Unable to determine upstream SVN information from ",
1005 "working tree history\n";
1008 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1009 $path = "." if $path eq "";
1011 my $full_url = $url . ($fullpath eq "" ?
"" : "/$fullpath");
1014 print escape_url
($full_url), "\n";
1018 my $result = "Path: $path\n";
1019 $result .= "Name: " . basename
($path) . "\n" if $file_type ne "dir";
1020 $result .= "URL: " . escape_url
($full_url) . "\n";
1023 my $repos_root = $gs->repos_root;
1024 Git
::SVN
::remove_username
($repos_root);
1025 $result .= "Repository Root: " . escape_url
($repos_root) . "\n";
1028 $result .= "Repository Root: (offline)\n";
1030 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
1031 ($SVN::Core
::VERSION
le '1.5.4' || $file_type ne "dir");
1032 $result .= "Revision: " . ($diff_status eq "A" ?
0 : $rev) . "\n";
1034 $result .= "Node Kind: " .
1035 ($file_type eq "dir" ?
"directory" : "file") . "\n";
1037 my $schedule = $diff_status eq "A"
1039 : ($diff_status eq "D" ?
"delete" : "normal");
1040 $result .= "Schedule: $schedule\n";
1042 if ($diff_status eq "A") {
1043 print $result, "\n";
1047 my ($lc_author, $lc_rev, $lc_date_utc);
1048 my @args = Git
::SVN
::Log
::git_svn_log_cmd
($rev, $rev, "--", $fullpath);
1049 my $log = command_output_pipe
(@args);
1050 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1052 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1054 $lc_date_utc = Git
::SVN
::Log
::parse_git_date
($2, $3);
1055 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
1056 (undef, $lc_rev, undef) = ::extract_metadata
($1);
1061 Git
::SVN
::Log
::set_local_timezone
();
1063 $result .= "Last Changed Author: $lc_author\n";
1064 $result .= "Last Changed Rev: $lc_rev\n";
1065 $result .= "Last Changed Date: " .
1066 Git
::SVN
::Log
::format_svn_date
($lc_date_utc) . "\n";
1068 if ($file_type ne "dir") {
1069 my $text_last_updated_date =
1070 ($diff_status eq "D" ?
$lc_date_utc : (stat $path)[9]);
1072 "Text Last Updated: " .
1073 Git
::SVN
::Log
::format_svn_date
($text_last_updated_date) .
1076 if ($diff_status eq "D") {
1078 command_output_pipe
(qw(cat-file blob), "HEAD:$path");
1079 if ($file_type eq "link") {
1080 my $file_name = <$fh>;
1081 $checksum = md5sum
("link $file_name");
1083 $checksum = md5sum
($fh);
1085 command_close_pipe
($fh, $ctx);
1086 } elsif ($file_type eq "link") {
1088 command
(qw(cat-file blob), "HEAD:$path");
1090 md5sum
("link " . $file_name);
1092 open FILE
, "<", $path or die $!;
1093 $checksum = md5sum
(\
*FILE
);
1094 close FILE
or die $!;
1096 $result .= "Checksum: " . $checksum . "\n";
1099 print $result, "\n";
1103 my $target = shift || $_revision or die "SVN revision required\n";
1104 $target = $1 if $target =~ /^r(\d+)$/;
1105 $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1106 my ($url, $rev, $uuid, $gs) = working_head_info
('HEAD');
1108 die "Unable to determine upstream SVN information from ".
1111 my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1112 $gs->rev_map_set($r, $c, 'reset', $uuid);
1113 print "r$r = $c ($gs->{ref_id})\n";
1117 if (!$can_compress) {
1118 warn "Compress::Zlib could not be found; unhandled.log " .
1119 "files will not be compressed.\n";
1121 find
({ wanted
=> \
&gc_directory
, no_chdir
=> 1}, "$ENV{GIT_DIR}/svn");
1124 ########################### utility functions #########################
1127 my @cmd = qw
/rebase/;
1128 push @cmd, '-v' if $_verbose;
1129 push @cmd, qw
/--merge/ if $_merge;
1130 push @cmd, "--strategy=$_strategy" if $_strategy;
1134 sub post_fetch_checkout
{
1135 return if $_no_checkout;
1136 my $gs = $Git::SVN
::_head
or return;
1137 return if verify_ref
('refs/heads/master^0');
1139 my $valid_head = verify_ref
('HEAD^0');
1140 command_noisy
(qw(update-ref refs/heads/master), $gs->refname);
1141 return if ($valid_head || !verify_ref
('HEAD^0'));
1143 return if $ENV{GIT_DIR
} !~ m
#^(?:.*/)?\.git$#;
1144 my $index = $ENV{GIT_INDEX_FILE
} || "$ENV{GIT_DIR}/index";
1145 return if -f
$index;
1147 return if command_oneline
(qw
/rev-parse --is-inside-work-tree/) eq 'false';
1148 return if command_oneline
(qw
/rev-parse --is-inside-git-dir/) eq 'true';
1149 command_noisy
(qw
/read-tree -m -u -v HEAD HEAD/);
1150 print STDERR
"Checked out HEAD:\n ",
1151 $gs->full_url, " r", $gs->last_rev, "\n";
1154 sub complete_svn_url
{
1155 my ($url, $path) = @_;
1157 if ($path !~ m
#^[a-z\+]+://#) {
1158 if (!defined $url || $url !~ m
#^[a-z\+]+://#) {
1159 fatal
("E: '$path' is not a complete URL ",
1160 "and a separate URL is not specified");
1162 return ($url, $path);
1167 sub complete_url_ls_init
{
1168 my ($ra, $repo_path, $switch, $pfx) = @_;
1169 unless ($repo_path) {
1170 print STDERR
"W: $switch not specified\n";
1173 $repo_path =~ s
#/+$##;
1174 if ($repo_path =~ m
#^[a-z\+]+://#) {
1175 $ra = Git
::SVN
::Ra
->new($repo_path);
1178 $repo_path =~ s
#^/+##;
1180 fatal
("E: '$repo_path' is not a complete URL ",
1181 "and a separate URL is not specified");
1184 my $url = $ra->{url
};
1185 my $gs = Git
::SVN
->init($url, undef, undef, undef, 1);
1186 my $k = "svn-remote.$gs->{repo_id}.url";
1187 my $orig_url = eval { command_oneline
(qw
/config --get/, $k) };
1188 if ($orig_url && ($orig_url ne $gs->{url
})) {
1189 die "$k already set: $orig_url\n",
1190 "wanted to set to: $gs->{url}\n";
1192 command_oneline
('config', $k, $gs->{url
}) unless $orig_url;
1193 my $remote_path = "$gs->{path}/$repo_path";
1194 $remote_path =~ s
#/+#/#g;
1195 $remote_path =~ s
#^/##g;
1196 $remote_path .= "/*" if $remote_path !~ /\
*/;
1197 my ($n) = ($switch =~ /^--(\w+)/);
1198 if (length $pfx && $pfx !~ m
#/$#) {
1199 die "--prefix='$pfx' must have a trailing slash '/'\n";
1201 command_noisy
('config',
1203 "svn-remote.$gs->{repo_id}.$n",
1204 "$remote_path:refs/remotes/$pfx*" .
1205 ('/*' x
(($remote_path =~ tr
/*/*/) - 1)) );
1210 eval { command_oneline
([ 'rev-parse', '--verify', $ref ],
1211 { STDERR
=> 0 }); };
1214 sub get_tree_from_treeish
{
1216 # $treeish can be a symbolic ref, too:
1217 my $type = command_oneline
(qw
/cat-file -t/, $treeish);
1219 while ($type eq 'tag') {
1220 ($treeish, $type) = command
(qw
/cat-file tag/, $treeish);
1222 if ($type eq 'commit') {
1223 $expected = (grep /^tree /, command
(qw
/cat-file commit/,
1225 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1226 die "Unable to get tree from $treeish\n" unless $expected;
1227 } elsif ($type eq 'tree') {
1228 $expected = $treeish;
1230 die "$treeish is a $type, expected tree, tag or commit\n";
1235 sub get_commit_entry
{
1236 my ($treeish) = shift;
1237 my %log_entry = ( log => '', tree
=> get_tree_from_treeish
($treeish) );
1238 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1239 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1240 open my $log_fh, '>', $commit_editmsg or croak
$!;
1242 my $type = command_oneline
(qw
/cat-file -t/, $treeish);
1243 if ($type eq 'commit' || $type eq 'tag') {
1244 my ($msg_fh, $ctx) = command_output_pipe
('cat-file',
1252 $in_msg = 1 if (/^\s*$/);
1253 $author = $1 if (/^author (.*>)/);
1254 } elsif (/^git-svn-id: /) {
1255 # skip this for now, we regenerate the
1256 # correct one on re-fetch anyways
1257 # TODO: set *:merge properties or like...
1259 if (/^From:/ || /^Signed-off-by:/) {
1265 $msgbuf =~ s/\s+$//s;
1266 if ($Git::SVN
::_add_author_from
&& defined($author)
1268 $msgbuf .= "\n\nFrom: $author";
1270 print $log_fh $msgbuf or croak
$!;
1271 command_close_pipe
($msg_fh, $ctx);
1273 close $log_fh or croak
$!;
1275 if ($_edit || ($type eq 'tree')) {
1276 my $editor = $ENV{VISUAL
} || $ENV{EDITOR
} || 'vi';
1277 # TODO: strip out spaces, comments, like git-commit.sh
1278 system($editor, $commit_editmsg);
1280 rename $commit_editmsg, $commit_msg or croak
$!;
1283 # SVN requires messages to be UTF-8 when entering the repo
1285 open $log_fh, '<', $commit_msg or croak
$!;
1287 chomp($log_entry{log} = <$log_fh>);
1289 my $enc = Git
::config
('i18n.commitencoding') || 'UTF-8';
1290 my $msg = $log_entry{log};
1292 eval { $msg = Encode
::decode
($enc, $msg, 1) };
1294 die "Could not decode as $enc:\n", $msg,
1295 "\nPerhaps you need to set i18n.commitencoding\n";
1298 eval { $msg = Encode
::encode
('UTF-8', $msg, 1) };
1299 die "Could not encode as UTF-8:\n$msg\n" if $@
;
1301 $log_entry{log} = $msg;
1303 close $log_fh or croak
$!;
1310 my ($str, $file, $mode) = @_;
1311 open my $fd,'>',$file or croak
$!;
1312 print $fd $str,"\n" or croak
$!;
1313 close $fd or croak
$!;
1314 chmod ($mode &~ umask, $file) if (defined $mode);
1319 open my $fd,'<',$file or croak
"$!: file: $file\n";
1322 close $fd or croak
$!;
1327 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1329 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1330 my $log = $cmd eq 'log';
1331 while (<$authors>) {
1333 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1334 my ($user, $name, $email) = ($1, $2, $3);
1336 $Git::SVN
::Log
::rusers
{"$name <$email>"} = $user;
1338 $users{$user} = [$name, $email];
1341 close $authors or croak
$!;
1344 # convert GetOpt::Long specs for use by git-config
1345 sub read_repo_config
{
1346 return unless -d
$ENV{GIT_DIR
};
1349 foreach my $o (keys %$opts) {
1350 # if we have mixedCase and a long option-only, then
1351 # it's a config-only variable that we don't need for
1353 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1354 my $v = $opts->{$o};
1355 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1357 my $arg = 'git config';
1358 $arg .= ' --int' if ($o =~ /[:=]i$/);
1359 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1360 if (ref $v eq 'ARRAY') {
1361 chomp(my @tmp = `$arg --get-all svn.$key`);
1364 chomp(my $tmp = `$arg --get svn.$key`);
1365 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1370 delete @
$opts{@config_only} if @config_only;
1373 sub extract_metadata
{
1374 my $id = shift or return (undef, undef, undef);
1375 my ($url, $rev, $uuid) = ($id =~ /^\s
*git
-svn
-id
:\s
+(.*)\@
(\d
+)
1376 \s
([a
-f\d\
-]+)$/ix
);
1377 if (!defined $rev || !$uuid || !$url) {
1378 # some of the original repositories I made had
1379 # identifiers like this:
1380 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
1382 return ($url, $rev, $uuid);
1386 return extract_metadata
((grep(/^git-svn-id: /,
1387 command
(qw
/cat-file commit/, shift)))[-1]);
1390 sub cmt_sha2rev_batch
{
1392 my ($pid, $in, $out, $ctx) = command_bidi_pipe
(qw
/cat-file --batch/);
1395 foreach my $sha (@
{$list}) {
1398 print $out $sha, "\n";
1400 while (my $line = <$in>) {
1401 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1404 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1408 } elsif ($line =~ /^(git-svn-id: )/) {
1409 my (undef, $rev, undef) =
1410 extract_metadata
($line);
1414 $size -= length($line);
1415 last if ($size == 0);
1419 command_close_bidi_pipe
($pid, $in, $out, $ctx);
1424 sub working_head_info
{
1425 my ($head, $refs) = @_;
1426 my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1427 my ($fh, $ctx) = command_output_pipe
(@args, $head);
1431 if ( m{^commit ($::sha1)$} ) {
1432 unshift @
$refs, $hash if $hash and $refs;
1436 next unless s{^\s*(git-svn-id:)}{$1};
1437 my ($url, $rev, $uuid) = extract_metadata
($_);
1438 if (defined $url && defined $rev) {
1439 next if $max{$url} and $max{$url} < $rev;
1440 if (my $gs = Git
::SVN
->find_by_url($url)) {
1441 my $c = $gs->rev_map_get($rev, $uuid);
1442 if ($c && $c eq $hash) {
1443 close $fh; # break the pipe
1444 return ($url, $rev, $uuid, $gs);
1446 $max{$url} ||= $gs->rev_map_max;
1451 command_close_pipe
($fh, $ctx);
1452 (undef, undef, undef, undef);
1455 sub read_commit_parents
{
1456 my ($parents, $c) = @_;
1457 chomp(my $p = command_oneline
(qw
/rev-list --parents -1/, $c));
1458 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1459 @
{$parents->{$c}} = split(/ /, $p);
1462 sub linearize_history
{
1463 my ($gs, $refs) = @_;
1465 foreach my $c (@
$refs) {
1466 read_commit_parents
(\
%parents, $c);
1471 my $last_svn_commit = $gs->last_commit;
1472 foreach my $c (reverse @
$refs) {
1473 next if $c eq $last_svn_commit;
1476 unshift @linear_refs, $c;
1479 # we only want the first parent to diff against for linear
1480 # history, we save the rest to inject when we finalize the
1482 my $fp_a = verify_ref
("$c~1");
1483 my $fp_b = shift @
{$parents{$c}} if $parents{$c};
1484 if (!$fp_a || !$fp_b) {
1486 "has no parent commit, and therefore ",
1487 "nothing to diff against.\n",
1488 "You should be working from a repository ",
1489 "originally created by git-svn\n";
1491 if ($fp_a ne $fp_b) {
1492 die "$c~1 = $fp_a, however parsing commit $c ",
1493 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1496 foreach my $p (@
{$parents{$c}}) {
1500 (\
@linear_refs, \
%parents);
1503 sub find_file_type_and_diff_status
{
1505 return ('dir', '') if $path eq '';
1508 command_oneline
(qw(diff --cached --name-status --), $path) || "";
1509 my $diff_status = (split(' ', $diff_output))[0] || "";
1511 my $ls_tree = command_oneline
(qw(ls-tree HEAD), $path) || "";
1513 return (undef, undef) if !$diff_status && !$ls_tree;
1515 if ($diff_status eq "A") {
1516 return ("link", $diff_status) if -l
$path;
1517 return ("dir", $diff_status) if -d
$path;
1518 return ("file", $diff_status);
1521 my $mode = (split(' ', $ls_tree))[0] || "";
1523 return ("link", $diff_status) if $mode eq "120000";
1524 return ("dir", $diff_status) if $mode eq "040000";
1525 return ("file", $diff_status);
1531 my $md5 = Digest
::MD5
->new();
1532 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1533 $md5->addfile($arg) or croak
$!;
1534 } elsif ($ref eq 'SCALAR') {
1535 $md5->add($$arg) or croak
$!;
1537 $md5->add($arg) or croak
$!;
1539 ::fatal
"Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1541 return $md5->hexdigest();
1545 if ($can_compress && -f
$_ && basename
($_) eq "unhandled.log") {
1546 my $out_filename = $_ . ".gz";
1547 open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
1549 my $gz = Compress
::Zlib
::gzopen
($out_filename, "ab") or
1550 die "Unable to open $out_filename: $!\n";
1553 while ($res = sysread($in_fh, my $str, 1024)) {
1554 $gz->gzwrite($str) or
1555 die "Unable to write: ".$gz->gzerror()."!\n";
1557 unlink $_ or die "unlink $File::Find::name: $!\n";
1558 } elsif (-f
$_ && basename
($_) eq "index") {
1559 unlink $_ or die "unlink $_: $!\n";
1566 use Fcntl qw
/:DEFAULT :seek/;
1567 use constant rev_map_fmt
=> 'NH40';
1568 use vars qw
/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1569 $_repack $_repack_flags $_use_svm_props $_head
1570 $_use_svnsync_props $no_reuse_existing $_minimize_url
1571 $_use_log_author $_add_author_from $_localtime/;
1573 use File
::Path qw
/mkpath/;
1574 use File
::Copy qw
/copy/;
1577 my ($_gc_nr, $_gc_period);
1579 # properties that we do not log:
1582 %SKIP_PROP = map { $_ => 1 } qw
/svn
:wc
:ra_dav
:version
-url
1583 svn
:special svn
:executable
1584 svn
:entry
:committed
-rev
1585 svn
:entry
:last-author
1587 svn
:entry
:committed
-date
/;
1589 # some options are read globally, but can be overridden locally
1590 # per [svn-remote "..."] section. Command-line options will *NOT*
1591 # override options set in an [svn-remote "..."] section
1593 for my $option (qw
/follow_parent no_metadata use_svm_props
1594 use_svnsync_props
/) {
1597 my $prop = "-$option";
1600 return $self->{$prop} if exists $self->{$prop};
1601 my $k = "svn-remote.$self->{repo_id}.$key";
1602 eval { command_oneline
(qw
/config --get/, $k) };
1604 $self->{$prop} = ${"Git::SVN::_$option"};
1606 my $v = command_oneline
(qw
/config --bool/,$k);
1607 $self->{$prop} = $v eq 'false' ?
0 : 1;
1609 return $self->{$prop};
1615 my (%LOCKFILES, %INDEX_FILES);
1617 unlink keys %LOCKFILES if %LOCKFILES;
1618 unlink keys %INDEX_FILES if %INDEX_FILES;
1621 sub resolve_local_globs
{
1622 my ($url, $fetch, $glob_spec) = @_;
1623 return unless defined $glob_spec;
1624 my $ref = $glob_spec->{ref};
1625 my $path = $glob_spec->{path
};
1626 foreach (command
(qw
#for-each-ref --format=%(refname) refs/remotes#)) {
1627 next unless m
#^refs/remotes/$ref->{regex}$#;
1629 my $pathname = desanitize_refname
($path->full_path($p));
1630 my $refname = desanitize_refname
($ref->full_path($p));
1631 if (my $existing = $fetch->{$pathname}) {
1632 if ($existing ne $refname) {
1633 die "Refspec conflict:\n",
1634 "existing: refs/remotes/$existing\n",
1635 " globbed: refs/remotes/$refname\n";
1637 my $u = (::cmt_metadata
("refs/remotes/$refname"))[0];
1638 $u =~ s!^\Q$url\E(/|$)!! or die
1639 "refs/remotes/$refname: '$url' not found in '$u'\n";
1640 if ($pathname ne $u) {
1641 warn "W: Refspec glob conflict ",
1642 "(ref: refs/remotes/$refname):\n",
1643 "expected path: $pathname\n",
1645 "Continuing ahead with $u\n";
1649 $fetch->{$pathname} = $refname;
1654 sub parse_revision_argument
{
1655 my ($base, $head) = @_;
1656 if (!defined $::_revision
|| $::_revision
eq 'BASE:HEAD') {
1657 return ($base, $head);
1659 return ($1, $2) if ($::_revision
=~ /^(\d+):(\d+)$/);
1660 return ($::_revision
, $::_revision
) if ($::_revision
=~ /^\d+$/);
1661 return ($head, $head) if ($::_revision
eq 'HEAD');
1662 return ($base, $1) if ($::_revision
=~ /^BASE:(\d+)$/);
1663 return ($1, $head) if ($::_revision
=~ /^(\d+):HEAD$/);
1664 die "revision argument: $::_revision not understood by git-svn\n";
1668 my ($repo_id, $remotes) = @_;
1672 $repo_id = $gs->{repo_id
};
1674 $remotes ||= read_all_remotes
();
1675 my $remote = $remotes->{$repo_id} or
1676 die "[svn-remote \"$repo_id\"] unknown\n";
1677 my $fetch = $remote->{fetch
};
1678 my $url = $remote->{url
} or die "svn-remote.$repo_id.url not defined\n";
1680 my $ra = Git
::SVN
::Ra
->new($url);
1681 my $uuid = $ra->get_uuid;
1682 my $head = $ra->get_latest_revnum;
1683 $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] });
1684 my $base = defined $fetch ?
$head : 0;
1686 # read the max revs for wildcard expansion (branches/*, tags/*)
1687 foreach my $t (qw
/branches tags/) {
1688 defined $remote->{$t} or next;
1689 push @globs, @
{$remote->{$t}};
1691 my $max_rev = eval { tmp_config
(qw
/--int --get/,
1692 "svn-remote.$repo_id.${t}-maxRev") };
1693 if (defined $max_rev && ($max_rev < $base)) {
1695 } elsif (!defined $max_rev) {
1701 foreach my $p (sort keys %$fetch) {
1702 my $gs = Git
::SVN
->new($fetch->{$p}, $repo_id, $p);
1703 my $lr = $gs->rev_map_max;
1705 $base = $lr if ($lr < $base);
1711 ($base, $head) = parse_revision_argument
($base, $head);
1712 $ra->gs_fetch_loop_common($base, $head, \
@gs, \
@globs);
1715 sub read_all_remotes
{
1717 my $use_svm_props = eval { command_oneline
(qw
/config
--bool
1718 svn
.useSvmProps
/) };
1719 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1720 foreach (grep { s/^svn-remote\.// } command
(qw
/config -l/)) {
1721 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*(.+)\s*$!) {
1722 my ($remote, $local_ref, $_remote_ref) = ($1, $2, $3);
1723 die("svn-remote.$remote: remote ref '$_remote_ref' "
1724 . "must start with 'refs/remotes/'\n")
1725 unless $_remote_ref =~ m{^refs/remotes/(.+)};
1726 my $remote_ref = $1;
1727 $local_ref =~ s{^/}{};
1728 $r->{$remote}->{fetch
}->{$local_ref} = $remote_ref;
1729 $r->{$remote}->{svm
} = {} if $use_svm_props;
1730 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1731 $r->{$1}->{svm
} = {};
1732 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1733 $r->{$1}->{url
} = $2;
1734 } elsif (m
!^(.+)\
.(branches
|tags
)=
1735 (.*):refs
/remotes
/(.+)\s
*$/!x
) {
1736 my ($p, $g) = ($3, $4);
1740 path
=> Git
::SVN
::GlobSpec
->new($p),
1741 ref => Git
::SVN
::GlobSpec
->new($g) };
1742 if (length($rs->{ref}->{right
}) != 0) {
1743 die "The '*' glob character must be the last ",
1744 "character of '$g'\n";
1746 push @
{ $r->{$1}->{$2} }, $rs;
1751 if (defined $r->{$_}->{svm
}) {
1754 my $section = "svn-remote.$_";
1756 source
=> tmp_config
('--get',
1757 "$section.svm-source"),
1758 replace
=> tmp_config
('--get',
1759 "$section.svm-replace"),
1762 $r->{$_}->{svm
} = $svm;
1770 $_gc_nr = $_gc_period = 1000;
1771 if (defined $_repack || defined $_repack_flags) {
1772 warn "Repack options are obsolete; they have no effect.\n";
1776 sub verify_remotes_sanity
{
1777 return unless -d
$ENV{GIT_DIR
};
1779 foreach (command
(qw
/config -l/)) {
1780 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1782 die "Remote ref refs/remote/$1 is tracked by",
1783 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1784 "Please resolve this ambiguity in ",
1785 "your git configuration file before ",
1793 sub find_existing_remote
{
1794 my ($url, $remotes) = @_;
1795 return undef if $no_reuse_existing;
1797 foreach my $repo_id (keys %$remotes) {
1798 my $u = $remotes->{$repo_id}->{url
} or next;
1800 $existing = $repo_id;
1806 sub init_remote_config
{
1807 my ($self, $url, $no_write) = @_;
1808 $url =~ s!/+$!!; # strip trailing slash
1809 my $r = read_all_remotes
();
1810 my $existing = find_existing_remote
($url, $r);
1812 unless ($no_write) {
1813 print STDERR
"Using existing ",
1814 "[svn-remote \"$existing\"]\n";
1816 $self->{repo_id
} = $existing;
1817 } elsif ($_minimize_url) {
1818 my $min_url = Git
::SVN
::Ra
->new($url)->minimize_url;
1819 $existing = find_existing_remote
($min_url, $r);
1821 unless ($no_write) {
1822 print STDERR
"Using existing ",
1823 "[svn-remote \"$existing\"]\n";
1825 $self->{repo_id
} = $existing;
1827 if ($min_url ne $url) {
1828 unless ($no_write) {
1829 print STDERR
"Using higher level of URL: ",
1830 "$url => $min_url\n";
1832 my $old_path = $self->{path
};
1833 $self->{path
} = $url;
1834 $self->{path
} =~ s!^\Q$min_url\E(/|$)!!;
1835 if (length $old_path) {
1836 $self->{path
} .= "/$old_path";
1843 # verify that we aren't overwriting anything:
1845 command_oneline
('config', '--get',
1846 "svn-remote.$self->{repo_id}.url")
1848 if ($orig_url && ($orig_url ne $url)) {
1849 die "svn-remote.$self->{repo_id}.url already set: ",
1850 "$orig_url\nwanted to set to: $url\n";
1853 my ($xrepo_id, $xpath) = find_ref
($self->refname);
1854 if (defined $xpath) {
1855 die "svn-remote.$xrepo_id.fetch already set to track ",
1856 "$xpath:refs/remotes/", $self->refname, "\n";
1858 unless ($no_write) {
1859 command_noisy
('config',
1860 "svn-remote.$self->{repo_id}.url", $url);
1861 $self->{path
} =~ s{^/}{};
1862 command_noisy
('config', '--add',
1863 "svn-remote.$self->{repo_id}.fetch",
1864 "$self->{path}:".$self->refname);
1866 $self->{url
} = $url;
1869 sub find_by_url
{ # repos_root and, path are optional
1870 my ($class, $full_url, $repos_root, $path) = @_;
1872 return undef unless defined $full_url;
1873 remove_username
($full_url);
1874 remove_username
($repos_root) if defined $repos_root;
1875 my $remotes = read_all_remotes
();
1876 if (defined $full_url && defined $repos_root && !defined $path) {
1878 $path =~ s
#^\Q$repos_root\E(?:/|$)##;
1880 foreach my $repo_id (keys %$remotes) {
1881 my $u = $remotes->{$repo_id}->{url
} or next;
1882 remove_username
($u);
1883 next if defined $repos_root && $repos_root ne $u;
1885 my $fetch = $remotes->{$repo_id}->{fetch
} || {};
1886 foreach my $t (qw
/branches tags/) {
1887 foreach my $globspec (@
{$remotes->{$repo_id}->{$t}}) {
1888 resolve_local_globs
($u, $fetch, $globspec);
1892 my $rwr = rewrite_root
({repo_id
=> $repo_id});
1893 my $svm = $remotes->{$repo_id}->{svm
}
1894 if defined $remotes->{$repo_id}->{svm
};
1895 unless (defined $p) {
1901 remove_username
($z);
1902 } elsif (defined $svm) {
1903 $z = $svm->{source
};
1904 $prefix = $svm->{replace
};
1905 $prefix =~ s
#^\Q$u\E(?:/|$)##;
1908 $p =~ s
#^\Q$z\E(?:/|$)#$prefix# or next;
1910 foreach my $f (keys %$fetch) {
1912 return Git
::SVN
->new($fetch->{$f}, $repo_id, $f);
1919 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1920 my $self = _new
($class, $repo_id, $ref_id, $path);
1922 $self->init_remote_config($url, $no_write);
1929 foreach (command
(qw
/config -l/)) {
1930 next unless m
!^svn
-remote\
.(.+)\
.fetch
=
1931 \s
*(.*)\s
*:\s
*refs
/remotes/(.+)\s
*$!x
;
1932 my ($repo_id, $path, $ref) = ($1, $2, $3);
1933 if ($ref eq $ref_id) {
1934 $path = '' if ($path =~ m
#^\./?#);
1935 return ($repo_id, $path);
1938 (undef, undef, undef);
1942 my ($class, $ref_id, $repo_id, $path) = @_;
1943 if (defined $ref_id && !defined $repo_id && !defined $path) {
1944 ($repo_id, $path) = find_ref
($ref_id);
1945 if (!defined $repo_id) {
1946 die "Could not find a \"svn-remote.*.fetch\" key ",
1947 "in the repository configuration matching: ",
1948 "refs/remotes/$ref_id\n";
1951 my $self = _new
($class, $repo_id, $ref_id, $path);
1952 if (!defined $self->{path
} || !length $self->{path
}) {
1953 my $fetch = command_oneline
('config', '--get',
1954 "svn-remote.$repo_id.fetch",
1955 ":refs/remotes/$ref_id\$") or
1956 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1957 "\":refs/remotes/$ref_id\$\" in config\n";
1958 ($self->{path
}, undef) = split(/\s*:\s*/, $fetch);
1960 $self->{url
} = command_oneline
('config', '--get',
1961 "svn-remote.$repo_id.url") or
1962 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1968 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1970 # It cannot end with a slash /, we'll throw up on this because
1971 # SVN can't have directories with a slash in their name, either:
1972 if ($refname =~ m{/$}) {
1973 die "ref: '$refname' ends with a trailing slash, this is ",
1974 "not permitted by git nor Subversion\n";
1977 # It cannot have ASCII control character space, tilde ~, caret ^,
1978 # colon :, question-mark ?, asterisk *, space, or open bracket [
1981 # Additionally, % must be escaped because it is used for escaping
1982 # and we want our escaped refname to be reversible
1983 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1985 # no slash-separated component can begin with a dot .
1987 $refname =~ s{/\.}{/%2E}g;
1989 # It cannot have two consecutive dots .. anywhere
1991 $refname =~ s{\.\.}{%2E%2E}g;
1996 sub desanitize_refname
{
1998 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
2004 return $self->{svm
}->{uuid
} if $self->svm;
2006 unless ($self->{svm
}) {
2007 die "SVM UUID not cached, and reading remotely failed\n";
2009 $self->{svm
}->{uuid
};
2014 return $self->{svm
} if $self->{svm
};
2016 # see if we have it in our config, first:
2018 my $section = "svn-remote.$self->{repo_id}";
2020 source
=> tmp_config
('--get', "$section.svm-source"),
2021 uuid
=> tmp_config
('--get', "$section.svm-uuid"),
2022 replace
=> tmp_config
('--get', "$section.svm-replace"),
2025 if ($svm && $svm->{source
} && $svm->{uuid
} && $svm->{replace
}) {
2026 $self->{svm
} = $svm;
2032 my ($self, $ra) = @_;
2033 return $ra if $self->svm;
2035 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
2036 "(svm:source, svm:uuid) ",
2037 "from the following URLs:\n" );
2038 sub read_svm_props
{
2039 my ($self, $ra, $path, $r) = @_;
2040 my $props = ($ra->get_dir($path, $r))[2];
2041 my $src = $props->{'svm:source'};
2042 my $uuid = $props->{'svm:uuid'};
2043 return undef if (!$src || !$uuid);
2047 $uuid =~ m{^[0-9a-f\-]{30,}$}i
2048 or die "doesn't look right - svm:uuid is '$uuid'\n";
2050 # the '!' is used to mark the repos_root!/relative/path
2051 $src =~ s{/?!/?}{/};
2052 $src =~ s{/+$}{}; # no trailing slashes please
2053 # username is of no interest
2054 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
2056 my $replace = $ra->{url
};
2057 $replace .= "/$path" if length $path;
2059 my $section = "svn-remote.$self->{repo_id}";
2060 tmp_config
("$section.svm-source", $src);
2061 tmp_config
("$section.svm-replace", $replace);
2062 tmp_config
("$section.svm-uuid", $uuid);
2070 my $r = $ra->get_latest_revnum;
2071 my $path = $self->{path
};
2073 while (length $path) {
2074 unless ($tried{"$self->{url}/$path"}) {
2075 return $ra if $self->read_svm_props($ra, $path, $r);
2076 $tried{"$self->{url}/$path"} = 1;
2078 $path =~ s
#/?[^/]+$##;
2080 die "Path: '$path' should be ''\n" if $path ne '';
2081 return $ra if $self->read_svm_props($ra, $path, $r);
2082 $tried{"$self->{url}/$path"} = 1;
2084 if ($ra->{repos_root
} eq $self->{url
}) {
2085 die @err, (map { " $_\n" } keys %tried), "\n";
2088 # nope, make sure we're connected to the repository root:
2091 $path = $ra->{svn_path
};
2092 $ra = Git
::SVN
::Ra
->new($ra->{repos_root
});
2093 while (length $path) {
2094 unless ($tried{"$ra->{url}/$path"}) {
2095 $ok = $self->read_svm_props($ra, $path, $r);
2097 $tried{"$ra->{url}/$path"} = 1;
2099 $path =~ s
#/?[^/]+$##;
2101 die "Path: '$path' should be ''\n" if $path ne '';
2102 $ok ||= $self->read_svm_props($ra, $path, $r);
2103 $tried{"$ra->{url}/$path"} = 1;
2105 die @err, (map { " $_\n" } keys %tried), "\n";
2107 Git
::SVN
::Ra
->new($self->{url
});
2112 return $self->{svnsync
} if $self->{svnsync
};
2114 if ($self->no_metadata) {
2115 die "Can't have both 'noMetadata' and ",
2116 "'useSvnsyncProps' options set!\n";
2118 if ($self->rewrite_root) {
2119 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2124 # see if we have it in our config, first:
2126 my $section = "svn-remote.$self->{repo_id}";
2128 my $url = tmp_config
('--get', "$section.svnsync-url");
2129 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2130 die "doesn't look right - svn:sync-from-url is '$url'\n";
2132 my $uuid = tmp_config
('--get', "$section.svnsync-uuid");
2133 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i
) or
2134 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2136 $svnsync = { url
=> $url, uuid
=> $uuid }
2138 if ($svnsync && $svnsync->{url
} && $svnsync->{uuid
}) {
2139 return $self->{svnsync
} = $svnsync;
2142 my $err = "useSvnsyncProps set, but failed to read " .
2143 "svnsync property: svn:sync-from-";
2144 my $rp = $self->ra->rev_proplist(0);
2146 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2147 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2148 die "doesn't look right - svn:sync-from-url is '$url'\n";
2150 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2151 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i
) or
2152 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2154 my $section = "svn-remote.$self->{repo_id}";
2155 tmp_config
('--add', "$section.svnsync-uuid", $uuid);
2156 tmp_config
('--add', "$section.svnsync-url", $url);
2157 return $self->{svnsync
} = { url
=> $url, uuid
=> $uuid };
2160 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2161 # remote lookup (useful for 'git svn log').
2164 unless ($self->{ra_uuid
}) {
2165 my $key = "svn-remote.$self->{repo_id}.uuid";
2166 my $uuid = eval { tmp_config
('--get', $key) };
2167 if (!$@
&& $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
2168 $self->{ra_uuid
} = $uuid;
2170 die "ra_uuid called without URL\n" unless $self->{url
};
2171 $self->{ra_uuid
} = $self->ra->get_uuid;
2172 tmp_config
('--add', $key, $self->{ra_uuid
});
2178 sub _set_repos_root
{
2179 my ($self, $repos_root) = @_;
2180 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2181 $repos_root ||= $self->ra->{repos_root
};
2182 tmp_config
($k, $repos_root);
2188 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2189 eval { tmp_config
('--get', $k) } || $self->_set_repos_root;
2194 my $ra = Git
::SVN
::Ra
->new($self->{url
});
2195 $self->_set_repos_root($ra->{repos_root
});
2196 if ($self->use_svm_props && !$self->{svm
}) {
2197 if ($self->no_metadata) {
2198 die "Can't have both 'noMetadata' and ",
2199 "'useSvmProps' options set!\n";
2200 } elsif ($self->use_svnsync_props) {
2201 die "Can't have both 'useSvnsyncProps' and ",
2202 "'useSvmProps' options set!\n";
2204 $ra = $self->_set_svm_vars($ra);
2205 $self->{-want_revprops
} = 1;
2210 # prop_walk(PATH, REV, SUB)
2211 # -------------------------
2212 # Recursively traverse PATH at revision REV and invoke SUB for each
2213 # directory that contains a SVN property. SUB will be invoked as
2214 # follows: &SUB(gs, path, props); where `gs' is this instance of
2215 # Git::SVN, `path' the path to the directory where the properties
2216 # `props' were found. The `path' will be relative to point of checkout,
2217 # that is, if url://repo/trunk is the current Git branch, and that
2218 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2219 # as `path' (note the trailing `/').
2221 my ($self, $path, $rev, $sub) = @_;
2224 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2227 # Strip the irrelevant part of the path.
2228 $p =~ s
#^/+\Q$self->{path}\E(/|$)#/#;
2229 # Ensure the path is terminated by a `/'.
2232 # The properties contain all the internal SVN stuff nobody
2233 # (usually) cares about.
2234 my $interesting_props = 0;
2235 foreach (keys %{$props}) {
2236 # If it doesn't start with `svn:', it must be a
2237 # user-defined property.
2238 ++$interesting_props and next if $_ !~ /^svn:/;
2239 # FIXME: Fragile, if SVN adds new public properties,
2240 # this needs to be updated.
2241 ++$interesting_props if /^svn
:(?
:ignore
|keywords
|executable
2242 |eol
-style
|mime
-type
2243 |externals
|needs
-lock)$/x
;
2245 &$sub($self, $p, $props) if $interesting_props;
2247 foreach (sort keys %$dirent) {
2248 next if $dirent->{$_}->{kind
} != $SVN::Node
::dir
;
2249 $self->prop_walk($self->{path
} . $p . $_, $rev, $sub);
2253 sub last_rev
{ ($_[0]->last_rev_commit)[0] }
2254 sub last_commit
{ ($_[0]->last_rev_commit)[1] }
2256 # returns the newest SVN revision number and newest commit SHA1
2257 sub last_rev_commit
{
2259 if (defined $self->{last_rev
} && defined $self->{last_commit
}) {
2260 return ($self->{last_rev
}, $self->{last_commit
});
2262 my $c = ::verify_ref
($self->refname.'^0');
2263 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2264 my $rev = (::cmt_metadata
($c))[1];
2266 ($self->{last_rev
}, $self->{last_commit
}) = ($rev, $c);
2270 my $map_path = $self->map_path;
2271 unless (-e
$map_path) {
2272 ($self->{last_rev
}, $self->{last_commit
}) = (undef, undef);
2273 return (undef, undef);
2275 my ($rev, $commit) = $self->rev_map_max(1);
2276 ($self->{last_rev
}, $self->{last_commit
}) = ($rev, $commit);
2277 return ($rev, $commit);
2280 sub get_fetch_range
{
2281 my ($self, $min, $max) = @_;
2282 $max ||= $self->ra->get_latest_revnum;
2283 $min ||= $self->rev_map_max;
2289 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2290 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2291 if (! -f
$config && -f
$old_def_config) {
2292 rename $old_def_config, $config or
2293 die "Failed rename $old_def_config => $config: $!\n";
2295 my $old_config = $ENV{GIT_CONFIG
};
2296 $ENV{GIT_CONFIG
} = $config;
2299 unless (-f
$config) {
2301 open my $fh, '>', $config or
2302 die "Can't open $config: $!\n";
2303 print $fh "; This file is used internally by ",
2305 "Couldn't write to $config: $!\n";
2306 print $fh "; You should not have to edit it\n" or
2307 die "Couldn't write to $config: $!\n";
2308 close $fh or die "Couldn't close $config: $!\n";
2310 command
('config', @args);
2313 if (defined $old_config) {
2314 $ENV{GIT_CONFIG
} = $old_config;
2316 delete $ENV{GIT_CONFIG
};
2319 wantarray ?
@ret : $ret[0];
2323 my ($self, $sub) = @_;
2324 my $old_index = $ENV{GIT_INDEX_FILE
};
2325 $ENV{GIT_INDEX_FILE
} = $self->{index};
2328 my ($dir, $base) = ($self->{index} =~ m
#^(.*?)/?([^/]+)$#);
2329 mkpath
([$dir]) unless -d
$dir;
2333 if (defined $old_index) {
2334 $ENV{GIT_INDEX_FILE
} = $old_index;
2336 delete $ENV{GIT_INDEX_FILE
};
2339 wantarray ?
@ret : $ret[0];
2342 sub assert_index_clean
{
2343 my ($self, $treeish) = @_;
2345 $self->tmp_index_do(sub {
2346 command_noisy
('read-tree', $treeish) unless -e
$self->{index};
2347 my $x = command_oneline
('write-tree');
2348 my ($y) = (command
(qw
/cat-file commit/, $treeish) =~
2349 /^tree ($::sha1)/mo);
2352 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2353 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2354 command_noisy
('read-tree', $treeish);
2355 $x = command_oneline
('write-tree');
2357 ::fatal
"trees ($treeish) $y != $x\n",
2358 "Something is seriously wrong...";
2363 sub get_commit_parents
{
2364 my ($self, $log_entry) = @_;
2365 my (%seen, @ret, @tmp);
2366 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2367 if (my $ip = $self->{inject_parents
}) {
2368 if (my $commit = delete $ip->{$log_entry->{revision
}}) {
2372 if (my $cur = ::verify_ref
($self->refname.'^0')) {
2375 if (my $ipd = $self->{inject_parents_dcommit
}) {
2376 if (my $commit = delete $ipd->{$log_entry->{revision
}}) {
2377 push @tmp, @
$commit;
2380 push @tmp, $_ foreach (@
{$log_entry->{parents
}}, @tmp);
2381 while (my $p = shift @tmp) {
2385 # MAXPARENT is defined to 16 in commit-tree.c:
2389 die "r$log_entry->{revision}: No room for parents:\n\t",
2390 join("\n\t", @tmp), "\n";
2397 return $self->{-rewrite_root
} if exists $self->{-rewrite_root
};
2398 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2399 my $rwr = eval { command_oneline
(qw
/config --get/, $k) };
2402 if ($rwr !~ m
#^[a-z\+]+://#) {
2403 die "$rwr is not a valid URL (key: $k)\n";
2406 $self->{-rewrite_root
} = $rwr;
2411 ($self->rewrite_root || $self->{url
}) .
2412 (length $self->{path
} ?
'/' . $self->{path
} : '');
2417 $self->{url
} . (length $self->{path
} ?
'/' . $self->{path
} : '');
2421 sub set_commit_header_env
{
2422 my ($log_entry) = @_;
2424 foreach my $ned (qw
/NAME EMAIL DATE/) {
2425 foreach my $ac (qw
/AUTHOR COMMITTER/) {
2426 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2430 $ENV{GIT_AUTHOR_NAME
} = $log_entry->{name
};
2431 $ENV{GIT_AUTHOR_EMAIL
} = $log_entry->{email
};
2432 $ENV{GIT_AUTHOR_DATE
} = $ENV{GIT_COMMITTER_DATE
} = $log_entry->{date
};
2434 $ENV{GIT_COMMITTER_NAME
} = (defined $log_entry->{commit_name
})
2435 ?
$log_entry->{commit_name
}
2436 : $log_entry->{name
};
2437 $ENV{GIT_COMMITTER_EMAIL
} = (defined $log_entry->{commit_email
})
2438 ?
$log_entry->{commit_email
}
2439 : $log_entry->{email
};
2443 sub restore_commit_header_env
{
2445 foreach my $ned (qw
/NAME EMAIL DATE/) {
2446 foreach my $ac (qw
/AUTHOR COMMITTER/) {
2447 my $k = "GIT_${ac}_${ned}";
2448 if (defined $env->{$k}) {
2449 $ENV{$k} = $env->{$k};
2458 command_noisy
('gc', '--auto');
2462 my ($self, $log_entry) = @_;
2463 my $lr = $self->last_rev;
2464 if (defined $lr && $lr >= $log_entry->{revision
}) {
2465 die "Last fetched revision of ", $self->refname,
2466 " was r$lr, but we are about to fetch: ",
2467 "r$log_entry->{revision}!\n";
2469 if (my $c = $self->rev_map_get($log_entry->{revision
})) {
2470 croak
"$log_entry->{revision} = $c already exists! ",
2471 "Why are we refetching it?\n";
2473 my $old_env = set_commit_header_env
($log_entry);
2474 my $tree = $log_entry->{tree
};
2475 if (!defined $tree) {
2476 $tree = $self->tmp_index_do(sub {
2477 command_oneline
('write-tree') });
2479 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2481 my @exec = ('git', 'commit-tree', $tree);
2482 foreach ($self->get_commit_parents($log_entry)) {
2483 push @exec, '-p', $_;
2485 defined(my $pid = open3
(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2489 # we always get UTF-8 from SVN, but we may want our commits in
2490 # a different encoding.
2491 if (my $enc = Git
::config
('i18n.commitencoding')) {
2493 Encode
::from_to
($log_entry->{log}, 'UTF-8', $enc);
2495 print $msg_fh $log_entry->{log} or croak
$!;
2496 restore_commit_header_env
($old_env);
2497 unless ($self->no_metadata) {
2498 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2501 $msg_fh->flush == 0 or croak
$!;
2502 close $msg_fh or croak
$!;
2503 chomp(my $commit = do { local $/; <$out_fh> });
2504 close $out_fh or croak
$!;
2507 if ($commit !~ /^$::sha1$/o) {
2508 die "Failed to commit, invalid sha1: $commit\n";
2511 $self->rev_map_set($log_entry->{revision
}, $commit, 1);
2513 $self->{last_rev
} = $log_entry->{revision
};
2514 $self->{last_commit
} = $commit;
2515 print "r$log_entry->{revision}" unless $::_q
> 1;
2516 if (defined $log_entry->{svm_revision
}) {
2517 print " (\@$log_entry->{svm_revision})" unless $::_q
> 1;
2518 $self->rev_map_set($log_entry->{svm_revision
}, $commit,
2519 0, $self->svm_uuid);
2521 print " = $commit ($self->{ref_id})\n" unless $::_q
> 1;
2522 if (--$_gc_nr == 0) {
2523 $_gc_nr = $_gc_period;
2530 my ($self, $paths, $r) = @_;
2531 return 1 if $self->{path
} eq '';
2532 if (my $path = $paths->{"/$self->{path}"}) {
2533 return ($path->{action
} eq 'D') ?
0 : 1;
2535 $self->{path_regex
} ||= qr/^\/\Q
$self->{path
}\E\
//;
2536 if (grep /$self->{path_regex}/, keys %$paths) {
2540 foreach (split m
#/#, $self->{path}) {
2542 next unless ($paths->{$c} &&
2543 ($paths->{$c}->{action
} =~ /^[AR]$/));
2544 if ($self->ra->check_path($self->{path
}, $r) ==
2552 sub find_parent_branch
{
2553 my ($self, $paths, $rev) = @_;
2554 return undef unless $self->follow_parent;
2555 unless (defined $paths) {
2556 my $err_handler = $SVN::Error
::handler
;
2557 $SVN::Error
::handler
= \
&Git
::SVN
::Ra
::skip_unknown_revs
;
2558 $self->ra->get_log([$self->{path
}], $rev, $rev, 0, 1, 1,
2559 sub { $paths = $_[0] });
2560 $SVN::Error
::handler
= $err_handler;
2562 return undef unless defined $paths;
2564 # look for a parent from another branch:
2565 my @b_path_components = split m
#/#, $self->{path};
2566 my @a_path_components;
2568 while (@b_path_components) {
2569 $i = $paths->{'/'.join('/', @b_path_components)};
2570 last if $i && defined $i->{copyfrom_path
};
2571 unshift(@a_path_components, pop(@b_path_components));
2573 return undef unless defined $i && defined $i->{copyfrom_path
};
2574 my $branch_from = $i->{copyfrom_path
};
2575 if (@a_path_components) {
2576 print STDERR
"branch_from: $branch_from => ";
2577 $branch_from .= '/'.join('/', @a_path_components);
2578 print STDERR
$branch_from, "\n";
2580 my $r = $i->{copyfrom_rev
};
2581 my $repos_root = $self->ra->{repos_root
};
2582 my $url = $self->ra->{url
};
2583 my $new_url = $url . $branch_from;
2584 print STDERR
"Found possible branch point: ",
2585 "$new_url => ", $self->full_url, ", $r\n";
2586 $branch_from =~ s
#^/##;
2587 my $gs = $self->other_gs($new_url, $url,
2588 $branch_from, $r, $self->{ref_id
});
2589 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2592 if (!defined $r0 || !defined $parent) {
2593 ($base, $head) = parse_revision_argument
(0, $r);
2596 $gs->ra->get_log([$gs->{path
}], $r0 + 1, $r, 1,
2597 0, 1, sub { $base = $_[1] - 1 });
2600 if (defined $base && $base <= $r) {
2601 $gs->fetch($base, $r);
2603 ($r0, $parent) = $gs->find_rev_before($r, 1);
2605 if (defined $r0 && defined $parent) {
2606 print STDERR
"Found branch parent: ($self->{ref_id}) $parent\n";
2608 if ($self->ra->can_do_switch) {
2609 $self->assert_index_clean($parent);
2610 print STDERR
"Following parent with do_switch\n";
2611 # do_switch works with svn/trunk >= r22312, but that
2612 # is not included with SVN 1.4.3 (the latest version
2613 # at the moment), so we can't rely on it
2614 $self->{last_rev
} = $r0;
2615 $self->{last_commit
} = $parent;
2616 $ed = SVN
::Git
::Fetcher
->new($self, $gs->{path
});
2617 $gs->ra->gs_do_switch($r0, $rev, $gs,
2618 $self->full_url, $ed)
2619 or die "SVN connection failed somewhere...\n";
2620 } elsif ($self->ra->trees_match($new_url, $r0,
2621 $self->full_url, $rev)) {
2622 print STDERR
"Trees match:\n",
2624 " ${\$self->full_url}\@$rev\n",
2625 "Following parent with no changes\n";
2626 $self->tmp_index_do(sub {
2627 command_noisy
('read-tree', $parent);
2629 $self->{last_commit
} = $parent;
2631 print STDERR
"Following parent with do_update\n";
2632 $ed = SVN
::Git
::Fetcher
->new($self);
2633 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2634 or die "SVN connection failed somewhere...\n";
2636 print STDERR
"Successfully followed parent\n";
2637 return $self->make_log_entry($rev, [$parent], $ed);
2643 my ($self, $paths, $rev) = @_;
2645 my ($last_rev, @parents);
2646 if (my $lc = $self->last_commit) {
2647 # we can have a branch that was deleted, then re-added
2648 # under the same name but copied from another path, in
2649 # which case we'll have multiple parents (we don't
2650 # want to break the original ref, nor lose copypath info):
2651 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2652 push @
{$log_entry->{parents
}}, $lc;
2655 $ed = SVN
::Git
::Fetcher
->new($self);
2656 $last_rev = $self->{last_rev
};
2661 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2664 $ed = SVN
::Git
::Fetcher
->new($self);
2666 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2667 die "SVN connection failed somewhere...\n";
2669 $self->make_log_entry($rev, \
@parents, $ed);
2673 my ($self, $ed) = @_;
2675 my $h = $ed->{empty
};
2676 foreach (sort keys %$h) {
2677 my $act = $h->{$_} ?
'+empty_dir' : '-empty_dir';
2678 push @out, " $act: " . uri_encode
($_);
2679 warn "W: $act: $_\n";
2681 foreach my $t (qw
/dir_prop file_prop/) {
2682 $h = $ed->{$t} or next;
2683 foreach my $path (sort keys %$h) {
2684 my $ppath = $path eq '' ?
'.' : $path;
2685 foreach my $prop (sort keys %{$h->{$path}}) {
2686 next if $SKIP_PROP{$prop};
2687 my $v = $h->{$path}->{$prop};
2688 my $t_ppath_prop = "$t: " .
2689 uri_encode
($ppath) . ' ' .
2692 push @out, " +$t_ppath_prop " .
2695 push @out, " -$t_ppath_prop";
2700 foreach my $t (qw
/absent_file absent_directory/) {
2701 $h = $ed->{$t} or next;
2702 foreach my $parent (sort keys %$h) {
2703 foreach my $path (sort @
{$h->{$parent}}) {
2704 push @out, " $t: " .
2705 uri_encode
("$parent/$path");
2706 warn "W: $t: $parent/$path ",
2707 "Insufficient permissions?\n";
2714 # parse_svn_date(DATE)
2715 # --------------------
2716 # Given a date (in UTC) from Subversion, return a string in the format
2717 # "<TZ Offset> <local date/time>" that Git will use.
2719 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
2720 # is true we'll convert it to the local timezone instead.
2721 sub parse_svn_date
{
2722 my $date = shift || return '+0000 1970-01-01 00:00:00';
2723 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d
{4})\
-(\d\d
)\
-(\d\d
)T
2724 (\d\d
)\
:(\d\d
)\
:(\d\d
)\
.\d
*Z
$/x
) or
2725 croak
"Unable to parse date: $date\n";
2726 my $parsed_date; # Set next.
2728 if ($Git::SVN
::_localtime
) {
2729 # Translate the Subversion datetime to an epoch time.
2730 # Begin by switching ourselves to $date's timezone, UTC.
2731 my $old_env_TZ = $ENV{TZ
};
2735 POSIX
::strftime
('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
2737 # Determine our local timezone (including DST) at the
2738 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
2739 # value of TZ, if any, at the time we were run.
2740 if (defined $Git::SVN
::Log
::TZ
) {
2741 $ENV{TZ
} = $Git::SVN
::Log
::TZ
;
2747 POSIX
::strftime
('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
2749 # This converts $epoch_in_UTC into our local timezone.
2750 my ($sec, $min, $hour, $mday, $mon, $year,
2751 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
2753 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
2754 $our_TZ, $year + 1900, $mon + 1,
2755 $mday, $hour, $min, $sec);
2757 # Reset us to the timezone in effect when we entered
2759 if (defined $old_env_TZ) {
2760 $ENV{TZ
} = $old_env_TZ;
2765 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
2768 return $parsed_date;
2772 my ($self, $new_url, $url,
2773 $branch_from, $r, $old_ref_id) = @_;
2774 my $gs = Git
::SVN
->find_by_url($new_url, $url, $branch_from);
2776 my $ref_id = $old_ref_id;
2777 $ref_id =~ s/\@\d+$//;
2779 # just grow a tail if we're not unique enough :x
2780 $ref_id .= '-' while find_ref
($ref_id);
2781 print STDERR
"Initializing parent: $ref_id\n";
2782 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2783 if ($u =~ s
#^\Q$url\E(/|$)##) {
2786 $repo_id = $self->{repo_id
};
2788 $gs = Git
::SVN
->init($u, $p, $repo_id, $ref_id, 1);
2793 sub call_authors_prog
{
2794 my ($orig_author) = @_;
2795 my $author = `$::_authors_prog $orig_author`;
2797 die "$::_authors_prog failed with exit code $?\n"
2799 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
2800 my ($name, $email) = ($1, $2);
2801 $email = undef if length $2 == 0;
2802 return [$name, $email];
2804 die "Author: $orig_author: $::_authors_prog returned "
2805 . "invalid author format: $author\n";
2811 if (!defined $author || length $author == 0) {
2812 $author = '(no author)';
2814 if (!defined $::users
{$author}) {
2815 if (defined $::_authors_prog
) {
2816 $::users
{$author} = call_authors_prog
($author);
2817 } elsif (defined $::_authors
) {
2818 die "Author: $author not defined in $::_authors file\n";
2824 sub make_log_entry
{
2825 my ($self, $rev, $parents, $ed) = @_;
2826 my $untracked = $self->get_untracked($ed);
2828 open my $un, '>>', "$self->{dir}/unhandled.log" or croak
$!;
2829 print $un "r$rev\n" or croak
$!;
2830 print $un $_, "\n" foreach @
$untracked;
2831 my %log_entry = ( parents
=> $parents || [], revision
=> $rev,
2835 my $logged = delete $self->{logged_rev_props
};
2836 if (!$logged || $self->{-want_revprops
}) {
2837 my $rp = $self->ra->rev_proplist($rev);
2838 foreach (sort keys %$rp) {
2840 if (/^svn:(author|date|log)$/) {
2841 $log_entry{$1} = $v;
2842 } elsif ($_ eq 'svm:headrev') {
2845 print $un " rev_prop: ", uri_encode
($_), ' ',
2846 uri_encode
($v), "\n";
2850 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2852 close $un or croak
$!;
2854 $log_entry{date
} = parse_svn_date
($log_entry{date
});
2855 $log_entry{log} .= "\n";
2856 my $author = $log_entry{author
} = check_author
($log_entry{author
});
2857 my ($name, $email) = defined $::users
{$author} ? @
{$::users
{$author}}
2860 my ($commit_name, $commit_email) = ($name, $email);
2861 if ($_use_log_author) {
2863 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2865 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2868 if (!defined $name_field) {
2869 if (!defined $email) {
2872 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
2873 ($name, $email) = ($1, $2);
2874 } elsif ($name_field =~ /(.*)@/) {
2875 ($name, $email) = ($1, $name_field);
2877 ($name, $email) = ($name_field, $name_field);
2880 if (defined $headrev && $self->use_svm_props) {
2881 if ($self->rewrite_root) {
2882 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2885 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d
+)$}i
;
2886 # we don't want "SVM: initializing mirror for junk" ...
2887 return undef if $r == 0;
2888 my $svm = $self->svm;
2889 if ($uuid ne $svm->{uuid
}) {
2890 die "UUID mismatch on SVM path:\n",
2891 "expected: $svm->{uuid}\n",
2894 my $full_url = $self->full_url;
2895 $full_url =~ s
#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2896 die "Failed to replace '$svm->{replace}' with ",
2897 "'$svm->{source}' in $full_url\n";
2898 # throw away username for storing in records
2899 remove_username
($full_url);
2900 $log_entry{metadata
} = "$full_url\@$r $uuid";
2901 $log_entry{svm_revision
} = $r;
2902 $email ||= "$author\@$uuid";
2903 $commit_email ||= "$author\@$uuid";
2904 } elsif ($self->use_svnsync_props) {
2905 my $full_url = $self->svnsync->{url
};
2906 $full_url .= "/$self->{path}" if length $self->{path
};
2907 remove_username
($full_url);
2908 my $uuid = $self->svnsync->{uuid
};
2909 $log_entry{metadata
} = "$full_url\@$rev $uuid";
2910 $email ||= "$author\@$uuid";
2911 $commit_email ||= "$author\@$uuid";
2913 my $url = $self->metadata_url;
2914 remove_username
($url);
2915 $log_entry{metadata
} = "$url\@$rev " .
2916 $self->ra->get_uuid;
2917 $email ||= "$author\@" . $self->ra->get_uuid;
2918 $commit_email ||= "$author\@" . $self->ra->get_uuid;
2920 $log_entry{name
} = $name;
2921 $log_entry{email
} = $email;
2922 $log_entry{commit_name
} = $commit_name;
2923 $log_entry{commit_email
} = $commit_email;
2928 my ($self, $min_rev, $max_rev, @parents) = @_;
2929 my ($last_rev, $last_commit) = $self->last_rev_commit;
2930 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2931 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2935 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2936 $self->{inject_parents
} = { $rev => $tree };
2937 $self->fetch(undef, undef);
2941 my ($self, $tree) = (shift, shift);
2942 my $log_entry = ::get_commit_entry
($tree);
2943 unless ($self->{last_rev
}) {
2944 ::fatal
("Must have an existing revision to commit");
2946 my %ed_opts = ( r
=> $self->{last_rev
},
2947 log => $log_entry->{log},
2949 tree_a
=> $self->{last_commit
},
2952 $self->set_tree_cb($log_entry, $tree, @_) },
2953 svn_path
=> $self->{path
} );
2954 if (!SVN
::Git
::Editor
->new(\
%ed_opts)->apply_diff) {
2955 print "No changes\nr$self->{last_rev} = $tree\n";
2959 sub rebuild_from_rev_db
{
2960 my ($self, $path) = @_;
2962 open my $fh, '<', $path or croak
"open: $!";
2963 binmode $fh or croak
"binmode: $!";
2965 length($_) == 41 or croak
"inconsistent size in ($_) != 41";
2968 next if $_ eq ('0' x
40);
2969 $self->rev_map_set($r, $_);
2972 close $fh or croak
"close: $!";
2973 unlink $path or croak
"unlink: $!";
2978 my $map_path = $self->map_path;
2979 my $partial = (-e
$map_path && ! -z
$map_path);
2980 return unless ::verify_ref
($self->refname.'^0');
2981 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
2982 my $rev_db = $self->rev_db_path;
2983 $self->rebuild_from_rev_db($rev_db);
2984 if ($self->use_svm_props) {
2985 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
2986 $self->rebuild_from_rev_db($svm_rev_db);
2988 $self->unlink_rev_db_symlink;
2991 print "Rebuilding $map_path ...\n" if (!$partial);
2992 my ($base_rev, $head) = ($partial ?
$self->rev_map_max_norebuild(1) :
2995 command_output_pipe
(qw
/rev-list --pretty=raw --no-color --reverse/,
2996 ($head ?
"$head.." : "") . $self->refname,
2998 my $metadata_url = $self->metadata_url;
2999 remove_username
($metadata_url);
3000 my $svn_uuid = $self->ra_uuid;
3003 if ( m{^commit ($::sha1)$} ) {
3007 next unless s{^\s*(git-svn-id:)}{$1};
3008 my ($url, $rev, $uuid) = ::extract_metadata
($_);
3009 remove_username
($url);
3011 # ignore merges (from set-tree)
3012 next if (!defined $rev || !$uuid);
3014 # if we merged or otherwise started elsewhere, this is
3015 # how we break out of it
3016 if (($uuid ne $svn_uuid) ||
3017 ($metadata_url && $url && ($url ne $metadata_url))) {
3020 if ($partial && $head) {
3021 print "Partial-rebuilding $map_path ...\n";
3022 print "Currently at $base_rev = $head\n";
3026 $self->rev_map_set($rev, $c);
3027 print "r$rev = $c\n";
3029 command_close_pipe
($log, $ctx);
3030 print "Done rebuilding $map_path\n" if (!$partial || !$head);
3031 my $rev_db_path = $self->rev_db_path;
3032 if (-f
$self->rev_db_path) {
3033 unlink $self->rev_db_path or croak
"unlink: $!";
3035 $self->unlink_rev_db_symlink;
3039 # Tie::File seems to be prone to offset errors if revisions get sparse,
3040 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
3041 # one of my favorite modules is out :< Next up would be one of the DBM
3042 # modules, but I'm not sure which is most portable...
3044 # This is the replacement for the rev_db format, which was too big
3045 # and inefficient for large repositories with a lot of sparse history
3048 # The format is this:
3049 # - 24 bytes for every record,
3050 # * 4 bytes for the integer representing an SVN revision number
3051 # * 20 bytes representing the sha1 of a git commit
3052 # - No empty padding records like the old format
3053 # (except the last record, which can be overwritten)
3054 # - new records are written append-only since SVN revision numbers
3055 # increase monotonically
3056 # - lookups on SVN revision number are done via a binary search
3057 # - Piping the file to xxd -c24 is a good way of dumping it for
3058 # viewing or editing (piped back through xxd -r), should the need
3060 # - The last record can be padding revision with an all-zero sha1
3061 # This is used to optimize fetch performance when using multiple
3062 # "fetch" directives in .git/config
3064 # These files are disposable unless noMetadata or useSvmProps is set
3067 my ($fh, $rev, $commit) = @_;
3069 binmode $fh or croak
"binmode: $!";
3070 my $size = (stat($fh))[7];
3071 ($size % 24) == 0 or croak
"inconsistent size: $size";
3075 sysseek($fh, -24, SEEK_END
) or croak
"seek: $!";
3076 my $read = sysread($fh, my $buf, 24) or croak
"read: $!";
3077 $read == 24 or croak
"read only $read bytes (!= 24)";
3078 my ($last_rev, $last_commit) = unpack(rev_map_fmt
, $buf);
3079 if ($last_commit eq ('0' x40
)) {
3081 sysseek($fh, -48, SEEK_END
) or croak
"seek: $!";
3082 $read = sysread($fh, $buf, 24) or
3085 croak
"read only $read bytes (!= 24)";
3086 ($last_rev, $last_commit) =
3087 unpack(rev_map_fmt
, $buf);
3088 if ($last_commit eq ('0' x40
)) {
3089 croak
"inconsistent .rev_map\n";
3092 if ($last_rev >= $rev) {
3093 croak
"last_rev is higher!: $last_rev >= $rev";
3098 sysseek($fh, $wr_offset, SEEK_END
) or croak
"seek: $!";
3099 syswrite($fh, pack(rev_map_fmt
, $rev, $commit), 24) == 24 or
3103 sub _rev_map_reset
{
3104 my ($fh, $rev, $commit) = @_;
3105 my $c = _rev_map_get
($fh, $rev);
3106 $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
3107 my $offset = sysseek($fh, 0, SEEK_CUR
) or croak
"seek: $!";
3108 truncate $fh, $offset or croak
"truncate: $!";
3114 my ($dir, $base) = ($path =~ m
#^(.*?)/?([^/]+)$#);
3115 mkpath
([$dir]) unless -d
$dir;
3116 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
3117 close $fh or die "Couldn't close (create) $path: $!\n";
3122 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
3123 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
3124 my $db = $self->map_path($uuid);
3125 my $db_lock = "$db.lock";
3129 $SIG{INT
} = $SIG{HUP
} = $SIG{TERM
} = $SIG{ALRM
} = $SIG{PIPE
} =
3130 $SIG{USR1
} = $SIG{USR2
} = sub { $sig = $_[0] };
3134 $LOCKFILES{$db_lock} = 1;
3136 # both of these options make our .rev_db file very, very important
3137 # and we can't afford to lose it because rebuild() won't work
3138 if ($self->use_svm_props || $self->no_metadata) {
3140 copy
($db, $db_lock) or die "rev_map_set(@_): ",
3142 "$db => $db_lock ($!)\n";
3144 rename $db, $db_lock or die "rev_map_set(@_): ",
3145 "Failed to rename: ",
3146 "$db => $db_lock ($!)\n";
3149 sysopen(my $fh, $db_lock, O_RDWR
| O_CREAT
)
3150 or croak
"Couldn't open $db_lock: $!\n";
3151 $update_ref eq 'reset' ? _rev_map_reset
($fh, $rev, $commit) :
3152 _rev_map_set
($fh, $rev, $commit);
3154 $fh->flush or die "Couldn't flush $db_lock: $!\n";
3155 $fh->sync or die "Couldn't sync $db_lock: $!\n";
3157 close $fh or croak
$!;
3161 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
3162 command_noisy
('update-ref', '-m', "r$rev$note",
3163 $self->refname, $commit);
3165 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
3166 "$db_lock => $db ($!)\n";
3167 delete $LOCKFILES{$db_lock};
3169 $SIG{INT
} = $SIG{HUP
} = $SIG{TERM
} = $SIG{ALRM
} = $SIG{PIPE
} =
3170 $SIG{USR1
} = $SIG{USR2
} = 'DEFAULT';
3171 kill $sig, $$ if defined $sig;
3175 # If want_commit, this will return an array of (rev, commit) where
3176 # commit _must_ be a valid commit in the archive.
3177 # Otherwise, it'll return the max revision (whether or not the
3178 # commit is valid or just a 0x40 placeholder).
3180 my ($self, $want_commit) = @_;
3182 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
3183 $want_commit ?
($r, $c) : $r;
3186 sub rev_map_max_norebuild
{
3187 my ($self, $want_commit) = @_;
3188 my $map_path = $self->map_path;
3189 stat $map_path or return $want_commit ?
(0, undef) : 0;
3190 sysopen(my $fh, $map_path, O_RDONLY
) or croak
"open: $!";
3191 binmode $fh or croak
"binmode: $!";
3192 my $size = (stat($fh))[7];
3193 ($size % 24) == 0 or croak
"inconsistent size: $size";
3196 close $fh or croak
"close: $!";
3197 return $want_commit ?
(0, undef) : 0;
3200 sysseek($fh, -24, SEEK_END
) or croak
"seek: $!";
3201 sysread($fh, my $buf, 24) == 24 or croak
"read: $!";
3202 my ($r, $c) = unpack(rev_map_fmt
, $buf);
3203 if ($want_commit && $c eq ('0' x40
)) {
3205 return $want_commit ?
(0, undef) : 0;
3207 sysseek($fh, -48, SEEK_END
) or croak
"seek: $!";
3208 sysread($fh, $buf, 24) == 24 or croak
"read: $!";
3209 ($r, $c) = unpack(rev_map_fmt
, $buf);
3210 if ($c eq ('0'x40
)) {
3211 croak
"Penultimate record is all-zeroes in $map_path";
3214 close $fh or croak
"close: $!";
3215 $want_commit ?
($r, $c) : $r;
3219 my ($self, $rev, $uuid) = @_;
3220 my $map_path = $self->map_path($uuid);
3221 return undef unless -e
$map_path;
3223 sysopen(my $fh, $map_path, O_RDONLY
) or croak
"open: $!";
3224 my $c = _rev_map_get
($fh, $rev);
3225 close($fh) or croak
"close: $!";
3230 my ($fh, $rev) = @_;
3232 binmode $fh or croak
"binmode: $!";
3233 my $size = (stat($fh))[7];
3234 ($size % 24) == 0 or croak
"inconsistent size: $size";
3240 my ($l, $u) = (0, $size - 24);
3244 my $i = int(($l/24 + $u/24) / 2) * 24;
3245 sysseek($fh, $i, SEEK_SET
) or croak
"seek: $!";
3246 sysread($fh, my $buf, 24) == 24 or croak
"read: $!";
3247 my ($r, $c) = unpack('NH40', $buf);
3251 } elsif ($r > $rev) {
3253 } else { # $r == $rev
3254 return $c eq ('0' x
40) ?
undef : $c;
3260 # Finds the first svn revision that exists on (if $eq_ok is true) or
3261 # before $rev for the current branch. It will not search any lower
3262 # than $min_rev. Returns the git commit hash and svn revision number
3263 # if found, else (undef, undef).
3264 sub find_rev_before
{
3265 my ($self, $rev, $eq_ok, $min_rev) = @_;
3266 --$rev unless $eq_ok;
3268 my $max_rev = $self->rev_map_max;
3269 $rev = $max_rev if ($rev > $max_rev);
3270 while ($rev >= $min_rev) {
3271 if (my $c = $self->rev_map_get($rev)) {
3276 return (undef, undef);
3279 # Finds the first svn revision that exists on (if $eq_ok is true) or
3280 # after $rev for the current branch. It will not search any higher
3281 # than $max_rev. Returns the git commit hash and svn revision number
3282 # if found, else (undef, undef).
3283 sub find_rev_after
{
3284 my ($self, $rev, $eq_ok, $max_rev) = @_;
3285 ++$rev unless $eq_ok;
3286 $max_rev ||= $self->rev_map_max;
3287 while ($rev <= $max_rev) {
3288 if (my $c = $self->rev_map_get($rev)) {
3293 return (undef, undef);
3297 my ($class, $repo_id, $ref_id, $path) = @_;
3298 unless (defined $repo_id && length $repo_id) {
3299 $repo_id = $Git::SVN
::default_repo_id
;
3301 unless (defined $ref_id && length $ref_id) {
3302 $_[2] = $ref_id = $Git::SVN
::default_ref_id
;
3305 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
3306 $_[3] = $path = '' unless (defined $path);
3307 mkpath
(["$ENV{GIT_DIR}/svn"]);
3309 ref_id
=> $ref_id, dir
=> $dir, index => "$dir/index",
3310 path
=> $path, config
=> "$ENV{GIT_DIR}/svn/config",
3311 map_root
=> "$dir/.rev_map", repo_id
=> $repo_id }, $class;
3314 # for read-only access of old .rev_db formats
3315 sub unlink_rev_db_symlink
{
3317 my $link = $self->rev_db_path;
3318 $link =~ s/\.[\w-]+$// or croak
"missing UUID at the end of $link";
3320 unlink $link or croak
"unlink: $link failed!";
3325 my ($self, $uuid) = @_;
3326 my $db_path = $self->map_path($uuid);
3327 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
3328 or croak
"map_path: $db_path does not contain '/.rev_map.' !";
3332 # the new replacement for .rev_db
3334 my ($self, $uuid) = @_;
3335 $uuid ||= $self->ra_uuid;
3336 "$self->{map_root}.$uuid";
3341 $f =~ s
#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
3345 sub remove_username
{
3346 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
3349 package Git
::SVN
::Prompt
;
3353 use vars qw
/$_no_auth_cache $_username/;
3356 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
3357 $may_save = undef if $_no_auth_cache;
3358 $default_username = $_username if defined $_username;
3359 if (defined $default_username && length $default_username) {
3360 if (defined $realm && length $realm) {
3361 print STDERR
"Authentication realm: $realm\n";
3364 $cred->username($default_username);
3366 username
($cred, $realm, $may_save, $pool);
3368 $cred->password(_read_password
("Password for '" .
3369 $cred->username . "': ", $realm));
3370 $cred->may_save($may_save);
3371 $SVN::_Core
::SVN_NO_ERROR
;
3374 sub ssl_server_trust
{
3375 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
3376 $may_save = undef if $_no_auth_cache;
3377 print STDERR
"Error validating server certificate for '$realm':\n";
3380 # All variables SVN::Auth::SSL::* are used only once,
3381 # so we're shutting up Perl warnings about this.
3382 if ($failures & $SVN::Auth
::SSL
::UNKNOWNCA
) {
3383 print STDERR
" - The certificate is not issued ",
3384 "by a trusted authority. Use the\n",
3385 " fingerprint to validate ",
3386 "the certificate manually!\n";
3388 if ($failures & $SVN::Auth
::SSL
::CNMISMATCH
) {
3389 print STDERR
" - The certificate hostname ",
3390 "does not match.\n";
3392 if ($failures & $SVN::Auth
::SSL
::NOTYETVALID
) {
3393 print STDERR
" - The certificate is not yet valid.\n";
3395 if ($failures & $SVN::Auth
::SSL
::EXPIRED
) {
3396 print STDERR
" - The certificate has expired.\n";
3398 if ($failures & $SVN::Auth
::SSL
::OTHER
) {
3399 print STDERR
" - The certificate has ",
3400 "an unknown error.\n";
3402 } # no warnings 'once'
3404 "Certificate information:\n".
3405 " - Hostname: %s\n".
3406 " - Valid: from %s until %s\n".
3408 " - Fingerprint: %s\n",
3409 map $cert_info->$_, qw(hostname valid_from valid_until
3410 issuer_dname fingerprint);
3413 print STDERR
$may_save ?
3414 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3415 "(R)eject or accept (t)emporarily? ";
3417 $choice = lc(substr(<STDIN
> || 'R', 0, 1));
3418 if ($choice =~ /^t$/i) {
3419 $cred->may_save(undef);
3420 } elsif ($choice =~ /^r$/i) {
3422 } elsif ($may_save && $choice =~ /^p$/i) {
3423 $cred->may_save($may_save);
3427 $cred->accepted_failures($failures);
3428 $SVN::_Core
::SVN_NO_ERROR
;
3431 sub ssl_client_cert
{
3432 my ($cred, $realm, $may_save, $pool) = @_;
3433 $may_save = undef if $_no_auth_cache;
3434 print STDERR
"Client certificate filename: ";
3436 chomp(my $filename = <STDIN
>);
3437 $cred->cert_file($filename);
3438 $cred->may_save($may_save);
3439 $SVN::_Core
::SVN_NO_ERROR
;
3442 sub ssl_client_cert_pw
{
3443 my ($cred, $realm, $may_save, $pool) = @_;
3444 $may_save = undef if $_no_auth_cache;
3445 $cred->password(_read_password
("Password: ", $realm));
3446 $cred->may_save($may_save);
3447 $SVN::_Core
::SVN_NO_ERROR
;
3451 my ($cred, $realm, $may_save, $pool) = @_;
3452 $may_save = undef if $_no_auth_cache;
3453 if (defined $realm && length $realm) {
3454 print STDERR
"Authentication realm: $realm\n";
3457 if (defined $_username) {
3458 $username = $_username;
3460 print STDERR
"Username: ";
3462 chomp($username = <STDIN
>);
3464 $cred->username($username);
3465 $cred->may_save($may_save);
3466 $SVN::_Core
::SVN_NO_ERROR
;
3469 sub _read_password
{
3470 my ($prompt, $realm) = @_;
3471 print STDERR
$prompt;
3473 require Term
::ReadKey
;
3474 Term
::ReadKey
::ReadMode
('noecho');
3476 while (defined(my $key = Term
::ReadKey
::ReadKey
(0))) {
3477 last if $key =~ /[\012\015]/; # \n\r
3480 Term
::ReadKey
::ReadMode
('restore');
3486 package SVN
::Git
::Fetcher
;
3491 use File
::Temp qw
/tempfile/;
3493 use vars qw
/$_ignore_regex/;
3495 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
3497 my ($class, $git_svn, $switch_path) = @_;
3498 my $self = SVN
::Delta
::Editor
->new;
3499 bless $self, $class;
3500 if (exists $git_svn->{last_commit
}) {
3501 $self->{c
} = $git_svn->{last_commit
};
3502 $self->{empty_symlinks
} =
3503 _mark_empty_symlinks
($git_svn, $switch_path);
3505 $self->{ignore_regex
} = eval { command_oneline
('config', '--get',
3506 "svn-remote.$git_svn->{repo_id}.ignore-paths") };
3507 $self->{empty
} = {};
3508 $self->{dir_prop
} = {};
3509 $self->{file_prop
} = {};
3510 $self->{absent_dir
} = {};
3511 $self->{absent_file
} = {};
3512 $self->{gii
} = $git_svn->tmp_index_do(sub { Git
::IndexInfo
->new });
3516 # this uses the Ra object, so it must be called before do_{switch,update},
3517 # not inside them (when the Git::SVN::Fetcher object is passed) to
3518 # do_{switch,update}
3519 sub _mark_empty_symlinks
{
3520 my ($git_svn, $switch_path) = @_;
3521 my $bool = Git
::config_bool
('svn.brokenSymlinkWorkaround');
3522 return {} if (!defined($bool)) || (defined($bool) && ! $bool);
3525 my ($rev, $cmt) = $git_svn->last_rev_commit;
3526 return {} unless ($rev && $cmt);
3528 # allow the warning to be printed for each revision we fetch to
3529 # ensure the user sees it. The user can also disable the workaround
3530 # on the repository even while git svn is running and the next
3531 # revision fetched will skip this expensive function.
3532 my $printed_warning;
3533 chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
3534 my ($ls, $ctx) = command_output_pipe
(qw
/ls-tree -r -z/, $cmt);
3536 my $pfx = defined($switch_path) ?
$switch_path : $git_svn->{path
};
3537 $pfx .= '/' if length($pfx);
3540 s/\A100644 blob $empty_blob\t//o or next;
3541 unless ($printed_warning) {
3542 print STDERR
"Scanning for empty symlinks, ",
3543 "this may take a while if you have ",
3544 "many empty files\n",
3545 "You may disable this with `",
3546 "git config svn.brokenSymlinkWorkaround ",
3548 "This may be done in a different ",
3549 "terminal without restarting ",
3551 $printed_warning = 1;
3554 my (undef, $props) =
3555 $git_svn->ra->get_file($pfx.$path, $rev, undef);
3556 if ($props->{'svn:special'}) {
3560 command_close_pipe
($ls, $ctx);
3564 # returns true if a given path is inside a ".git" directory
3566 $_[0] =~ m{(?:^|/)\.git(?:/|$)};
3569 # return value: 0 -- don't ignore, 1 -- ignore
3570 sub is_path_ignored
{
3571 my ($self, $path) = @_;
3572 return 1 if in_dot_git
($path);
3573 return 1 if defined($self->{ignore_regex
}) &&
3574 $path =~ m!$self->{ignore_regex}!;
3575 return 0 unless defined($_ignore_regex);
3576 return 1 if $path =~ m!$_ignore_regex!o;
3580 sub set_path_strip
{
3581 my ($self, $path) = @_;
3582 $self->{path_strip
} = qr/^\Q$path\E(\/|$)/ if length $path;
3589 sub open_directory
{
3590 my ($self, $path, $pb, $rev) = @_;
3595 my ($self, $path) = @_;
3596 if ($self->{path_strip
}) {
3597 $path =~ s!$self->{path_strip}!! or
3598 die "Failed to strip path '$path' ($self->{path_strip})\n";
3604 my ($self, $path, $rev, $pb) = @_;
3605 return undef if $self->is_path_ignored($path);
3607 my $gpath = $self->git_path($path);
3608 return undef if ($gpath eq '');
3610 # remove entire directories.
3611 my ($tree) = (command
('ls-tree', '-z', $self->{c
}, "./$gpath")
3612 =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
3614 my ($ls, $ctx) = command_output_pipe
(qw
/ls
-tree
3620 my $rmpath = "$gpath/$_";
3621 $self->{gii
}->remove($rmpath);
3622 print "\tD\t$rmpath\n" unless $::_q
;
3624 print "\tD\t$gpath/\n" unless $::_q
;
3625 command_close_pipe
($ls, $ctx);
3626 $self->{empty
}->{$path} = 0
3628 $self->{gii
}->remove($gpath);
3629 print "\tD\t$gpath\n" unless $::_q
;
3635 my ($self, $path, $pb, $rev) = @_;
3638 goto out
if $self->is_path_ignored($path);
3640 my $gpath = $self->git_path($path);
3641 ($mode, $blob) = (command
('ls-tree', '-z', $self->{c
}, "./$gpath")
3642 =~ /\A(\d{6}) blob ([a-f\d]{40})\t\Q$gpath\E\0/);
3643 unless (defined $mode && defined $blob) {
3644 die "$path was not found in commit $self->{c} (r$rev)\n";
3646 if ($mode eq '100644' && $self->{empty_symlinks
}->{$path}) {
3650 { path
=> $path, mode_a
=> $mode, mode_b
=> $mode, blob
=> $blob,
3651 pool
=> SVN
::Pool
->new, action
=> 'M' };
3655 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3658 if (!$self->is_path_ignored($path)) {
3659 my ($dir, $file) = ($path =~ m
#^(.*?)/?([^/]+)$#);
3660 delete $self->{empty
}->{$dir};
3663 { path
=> $path, mode_a
=> $mode, mode_b
=> $mode,
3664 pool
=> SVN
::Pool
->new, action
=> 'A' };
3668 my ($self, $path, $cp_path, $cp_rev) = @_;
3669 goto out
if $self->is_path_ignored($path);
3670 my $gpath = $self->git_path($path);
3672 my ($ls, $ctx) = command_output_pipe
(qw
/ls
-tree
3678 $self->{gii
}->remove($_);
3679 print "\tD\t$_\n" unless $::_q
;
3681 command_close_pipe
($ls, $ctx);
3682 $self->{empty
}->{$path} = 0;
3684 my ($dir, $file) = ($path =~ m
#^(.*?)/?([^/]+)$#);
3685 delete $self->{empty
}->{$dir};
3686 $self->{empty
}->{$path} = 1;
3691 sub change_dir_prop
{
3692 my ($self, $db, $prop, $value) = @_;
3693 return undef if $self->is_path_ignored($db->{path
});
3694 $self->{dir_prop
}->{$db->{path
}} ||= {};
3695 $self->{dir_prop
}->{$db->{path
}}->{$prop} = $value;
3699 sub absent_directory
{
3700 my ($self, $path, $pb) = @_;
3701 return undef if $self->is_path_ignored($path);
3702 $self->{absent_dir
}->{$pb->{path
}} ||= [];
3703 push @
{$self->{absent_dir
}->{$pb->{path
}}}, $path;
3708 my ($self, $path, $pb) = @_;
3709 return undef if $self->is_path_ignored($path);
3710 $self->{absent_file
}->{$pb->{path
}} ||= [];
3711 push @
{$self->{absent_file
}->{$pb->{path
}}}, $path;
3715 sub change_file_prop
{
3716 my ($self, $fb, $prop, $value) = @_;
3717 return undef if $self->is_path_ignored($fb->{path
});
3718 if ($prop eq 'svn:executable') {
3719 if ($fb->{mode_b
} != 120000) {
3720 $fb->{mode_b
} = defined $value ?
100755 : 100644;
3722 } elsif ($prop eq 'svn:special') {
3723 $fb->{mode_b
} = defined $value ?
120000 : 100644;
3725 $self->{file_prop
}->{$fb->{path
}} ||= {};
3726 $self->{file_prop
}->{$fb->{path
}}->{$prop} = $value;
3731 sub apply_textdelta
{
3732 my ($self, $fb, $exp) = @_;
3733 return undef if $self->is_path_ignored($fb->{path
});
3734 my $fh = $::_repository
->temp_acquire('svn_delta');
3735 # $fh gets auto-closed() by SVN::TxDelta::apply(),
3736 # (but $base does not,) so dup() it for reading in close_file
3737 open my $dup, '<&', $fh or croak
$!;
3738 my $base = $::_repository
->temp_acquire('git_blob');
3741 my ($base_is_link, $size);
3743 if ($fb->{mode_a
} eq '120000' &&
3744 ! $self->{empty_symlinks
}->{$fb->{path
}}) {
3745 print $base 'link ' or die "print $!\n";
3749 $size = $::_repository
->cat_blob($fb->{blob
}, $base);
3750 die "Failed to read object $fb->{blob}" if ($size < 0);
3753 seek $base, 0, 0 or croak
$!;
3754 my $got = ::md5sum
($base);
3756 my $err = "Checksum mismatch: ".
3757 "$fb->{path} $fb->{blob}\n" .
3758 "expected: $exp\n" .
3760 if ($base_is_link) {
3762 "Retrying... (possibly ",
3763 "a bad symlink from SVN)\n";
3764 $::_repository
->temp_reset($base);
3772 seek $base, 0, 0 or croak
$!;
3774 $fb->{base
} = $base;
3775 [ SVN
::TxDelta
::apply
($base, $dup, undef, $fb->{path
}, $fb->{pool
}) ];
3779 my ($self, $fb, $exp) = @_;
3780 return undef if $self->is_path_ignored($fb->{path
});
3783 my $path = $self->git_path($fb->{path
});
3784 if (my $fh = $fb->{fh
}) {
3786 seek($fh, 0, 0) or croak
$!;
3787 my $got = ::md5sum
($fh);
3789 die "Checksum mismatch: $path\n",
3790 "expected: $exp\n got: $got\n";
3793 if ($fb->{mode_b
} == 120000) {
3794 sysseek($fh, 0, 0) or croak
$!;
3795 my $rd = sysread($fh, my $buf, 5);
3798 croak
"sysread: $!\n";
3799 } elsif ($rd == 0) {
3800 warn "$path has mode 120000",
3801 " but it points to nothing\n",
3802 "converting to an empty file with mode",
3804 $fb->{mode_b
} = '100644';
3805 } elsif ($buf ne 'link ') {
3806 warn "$path has mode 120000",
3807 " but is not a link\n";
3809 my $tmp_fh = $::_repository
->temp_acquire(
3812 while ($res = sysread($fh, my $str, 1024)) {
3813 my $out = syswrite($tmp_fh, $str, $res);
3814 defined($out) && $out == $res
3816 Git
::temp_path
($tmp_fh),
3819 defined $res or croak
$!;
3821 ($fh, $tmp_fh) = ($tmp_fh, $fh);
3822 Git
::temp_release
($tmp_fh, 1);
3826 $hash = $::_repository
->hash_and_insert_object(
3827 Git
::temp_path
($fh));
3828 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3830 Git
::temp_release
($fb->{base
}, 1);
3831 Git
::temp_release
($fh, 1);
3833 $hash = $fb->{blob
} or die "no blob information\n";
3836 $self->{gii
}->update($fb->{mode_b
}, $hash, $path) or croak
$!;
3837 print "\t$fb->{action}\t$path\n" if $fb->{action
} && ! $::_q
;
3843 $self->{nr
} = $self->{gii
}->{nr
};
3844 delete $self->{gii
};
3845 $self->SUPER::abort_edit
(@_);
3850 $self->{git_commit_ok
} = 1;
3851 $self->{nr
} = $self->{gii
}->{nr
};
3852 delete $self->{gii
};
3853 $self->SUPER::close_edit
(@_);
3856 package SVN
::Git
::Editor
;
3857 use vars qw
/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
3864 my ($class, $opts) = @_;
3865 foreach (qw
/svn_path r ra tree_a tree_b log editor_cb/) {
3866 die "$_ required!\n" unless (defined $opts->{$_});
3869 my $pool = SVN
::Pool
->new;
3870 my $mods = generate_diff
($opts->{tree_a
}, $opts->{tree_b
});
3871 my $types = check_diff_paths
($opts->{ra
}, $opts->{svn_path
},
3874 # $opts->{ra} functions should not be used after this:
3875 my @ce = $opts->{ra
}->get_commit_editor($opts->{log},
3876 $opts->{editor_cb
}, $pool);
3877 my $self = SVN
::Delta
::Editor
->new(@ce, $pool);
3878 bless $self, $class;
3879 foreach (qw
/svn_path r tree_a tree_b/) {
3880 $self->{$_} = $opts->{$_};
3882 $self->{url
} = $opts->{ra
}->{url
};
3883 $self->{mods
} = $mods;
3884 $self->{types
} = $types;
3885 $self->{pool
} = $pool;
3886 $self->{bat
} = { '' => $self->open_root($self->{r
}, $self->{pool
}) };
3888 $self->{path_prefix
} = length $self->{svn_path
} ?
3889 "$self->{svn_path}/" : '';
3890 $self->{config
} = $opts->{config
};
3895 my ($tree_a, $tree_b) = @_;
3896 my @diff_tree = qw(diff-tree -z -r);
3897 if ($_cp_similarity) {
3898 push @diff_tree, "-C$_cp_similarity";
3900 push @diff_tree, '-C';
3902 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3903 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
3904 push @diff_tree, $tree_a, $tree_b;
3905 my ($diff_fh, $ctx) = command_output_pipe
(@diff_tree);
3909 while (<$diff_fh>) {
3910 chomp $_; # this gets rid of the trailing "\0"
3911 if ($state eq 'meta' && /^:(\d
{6})\s
(\d
{6})\s
3912 ($::sha1
)\s
($::sha1
)\s
3913 ([MTCRAD
])\d
*$/xo
) {
3914 push @mods, { mode_a
=> $1, mode_b
=> $2,
3915 sha1_a
=> $3, sha1_b
=> $4,
3917 if ($5 =~ /^(?:C|R)$/) {
3922 } elsif ($state eq 'file_a') {
3923 my $x = $mods[$#mods] or croak
"Empty array\n";
3924 if ($x->{chg
} !~ /^(?:C|R)$/) {
3925 croak
"Error parsing $_, $x->{chg}\n";
3929 } elsif ($state eq 'file_b') {
3930 my $x = $mods[$#mods] or croak
"Empty array\n";
3931 if (exists $x->{file_a
} && $x->{chg
} !~ /^(?:C|R)$/) {
3932 croak
"Error parsing $_, $x->{chg}\n";
3934 if (!exists $x->{file_a
} && $x->{chg
} =~ /^(?:C|R)$/) {
3935 croak
"Error parsing $_, $x->{chg}\n";
3940 croak
"Error parsing $_\n";
3943 command_close_pipe
($diff_fh, $ctx);
3947 sub check_diff_paths
{
3948 my ($ra, $pfx, $rev, $mods) = @_;
3950 $pfx .= '/' if length $pfx;
3952 sub type_diff_paths
{
3953 my ($ra, $types, $path, $rev) = @_;
3954 my @p = split m
#/+#, $path;
3956 unless (defined $types->{$c}) {
3957 $types->{$c} = $ra->check_path($c, $rev);
3960 $c .= '/' . shift @p;
3961 next if defined $types->{$c};
3962 $types->{$c} = $ra->check_path($c, $rev);
3966 foreach my $m (@
$mods) {
3967 foreach my $f (qw
/file_a file_b/) {
3968 next unless defined $m->{$f};
3969 my ($dir) = ($m->{$f} =~ m
#^(.*?)/?(?:[^/]+)$#);
3970 if (length $pfx.$dir && ! defined $types{$dir}) {
3971 type_diff_paths
($ra, \
%types, $pfx.$dir, $rev);
3979 return ($_[0] =~ m
#^(.*?)/?([^/]+)$#);
3983 my ($self, $path) = @_;
3984 $self->{path_prefix
}.(defined $path ?
$path : '');
3988 my ($self, $path) = @_;
3989 if ($self->{url
} =~ m
#^https?://#) {
3990 $path =~ s/([^~a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
3992 $self->{url
} . '/' . $self->repo_path($path);
3997 my $rm = $self->{rm
};
3998 delete $rm->{''}; # we never delete the url we're tracking
4001 foreach (keys %$rm) {
4002 my @d = split m
#/#, $_;
4006 $c .= '/' . shift @d;
4010 delete $rm->{$self->{svn_path
}};
4011 delete $rm->{''}; # we never delete the url we're tracking
4014 my ($fh, $ctx) = command_output_pipe
(qw
/ls-tree --name-only -r -z/,
4019 my @dn = split m
#/#, $_;
4021 delete $rm->{join '/', @dn};
4028 command_close_pipe
($fh, $ctx);
4030 my ($r, $p, $bat) = ($self->{r
}, $self->{pool
}, $self->{bat
});
4031 foreach my $d (sort { $b =~ tr
#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
4032 $self->close_directory($bat->{$d}, $p);
4033 my ($dn) = ($d =~ m
#^(.*?)/?(?:[^/]+)$#);
4034 print "\tD+\t$d/\n" unless $::_q
;
4035 $self->SUPER::delete_entry
($d, $r, $bat->{$dn}, $p);
4040 sub open_or_add_dir
{
4041 my ($self, $full_path, $baton) = @_;
4042 my $t = $self->{types
}->{$full_path};
4044 die "$full_path not known in r$self->{r} or we have a bug!\n";
4048 # SVN::Node::none and SVN::Node::file are used only once,
4049 # so we're shutting up Perl's warnings about them.
4050 if ($t == $SVN::Node
::none
) {
4051 return $self->add_directory($full_path, $baton,
4052 undef, -1, $self->{pool
});
4053 } elsif ($t == $SVN::Node
::dir
) {
4054 return $self->open_directory($full_path, $baton,
4055 $self->{r
}, $self->{pool
});
4056 } # no warnings 'once'
4057 print STDERR
"$full_path already exists in repository at ",
4058 "r$self->{r} and it is not a directory (",
4059 ($t == $SVN::Node
::file ?
'file' : 'unknown'),"/$t)\n";
4060 } # no warnings 'once'
4065 my ($self, $path) = @_;
4066 my $bat = $self->{bat
};
4067 my $repo_path = $self->repo_path($path);
4068 return $bat->{''} unless (length $repo_path);
4069 my @p = split m
#/+#, $repo_path;
4071 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
4074 $c .= '/' . shift @p;
4075 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
4080 # Subroutine to convert a globbing pattern to a regular expression.
4081 # From perl cookbook.
4083 my $globstr = shift;
4084 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
4085 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
4086 return '^' . $globstr . '$';
4089 sub check_autoprop
{
4090 my ($self, $pattern, $properties, $file, $fbat) = @_;
4091 # Convert the globbing pattern to a regular expression.
4092 my $regex = glob2pat
($pattern);
4093 # Check if the pattern matches the file name.
4094 if($file =~ m/($regex)/) {
4095 # Parse the list of properties to set.
4096 my @props = split(/;/, $properties);
4097 foreach my $prop (@props) {
4098 # Parse 'name=value' syntax and set the property.
4099 if ($prop =~ /([^=]+)=(.*)/) {
4100 my ($n,$v) = ($1,$2);
4104 $self->change_file_prop($fbat, $n, $v);
4110 sub apply_autoprops
{
4111 my ($self, $file, $fbat) = @_;
4112 my $conf_t = ${$self->{config
}}{'config'};
4114 # Check [miscellany]/enable-auto-props in svn configuration.
4115 if (SVN
::_Core
::svn_config_get_bool
(
4117 $SVN::_Core
::SVN_CONFIG_SECTION_MISCELLANY
,
4118 $SVN::_Core
::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS
,
4120 # Auto-props are enabled. Enumerate them to look for matches.
4121 my $callback = sub {
4122 $self->check_autoprop($_[0], $_[1], $file, $fbat);
4124 SVN
::_Core
::svn_config_enumerate
(
4126 $SVN::_Core
::SVN_CONFIG_SECTION_AUTO_PROPS
,
4132 my ($self, $m) = @_;
4133 my ($dir, $file) = split_path
($m->{file_b
});
4134 my $pbat = $self->ensure_path($dir);
4135 my $fbat = $self->add_file($self->repo_path($m->{file_b
}), $pbat,
4137 print "\tA\t$m->{file_b}\n" unless $::_q
;
4138 $self->apply_autoprops($file, $fbat);
4139 $self->chg_file($fbat, $m);
4140 $self->close_file($fbat,undef,$self->{pool
});
4144 my ($self, $m) = @_;
4145 my ($dir, $file) = split_path
($m->{file_b
});
4146 my $pbat = $self->ensure_path($dir);
4147 my $fbat = $self->add_file($self->repo_path($m->{file_b
}), $pbat,
4148 $self->url_path($m->{file_a
}), $self->{r
});
4149 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q
;
4150 $self->chg_file($fbat, $m);
4151 $self->close_file($fbat,undef,$self->{pool
});
4155 my ($self, $path, $pbat) = @_;
4156 my $rpath = $self->repo_path($path);
4157 my ($dir, $file) = split_path
($rpath);
4158 $self->{rm
}->{$dir} = 1;
4159 $self->SUPER::delete_entry
($rpath, $self->{r
}, $pbat, $self->{pool
});
4163 my ($self, $m) = @_;
4164 my ($dir, $file) = split_path
($m->{file_b
});
4165 my $pbat = $self->ensure_path($dir);
4166 my $fbat = $self->add_file($self->repo_path($m->{file_b
}), $pbat,
4167 $self->url_path($m->{file_a
}), $self->{r
});
4168 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q
;
4169 $self->apply_autoprops($file, $fbat);
4170 $self->chg_file($fbat, $m);
4171 $self->close_file($fbat,undef,$self->{pool
});
4173 ($dir, $file) = split_path
($m->{file_a
});
4174 $pbat = $self->ensure_path($dir);
4175 $self->delete_entry($m->{file_a
}, $pbat);
4179 my ($self, $m) = @_;
4180 my ($dir, $file) = split_path
($m->{file_b
});
4181 my $pbat = $self->ensure_path($dir);
4182 my $fbat = $self->open_file($self->repo_path($m->{file_b
}),
4183 $pbat,$self->{r
},$self->{pool
});
4184 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q
;
4185 $self->chg_file($fbat, $m);
4186 $self->close_file($fbat,undef,$self->{pool
});
4189 sub T
{ shift->M(@_) }
4191 sub change_file_prop
{
4192 my ($self, $fbat, $pname, $pval) = @_;
4193 $self->SUPER::change_file_prop
($fbat, $pname, $pval, $self->{pool
});
4196 sub _chg_file_get_blob
($$$$) {
4197 my ($self, $fbat, $m, $which) = @_;
4198 my $fh = $::_repository
->temp_acquire("git_blob_$which");
4199 if ($m->{"mode_$which"} =~ /^120/) {
4200 print $fh 'link ' or croak
$!;
4201 $self->change_file_prop($fbat,'svn:special','*');
4202 } elsif ($m->{mode_a
} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
4203 $self->change_file_prop($fbat,'svn:special',undef);
4205 my $blob = $m->{"sha1_$which"};
4206 return ($fh,) if ($blob =~ /^0{40}$/);
4207 my $size = $::_repository
->cat_blob($blob, $fh);
4208 croak
"Failed to read object $blob" if ($size < 0);
4209 $fh->flush == 0 or croak
$!;
4210 seek $fh, 0, 0 or croak
$!;
4212 my $exp = ::md5sum
($fh);
4213 seek $fh, 0, 0 or croak
$!;
4218 my ($self, $fbat, $m) = @_;
4219 if ($m->{mode_b
} =~ /755$/ && $m->{mode_a
} !~ /755$/) {
4220 $self->change_file_prop($fbat,'svn:executable','*');
4221 } elsif ($m->{mode_b
} !~ /755$/ && $m->{mode_a
} =~ /755$/) {
4222 $self->change_file_prop($fbat,'svn:executable',undef);
4224 my ($fh_a, $exp_a) = _chg_file_get_blob
$self, $fbat, $m, 'a';
4225 my ($fh_b, $exp_b) = _chg_file_get_blob
$self, $fbat, $m, 'b';
4226 my $pool = SVN
::Pool
->new;
4227 my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
4229 my $txstream = SVN
::TxDelta
::new
($fh_a, $fh_b, $pool);
4230 my $res = SVN
::TxDelta
::send_txstream
($txstream, @
$atd, $pool);
4232 die "Unexpected result from send_txstream: $res\n",
4233 "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
4236 my $got = SVN
::TxDelta
::send_stream
($fh_b, @
$atd, $pool);
4237 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
4238 if ($got ne $exp_b);
4240 Git
::temp_release
($fh_b, 1);
4241 Git
::temp_release
($fh_a, 1);
4246 my ($self, $m) = @_;
4247 my ($dir, $file) = split_path
($m->{file_b
});
4248 my $pbat = $self->ensure_path($dir);
4249 print "\tD\t$m->{file_b}\n" unless $::_q
;
4250 $self->delete_entry($m->{file_b
}, $pbat);
4255 my ($p,$bat) = ($self->{pool
}, $self->{bat
});
4256 foreach (sort { $b =~ tr
#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
4258 $self->close_directory($bat->{$_}, $p);
4260 $self->close_directory($bat->{''}, $p);
4261 $self->SUPER::close_edit
($p);
4267 $self->SUPER::abort_edit
($self->{pool
});
4272 $self->SUPER::DESTROY
(@_);
4273 $self->{pool
}->clear;
4276 # this drives the editor
4279 my $mods = $self->{mods
};
4280 my %o = ( D
=> 1, R
=> 0, C
=> -1, A
=> 3, M
=> 3, T
=> 3 );
4281 foreach my $m (sort { $o{$a->{chg
}} <=> $o{$b->{chg
}} } @
$mods) {
4283 if (defined $o{$f}) {
4286 fatal
("Invalid change type: $f");
4289 $self->rmdirs if $_rmdir;
4295 return scalar @
$mods;
4298 package Git
::SVN
::Ra
;
4299 use vars qw
/@ISA $config_dir $_log_window_size/;
4302 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
4305 # enforce temporary pool usage for some simple functions
4307 for my $f (qw
/rev_proplist get_latest_revnum get_uuid get_repos_root
4309 my $SUPER = "SUPER::$f";
4312 my $pool = SVN
::Pool
->new;
4313 my @ret = $self->$SUPER(@_,$pool);
4315 wantarray ?
@ret : $ret[0];
4320 sub _auth_providers
() {
4322 SVN
::Client
::get_simple_provider
(),
4323 SVN
::Client
::get_ssl_server_trust_file_provider
(),
4324 SVN
::Client
::get_simple_prompt_provider
(
4325 \
&Git
::SVN
::Prompt
::simple
, 2),
4326 SVN
::Client
::get_ssl_client_cert_file_provider
(),
4327 SVN
::Client
::get_ssl_client_cert_prompt_provider
(
4328 \
&Git
::SVN
::Prompt
::ssl_client_cert
, 2),
4329 SVN
::Client
::get_ssl_client_cert_pw_file_provider
(),
4330 SVN
::Client
::get_ssl_client_cert_pw_prompt_provider
(
4331 \
&Git
::SVN
::Prompt
::ssl_client_cert_pw
, 2),
4332 SVN
::Client
::get_username_provider
(),
4333 SVN
::Client
::get_ssl_server_trust_prompt_provider
(
4334 \
&Git
::SVN
::Prompt
::ssl_server_trust
),
4335 SVN
::Client
::get_username_prompt_provider
(
4336 \
&Git
::SVN
::Prompt
::username
, 2)
4340 sub escape_uri_only
{
4343 foreach (split m{/}, $uri) {
4344 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
4352 if ($url =~ m
#^(https?)://([^/]+)(.*)$#) {
4353 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only
($3));
4354 $url = "$scheme://$domain$uri";
4360 my ($class, $url) = @_;
4362 return $RA if ($RA && $RA->{url
} eq $url);
4364 SVN
::_Core
::svn_config_ensure
($config_dir, undef);
4365 my ($baton, $callbacks) = SVN
::Core
::auth_open_helper
(_auth_providers
);
4366 my $config = SVN
::Core
::config_get_config
($config_dir);
4368 my $dont_store_passwords = 1;
4369 my $conf_t = ${$config}{'config'};
4372 # The usage of $SVN::_Core::SVN_CONFIG_* variables
4373 # produces warnings that variables are used only once.
4374 # I had not found the better way to shut them up, so
4375 # the warnings of type 'once' are disabled in this block.
4376 if (SVN
::_Core
::svn_config_get_bool
($conf_t,
4377 $SVN::_Core
::SVN_CONFIG_SECTION_AUTH
,
4378 $SVN::_Core
::SVN_CONFIG_OPTION_STORE_PASSWORDS
,
4380 SVN
::_Core
::svn_auth_set_parameter
($baton,
4381 $SVN::_Core
::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS
,
4382 bless (\
$dont_store_passwords, "_p_void"));
4384 if (SVN
::_Core
::svn_config_get_bool
($conf_t,
4385 $SVN::_Core
::SVN_CONFIG_SECTION_AUTH
,
4386 $SVN::_Core
::SVN_CONFIG_OPTION_STORE_AUTH_CREDS
,
4388 $Git::SVN
::Prompt
::_no_auth_cache
= 1;
4390 } # no warnings 'once'
4391 my $self = SVN
::Ra
->new(url
=> escape_url
($url), auth
=> $baton,
4393 pool
=> SVN
::Pool
->new,
4394 auth_provider_callbacks
=> $callbacks);
4395 $self->{url
} = $url;
4396 $self->{svn_path
} = $url;
4397 $self->{repos_root
} = $self->get_repos_root;
4398 $self->{svn_path
} =~ s
#^\Q$self->{repos_root}\E(/|$)##;
4399 $self->{cache
} = { check_path
=> { r
=> 0, data
=> {} },
4400 get_dir
=> { r
=> 0, data
=> {} } };
4401 $RA = bless $self, $class;
4405 my ($self, $path, $r) = @_;
4406 my $cache = $self->{cache
}->{check_path
};
4407 if ($r == $cache->{r
} && exists $cache->{data
}->{$path}) {
4408 return $cache->{data
}->{$path};
4410 my $pool = SVN
::Pool
->new;
4411 my $t = $self->SUPER::check_path
($path, $r, $pool);
4413 if ($r != $cache->{r
}) {
4414 %{$cache->{data
}} = ();
4417 $cache->{data
}->{$path} = $t;
4421 my ($self, $dir, $r) = @_;
4422 my $cache = $self->{cache
}->{get_dir
};
4423 if ($r == $cache->{r
}) {
4424 if (my $x = $cache->{data
}->{$dir}) {
4425 return wantarray ? @
$x : $x->[0];
4428 my $pool = SVN
::Pool
->new;
4429 my ($d, undef, $props) = $self->SUPER::get_dir
($dir, $r, $pool);
4430 my %dirents = map { $_ => { kind
=> $d->{$_}->kind } } keys %$d;
4432 if ($r != $cache->{r
}) {
4433 %{$cache->{data
}} = ();
4436 $cache->{data
}->{$dir} = [ \
%dirents, $r, $props ];
4437 wantarray ?
(\
%dirents, $r, $props) : \
%dirents;
4441 # do not call the real DESTROY since we store ourselves in $RA
4444 # get_log(paths, start, end, limit,
4445 # discover_changed_paths, strict_node_history, receiver)
4447 my ($self, @args) = @_;
4448 my $pool = SVN
::Pool
->new;
4450 # svn_log_changed_path_t objects passed to get_log are likely to be
4451 # overwritten even if only the refs are copied to an external variable,
4452 # so we should dup the structures in their entirety. Using an
4453 # externally passed pool (instead of our temporary and quickly cleared
4454 # pool in Git::SVN::Ra) does not help matters at all...
4455 my $receiver = pop @args;
4456 my $prefix = "/".$self->{svn_path
};
4457 $prefix =~ s
#/+($)##;
4458 my $prefix_regex = qr
#^\Q$prefix\E#;
4460 my ($paths) = $_[0];
4461 return &$receiver(@_) unless $paths;
4463 foreach my $p (keys %$paths) {
4464 my $i = $paths->{$p};
4465 # Make path relative to our url, not repos_root
4466 $p =~ s/$prefix_regex//;
4467 my %s = map { $_ => $i->$_; }
4468 qw
/copyfrom_path copyfrom_rev action/;
4469 if ($s{'copyfrom_path'}) {
4470 $s{'copyfrom_path'} =~ s/$prefix_regex//;
4478 # the limit parameter was not supported in SVN 1.1.x, so we
4479 # drop it. Therefore, the receiver callback passed to it
4480 # is made aware of this limitation by being wrapped if
4481 # the limit passed to is being wrapped.
4482 if ($SVN::Core
::VERSION
le '1.2.0') {
4483 my $limit = splice(@args, 3, 1);
4485 my $receiver = pop @args;
4486 push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
4489 my $ret = $self->SUPER::get_log
(@args, $pool);
4495 my ($self, $url1, $rev1, $url2, $rev2) = @_;
4496 my $ctx = SVN
::Client
->new(auth
=> _auth_providers
);
4497 my $out = IO
::File
->new_tmpfile;
4499 # older SVN (1.1.x) doesn't take $pool as the last parameter for
4500 # $ctx->diff(), so we'll create a default one
4501 my $pool = SVN
::Pool
->new_default_sub;
4503 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
4504 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
4506 my $ret = (($out->stat)[7] == 0);
4507 close $out or croak
$!;
4512 sub get_commit_editor
{
4513 my ($self, $log, $cb, $pool) = @_;
4514 my @lock = $SVN::Core
::VERSION
ge '1.2.0' ?
(undef, 0) : ();
4515 $self->SUPER::get_commit_editor
($log, $cb, @lock, $pool);
4519 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
4520 my $new = ($rev_a == $rev_b);
4521 my $path = $gs->{path
};
4523 if ($new && -e
$gs->{index}) {
4524 unlink $gs->{index} or die
4525 "Couldn't unlink index: $gs->{index}: $!\n";
4527 my $pool = SVN
::Pool
->new;
4528 $editor->set_path_strip($path);
4529 my (@pc) = split m
#/#, $path;
4530 my $reporter = $self->do_update($rev_b, (@pc ?
shift @pc : ''),
4532 my @lock = $SVN::Core
::VERSION
ge '1.2.0' ?
(undef) : ();
4534 # Since we can't rely on svn_ra_reparent being available, we'll
4535 # just have to do some magic with set_path to make it so
4536 # we only want a partial path.
4538 my $final = join('/', @pc);
4540 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
4541 $sp .= '/' if length $sp;
4544 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
4546 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
4548 $reporter->finish_report($pool);
4550 $editor->{git_commit_ok
};
4553 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
4554 # svn_ra_reparent didn't work before 1.4)
4556 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
4557 my $path = $gs->{path
};
4558 my $pool = SVN
::Pool
->new;
4560 my $full_url = $self->{url
};
4561 my $old_url = $full_url;
4562 $full_url .= '/' . $path if length $path;
4563 my ($ra, $reparented);
4565 if ($old_url =~ m
#^svn(\+ssh)?://# ||
4566 ($full_url =~ m
#^https?://# &&
4567 escape_url
($full_url) ne $full_url)) {
4571 $ra = Git
::SVN
::Ra
->new($full_url);
4573 } elsif ($old_url ne $full_url) {
4574 SVN
::_Ra
::svn_ra_reparent
($self->{session
}, $full_url, $pool);
4575 $self->{url
} = $full_url;
4580 $url_b = escape_url
($url_b);
4581 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
4582 my @lock = $SVN::Core
::VERSION
ge '1.2.0' ?
(undef) : ();
4583 $reporter->set_path('', $rev_a, 0, @lock, $pool);
4584 $reporter->finish_report($pool);
4587 SVN
::_Ra
::svn_ra_reparent
($self->{session
}, $old_url, $pool);
4588 $self->{url
} = $old_url;
4592 $editor->{git_commit_ok
};
4595 sub longest_common_path
{
4596 my ($gsv, $globs) = @_;
4598 my $common_max = scalar @
$gsv;
4600 foreach my $gs (@
$gsv) {
4601 my @tmp = split m
#/#, $gs->{path};
4604 $p .= length($p) ?
"/$_" : $_;
4610 $common_max += scalar @
$globs;
4611 foreach my $glob (@
$globs) {
4612 my @tmp = split m
#/#, $glob->{path}->{left};
4615 $p .= length($p) ?
"/$_" : $_;
4621 my $longest_path = '';
4622 foreach (sort {length $b <=> length $a} keys %common) {
4623 if ($common{$_} == $common_max) {
4631 sub gs_fetch_loop_common
{
4632 my ($self, $base, $head, $gsv, $globs) = @_;
4633 return if ($base > $head);
4634 my $inc = $_log_window_size;
4635 my ($min, $max) = ($base, $head < $base + $inc ?
$head : $base + $inc);
4636 my $longest_path = longest_common_path
($gsv, $globs);
4637 my $ra_url = $self->{url
};
4638 my $find_trailing_edge;
4642 my $err_handler = $SVN::Error
::handler
;
4643 $SVN::Error
::handler
= sub {
4645 skip_unknown_revs
($err);
4648 my ($paths, $r, $author, $date, $log) = @_;
4650 { author
=> $author, date
=> $date, log => $log } ];
4652 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
4653 sub { $revs{$_[1]} = _cb
(@_) });
4655 print "Checked through r$max\r";
4657 $find_trailing_edge = 1;
4659 if ($err and $find_trailing_edge) {
4660 print STDERR
"Path '$longest_path' ",
4661 "was probably deleted:\n",
4662 $err->expanded_message,
4663 "\nWill attempt to follow ",
4664 "revisions r$min .. r$max ",
4665 "committed before the deletion\n";
4667 while (--$hi >= $min) {
4669 $self->get_log([$longest_path], $min, $hi,
4672 $revs{$_[1]} = _cb
(@_) });
4674 print STDERR
"r$min .. r$ok OK\n";
4678 $find_trailing_edge = 0;
4680 $SVN::Error
::handler
= $err_handler;
4682 my %exists = map { $_->{path
} => $_ } @
$gsv;
4683 foreach my $r (sort {$a <=> $b} keys %revs) {
4684 my ($paths, $logged) = @
{$revs{$r}};
4686 foreach my $gs ($self->match_globs(\
%exists, $paths,
4688 if ($gs->rev_map_max >= $r) {
4691 next unless $gs->match_paths($paths, $r);
4692 $gs->{logged_rev_props
} = $logged;
4693 if (my $last_commit = $gs->last_commit) {
4694 $gs->assert_index_clean($last_commit);
4696 my $log_entry = $gs->do_fetch($paths, $r);
4698 $gs->do_git_commit($log_entry);
4700 $INDEX_FILES{$gs->{index}} = 1;
4702 foreach my $g (@
$globs) {
4703 my $k = "svn-remote.$g->{remote}." .
4705 Git
::SVN
::tmp_config
($k, $r);
4711 $self = Git
::SVN
::Ra
->new($ra_url);
4712 $ra_invalid = undef;
4715 # pre-fill the .rev_db since it'll eventually get filled in
4716 # with '0' x40 if something new gets committed
4717 foreach my $gs (@
$gsv) {
4718 next if $gs->rev_map_max >= $max;
4719 next if defined $gs->rev_map_get($max);
4720 $gs->rev_map_set($max, 0 x40
);
4722 foreach my $g (@
$globs) {
4723 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
4724 Git
::SVN
::tmp_config
($k, $max);
4726 last if $max >= $head;
4729 $max = $head if ($max > $head);
4734 sub get_dir_globbed
{
4735 my ($self, $left, $depth, $r) = @_;
4737 my @x = eval { $self->get_dir($left, $r) };
4738 return unless scalar @x == 3;
4739 my $dirents = $x[0];
4741 foreach my $de (keys %$dirents) {
4742 next if $dirents->{$de}->{kind
} != $SVN::Node
::dir
;
4744 my @args = ("$left/$de", $depth - 1, $r);
4745 foreach my $dir ($self->get_dir_globbed(@args)) {
4746 push @finalents, "$de/$dir";
4749 push @finalents, $de;
4756 my ($self, $exists, $paths, $globs, $r) = @_;
4759 my ($self, $exists, $g, $r) = @_;
4761 my @dirs = $self->get_dir_globbed($g->{path
}->{left
},
4762 $g->{path
}->{depth
},
4765 foreach my $de (@dirs) {
4766 my $p = $g->{path
}->full_path($de);
4767 next if $exists->{$p};
4768 next if (length $g->{path
}->{right
} &&
4769 ($self->check_path($p, $r) !=
4771 $exists->{$p} = Git
::SVN
->init($self->{url
}, $p, undef,
4772 $g->{ref}->full_path($de), 1);
4775 foreach my $g (@
$globs) {
4776 if (my $path = $paths->{"/$g->{path}->{left}"}) {
4777 if ($path->{action
} =~ /^[AR]$/) {
4778 get_dir_check
($self, $exists, $g, $r);
4781 foreach (keys %$paths) {
4782 if (/$g->{path}->{left_regex}/ &&
4783 !/$g->{path}->{regex}/) {
4784 next if $paths->{$_}->{action
} !~ /^[AR]$/;
4785 get_dir_check
($self, $exists, $g, $r);
4787 next unless /$g->{path}->{regex}/;
4789 my $pathname = $g->{path
}->full_path($p);
4790 next if $exists->{$pathname};
4791 next if ($self->check_path($pathname, $r) !=
4793 $exists->{$pathname} = Git
::SVN
->init(
4794 $self->{url
}, $pathname, undef,
4795 $g->{ref}->full_path($p), 1);
4798 foreach (split m
#/#, $g->{path}->{left}) {
4800 next unless ($paths->{$c} &&
4801 ($paths->{$c}->{action
} =~ /^[AR]$/));
4802 get_dir_check
($self, $exists, $g, $r);
4810 return $self->{url
} if ($self->{url
} eq $self->{repos_root
});
4811 my $url = $self->{repos_root
};
4812 my @components = split(m!/!, $self->{svn_path
});
4815 $url .= "/$c" if length $c;
4816 eval { (ref $self)->new($url)->get_latest_revnum };
4817 } while ($@
&& ($c = shift @components));
4823 unless (defined $can_do_switch) {
4824 my $pool = SVN
::Pool
->new;
4826 $self->do_switch(1, '', 0, $self->{url
},
4827 SVN
::Delta
::Editor
->new, $pool);
4832 $rep->abort_report($pool);
4840 sub skip_unknown_revs
{
4842 my $errno = $err->apr_err();
4843 # Maybe the branch we're tracking didn't
4844 # exist when the repo started, so it's
4845 # not an error if it doesn't, just continue
4847 # Wonderfully consistent library, eh?
4848 # 160013 - svn:// and file://
4849 # 175002 - http(s)://
4850 # 175007 - http(s):// (this repo required authorization, too...)
4851 # More codes may be discovered later...
4852 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
4853 my $err_key = $err->expanded_message;
4854 # revision numbers change every time, filter them out
4855 $err_key =~ s/\d+/\0/g;
4856 $err_key = "$errno\0$err_key";
4857 unless ($ignored_err{$err_key}) {
4858 warn "W: Ignoring error from SVN, path probably ",
4859 "does not exist: ($errno): ",
4860 $err->expanded_message,"\n";
4861 warn "W: Do not be alarmed at the above message ",
4862 "git-svn is just searching aggressively for ",
4864 "This may take a while on large repositories\n";
4865 $ignored_err{$err_key} = 1;
4869 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
4872 package Git
::SVN
::Log
;
4875 use POSIX qw
/strftime/;
4877 use constant commit_log_separator
=> ('-' x
72) . "\n";
4878 use vars qw
/$TZ $limit $color $pager $non_recursive $verbose $oneline
4879 %rusers $show_commit $incremental/;
4884 return 1 if defined $c->{r
};
4886 # big commit message got truncated by the 16k pretty buffer in rev-list
4887 if ($c->{l
} && $c->{l
}->[-1] eq "...\n" &&
4888 $c->{a_raw
} =~ /\@([a-f\d\-]+)>$/) {
4890 my @log = command
(qw
/cat-file commit/, $c->{c
});
4892 # shift off the headers
4893 shift @log while ($log[0] ne '');
4896 # TODO: make $c->{l} not have a trailing newline in the future
4897 @
{$c->{l
}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
4899 (undef, $c->{r
}, undef) = ::extract_metadata
(
4900 (grep(/^git-svn-id: /, @log))[-1]);
4902 return defined $c->{r
};
4906 return $color || Git
->repository->get_colorbool('color.diff');
4909 sub git_svn_log_cmd
{
4910 my ($r_min, $r_max, @args) = @_;
4912 my (@files, @log_opts);
4913 foreach my $x (@args) {
4914 if ($x eq '--' || @files) {
4917 if (::verify_ref
("$x^0")) {
4925 my ($url, $rev, $uuid, $gs) = ::working_head_info
($head);
4926 $gs ||= Git
::SVN
->_new;
4927 my @cmd = (qw
/log --abbrev-commit --pretty=raw --default/,
4929 push @cmd, '-r' unless $non_recursive;
4930 push @cmd, qw
/--raw --name-status/ if $verbose;
4931 push @cmd, '--color' if log_use_color
();
4932 push @cmd, @log_opts;
4933 if (defined $r_max && $r_max == $r_min) {
4934 push @cmd, '--max-count=1';
4935 if (my $c = $gs->rev_map_get($r_max)) {
4938 } elsif (defined $r_max) {
4939 if ($r_max < $r_min) {
4940 ($r_min, $r_max) = ($r_max, $r_min);
4942 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
4943 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
4944 # If there are no commits in the range, both $c_max and $c_min
4945 # will be undefined. If there is at least 1 commit in the
4946 # range, both will be defined.
4947 return () if !defined $c_min || !defined $c_max;
4948 if ($c_min eq $c_max) {
4949 push @cmd, '--max-count=1', $c_min;
4951 push @cmd, '--boundary', "$c_min..$c_max";
4954 return (@cmd, @files);
4957 # adapted from pager.c
4959 $pager ||= $ENV{GIT_PAGER
} || $ENV{PAGER
};
4960 if (!defined $pager) {
4962 } elsif (length $pager == 0 || $pager eq 'cat') {
4965 $ENV{GIT_PAGER_IN_USE
} = defined($pager);
4969 return unless -t
*STDOUT
&& defined $pager;
4970 pipe my ($rfd, $wfd) or return;
4971 defined(my $pid = fork) or ::fatal
"Can't fork: $!";
4973 open STDOUT
, '>&', $wfd or
4974 ::fatal
"Can't redirect to stdout: $!";
4977 open STDIN
, '<&', $rfd or ::fatal
"Can't redirect stdin: $!";
4978 $ENV{LESS
} ||= 'FRSX';
4979 exec $pager or ::fatal
"Can't run pager: $! ($pager)";
4982 sub format_svn_date
{
4983 # some systmes don't handle or mishandle %z, so be creative.
4984 my $t = shift || time;
4985 my $gm = timelocal
(gmtime($t));
4986 my $sign = qw( + + - )[ $t <=> $gm ];
4987 my $gmoff = sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
4988 return strftime
("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
4991 sub parse_git_date
{
4993 # Date::Parse isn't in the standard Perl distro :(
4994 if ($tz =~ s/^\+//) {
4995 $t += tz_to_s_offset
($tz);
4996 } elsif ($tz =~ s/^\-//) {
4997 $t -= tz_to_s_offset
($tz);
5002 sub set_local_timezone
{
5010 sub tz_to_s_offset
{
5013 return ($1 * 60) + ($tz * 3600);
5016 sub get_author_info
{
5017 my ($dest, $author, $t, $tz) = @_;
5018 $author =~ s/(?:^\s*|\s*$)//g;
5019 $dest->{a_raw
} = $author;
5022 $au = $rusers{$author} || undef;
5025 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
5030 $dest->{t_utc
} = parse_git_date
($t, $tz);
5033 sub process_commit
{
5034 my ($c, $r_min, $r_max, $defer) = @_;
5035 if (defined $r_min && defined $r_max) {
5036 if ($r_min == $c->{r
} && $r_min == $r_max) {
5040 return 1 if $r_min == $r_max;
5041 if ($r_min < $r_max) {
5042 # we need to reverse the print order
5043 return 0 if (defined $limit && --$limit < 0);
5047 if ($r_min != $r_max) {
5048 return 1 if ($r_min < $c->{r
});
5049 return 1 if ($r_max > $c->{r
});
5052 return 0 if (defined $limit && --$limit < 0);
5061 if (my $l = $c->{l
}) {
5062 while ($l->[0] =~ /^\s*$/) { shift @
$l }
5065 $l_fmt ||= 'A' . length($c->{r
});
5066 print 'r',pack($l_fmt, $c->{r
}),' | ';
5067 print "$c->{c} | " if $show_commit;
5070 show_commit_normal
($c);
5074 sub show_commit_changed_paths
{
5076 return unless $c->{changed
};
5077 print "Changed paths:\n", @
{$c->{changed
}};
5080 sub show_commit_normal
{
5082 print commit_log_separator
, "r$c->{r} | ";
5083 print "$c->{c} | " if $show_commit;
5084 print "$c->{a} | ", format_svn_date
($c->{t_utc
}), ' | ';
5087 if (my $l = $c->{l
}) {
5088 while ($l->[$#$l] eq "\n" && $#$l > 0
5089 && $l->[($#$l - 1)] eq "\n") {
5092 $nr_line = scalar @
$l;
5094 print "1 line\n\n\n";
5096 if ($nr_line == 1) {
5097 $nr_line = '1 line';
5099 $nr_line .= ' lines';
5101 print $nr_line, "\n";
5102 show_commit_changed_paths
($c);
5104 print $_ foreach @
$l;
5108 show_commit_changed_paths
($c);
5112 foreach my $x (qw
/raw stat diff/) {
5115 print $_ foreach @
{$c->{$x}}
5122 my ($r_min, $r_max);
5123 my $r_last = -1; # prevent dupes
5124 set_local_timezone
();
5125 if (defined $::_revision
) {
5126 if ($::_revision
=~ /^(\d+):(\d+)$/) {
5127 ($r_min, $r_max) = ($1, $2);
5128 } elsif ($::_revision
=~ /^\d+$/) {
5129 $r_min = $r_max = $::_revision
;
5131 ::fatal
"-r$::_revision is not supported, use ",
5132 "standard 'git log' arguments instead";
5137 @args = git_svn_log_cmd
($r_min, $r_max, @args);
5139 print commit_log_separator
unless $incremental || $oneline;
5142 my $log = command_output_pipe
(@args);
5144 my (@k, $c, $d, $stat);
5145 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
5147 if (/^${esc_color}commit -?($::sha1_short)/o) {
5149 if ($c && cmt_showable
($c) && $c->{r
} != $r_last) {
5151 process_commit
($c, $r_min, $r_max, \
@k) or
5156 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
5157 get_author_info
($c, $1, $2, $3);
5158 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
5160 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
5161 push @
{$c->{raw
}}, $_;
5162 } elsif (/^${esc_color}[ACRMDT]\t/) {
5163 # we could add $SVN->{svn_path} here, but that requires
5164 # remote access at the moment (repo_path_split)...
5165 s
#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
5166 push @
{$c->{changed
}}, $_;
5167 } elsif (/^${esc_color}diff /o) {
5169 push @
{$c->{diff
}}, $_;
5171 push @
{$c->{diff
}}, $_;
5172 } elsif (/^\
.+\ \
|\s
*\d
+\
$esc_color[\
+\
-]*
5173 $esc_color*[\
+\
-]*$esc_color$/x
) {
5175 push @
{$c->{stat}}, $_;
5176 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
5177 push @
{$c->{stat}}, $_;
5179 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
5180 ($c->{url
}, $c->{r
}, undef) = ::extract_metadata
($1);
5181 } elsif (s/^${esc_color} //o) {
5182 push @
{$c->{l
}}, $_;
5185 if ($c && defined $c->{r
} && $c->{r
} != $r_last) {
5187 process_commit
($c, $r_min, $r_max, \
@k);
5190 ($r_min, $r_max) = ($r_max, $r_min);
5191 process_commit
($_, $r_min, $r_max) foreach reverse @k;
5195 print commit_log_separator
unless $incremental || $oneline;
5204 my ($fh, $ctx, $rev);
5207 ($fh, $ctx) = command_output_pipe
('blame', @_, $path);
5208 while (my $line = <$fh>) {
5209 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
5210 # Uncommitted edits show up as a rev ID of
5211 # all zeros, which we can't look up with
5214 (undef, $rev, undef) =
5216 $rev = '0' if (!$rev);
5220 $rev = sprintf('%-10s', $rev);
5221 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
5226 ($fh, $ctx) = command_output_pipe
('blame', '-p', @_, 'HEAD',
5231 my %dsha; #distinct sha keys
5233 while (my $line = <$fh>) {
5234 push @buffer, $line;
5235 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5240 my $s2r = ::cmt_sha2rev_batch
([keys %dsha]);
5242 foreach my $line (@buffer) {
5243 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5245 $rev = '0' if (!$rev)
5247 elsif ($line =~ /^author (.*)/) {
5248 $authors{$rev} = $1;
5249 $authors{$rev} =~ s/\s/_/g;
5251 elsif ($line =~ /^\t(.*)$/) {
5252 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
5256 command_close_pipe
($fh, $ctx);
5259 package Git
::SVN
::Migration
;
5260 # these version numbers do NOT correspond to actual version numbers
5261 # of git nor git-svn. They are just relative.
5263 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
5265 # v1 layout: .git/$id/info/url, refs/remotes/$id
5267 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
5269 # v3 layout: .git/svn/$id, refs/remotes/$id
5270 # - info/url may remain for backwards compatibility
5271 # - this is what we migrate up to this layout automatically,
5272 # - this will be used by git svn init on single branches
5273 # v3.1 layout (auto migrated):
5274 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
5275 # for backwards compatibility
5277 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
5278 # - this is only created for newly multi-init-ed
5279 # repositories. Similar in spirit to the
5280 # --use-separate-remotes option in git-clone (now default)
5281 # - we do not automatically migrate to this (following
5282 # the example set by core git)
5284 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
5285 # - newer, more-efficient format that uses 24-bytes per record
5286 # with no filler space.
5287 # - use xxd -c24 < .rev_map.$UUID to view and debug
5288 # - This is a one-way migration, repositories updated to the
5289 # new format will not be able to use old git-svn without
5290 # rebuilding the .rev_db. Rebuilding the rev_db is not
5291 # possible if noMetadata or useSvmProps are set; but should
5292 # be no problem for users that use the (sensible) defaults.
5296 use File
::Path qw
/mkpath/;
5297 use File
::Basename qw
/dirname basename/;
5298 use vars qw
/$_minimize/;
5300 sub migrate_from_v0
{
5301 my $git_dir = $ENV{GIT_DIR
};
5302 return undef unless -d
$git_dir;
5303 my ($fh, $ctx) = command_output_pipe
(qw
/rev-parse --symbolic --all/);
5307 my ($id, $orig_ref) = ($_, $_);
5308 next unless $id =~ s
#^refs/heads/(.+)-HEAD$#$1#;
5309 next unless -f
"$git_dir/$id/info/url";
5310 my $new_ref = "refs/remotes/$id";
5311 if (::verify_ref
("$new_ref^0")) {
5312 print STDERR
"W: $orig_ref is probably an old ",
5313 "branch used by an ancient version of ",
5315 "However, $new_ref also exists.\n",
5316 "We will not be able ",
5317 "to use this branch until this ",
5318 "ambiguity is resolved.\n";
5321 print STDERR
"Migrating from v0 layout...\n" if !$migrated;
5322 print STDERR
"Renaming ref: $orig_ref => $new_ref\n";
5323 command_noisy
('update-ref', $new_ref, $orig_ref);
5324 command_noisy
('update-ref', '-d', $orig_ref, $orig_ref);
5327 command_close_pipe
($fh, $ctx);
5328 print STDERR
"Done migrating from v0 layout...\n" if $migrated;
5332 sub migrate_from_v1
{
5333 my $git_dir = $ENV{GIT_DIR
};
5335 return $migrated unless -d
$git_dir;
5336 my $svn_dir = "$git_dir/svn";
5338 # just in case somebody used 'svn' as their $id at some point...
5339 return $migrated if -d
$svn_dir && ! -f
"$svn_dir/info/url";
5341 print STDERR
"Migrating from a git-svn v1 layout...\n";
5343 print STDERR
"Data from a previous version of git-svn exists, but\n\t",
5344 "$svn_dir\n\t(required for this version ",
5345 "($::VERSION) of git-svn) does not exist.\n";
5346 my ($fh, $ctx) = command_output_pipe
(qw
/rev-parse --symbolic --all/);
5349 next unless $x =~ s
#^refs/remotes/##;
5351 next unless -f
"$git_dir/$x/info/url";
5352 my $u = eval { ::file_to_s
("$git_dir/$x/info/url") };
5354 my $dn = dirname
("$git_dir/svn/$x");
5355 mkpath
([$dn]) unless -d
$dn;
5356 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
5357 mkpath
(["$git_dir/svn/svn"]);
5358 print STDERR
" - $git_dir/$x/info => ",
5359 "$git_dir/svn/$x/info\n";
5360 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
5362 # don't worry too much about these, they probably
5363 # don't exist with repos this old (save for index,
5364 # and we can easily regenerate that)
5365 foreach my $f (qw
/unhandled.log index .rev_db/) {
5366 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
5369 print STDERR
" - $git_dir/$x => $git_dir/svn/$x\n";
5370 rename "$git_dir/$x", "$git_dir/svn/$x" or
5375 command_close_pipe
($fh, $ctx);
5376 print STDERR
"Done migrating from a git-svn v1 layout\n";
5381 my ($l_map, $pfx, $path) = @_;
5383 foreach (<$path/*>) {
5384 if (-r
"$_/info/url") {
5385 $pfx .= '/' if $pfx && $pfx !~ m
!/$!;
5386 my $ref_id = $pfx . basename
$_;
5387 my $url = ::file_to_s
("$_/info/url");
5388 $l_map->{$ref_id} = $url;
5395 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
5396 read_old_urls
($l_map, $x, $_);
5400 sub migrate_from_v2
{
5401 my @cfg = command
(qw
/config -l/);
5402 return if grep /^svn-remote\..+\.url=/, @cfg;
5404 read_old_urls
(\
%l_map, '', "$ENV{GIT_DIR}/svn");
5407 foreach my $ref_id (sort keys %l_map) {
5408 eval { Git
::SVN
->init($l_map{$ref_id}, '', undef, $ref_id) };
5410 Git
::SVN
->init($l_map{$ref_id}, '', $ref_id, $ref_id);
5417 sub minimize_connections
{
5418 my $r = Git
::SVN
::read_all_remotes
();
5420 my $root_repos = {};
5421 foreach my $repo_id (keys %$r) {
5422 my $url = $r->{$repo_id}->{url
} or next;
5423 my $fetch = $r->{$repo_id}->{fetch
} or next;
5424 my $ra = Git
::SVN
::Ra
->new($url);
5426 # skip existing cases where we already connect to the root
5427 if (($ra->{url
} eq $ra->{repos_root
}) ||
5428 ($ra->{repos_root
} eq $repo_id)) {
5429 $root_repos->{$ra->{url
}} = $repo_id;
5433 my $root_ra = Git
::SVN
::Ra
->new($ra->{repos_root
});
5434 my $root_path = $ra->{url
};
5435 $root_path =~ s
#^\Q$ra->{repos_root}\E(/|$)##;
5436 foreach my $path (keys %$fetch) {
5437 my $ref_id = $fetch->{$path};
5438 my $gs = Git
::SVN
->new($ref_id, $repo_id, $path);
5440 # make sure we can read when connecting to
5441 # a higher level of a repository
5442 my ($last_rev, undef) = $gs->last_rev_commit;
5443 if (!defined $last_rev) {
5445 $root_ra->get_latest_revnum;
5449 my $new = $root_path;
5450 $new .= length $path ?
"/$path" : '';
5452 $root_ra->get_log([$new], $last_rev, $last_rev,
5456 $new_urls->{$ra->{repos_root
}}->{$new} =
5457 { ref_id
=> $ref_id,
5458 old_repo_id
=> $repo_id,
5459 old_path
=> $path };
5464 foreach my $url (keys %$new_urls) {
5465 # see if we can re-use an existing [svn-remote "repo_id"]
5466 # instead of creating a(n ugly) new section:
5467 my $repo_id = $root_repos->{$url} || $url;
5469 my $fetch = $new_urls->{$url};
5470 foreach my $path (keys %$fetch) {
5471 my $x = $fetch->{$path};
5472 Git
::SVN
->init($url, $path, $repo_id, $x->{ref_id
});
5473 my $pfx = "svn-remote.$x->{old_repo_id}";
5475 my $old_fetch = quotemeta("$x->{old_path}:".
5476 "refs/remotes/$x->{ref_id}");
5477 command_noisy
(qw
/config --unset/,
5478 "$pfx.fetch", '^'. $old_fetch . '$');
5479 delete $r->{$x->{old_repo_id
}}->
5480 {fetch
}->{$x->{old_path
}};
5481 if (!keys %{$r->{$x->{old_repo_id
}}->{fetch
}}) {
5482 command_noisy
(qw
/config --unset/,
5484 push @emptied, $x->{old_repo_id
}
5489 my $file = $ENV{GIT_CONFIG
} || "$ENV{GIT_DIR}/config";
5491 The following [svn-remote] sections in your config file ($file) are empty
5492 and can be safely removed:
5494 print STDERR
"[svn-remote \"$_\"]\n" foreach @emptied;
5498 sub migration_check
{
5502 minimize_connections
() if $_minimize;
5505 package Git
::IndexInfo
;
5508 use Git qw
/command_input_pipe command_close_pipe/;
5512 my ($gui, $ctx) = command_input_pipe
(qw
/update-index -z --index-info/);
5513 bless { gui
=> $gui, ctx
=> $ctx, nr
=> 0}, $class;
5517 my ($self, $path) = @_;
5518 if (print { $self->{gui
} } '0 ', 0 x
40, "\t", $path, "\0") {
5519 return ++$self->{nr
};
5525 my ($self, $mode, $hash, $path) = @_;
5526 if (print { $self->{gui
} } $mode, ' ', $hash, "\t", $path, "\0") {
5527 return ++$self->{nr
};
5534 command_close_pipe
($self->{gui
}, $self->{ctx
});
5537 package Git
::SVN
::GlobSpec
;
5542 my ($class, $glob) = @_;
5544 $re =~ s!/+$!!g; # no need for trailing slashes
5545 $re =~ m!^([^*]*)(\*(?:/\*)*)([^*]*)$!;
5547 my ($left, $right) = ($1, $3);
5549 my $depth = $re =~ tr/*/*/;
5550 if ($depth != $temp =~ tr/*/*/) {
5551 die "Only one set of wildcard directories " .
5552 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
5555 die "One '*' is needed for glob: '$glob'\n";
5557 $re =~ s!\*!\[^/\]*!g;
5558 $re = quotemeta($left) . "($re)" . quotemeta($right);
5559 if (length $left && !($left =~ s!/+$!!g)) {
5560 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
5562 if (length $right && !($right =~ s!^/+!!g)) {
5563 die "Missing leading '/' on right side of: '$glob' ($right)\n";
5565 my $left_re = qr/^\/\Q
$left\E
(\
/|$)/;
5566 bless { left
=> $left, right
=> $right, left_regex
=> $left_re,
5567 regex
=> qr/$re/, glob => $glob, depth
=> $depth }, $class;
5571 my ($self, $path) = @_;
5572 return (length $self->{left
} ?
"$self->{left}/" : '') .
5573 $path . (length $self->{right
} ?
"/$self->{right}" : '');
5581 $remotes = { # returned by read_all_remotes()
5583 # svn-remote.svn.url=https://svn.musicpd.org
5584 url
=> 'https://svn.musicpd.org',
5585 # svn-remote.svn.fetch=mpd/trunk:trunk
5587 'mpd/trunk' => 'trunk',
5589 # svn-remote.svn.tags=mpd/tags/*:tags/*
5594 regex
=> qr!mpd/tags/([^/]+)$!,
5600 regex
=> qr!tags/([^/]+)$!,
5607 $log_entry hashref as returned by libsvn_log_entry
()
5609 log => 'whitespace-formatted log entry
5610 ', # trailing newline is preserved
5611 revision
=> '8', # integer
5612 date
=> '2004-02-24T17:01:44.108345Z', # commit date
5613 author
=> 'committer name'
5617 # this is generated by generate_diff();
5618 @mods = array of diff
-index line hashes
, each element represents one line
5619 of diff
-index output
5621 diff
-index line
($m hash
)
5623 mode_a
=> first column of diff
-index output
, no leading
':',
5624 mode_b
=> second column of diff
-index output
,
5625 sha1_b
=> sha1sum of the final blob
,
5626 chg
=> change type
[MCRADT
],
5627 file_a
=> original file name of a file
(iff chg is
'C' or 'R')
5628 file_b
=> new
/current file name of a file
(any chg
)
5632 # retval of read_url_paths{,_all}();
5634 # repository root url
5635 'https://svn.musicpd.org' => {
5636 # repository path # GIT_SVN_ID
5637 'mpd/trunk' => 'trunk',
5638 'mpd/tags/0.11.5' => 'tags/0.11.5',
5643 I don
't trust the each() function on unless I created %hash myself
5644 because the internal iterator may not have started at base.