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

/git/git-svn.perl

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