PageRenderTime 40ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/bin/git-folder/git-svn

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