PageRenderTime 82ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/.metadata/.plugins/com.aptana.portablegit.win32/libexec/git-core/git-svn

https://github.com/amariebk/SuiviActivPPE
Perl | 6237 lines | 5539 code | 414 blank | 284 comment | 786 complexity | 4c7ba5ca7758cc8bb096fdd155b2206d MD5 | raw file
  1. #!/usr/bin/perl
  2. use lib (split(/;/, $ENV{GITPERLLIB} || "/lib"));
  3. # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
  4. # License: GPL v2 or later
  5. use warnings;
  6. use strict;
  7. use vars qw/ $AUTHOR $VERSION
  8. $sha1 $sha1_short $_revision $_repository
  9. $_q $_authors $_authors_prog %users/;
  10. $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
  11. $VERSION = '1.7.3.1.msysgit.0';
  12. # From which subdir have we been invoked?
  13. my $cmd_dir_prefix = eval {
  14. command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
  15. } || '';
  16. my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
  17. $ENV{GIT_DIR} ||= '.git';
  18. $Git::SVN::default_repo_id = 'svn';
  19. $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
  20. $Git::SVN::Ra::_log_window_size = 100;
  21. $Git::SVN::_minimize_url = 'unset';
  22. if (! exists $ENV{SVN_SSH}) {
  23. if (exists $ENV{GIT_SSH}) {
  24. $ENV{SVN_SSH} = $ENV{GIT_SSH};
  25. if ($^O eq 'msys') {
  26. $ENV{SVN_SSH} =~ s/\\/\\\\/g;
  27. $ENV{SVN_SSH} =~ s/(.*)/"$1"/;
  28. }
  29. }
  30. }
  31. $Git::SVN::Log::TZ = $ENV{TZ};
  32. $ENV{TZ} = 'UTC';
  33. $| = 1; # unbuffer STDOUT
  34. sub fatal (@) { print STDERR "@_\n"; exit 1 }
  35. sub _req_svn {
  36. require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
  37. require SVN::Ra;
  38. require SVN::Delta;
  39. if ($SVN::Core::VERSION lt '1.1.0') {
  40. fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
  41. }
  42. }
  43. my $can_compress = eval { require Compress::Zlib; 1};
  44. push @Git::SVN::Ra::ISA, 'SVN::Ra';
  45. push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
  46. push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
  47. use Carp qw/croak/;
  48. use Digest::MD5;
  49. use IO::File qw//;
  50. use File::Basename qw/dirname basename/;
  51. use File::Path qw/mkpath/;
  52. use File::Spec;
  53. use File::Find;
  54. use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
  55. use IPC::Open3;
  56. use Git;
  57. BEGIN {
  58. # import functions from Git into our packages, en masse
  59. no strict 'refs';
  60. foreach (qw/command command_oneline command_noisy command_output_pipe
  61. command_input_pipe command_close_pipe
  62. command_bidi_pipe command_close_bidi_pipe/) {
  63. for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
  64. Git::SVN::Migration Git::SVN::Log Git::SVN),
  65. __PACKAGE__) {
  66. *{"${package}::$_"} = \&{"Git::$_"};
  67. }
  68. }
  69. }
  70. my ($SVN);
  71. $sha1 = qr/[a-f\d]{40}/;
  72. $sha1_short = qr/[a-f\d]{4,40}/;
  73. my ($_stdin, $_help, $_edit,
  74. $_message, $_file, $_branch_dest,
  75. $_template, $_shared,
  76. $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
  77. $_merge, $_strategy, $_dry_run, $_local,
  78. $_prefix, $_no_checkout, $_url, $_verbose,
  79. $_git_format, $_commit_url, $_tag);
  80. $Git::SVN::_follow_parent = 1;
  81. $_q ||= 0;
  82. my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
  83. 'config-dir=s' => \$Git::SVN::Ra::config_dir,
  84. 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
  85. 'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex );
  86. my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
  87. 'authors-file|A=s' => \$_authors,
  88. 'authors-prog=s' => \$_authors_prog,
  89. 'repack:i' => \$Git::SVN::_repack,
  90. 'noMetadata' => \$Git::SVN::_no_metadata,
  91. 'useSvmProps' => \$Git::SVN::_use_svm_props,
  92. 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
  93. 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
  94. 'no-checkout' => \$_no_checkout,
  95. 'quiet|q+' => \$_q,
  96. 'repack-flags|repack-args|repack-opts=s' =>
  97. \$Git::SVN::_repack_flags,
  98. 'use-log-author' => \$Git::SVN::_use_log_author,
  99. 'add-author-from' => \$Git::SVN::_add_author_from,
  100. 'localtime' => \$Git::SVN::_localtime,
  101. %remote_opts );
  102. my ($_trunk, @_tags, @_branches, $_stdlayout);
  103. my %icv;
  104. my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
  105. 'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
  106. 'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
  107. 'stdlayout|s' => \$_stdlayout,
  108. 'minimize-url|m!' => \$Git::SVN::_minimize_url,
  109. 'no-metadata' => sub { $icv{noMetadata} = 1 },
  110. 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
  111. 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
  112. 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
  113. 'rewrite-uuid=s' => sub { $icv{rewriteUUID} = $_[1] },
  114. %remote_opts );
  115. my %cmt_opts = ( 'edit|e' => \$_edit,
  116. 'rmdir' => \$SVN::Git::Editor::_rmdir,
  117. 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
  118. 'l=i' => \$SVN::Git::Editor::_rename_limit,
  119. 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
  120. );
  121. my %cmd = (
  122. fetch => [ \&cmd_fetch, "Download new revisions from SVN",
  123. { 'revision|r=s' => \$_revision,
  124. 'fetch-all|all' => \$_fetch_all,
  125. 'parent|p' => \$_fetch_parent,
  126. %fc_opts } ],
  127. clone => [ \&cmd_clone, "Initialize and fetch revisions",
  128. { 'revision|r=s' => \$_revision,
  129. %fc_opts, %init_opts } ],
  130. init => [ \&cmd_init, "Initialize a repo for tracking" .
  131. " (requires URL argument)",
  132. \%init_opts ],
  133. 'multi-init' => [ \&cmd_multi_init,
  134. "Deprecated alias for ".
  135. "'$0 init -T<trunk> -b<branches> -t<tags>'",
  136. \%init_opts ],
  137. dcommit => [ \&cmd_dcommit,
  138. 'Commit several diffs to merge with upstream',
  139. { 'merge|m|M' => \$_merge,
  140. 'strategy|s=s' => \$_strategy,
  141. 'verbose|v' => \$_verbose,
  142. 'dry-run|n' => \$_dry_run,
  143. 'fetch-all|all' => \$_fetch_all,
  144. 'commit-url=s' => \$_commit_url,
  145. 'revision|r=i' => \$_revision,
  146. 'no-rebase' => \$_no_rebase,
  147. %cmt_opts, %fc_opts } ],
  148. branch => [ \&cmd_branch,
  149. 'Create a branch in the SVN repository',
  150. { 'message|m=s' => \$_message,
  151. 'destination|d=s' => \$_branch_dest,
  152. 'dry-run|n' => \$_dry_run,
  153. 'tag|t' => \$_tag,
  154. 'username=s' => \$Git::SVN::Prompt::_username,
  155. 'commit-url=s' => \$_commit_url } ],
  156. tag => [ sub { $_tag = 1; cmd_branch(@_) },
  157. 'Create a tag in the SVN repository',
  158. { 'message|m=s' => \$_message,
  159. 'destination|d=s' => \$_branch_dest,
  160. 'dry-run|n' => \$_dry_run,
  161. 'username=s' => \$Git::SVN::Prompt::_username,
  162. 'commit-url=s' => \$_commit_url } ],
  163. 'set-tree' => [ \&cmd_set_tree,
  164. "Set an SVN repository to a git tree-ish",
  165. { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
  166. 'create-ignore' => [ \&cmd_create_ignore,
  167. 'Create a .gitignore per svn:ignore',
  168. { 'revision|r=i' => \$_revision
  169. } ],
  170. 'mkdirs' => [ \&cmd_mkdirs ,
  171. "recreate empty directories after a checkout",
  172. { 'revision|r=i' => \$_revision } ],
  173. 'propget' => [ \&cmd_propget,
  174. 'Print the value of a property on a file or directory',
  175. { 'revision|r=i' => \$_revision } ],
  176. 'proplist' => [ \&cmd_proplist,
  177. 'List all properties of a file or directory',
  178. { 'revision|r=i' => \$_revision } ],
  179. 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
  180. { 'revision|r=i' => \$_revision
  181. } ],
  182. 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
  183. { 'revision|r=i' => \$_revision
  184. } ],
  185. 'multi-fetch' => [ \&cmd_multi_fetch,
  186. "Deprecated alias for $0 fetch --all",
  187. { 'revision|r=s' => \$_revision, %fc_opts } ],
  188. 'migrate' => [ sub { },
  189. # no-op, we automatically run this anyways,
  190. 'Migrate configuration/metadata/layout from
  191. previous versions of git-svn',
  192. { 'minimize' => \$Git::SVN::Migration::_minimize,
  193. %remote_opts } ],
  194. 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
  195. { 'limit=i' => \$Git::SVN::Log::limit,
  196. 'revision|r=s' => \$_revision,
  197. 'verbose|v' => \$Git::SVN::Log::verbose,
  198. 'incremental' => \$Git::SVN::Log::incremental,
  199. 'oneline' => \$Git::SVN::Log::oneline,
  200. 'show-commit' => \$Git::SVN::Log::show_commit,
  201. 'non-recursive' => \$Git::SVN::Log::non_recursive,
  202. 'authors-file|A=s' => \$_authors,
  203. 'color' => \$Git::SVN::Log::color,
  204. 'pager=s' => \$Git::SVN::Log::pager
  205. } ],
  206. 'find-rev' => [ \&cmd_find_rev,
  207. "Translate between SVN revision numbers and tree-ish",
  208. {} ],
  209. 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
  210. { 'merge|m|M' => \$_merge,
  211. 'verbose|v' => \$_verbose,
  212. 'strategy|s=s' => \$_strategy,
  213. 'local|l' => \$_local,
  214. 'fetch-all|all' => \$_fetch_all,
  215. 'dry-run|n' => \$_dry_run,
  216. %fc_opts } ],
  217. 'commit-diff' => [ \&cmd_commit_diff,
  218. 'Commit a diff between two trees',
  219. { 'message|m=s' => \$_message,
  220. 'file|F=s' => \$_file,
  221. 'revision|r=s' => \$_revision,
  222. %cmt_opts } ],
  223. 'info' => [ \&cmd_info,
  224. "Show info about the latest SVN revision
  225. on the current branch",
  226. { 'url' => \$_url, } ],
  227. 'blame' => [ \&Git::SVN::Log::cmd_blame,
  228. "Show what revision and author last modified each line of a file",
  229. { 'git-format' => \$_git_format } ],
  230. 'reset' => [ \&cmd_reset,
  231. "Undo fetches back to the specified SVN revision",
  232. { 'revision|r=s' => \$_revision,
  233. 'parent|p' => \$_fetch_parent } ],
  234. 'gc' => [ \&cmd_gc,
  235. "Compress unhandled.log files in .git/svn and remove " .
  236. "index files in .git/svn",
  237. {} ],
  238. );
  239. my $cmd;
  240. for (my $i = 0; $i < @ARGV; $i++) {
  241. if (defined $cmd{$ARGV[$i]}) {
  242. $cmd = $ARGV[$i];
  243. splice @ARGV, $i, 1;
  244. last;
  245. } elsif ($ARGV[$i] eq 'help') {
  246. $cmd = $ARGV[$i+1];
  247. usage(0);
  248. }
  249. };
  250. # make sure we're always running at the top-level working directory
  251. unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
  252. unless (-d $ENV{GIT_DIR}) {
  253. if ($git_dir_user_set) {
  254. die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
  255. "but it is not a directory\n";
  256. }
  257. my $git_dir = delete $ENV{GIT_DIR};
  258. my $cdup = undef;
  259. git_cmd_try {
  260. $cdup = command_oneline(qw/rev-parse --show-cdup/);
  261. $git_dir = '.' unless ($cdup);
  262. chomp $cdup if ($cdup);
  263. $cdup = "." unless ($cdup && length $cdup);
  264. } "Already at toplevel, but $git_dir not found\n";
  265. chdir $cdup or die "Unable to chdir up to '$cdup'\n";
  266. unless (-d $git_dir) {
  267. die "$git_dir still not found after going to ",
  268. "'$cdup'\n";
  269. }
  270. $ENV{GIT_DIR} = $git_dir;
  271. }
  272. $_repository = Git->repository(Repository => $ENV{GIT_DIR});
  273. }
  274. my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
  275. read_git_config(\%opts);
  276. if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
  277. Getopt::Long::Configure('pass_through');
  278. }
  279. my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
  280. 'minimize-connections' => \$Git::SVN::Migration::_minimize,
  281. 'id|i=s' => \$Git::SVN::default_ref_id,
  282. 'svn-remote|remote|R=s' => sub {
  283. $Git::SVN::no_reuse_existing = 1;
  284. $Git::SVN::default_repo_id = $_[1] });
  285. exit 1 if (!$rv && $cmd && $cmd ne 'log');
  286. usage(0) if $_help;
  287. version() if $_version;
  288. usage(1) unless defined $cmd;
  289. load_authors() if $_authors;
  290. if (defined $_authors_prog) {
  291. $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
  292. }
  293. unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
  294. Git::SVN::Migration::migration_check();
  295. }
  296. Git::SVN::init_vars();
  297. eval {
  298. Git::SVN::verify_remotes_sanity();
  299. $cmd{$cmd}->[0]->(@ARGV);
  300. };
  301. fatal $@ if $@;
  302. post_fetch_checkout();
  303. exit 0;
  304. ####################### primary functions ######################
  305. sub usage {
  306. my $exit = shift || 0;
  307. my $fd = $exit ? \*STDERR : \*STDOUT;
  308. print $fd <<"";
  309. git-svn - bidirectional operations between a single Subversion tree and git
  310. Usage: git svn <command> [options] [arguments]\n
  311. print $fd "Available commands:\n" unless $cmd;
  312. foreach (sort keys %cmd) {
  313. next if $cmd && $cmd ne $_;
  314. next if /^multi-/; # don't show deprecated commands
  315. print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
  316. foreach (sort keys %{$cmd{$_}->[2]}) {
  317. # mixed-case options are for .git/config only
  318. next if /[A-Z]/ && /^[a-z]+$/i;
  319. # prints out arguments as they should be passed:
  320. my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
  321. print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
  322. "--$_" : "-$_" }
  323. split /\|/,$_)," $x\n";
  324. }
  325. }
  326. print $fd <<"";
  327. \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
  328. arbitrary identifier if you're tracking multiple SVN branches/repositories in
  329. one git repository and want to keep them separate. See git-svn(1) for more
  330. information.
  331. exit $exit;
  332. }
  333. sub version {
  334. ::_req_svn();
  335. print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
  336. exit 0;
  337. }
  338. sub do_git_init_db {
  339. unless (-d $ENV{GIT_DIR}) {
  340. my @init_db = ('init');
  341. push @init_db, "--template=$_template" if defined $_template;
  342. if (defined $_shared) {
  343. if ($_shared =~ /[a-z]/) {
  344. push @init_db, "--shared=$_shared";
  345. } else {
  346. push @init_db, "--shared";
  347. }
  348. }
  349. command_noisy(@init_db);
  350. $_repository = Git->repository(Repository => ".git");
  351. }
  352. my $set;
  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});
  358. $set = $i;
  359. }
  360. my $ignore_regex = \$SVN::Git::Fetcher::_ignore_regex;
  361. command_noisy('config', "$pfx.ignore-paths", $$ignore_regex)
  362. if defined $$ignore_regex;
  363. }
  364. sub init_subdir {
  365. my $repo_path = shift or return;
  366. mkpath([$repo_path]) unless -d $repo_path;
  367. chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
  368. $ENV{GIT_DIR} = '.git';
  369. $_repository = Git->repository(Repository => $ENV{GIT_DIR});
  370. }
  371. sub cmd_clone {
  372. my ($url, $path) = @_;
  373. if (!defined $path &&
  374. (defined $_trunk || @_branches || @_tags ||
  375. defined $_stdlayout) &&
  376. $url !~ m#^[a-z\+]+://#) {
  377. $path = $url;
  378. }
  379. $path = basename($url) if !defined $path || !length $path;
  380. my $authors_absolute = $_authors ? File::Spec->rel2abs($_authors) : "";
  381. cmd_init($url, $path);
  382. command_oneline('config', 'svn.authorsfile', $authors_absolute)
  383. if $_authors;
  384. Git::SVN::fetch_all($Git::SVN::default_repo_id);
  385. }
  386. sub cmd_init {
  387. if (defined $_stdlayout) {
  388. $_trunk = 'trunk' if (!defined $_trunk);
  389. @_tags = 'tags' if (! @_tags);
  390. @_branches = 'branches' if (! @_branches);
  391. }
  392. if (defined $_trunk || @_branches || @_tags) {
  393. return cmd_multi_init(@_);
  394. }
  395. my $url = shift or die "SVN repository location required ",
  396. "as a command-line argument\n";
  397. $url = canonicalize_url($url);
  398. init_subdir(@_);
  399. do_git_init_db();
  400. if ($Git::SVN::_minimize_url eq 'unset') {
  401. $Git::SVN::_minimize_url = 0;
  402. }
  403. Git::SVN->init($url);
  404. }
  405. sub cmd_fetch {
  406. if (grep /^\d+=./, @_) {
  407. die "'<rev>=<commit>' fetch arguments are ",
  408. "no longer supported.\n";
  409. }
  410. my ($remote) = @_;
  411. if (@_ > 1) {
  412. die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
  413. }
  414. $Git::SVN::no_reuse_existing = undef;
  415. if ($_fetch_parent) {
  416. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  417. unless ($gs) {
  418. die "Unable to determine upstream SVN information from ",
  419. "working tree history\n";
  420. }
  421. # just fetch, don't checkout.
  422. $_no_checkout = 'true';
  423. $_fetch_all ? $gs->fetch_all : $gs->fetch;
  424. } elsif ($_fetch_all) {
  425. cmd_multi_fetch();
  426. } else {
  427. $remote ||= $Git::SVN::default_repo_id;
  428. Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
  429. }
  430. }
  431. sub cmd_set_tree {
  432. my (@commits) = @_;
  433. if ($_stdin || !@commits) {
  434. print "Reading from stdin...\n";
  435. @commits = ();
  436. while (<STDIN>) {
  437. if (/\b($sha1_short)\b/o) {
  438. unshift @commits, $1;
  439. }
  440. }
  441. }
  442. my @revs;
  443. foreach my $c (@commits) {
  444. my @tmp = command('rev-parse',$c);
  445. if (scalar @tmp == 1) {
  446. push @revs, $tmp[0];
  447. } elsif (scalar @tmp > 1) {
  448. push @revs, reverse(command('rev-list',@tmp));
  449. } else {
  450. fatal "Failed to rev-parse $c";
  451. }
  452. }
  453. my $gs = Git::SVN->new;
  454. my ($r_last, $cmt_last) = $gs->last_rev_commit;
  455. $gs->fetch;
  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}";
  461. }
  462. $gs->set_tree($_) foreach @revs;
  463. print "Done committing ",scalar @revs," revisions to SVN\n";
  464. unlink $gs->{index};
  465. }
  466. sub cmd_dcommit {
  467. my $head = shift;
  468. command_noisy(qw/update-index --refresh/);
  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";
  472. $head ||= 'HEAD';
  473. my $old_head;
  474. if ($head ne 'HEAD') {
  475. $old_head = eval {
  476. command_oneline([qw/symbolic-ref -q HEAD/])
  477. };
  478. if ($old_head) {
  479. $old_head =~ s{^refs/heads/}{};
  480. } else {
  481. $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
  482. }
  483. command(['checkout', $head], STDERR => 0);
  484. }
  485. my @refs;
  486. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
  487. unless ($gs) {
  488. die "Unable to determine upstream SVN information from ",
  489. "$head history.\nPerhaps the repository is empty.";
  490. }
  491. if (defined $_commit_url) {
  492. $url = $_commit_url;
  493. } else {
  494. $url = eval { command_oneline('config', '--get',
  495. "svn-remote.$gs->{repo_id}.commiturl") };
  496. if (!$url) {
  497. $url = $gs->full_url
  498. }
  499. }
  500. my $last_rev = $_revision if defined $_revision;
  501. if ($url) {
  502. print "Committing to $url ...\n";
  503. }
  504. my ($linear_refs, $parents) = linearize_history($gs, \@refs);
  505. if ($_no_rebase && scalar(@$linear_refs) > 1) {
  506. warn "Attempting to commit more than one change while ",
  507. "--no-rebase is enabled.\n",
  508. "If these changes depend on each other, re-running ",
  509. "without --no-rebase may be required."
  510. }
  511. my $expect_url = $url;
  512. Git::SVN::remove_username($expect_url);
  513. while (1) {
  514. my $d = shift @$linear_refs or last;
  515. unless (defined $last_rev) {
  516. (undef, $last_rev, undef) = cmt_metadata("$d~1");
  517. unless (defined $last_rev) {
  518. fatal "Unable to extract revision information ",
  519. "from commit $d~1";
  520. }
  521. }
  522. if ($_dry_run) {
  523. print "diff-tree $d~1 $d\n";
  524. } else {
  525. my $cmt_rev;
  526. my %ed_opts = ( r => $last_rev,
  527. log => get_commit_entry($d)->{log},
  528. ra => Git::SVN::Ra->new($url),
  529. config => SVN::Core::config_get_config(
  530. $Git::SVN::Ra::config_dir
  531. ),
  532. tree_a => "$d~1",
  533. tree_b => $d,
  534. editor_cb => sub {
  535. print "Committed r$_[0]\n";
  536. $cmt_rev = $_[0];
  537. },
  538. svn_path => '');
  539. if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
  540. print "No changes\n$d~1 == $d\n";
  541. } elsif ($parents->{$d} && @{$parents->{$d}}) {
  542. $gs->{inject_parents_dcommit}->{$cmt_rev} =
  543. $parents->{$d};
  544. }
  545. $_fetch_all ? $gs->fetch_all : $gs->fetch;
  546. $last_rev = $cmt_rev;
  547. next if $_no_rebase;
  548. # we always want to rebase against the current HEAD,
  549. # not any head that was passed to us
  550. my @diff = command('diff-tree', $d,
  551. $gs->refname, '--');
  552. my @finish;
  553. if (@diff) {
  554. @finish = rebase_cmd();
  555. print STDERR "W: $d and ", $gs->refname,
  556. " differ, using @finish:\n",
  557. join("\n", @diff), "\n";
  558. } else {
  559. print "No changes between current HEAD and ",
  560. $gs->refname,
  561. "\nResetting to the latest ",
  562. $gs->refname, "\n";
  563. @finish = qw/reset --mixed/;
  564. }
  565. command_noisy(@finish, $gs->refname);
  566. if (@diff) {
  567. @refs = ();
  568. my ($url_, $rev_, $uuid_, $gs_) =
  569. working_head_info('HEAD', \@refs);
  570. my ($linear_refs_, $parents_) =
  571. linearize_history($gs_, \@refs);
  572. if (scalar(@$linear_refs) !=
  573. scalar(@$linear_refs_)) {
  574. fatal "# of revisions changed ",
  575. "\nbefore:\n",
  576. join("\n", @$linear_refs),
  577. "\n\nafter:\n",
  578. join("\n", @$linear_refs_), "\n",
  579. 'If you are attempting to commit ',
  580. "merges, try running:\n\t",
  581. 'git rebase --interactive',
  582. '--preserve-merges ',
  583. $gs->refname,
  584. "\nBefore dcommitting";
  585. }
  586. if ($url_ ne $expect_url) {
  587. if ($url_ eq $gs->metadata_url) {
  588. print
  589. "Accepting rewritten URL:",
  590. " $url_\n";
  591. } else {
  592. fatal
  593. "URL mismatch after rebase:",
  594. " $url_ != $expect_url";
  595. }
  596. }
  597. if ($uuid_ ne $uuid) {
  598. fatal "uuid mismatch after rebase: ",
  599. "$uuid_ != $uuid";
  600. }
  601. # remap parents
  602. my (%p, @l, $i);
  603. for ($i = 0; $i < scalar @$linear_refs; $i++) {
  604. my $new = $linear_refs_->[$i] or next;
  605. $p{$new} =
  606. $parents->{$linear_refs->[$i]};
  607. push @l, $new;
  608. }
  609. $parents = \%p;
  610. $linear_refs = \@l;
  611. }
  612. }
  613. }
  614. if ($old_head) {
  615. my $new_head = command_oneline(qw/rev-parse HEAD/);
  616. my $new_is_symbolic = eval {
  617. command_oneline(qw/symbolic-ref -q HEAD/);
  618. };
  619. if ($new_is_symbolic) {
  620. print "dcommitted the branch ", $head, "\n";
  621. } else {
  622. print "dcommitted on a detached HEAD because you gave ",
  623. "a revision argument.\n",
  624. "The rewritten commit is: ", $new_head, "\n";
  625. }
  626. command(['checkout', $old_head], STDERR => 0);
  627. }
  628. unlink $gs->{index};
  629. }
  630. sub cmd_branch {
  631. my ($branch_name, $head) = @_;
  632. unless (defined $branch_name && length $branch_name) {
  633. die(($_tag ? "tag" : "branch") . " name required\n");
  634. }
  635. $head ||= 'HEAD';
  636. my (undef, $rev, undef, $gs) = working_head_info($head);
  637. my $src = $gs->full_url;
  638. my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
  639. my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
  640. my $glob;
  641. if ($#{$allglobs} == 0) {
  642. $glob = $allglobs->[0];
  643. } else {
  644. unless(defined $_branch_dest) {
  645. die "Multiple ",
  646. $_tag ? "tag" : "branch",
  647. " paths defined for Subversion repository.\n",
  648. "You must specify where you want to create the ",
  649. $_tag ? "tag" : "branch",
  650. " with the --destination argument.\n";
  651. }
  652. foreach my $g (@{$allglobs}) {
  653. # SVN::Git::Editor could probably be moved to Git.pm..
  654. my $re = SVN::Git::Editor::glob2pat($g->{path}->{left});
  655. if ($_branch_dest =~ /$re/) {
  656. $glob = $g;
  657. last;
  658. }
  659. }
  660. unless (defined $glob) {
  661. my $dest_re = qr/\b\Q$_branch_dest\E\b/;
  662. foreach my $g (@{$allglobs}) {
  663. $g->{path}->{left} =~ /$dest_re/ or next;
  664. if (defined $glob) {
  665. die "Ambiguous destination: ",
  666. $_branch_dest, "\nmatches both '",
  667. $glob->{path}->{left}, "' and '",
  668. $g->{path}->{left}, "'\n";
  669. }
  670. $glob = $g;
  671. }
  672. unless (defined $glob) {
  673. die "Unknown ",
  674. $_tag ? "tag" : "branch",
  675. " destination $_branch_dest\n";
  676. }
  677. }
  678. }
  679. my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
  680. my $url;
  681. if (defined $_commit_url) {
  682. $url = $_commit_url;
  683. } else {
  684. $url = eval { command_oneline('config', '--get',
  685. "svn-remote.$gs->{repo_id}.commiturl") };
  686. if (!$url) {
  687. $url = $remote->{url};
  688. }
  689. }
  690. my $dst = join '/', $url, $lft, $branch_name, ($rgt || ());
  691. if ($dst =~ /^https:/ && $src =~ /^http:/) {
  692. $src=~s/^http:/https:/;
  693. }
  694. ::_req_svn();
  695. my $ctx = SVN::Client->new(
  696. auth => Git::SVN::Ra::_auth_providers(),
  697. log_msg => sub {
  698. ${ $_[0] } = defined $_message
  699. ? $_message
  700. : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
  701. . $branch_name;
  702. },
  703. );
  704. eval {
  705. $ctx->ls($dst, 'HEAD', 0);
  706. } and die "branch ${branch_name} already exists\n";
  707. print "Copying ${src} at r${rev} to ${dst}...\n";
  708. $ctx->copy($src, $rev, $dst)
  709. unless $_dry_run;
  710. $gs->fetch_all;
  711. }
  712. sub cmd_find_rev {
  713. my $revision_or_hash = shift or die "SVN or git revision required ",
  714. "as a command-line argument\n";
  715. my $result;
  716. if ($revision_or_hash =~ /^r\d+$/) {
  717. my $head = shift;
  718. $head ||= 'HEAD';
  719. my @refs;
  720. my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
  721. unless ($gs) {
  722. die "Unable to determine upstream SVN information from ",
  723. "$head history\n";
  724. }
  725. my $desired_revision = substr($revision_or_hash, 1);
  726. $result = $gs->rev_map_get($desired_revision, $uuid);
  727. } else {
  728. my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
  729. $result = $rev;
  730. }
  731. print "$result\n" if $result;
  732. }
  733. sub cmd_rebase {
  734. command_noisy(qw/update-index --refresh/);
  735. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  736. unless ($gs) {
  737. die "Unable to determine upstream SVN information from ",
  738. "working tree history\n";
  739. }
  740. if ($_dry_run) {
  741. print "Remote Branch: " . $gs->refname . "\n";
  742. print "SVN URL: " . $url . "\n";
  743. return;
  744. }
  745. if (command(qw/diff-index HEAD --/)) {
  746. print STDERR "Cannot rebase with uncommited changes:\n";
  747. command_noisy('status');
  748. exit 1;
  749. }
  750. unless ($_local) {
  751. # rebase will checkout for us, so no need to do it explicitly
  752. $_no_checkout = 'true';
  753. $_fetch_all ? $gs->fetch_all : $gs->fetch;
  754. }
  755. command_noisy(rebase_cmd(), $gs->refname);
  756. $gs->mkemptydirs;
  757. }
  758. sub cmd_show_ignore {
  759. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  760. $gs ||= Git::SVN->new;
  761. my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
  762. $gs->prop_walk($gs->{path}, $r, sub {
  763. my ($gs, $path, $props) = @_;
  764. print STDOUT "\n# $path\n";
  765. my $s = $props->{'svn:ignore'} or return;
  766. $s =~ s/[\r\n]+/\n/g;
  767. $s =~ s/^\n+//;
  768. chomp $s;
  769. $s =~ s#^#$path#gm;
  770. print STDOUT "$s\n";
  771. });
  772. }
  773. sub cmd_show_externals {
  774. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  775. $gs ||= Git::SVN->new;
  776. my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
  777. $gs->prop_walk($gs->{path}, $r, sub {
  778. my ($gs, $path, $props) = @_;
  779. print STDOUT "\n# $path\n";
  780. my $s = $props->{'svn:externals'} or return;
  781. $s =~ s/[\r\n]+/\n/g;
  782. chomp $s;
  783. $s =~ s#^#$path#gm;
  784. print STDOUT "$s\n";
  785. });
  786. }
  787. sub cmd_create_ignore {
  788. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  789. $gs ||= Git::SVN->new;
  790. my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
  791. $gs->prop_walk($gs->{path}, $r, sub {
  792. my ($gs, $path, $props) = @_;
  793. # $path is of the form /path/to/dir/
  794. $path = '.' . $path;
  795. # SVN can have attributes on empty directories,
  796. # which git won't track
  797. mkpath([$path]) unless -d $path;
  798. my $ignore = $path . '.gitignore';
  799. my $s = $props->{'svn:ignore'} or return;
  800. open(GITIGNORE, '>', $ignore)
  801. or fatal("Failed to open `$ignore' for writing: $!");
  802. $s =~ s/[\r\n]+/\n/g;
  803. $s =~ s/^\n+//;
  804. chomp $s;
  805. # Prefix all patterns so that the ignore doesn't apply
  806. # to sub-directories.
  807. $s =~ s#^#/#gm;
  808. print GITIGNORE "$s\n";
  809. close(GITIGNORE)
  810. or fatal("Failed to close `$ignore': $!");
  811. command_noisy('add', '-f', $ignore);
  812. });
  813. }
  814. sub cmd_mkdirs {
  815. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  816. $gs ||= Git::SVN->new;
  817. $gs->mkemptydirs($_revision);
  818. }
  819. sub canonicalize_path {
  820. my ($path) = @_;
  821. my $dot_slash_added = 0;
  822. if (substr($path, 0, 1) ne "/") {
  823. $path = "./" . $path;
  824. $dot_slash_added = 1;
  825. }
  826. # File::Spec->canonpath doesn't collapse x/../y into y (for a
  827. # good reason), so let's do this manually.
  828. $path =~ s#/+#/#g;
  829. $path =~ s#/\.(?:/|$)#/#g;
  830. $path =~ s#/[^/]+/\.\.##g;
  831. $path =~ s#/$##g;
  832. $path =~ s#^\./## if $dot_slash_added;
  833. $path =~ s#^/##;
  834. $path =~ s#^\.$##;
  835. return $path;
  836. }
  837. sub canonicalize_url {
  838. my ($url) = @_;
  839. $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
  840. return $url;
  841. }
  842. # get_svnprops(PATH)
  843. # ------------------
  844. # Helper for cmd_propget and cmd_proplist below.
  845. sub get_svnprops {
  846. my $path = shift;
  847. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  848. $gs ||= Git::SVN->new;
  849. # prefix THE PATH by the sub-directory from which the user
  850. # invoked us.
  851. $path = $cmd_dir_prefix . $path;
  852. fatal("No such file or directory: $path") unless -e $path;
  853. my $is_dir = -d $path ? 1 : 0;
  854. $path = $gs->{path} . '/' . $path;
  855. # canonicalize the path (otherwise libsvn will abort or fail to
  856. # find the file)
  857. $path = canonicalize_path($path);
  858. my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
  859. my $props;
  860. if ($is_dir) {
  861. (undef, undef, $props) = $gs->ra->get_dir($path, $r);
  862. }
  863. else {
  864. (undef, $props) = $gs->ra->get_file($path, $r, undef);
  865. }
  866. return $props;
  867. }
  868. # cmd_propget (PROP, PATH)
  869. # ------------------------
  870. # Print the SVN property PROP for PATH.
  871. sub cmd_propget {
  872. my ($prop, $path) = @_;
  873. $path = '.' if not defined $path;
  874. usage(1) if not defined $prop;
  875. my $props = get_svnprops($path);
  876. if (not defined $props->{$prop}) {
  877. fatal("`$path' does not have a `$prop' SVN property.");
  878. }
  879. print $props->{$prop} . "\n";
  880. }
  881. # cmd_proplist (PATH)
  882. # -------------------
  883. # Print the list of SVN properties for PATH.
  884. sub cmd_proplist {
  885. my $path = shift;
  886. $path = '.' if not defined $path;
  887. my $props = get_svnprops($path);
  888. print "Properties on '$path':\n";
  889. foreach (sort keys %{$props}) {
  890. print " $_\n";
  891. }
  892. }
  893. sub cmd_multi_init {
  894. my $url = shift;
  895. unless (defined $_trunk || @_branches || @_tags) {
  896. usage(1);
  897. }
  898. $_prefix = '' unless defined $_prefix;
  899. if (defined $url) {
  900. $url = canonicalize_url($url);
  901. init_subdir(@_);
  902. }
  903. do_git_init_db();
  904. if (defined $_trunk) {
  905. $_trunk =~ s#^/+##;
  906. my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
  907. # try both old-style and new-style lookups:
  908. my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
  909. unless ($gs_trunk) {
  910. my ($trunk_url, $trunk_path) =
  911. complete_svn_url($url, $_trunk);
  912. $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
  913. undef, $trunk_ref);
  914. }
  915. }
  916. return unless @_branches || @_tags;
  917. my $ra = $url ? Git::SVN::Ra->new($url) : undef;
  918. foreach my $path (@_branches) {
  919. complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
  920. }
  921. foreach my $path (@_tags) {
  922. complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
  923. }
  924. }
  925. sub cmd_multi_fetch {
  926. $Git::SVN::no_reuse_existing = undef;
  927. my $remotes = Git::SVN::read_all_remotes();
  928. foreach my $repo_id (sort keys %$remotes) {
  929. if ($remotes->{$repo_id}->{url}) {
  930. Git::SVN::fetch_all($repo_id, $remotes);
  931. }
  932. }
  933. }
  934. # this command is special because it requires no metadata
  935. sub cmd_commit_diff {
  936. my ($ta, $tb, $url) = @_;
  937. my $usage = "Usage: $0 commit-diff -r<revision> ".
  938. "<tree-ish> <tree-ish> [<URL>]";
  939. fatal($usage) if (!defined $ta || !defined $tb);
  940. my $svn_path = '';
  941. if (!defined $url) {
  942. my $gs = eval { Git::SVN->new };
  943. if (!$gs) {
  944. fatal("Needed URL or usable git-svn --id in ",
  945. "the command-line\n", $usage);
  946. }
  947. $url = $gs->{url};
  948. $svn_path = $gs->{path};
  949. }
  950. unless (defined $_revision) {
  951. fatal("-r|--revision is a required argument\n", $usage);
  952. }
  953. if (defined $_message && defined $_file) {
  954. fatal("Both --message/-m and --file/-F specified ",
  955. "for the commit message.\n",
  956. "I have no idea what you mean");
  957. }
  958. if (defined $_file) {
  959. $_message = file_to_s($_file);
  960. } else {
  961. $_message ||= get_commit_entry($tb)->{log};
  962. }
  963. my $ra ||= Git::SVN::Ra->new($url);
  964. my $r = $_revision;
  965. if ($r eq 'HEAD') {
  966. $r = $ra->get_latest_revnum;
  967. } elsif ($r !~ /^\d+$/) {
  968. die "revision argument: $r not understood by git-svn\n";
  969. }
  970. my %ed_opts = ( r => $r,
  971. log => $_message,
  972. ra => $ra,
  973. tree_a => $ta,
  974. tree_b => $tb,
  975. editor_cb => sub { print "Committed r$_[0]\n" },
  976. svn_path => $svn_path );
  977. if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
  978. print "No changes\n$ta == $tb\n";
  979. }
  980. }
  981. sub escape_uri_only {
  982. my ($uri) = @_;
  983. my @tmp;
  984. foreach (split m{/}, $uri) {
  985. s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
  986. push @tmp, $_;
  987. }
  988. join('/', @tmp);
  989. }
  990. sub escape_url {
  991. my ($url) = @_;
  992. if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
  993. my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
  994. $url = "$scheme://$domain$uri";
  995. }
  996. $url;
  997. }
  998. sub cmd_info {
  999. my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
  1000. my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
  1001. if (exists $_[1]) {
  1002. die "Too many arguments specified\n";
  1003. }
  1004. my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
  1005. if (!$file_type && !$diff_status) {
  1006. print STDERR "svn: '$path' is not under version control\n";
  1007. exit 1;
  1008. }
  1009. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  1010. unless ($gs) {
  1011. die "Unable to determine upstream SVN information from ",
  1012. "working tree history\n";
  1013. }
  1014. # canonicalize_path() will return "" to make libsvn 1.5.x happy,
  1015. $path = "." if $path eq "";
  1016. my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
  1017. if ($_url) {
  1018. print escape_url($full_url), "\n";
  1019. return;
  1020. }
  1021. my $result = "Path: $path\n";
  1022. $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
  1023. $result .= "URL: " . escape_url($full_url) . "\n";
  1024. eval {
  1025. my $repos_root = $gs->repos_root;
  1026. Git::SVN::remove_username($repos_root);
  1027. $result .= "Repository Root: " . escape_url($repos_root) . "\n";
  1028. };
  1029. if ($@) {
  1030. $result .= "Repository Root: (offline)\n";
  1031. }
  1032. ::_req_svn();
  1033. $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
  1034. ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
  1035. $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
  1036. $result .= "Node Kind: " .
  1037. ($file_type eq "dir" ? "directory" : "file") . "\n";
  1038. my $schedule = $diff_status eq "A"
  1039. ? "add"
  1040. : ($diff_status eq "D" ? "delete" : "normal");
  1041. $result .= "Schedule: $schedule\n";
  1042. if ($diff_status eq "A") {
  1043. print $result, "\n";
  1044. return;
  1045. }
  1046. my ($lc_author, $lc_rev, $lc_date_utc);
  1047. my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
  1048. my $log = command_output_pipe(@args);
  1049. my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
  1050. while (<$log>) {
  1051. if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
  1052. $lc_author = $1;
  1053. $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
  1054. } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
  1055. (undef, $lc_rev, undef) = ::extract_metadata($1);
  1056. }
  1057. }
  1058. close $log;
  1059. Git::SVN::Log::set_local_timezone();
  1060. $result .= "Last Changed Author: $lc_author\n";
  1061. $result .= "Last Changed Rev: $lc_rev\n";
  1062. $result .= "Last Changed Date: " .
  1063. Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
  1064. if ($file_type ne "dir") {
  1065. my $text_last_updated_date =
  1066. ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
  1067. $result .=
  1068. "Text Last Updated: " .
  1069. Git::SVN::Log::format_svn_date($text_last_updated_date) .
  1070. "\n";
  1071. my $checksum;
  1072. if ($diff_status eq "D") {
  1073. my ($fh, $ctx) =
  1074. command_output_pipe(qw(cat-file blob), "HEAD:$path");
  1075. if ($file_type eq "link") {
  1076. my $file_name = <$fh>;
  1077. $checksum = md5sum("link $file_name");
  1078. } else {
  1079. $checksum = md5sum($fh);
  1080. }
  1081. command_close_pipe($fh, $ctx);
  1082. } elsif ($file_type eq "link") {
  1083. my $file_name =
  1084. command(qw(cat-file blob), "HEAD:$path");
  1085. $checksum =
  1086. md5sum("link " . $file_name);
  1087. } else {
  1088. open FILE, "<", $path or die $!;
  1089. $checksum = md5sum(\*FILE);
  1090. close FILE or die $!;
  1091. }
  1092. $result .= "Checksum: " . $checksum . "\n";
  1093. }
  1094. print $result, "\n";
  1095. }
  1096. sub cmd_reset {
  1097. my $target = shift || $_revision or die "SVN revision required\n";
  1098. $target = $1 if $target =~ /^r(\d+)$/;
  1099. $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
  1100. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  1101. unless ($gs) {
  1102. die "Unable to determine upstream SVN information from ".
  1103. "history\n";
  1104. }
  1105. my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
  1106. die "Cannot find SVN revision $target\n" unless defined($c);
  1107. $gs->rev_map_set($r, $c, 'reset', $uuid);
  1108. print "r$r = $c ($gs->{ref_id})\n";
  1109. }
  1110. sub cmd_gc {
  1111. if (!$can_compress) {
  1112. warn "Compress::Zlib could not be found; unhandled.log " .
  1113. "files will not be compressed.\n";
  1114. }
  1115. find({ wanted => \&gc_directory, no_chdir => 1}, "$ENV{GIT_DIR}/svn");
  1116. }
  1117. ########################### utility functions #########################
  1118. sub rebase_cmd {
  1119. my @cmd = qw/rebase/;
  1120. push @cmd, '-v' if $_verbose;
  1121. push @cmd, qw/--merge/ if $_merge;
  1122. push @cmd, "--strategy=$_strategy" if $_strategy;
  1123. @cmd;
  1124. }
  1125. sub post_fetch_checkout {
  1126. return if $_no_checkout;
  1127. my $gs = $Git::SVN::_head or return;
  1128. return if verify_ref('refs/heads/master^0');
  1129. # look for "trunk" ref if it exists
  1130. my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
  1131. my $fetch = $remote->{fetch};
  1132. if ($fetch) {
  1133. foreach my $p (keys %$fetch) {
  1134. basename($fetch->{$p}) eq 'trunk' or next;
  1135. $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
  1136. last;
  1137. }
  1138. }
  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'));
  1142. return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
  1143. my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
  1144. return if -f $index;
  1145. return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
  1146. return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
  1147. command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
  1148. print STDERR "Checked out HEAD:\n ",
  1149. $gs->full_url, " r", $gs->last_rev, "\n";
  1150. $gs->mkemptydirs($gs->last_rev);
  1151. }
  1152. sub complete_svn_url {
  1153. my ($url, $path) = @_;
  1154. $path =~ s#/+$##;
  1155. if ($path !~ m#^[a-z\+]+://#) {
  1156. if (!defined $url || $url !~ m#^[a-z\+]+://#) {
  1157. fatal("E: '$path' is not a complete URL ",
  1158. "and a separate URL is not specified");
  1159. }
  1160. return ($url, $path);
  1161. }
  1162. return ($path, '');
  1163. }
  1164. sub complete_url_ls_init {
  1165. my ($ra, $repo_path, $switch, $pfx) = @_;
  1166. unless ($repo_path) {
  1167. print STDERR "W: $switch not specified\n";
  1168. return;
  1169. }
  1170. $repo_path =~ s#/+$##;
  1171. if ($repo_path =~ m#^[a-z\+]+://#) {
  1172. $ra = Git::SVN::Ra->new($repo_path);
  1173. $repo_path = '';
  1174. } else {
  1175. $repo_path =~ s#^/+##;
  1176. unless ($ra) {
  1177. fatal("E: '$repo_path' is not a complete URL ",
  1178. "and a separate URL is not specified");
  1179. }
  1180. }
  1181. my $url = $ra->{url};
  1182. my $gs = Git::SVN->init($url, undef, undef, undef, 1);
  1183. my $k = "svn-remote.$gs->{repo_id}.url";
  1184. my $orig_url = eval { command_oneline(qw/config --get/, $k) };
  1185. if ($orig_url && ($orig_url ne $gs->{url})) {
  1186. die "$k already set: $orig_url\n",
  1187. "wanted to set to: $gs->{url}\n";
  1188. }
  1189. command_oneline('config', $k, $gs->{url}) unless $orig_url;
  1190. my $remote_path = "$gs->{path}/$repo_path";
  1191. $remote_path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
  1192. $remote_path =~ s#/+#/#g;
  1193. $remote_path =~ s#^/##g;
  1194. $remote_path .= "/*" if $remote_path !~ /\*/;
  1195. my ($n) = ($switch =~ /^--(\w+)/);
  1196. if (length $pfx && $pfx !~ m#/$#) {
  1197. die "--prefix='$pfx' must have a trailing slash '/'\n";
  1198. }
  1199. command_noisy('config',
  1200. '--add',
  1201. "svn-remote.$gs->{repo_id}.$n",
  1202. "$remote_path:refs/remotes/$pfx*" .
  1203. ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
  1204. }
  1205. sub verify_ref {
  1206. my ($ref) = @_;
  1207. eval { command_oneline([ 'rev-parse', '--verify', $ref ],
  1208. { STDERR => 0 }); };
  1209. }
  1210. sub get_tree_from_treeish {
  1211. my ($treeish) = @_;
  1212. # $treeish can be a symbolic ref, too:
  1213. my $type = command_oneline(qw/cat-file -t/, $treeish);
  1214. my $expected;
  1215. while ($type eq 'tag') {
  1216. ($treeish, $type) = command(qw/cat-file tag/, $treeish);
  1217. }
  1218. if ($type eq 'commit') {
  1219. $expected = (grep /^tree /, command(qw/cat-file commit/,
  1220. $treeish))[0];
  1221. ($expected) = ($expected =~ /^tree ($sha1)$/o);
  1222. die "Unable to get tree from $treeish\n" unless $expected;
  1223. } elsif ($type eq 'tree') {
  1224. $expected = $treeish;
  1225. } else {
  1226. die "$treeish is a $type, expected tree, tag or commit\n";
  1227. }
  1228. return $expected;
  1229. }
  1230. sub get_commit_entry {
  1231. my ($treeish) = shift;
  1232. my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
  1233. my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
  1234. my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
  1235. open my $log_fh, '>', $commit_editmsg or croak $!;
  1236. my $type = command_oneline(qw/cat-file -t/, $treeish);
  1237. if ($type eq 'commit' || $type eq 'tag') {
  1238. my ($msg_fh, $ctx) = command_output_pipe('cat-file',
  1239. $type, $treeish);
  1240. my $in_msg = 0;
  1241. my $author;
  1242. my $saw_from = 0;
  1243. my $msgbuf = "";
  1244. while (<$msg_fh>) {
  1245. if (!$in_msg) {
  1246. $in_msg = 1 if (/^\s*$/);
  1247. $author = $1 if (/^author (.*>)/);
  1248. } elsif (/^git-svn-id: /) {
  1249. # skip this for now, we regenerate the
  1250. # correct one on re-fetch anyways
  1251. # TODO: set *:merge properties or like...
  1252. } else {
  1253. if (/^From:/ || /^Signed-off-by:/) {
  1254. $saw_from = 1;
  1255. }
  1256. $msgbuf .= $_;
  1257. }
  1258. }
  1259. $msgbuf =~ s/\s+$//s;
  1260. if ($Git::SVN::_add_author_from && defined($author)
  1261. && !$saw_from) {
  1262. $msgbuf .= "\n\nFrom: $author";
  1263. }
  1264. print $log_fh $msgbuf or croak $!;
  1265. command_close_pipe($msg_fh, $ctx);
  1266. }
  1267. close $log_fh or croak $!;
  1268. if ($_edit || ($type eq 'tree')) {
  1269. chomp(my $editor = command_oneline(qw(var GIT_EDITOR)));
  1270. system('sh', '-c', $editor.' "$@"', $editor, $commit_editmsg);
  1271. }
  1272. rename $commit_editmsg, $commit_msg or croak $!;
  1273. {
  1274. require Encode;
  1275. # SVN requires messages to be UTF-8 when entering the repo
  1276. local $/;
  1277. open $log_fh, '<', $commit_msg or croak $!;
  1278. binmode $log_fh;
  1279. chomp($log_entry{log} = <$log_fh>);
  1280. my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
  1281. my $msg = $log_entry{log};
  1282. eval { $msg = Encode::decode($enc, $msg, 1) };
  1283. if ($@) {
  1284. die "Could not decode as $enc:\n", $msg,
  1285. "\nPerhaps you need to set i18n.commitencoding\n";
  1286. }
  1287. eval { $msg = Encode::encode('UTF-8', $msg, 1) };
  1288. die "Could not encode as UTF-8:\n$msg\n" if $@;
  1289. $log_entry{log} = $msg;
  1290. close $log_fh or croak $!;
  1291. }
  1292. unlink $commit_msg;
  1293. \%log_entry;
  1294. }
  1295. sub s_to_file {
  1296. my ($str, $file, $mode) = @_;
  1297. open my $fd,'>',$file or croak $!;
  1298. print $fd $str,"\n" or croak $!;
  1299. close $fd or croak $!;
  1300. chmod ($mode &~ umask, $file) if (defined $mode);
  1301. }
  1302. sub file_to_s {
  1303. my $file = shift;
  1304. open my $fd,'<',$file or croak "$!: file: $file\n";
  1305. local $/;
  1306. my $ret = <$fd>;
  1307. close $fd or croak $!;
  1308. $ret =~ s/\s*$//s;
  1309. return $ret;
  1310. }
  1311. # '<svn username> = real-name <email address>' mapping based on git-svnimport:
  1312. sub load_authors {
  1313. open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
  1314. my $log = $cmd eq 'log';
  1315. while (<$authors>) {
  1316. chomp;
  1317. next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
  1318. my ($user, $name, $email) = ($1, $2, $3);
  1319. if ($log) {
  1320. $Git::SVN::Log::rusers{"$name <$email>"} = $user;
  1321. } else {
  1322. $users{$user} = [$name, $email];
  1323. }
  1324. }
  1325. close $authors or croak $!;
  1326. }
  1327. # convert GetOpt::Long specs for use by git-config
  1328. sub read_git_config {
  1329. my $opts = shift;
  1330. my @config_only;
  1331. foreach my $o (keys %$opts) {
  1332. # if we have mixedCase and a long option-only, then
  1333. # it's a config-only variable that we don't need for
  1334. # the command-line.
  1335. push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
  1336. my $v = $opts->{$o};
  1337. my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
  1338. $key =~ s/-//g;
  1339. my $arg = 'git config';
  1340. $arg .= ' --int' if ($o =~ /[:=]i$/);
  1341. $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
  1342. if (ref $v eq 'ARRAY') {
  1343. chomp(my @tmp = `$arg --get-all svn.$key`);
  1344. @$v = @tmp if @tmp;
  1345. } else {
  1346. chomp(my $tmp = `$arg --get svn.$key`);
  1347. if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
  1348. $$v = $tmp;
  1349. }
  1350. }
  1351. }
  1352. delete @$opts{@config_only} if @config_only;
  1353. }
  1354. sub extract_metadata {
  1355. my $id = shift or return (undef, undef, undef);
  1356. my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
  1357. \s([a-f\d\-]+)$/ix);
  1358. if (!defined $rev || !$uuid || !$url) {
  1359. # some of the original repositories I made had
  1360. # identifiers like this:
  1361. ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
  1362. }
  1363. return ($url, $rev, $uuid);
  1364. }
  1365. sub cmt_metadata {
  1366. return extract_metadata((grep(/^git-svn-id: /,
  1367. command(qw/cat-file commit/, shift)))[-1]);
  1368. }
  1369. sub cmt_sha2rev_batch {
  1370. my %s2r;
  1371. my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
  1372. my $list = shift;
  1373. foreach my $sha (@{$list}) {
  1374. my $first = 1;
  1375. my $size = 0;
  1376. print $out $sha, "\n";
  1377. while (my $line = <$in>) {
  1378. if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
  1379. last;
  1380. } elsif ($first &&
  1381. $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
  1382. $first = 0;
  1383. $size = $1;
  1384. next;
  1385. } elsif ($line =~ /^(git-svn-id: )/) {
  1386. my (undef, $rev, undef) =
  1387. extract_metadata($line);
  1388. $s2r{$sha} = $rev;
  1389. }
  1390. $size -= length($line);
  1391. last if ($size == 0);
  1392. }
  1393. }
  1394. command_close_bidi_pipe($pid, $in, $out, $ctx);
  1395. return \%s2r;
  1396. }
  1397. sub working_head_info {
  1398. my ($head, $refs) = @_;
  1399. my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
  1400. my ($fh, $ctx) = command_output_pipe(@args, $head);
  1401. my $hash;
  1402. my %max;
  1403. while (<$fh>) {
  1404. if ( m{^commit ($::sha1)$} ) {
  1405. unshift @$refs, $hash if $hash and $refs;
  1406. $hash = $1;
  1407. next;
  1408. }
  1409. next unless s{^\s*(git-svn-id:)}{$1};
  1410. my ($url, $rev, $uuid) = extract_metadata($_);
  1411. if (defined $url && defined $rev) {
  1412. next if $max{$url} and $max{$url} < $rev;
  1413. if (my $gs = Git::SVN->find_by_url($url)) {
  1414. my $c = $gs->rev_map_get($rev, $uuid);
  1415. if ($c && $c eq $hash) {
  1416. close $fh; # break the pipe
  1417. return ($url, $rev, $uuid, $gs);
  1418. } else {
  1419. $max{$url} ||= $gs->rev_map_max;
  1420. }
  1421. }
  1422. }
  1423. }
  1424. command_close_pipe($fh, $ctx);
  1425. (undef, undef, undef, undef);
  1426. }
  1427. sub read_commit_parents {
  1428. my ($parents, $c) = @_;
  1429. chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
  1430. $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
  1431. @{$parents->{$c}} = split(/ /, $p);
  1432. }
  1433. sub linearize_history {
  1434. my ($gs, $refs) = @_;
  1435. my %parents;
  1436. foreach my $c (@$refs) {
  1437. read_commit_parents(\%parents, $c);
  1438. }
  1439. my @linear_refs;
  1440. my %skip = ();
  1441. my $last_svn_commit = $gs->last_commit;
  1442. foreach my $c (reverse @$refs) {
  1443. next if $c eq $last_svn_commit;
  1444. last if $skip{$c};
  1445. unshift @linear_refs, $c;
  1446. $skip{$c} = 1;
  1447. # we only want the first parent to diff against for linear
  1448. # history, we save the rest to inject when we finalize the
  1449. # svn commit
  1450. my $fp_a = verify_ref("$c~1");
  1451. my $fp_b = shift @{$parents{$c}} if $parents{$c};
  1452. if (!$fp_a || !$fp_b) {
  1453. die "Commit $c\n",
  1454. "has no parent commit, and therefore ",
  1455. "nothing to diff against.\n",
  1456. "You should be working from a repository ",
  1457. "originally created by git-svn\n";
  1458. }
  1459. if ($fp_a ne $fp_b) {
  1460. die "$c~1 = $fp_a, however parsing commit $c ",
  1461. "revealed that:\n$c~1 = $fp_b\nBUG!\n";
  1462. }
  1463. foreach my $p (@{$parents{$c}}) {
  1464. $skip{$p} = 1;
  1465. }
  1466. }
  1467. (\@linear_refs, \%parents);
  1468. }
  1469. sub find_file_type_and_diff_status {
  1470. my ($path) = @_;
  1471. return ('dir', '') if $path eq '';
  1472. my $diff_output =
  1473. command_oneline(qw(diff --cached --name-status --), $path) || "";
  1474. my $diff_status = (split(' ', $diff_output))[0] || "";
  1475. my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
  1476. return (undef, undef) if !$diff_status && !$ls_tree;
  1477. if ($diff_status eq "A") {
  1478. return ("link", $diff_status) if -l $path;
  1479. return ("dir", $diff_status) if -d $path;
  1480. return ("file", $diff_status);
  1481. }
  1482. my $mode = (split(' ', $ls_tree))[0] || "";
  1483. return ("link", $diff_status) if $mode eq "120000";
  1484. return ("dir", $diff_status) if $mode eq "040000";
  1485. return ("file", $diff_status);
  1486. }
  1487. sub md5sum {
  1488. my $arg = shift;
  1489. my $ref = ref $arg;
  1490. my $md5 = Digest::MD5->new();
  1491. if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
  1492. $md5->addfile($arg) or croak $!;
  1493. } elsif ($ref eq 'SCALAR') {
  1494. $md5->add($$arg) or croak $!;
  1495. } elsif (!$ref) {
  1496. $md5->add($arg) or croak $!;
  1497. } else {
  1498. ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
  1499. }
  1500. return $md5->hexdigest();
  1501. }
  1502. sub gc_directory {
  1503. if ($can_compress && -f $_ && basename($_) eq "unhandled.log") {
  1504. my $out_filename = $_ . ".gz";
  1505. open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
  1506. binmode $in_fh;
  1507. my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
  1508. die "Unable to open $out_filename: $!\n";
  1509. my $res;
  1510. while ($res = sysread($in_fh, my $str, 1024)) {
  1511. $gz->gzwrite($str) or
  1512. die "Unable to write: ".$gz->gzerror()."!\n";
  1513. }
  1514. unlink $_ or die "unlink $File::Find::name: $!\n";
  1515. } elsif (-f $_ && basename($_) eq "index") {
  1516. unlink $_ or die "unlink $_: $!\n";
  1517. }
  1518. }
  1519. package Git::SVN;
  1520. use strict;
  1521. use warnings;
  1522. use Fcntl qw/:DEFAULT :seek/;
  1523. use constant rev_map_fmt => 'NH40';
  1524. use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
  1525. $_repack $_repack_flags $_use_svm_props $_head
  1526. $_use_svnsync_props $no_reuse_existing $_minimize_url
  1527. $_use_log_author $_add_author_from $_localtime/;
  1528. use Carp qw/croak/;
  1529. use File::Path qw/mkpath/;
  1530. use File::Copy qw/copy/;
  1531. use IPC::Open3;
  1532. use Memoize; # core since 5.8.0, Jul 2002
  1533. use Memoize::Storable;
  1534. my ($_gc_nr, $_gc_period);
  1535. # properties that we do not log:
  1536. my %SKIP_PROP;
  1537. BEGIN {
  1538. %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
  1539. svn:special svn:executable
  1540. svn:entry:committed-rev
  1541. svn:entry:last-author
  1542. svn:entry:uuid
  1543. svn:entry:committed-date/;
  1544. # some options are read globally, but can be overridden locally
  1545. # per [svn-remote "..."] section. Command-line options will *NOT*
  1546. # override options set in an [svn-remote "..."] section
  1547. no strict 'refs';
  1548. for my $option (qw/follow_parent no_metadata use_svm_props
  1549. use_svnsync_props/) {
  1550. my $key = $option;
  1551. $key =~ tr/_//d;
  1552. my $prop = "-$option";
  1553. *$option = sub {
  1554. my ($self) = @_;
  1555. return $self->{$prop} if exists $self->{$prop};
  1556. my $k = "svn-remote.$self->{repo_id}.$key";
  1557. eval { command_oneline(qw/config --get/, $k) };
  1558. if ($@) {
  1559. $self->{$prop} = ${"Git::SVN::_$option"};
  1560. } else {
  1561. my $v = command_oneline(qw/config --bool/,$k);
  1562. $self->{$prop} = $v eq 'false' ? 0 : 1;
  1563. }
  1564. return $self->{$prop};
  1565. }
  1566. }
  1567. }
  1568. my (%LOCKFILES, %INDEX_FILES);
  1569. END {
  1570. unlink keys %LOCKFILES if %LOCKFILES;
  1571. unlink keys %INDEX_FILES if %INDEX_FILES;
  1572. }
  1573. sub resolve_local_globs {
  1574. my ($url, $fetch, $glob_spec) = @_;
  1575. return unless defined $glob_spec;
  1576. my $ref = $glob_spec->{ref};
  1577. my $path = $glob_spec->{path};
  1578. foreach (command(qw#for-each-ref --format=%(refname) refs/#)) {
  1579. next unless m#^$ref->{regex}$#;
  1580. my $p = $1;
  1581. my $pathname = desanitize_refname($path->full_path($p));
  1582. my $refname = desanitize_refname($ref->full_path($p));
  1583. if (my $existing = $fetch->{$pathname}) {
  1584. if ($existing ne $refname) {
  1585. die "Refspec conflict:\n",
  1586. "existing: $existing\n",
  1587. " globbed: $refname\n";
  1588. }
  1589. my $u = (::cmt_metadata("$refname"))[0];
  1590. $u =~ s!^\Q$url\E(/|$)!! or die
  1591. "$refname: '$url' not found in '$u'\n";
  1592. if ($pathname ne $u) {
  1593. warn "W: Refspec glob conflict ",
  1594. "(ref: $refname):\n",
  1595. "expected path: $pathname\n",
  1596. " real path: $u\n",
  1597. "Continuing ahead with $u\n";
  1598. next;
  1599. }
  1600. } else {
  1601. $fetch->{$pathname} = $refname;
  1602. }
  1603. }
  1604. }
  1605. sub parse_revision_argument {
  1606. my ($base, $head) = @_;
  1607. if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
  1608. return ($base, $head);
  1609. }
  1610. return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
  1611. return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
  1612. return ($head, $head) if ($::_revision eq 'HEAD');
  1613. return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
  1614. return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
  1615. die "revision argument: $::_revision not understood by git-svn\n";
  1616. }
  1617. sub fetch_all {
  1618. my ($repo_id, $remotes) = @_;
  1619. if (ref $repo_id) {
  1620. my $gs = $repo_id;
  1621. $repo_id = undef;
  1622. $repo_id = $gs->{repo_id};
  1623. }
  1624. $remotes ||= read_all_remotes();
  1625. my $remote = $remotes->{$repo_id} or
  1626. die "[svn-remote \"$repo_id\"] unknown\n";
  1627. my $fetch = $remote->{fetch};
  1628. my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
  1629. my (@gs, @globs);
  1630. my $ra = Git::SVN::Ra->new($url);
  1631. my $uuid = $ra->get_uuid;
  1632. my $head = $ra->get_latest_revnum;
  1633. # ignore errors, $head revision may not even exist anymore
  1634. eval { $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] }) };
  1635. warn "W: $@\n" if $@;
  1636. my $base = defined $fetch ? $head : 0;
  1637. # read the max revs for wildcard expansion (branches/*, tags/*)
  1638. foreach my $t (qw/branches tags/) {
  1639. defined $remote->{$t} or next;
  1640. push @globs, @{$remote->{$t}};
  1641. my $max_rev = eval { tmp_config(qw/--int --get/,
  1642. "svn-remote.$repo_id.${t}-maxRev") };
  1643. if (defined $max_rev && ($max_rev < $base)) {
  1644. $base = $max_rev;
  1645. } elsif (!defined $max_rev) {
  1646. $base = 0;
  1647. }
  1648. }
  1649. if ($fetch) {
  1650. foreach my $p (sort keys %$fetch) {
  1651. my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
  1652. my $lr = $gs->rev_map_max;
  1653. if (defined $lr) {
  1654. $base = $lr if ($lr < $base);
  1655. }
  1656. push @gs, $gs;
  1657. }
  1658. }
  1659. ($base, $head) = parse_revision_argument($base, $head);
  1660. $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
  1661. }
  1662. sub read_all_remotes {
  1663. my $r = {};
  1664. my $use_svm_props = eval { command_oneline(qw/config --bool
  1665. svn.useSvmProps/) };
  1666. $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
  1667. my $svn_refspec = qr{\s*(.*?)\s*:\s*(.+?)\s*};
  1668. foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
  1669. if (m!^(.+)\.fetch=$svn_refspec$!) {
  1670. my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
  1671. die("svn-remote.$remote: remote ref '$remote_ref' "
  1672. . "must start with 'refs/'\n")
  1673. unless $remote_ref =~ m{^refs/};
  1674. $local_ref = uri_decode($local_ref);
  1675. $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
  1676. $r->{$remote}->{svm} = {} if $use_svm_props;
  1677. } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
  1678. $r->{$1}->{svm} = {};
  1679. } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
  1680. $r->{$1}->{url} = $2;
  1681. } elsif (m!^(.+)\.(branches|tags)=$svn_refspec$!) {
  1682. my ($remote, $t, $local_ref, $remote_ref) =
  1683. ($1, $2, $3, $4);
  1684. die("svn-remote.$remote: remote ref '$remote_ref' ($t) "
  1685. . "must start with 'refs/'\n")
  1686. unless $remote_ref =~ m{^refs/};
  1687. $local_ref = uri_decode($local_ref);
  1688. my $rs = {
  1689. t => $t,
  1690. remote => $remote,
  1691. path => Git::SVN::GlobSpec->new($local_ref, 1),
  1692. ref => Git::SVN::GlobSpec->new($remote_ref, 0) };
  1693. if (length($rs->{ref}->{right}) != 0) {
  1694. die "The '*' glob character must be the last ",
  1695. "character of '$remote_ref'\n";
  1696. }
  1697. push @{ $r->{$remote}->{$t} }, $rs;
  1698. }
  1699. }
  1700. map {
  1701. if (defined $r->{$_}->{svm}) {
  1702. my $svm;
  1703. eval {
  1704. my $section = "svn-remote.$_";
  1705. $svm = {
  1706. source => tmp_config('--get',
  1707. "$section.svm-source"),
  1708. replace => tmp_config('--get',
  1709. "$section.svm-replace"),
  1710. }
  1711. };
  1712. $r->{$_}->{svm} = $svm;
  1713. }
  1714. } keys %$r;
  1715. $r;
  1716. }
  1717. sub init_vars {
  1718. $_gc_nr = $_gc_period = 1000;
  1719. if (defined $_repack || defined $_repack_flags) {
  1720. warn "Repack options are obsolete; they have no effect.\n";
  1721. }
  1722. }
  1723. sub verify_remotes_sanity {
  1724. return unless -d $ENV{GIT_DIR};
  1725. my %seen;
  1726. foreach (command(qw/config -l/)) {
  1727. if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
  1728. if ($seen{$1}) {
  1729. die "Remote ref refs/remote/$1 is tracked by",
  1730. "\n \"$_\"\nand\n \"$seen{$1}\"\n",
  1731. "Please resolve this ambiguity in ",
  1732. "your git configuration file before ",
  1733. "continuing\n";
  1734. }
  1735. $seen{$1} = $_;
  1736. }
  1737. }
  1738. }
  1739. sub find_existing_remote {
  1740. my ($url, $remotes) = @_;
  1741. return undef if $no_reuse_existing;
  1742. my $existing;
  1743. foreach my $repo_id (keys %$remotes) {
  1744. my $u = $remotes->{$repo_id}->{url} or next;
  1745. next if $u ne $url;
  1746. $existing = $repo_id;
  1747. last;
  1748. }
  1749. $existing;
  1750. }
  1751. sub init_remote_config {
  1752. my ($self, $url, $no_write) = @_;
  1753. $url =~ s!/+$!!; # strip trailing slash
  1754. my $r = read_all_remotes();
  1755. my $existing = find_existing_remote($url, $r);
  1756. if ($existing) {
  1757. unless ($no_write) {
  1758. print STDERR "Using existing ",
  1759. "[svn-remote \"$existing\"]\n";
  1760. }
  1761. $self->{repo_id} = $existing;
  1762. } elsif ($_minimize_url) {
  1763. my $min_url = Git::SVN::Ra->new($url)->minimize_url;
  1764. $existing = find_existing_remote($min_url, $r);
  1765. if ($existing) {
  1766. unless ($no_write) {
  1767. print STDERR "Using existing ",
  1768. "[svn-remote \"$existing\"]\n";
  1769. }
  1770. $self->{repo_id} = $existing;
  1771. }
  1772. if ($min_url ne $url) {
  1773. unless ($no_write) {
  1774. print STDERR "Using higher level of URL: ",
  1775. "$url => $min_url\n";
  1776. }
  1777. my $old_path = $self->{path};
  1778. $self->{path} = $url;
  1779. $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
  1780. if (length $old_path) {
  1781. $self->{path} .= "/$old_path";
  1782. }
  1783. $url = $min_url;
  1784. }
  1785. }
  1786. my $orig_url;
  1787. if (!$existing) {
  1788. # verify that we aren't overwriting anything:
  1789. $orig_url = eval {
  1790. command_oneline('config', '--get',
  1791. "svn-remote.$self->{repo_id}.url")
  1792. };
  1793. if ($orig_url && ($orig_url ne $url)) {
  1794. die "svn-remote.$self->{repo_id}.url already set: ",
  1795. "$orig_url\nwanted to set to: $url\n";
  1796. }
  1797. }
  1798. my ($xrepo_id, $xpath) = find_ref($self->refname);
  1799. if (!$no_write && defined $xpath) {
  1800. die "svn-remote.$xrepo_id.fetch already set to track ",
  1801. "$xpath:", $self->refname, "\n";
  1802. }
  1803. unless ($no_write) {
  1804. command_noisy('config',
  1805. "svn-remote.$self->{repo_id}.url", $url);
  1806. $self->{path} =~ s{^/}{};
  1807. $self->{path} =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
  1808. command_noisy('config', '--add',
  1809. "svn-remote.$self->{repo_id}.fetch",
  1810. "$self->{path}:".$self->refname);
  1811. }
  1812. $self->{url} = $url;
  1813. }
  1814. sub find_by_url { # repos_root and, path are optional
  1815. my ($class, $full_url, $repos_root, $path) = @_;
  1816. return undef unless defined $full_url;
  1817. remove_username($full_url);
  1818. remove_username($repos_root) if defined $repos_root;
  1819. my $remotes = read_all_remotes();
  1820. if (defined $full_url && defined $repos_root && !defined $path) {
  1821. $path = $full_url;
  1822. $path =~ s#^\Q$repos_root\E(?:/|$)##;
  1823. }
  1824. foreach my $repo_id (keys %$remotes) {
  1825. my $u = $remotes->{$repo_id}->{url} or next;
  1826. remove_username($u);
  1827. next if defined $repos_root && $repos_root ne $u;
  1828. my $fetch = $remotes->{$repo_id}->{fetch} || {};
  1829. foreach my $t (qw/branches tags/) {
  1830. foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
  1831. resolve_local_globs($u, $fetch, $globspec);
  1832. }
  1833. }
  1834. my $p = $path;
  1835. my $rwr = rewrite_root({repo_id => $repo_id});
  1836. my $svm = $remotes->{$repo_id}->{svm}
  1837. if defined $remotes->{$repo_id}->{svm};
  1838. unless (defined $p) {
  1839. $p = $full_url;
  1840. my $z = $u;
  1841. my $prefix = '';
  1842. if ($rwr) {
  1843. $z = $rwr;
  1844. remove_username($z);
  1845. } elsif (defined $svm) {
  1846. $z = $svm->{source};
  1847. $prefix = $svm->{replace};
  1848. $prefix =~ s#^\Q$u\E(?:/|$)##;
  1849. $prefix =~ s#/$##;
  1850. }
  1851. $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
  1852. }
  1853. foreach my $f (keys %$fetch) {
  1854. next if $f ne $p;
  1855. return Git::SVN->new($fetch->{$f}, $repo_id, $f);
  1856. }
  1857. }
  1858. undef;
  1859. }
  1860. sub init {
  1861. my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
  1862. my $self = _new($class, $repo_id, $ref_id, $path);
  1863. if (defined $url) {
  1864. $self->init_remote_config($url, $no_write);
  1865. }
  1866. $self;
  1867. }
  1868. sub find_ref {
  1869. my ($ref_id) = @_;
  1870. foreach (command(qw/config -l/)) {
  1871. next unless m!^svn-remote\.(.+)\.fetch=
  1872. \s*(.*?)\s*:\s*(.+?)\s*$!x;
  1873. my ($repo_id, $path, $ref) = ($1, $2, $3);
  1874. if ($ref eq $ref_id) {
  1875. $path = '' if ($path =~ m#^\./?#);
  1876. return ($repo_id, $path);
  1877. }
  1878. }
  1879. (undef, undef, undef);
  1880. }
  1881. sub new {
  1882. my ($class, $ref_id, $repo_id, $path) = @_;
  1883. if (defined $ref_id && !defined $repo_id && !defined $path) {
  1884. ($repo_id, $path) = find_ref($ref_id);
  1885. if (!defined $repo_id) {
  1886. die "Could not find a \"svn-remote.*.fetch\" key ",
  1887. "in the repository configuration matching: ",
  1888. "$ref_id\n";
  1889. }
  1890. }
  1891. my $self = _new($class, $repo_id, $ref_id, $path);
  1892. if (!defined $self->{path} || !length $self->{path}) {
  1893. my $fetch = command_oneline('config', '--get',
  1894. "svn-remote.$repo_id.fetch",
  1895. ":$ref_id\$") or
  1896. die "Failed to read \"svn-remote.$repo_id.fetch\" ",
  1897. "\":$ref_id\$\" in config\n";
  1898. ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
  1899. }
  1900. $self->{path} =~ s{/+}{/}g;
  1901. $self->{path} =~ s{\A/}{};
  1902. $self->{path} =~ s{/\z}{};
  1903. $self->{url} = command_oneline('config', '--get',
  1904. "svn-remote.$repo_id.url") or
  1905. die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
  1906. $self->rebuild;
  1907. $self;
  1908. }
  1909. sub refname {
  1910. my ($refname) = $_[0]->{ref_id} ;
  1911. # It cannot end with a slash /, we'll throw up on this because
  1912. # SVN can't have directories with a slash in their name, either:
  1913. if ($refname =~ m{/$}) {
  1914. die "ref: '$refname' ends with a trailing slash, this is ",
  1915. "not permitted by git nor Subversion\n";
  1916. }
  1917. # It cannot have ASCII control character space, tilde ~, caret ^,
  1918. # colon :, question-mark ?, asterisk *, space, or open bracket [
  1919. # anywhere.
  1920. #
  1921. # Additionally, % must be escaped because it is used for escaping
  1922. # and we want our escaped refname to be reversible
  1923. $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
  1924. # no slash-separated component can begin with a dot .
  1925. # /.* becomes /%2E*
  1926. $refname =~ s{/\.}{/%2E}g;
  1927. # It cannot have two consecutive dots .. anywhere
  1928. # .. becomes %2E%2E
  1929. $refname =~ s{\.\.}{%2E%2E}g;
  1930. # trailing dots and .lock are not allowed
  1931. # .$ becomes %2E and .lock becomes %2Elock
  1932. $refname =~ s{\.(?=$|lock$)}{%2E};
  1933. # the sequence @{ is used to access the reflog
  1934. # @{ becomes %40{
  1935. $refname =~ s{\@\{}{%40\{}g;
  1936. return $refname;
  1937. }
  1938. sub desanitize_refname {
  1939. my ($refname) = @_;
  1940. $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
  1941. return $refname;
  1942. }
  1943. sub svm_uuid {
  1944. my ($self) = @_;
  1945. return $self->{svm}->{uuid} if $self->svm;
  1946. $self->ra;
  1947. unless ($self->{svm}) {
  1948. die "SVM UUID not cached, and reading remotely failed\n";
  1949. }
  1950. $self->{svm}->{uuid};
  1951. }
  1952. sub svm {
  1953. my ($self) = @_;
  1954. return $self->{svm} if $self->{svm};
  1955. my $svm;
  1956. # see if we have it in our config, first:
  1957. eval {
  1958. my $section = "svn-remote.$self->{repo_id}";
  1959. $svm = {
  1960. source => tmp_config('--get', "$section.svm-source"),
  1961. uuid => tmp_config('--get', "$section.svm-uuid"),
  1962. replace => tmp_config('--get', "$section.svm-replace"),
  1963. }
  1964. };
  1965. if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
  1966. $self->{svm} = $svm;
  1967. }
  1968. $self->{svm};
  1969. }
  1970. sub _set_svm_vars {
  1971. my ($self, $ra) = @_;
  1972. return $ra if $self->svm;
  1973. my @err = ( "useSvmProps set, but failed to read SVM properties\n",
  1974. "(svm:source, svm:uuid) ",
  1975. "from the following URLs:\n" );
  1976. sub read_svm_props {
  1977. my ($self, $ra, $path, $r) = @_;
  1978. my $props = ($ra->get_dir($path, $r))[2];
  1979. my $src = $props->{'svm:source'};
  1980. my $uuid = $props->{'svm:uuid'};
  1981. return undef if (!$src || !$uuid);
  1982. chomp($src, $uuid);
  1983. $uuid =~ m{^[0-9a-f\-]{30,}$}i
  1984. or die "doesn't look right - svm:uuid is '$uuid'\n";
  1985. # the '!' is used to mark the repos_root!/relative/path
  1986. $src =~ s{/?!/?}{/};
  1987. $src =~ s{/+$}{}; # no trailing slashes please
  1988. # username is of no interest
  1989. $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
  1990. my $replace = $ra->{url};
  1991. $replace .= "/$path" if length $path;
  1992. my $section = "svn-remote.$self->{repo_id}";
  1993. tmp_config("$section.svm-source", $src);
  1994. tmp_config("$section.svm-replace", $replace);
  1995. tmp_config("$section.svm-uuid", $uuid);
  1996. $self->{svm} = {
  1997. source => $src,
  1998. uuid => $uuid,
  1999. replace => $replace
  2000. };
  2001. }
  2002. my $r = $ra->get_latest_revnum;
  2003. my $path = $self->{path};
  2004. my %tried;
  2005. while (length $path) {
  2006. unless ($tried{"$self->{url}/$path"}) {
  2007. return $ra if $self->read_svm_props($ra, $path, $r);
  2008. $tried{"$self->{url}/$path"} = 1;
  2009. }
  2010. $path =~ s#/?[^/]+$##;
  2011. }
  2012. die "Path: '$path' should be ''\n" if $path ne '';
  2013. return $ra if $self->read_svm_props($ra, $path, $r);
  2014. $tried{"$self->{url}/$path"} = 1;
  2015. if ($ra->{repos_root} eq $self->{url}) {
  2016. die @err, (map { " $_\n" } keys %tried), "\n";
  2017. }
  2018. # nope, make sure we're connected to the repository root:
  2019. my $ok;
  2020. my @tried_b;
  2021. $path = $ra->{svn_path};
  2022. $ra = Git::SVN::Ra->new($ra->{repos_root});
  2023. while (length $path) {
  2024. unless ($tried{"$ra->{url}/$path"}) {
  2025. $ok = $self->read_svm_props($ra, $path, $r);
  2026. last if $ok;
  2027. $tried{"$ra->{url}/$path"} = 1;
  2028. }
  2029. $path =~ s#/?[^/]+$##;
  2030. }
  2031. die "Path: '$path' should be ''\n" if $path ne '';
  2032. $ok ||= $self->read_svm_props($ra, $path, $r);
  2033. $tried{"$ra->{url}/$path"} = 1;
  2034. if (!$ok) {
  2035. die @err, (map { " $_\n" } keys %tried), "\n";
  2036. }
  2037. Git::SVN::Ra->new($self->{url});
  2038. }
  2039. sub svnsync {
  2040. my ($self) = @_;
  2041. return $self->{svnsync} if $self->{svnsync};
  2042. if ($self->no_metadata) {
  2043. die "Can't have both 'noMetadata' and ",
  2044. "'useSvnsyncProps' options set!\n";
  2045. }
  2046. if ($self->rewrite_root) {
  2047. die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
  2048. "options set!\n";
  2049. }
  2050. if ($self->rewrite_uuid) {
  2051. die "Can't have both 'useSvnsyncProps' and 'rewriteUUID' ",
  2052. "options set!\n";
  2053. }
  2054. my $svnsync;
  2055. # see if we have it in our config, first:
  2056. eval {
  2057. my $section = "svn-remote.$self->{repo_id}";
  2058. my $url = tmp_config('--get', "$section.svnsync-url");
  2059. ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
  2060. die "doesn't look right - svn:sync-from-url is '$url'\n";
  2061. my $uuid = tmp_config('--get', "$section.svnsync-uuid");
  2062. ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
  2063. die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
  2064. $svnsync = { url => $url, uuid => $uuid }
  2065. };
  2066. if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
  2067. return $self->{svnsync} = $svnsync;
  2068. }
  2069. my $err = "useSvnsyncProps set, but failed to read " .
  2070. "svnsync property: svn:sync-from-";
  2071. my $rp = $self->ra->rev_proplist(0);
  2072. my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
  2073. ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
  2074. die "doesn't look right - svn:sync-from-url is '$url'\n";
  2075. my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
  2076. ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
  2077. die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
  2078. my $section = "svn-remote.$self->{repo_id}";
  2079. tmp_config('--add', "$section.svnsync-uuid", $uuid);
  2080. tmp_config('--add', "$section.svnsync-url", $url);
  2081. return $self->{svnsync} = { url => $url, uuid => $uuid };
  2082. }
  2083. # this allows us to memoize our SVN::Ra UUID locally and avoid a
  2084. # remote lookup (useful for 'git svn log').
  2085. sub ra_uuid {
  2086. my ($self) = @_;
  2087. unless ($self->{ra_uuid}) {
  2088. my $key = "svn-remote.$self->{repo_id}.uuid";
  2089. my $uuid = eval { tmp_config('--get', $key) };
  2090. if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
  2091. $self->{ra_uuid} = $uuid;
  2092. } else {
  2093. die "ra_uuid called without URL\n" unless $self->{url};
  2094. $self->{ra_uuid} = $self->ra->get_uuid;
  2095. tmp_config('--add', $key, $self->{ra_uuid});
  2096. }
  2097. }
  2098. $self->{ra_uuid};
  2099. }
  2100. sub _set_repos_root {
  2101. my ($self, $repos_root) = @_;
  2102. my $k = "svn-remote.$self->{repo_id}.reposRoot";
  2103. $repos_root ||= $self->ra->{repos_root};
  2104. tmp_config($k, $repos_root);
  2105. $repos_root;
  2106. }
  2107. sub repos_root {
  2108. my ($self) = @_;
  2109. my $k = "svn-remote.$self->{repo_id}.reposRoot";
  2110. eval { tmp_config('--get', $k) } || $self->_set_repos_root;
  2111. }
  2112. sub ra {
  2113. my ($self) = shift;
  2114. my $ra = Git::SVN::Ra->new($self->{url});
  2115. $self->_set_repos_root($ra->{repos_root});
  2116. if ($self->use_svm_props && !$self->{svm}) {
  2117. if ($self->no_metadata) {
  2118. die "Can't have both 'noMetadata' and ",
  2119. "'useSvmProps' options set!\n";
  2120. } elsif ($self->use_svnsync_props) {
  2121. die "Can't have both 'useSvnsyncProps' and ",
  2122. "'useSvmProps' options set!\n";
  2123. }
  2124. $ra = $self->_set_svm_vars($ra);
  2125. $self->{-want_revprops} = 1;
  2126. }
  2127. $ra;
  2128. }
  2129. # prop_walk(PATH, REV, SUB)
  2130. # -------------------------
  2131. # Recursively traverse PATH at revision REV and invoke SUB for each
  2132. # directory that contains a SVN property. SUB will be invoked as
  2133. # follows: &SUB(gs, path, props); where `gs' is this instance of
  2134. # Git::SVN, `path' the path to the directory where the properties
  2135. # `props' were found. The `path' will be relative to point of checkout,
  2136. # that is, if url://repo/trunk is the current Git branch, and that
  2137. # directory contains a sub-directory `d', SUB will be invoked with `/d/'
  2138. # as `path' (note the trailing `/').
  2139. sub prop_walk {
  2140. my ($self, $path, $rev, $sub) = @_;
  2141. $path =~ s#^/##;
  2142. my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
  2143. $path =~ s#^/*#/#g;
  2144. my $p = $path;
  2145. # Strip the irrelevant part of the path.
  2146. $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
  2147. # Ensure the path is terminated by a `/'.
  2148. $p =~ s#/*$#/#;
  2149. # The properties contain all the internal SVN stuff nobody
  2150. # (usually) cares about.
  2151. my $interesting_props = 0;
  2152. foreach (keys %{$props}) {
  2153. # If it doesn't start with `svn:', it must be a
  2154. # user-defined property.
  2155. ++$interesting_props and next if $_ !~ /^svn:/;
  2156. # FIXME: Fragile, if SVN adds new public properties,
  2157. # this needs to be updated.
  2158. ++$interesting_props if /^svn:(?:ignore|keywords|executable
  2159. |eol-style|mime-type
  2160. |externals|needs-lock)$/x;
  2161. }
  2162. &$sub($self, $p, $props) if $interesting_props;
  2163. foreach (sort keys %$dirent) {
  2164. next if $dirent->{$_}->{kind} != $SVN::Node::dir;
  2165. $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
  2166. }
  2167. }
  2168. sub last_rev { ($_[0]->last_rev_commit)[0] }
  2169. sub last_commit { ($_[0]->last_rev_commit)[1] }
  2170. # returns the newest SVN revision number and newest commit SHA1
  2171. sub last_rev_commit {
  2172. my ($self) = @_;
  2173. if (defined $self->{last_rev} && defined $self->{last_commit}) {
  2174. return ($self->{last_rev}, $self->{last_commit});
  2175. }
  2176. my $c = ::verify_ref($self->refname.'^0');
  2177. if ($c && !$self->use_svm_props && !$self->no_metadata) {
  2178. my $rev = (::cmt_metadata($c))[1];
  2179. if (defined $rev) {
  2180. ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
  2181. return ($rev, $c);
  2182. }
  2183. }
  2184. my $map_path = $self->map_path;
  2185. unless (-e $map_path) {
  2186. ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
  2187. return (undef, undef);
  2188. }
  2189. my ($rev, $commit) = $self->rev_map_max(1);
  2190. ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
  2191. return ($rev, $commit);
  2192. }
  2193. sub get_fetch_range {
  2194. my ($self, $min, $max) = @_;
  2195. $max ||= $self->ra->get_latest_revnum;
  2196. $min ||= $self->rev_map_max;
  2197. (++$min, $max);
  2198. }
  2199. sub tmp_config {
  2200. my (@args) = @_;
  2201. my $old_def_config = "$ENV{GIT_DIR}/svn/config";
  2202. my $config = "$ENV{GIT_DIR}/svn/.metadata";
  2203. if (! -f $config && -f $old_def_config) {
  2204. rename $old_def_config, $config or
  2205. die "Failed rename $old_def_config => $config: $!\n";
  2206. }
  2207. my $old_config = $ENV{GIT_CONFIG};
  2208. $ENV{GIT_CONFIG} = $config;
  2209. $@ = undef;
  2210. my @ret = eval {
  2211. unless (-f $config) {
  2212. mkfile($config);
  2213. open my $fh, '>', $config or
  2214. die "Can't open $config: $!\n";
  2215. print $fh "; This file is used internally by ",
  2216. "git-svn\n" or die
  2217. "Couldn't write to $config: $!\n";
  2218. print $fh "; You should not have to edit it\n" or
  2219. die "Couldn't write to $config: $!\n";
  2220. close $fh or die "Couldn't close $config: $!\n";
  2221. }
  2222. command('config', @args);
  2223. };
  2224. my $err = $@;
  2225. if (defined $old_config) {
  2226. $ENV{GIT_CONFIG} = $old_config;
  2227. } else {
  2228. delete $ENV{GIT_CONFIG};
  2229. }
  2230. die $err if $err;
  2231. wantarray ? @ret : $ret[0];
  2232. }
  2233. sub tmp_index_do {
  2234. my ($self, $sub) = @_;
  2235. my $old_index = $ENV{GIT_INDEX_FILE};
  2236. $ENV{GIT_INDEX_FILE} = $self->{index};
  2237. $@ = undef;
  2238. my @ret = eval {
  2239. my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
  2240. mkpath([$dir]) unless -d $dir;
  2241. &$sub;
  2242. };
  2243. my $err = $@;
  2244. if (defined $old_index) {
  2245. $ENV{GIT_INDEX_FILE} = $old_index;
  2246. } else {
  2247. delete $ENV{GIT_INDEX_FILE};
  2248. }
  2249. die $err if $err;
  2250. wantarray ? @ret : $ret[0];
  2251. }
  2252. sub assert_index_clean {
  2253. my ($self, $treeish) = @_;
  2254. $self->tmp_index_do(sub {
  2255. command_noisy('read-tree', $treeish) unless -e $self->{index};
  2256. my $x = command_oneline('write-tree');
  2257. my ($y) = (command(qw/cat-file commit/, $treeish) =~
  2258. /^tree ($::sha1)/mo);
  2259. return if $y eq $x;
  2260. warn "Index mismatch: $y != $x\nrereading $treeish\n";
  2261. unlink $self->{index} or die "unlink $self->{index}: $!\n";
  2262. command_noisy('read-tree', $treeish);
  2263. $x = command_oneline('write-tree');
  2264. if ($y ne $x) {
  2265. ::fatal "trees ($treeish) $y != $x\n",
  2266. "Something is seriously wrong...";
  2267. }
  2268. });
  2269. }
  2270. sub get_commit_parents {
  2271. my ($self, $log_entry) = @_;
  2272. my (%seen, @ret, @tmp);
  2273. # legacy support for 'set-tree'; this is only used by set_tree_cb:
  2274. if (my $ip = $self->{inject_parents}) {
  2275. if (my $commit = delete $ip->{$log_entry->{revision}}) {
  2276. push @tmp, $commit;
  2277. }
  2278. }
  2279. if (my $cur = ::verify_ref($self->refname.'^0')) {
  2280. push @tmp, $cur;
  2281. }
  2282. if (my $ipd = $self->{inject_parents_dcommit}) {
  2283. if (my $commit = delete $ipd->{$log_entry->{revision}}) {
  2284. push @tmp, @$commit;
  2285. }
  2286. }
  2287. push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
  2288. while (my $p = shift @tmp) {
  2289. next if $seen{$p};
  2290. $seen{$p} = 1;
  2291. push @ret, $p;
  2292. }
  2293. @ret;
  2294. }
  2295. sub rewrite_root {
  2296. my ($self) = @_;
  2297. return $self->{-rewrite_root} if exists $self->{-rewrite_root};
  2298. my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
  2299. my $rwr = eval { command_oneline(qw/config --get/, $k) };
  2300. if ($rwr) {
  2301. $rwr =~ s#/+$##;
  2302. if ($rwr !~ m#^[a-z\+]+://#) {
  2303. die "$rwr is not a valid URL (key: $k)\n";
  2304. }
  2305. }
  2306. $self->{-rewrite_root} = $rwr;
  2307. }
  2308. sub rewrite_uuid {
  2309. my ($self) = @_;
  2310. return $self->{-rewrite_uuid} if exists $self->{-rewrite_uuid};
  2311. my $k = "svn-remote.$self->{repo_id}.rewriteUUID";
  2312. my $rwid = eval { command_oneline(qw/config --get/, $k) };
  2313. if ($rwid) {
  2314. $rwid =~ s#/+$##;
  2315. if ($rwid !~ m#^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$#) {
  2316. die "$rwid is not a valid UUID (key: $k)\n";
  2317. }
  2318. }
  2319. $self->{-rewrite_uuid} = $rwid;
  2320. }
  2321. sub metadata_url {
  2322. my ($self) = @_;
  2323. ($self->rewrite_root || $self->{url}) .
  2324. (length $self->{path} ? '/' . $self->{path} : '');
  2325. }
  2326. sub full_url {
  2327. my ($self) = @_;
  2328. $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
  2329. }
  2330. sub set_commit_header_env {
  2331. my ($log_entry) = @_;
  2332. my %env;
  2333. foreach my $ned (qw/NAME EMAIL DATE/) {
  2334. foreach my $ac (qw/AUTHOR COMMITTER/) {
  2335. $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
  2336. }
  2337. }
  2338. $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
  2339. $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
  2340. $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
  2341. $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
  2342. ? $log_entry->{commit_name}
  2343. : $log_entry->{name};
  2344. $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
  2345. ? $log_entry->{commit_email}
  2346. : $log_entry->{email};
  2347. \%env;
  2348. }
  2349. sub restore_commit_header_env {
  2350. my ($env) = @_;
  2351. foreach my $ned (qw/NAME EMAIL DATE/) {
  2352. foreach my $ac (qw/AUTHOR COMMITTER/) {
  2353. my $k = "GIT_${ac}_${ned}";
  2354. if (defined $env->{$k}) {
  2355. $ENV{$k} = $env->{$k};
  2356. } else {
  2357. delete $ENV{$k};
  2358. }
  2359. }
  2360. }
  2361. }
  2362. sub gc {
  2363. command_noisy('gc', '--auto');
  2364. };
  2365. sub do_git_commit {
  2366. my ($self, $log_entry) = @_;
  2367. my $lr = $self->last_rev;
  2368. if (defined $lr && $lr >= $log_entry->{revision}) {
  2369. die "Last fetched revision of ", $self->refname,
  2370. " was r$lr, but we are about to fetch: ",
  2371. "r$log_entry->{revision}!\n";
  2372. }
  2373. if (my $c = $self->rev_map_get($log_entry->{revision})) {
  2374. croak "$log_entry->{revision} = $c already exists! ",
  2375. "Why are we refetching it?\n";
  2376. }
  2377. my $old_env = set_commit_header_env($log_entry);
  2378. my $tree = $log_entry->{tree};
  2379. if (!defined $tree) {
  2380. $tree = $self->tmp_index_do(sub {
  2381. command_oneline('write-tree') });
  2382. }
  2383. die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
  2384. my @exec = ('git', 'commit-tree', $tree);
  2385. foreach ($self->get_commit_parents($log_entry)) {
  2386. push @exec, '-p', $_;
  2387. }
  2388. defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
  2389. or croak $!;
  2390. binmode $msg_fh;
  2391. # we always get UTF-8 from SVN, but we may want our commits in
  2392. # a different encoding.
  2393. if (my $enc = Git::config('i18n.commitencoding')) {
  2394. require Encode;
  2395. Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
  2396. }
  2397. print $msg_fh $log_entry->{log} or croak $!;
  2398. restore_commit_header_env($old_env);
  2399. unless ($self->no_metadata) {
  2400. print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
  2401. or croak $!;
  2402. }
  2403. $msg_fh->flush == 0 or croak $!;
  2404. close $msg_fh or croak $!;
  2405. chomp(my $commit = do { local $/; <$out_fh> });
  2406. close $out_fh or croak $!;
  2407. waitpid $pid, 0;
  2408. croak $? if $?;
  2409. if ($commit !~ /^$::sha1$/o) {
  2410. die "Failed to commit, invalid sha1: $commit\n";
  2411. }
  2412. $self->rev_map_set($log_entry->{revision}, $commit, 1);
  2413. $self->{last_rev} = $log_entry->{revision};
  2414. $self->{last_commit} = $commit;
  2415. print "r$log_entry->{revision}" unless $::_q > 1;
  2416. if (defined $log_entry->{svm_revision}) {
  2417. print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
  2418. $self->rev_map_set($log_entry->{svm_revision}, $commit,
  2419. 0, $self->svm_uuid);
  2420. }
  2421. print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
  2422. if (--$_gc_nr == 0) {
  2423. $_gc_nr = $_gc_period;
  2424. gc();
  2425. }
  2426. return $commit;
  2427. }
  2428. sub match_paths {
  2429. my ($self, $paths, $r) = @_;
  2430. return 1 if $self->{path} eq '';
  2431. if (my $path = $paths->{"/$self->{path}"}) {
  2432. return ($path->{action} eq 'D') ? 0 : 1;
  2433. }
  2434. $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
  2435. if (grep /$self->{path_regex}/, keys %$paths) {
  2436. return 1;
  2437. }
  2438. my $c = '';
  2439. foreach (split m#/#, $self->{path}) {
  2440. $c .= "/$_";
  2441. next unless ($paths->{$c} &&
  2442. ($paths->{$c}->{action} =~ /^[AR]$/));
  2443. if ($self->ra->check_path($self->{path}, $r) ==
  2444. $SVN::Node::dir) {
  2445. return 1;
  2446. }
  2447. }
  2448. return 0;
  2449. }
  2450. sub find_parent_branch {
  2451. my ($self, $paths, $rev) = @_;
  2452. return undef unless $self->follow_parent;
  2453. unless (defined $paths) {
  2454. my $err_handler = $SVN::Error::handler;
  2455. $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
  2456. $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1,
  2457. sub { $paths = $_[0] });
  2458. $SVN::Error::handler = $err_handler;
  2459. }
  2460. return undef unless defined $paths;
  2461. # look for a parent from another branch:
  2462. my @b_path_components = split m#/#, $self->{path};
  2463. my @a_path_components;
  2464. my $i;
  2465. while (@b_path_components) {
  2466. $i = $paths->{'/'.join('/', @b_path_components)};
  2467. last if $i && defined $i->{copyfrom_path};
  2468. unshift(@a_path_components, pop(@b_path_components));
  2469. }
  2470. return undef unless defined $i && defined $i->{copyfrom_path};
  2471. my $branch_from = $i->{copyfrom_path};
  2472. if (@a_path_components) {
  2473. print STDERR "branch_from: $branch_from => ";
  2474. $branch_from .= '/'.join('/', @a_path_components);
  2475. print STDERR $branch_from, "\n";
  2476. }
  2477. my $r = $i->{copyfrom_rev};
  2478. my $repos_root = $self->ra->{repos_root};
  2479. my $url = $self->ra->{url};
  2480. my $new_url = $url . $branch_from;
  2481. print STDERR "Found possible branch point: ",
  2482. "$new_url => ", $self->full_url, ", $r\n"
  2483. unless $::_q > 1;
  2484. $branch_from =~ s#^/##;
  2485. my $gs = $self->other_gs($new_url, $url,
  2486. $branch_from, $r, $self->{ref_id});
  2487. my ($r0, $parent) = $gs->find_rev_before($r, 1);
  2488. {
  2489. my ($base, $head);
  2490. if (!defined $r0 || !defined $parent) {
  2491. ($base, $head) = parse_revision_argument(0, $r);
  2492. } else {
  2493. if ($r0 < $r) {
  2494. $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
  2495. 0, 1, sub { $base = $_[1] - 1 });
  2496. }
  2497. }
  2498. if (defined $base && $base <= $r) {
  2499. $gs->fetch($base, $r);
  2500. }
  2501. ($r0, $parent) = $gs->find_rev_before($r, 1);
  2502. }
  2503. if (defined $r0 && defined $parent) {
  2504. print STDERR "Found branch parent: ($self->{ref_id}) $parent\n"
  2505. unless $::_q > 1;
  2506. my $ed;
  2507. if ($self->ra->can_do_switch) {
  2508. $self->assert_index_clean($parent);
  2509. print STDERR "Following parent with do_switch\n"
  2510. unless $::_q > 1;
  2511. # do_switch works with svn/trunk >= r22312, but that
  2512. # is not included with SVN 1.4.3 (the latest version
  2513. # at the moment), so we can't rely on it
  2514. $self->{last_rev} = $r0;
  2515. $self->{last_commit} = $parent;
  2516. $ed = SVN::Git::Fetcher->new($self, $gs->{path});
  2517. $gs->ra->gs_do_switch($r0, $rev, $gs,
  2518. $self->full_url, $ed)
  2519. or die "SVN connection failed somewhere...\n";
  2520. } elsif ($self->ra->trees_match($new_url, $r0,
  2521. $self->full_url, $rev)) {
  2522. print STDERR "Trees match:\n",
  2523. " $new_url\@$r0\n",
  2524. " ${\$self->full_url}\@$rev\n",
  2525. "Following parent with no changes\n"
  2526. unless $::_q > 1;
  2527. $self->tmp_index_do(sub {
  2528. command_noisy('read-tree', $parent);
  2529. });
  2530. $self->{last_commit} = $parent;
  2531. } else {
  2532. print STDERR "Following parent with do_update\n"
  2533. unless $::_q > 1;
  2534. $ed = SVN::Git::Fetcher->new($self);
  2535. $self->ra->gs_do_update($rev, $rev, $self, $ed)
  2536. or die "SVN connection failed somewhere...\n";
  2537. }
  2538. print STDERR "Successfully followed parent\n" unless $::_q > 1;
  2539. return $self->make_log_entry($rev, [$parent], $ed);
  2540. }
  2541. return undef;
  2542. }
  2543. sub do_fetch {
  2544. my ($self, $paths, $rev) = @_;
  2545. my $ed;
  2546. my ($last_rev, @parents);
  2547. if (my $lc = $self->last_commit) {
  2548. # we can have a branch that was deleted, then re-added
  2549. # under the same name but copied from another path, in
  2550. # which case we'll have multiple parents (we don't
  2551. # want to break the original ref, nor lose copypath info):
  2552. if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
  2553. push @{$log_entry->{parents}}, $lc;
  2554. return $log_entry;
  2555. }
  2556. $ed = SVN::Git::Fetcher->new($self);
  2557. $last_rev = $self->{last_rev};
  2558. $ed->{c} = $lc;
  2559. @parents = ($lc);
  2560. } else {
  2561. $last_rev = $rev;
  2562. if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
  2563. return $log_entry;
  2564. }
  2565. $ed = SVN::Git::Fetcher->new($self);
  2566. }
  2567. unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
  2568. die "SVN connection failed somewhere...\n";
  2569. }
  2570. $self->make_log_entry($rev, \@parents, $ed);
  2571. }
  2572. sub mkemptydirs {
  2573. my ($self, $r) = @_;
  2574. sub scan {
  2575. my ($r, $empty_dirs, $line) = @_;
  2576. if (defined $r && $line =~ /^r(\d+)$/) {
  2577. return 0 if $1 > $r;
  2578. } elsif ($line =~ /^ \+empty_dir: (.+)$/) {
  2579. $empty_dirs->{$1} = 1;
  2580. } elsif ($line =~ /^ \-empty_dir: (.+)$/) {
  2581. my @d = grep {m[^\Q$1\E(/|$)]} (keys %$empty_dirs);
  2582. delete @$empty_dirs{@d};
  2583. }
  2584. 1; # continue
  2585. };
  2586. my %empty_dirs = ();
  2587. my $gz_file = "$self->{dir}/unhandled.log.gz";
  2588. if (-f $gz_file) {
  2589. if (!$can_compress) {
  2590. warn "Compress::Zlib could not be found; ",
  2591. "empty directories in $gz_file will not be read\n";
  2592. } else {
  2593. my $gz = Compress::Zlib::gzopen($gz_file, "rb") or
  2594. die "Unable to open $gz_file: $!\n";
  2595. my $line;
  2596. while ($gz->gzreadline($line) > 0) {
  2597. scan($r, \%empty_dirs, $line) or last;
  2598. }
  2599. $gz->gzclose;
  2600. }
  2601. }
  2602. if (open my $fh, '<', "$self->{dir}/unhandled.log") {
  2603. binmode $fh or croak "binmode: $!";
  2604. while (<$fh>) {
  2605. scan($r, \%empty_dirs, $_) or last;
  2606. }
  2607. close $fh;
  2608. }
  2609. my $strip = qr/\A\Q$self->{path}\E(?:\/|$)/;
  2610. foreach my $d (sort keys %empty_dirs) {
  2611. $d = uri_decode($d);
  2612. $d =~ s/$strip//;
  2613. next unless length($d);
  2614. next if -d $d;
  2615. if (-e $d) {
  2616. warn "$d exists but is not a directory\n";
  2617. } else {
  2618. print "creating empty directory: $d\n";
  2619. mkpath([$d]);
  2620. }
  2621. }
  2622. }
  2623. sub get_untracked {
  2624. my ($self, $ed) = @_;
  2625. my @out;
  2626. my $h = $ed->{empty};
  2627. foreach (sort keys %$h) {
  2628. my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
  2629. push @out, " $act: " . uri_encode($_);
  2630. warn "W: $act: $_\n";
  2631. }
  2632. foreach my $t (qw/dir_prop file_prop/) {
  2633. $h = $ed->{$t} or next;
  2634. foreach my $path (sort keys %$h) {
  2635. my $ppath = $path eq '' ? '.' : $path;
  2636. foreach my $prop (sort keys %{$h->{$path}}) {
  2637. next if $SKIP_PROP{$prop};
  2638. my $v = $h->{$path}->{$prop};
  2639. my $t_ppath_prop = "$t: " .
  2640. uri_encode($ppath) . ' ' .
  2641. uri_encode($prop);
  2642. if (defined $v) {
  2643. push @out, " +$t_ppath_prop " .
  2644. uri_encode($v);
  2645. } else {
  2646. push @out, " -$t_ppath_prop";
  2647. }
  2648. }
  2649. }
  2650. }
  2651. foreach my $t (qw/absent_file absent_directory/) {
  2652. $h = $ed->{$t} or next;
  2653. foreach my $parent (sort keys %$h) {
  2654. foreach my $path (sort @{$h->{$parent}}) {
  2655. push @out, " $t: " .
  2656. uri_encode("$parent/$path");
  2657. warn "W: $t: $parent/$path ",
  2658. "Insufficient permissions?\n";
  2659. }
  2660. }
  2661. }
  2662. \@out;
  2663. }
  2664. # parse_svn_date(DATE)
  2665. # --------------------
  2666. # Given a date (in UTC) from Subversion, return a string in the format
  2667. # "<TZ Offset> <local date/time>" that Git will use.
  2668. #
  2669. # By default the parsed date will be in UTC; if $Git::SVN::_localtime
  2670. # is true we'll convert it to the local timezone instead.
  2671. sub parse_svn_date {
  2672. my $date = shift || return '+0000 1970-01-01 00:00:00';
  2673. my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
  2674. (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
  2675. croak "Unable to parse date: $date\n";
  2676. my $parsed_date; # Set next.
  2677. if ($Git::SVN::_localtime) {
  2678. # Translate the Subversion datetime to an epoch time.
  2679. # Begin by switching ourselves to $date's timezone, UTC.
  2680. my $old_env_TZ = $ENV{TZ};
  2681. $ENV{TZ} = 'UTC';
  2682. my $epoch_in_UTC =
  2683. POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
  2684. # Determine our local timezone (including DST) at the
  2685. # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
  2686. # value of TZ, if any, at the time we were run.
  2687. if (defined $Git::SVN::Log::TZ) {
  2688. $ENV{TZ} = $Git::SVN::Log::TZ;
  2689. } else {
  2690. delete $ENV{TZ};
  2691. }
  2692. my $our_TZ =
  2693. POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
  2694. # This converts $epoch_in_UTC into our local timezone.
  2695. my ($sec, $min, $hour, $mday, $mon, $year,
  2696. $wday, $yday, $isdst) = localtime($epoch_in_UTC);
  2697. $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
  2698. $our_TZ, $year + 1900, $mon + 1,
  2699. $mday, $hour, $min, $sec);
  2700. # Reset us to the timezone in effect when we entered
  2701. # this routine.
  2702. if (defined $old_env_TZ) {
  2703. $ENV{TZ} = $old_env_TZ;
  2704. } else {
  2705. delete $ENV{TZ};
  2706. }
  2707. } else {
  2708. $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
  2709. }
  2710. return $parsed_date;
  2711. }
  2712. sub other_gs {
  2713. my ($self, $new_url, $url,
  2714. $branch_from, $r, $old_ref_id) = @_;
  2715. my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
  2716. unless ($gs) {
  2717. my $ref_id = $old_ref_id;
  2718. $ref_id =~ s/\@\d+-*$//;
  2719. $ref_id .= "\@$r";
  2720. # just grow a tail if we're not unique enough :x
  2721. $ref_id .= '-' while find_ref($ref_id);
  2722. my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
  2723. if ($u =~ s#^\Q$url\E(/|$)##) {
  2724. $p = $u;
  2725. $u = $url;
  2726. $repo_id = $self->{repo_id};
  2727. }
  2728. while (1) {
  2729. # It is possible to tag two different subdirectories at
  2730. # the same revision. If the url for an existing ref
  2731. # does not match, we must either find a ref with a
  2732. # matching url or create a new ref by growing a tail.
  2733. $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
  2734. my (undef, $max_commit) = $gs->rev_map_max(1);
  2735. last if (!$max_commit);
  2736. my ($url) = ::cmt_metadata($max_commit);
  2737. last if ($url eq $gs->full_url);
  2738. $ref_id .= '-';
  2739. }
  2740. print STDERR "Initializing parent: $ref_id\n" unless $::_q > 1;
  2741. }
  2742. $gs
  2743. }
  2744. sub call_authors_prog {
  2745. my ($orig_author) = @_;
  2746. $orig_author = command_oneline('rev-parse', '--sq-quote', $orig_author);
  2747. my $author = `$::_authors_prog $orig_author`;
  2748. if ($? != 0) {
  2749. die "$::_authors_prog failed with exit code $?\n"
  2750. }
  2751. if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
  2752. my ($name, $email) = ($1, $2);
  2753. $email = undef if length $2 == 0;
  2754. return [$name, $email];
  2755. } else {
  2756. die "Author: $orig_author: $::_authors_prog returned "
  2757. . "invalid author format: $author\n";
  2758. }
  2759. }
  2760. sub check_author {
  2761. my ($author) = @_;
  2762. if (!defined $author || length $author == 0) {
  2763. $author = '(no author)';
  2764. }
  2765. if (!defined $::users{$author}) {
  2766. if (defined $::_authors_prog) {
  2767. $::users{$author} = call_authors_prog($author);
  2768. } elsif (defined $::_authors) {
  2769. die "Author: $author not defined in $::_authors file\n";
  2770. }
  2771. }
  2772. $author;
  2773. }
  2774. sub find_extra_svk_parents {
  2775. my ($self, $ed, $tickets, $parents) = @_;
  2776. # aha! svk:merge property changed...
  2777. my @tickets = split "\n", $tickets;
  2778. my @known_parents;
  2779. for my $ticket ( @tickets ) {
  2780. my ($uuid, $path, $rev) = split /:/, $ticket;
  2781. if ( $uuid eq $self->ra_uuid ) {
  2782. my $url = $self->{url};
  2783. my $repos_root = $url;
  2784. my $branch_from = $path;
  2785. $branch_from =~ s{^/}{};
  2786. my $gs = $self->other_gs($repos_root."/".$branch_from,
  2787. $url,
  2788. $branch_from,
  2789. $rev,
  2790. $self->{ref_id});
  2791. if ( my $commit = $gs->rev_map_get($rev, $uuid) ) {
  2792. # wahey! we found it, but it might be
  2793. # an old one (!)
  2794. push @known_parents, [ $rev, $commit ];
  2795. }
  2796. }
  2797. }
  2798. # Ordering matters; highest-numbered commit merge tickets
  2799. # first, as they may account for later merge ticket additions
  2800. # or changes.
  2801. @known_parents = map {$_->[1]} sort {$b->[0] <=> $a->[0]} @known_parents;
  2802. for my $parent ( @known_parents ) {
  2803. my @cmd = ('rev-list', $parent, map { "^$_" } @$parents );
  2804. my ($msg_fh, $ctx) = command_output_pipe(@cmd);
  2805. my $new;
  2806. while ( <$msg_fh> ) {
  2807. $new=1;last;
  2808. }
  2809. command_close_pipe($msg_fh, $ctx);
  2810. if ( $new ) {
  2811. print STDERR
  2812. "Found merge parent (svk:merge ticket): $parent\n";
  2813. push @$parents, $parent;
  2814. }
  2815. }
  2816. }
  2817. sub lookup_svn_merge {
  2818. my $uuid = shift;
  2819. my $url = shift;
  2820. my $merge = shift;
  2821. my ($source, $revs) = split ":", $merge;
  2822. my $path = $source;
  2823. $path =~ s{^/}{};
  2824. my $gs = Git::SVN->find_by_url($url.$source, $url, $path);
  2825. if ( !$gs ) {
  2826. warn "Couldn't find revmap for $url$source\n";
  2827. return;
  2828. }
  2829. my @ranges = split ",", $revs;
  2830. my ($tip, $tip_commit);
  2831. my @merged_commit_ranges;
  2832. # find the tip
  2833. for my $range ( @ranges ) {
  2834. my ($bottom, $top) = split "-", $range;
  2835. $top ||= $bottom;
  2836. my $bottom_commit = $gs->find_rev_after( $bottom, 1, $top );
  2837. my $top_commit = $gs->find_rev_before( $top, 1, $bottom );
  2838. unless ($top_commit and $bottom_commit) {
  2839. warn "W:unknown path/rev in svn:mergeinfo "
  2840. ."dirprop: $source:$range\n";
  2841. next;
  2842. }
  2843. push @merged_commit_ranges,
  2844. "$bottom_commit^..$top_commit";
  2845. if ( !defined $tip or $top > $tip ) {
  2846. $tip = $top;
  2847. $tip_commit = $top_commit;
  2848. }
  2849. }
  2850. return ($tip_commit, @merged_commit_ranges);
  2851. }
  2852. sub _rev_list {
  2853. my ($msg_fh, $ctx) = command_output_pipe(
  2854. "rev-list", @_,
  2855. );
  2856. my @rv;
  2857. while ( <$msg_fh> ) {
  2858. chomp;
  2859. push @rv, $_;
  2860. }
  2861. command_close_pipe($msg_fh, $ctx);
  2862. @rv;
  2863. }
  2864. sub check_cherry_pick {
  2865. my $base = shift;
  2866. my $tip = shift;
  2867. my @ranges = @_;
  2868. my %commits = map { $_ => 1 }
  2869. _rev_list("--no-merges", $tip, "--not", $base);
  2870. for my $range ( @ranges ) {
  2871. delete @commits{_rev_list($range)};
  2872. }
  2873. for my $commit (keys %commits) {
  2874. if (has_no_changes($commit)) {
  2875. delete $commits{$commit};
  2876. }
  2877. }
  2878. return (keys %commits);
  2879. }
  2880. sub has_no_changes {
  2881. my $commit = shift;
  2882. my @revs = split / /, command_oneline(
  2883. qw(rev-list --parents -1 -m), $commit);
  2884. # Commits with no parents, e.g. the start of a partial branch,
  2885. # have changes by definition.
  2886. return 1 if (@revs < 2);
  2887. # Commits with multiple parents, e.g a merge, have no changes
  2888. # by definition.
  2889. return 0 if (@revs > 2);
  2890. return (command_oneline("rev-parse", "$commit^{tree}") eq
  2891. command_oneline("rev-parse", "$commit~1^{tree}"));
  2892. }
  2893. # The GIT_DIR environment variable is not always set until after the command
  2894. # line arguments are processed, so we can't memoize in a BEGIN block.
  2895. {
  2896. my $memoized = 0;
  2897. sub memoize_svn_mergeinfo_functions {
  2898. return if $memoized;
  2899. $memoized = 1;
  2900. my $cache_path = "$ENV{GIT_DIR}/svn/.caches/";
  2901. mkpath([$cache_path]) unless -d $cache_path;
  2902. tie my %lookup_svn_merge_cache => 'Memoize::Storable',
  2903. "$cache_path/lookup_svn_merge.db", 'nstore';
  2904. memoize 'lookup_svn_merge',
  2905. SCALAR_CACHE => 'FAULT',
  2906. LIST_CACHE => ['HASH' => \%lookup_svn_merge_cache],
  2907. ;
  2908. tie my %check_cherry_pick_cache => 'Memoize::Storable',
  2909. "$cache_path/check_cherry_pick.db", 'nstore';
  2910. memoize 'check_cherry_pick',
  2911. SCALAR_CACHE => 'FAULT',
  2912. LIST_CACHE => ['HASH' => \%check_cherry_pick_cache],
  2913. ;
  2914. tie my %has_no_changes_cache => 'Memoize::Storable',
  2915. "$cache_path/has_no_changes.db", 'nstore';
  2916. memoize 'has_no_changes',
  2917. SCALAR_CACHE => ['HASH' => \%has_no_changes_cache],
  2918. LIST_CACHE => 'FAULT',
  2919. ;
  2920. }
  2921. sub unmemoize_svn_mergeinfo_functions {
  2922. return if not $memoized;
  2923. $memoized = 0;
  2924. Memoize::unmemoize 'lookup_svn_merge';
  2925. Memoize::unmemoize 'check_cherry_pick';
  2926. Memoize::unmemoize 'has_no_changes';
  2927. }
  2928. }
  2929. END {
  2930. # Force cache writeout explicitly instead of waiting for
  2931. # global destruction to avoid segfault in Storable:
  2932. # http://rt.cpan.org/Public/Bug/Display.html?id=36087
  2933. unmemoize_svn_mergeinfo_functions();
  2934. }
  2935. sub parents_exclude {
  2936. my $parents = shift;
  2937. my @commits = @_;
  2938. return unless @commits;
  2939. my @excluded;
  2940. my $excluded;
  2941. do {
  2942. my @cmd = ('rev-list', "-1", @commits, "--not", @$parents );
  2943. $excluded = command_oneline(@cmd);
  2944. if ( $excluded ) {
  2945. my @new;
  2946. my $found;
  2947. for my $commit ( @commits ) {
  2948. if ( $commit eq $excluded ) {
  2949. push @excluded, $commit;
  2950. $found++;
  2951. last;
  2952. }
  2953. else {
  2954. push @new, $commit;
  2955. }
  2956. }
  2957. die "saw commit '$excluded' in rev-list output, "
  2958. ."but we didn't ask for that commit (wanted: @commits --not @$parents)"
  2959. unless $found;
  2960. @commits = @new;
  2961. }
  2962. }
  2963. while ($excluded and @commits);
  2964. return @excluded;
  2965. }
  2966. # note: this function should only be called if the various dirprops
  2967. # have actually changed
  2968. sub find_extra_svn_parents {
  2969. my ($self, $ed, $mergeinfo, $parents) = @_;
  2970. # aha! svk:merge property changed...
  2971. memoize_svn_mergeinfo_functions();
  2972. # We first search for merged tips which are not in our
  2973. # history. Then, we figure out which git revisions are in
  2974. # that tip, but not this revision. If all of those revisions
  2975. # are now marked as merge, we can add the tip as a parent.
  2976. my @merges = split "\n", $mergeinfo;
  2977. my @merge_tips;
  2978. my $url = $self->{url};
  2979. my $uuid = $self->ra_uuid;
  2980. my %ranges;
  2981. for my $merge ( @merges ) {
  2982. my ($tip_commit, @ranges) =
  2983. lookup_svn_merge( $uuid, $url, $merge );
  2984. unless (!$tip_commit or
  2985. grep { $_ eq $tip_commit } @$parents ) {
  2986. push @merge_tips, $tip_commit;
  2987. $ranges{$tip_commit} = \@ranges;
  2988. } else {
  2989. push @merge_tips, undef;
  2990. }
  2991. }
  2992. my %excluded = map { $_ => 1 }
  2993. parents_exclude($parents, grep { defined } @merge_tips);
  2994. # check merge tips for new parents
  2995. my @new_parents;
  2996. for my $merge_tip ( @merge_tips ) {
  2997. my $spec = shift @merges;
  2998. next unless $merge_tip and $excluded{$merge_tip};
  2999. my $ranges = $ranges{$merge_tip};
  3000. # check out 'new' tips
  3001. my $merge_base;
  3002. eval {
  3003. $merge_base = command_oneline(
  3004. "merge-base",
  3005. @$parents, $merge_tip,
  3006. );
  3007. };
  3008. if ($@) {
  3009. die "An error occurred during merge-base"
  3010. unless $@->isa("Git::Error::Command");
  3011. warn "W: Cannot find common ancestor between ".
  3012. "@$parents and $merge_tip. Ignoring merge info.\n";
  3013. next;
  3014. }
  3015. # double check that there are no missing non-merge commits
  3016. my (@incomplete) = check_cherry_pick(
  3017. $merge_base, $merge_tip,
  3018. @$ranges,
  3019. );
  3020. if ( @incomplete ) {
  3021. warn "W:svn cherry-pick ignored ($spec) - missing "
  3022. .@incomplete." commit(s) (eg $incomplete[0])\n";
  3023. } else {
  3024. warn
  3025. "Found merge parent (svn:mergeinfo prop): ",
  3026. $merge_tip, "\n";
  3027. push @new_parents, $merge_tip;
  3028. }
  3029. }
  3030. # cater for merges which merge commits from multiple branches
  3031. if ( @new_parents > 1 ) {
  3032. for ( my $i = 0; $i <= $#new_parents; $i++ ) {
  3033. for ( my $j = 0; $j <= $#new_parents; $j++ ) {
  3034. next if $i == $j;
  3035. next unless $new_parents[$i];
  3036. next unless $new_parents[$j];
  3037. my $revs = command_oneline(
  3038. "rev-list", "-1",
  3039. "$new_parents[$i]..$new_parents[$j]",
  3040. );
  3041. if ( !$revs ) {
  3042. undef($new_parents[$j]);
  3043. }
  3044. }
  3045. }
  3046. }
  3047. push @$parents, grep { defined } @new_parents;
  3048. }
  3049. sub make_log_entry {
  3050. my ($self, $rev, $parents, $ed) = @_;
  3051. my $untracked = $self->get_untracked($ed);
  3052. my @parents = @$parents;
  3053. my $ps = $ed->{path_strip} || "";
  3054. for my $path ( grep { m/$ps/ } %{$ed->{dir_prop}} ) {
  3055. my $props = $ed->{dir_prop}{$path};
  3056. if ( $props->{"svk:merge"} ) {
  3057. $self->find_extra_svk_parents
  3058. ($ed, $props->{"svk:merge"}, \@parents);
  3059. }
  3060. if ( $props->{"svn:mergeinfo"} ) {
  3061. $self->find_extra_svn_parents
  3062. ($ed,
  3063. $props->{"svn:mergeinfo"},
  3064. \@parents);
  3065. }
  3066. }
  3067. open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
  3068. print $un "r$rev\n" or croak $!;
  3069. print $un $_, "\n" foreach @$untracked;
  3070. my %log_entry = ( parents => \@parents, revision => $rev,
  3071. log => '');
  3072. my $headrev;
  3073. my $logged = delete $self->{logged_rev_props};
  3074. if (!$logged || $self->{-want_revprops}) {
  3075. my $rp = $self->ra->rev_proplist($rev);
  3076. foreach (sort keys %$rp) {
  3077. my $v = $rp->{$_};
  3078. if (/^svn:(author|date|log)$/) {
  3079. $log_entry{$1} = $v;
  3080. } elsif ($_ eq 'svm:headrev') {
  3081. $headrev = $v;
  3082. } else {
  3083. print $un " rev_prop: ", uri_encode($_), ' ',
  3084. uri_encode($v), "\n";
  3085. }
  3086. }
  3087. } else {
  3088. map { $log_entry{$_} = $logged->{$_} } keys %$logged;
  3089. }
  3090. close $un or croak $!;
  3091. $log_entry{date} = parse_svn_date($log_entry{date});
  3092. $log_entry{log} .= "\n";
  3093. my $author = $log_entry{author} = check_author($log_entry{author});
  3094. my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
  3095. : ($author, undef);
  3096. my ($commit_name, $commit_email) = ($name, $email);
  3097. if ($_use_log_author) {
  3098. my $name_field;
  3099. if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
  3100. $name_field = $1;
  3101. } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
  3102. $name_field = $1;
  3103. }
  3104. if (!defined $name_field) {
  3105. if (!defined $email) {
  3106. $email = $name;
  3107. }
  3108. } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
  3109. ($name, $email) = ($1, $2);
  3110. } elsif ($name_field =~ /(.*)@/) {
  3111. ($name, $email) = ($1, $name_field);
  3112. } else {
  3113. ($name, $email) = ($name_field, $name_field);
  3114. }
  3115. }
  3116. if (defined $headrev && $self->use_svm_props) {
  3117. if ($self->rewrite_root) {
  3118. die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
  3119. "options set!\n";
  3120. }
  3121. if ($self->rewrite_uuid) {
  3122. die "Can't have both 'useSvmProps' and 'rewriteUUID' ",
  3123. "options set!\n";
  3124. }
  3125. my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$}i;
  3126. # we don't want "SVM: initializing mirror for junk" ...
  3127. return undef if $r == 0;
  3128. my $svm = $self->svm;
  3129. if ($uuid ne $svm->{uuid}) {
  3130. die "UUID mismatch on SVM path:\n",
  3131. "expected: $svm->{uuid}\n",
  3132. " got: $uuid\n";
  3133. }
  3134. my $full_url = $self->full_url;
  3135. $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
  3136. die "Failed to replace '$svm->{replace}' with ",
  3137. "'$svm->{source}' in $full_url\n";
  3138. # throw away username for storing in records
  3139. remove_username($full_url);
  3140. $log_entry{metadata} = "$full_url\@$r $uuid";
  3141. $log_entry{svm_revision} = $r;
  3142. $email ||= "$author\@$uuid";
  3143. $commit_email ||= "$author\@$uuid";
  3144. } elsif ($self->use_svnsync_props) {
  3145. my $full_url = $self->svnsync->{url};
  3146. $full_url .= "/$self->{path}" if length $self->{path};
  3147. remove_username($full_url);
  3148. my $uuid = $self->svnsync->{uuid};
  3149. $log_entry{metadata} = "$full_url\@$rev $uuid";
  3150. $email ||= "$author\@$uuid";
  3151. $commit_email ||= "$author\@$uuid";
  3152. } else {
  3153. my $url = $self->metadata_url;
  3154. remove_username($url);
  3155. my $uuid = $self->rewrite_uuid || $self->ra->get_uuid;
  3156. $log_entry{metadata} = "$url\@$rev " . $uuid;
  3157. $email ||= "$author\@" . $uuid;
  3158. $commit_email ||= "$author\@" . $uuid;
  3159. }
  3160. $log_entry{name} = $name;
  3161. $log_entry{email} = $email;
  3162. $log_entry{commit_name} = $commit_name;
  3163. $log_entry{commit_email} = $commit_email;
  3164. \%log_entry;
  3165. }
  3166. sub fetch {
  3167. my ($self, $min_rev, $max_rev, @parents) = @_;
  3168. my ($last_rev, $last_commit) = $self->last_rev_commit;
  3169. my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
  3170. $self->ra->gs_fetch_loop_common($base, $head, [$self]);
  3171. }
  3172. sub set_tree_cb {
  3173. my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
  3174. $self->{inject_parents} = { $rev => $tree };
  3175. $self->fetch(undef, undef);
  3176. }
  3177. sub set_tree {
  3178. my ($self, $tree) = (shift, shift);
  3179. my $log_entry = ::get_commit_entry($tree);
  3180. unless ($self->{last_rev}) {
  3181. ::fatal("Must have an existing revision to commit");
  3182. }
  3183. my %ed_opts = ( r => $self->{last_rev},
  3184. log => $log_entry->{log},
  3185. ra => $self->ra,
  3186. tree_a => $self->{last_commit},
  3187. tree_b => $tree,
  3188. editor_cb => sub {
  3189. $self->set_tree_cb($log_entry, $tree, @_) },
  3190. svn_path => $self->{path} );
  3191. if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
  3192. print "No changes\nr$self->{last_rev} = $tree\n";
  3193. }
  3194. }
  3195. sub rebuild_from_rev_db {
  3196. my ($self, $path) = @_;
  3197. my $r = -1;
  3198. open my $fh, '<', $path or croak "open: $!";
  3199. binmode $fh or croak "binmode: $!";
  3200. while (<$fh>) {
  3201. length($_) == 41 or croak "inconsistent size in ($_) != 41";
  3202. chomp($_);
  3203. ++$r;
  3204. next if $_ eq ('0' x 40);
  3205. $self->rev_map_set($r, $_);
  3206. print "r$r = $_\n";
  3207. }
  3208. close $fh or croak "close: $!";
  3209. unlink $path or croak "unlink: $!";
  3210. }
  3211. sub rebuild {
  3212. my ($self) = @_;
  3213. my $map_path = $self->map_path;
  3214. my $partial = (-e $map_path && ! -z $map_path);
  3215. return unless ::verify_ref($self->refname.'^0');
  3216. if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
  3217. my $rev_db = $self->rev_db_path;
  3218. $self->rebuild_from_rev_db($rev_db);
  3219. if ($self->use_svm_props) {
  3220. my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
  3221. $self->rebuild_from_rev_db($svm_rev_db);
  3222. }
  3223. $self->unlink_rev_db_symlink;
  3224. return;
  3225. }
  3226. print "Rebuilding $map_path ...\n" if (!$partial);
  3227. my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
  3228. (undef, undef));
  3229. my ($log, $ctx) =
  3230. command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
  3231. ($head ? "$head.." : "") . $self->refname,
  3232. '--');
  3233. my $metadata_url = $self->metadata_url;
  3234. remove_username($metadata_url);
  3235. my $svn_uuid = $self->rewrite_uuid || $self->ra_uuid;
  3236. my $c;
  3237. while (<$log>) {
  3238. if ( m{^commit ($::sha1)$} ) {
  3239. $c = $1;
  3240. next;
  3241. }
  3242. next unless s{^\s*(git-svn-id:)}{$1};
  3243. my ($url, $rev, $uuid) = ::extract_metadata($_);
  3244. remove_username($url);
  3245. # ignore merges (from set-tree)
  3246. next if (!defined $rev || !$uuid);
  3247. # if we merged or otherwise started elsewhere, this is
  3248. # how we break out of it
  3249. if (($uuid ne $svn_uuid) ||
  3250. ($metadata_url && $url && ($url ne $metadata_url))) {
  3251. next;
  3252. }
  3253. if ($partial && $head) {
  3254. print "Partial-rebuilding $map_path ...\n";
  3255. print "Currently at $base_rev = $head\n";
  3256. $head = undef;
  3257. }
  3258. $self->rev_map_set($rev, $c);
  3259. print "r$rev = $c\n";
  3260. }
  3261. command_close_pipe($log, $ctx);
  3262. print "Done rebuilding $map_path\n" if (!$partial || !$head);
  3263. my $rev_db_path = $self->rev_db_path;
  3264. if (-f $self->rev_db_path) {
  3265. unlink $self->rev_db_path or croak "unlink: $!";
  3266. }
  3267. $self->unlink_rev_db_symlink;
  3268. }
  3269. # rev_map:
  3270. # Tie::File seems to be prone to offset errors if revisions get sparse,
  3271. # it's not that fast, either. Tie::File is also not in Perl 5.6. So
  3272. # one of my favorite modules is out :< Next up would be one of the DBM
  3273. # modules, but I'm not sure which is most portable...
  3274. #
  3275. # This is the replacement for the rev_db format, which was too big
  3276. # and inefficient for large repositories with a lot of sparse history
  3277. # (mainly tags)
  3278. #
  3279. # The format is this:
  3280. # - 24 bytes for every record,
  3281. # * 4 bytes for the integer representing an SVN revision number
  3282. # * 20 bytes representing the sha1 of a git commit
  3283. # - No empty padding records like the old format
  3284. # (except the last record, which can be overwritten)
  3285. # - new records are written append-only since SVN revision numbers
  3286. # increase monotonically
  3287. # - lookups on SVN revision number are done via a binary search
  3288. # - Piping the file to xxd -c24 is a good way of dumping it for
  3289. # viewing or editing (piped back through xxd -r), should the need
  3290. # ever arise.
  3291. # - The last record can be padding revision with an all-zero sha1
  3292. # This is used to optimize fetch performance when using multiple
  3293. # "fetch" directives in .git/config
  3294. #
  3295. # These files are disposable unless noMetadata or useSvmProps is set
  3296. sub _rev_map_set {
  3297. my ($fh, $rev, $commit) = @_;
  3298. binmode $fh or croak "binmode: $!";
  3299. my $size = (stat($fh))[7];
  3300. ($size % 24) == 0 or croak "inconsistent size: $size";
  3301. my $wr_offset = 0;
  3302. if ($size > 0) {
  3303. sysseek($fh, -24, SEEK_END) or croak "seek: $!";
  3304. my $read = sysread($fh, my $buf, 24) or croak "read: $!";
  3305. $read == 24 or croak "read only $read bytes (!= 24)";
  3306. my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
  3307. if ($last_commit eq ('0' x40)) {
  3308. if ($size >= 48) {
  3309. sysseek($fh, -48, SEEK_END) or croak "seek: $!";
  3310. $read = sysread($fh, $buf, 24) or
  3311. croak "read: $!";
  3312. $read == 24 or
  3313. croak "read only $read bytes (!= 24)";
  3314. ($last_rev, $last_commit) =
  3315. unpack(rev_map_fmt, $buf);
  3316. if ($last_commit eq ('0' x40)) {
  3317. croak "inconsistent .rev_map\n";
  3318. }
  3319. }
  3320. if ($last_rev >= $rev) {
  3321. croak "last_rev is higher!: $last_rev >= $rev";
  3322. }
  3323. $wr_offset = -24;
  3324. }
  3325. }
  3326. sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
  3327. syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
  3328. croak "write: $!";
  3329. }
  3330. sub _rev_map_reset {
  3331. my ($fh, $rev, $commit) = @_;
  3332. my $c = _rev_map_get($fh, $rev);
  3333. $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
  3334. my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
  3335. truncate $fh, $offset or croak "truncate: $!";
  3336. }
  3337. sub mkfile {
  3338. my ($path) = @_;
  3339. unless (-e $path) {
  3340. my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
  3341. mkpath([$dir]) unless -d $dir;
  3342. open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
  3343. close $fh or die "Couldn't close (create) $path: $!\n";
  3344. }
  3345. }
  3346. sub rev_map_set {
  3347. my ($self, $rev, $commit, $update_ref, $uuid) = @_;
  3348. defined $commit or die "missing arg3\n";
  3349. length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
  3350. my $db = $self->map_path($uuid);
  3351. my $db_lock = "$db.lock";
  3352. my $sig;
  3353. $update_ref ||= 0;
  3354. if ($update_ref) {
  3355. $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
  3356. $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
  3357. }
  3358. mkfile($db);
  3359. $LOCKFILES{$db_lock} = 1;
  3360. my $sync;
  3361. # both of these options make our .rev_db file very, very important
  3362. # and we can't afford to lose it because rebuild() won't work
  3363. if ($self->use_svm_props || $self->no_metadata) {
  3364. $sync = 1;
  3365. copy($db, $db_lock) or die "rev_map_set(@_): ",
  3366. "Failed to copy: ",
  3367. "$db => $db_lock ($!)\n";
  3368. } else {
  3369. rename $db, $db_lock or die "rev_map_set(@_): ",
  3370. "Failed to rename: ",
  3371. "$db => $db_lock ($!)\n";
  3372. }
  3373. sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
  3374. or croak "Couldn't open $db_lock: $!\n";
  3375. $update_ref eq 'reset' ? _rev_map_reset($fh, $rev, $commit) :
  3376. _rev_map_set($fh, $rev, $commit);
  3377. if ($sync) {
  3378. $fh->flush or die "Couldn't flush $db_lock: $!\n";
  3379. $fh->sync or die "Couldn't sync $db_lock: $!\n";
  3380. }
  3381. close $fh or croak $!;
  3382. if ($update_ref) {
  3383. $_head = $self;
  3384. my $note = "";
  3385. $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
  3386. command_noisy('update-ref', '-m', "r$rev$note",
  3387. $self->refname, $commit);
  3388. }
  3389. rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
  3390. "$db_lock => $db ($!)\n";
  3391. delete $LOCKFILES{$db_lock};
  3392. if ($update_ref) {
  3393. $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
  3394. $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
  3395. kill $sig, $$ if defined $sig;
  3396. }
  3397. }
  3398. # If want_commit, this will return an array of (rev, commit) where
  3399. # commit _must_ be a valid commit in the archive.
  3400. # Otherwise, it'll return the max revision (whether or not the
  3401. # commit is valid or just a 0x40 placeholder).
  3402. sub rev_map_max {
  3403. my ($self, $want_commit) = @_;
  3404. $self->rebuild;
  3405. my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
  3406. $want_commit ? ($r, $c) : $r;
  3407. }
  3408. sub rev_map_max_norebuild {
  3409. my ($self, $want_commit) = @_;
  3410. my $map_path = $self->map_path;
  3411. stat $map_path or return $want_commit ? (0, undef) : 0;
  3412. sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
  3413. binmode $fh or croak "binmode: $!";
  3414. my $size = (stat($fh))[7];
  3415. ($size % 24) == 0 or croak "inconsistent size: $size";
  3416. if ($size == 0) {
  3417. close $fh or croak "close: $!";
  3418. return $want_commit ? (0, undef) : 0;
  3419. }
  3420. sysseek($fh, -24, SEEK_END) or croak "seek: $!";
  3421. sysread($fh, my $buf, 24) == 24 or croak "read: $!";
  3422. my ($r, $c) = unpack(rev_map_fmt, $buf);
  3423. if ($want_commit && $c eq ('0' x40)) {
  3424. if ($size < 48) {
  3425. return $want_commit ? (0, undef) : 0;
  3426. }
  3427. sysseek($fh, -48, SEEK_END) or croak "seek: $!";
  3428. sysread($fh, $buf, 24) == 24 or croak "read: $!";
  3429. ($r, $c) = unpack(rev_map_fmt, $buf);
  3430. if ($c eq ('0'x40)) {
  3431. croak "Penultimate record is all-zeroes in $map_path";
  3432. }
  3433. }
  3434. close $fh or croak "close: $!";
  3435. $want_commit ? ($r, $c) : $r;
  3436. }
  3437. sub rev_map_get {
  3438. my ($self, $rev, $uuid) = @_;
  3439. my $map_path = $self->map_path($uuid);
  3440. return undef unless -e $map_path;
  3441. sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
  3442. my $c = _rev_map_get($fh, $rev);
  3443. close($fh) or croak "close: $!";
  3444. $c
  3445. }
  3446. sub _rev_map_get {
  3447. my ($fh, $rev) = @_;
  3448. binmode $fh or croak "binmode: $!";
  3449. my $size = (stat($fh))[7];
  3450. ($size % 24) == 0 or croak "inconsistent size: $size";
  3451. if ($size == 0) {
  3452. return undef;
  3453. }
  3454. my ($l, $u) = (0, $size - 24);
  3455. my ($r, $c, $buf);
  3456. while ($l <= $u) {
  3457. my $i = int(($l/24 + $u/24) / 2) * 24;
  3458. sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
  3459. sysread($fh, my $buf, 24) == 24 or croak "read: $!";
  3460. my ($r, $c) = unpack(rev_map_fmt, $buf);
  3461. if ($r < $rev) {
  3462. $l = $i + 24;
  3463. } elsif ($r > $rev) {
  3464. $u = $i - 24;
  3465. } else { # $r == $rev
  3466. return $c eq ('0' x 40) ? undef : $c;
  3467. }
  3468. }
  3469. undef;
  3470. }
  3471. # Finds the first svn revision that exists on (if $eq_ok is true) or
  3472. # before $rev for the current branch. It will not search any lower
  3473. # than $min_rev. Returns the git commit hash and svn revision number
  3474. # if found, else (undef, undef).
  3475. sub find_rev_before {
  3476. my ($self, $rev, $eq_ok, $min_rev) = @_;
  3477. --$rev unless $eq_ok;
  3478. $min_rev ||= 1;
  3479. my $max_rev = $self->rev_map_max;
  3480. $rev = $max_rev if ($rev > $max_rev);
  3481. while ($rev >= $min_rev) {
  3482. if (my $c = $self->rev_map_get($rev)) {
  3483. return ($rev, $c);
  3484. }
  3485. --$rev;
  3486. }
  3487. return (undef, undef);
  3488. }
  3489. # Finds the first svn revision that exists on (if $eq_ok is true) or
  3490. # after $rev for the current branch. It will not search any higher
  3491. # than $max_rev. Returns the git commit hash and svn revision number
  3492. # if found, else (undef, undef).
  3493. sub find_rev_after {
  3494. my ($self, $rev, $eq_ok, $max_rev) = @_;
  3495. ++$rev unless $eq_ok;
  3496. $max_rev ||= $self->rev_map_max;
  3497. while ($rev <= $max_rev) {
  3498. if (my $c = $self->rev_map_get($rev)) {
  3499. return ($rev, $c);
  3500. }
  3501. ++$rev;
  3502. }
  3503. return (undef, undef);
  3504. }
  3505. sub _new {
  3506. my ($class, $repo_id, $ref_id, $path) = @_;
  3507. unless (defined $repo_id && length $repo_id) {
  3508. $repo_id = $Git::SVN::default_repo_id;
  3509. }
  3510. unless (defined $ref_id && length $ref_id) {
  3511. $_prefix = '' unless defined($_prefix);
  3512. $_[2] = $ref_id =
  3513. "refs/remotes/$_prefix$Git::SVN::default_ref_id";
  3514. }
  3515. $_[1] = $repo_id;
  3516. my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
  3517. # Older repos imported by us used $GIT_DIR/svn/foo instead of
  3518. # $GIT_DIR/svn/refs/remotes/foo when tracking refs/remotes/foo
  3519. if ($ref_id =~ m{^refs/remotes/(.*)}) {
  3520. my $old_dir = "$ENV{GIT_DIR}/svn/$1";
  3521. if (-d $old_dir && ! -d $dir) {
  3522. $dir = $old_dir;
  3523. }
  3524. }
  3525. $_[3] = $path = '' unless (defined $path);
  3526. mkpath([$dir]);
  3527. bless {
  3528. ref_id => $ref_id, dir => $dir, index => "$dir/index",
  3529. path => $path, config => "$ENV{GIT_DIR}/svn/config",
  3530. map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
  3531. }
  3532. # for read-only access of old .rev_db formats
  3533. sub unlink_rev_db_symlink {
  3534. my ($self) = @_;
  3535. my $link = $self->rev_db_path;
  3536. $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
  3537. if (-l $link) {
  3538. unlink $link or croak "unlink: $link failed!";
  3539. }
  3540. }
  3541. sub rev_db_path {
  3542. my ($self, $uuid) = @_;
  3543. my $db_path = $self->map_path($uuid);
  3544. $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
  3545. or croak "map_path: $db_path does not contain '/.rev_map.' !";
  3546. $db_path;
  3547. }
  3548. # the new replacement for .rev_db
  3549. sub map_path {
  3550. my ($self, $uuid) = @_;
  3551. $uuid ||= $self->ra_uuid;
  3552. "$self->{map_root}.$uuid";
  3553. }
  3554. sub uri_encode {
  3555. my ($f) = @_;
  3556. $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
  3557. $f
  3558. }
  3559. sub uri_decode {
  3560. my ($f) = @_;
  3561. $f =~ s#%([0-9a-fA-F]{2})#chr(hex($1))#eg;
  3562. $f
  3563. }
  3564. sub remove_username {
  3565. $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
  3566. }
  3567. package Git::SVN::Prompt;
  3568. use strict;
  3569. use warnings;
  3570. require SVN::Core;
  3571. use vars qw/$_no_auth_cache $_username/;
  3572. sub simple {
  3573. my ($cred, $realm, $default_username, $may_save, $pool) = @_;
  3574. $may_save = undef if $_no_auth_cache;
  3575. $default_username = $_username if defined $_username;
  3576. if (defined $default_username && length $default_username) {
  3577. if (defined $realm && length $realm) {
  3578. print STDERR "Authentication realm: $realm\n";
  3579. STDERR->flush;
  3580. }
  3581. $cred->username($default_username);
  3582. } else {
  3583. username($cred, $realm, $may_save, $pool);
  3584. }
  3585. $cred->password(_read_password("Password for '" .
  3586. $cred->username . "': ", $realm));
  3587. $cred->may_save($may_save);
  3588. $SVN::_Core::SVN_NO_ERROR;
  3589. }
  3590. sub ssl_server_trust {
  3591. my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
  3592. $may_save = undef if $_no_auth_cache;
  3593. print STDERR "Error validating server certificate for '$realm':\n";
  3594. {
  3595. no warnings 'once';
  3596. # All variables SVN::Auth::SSL::* are used only once,
  3597. # so we're shutting up Perl warnings about this.
  3598. if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
  3599. print STDERR " - The certificate is not issued ",
  3600. "by a trusted authority. Use the\n",
  3601. " fingerprint to validate ",
  3602. "the certificate manually!\n";
  3603. }
  3604. if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
  3605. print STDERR " - The certificate hostname ",
  3606. "does not match.\n";
  3607. }
  3608. if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
  3609. print STDERR " - The certificate is not yet valid.\n";
  3610. }
  3611. if ($failures & $SVN::Auth::SSL::EXPIRED) {
  3612. print STDERR " - The certificate has expired.\n";
  3613. }
  3614. if ($failures & $SVN::Auth::SSL::OTHER) {
  3615. print STDERR " - The certificate has ",
  3616. "an unknown error.\n";
  3617. }
  3618. } # no warnings 'once'
  3619. printf STDERR
  3620. "Certificate information:\n".
  3621. " - Hostname: %s\n".
  3622. " - Valid: from %s until %s\n".
  3623. " - Issuer: %s\n".
  3624. " - Fingerprint: %s\n",
  3625. map $cert_info->$_, qw(hostname valid_from valid_until
  3626. issuer_dname fingerprint);
  3627. my $choice;
  3628. prompt:
  3629. print STDERR $may_save ?
  3630. "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
  3631. "(R)eject or accept (t)emporarily? ";
  3632. STDERR->flush;
  3633. $choice = lc(substr(<STDIN> || 'R', 0, 1));
  3634. if ($choice =~ /^t$/i) {
  3635. $cred->may_save(undef);
  3636. } elsif ($choice =~ /^r$/i) {
  3637. return -1;
  3638. } elsif ($may_save && $choice =~ /^p$/i) {
  3639. $cred->may_save($may_save);
  3640. } else {
  3641. goto prompt;
  3642. }
  3643. $cred->accepted_failures($failures);
  3644. $SVN::_Core::SVN_NO_ERROR;
  3645. }
  3646. sub ssl_client_cert {
  3647. my ($cred, $realm, $may_save, $pool) = @_;
  3648. $may_save = undef if $_no_auth_cache;
  3649. print STDERR "Client certificate filename: ";
  3650. STDERR->flush;
  3651. chomp(my $filename = <STDIN>);
  3652. $cred->cert_file($filename);
  3653. $cred->may_save($may_save);
  3654. $SVN::_Core::SVN_NO_ERROR;
  3655. }
  3656. sub ssl_client_cert_pw {
  3657. my ($cred, $realm, $may_save, $pool) = @_;
  3658. $may_save = undef if $_no_auth_cache;
  3659. $cred->password(_read_password("Password: ", $realm));
  3660. $cred->may_save($may_save);
  3661. $SVN::_Core::SVN_NO_ERROR;
  3662. }
  3663. sub username {
  3664. my ($cred, $realm, $may_save, $pool) = @_;
  3665. $may_save = undef if $_no_auth_cache;
  3666. if (defined $realm && length $realm) {
  3667. print STDERR "Authentication realm: $realm\n";
  3668. }
  3669. my $username;
  3670. if (defined $_username) {
  3671. $username = $_username;
  3672. } else {
  3673. print STDERR "Username: ";
  3674. STDERR->flush;
  3675. chomp($username = <STDIN>);
  3676. }
  3677. $cred->username($username);
  3678. $cred->may_save($may_save);
  3679. $SVN::_Core::SVN_NO_ERROR;
  3680. }
  3681. sub _read_password {
  3682. my ($prompt, $realm) = @_;
  3683. my $password = '';
  3684. if (exists $ENV{GIT_ASKPASS}) {
  3685. open(PH, "-|", $ENV{GIT_ASKPASS}, $prompt);
  3686. $password = <PH>;
  3687. $password =~ s/[\012\015]//; # \n\r
  3688. close(PH);
  3689. } else {
  3690. print STDERR $prompt;
  3691. STDERR->flush;
  3692. require Term::ReadKey;
  3693. Term::ReadKey::ReadMode('noecho');
  3694. while (defined(my $key = Term::ReadKey::ReadKey(0))) {
  3695. last if $key =~ /[\012\015]/; # \n\r
  3696. $password .= $key;
  3697. }
  3698. Term::ReadKey::ReadMode('restore');
  3699. print STDERR "\n";
  3700. STDERR->flush;
  3701. }
  3702. $password;
  3703. }
  3704. package SVN::Git::Fetcher;
  3705. use vars qw/@ISA/;
  3706. use strict;
  3707. use warnings;
  3708. use Carp qw/croak/;
  3709. use IO::File qw//;
  3710. use vars qw/$_ignore_regex/;
  3711. # file baton members: path, mode_a, mode_b, pool, fh, blob, base
  3712. sub new {
  3713. my ($class, $git_svn, $switch_path) = @_;
  3714. my $self = SVN::Delta::Editor->new;
  3715. bless $self, $class;
  3716. if (exists $git_svn->{last_commit}) {
  3717. $self->{c} = $git_svn->{last_commit};
  3718. $self->{empty_symlinks} =
  3719. _mark_empty_symlinks($git_svn, $switch_path);
  3720. }
  3721. $self->{ignore_regex} = eval { command_oneline('config', '--get',
  3722. "svn-remote.$git_svn->{repo_id}.ignore-paths") };
  3723. $self->{empty} = {};
  3724. $self->{dir_prop} = {};
  3725. $self->{file_prop} = {};
  3726. $self->{absent_dir} = {};
  3727. $self->{absent_file} = {};
  3728. $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
  3729. $self->{pathnameencoding} = Git::config('svn.pathnameencoding');
  3730. $self;
  3731. }
  3732. # this uses the Ra object, so it must be called before do_{switch,update},
  3733. # not inside them (when the Git::SVN::Fetcher object is passed) to
  3734. # do_{switch,update}
  3735. sub _mark_empty_symlinks {
  3736. my ($git_svn, $switch_path) = @_;
  3737. my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
  3738. return {} if (!defined($bool)) || (defined($bool) && ! $bool);
  3739. my %ret;
  3740. my ($rev, $cmt) = $git_svn->last_rev_commit;
  3741. return {} unless ($rev && $cmt);
  3742. # allow the warning to be printed for each revision we fetch to
  3743. # ensure the user sees it. The user can also disable the workaround
  3744. # on the repository even while git svn is running and the next
  3745. # revision fetched will skip this expensive function.
  3746. my $printed_warning;
  3747. chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
  3748. my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
  3749. local $/ = "\0";
  3750. my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
  3751. $pfx .= '/' if length($pfx);
  3752. while (<$ls>) {
  3753. chomp;
  3754. s/\A100644 blob $empty_blob\t//o or next;
  3755. unless ($printed_warning) {
  3756. print STDERR "Scanning for empty symlinks, ",
  3757. "this may take a while if you have ",
  3758. "many empty files\n",
  3759. "You may disable this with `",
  3760. "git config svn.brokenSymlinkWorkaround ",
  3761. "false'.\n",
  3762. "This may be done in a different ",
  3763. "terminal without restarting ",
  3764. "git svn\n";
  3765. $printed_warning = 1;
  3766. }
  3767. my $path = $_;
  3768. my (undef, $props) =
  3769. $git_svn->ra->get_file($pfx.$path, $rev, undef);
  3770. if ($props->{'svn:special'}) {
  3771. $ret{$path} = 1;
  3772. }
  3773. }
  3774. command_close_pipe($ls, $ctx);
  3775. \%ret;
  3776. }
  3777. # returns true if a given path is inside a ".git" directory
  3778. sub in_dot_git {
  3779. $_[0] =~ m{(?:^|/)\.git(?:/|$)};
  3780. }
  3781. # return value: 0 -- don't ignore, 1 -- ignore
  3782. sub is_path_ignored {
  3783. my ($self, $path) = @_;
  3784. return 1 if in_dot_git($path);
  3785. return 1 if defined($self->{ignore_regex}) &&
  3786. $path =~ m!$self->{ignore_regex}!;
  3787. return 0 unless defined($_ignore_regex);
  3788. return 1 if $path =~ m!$_ignore_regex!o;
  3789. return 0;
  3790. }
  3791. sub set_path_strip {
  3792. my ($self, $path) = @_;
  3793. $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
  3794. }
  3795. sub open_root {
  3796. { path => '' };
  3797. }
  3798. sub open_directory {
  3799. my ($self, $path, $pb, $rev) = @_;
  3800. { path => $path };
  3801. }
  3802. sub git_path {
  3803. my ($self, $path) = @_;
  3804. if (my $enc = $self->{pathnameencoding}) {
  3805. require Encode;
  3806. Encode::from_to($path, 'UTF-8', $enc);
  3807. }
  3808. if ($self->{path_strip}) {
  3809. $path =~ s!$self->{path_strip}!! or
  3810. die "Failed to strip path '$path' ($self->{path_strip})\n";
  3811. }
  3812. $path;
  3813. }
  3814. sub delete_entry {
  3815. my ($self, $path, $rev, $pb) = @_;
  3816. return undef if $self->is_path_ignored($path);
  3817. my $gpath = $self->git_path($path);
  3818. return undef if ($gpath eq '');
  3819. # remove entire directories.
  3820. my ($tree) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
  3821. =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
  3822. if ($tree) {
  3823. my ($ls, $ctx) = command_output_pipe(qw/ls-tree
  3824. -r --name-only -z/,
  3825. $tree);
  3826. local $/ = "\0";
  3827. while (<$ls>) {
  3828. chomp;
  3829. my $rmpath = "$gpath/$_";
  3830. $self->{gii}->remove($rmpath);
  3831. print "\tD\t$rmpath\n" unless $::_q;
  3832. }
  3833. print "\tD\t$gpath/\n" unless $::_q;
  3834. command_close_pipe($ls, $ctx);
  3835. } else {
  3836. $self->{gii}->remove($gpath);
  3837. print "\tD\t$gpath\n" unless $::_q;
  3838. }
  3839. $self->{empty}->{$path} = 0;
  3840. undef;
  3841. }
  3842. sub open_file {
  3843. my ($self, $path, $pb, $rev) = @_;
  3844. my ($mode, $blob);
  3845. goto out if $self->is_path_ignored($path);
  3846. my $gpath = $self->git_path($path);
  3847. ($mode, $blob) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
  3848. =~ /\A(\d{6}) blob ([a-f\d]{40})\t\Q$gpath\E\0/);
  3849. unless (defined $mode && defined $blob) {
  3850. die "$path was not found in commit $self->{c} (r$rev)\n";
  3851. }
  3852. if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
  3853. $mode = '120000';
  3854. }
  3855. out:
  3856. { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
  3857. pool => SVN::Pool->new, action => 'M' };
  3858. }
  3859. sub add_file {
  3860. my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
  3861. my $mode;
  3862. if (!$self->is_path_ignored($path)) {
  3863. my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
  3864. delete $self->{empty}->{$dir};
  3865. $mode = '100644';
  3866. }
  3867. { path => $path, mode_a => $mode, mode_b => $mode,
  3868. pool => SVN::Pool->new, action => 'A' };
  3869. }
  3870. sub add_directory {
  3871. my ($self, $path, $cp_path, $cp_rev) = @_;
  3872. goto out if $self->is_path_ignored($path);
  3873. my $gpath = $self->git_path($path);
  3874. if ($gpath eq '') {
  3875. my ($ls, $ctx) = command_output_pipe(qw/ls-tree
  3876. -r --name-only -z/,
  3877. $self->{c});
  3878. local $/ = "\0";
  3879. while (<$ls>) {
  3880. chomp;
  3881. $self->{gii}->remove($_);
  3882. print "\tD\t$_\n" unless $::_q;
  3883. }
  3884. command_close_pipe($ls, $ctx);
  3885. $self->{empty}->{$path} = 0;
  3886. }
  3887. my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
  3888. delete $self->{empty}->{$dir};
  3889. $self->{empty}->{$path} = 1;
  3890. out:
  3891. { path => $path };
  3892. }
  3893. sub change_dir_prop {
  3894. my ($self, $db, $prop, $value) = @_;
  3895. return undef if $self->is_path_ignored($db->{path});
  3896. $self->{dir_prop}->{$db->{path}} ||= {};
  3897. $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
  3898. undef;
  3899. }
  3900. sub absent_directory {
  3901. my ($self, $path, $pb) = @_;
  3902. return undef if $self->is_path_ignored($path);
  3903. $self->{absent_dir}->{$pb->{path}} ||= [];
  3904. push @{$self->{absent_dir}->{$pb->{path}}}, $path;
  3905. undef;
  3906. }
  3907. sub absent_file {
  3908. my ($self, $path, $pb) = @_;
  3909. return undef if $self->is_path_ignored($path);
  3910. $self->{absent_file}->{$pb->{path}} ||= [];
  3911. push @{$self->{absent_file}->{$pb->{path}}}, $path;
  3912. undef;
  3913. }
  3914. sub change_file_prop {
  3915. my ($self, $fb, $prop, $value) = @_;
  3916. return undef if $self->is_path_ignored($fb->{path});
  3917. if ($prop eq 'svn:executable') {
  3918. if ($fb->{mode_b} != 120000) {
  3919. $fb->{mode_b} = defined $value ? 100755 : 100644;
  3920. }
  3921. } elsif ($prop eq 'svn:special') {
  3922. $fb->{mode_b} = defined $value ? 120000 : 100644;
  3923. } else {
  3924. $self->{file_prop}->{$fb->{path}} ||= {};
  3925. $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
  3926. }
  3927. undef;
  3928. }
  3929. sub apply_textdelta {
  3930. my ($self, $fb, $exp) = @_;
  3931. return undef if $self->is_path_ignored($fb->{path});
  3932. my $fh = $::_repository->temp_acquire('svn_delta');
  3933. # $fh gets auto-closed() by SVN::TxDelta::apply(),
  3934. # (but $base does not,) so dup() it for reading in close_file
  3935. open my $dup, '<&', $fh or croak $!;
  3936. my $base = $::_repository->temp_acquire('git_blob');
  3937. if ($fb->{blob}) {
  3938. my ($base_is_link, $size);
  3939. if ($fb->{mode_a} eq '120000' &&
  3940. ! $self->{empty_symlinks}->{$fb->{path}}) {
  3941. print $base 'link ' or die "print $!\n";
  3942. $base_is_link = 1;
  3943. }
  3944. retry:
  3945. $size = $::_repository->cat_blob($fb->{blob}, $base);
  3946. die "Failed to read object $fb->{blob}" if ($size < 0);
  3947. if (defined $exp) {
  3948. seek $base, 0, 0 or croak $!;
  3949. my $got = ::md5sum($base);
  3950. if ($got ne $exp) {
  3951. my $err = "Checksum mismatch: ".
  3952. "$fb->{path} $fb->{blob}\n" .
  3953. "expected: $exp\n" .
  3954. " got: $got\n";
  3955. if ($base_is_link) {
  3956. warn $err,
  3957. "Retrying... (possibly ",
  3958. "a bad symlink from SVN)\n";
  3959. $::_repository->temp_reset($base);
  3960. $base_is_link = 0;
  3961. goto retry;
  3962. }
  3963. die $err;
  3964. }
  3965. }
  3966. }
  3967. seek $base, 0, 0 or croak $!;
  3968. $fb->{fh} = $fh;
  3969. $fb->{base} = $base;
  3970. [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
  3971. }
  3972. sub close_file {
  3973. my ($self, $fb, $exp) = @_;
  3974. return undef if $self->is_path_ignored($fb->{path});
  3975. my $hash;
  3976. my $path = $self->git_path($fb->{path});
  3977. if (my $fh = $fb->{fh}) {
  3978. if (defined $exp) {
  3979. seek($fh, 0, 0) or croak $!;
  3980. my $got = ::md5sum($fh);
  3981. if ($got ne $exp) {
  3982. die "Checksum mismatch: $path\n",
  3983. "expected: $exp\n got: $got\n";
  3984. }
  3985. }
  3986. if ($fb->{mode_b} == 120000) {
  3987. sysseek($fh, 0, 0) or croak $!;
  3988. my $rd = sysread($fh, my $buf, 5);
  3989. if (!defined $rd) {
  3990. croak "sysread: $!\n";
  3991. } elsif ($rd == 0) {
  3992. warn "$path has mode 120000",
  3993. " but it points to nothing\n",
  3994. "converting to an empty file with mode",
  3995. " 100644\n";
  3996. $fb->{mode_b} = '100644';
  3997. } elsif ($buf ne 'link ') {
  3998. warn "$path has mode 120000",
  3999. " but is not a link\n";
  4000. } else {
  4001. my $tmp_fh = $::_repository->temp_acquire(
  4002. 'svn_hash');
  4003. my $res;
  4004. while ($res = sysread($fh, my $str, 1024)) {
  4005. my $out = syswrite($tmp_fh, $str, $res);
  4006. defined($out) && $out == $res
  4007. or croak("write ",
  4008. Git::temp_path($tmp_fh),
  4009. ": $!\n");
  4010. }
  4011. defined $res or croak $!;
  4012. ($fh, $tmp_fh) = ($tmp_fh, $fh);
  4013. Git::temp_release($tmp_fh, 1);
  4014. }
  4015. }
  4016. $hash = $::_repository->hash_and_insert_object(
  4017. Git::temp_path($fh));
  4018. $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
  4019. Git::temp_release($fb->{base}, 1);
  4020. Git::temp_release($fh, 1);
  4021. } else {
  4022. $hash = $fb->{blob} or die "no blob information\n";
  4023. }
  4024. $fb->{pool}->clear;
  4025. $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
  4026. print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
  4027. undef;
  4028. }
  4029. sub abort_edit {
  4030. my $self = shift;
  4031. $self->{nr} = $self->{gii}->{nr};
  4032. delete $self->{gii};
  4033. $self->SUPER::abort_edit(@_);
  4034. }
  4035. sub close_edit {
  4036. my $self = shift;
  4037. $self->{git_commit_ok} = 1;
  4038. $self->{nr} = $self->{gii}->{nr};
  4039. delete $self->{gii};
  4040. $self->SUPER::close_edit(@_);
  4041. }
  4042. package SVN::Git::Editor;
  4043. use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
  4044. use strict;
  4045. use warnings;
  4046. use Carp qw/croak/;
  4047. use IO::File;
  4048. sub new {
  4049. my ($class, $opts) = @_;
  4050. foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
  4051. die "$_ required!\n" unless (defined $opts->{$_});
  4052. }
  4053. my $pool = SVN::Pool->new;
  4054. my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
  4055. my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
  4056. $opts->{r}, $mods);
  4057. # $opts->{ra} functions should not be used after this:
  4058. my @ce = $opts->{ra}->get_commit_editor($opts->{log},
  4059. $opts->{editor_cb}, $pool);
  4060. my $self = SVN::Delta::Editor->new(@ce, $pool);
  4061. bless $self, $class;
  4062. foreach (qw/svn_path r tree_a tree_b/) {
  4063. $self->{$_} = $opts->{$_};
  4064. }
  4065. $self->{url} = $opts->{ra}->{url};
  4066. $self->{mods} = $mods;
  4067. $self->{types} = $types;
  4068. $self->{pool} = $pool;
  4069. $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
  4070. $self->{rm} = { };
  4071. $self->{path_prefix} = length $self->{svn_path} ?
  4072. "$self->{svn_path}/" : '';
  4073. $self->{config} = $opts->{config};
  4074. return $self;
  4075. }
  4076. sub generate_diff {
  4077. my ($tree_a, $tree_b) = @_;
  4078. my @diff_tree = qw(diff-tree -z -r);
  4079. if ($_cp_similarity) {
  4080. push @diff_tree, "-C$_cp_similarity";
  4081. } else {
  4082. push @diff_tree, '-C';
  4083. }
  4084. push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
  4085. push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
  4086. push @diff_tree, $tree_a, $tree_b;
  4087. my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
  4088. local $/ = "\0";
  4089. my $state = 'meta';
  4090. my @mods;
  4091. while (<$diff_fh>) {
  4092. chomp $_; # this gets rid of the trailing "\0"
  4093. if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
  4094. ($::sha1)\s($::sha1)\s
  4095. ([MTCRAD])\d*$/xo) {
  4096. push @mods, { mode_a => $1, mode_b => $2,
  4097. sha1_a => $3, sha1_b => $4,
  4098. chg => $5 };
  4099. if ($5 =~ /^(?:C|R)$/) {
  4100. $state = 'file_a';
  4101. } else {
  4102. $state = 'file_b';
  4103. }
  4104. } elsif ($state eq 'file_a') {
  4105. my $x = $mods[$#mods] or croak "Empty array\n";
  4106. if ($x->{chg} !~ /^(?:C|R)$/) {
  4107. croak "Error parsing $_, $x->{chg}\n";
  4108. }
  4109. $x->{file_a} = $_;
  4110. $state = 'file_b';
  4111. } elsif ($state eq 'file_b') {
  4112. my $x = $mods[$#mods] or croak "Empty array\n";
  4113. if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
  4114. croak "Error parsing $_, $x->{chg}\n";
  4115. }
  4116. if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
  4117. croak "Error parsing $_, $x->{chg}\n";
  4118. }
  4119. $x->{file_b} = $_;
  4120. $state = 'meta';
  4121. } else {
  4122. croak "Error parsing $_\n";
  4123. }
  4124. }
  4125. command_close_pipe($diff_fh, $ctx);
  4126. \@mods;
  4127. }
  4128. sub check_diff_paths {
  4129. my ($ra, $pfx, $rev, $mods) = @_;
  4130. my %types;
  4131. $pfx .= '/' if length $pfx;
  4132. sub type_diff_paths {
  4133. my ($ra, $types, $path, $rev) = @_;
  4134. my @p = split m#/+#, $path;
  4135. my $c = shift @p;
  4136. unless (defined $types->{$c}) {
  4137. $types->{$c} = $ra->check_path($c, $rev);
  4138. }
  4139. while (@p) {
  4140. $c .= '/' . shift @p;
  4141. next if defined $types->{$c};
  4142. $types->{$c} = $ra->check_path($c, $rev);
  4143. }
  4144. }
  4145. foreach my $m (@$mods) {
  4146. foreach my $f (qw/file_a file_b/) {
  4147. next unless defined $m->{$f};
  4148. my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
  4149. if (length $pfx.$dir && ! defined $types{$dir}) {
  4150. type_diff_paths($ra, \%types, $pfx.$dir, $rev);
  4151. }
  4152. }
  4153. }
  4154. \%types;
  4155. }
  4156. sub split_path {
  4157. return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
  4158. }
  4159. sub repo_path {
  4160. my ($self, $path) = @_;
  4161. if (my $enc = $self->{pathnameencoding}) {
  4162. require Encode;
  4163. Encode::from_to($path, $enc, 'UTF-8');
  4164. }
  4165. $self->{path_prefix}.(defined $path ? $path : '');
  4166. }
  4167. sub url_path {
  4168. my ($self, $path) = @_;
  4169. if ($self->{url} =~ m#^https?://#) {
  4170. $path =~ s!([^~a-zA-Z0-9_./-])!uc sprintf("%%%02x",ord($1))!eg;
  4171. }
  4172. $self->{url} . '/' . $self->repo_path($path);
  4173. }
  4174. sub rmdirs {
  4175. my ($self) = @_;
  4176. my $rm = $self->{rm};
  4177. delete $rm->{''}; # we never delete the url we're tracking
  4178. return unless %$rm;
  4179. foreach (keys %$rm) {
  4180. my @d = split m#/#, $_;
  4181. my $c = shift @d;
  4182. $rm->{$c} = 1;
  4183. while (@d) {
  4184. $c .= '/' . shift @d;
  4185. $rm->{$c} = 1;
  4186. }
  4187. }
  4188. delete $rm->{$self->{svn_path}};
  4189. delete $rm->{''}; # we never delete the url we're tracking
  4190. return unless %$rm;
  4191. my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
  4192. $self->{tree_b});
  4193. local $/ = "\0";
  4194. while (<$fh>) {
  4195. chomp;
  4196. my @dn = split m#/#, $_;
  4197. while (pop @dn) {
  4198. delete $rm->{join '/', @dn};
  4199. }
  4200. unless (%$rm) {
  4201. close $fh;
  4202. return;
  4203. }
  4204. }
  4205. command_close_pipe($fh, $ctx);
  4206. my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
  4207. foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
  4208. $self->close_directory($bat->{$d}, $p);
  4209. my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
  4210. print "\tD+\t$d/\n" unless $::_q;
  4211. $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
  4212. delete $bat->{$d};
  4213. }
  4214. }
  4215. sub open_or_add_dir {
  4216. my ($self, $full_path, $baton) = @_;
  4217. my $t = $self->{types}->{$full_path};
  4218. if (!defined $t) {
  4219. die "$full_path not known in r$self->{r} or we have a bug!\n";
  4220. }
  4221. {
  4222. no warnings 'once';
  4223. # SVN::Node::none and SVN::Node::file are used only once,
  4224. # so we're shutting up Perl's warnings about them.
  4225. if ($t == $SVN::Node::none) {
  4226. return $self->add_directory($full_path, $baton,
  4227. undef, -1, $self->{pool});
  4228. } elsif ($t == $SVN::Node::dir) {
  4229. return $self->open_directory($full_path, $baton,
  4230. $self->{r}, $self->{pool});
  4231. } # no warnings 'once'
  4232. print STDERR "$full_path already exists in repository at ",
  4233. "r$self->{r} and it is not a directory (",
  4234. ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
  4235. } # no warnings 'once'
  4236. exit 1;
  4237. }
  4238. sub ensure_path {
  4239. my ($self, $path) = @_;
  4240. my $bat = $self->{bat};
  4241. my $repo_path = $self->repo_path($path);
  4242. return $bat->{''} unless (length $repo_path);
  4243. my @p = split m#/+#, $repo_path;
  4244. my $c = shift @p;
  4245. $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
  4246. while (@p) {
  4247. my $c0 = $c;
  4248. $c .= '/' . shift @p;
  4249. $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
  4250. }
  4251. return $bat->{$c};
  4252. }
  4253. # Subroutine to convert a globbing pattern to a regular expression.
  4254. # From perl cookbook.
  4255. sub glob2pat {
  4256. my $globstr = shift;
  4257. my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
  4258. $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
  4259. return '^' . $globstr . '$';
  4260. }
  4261. sub check_autoprop {
  4262. my ($self, $pattern, $properties, $file, $fbat) = @_;
  4263. # Convert the globbing pattern to a regular expression.
  4264. my $regex = glob2pat($pattern);
  4265. # Check if the pattern matches the file name.
  4266. if($file =~ m/($regex)/) {
  4267. # Parse the list of properties to set.
  4268. my @props = split(/;/, $properties);
  4269. foreach my $prop (@props) {
  4270. # Parse 'name=value' syntax and set the property.
  4271. if ($prop =~ /([^=]+)=(.*)/) {
  4272. my ($n,$v) = ($1,$2);
  4273. for ($n, $v) {
  4274. s/^\s+//; s/\s+$//;
  4275. }
  4276. $self->change_file_prop($fbat, $n, $v);
  4277. }
  4278. }
  4279. }
  4280. }
  4281. sub apply_autoprops {
  4282. my ($self, $file, $fbat) = @_;
  4283. my $conf_t = ${$self->{config}}{'config'};
  4284. no warnings 'once';
  4285. # Check [miscellany]/enable-auto-props in svn configuration.
  4286. if (SVN::_Core::svn_config_get_bool(
  4287. $conf_t,
  4288. $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
  4289. $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
  4290. 0)) {
  4291. # Auto-props are enabled. Enumerate them to look for matches.
  4292. my $callback = sub {
  4293. $self->check_autoprop($_[0], $_[1], $file, $fbat);
  4294. };
  4295. SVN::_Core::svn_config_enumerate(
  4296. $conf_t,
  4297. $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
  4298. $callback);
  4299. }
  4300. }
  4301. sub A {
  4302. my ($self, $m) = @_;
  4303. my ($dir, $file) = split_path($m->{file_b});
  4304. my $pbat = $self->ensure_path($dir);
  4305. my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
  4306. undef, -1);
  4307. print "\tA\t$m->{file_b}\n" unless $::_q;
  4308. $self->apply_autoprops($file, $fbat);
  4309. $self->chg_file($fbat, $m);
  4310. $self->close_file($fbat,undef,$self->{pool});
  4311. }
  4312. sub C {
  4313. my ($self, $m) = @_;
  4314. my ($dir, $file) = split_path($m->{file_b});
  4315. my $pbat = $self->ensure_path($dir);
  4316. my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
  4317. $self->url_path($m->{file_a}), $self->{r});
  4318. print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
  4319. $self->chg_file($fbat, $m);
  4320. $self->close_file($fbat,undef,$self->{pool});
  4321. }
  4322. sub delete_entry {
  4323. my ($self, $path, $pbat) = @_;
  4324. my $rpath = $self->repo_path($path);
  4325. my ($dir, $file) = split_path($rpath);
  4326. $self->{rm}->{$dir} = 1;
  4327. $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
  4328. }
  4329. sub R {
  4330. my ($self, $m) = @_;
  4331. my ($dir, $file) = split_path($m->{file_b});
  4332. my $pbat = $self->ensure_path($dir);
  4333. my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
  4334. $self->url_path($m->{file_a}), $self->{r});
  4335. print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
  4336. $self->apply_autoprops($file, $fbat);
  4337. $self->chg_file($fbat, $m);
  4338. $self->close_file($fbat,undef,$self->{pool});
  4339. ($dir, $file) = split_path($m->{file_a});
  4340. $pbat = $self->ensure_path($dir);
  4341. $self->delete_entry($m->{file_a}, $pbat);
  4342. }
  4343. sub M {
  4344. my ($self, $m) = @_;
  4345. my ($dir, $file) = split_path($m->{file_b});
  4346. my $pbat = $self->ensure_path($dir);
  4347. my $fbat = $self->open_file($self->repo_path($m->{file_b}),
  4348. $pbat,$self->{r},$self->{pool});
  4349. print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
  4350. $self->chg_file($fbat, $m);
  4351. $self->close_file($fbat,undef,$self->{pool});
  4352. }
  4353. sub T { shift->M(@_) }
  4354. sub change_file_prop {
  4355. my ($self, $fbat, $pname, $pval) = @_;
  4356. $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
  4357. }
  4358. sub _chg_file_get_blob ($$$$) {
  4359. my ($self, $fbat, $m, $which) = @_;
  4360. my $fh = $::_repository->temp_acquire("git_blob_$which");
  4361. if ($m->{"mode_$which"} =~ /^120/) {
  4362. print $fh 'link ' or croak $!;
  4363. $self->change_file_prop($fbat,'svn:special','*');
  4364. } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
  4365. $self->change_file_prop($fbat,'svn:special',undef);
  4366. }
  4367. my $blob = $m->{"sha1_$which"};
  4368. return ($fh,) if ($blob =~ /^0{40}$/);
  4369. my $size = $::_repository->cat_blob($blob, $fh);
  4370. croak "Failed to read object $blob" if ($size < 0);
  4371. $fh->flush == 0 or croak $!;
  4372. seek $fh, 0, 0 or croak $!;
  4373. my $exp = ::md5sum($fh);
  4374. seek $fh, 0, 0 or croak $!;
  4375. return ($fh, $exp);
  4376. }
  4377. sub chg_file {
  4378. my ($self, $fbat, $m) = @_;
  4379. if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
  4380. $self->change_file_prop($fbat,'svn:executable','*');
  4381. } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
  4382. $self->change_file_prop($fbat,'svn:executable',undef);
  4383. }
  4384. my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
  4385. my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
  4386. my $pool = SVN::Pool->new;
  4387. my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
  4388. if (-s $fh_a) {
  4389. my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
  4390. my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
  4391. if (defined $res) {
  4392. die "Unexpected result from send_txstream: $res\n",
  4393. "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
  4394. }
  4395. } else {
  4396. my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
  4397. die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
  4398. if ($got ne $exp_b);
  4399. }
  4400. Git::temp_release($fh_b, 1);
  4401. Git::temp_release($fh_a, 1);
  4402. $pool->clear;
  4403. }
  4404. sub D {
  4405. my ($self, $m) = @_;
  4406. my ($dir, $file) = split_path($m->{file_b});
  4407. my $pbat = $self->ensure_path($dir);
  4408. print "\tD\t$m->{file_b}\n" unless $::_q;
  4409. $self->delete_entry($m->{file_b}, $pbat);
  4410. }
  4411. sub close_edit {
  4412. my ($self) = @_;
  4413. my ($p,$bat) = ($self->{pool}, $self->{bat});
  4414. foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
  4415. next if $_ eq '';
  4416. $self->close_directory($bat->{$_}, $p);
  4417. }
  4418. $self->close_directory($bat->{''}, $p);
  4419. $self->SUPER::close_edit($p);
  4420. $p->clear;
  4421. }
  4422. sub abort_edit {
  4423. my ($self) = @_;
  4424. $self->SUPER::abort_edit($self->{pool});
  4425. }
  4426. sub DESTROY {
  4427. my $self = shift;
  4428. $self->SUPER::DESTROY(@_);
  4429. $self->{pool}->clear;
  4430. }
  4431. # this drives the editor
  4432. sub apply_diff {
  4433. my ($self) = @_;
  4434. my $mods = $self->{mods};
  4435. my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
  4436. foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
  4437. my $f = $m->{chg};
  4438. if (defined $o{$f}) {
  4439. $self->$f($m);
  4440. } else {
  4441. fatal("Invalid change type: $f");
  4442. }
  4443. }
  4444. $self->rmdirs if $_rmdir;
  4445. if (@$mods == 0) {
  4446. $self->abort_edit;
  4447. } else {
  4448. $self->close_edit;
  4449. }
  4450. return scalar @$mods;
  4451. }
  4452. package Git::SVN::Ra;
  4453. use vars qw/@ISA $config_dir $_log_window_size/;
  4454. use strict;
  4455. use warnings;
  4456. my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
  4457. BEGIN {
  4458. # enforce temporary pool usage for some simple functions
  4459. no strict 'refs';
  4460. for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
  4461. get_file/) {
  4462. my $SUPER = "SUPER::$f";
  4463. *$f = sub {
  4464. my $self = shift;
  4465. my $pool = SVN::Pool->new;
  4466. my @ret = $self->$SUPER(@_,$pool);
  4467. $pool->clear;
  4468. wantarray ? @ret : $ret[0];
  4469. };
  4470. }
  4471. }
  4472. sub _auth_providers () {
  4473. [
  4474. SVN::Client::get_simple_provider(),
  4475. SVN::Client::get_ssl_server_trust_file_provider(),
  4476. SVN::Client::get_simple_prompt_provider(
  4477. \&Git::SVN::Prompt::simple, 2),
  4478. SVN::Client::get_ssl_client_cert_file_provider(),
  4479. SVN::Client::get_ssl_client_cert_prompt_provider(
  4480. \&Git::SVN::Prompt::ssl_client_cert, 2),
  4481. SVN::Client::get_ssl_client_cert_pw_file_provider(),
  4482. SVN::Client::get_ssl_client_cert_pw_prompt_provider(
  4483. \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
  4484. SVN::Client::get_username_provider(),
  4485. SVN::Client::get_ssl_server_trust_prompt_provider(
  4486. \&Git::SVN::Prompt::ssl_server_trust),
  4487. SVN::Client::get_username_prompt_provider(
  4488. \&Git::SVN::Prompt::username, 2)
  4489. ]
  4490. }
  4491. sub escape_uri_only {
  4492. my ($uri) = @_;
  4493. my @tmp;
  4494. foreach (split m{/}, $uri) {
  4495. s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
  4496. push @tmp, $_;
  4497. }
  4498. join('/', @tmp);
  4499. }
  4500. sub escape_url {
  4501. my ($url) = @_;
  4502. if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
  4503. my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
  4504. $url = "$scheme://$domain$uri";
  4505. }
  4506. $url;
  4507. }
  4508. sub new {
  4509. my ($class, $url) = @_;
  4510. $url =~ s!/+$!!;
  4511. return $RA if ($RA && $RA->{url} eq $url);
  4512. ::_req_svn();
  4513. SVN::_Core::svn_config_ensure($config_dir, undef);
  4514. my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
  4515. my $config = SVN::Core::config_get_config($config_dir);
  4516. $RA = undef;
  4517. my $dont_store_passwords = 1;
  4518. my $conf_t = ${$config}{'config'};
  4519. {
  4520. no warnings 'once';
  4521. # The usage of $SVN::_Core::SVN_CONFIG_* variables
  4522. # produces warnings that variables are used only once.
  4523. # I had not found the better way to shut them up, so
  4524. # the warnings of type 'once' are disabled in this block.
  4525. if (SVN::_Core::svn_config_get_bool($conf_t,
  4526. $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
  4527. $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
  4528. 1) == 0) {
  4529. SVN::_Core::svn_auth_set_parameter($baton,
  4530. $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
  4531. bless (\$dont_store_passwords, "_p_void"));
  4532. }
  4533. if (SVN::_Core::svn_config_get_bool($conf_t,
  4534. $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
  4535. $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
  4536. 1) == 0) {
  4537. $Git::SVN::Prompt::_no_auth_cache = 1;
  4538. }
  4539. } # no warnings 'once'
  4540. my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
  4541. config => $config,
  4542. pool => SVN::Pool->new,
  4543. auth_provider_callbacks => $callbacks);
  4544. $self->{url} = $url;
  4545. $self->{svn_path} = $url;
  4546. $self->{repos_root} = $self->get_repos_root;
  4547. $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
  4548. $self->{cache} = { check_path => { r => 0, data => {} },
  4549. get_dir => { r => 0, data => {} } };
  4550. $RA = bless $self, $class;
  4551. }
  4552. sub check_path {
  4553. my ($self, $path, $r) = @_;
  4554. my $cache = $self->{cache}->{check_path};
  4555. if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
  4556. return $cache->{data}->{$path};
  4557. }
  4558. my $pool = SVN::Pool->new;
  4559. my $t = $self->SUPER::check_path($path, $r, $pool);
  4560. $pool->clear;
  4561. if ($r != $cache->{r}) {
  4562. %{$cache->{data}} = ();
  4563. $cache->{r} = $r;
  4564. }
  4565. $cache->{data}->{$path} = $t;
  4566. }
  4567. sub get_dir {
  4568. my ($self, $dir, $r) = @_;
  4569. my $cache = $self->{cache}->{get_dir};
  4570. if ($r == $cache->{r}) {
  4571. if (my $x = $cache->{data}->{$dir}) {
  4572. return wantarray ? @$x : $x->[0];
  4573. }
  4574. }
  4575. my $pool = SVN::Pool->new;
  4576. my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
  4577. my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
  4578. $pool->clear;
  4579. if ($r != $cache->{r}) {
  4580. %{$cache->{data}} = ();
  4581. $cache->{r} = $r;
  4582. }
  4583. $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
  4584. wantarray ? (\%dirents, $r, $props) : \%dirents;
  4585. }
  4586. sub DESTROY {
  4587. # do not call the real DESTROY since we store ourselves in $RA
  4588. }
  4589. # get_log(paths, start, end, limit,
  4590. # discover_changed_paths, strict_node_history, receiver)
  4591. sub get_log {
  4592. my ($self, @args) = @_;
  4593. my $pool = SVN::Pool->new;
  4594. # svn_log_changed_path_t objects passed to get_log are likely to be
  4595. # overwritten even if only the refs are copied to an external variable,
  4596. # so we should dup the structures in their entirety. Using an
  4597. # externally passed pool (instead of our temporary and quickly cleared
  4598. # pool in Git::SVN::Ra) does not help matters at all...
  4599. my $receiver = pop @args;
  4600. my $prefix = "/".$self->{svn_path};
  4601. $prefix =~ s#/+($)##;
  4602. my $prefix_regex = qr#^\Q$prefix\E#;
  4603. push(@args, sub {
  4604. my ($paths) = $_[0];
  4605. return &$receiver(@_) unless $paths;
  4606. $_[0] = ();
  4607. foreach my $p (keys %$paths) {
  4608. my $i = $paths->{$p};
  4609. # Make path relative to our url, not repos_root
  4610. $p =~ s/$prefix_regex//;
  4611. my %s = map { $_ => $i->$_; }
  4612. qw/copyfrom_path copyfrom_rev action/;
  4613. if ($s{'copyfrom_path'}) {
  4614. $s{'copyfrom_path'} =~ s/$prefix_regex//;
  4615. }
  4616. $_[0]{$p} = \%s;
  4617. }
  4618. &$receiver(@_);
  4619. });
  4620. # the limit parameter was not supported in SVN 1.1.x, so we
  4621. # drop it. Therefore, the receiver callback passed to it
  4622. # is made aware of this limitation by being wrapped if
  4623. # the limit passed to is being wrapped.
  4624. if ($SVN::Core::VERSION le '1.2.0') {
  4625. my $limit = splice(@args, 3, 1);
  4626. if ($limit > 0) {
  4627. my $receiver = pop @args;
  4628. push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
  4629. }
  4630. }
  4631. my $ret = $self->SUPER::get_log(@args, $pool);
  4632. $pool->clear;
  4633. $ret;
  4634. }
  4635. sub trees_match {
  4636. my ($self, $url1, $rev1, $url2, $rev2) = @_;
  4637. my $ctx = SVN::Client->new(auth => _auth_providers);
  4638. my $out = IO::File->new_tmpfile;
  4639. # older SVN (1.1.x) doesn't take $pool as the last parameter for
  4640. # $ctx->diff(), so we'll create a default one
  4641. my $pool = SVN::Pool->new_default_sub;
  4642. $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
  4643. $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
  4644. $out->flush;
  4645. my $ret = (($out->stat)[7] == 0);
  4646. close $out or croak $!;
  4647. $ret;
  4648. }
  4649. sub get_commit_editor {
  4650. my ($self, $log, $cb, $pool) = @_;
  4651. my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
  4652. $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
  4653. }
  4654. sub gs_do_update {
  4655. my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
  4656. my $new = ($rev_a == $rev_b);
  4657. my $path = $gs->{path};
  4658. if ($new && -e $gs->{index}) {
  4659. unlink $gs->{index} or die
  4660. "Couldn't unlink index: $gs->{index}: $!\n";
  4661. }
  4662. my $pool = SVN::Pool->new;
  4663. $editor->set_path_strip($path);
  4664. my (@pc) = split m#/#, $path;
  4665. my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
  4666. 1, $editor, $pool);
  4667. my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
  4668. # Since we can't rely on svn_ra_reparent being available, we'll
  4669. # just have to do some magic with set_path to make it so
  4670. # we only want a partial path.
  4671. my $sp = '';
  4672. my $final = join('/', @pc);
  4673. while (@pc) {
  4674. $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
  4675. $sp .= '/' if length $sp;
  4676. $sp .= shift @pc;
  4677. }
  4678. die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
  4679. $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
  4680. $reporter->finish_report($pool);
  4681. $pool->clear;
  4682. $editor->{git_commit_ok};
  4683. }
  4684. # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
  4685. # svn_ra_reparent didn't work before 1.4)
  4686. sub gs_do_switch {
  4687. my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
  4688. my $path = $gs->{path};
  4689. my $pool = SVN::Pool->new;
  4690. my $full_url = $self->{url};
  4691. my $old_url = $full_url;
  4692. $full_url .= '/' . $path if length $path;
  4693. my ($ra, $reparented);
  4694. if ($old_url =~ m#^svn(\+ssh)?://# ||
  4695. ($full_url =~ m#^https?://# &&
  4696. escape_url($full_url) ne $full_url)) {
  4697. $_[0] = undef;
  4698. $self = undef;
  4699. $RA = undef;
  4700. $ra = Git::SVN::Ra->new($full_url);
  4701. $ra_invalid = 1;
  4702. } elsif ($old_url ne $full_url) {
  4703. SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
  4704. $self->{url} = $full_url;
  4705. $reparented = 1;
  4706. }
  4707. $ra ||= $self;
  4708. $url_b = escape_url($url_b);
  4709. my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
  4710. my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
  4711. $reporter->set_path('', $rev_a, 0, @lock, $pool);
  4712. $reporter->finish_report($pool);
  4713. if ($reparented) {
  4714. SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
  4715. $self->{url} = $old_url;
  4716. }
  4717. $pool->clear;
  4718. $editor->{git_commit_ok};
  4719. }
  4720. sub longest_common_path {
  4721. my ($gsv, $globs) = @_;
  4722. my %common;
  4723. my $common_max = scalar @$gsv;
  4724. foreach my $gs (@$gsv) {
  4725. my @tmp = split m#/#, $gs->{path};
  4726. my $p = '';
  4727. foreach (@tmp) {
  4728. $p .= length($p) ? "/$_" : $_;
  4729. $common{$p} ||= 0;
  4730. $common{$p}++;
  4731. }
  4732. }
  4733. $globs ||= [];
  4734. $common_max += scalar @$globs;
  4735. foreach my $glob (@$globs) {
  4736. my @tmp = split m#/#, $glob->{path}->{left};
  4737. my $p = '';
  4738. foreach (@tmp) {
  4739. $p .= length($p) ? "/$_" : $_;
  4740. $common{$p} ||= 0;
  4741. $common{$p}++;
  4742. }
  4743. }
  4744. my $longest_path = '';
  4745. foreach (sort {length $b <=> length $a} keys %common) {
  4746. if ($common{$_} == $common_max) {
  4747. $longest_path = $_;
  4748. last;
  4749. }
  4750. }
  4751. $longest_path;
  4752. }
  4753. sub gs_fetch_loop_common {
  4754. my ($self, $base, $head, $gsv, $globs) = @_;
  4755. return if ($base > $head);
  4756. my $inc = $_log_window_size;
  4757. my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
  4758. my $longest_path = longest_common_path($gsv, $globs);
  4759. my $ra_url = $self->{url};
  4760. my $find_trailing_edge;
  4761. while (1) {
  4762. my %revs;
  4763. my $err;
  4764. my $err_handler = $SVN::Error::handler;
  4765. $SVN::Error::handler = sub {
  4766. ($err) = @_;
  4767. skip_unknown_revs($err);
  4768. };
  4769. sub _cb {
  4770. my ($paths, $r, $author, $date, $log) = @_;
  4771. [ $paths,
  4772. { author => $author, date => $date, log => $log } ];
  4773. }
  4774. $self->get_log([$longest_path], $min, $max, 0, 1, 1,
  4775. sub { $revs{$_[1]} = _cb(@_) });
  4776. if ($err) {
  4777. print "Checked through r$max\r";
  4778. } else {
  4779. $find_trailing_edge = 1;
  4780. }
  4781. if ($err and $find_trailing_edge) {
  4782. print STDERR "Path '$longest_path' ",
  4783. "was probably deleted:\n",
  4784. $err->expanded_message,
  4785. "\nWill attempt to follow ",
  4786. "revisions r$min .. r$max ",
  4787. "committed before the deletion\n";
  4788. my $hi = $max;
  4789. while (--$hi >= $min) {
  4790. my $ok;
  4791. $self->get_log([$longest_path], $min, $hi,
  4792. 0, 1, 1, sub {
  4793. $ok = $_[1];
  4794. $revs{$_[1]} = _cb(@_) });
  4795. if ($ok) {
  4796. print STDERR "r$min .. r$ok OK\n";
  4797. last;
  4798. }
  4799. }
  4800. $find_trailing_edge = 0;
  4801. }
  4802. $SVN::Error::handler = $err_handler;
  4803. my %exists = map { $_->{path} => $_ } @$gsv;
  4804. foreach my $r (sort {$a <=> $b} keys %revs) {
  4805. my ($paths, $logged) = @{$revs{$r}};
  4806. foreach my $gs ($self->match_globs(\%exists, $paths,
  4807. $globs, $r)) {
  4808. if ($gs->rev_map_max >= $r) {
  4809. next;
  4810. }
  4811. next unless $gs->match_paths($paths, $r);
  4812. $gs->{logged_rev_props} = $logged;
  4813. if (my $last_commit = $gs->last_commit) {
  4814. $gs->assert_index_clean($last_commit);
  4815. }
  4816. my $log_entry = $gs->do_fetch($paths, $r);
  4817. if ($log_entry) {
  4818. $gs->do_git_commit($log_entry);
  4819. }
  4820. $INDEX_FILES{$gs->{index}} = 1;
  4821. }
  4822. foreach my $g (@$globs) {
  4823. my $k = "svn-remote.$g->{remote}." .
  4824. "$g->{t}-maxRev";
  4825. Git::SVN::tmp_config($k, $r);
  4826. }
  4827. if ($ra_invalid) {
  4828. $_[0] = undef;
  4829. $self = undef;
  4830. $RA = undef;
  4831. $self = Git::SVN::Ra->new($ra_url);
  4832. $ra_invalid = undef;
  4833. }
  4834. }
  4835. # pre-fill the .rev_db since it'll eventually get filled in
  4836. # with '0' x40 if something new gets committed
  4837. foreach my $gs (@$gsv) {
  4838. next if $gs->rev_map_max >= $max;
  4839. next if defined $gs->rev_map_get($max);
  4840. $gs->rev_map_set($max, 0 x40);
  4841. }
  4842. foreach my $g (@$globs) {
  4843. my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
  4844. Git::SVN::tmp_config($k, $max);
  4845. }
  4846. last if $max >= $head;
  4847. $min = $max + 1;
  4848. $max += $inc;
  4849. $max = $head if ($max > $head);
  4850. }
  4851. Git::SVN::gc();
  4852. }
  4853. sub get_dir_globbed {
  4854. my ($self, $left, $depth, $r) = @_;
  4855. my @x = eval { $self->get_dir($left, $r) };
  4856. return unless scalar @x == 3;
  4857. my $dirents = $x[0];
  4858. my @finalents;
  4859. foreach my $de (keys %$dirents) {
  4860. next if $dirents->{$de}->{kind} != $SVN::Node::dir;
  4861. if ($depth > 1) {
  4862. my @args = ("$left/$de", $depth - 1, $r);
  4863. foreach my $dir ($self->get_dir_globbed(@args)) {
  4864. push @finalents, "$de/$dir";
  4865. }
  4866. } else {
  4867. push @finalents, $de;
  4868. }
  4869. }
  4870. @finalents;
  4871. }
  4872. sub match_globs {
  4873. my ($self, $exists, $paths, $globs, $r) = @_;
  4874. sub get_dir_check {
  4875. my ($self, $exists, $g, $r) = @_;
  4876. my @dirs = $self->get_dir_globbed($g->{path}->{left},
  4877. $g->{path}->{depth},
  4878. $r);
  4879. foreach my $de (@dirs) {
  4880. my $p = $g->{path}->full_path($de);
  4881. next if $exists->{$p};
  4882. next if (length $g->{path}->{right} &&
  4883. ($self->check_path($p, $r) !=
  4884. $SVN::Node::dir));
  4885. next unless $p =~ /$g->{path}->{regex}/;
  4886. $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
  4887. $g->{ref}->full_path($de), 1);
  4888. }
  4889. }
  4890. foreach my $g (@$globs) {
  4891. if (my $path = $paths->{"/$g->{path}->{left}"}) {
  4892. if ($path->{action} =~ /^[AR]$/) {
  4893. get_dir_check($self, $exists, $g, $r);
  4894. }
  4895. }
  4896. foreach (keys %$paths) {
  4897. if (/$g->{path}->{left_regex}/ &&
  4898. !/$g->{path}->{regex}/) {
  4899. next if $paths->{$_}->{action} !~ /^[AR]$/;
  4900. get_dir_check($self, $exists, $g, $r);
  4901. }
  4902. next unless /$g->{path}->{regex}/;
  4903. my $p = $1;
  4904. my $pathname = $g->{path}->full_path($p);
  4905. next if $exists->{$pathname};
  4906. next if ($self->check_path($pathname, $r) !=
  4907. $SVN::Node::dir);
  4908. $exists->{$pathname} = Git::SVN->init(
  4909. $self->{url}, $pathname, undef,
  4910. $g->{ref}->full_path($p), 1);
  4911. }
  4912. my $c = '';
  4913. foreach (split m#/#, $g->{path}->{left}) {
  4914. $c .= "/$_";
  4915. next unless ($paths->{$c} &&
  4916. ($paths->{$c}->{action} =~ /^[AR]$/));
  4917. get_dir_check($self, $exists, $g, $r);
  4918. }
  4919. }
  4920. values %$exists;
  4921. }
  4922. sub minimize_url {
  4923. my ($self) = @_;
  4924. return $self->{url} if ($self->{url} eq $self->{repos_root});
  4925. my $url = $self->{repos_root};
  4926. my @components = split(m!/!, $self->{svn_path});
  4927. my $c = '';
  4928. do {
  4929. $url .= "/$c" if length $c;
  4930. eval {
  4931. my $ra = (ref $self)->new($url);
  4932. my $latest = $ra->get_latest_revnum;
  4933. $ra->get_log("", $latest, 0, 1, 0, 1, sub {});
  4934. };
  4935. } while ($@ && ($c = shift @components));
  4936. $url;
  4937. }
  4938. sub can_do_switch {
  4939. my $self = shift;
  4940. unless (defined $can_do_switch) {
  4941. my $pool = SVN::Pool->new;
  4942. my $rep = eval {
  4943. $self->do_switch(1, '', 0, $self->{url},
  4944. SVN::Delta::Editor->new, $pool);
  4945. };
  4946. if ($@) {
  4947. $can_do_switch = 0;
  4948. } else {
  4949. $rep->abort_report($pool);
  4950. $can_do_switch = 1;
  4951. }
  4952. $pool->clear;
  4953. }
  4954. $can_do_switch;
  4955. }
  4956. sub skip_unknown_revs {
  4957. my ($err) = @_;
  4958. my $errno = $err->apr_err();
  4959. # Maybe the branch we're tracking didn't
  4960. # exist when the repo started, so it's
  4961. # not an error if it doesn't, just continue
  4962. #
  4963. # Wonderfully consistent library, eh?
  4964. # 160013 - svn:// and file://
  4965. # 175002 - http(s)://
  4966. # 175007 - http(s):// (this repo required authorization, too...)
  4967. # More codes may be discovered later...
  4968. if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
  4969. my $err_key = $err->expanded_message;
  4970. # revision numbers change every time, filter them out
  4971. $err_key =~ s/\d+/\0/g;
  4972. $err_key = "$errno\0$err_key";
  4973. unless ($ignored_err{$err_key}) {
  4974. warn "W: Ignoring error from SVN, path probably ",
  4975. "does not exist: ($errno): ",
  4976. $err->expanded_message,"\n";
  4977. warn "W: Do not be alarmed at the above message ",
  4978. "git-svn is just searching aggressively for ",
  4979. "old history.\n",
  4980. "This may take a while on large repositories\n";
  4981. $ignored_err{$err_key} = 1;
  4982. }
  4983. return;
  4984. }
  4985. die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
  4986. }
  4987. package Git::SVN::Log;
  4988. use strict;
  4989. use warnings;
  4990. use POSIX qw/strftime/;
  4991. use Time::Local;
  4992. use constant commit_log_separator => ('-' x 72) . "\n";
  4993. use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
  4994. %rusers $show_commit $incremental/;
  4995. my $l_fmt;
  4996. sub cmt_showable {
  4997. my ($c) = @_;
  4998. return 1 if defined $c->{r};
  4999. # big commit message got truncated by the 16k pretty buffer in rev-list
  5000. if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
  5001. $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
  5002. @{$c->{l}} = ();
  5003. my @log = command(qw/cat-file commit/, $c->{c});
  5004. # shift off the headers
  5005. shift @log while ($log[0] ne '');
  5006. shift @log;
  5007. # TODO: make $c->{l} not have a trailing newline in the future
  5008. @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
  5009. (undef, $c->{r}, undef) = ::extract_metadata(
  5010. (grep(/^git-svn-id: /, @log))[-1]);
  5011. }
  5012. return defined $c->{r};
  5013. }
  5014. sub log_use_color {
  5015. return $color || Git->repository->get_colorbool('color.diff');
  5016. }
  5017. sub git_svn_log_cmd {
  5018. my ($r_min, $r_max, @args) = @_;
  5019. my $head = 'HEAD';
  5020. my (@files, @log_opts);
  5021. foreach my $x (@args) {
  5022. if ($x eq '--' || @files) {
  5023. push @files, $x;
  5024. } else {
  5025. if (::verify_ref("$x^0")) {
  5026. $head = $x;
  5027. } else {
  5028. push @log_opts, $x;
  5029. }
  5030. }
  5031. }
  5032. my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
  5033. $gs ||= Git::SVN->_new;
  5034. my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
  5035. $gs->refname);
  5036. push @cmd, '-r' unless $non_recursive;
  5037. push @cmd, qw/--raw --name-status/ if $verbose;
  5038. push @cmd, '--color' if log_use_color();
  5039. push @cmd, @log_opts;
  5040. if (defined $r_max && $r_max == $r_min) {
  5041. push @cmd, '--max-count=1';
  5042. if (my $c = $gs->rev_map_get($r_max)) {
  5043. push @cmd, $c;
  5044. }
  5045. } elsif (defined $r_max) {
  5046. if ($r_max < $r_min) {
  5047. ($r_min, $r_max) = ($r_max, $r_min);
  5048. }
  5049. my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
  5050. my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
  5051. # If there are no commits in the range, both $c_max and $c_min
  5052. # will be undefined. If there is at least 1 commit in the
  5053. # range, both will be defined.
  5054. return () if !defined $c_min || !defined $c_max;
  5055. if ($c_min eq $c_max) {
  5056. push @cmd, '--max-count=1', $c_min;
  5057. } else {
  5058. push @cmd, '--boundary', "$c_min..$c_max";
  5059. }
  5060. }
  5061. return (@cmd, @files);
  5062. }
  5063. # adapted from pager.c
  5064. sub config_pager {
  5065. if (! -t *STDOUT) {
  5066. $ENV{GIT_PAGER_IN_USE} = 'false';
  5067. $pager = undef;
  5068. return;
  5069. }
  5070. chomp($pager = command_oneline(qw(var GIT_PAGER)));
  5071. if ($pager eq 'cat') {
  5072. $pager = undef;
  5073. }
  5074. $ENV{GIT_PAGER_IN_USE} = defined($pager);
  5075. }
  5076. sub run_pager {
  5077. return unless defined $pager;
  5078. pipe my ($rfd, $wfd) or return;
  5079. defined(my $pid = fork) or ::fatal "Can't fork: $!";
  5080. if (!$pid) {
  5081. open STDOUT, '>&', $wfd or
  5082. ::fatal "Can't redirect to stdout: $!";
  5083. return;
  5084. }
  5085. open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
  5086. $ENV{LESS} ||= 'FRSX';
  5087. exec $pager or ::fatal "Can't run pager: $! ($pager)";
  5088. }
  5089. sub format_svn_date {
  5090. # some systmes don't handle or mishandle %z, so be creative.
  5091. my $t = shift || time;
  5092. my $gm = timelocal(gmtime($t));
  5093. my $sign = qw( + + - )[ $t <=> $gm ];
  5094. my $gmoff = sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
  5095. return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
  5096. }
  5097. sub parse_git_date {
  5098. my ($t, $tz) = @_;
  5099. # Date::Parse isn't in the standard Perl distro :(
  5100. if ($tz =~ s/^\+//) {
  5101. $t += tz_to_s_offset($tz);
  5102. } elsif ($tz =~ s/^\-//) {
  5103. $t -= tz_to_s_offset($tz);
  5104. }
  5105. return $t;
  5106. }
  5107. sub set_local_timezone {
  5108. if (defined $TZ) {
  5109. $ENV{TZ} = $TZ;
  5110. } else {
  5111. delete $ENV{TZ};
  5112. }
  5113. }
  5114. sub tz_to_s_offset {
  5115. my ($tz) = @_;
  5116. $tz =~ s/(\d\d)$//;
  5117. return ($1 * 60) + ($tz * 3600);
  5118. }
  5119. sub get_author_info {
  5120. my ($dest, $author, $t, $tz) = @_;
  5121. $author =~ s/(?:^\s*|\s*$)//g;
  5122. $dest->{a_raw} = $author;
  5123. my $au;
  5124. if ($::_authors) {
  5125. $au = $rusers{$author} || undef;
  5126. }
  5127. if (!$au) {
  5128. ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
  5129. }
  5130. $dest->{t} = $t;
  5131. $dest->{tz} = $tz;
  5132. $dest->{a} = $au;
  5133. $dest->{t_utc} = parse_git_date($t, $tz);
  5134. }
  5135. sub process_commit {
  5136. my ($c, $r_min, $r_max, $defer) = @_;
  5137. if (defined $r_min && defined $r_max) {
  5138. if ($r_min == $c->{r} && $r_min == $r_max) {
  5139. show_commit($c);
  5140. return 0;
  5141. }
  5142. return 1 if $r_min == $r_max;
  5143. if ($r_min < $r_max) {
  5144. # we need to reverse the print order
  5145. return 0 if (defined $limit && --$limit < 0);
  5146. push @$defer, $c;
  5147. return 1;
  5148. }
  5149. if ($r_min != $r_max) {
  5150. return 1 if ($r_min < $c->{r});
  5151. return 1 if ($r_max > $c->{r});
  5152. }
  5153. }
  5154. return 0 if (defined $limit && --$limit < 0);
  5155. show_commit($c);
  5156. return 1;
  5157. }
  5158. sub show_commit {
  5159. my $c = shift;
  5160. if ($oneline) {
  5161. my $x = "\n";
  5162. if (my $l = $c->{l}) {
  5163. while ($l->[0] =~ /^\s*$/) { shift @$l }
  5164. $x = $l->[0];
  5165. }
  5166. $l_fmt ||= 'A' . length($c->{r});
  5167. print 'r',pack($l_fmt, $c->{r}),' | ';
  5168. print "$c->{c} | " if $show_commit;
  5169. print $x;
  5170. } else {
  5171. show_commit_normal($c);
  5172. }
  5173. }
  5174. sub show_commit_changed_paths {
  5175. my ($c) = @_;
  5176. return unless $c->{changed};
  5177. print "Changed paths:\n", @{$c->{changed}};
  5178. }
  5179. sub show_commit_normal {
  5180. my ($c) = @_;
  5181. print commit_log_separator, "r$c->{r} | ";
  5182. print "$c->{c} | " if $show_commit;
  5183. print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
  5184. my $nr_line = 0;
  5185. if (my $l = $c->{l}) {
  5186. while ($l->[$#$l] eq "\n" && $#$l > 0
  5187. && $l->[($#$l - 1)] eq "\n") {
  5188. pop @$l;
  5189. }
  5190. $nr_line = scalar @$l;
  5191. if (!$nr_line) {
  5192. print "1 line\n\n\n";
  5193. } else {
  5194. if ($nr_line == 1) {
  5195. $nr_line = '1 line';
  5196. } else {
  5197. $nr_line .= ' lines';
  5198. }
  5199. print $nr_line, "\n";
  5200. show_commit_changed_paths($c);
  5201. print "\n";
  5202. print $_ foreach @$l;
  5203. }
  5204. } else {
  5205. print "1 line\n";
  5206. show_commit_changed_paths($c);
  5207. print "\n";
  5208. }
  5209. foreach my $x (qw/raw stat diff/) {
  5210. if ($c->{$x}) {
  5211. print "\n";
  5212. print $_ foreach @{$c->{$x}}
  5213. }
  5214. }
  5215. }
  5216. sub cmd_show_log {
  5217. my (@args) = @_;
  5218. my ($r_min, $r_max);
  5219. my $r_last = -1; # prevent dupes
  5220. set_local_timezone();
  5221. if (defined $::_revision) {
  5222. if ($::_revision =~ /^(\d+):(\d+)$/) {
  5223. ($r_min, $r_max) = ($1, $2);
  5224. } elsif ($::_revision =~ /^\d+$/) {
  5225. $r_min = $r_max = $::_revision;
  5226. } else {
  5227. ::fatal "-r$::_revision is not supported, use ",
  5228. "standard 'git log' arguments instead";
  5229. }
  5230. }
  5231. config_pager();
  5232. @args = git_svn_log_cmd($r_min, $r_max, @args);
  5233. if (!@args) {
  5234. print commit_log_separator unless $incremental || $oneline;
  5235. return;
  5236. }
  5237. my $log = command_output_pipe(@args);
  5238. run_pager();
  5239. my (@k, $c, $d, $stat);
  5240. my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
  5241. while (<$log>) {
  5242. if (/^${esc_color}commit -?($::sha1_short)/o) {
  5243. my $cmt = $1;
  5244. if ($c && cmt_showable($c) && $c->{r} != $r_last) {
  5245. $r_last = $c->{r};
  5246. process_commit($c, $r_min, $r_max, \@k) or
  5247. goto out;
  5248. }
  5249. $d = undef;
  5250. $c = { c => $cmt };
  5251. } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
  5252. get_author_info($c, $1, $2, $3);
  5253. } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
  5254. # ignore
  5255. } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
  5256. push @{$c->{raw}}, $_;
  5257. } elsif (/^${esc_color}[ACRMDT]\t/) {
  5258. # we could add $SVN->{svn_path} here, but that requires
  5259. # remote access at the moment (repo_path_split)...
  5260. s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
  5261. push @{$c->{changed}}, $_;
  5262. } elsif (/^${esc_color}diff /o) {
  5263. $d = 1;
  5264. push @{$c->{diff}}, $_;
  5265. } elsif ($d) {
  5266. push @{$c->{diff}}, $_;
  5267. } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
  5268. $esc_color*[\+\-]*$esc_color$/x) {
  5269. $stat = 1;
  5270. push @{$c->{stat}}, $_;
  5271. } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
  5272. push @{$c->{stat}}, $_;
  5273. $stat = undef;
  5274. } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
  5275. ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
  5276. } elsif (s/^${esc_color} //o) {
  5277. push @{$c->{l}}, $_;
  5278. }
  5279. }
  5280. if ($c && defined $c->{r} && $c->{r} != $r_last) {
  5281. $r_last = $c->{r};
  5282. process_commit($c, $r_min, $r_max, \@k);
  5283. }
  5284. if (@k) {
  5285. ($r_min, $r_max) = ($r_max, $r_min);
  5286. process_commit($_, $r_min, $r_max) foreach reverse @k;
  5287. }
  5288. out:
  5289. close $log;
  5290. print commit_log_separator unless $incremental || $oneline;
  5291. }
  5292. sub cmd_blame {
  5293. my $path = pop;
  5294. config_pager();
  5295. run_pager();
  5296. my ($fh, $ctx, $rev);
  5297. if ($_git_format) {
  5298. ($fh, $ctx) = command_output_pipe('blame', @_, $path);
  5299. while (my $line = <$fh>) {
  5300. if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
  5301. # Uncommitted edits show up as a rev ID of
  5302. # all zeros, which we can't look up with
  5303. # cmt_metadata
  5304. if ($1 !~ /^0+$/) {
  5305. (undef, $rev, undef) =
  5306. ::cmt_metadata($1);
  5307. $rev = '0' if (!$rev);
  5308. } else {
  5309. $rev = '0';
  5310. }
  5311. $rev = sprintf('%-10s', $rev);
  5312. $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
  5313. }
  5314. print $line;
  5315. }
  5316. } else {
  5317. ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
  5318. '--', $path);
  5319. my ($sha1);
  5320. my %authors;
  5321. my @buffer;
  5322. my %dsha; #distinct sha keys
  5323. while (my $line = <$fh>) {
  5324. push @buffer, $line;
  5325. if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
  5326. $dsha{$1} = 1;
  5327. }
  5328. }
  5329. my $s2r = ::cmt_sha2rev_batch([keys %dsha]);
  5330. foreach my $line (@buffer) {
  5331. if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
  5332. $rev = $s2r->{$1};
  5333. $rev = '0' if (!$rev)
  5334. }
  5335. elsif ($line =~ /^author (.*)/) {
  5336. $authors{$rev} = $1;
  5337. $authors{$rev} =~ s/\s/_/g;
  5338. }
  5339. elsif ($line =~ /^\t(.*)$/) {
  5340. printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
  5341. }
  5342. }
  5343. }
  5344. command_close_pipe($fh, $ctx);
  5345. }
  5346. package Git::SVN::Migration;
  5347. # these version numbers do NOT correspond to actual version numbers
  5348. # of git nor git-svn. They are just relative.
  5349. #
  5350. # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
  5351. #
  5352. # v1 layout: .git/$id/info/url, refs/remotes/$id
  5353. #
  5354. # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
  5355. #
  5356. # v3 layout: .git/svn/$id, refs/remotes/$id
  5357. # - info/url may remain for backwards compatibility
  5358. # - this is what we migrate up to this layout automatically,
  5359. # - this will be used by git svn init on single branches
  5360. # v3.1 layout (auto migrated):
  5361. # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
  5362. # for backwards compatibility
  5363. #
  5364. # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
  5365. # - this is only created for newly multi-init-ed
  5366. # repositories. Similar in spirit to the
  5367. # --use-separate-remotes option in git-clone (now default)
  5368. # - we do not automatically migrate to this (following
  5369. # the example set by core git)
  5370. #
  5371. # v5 layout: .rev_db.$UUID => .rev_map.$UUID
  5372. # - newer, more-efficient format that uses 24-bytes per record
  5373. # with no filler space.
  5374. # - use xxd -c24 < .rev_map.$UUID to view and debug
  5375. # - This is a one-way migration, repositories updated to the
  5376. # new format will not be able to use old git-svn without
  5377. # rebuilding the .rev_db. Rebuilding the rev_db is not
  5378. # possible if noMetadata or useSvmProps are set; but should
  5379. # be no problem for users that use the (sensible) defaults.
  5380. use strict;
  5381. use warnings;
  5382. use Carp qw/croak/;
  5383. use File::Path qw/mkpath/;
  5384. use File::Basename qw/dirname basename/;
  5385. use vars qw/$_minimize/;
  5386. sub migrate_from_v0 {
  5387. my $git_dir = $ENV{GIT_DIR};
  5388. return undef unless -d $git_dir;
  5389. my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
  5390. my $migrated = 0;
  5391. while (<$fh>) {
  5392. chomp;
  5393. my ($id, $orig_ref) = ($_, $_);
  5394. next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
  5395. next unless -f "$git_dir/$id/info/url";
  5396. my $new_ref = "refs/remotes/$id";
  5397. if (::verify_ref("$new_ref^0")) {
  5398. print STDERR "W: $orig_ref is probably an old ",
  5399. "branch used by an ancient version of ",
  5400. "git-svn.\n",
  5401. "However, $new_ref also exists.\n",
  5402. "We will not be able ",
  5403. "to use this branch until this ",
  5404. "ambiguity is resolved.\n";
  5405. next;
  5406. }
  5407. print STDERR "Migrating from v0 layout...\n" if !$migrated;
  5408. print STDERR "Renaming ref: $orig_ref => $new_ref\n";
  5409. command_noisy('update-ref', $new_ref, $orig_ref);
  5410. command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
  5411. $migrated++;
  5412. }
  5413. command_close_pipe($fh, $ctx);
  5414. print STDERR "Done migrating from v0 layout...\n" if $migrated;
  5415. $migrated;
  5416. }
  5417. sub migrate_from_v1 {
  5418. my $git_dir = $ENV{GIT_DIR};
  5419. my $migrated = 0;
  5420. return $migrated unless -d $git_dir;
  5421. my $svn_dir = "$git_dir/svn";
  5422. # just in case somebody used 'svn' as their $id at some point...
  5423. return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
  5424. print STDERR "Migrating from a git-svn v1 layout...\n";
  5425. mkpath([$svn_dir]);
  5426. print STDERR "Data from a previous version of git-svn exists, but\n\t",
  5427. "$svn_dir\n\t(required for this version ",
  5428. "($::VERSION) of git-svn) does not exist.\n";
  5429. my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
  5430. while (<$fh>) {
  5431. my $x = $_;
  5432. next unless $x =~ s#^refs/remotes/##;
  5433. chomp $x;
  5434. next unless -f "$git_dir/$x/info/url";
  5435. my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
  5436. next unless $u;
  5437. my $dn = dirname("$git_dir/svn/$x");
  5438. mkpath([$dn]) unless -d $dn;
  5439. if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
  5440. mkpath(["$git_dir/svn/svn"]);
  5441. print STDERR " - $git_dir/$x/info => ",
  5442. "$git_dir/svn/$x/info\n";
  5443. rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
  5444. croak "$!: $x";
  5445. # don't worry too much about these, they probably
  5446. # don't exist with repos this old (save for index,
  5447. # and we can easily regenerate that)
  5448. foreach my $f (qw/unhandled.log index .rev_db/) {
  5449. rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
  5450. }
  5451. } else {
  5452. print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
  5453. rename "$git_dir/$x", "$git_dir/svn/$x" or
  5454. croak "$!: $x";
  5455. }
  5456. $migrated++;
  5457. }
  5458. command_close_pipe($fh, $ctx);
  5459. print STDERR "Done migrating from a git-svn v1 layout\n";
  5460. $migrated;
  5461. }
  5462. sub read_old_urls {
  5463. my ($l_map, $pfx, $path) = @_;
  5464. my @dir;
  5465. foreach (<$path/*>) {
  5466. if (-r "$_/info/url") {
  5467. $pfx .= '/' if $pfx && $pfx !~ m!/$!;
  5468. my $ref_id = $pfx . basename $_;
  5469. my $url = ::file_to_s("$_/info/url");
  5470. $l_map->{$ref_id} = $url;
  5471. } elsif (-d $_) {
  5472. push @dir, $_;
  5473. }
  5474. }
  5475. foreach (@dir) {
  5476. my $x = $_;
  5477. $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
  5478. read_old_urls($l_map, $x, $_);
  5479. }
  5480. }
  5481. sub migrate_from_v2 {
  5482. my @cfg = command(qw/config -l/);
  5483. return if grep /^svn-remote\..+\.url=/, @cfg;
  5484. my %l_map;
  5485. read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
  5486. my $migrated = 0;
  5487. foreach my $ref_id (sort keys %l_map) {
  5488. eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
  5489. if ($@) {
  5490. Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
  5491. }
  5492. $migrated++;
  5493. }
  5494. $migrated;
  5495. }
  5496. sub minimize_connections {
  5497. my $r = Git::SVN::read_all_remotes();
  5498. my $new_urls = {};
  5499. my $root_repos = {};
  5500. foreach my $repo_id (keys %$r) {
  5501. my $url = $r->{$repo_id}->{url} or next;
  5502. my $fetch = $r->{$repo_id}->{fetch} or next;
  5503. my $ra = Git::SVN::Ra->new($url);
  5504. # skip existing cases where we already connect to the root
  5505. if (($ra->{url} eq $ra->{repos_root}) ||
  5506. ($ra->{repos_root} eq $repo_id)) {
  5507. $root_repos->{$ra->{url}} = $repo_id;
  5508. next;
  5509. }
  5510. my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
  5511. my $root_path = $ra->{url};
  5512. $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
  5513. foreach my $path (keys %$fetch) {
  5514. my $ref_id = $fetch->{$path};
  5515. my $gs = Git::SVN->new($ref_id, $repo_id, $path);
  5516. # make sure we can read when connecting to
  5517. # a higher level of a repository
  5518. my ($last_rev, undef) = $gs->last_rev_commit;
  5519. if (!defined $last_rev) {
  5520. $last_rev = eval {
  5521. $root_ra->get_latest_revnum;
  5522. };
  5523. next if $@;
  5524. }
  5525. my $new = $root_path;
  5526. $new .= length $path ? "/$path" : '';
  5527. eval {
  5528. $root_ra->get_log([$new], $last_rev, $last_rev,
  5529. 0, 0, 1, sub { });
  5530. };
  5531. next if $@;
  5532. $new_urls->{$ra->{repos_root}}->{$new} =
  5533. { ref_id => $ref_id,
  5534. old_repo_id => $repo_id,
  5535. old_path => $path };
  5536. }
  5537. }
  5538. my @emptied;
  5539. foreach my $url (keys %$new_urls) {
  5540. # see if we can re-use an existing [svn-remote "repo_id"]
  5541. # instead of creating a(n ugly) new section:
  5542. my $repo_id = $root_repos->{$url} || $url;
  5543. my $fetch = $new_urls->{$url};
  5544. foreach my $path (keys %$fetch) {
  5545. my $x = $fetch->{$path};
  5546. Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
  5547. my $pfx = "svn-remote.$x->{old_repo_id}";
  5548. my $old_fetch = quotemeta("$x->{old_path}:".
  5549. "$x->{ref_id}");
  5550. command_noisy(qw/config --unset/,
  5551. "$pfx.fetch", '^'. $old_fetch . '$');
  5552. delete $r->{$x->{old_repo_id}}->
  5553. {fetch}->{$x->{old_path}};
  5554. if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
  5555. command_noisy(qw/config --unset/,
  5556. "$pfx.url");
  5557. push @emptied, $x->{old_repo_id}
  5558. }
  5559. }
  5560. }
  5561. if (@emptied) {
  5562. my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
  5563. print STDERR <<EOF;
  5564. The following [svn-remote] sections in your config file ($file) are empty
  5565. and can be safely removed:
  5566. EOF
  5567. print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
  5568. }
  5569. }
  5570. sub migration_check {
  5571. migrate_from_v0();
  5572. migrate_from_v1();
  5573. migrate_from_v2();
  5574. minimize_connections() if $_minimize;
  5575. }
  5576. package Git::IndexInfo;
  5577. use strict;
  5578. use warnings;
  5579. use Git qw/command_input_pipe command_close_pipe/;
  5580. sub new {
  5581. my ($class) = @_;
  5582. my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
  5583. bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
  5584. }
  5585. sub remove {
  5586. my ($self, $path) = @_;
  5587. if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
  5588. return ++$self->{nr};
  5589. }
  5590. undef;
  5591. }
  5592. sub update {
  5593. my ($self, $mode, $hash, $path) = @_;
  5594. if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
  5595. return ++$self->{nr};
  5596. }
  5597. undef;
  5598. }
  5599. sub DESTROY {
  5600. my ($self) = @_;
  5601. command_close_pipe($self->{gui}, $self->{ctx});
  5602. }
  5603. package Git::SVN::GlobSpec;
  5604. use strict;
  5605. use warnings;
  5606. sub new {
  5607. my ($class, $glob, $pattern_ok) = @_;
  5608. my $re = $glob;
  5609. $re =~ s!/+$!!g; # no need for trailing slashes
  5610. my (@left, @right, @patterns);
  5611. my $state = "left";
  5612. my $die_msg = "Only one set of wildcard directories " .
  5613. "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
  5614. for my $part (split(m|/|, $glob)) {
  5615. if ($part =~ /\*/ && $part ne "*") {
  5616. die "Invalid pattern in '$glob': $part\n";
  5617. } elsif ($pattern_ok && $part =~ /[{}]/ &&
  5618. $part !~ /^\{[^{}]+\}/) {
  5619. die "Invalid pattern in '$glob': $part\n";
  5620. }
  5621. if ($part eq "*") {
  5622. die $die_msg if $state eq "right";
  5623. $state = "pattern";
  5624. push(@patterns, "[^/]*");
  5625. } elsif ($pattern_ok && $part =~ /^\{(.*)\}$/) {
  5626. die $die_msg if $state eq "right";
  5627. $state = "pattern";
  5628. my $p = quotemeta($1);
  5629. $p =~ s/\\,/|/g;
  5630. push(@patterns, "(?:$p)");
  5631. } else {
  5632. if ($state eq "left") {
  5633. push(@left, $part);
  5634. } else {
  5635. push(@right, $part);
  5636. $state = "right";
  5637. }
  5638. }
  5639. }
  5640. my $depth = @patterns;
  5641. if ($depth == 0) {
  5642. die "One '*' is needed in glob: '$glob'\n";
  5643. }
  5644. my $left = join('/', @left);
  5645. my $right = join('/', @right);
  5646. $re = join('/', @patterns);
  5647. $re = join('\/',
  5648. grep(length, quotemeta($left), "($re)", quotemeta($right)));
  5649. my $left_re = qr/^\/\Q$left\E(\/|$)/;
  5650. bless { left => $left, right => $right, left_regex => $left_re,
  5651. regex => qr/$re/, glob => $glob, depth => $depth }, $class;
  5652. }
  5653. sub full_path {
  5654. my ($self, $path) = @_;
  5655. return (length $self->{left} ? "$self->{left}/" : '') .
  5656. $path . (length $self->{right} ? "/$self->{right}" : '');
  5657. }
  5658. __END__
  5659. Data structures:
  5660. $remotes = { # returned by read_all_remotes()
  5661. 'svn' => {
  5662. # svn-remote.svn.url=https://svn.musicpd.org
  5663. url => 'https://svn.musicpd.org',
  5664. # svn-remote.svn.fetch=mpd/trunk:trunk
  5665. fetch => {
  5666. 'mpd/trunk' => 'trunk',
  5667. },
  5668. # svn-remote.svn.tags=mpd/tags/*:tags/*
  5669. tags => {
  5670. path => {
  5671. left => 'mpd/tags',
  5672. right => '',
  5673. regex => qr!mpd/tags/([^/]+)$!,
  5674. glob => 'tags/*',
  5675. },
  5676. ref => {
  5677. left => 'tags',
  5678. right => '',
  5679. regex => qr!tags/([^/]+)$!,
  5680. glob => 'tags/*',
  5681. },
  5682. }
  5683. }
  5684. };
  5685. $log_entry hashref as returned by libsvn_log_entry()
  5686. {
  5687. log => 'whitespace-formatted log entry
  5688. ', # trailing newline is preserved
  5689. revision => '8', # integer
  5690. date => '2004-02-24T17:01:44.108345Z', # commit date
  5691. author => 'committer name'
  5692. };
  5693. # this is generated by generate_diff();
  5694. @mods = array of diff-index line hashes, each element represents one line
  5695. of diff-index output
  5696. diff-index line ($m hash)
  5697. {
  5698. mode_a => first column of diff-index output, no leading ':',
  5699. mode_b => second column of diff-index output,
  5700. sha1_b => sha1sum of the final blob,
  5701. chg => change type [MCRADT],
  5702. file_a => original file name of a file (iff chg is 'C' or 'R')
  5703. file_b => new/current file name of a file (any chg)
  5704. }
  5705. ;
  5706. # retval of read_url_paths{,_all}();
  5707. $l_map = {
  5708. # repository root url
  5709. 'https://svn.musicpd.org' => {
  5710. # repository path # GIT_SVN_ID
  5711. 'mpd/trunk' => 'trunk',
  5712. 'mpd/tags/0.11.5' => 'tags/0.11.5',
  5713. },
  5714. }
  5715. Notes:
  5716. I don't trust the each() function on unless I created %hash myself
  5717. because the internal iterator may not have started at base.