PageRenderTime 62ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/git-svn.perl

https://bitbucket.org/grubix/git
Perl | 2231 lines | 2048 code | 128 blank | 55 comment | 201 complexity | 3bc165b59d64ae2d5139a7801d04ce58 MD5 | raw file
Possible License(s): Apache-2.0, BSD-2-Clause, GPL-2.0, LGPL-2.1

Large files files are truncated, but you can click here to view the full file

  1. #!/usr/bin/perl
  2. # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
  3. # License: GPL v2 or later
  4. use 5.008;
  5. use warnings;
  6. use strict;
  7. use vars qw/ $AUTHOR $VERSION
  8. $sha1 $sha1_short $_revision $_repository
  9. $_q $_authors $_authors_prog %users/;
  10. $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
  11. $VERSION = '@@GIT_VERSION@@';
  12. use Carp qw/croak/;
  13. use File::Basename qw/dirname basename/;
  14. use File::Path qw/mkpath/;
  15. use File::Spec;
  16. use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
  17. use Memoize;
  18. use Git::SVN;
  19. use Git::SVN::Editor;
  20. use Git::SVN::Fetcher;
  21. use Git::SVN::Ra;
  22. use Git::SVN::Prompt;
  23. use Git::SVN::Log;
  24. use Git::SVN::Migration;
  25. use Git::SVN::Utils qw(
  26. fatal
  27. can_compress
  28. canonicalize_path
  29. canonicalize_url
  30. join_paths
  31. add_path_to_url
  32. join_paths
  33. );
  34. use Git qw(
  35. git_cmd_try
  36. command
  37. command_oneline
  38. command_noisy
  39. command_output_pipe
  40. command_close_pipe
  41. command_bidi_pipe
  42. command_close_bidi_pipe
  43. );
  44. BEGIN {
  45. Memoize::memoize 'Git::config';
  46. Memoize::memoize 'Git::config_bool';
  47. }
  48. # From which subdir have we been invoked?
  49. my $cmd_dir_prefix = eval {
  50. command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
  51. } || '';
  52. $Git::SVN::Ra::_log_window_size = 100;
  53. if (! exists $ENV{SVN_SSH} && exists $ENV{GIT_SSH}) {
  54. $ENV{SVN_SSH} = $ENV{GIT_SSH};
  55. }
  56. if (exists $ENV{SVN_SSH} && $^O eq 'msys') {
  57. $ENV{SVN_SSH} =~ s/\\/\\\\/g;
  58. $ENV{SVN_SSH} =~ s/(.*)/"$1"/;
  59. }
  60. $Git::SVN::Log::TZ = $ENV{TZ};
  61. $ENV{TZ} = 'UTC';
  62. $| = 1; # unbuffer STDOUT
  63. # All SVN commands do it. Otherwise we may die on SIGPIPE when the remote
  64. # repository decides to close the connection which we expect to be kept alive.
  65. $SIG{PIPE} = 'IGNORE';
  66. # Given a dot separated version number, "subtract" it from
  67. # the SVN::Core::VERSION; non-negaitive return means the SVN::Core
  68. # is at least at the version the caller asked for.
  69. sub compare_svn_version {
  70. my (@ours) = split(/\./, $SVN::Core::VERSION);
  71. my (@theirs) = split(/\./, $_[0]);
  72. my ($i, $diff);
  73. for ($i = 0; $i < @ours && $i < @theirs; $i++) {
  74. $diff = $ours[$i] - $theirs[$i];
  75. return $diff if ($diff);
  76. }
  77. return 1 if ($i < @ours);
  78. return -1 if ($i < @theirs);
  79. return 0;
  80. }
  81. sub _req_svn {
  82. require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
  83. require SVN::Ra;
  84. require SVN::Delta;
  85. if (::compare_svn_version('1.1.0') < 0) {
  86. fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
  87. }
  88. }
  89. $sha1 = qr/[a-f\d]{40}/;
  90. $sha1_short = qr/[a-f\d]{4,40}/;
  91. my ($_stdin, $_help, $_edit,
  92. $_message, $_file, $_branch_dest,
  93. $_template, $_shared,
  94. $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
  95. $_before, $_after,
  96. $_merge, $_strategy, $_preserve_merges, $_dry_run, $_parents, $_local,
  97. $_prefix, $_no_checkout, $_url, $_verbose,
  98. $_commit_url, $_tag, $_merge_info, $_interactive, $_set_svn_props);
  99. # This is a refactoring artifact so Git::SVN can get at this git-svn switch.
  100. sub opt_prefix { return $_prefix || '' }
  101. $Git::SVN::Fetcher::_placeholder_filename = ".gitignore";
  102. $_q ||= 0;
  103. my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
  104. 'config-dir=s' => \$Git::SVN::Ra::config_dir,
  105. 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
  106. 'ignore-paths=s' => \$Git::SVN::Fetcher::_ignore_regex,
  107. 'include-paths=s' => \$Git::SVN::Fetcher::_include_regex,
  108. 'ignore-refs=s' => \$Git::SVN::Ra::_ignore_refs_regex );
  109. my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
  110. 'authors-file|A=s' => \$_authors,
  111. 'authors-prog=s' => \$_authors_prog,
  112. 'repack:i' => \$Git::SVN::_repack,
  113. 'noMetadata' => \$Git::SVN::_no_metadata,
  114. 'useSvmProps' => \$Git::SVN::_use_svm_props,
  115. 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
  116. 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
  117. 'no-checkout' => \$_no_checkout,
  118. 'quiet|q+' => \$_q,
  119. 'repack-flags|repack-args|repack-opts=s' =>
  120. \$Git::SVN::_repack_flags,
  121. 'use-log-author' => \$Git::SVN::_use_log_author,
  122. 'add-author-from' => \$Git::SVN::_add_author_from,
  123. 'localtime' => \$Git::SVN::_localtime,
  124. %remote_opts );
  125. my ($_trunk, @_tags, @_branches, $_stdlayout);
  126. my %icv;
  127. my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
  128. 'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
  129. 'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
  130. 'stdlayout|s' => \$_stdlayout,
  131. 'minimize-url|m!' => \$Git::SVN::_minimize_url,
  132. 'no-metadata' => sub { $icv{noMetadata} = 1 },
  133. 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
  134. 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
  135. 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
  136. 'rewrite-uuid=s' => sub { $icv{rewriteUUID} = $_[1] },
  137. %remote_opts );
  138. my %cmt_opts = ( 'edit|e' => \$_edit,
  139. 'rmdir' => \$Git::SVN::Editor::_rmdir,
  140. 'find-copies-harder' => \$Git::SVN::Editor::_find_copies_harder,
  141. 'l=i' => \$Git::SVN::Editor::_rename_limit,
  142. 'copy-similarity|C=i'=> \$Git::SVN::Editor::_cp_similarity
  143. );
  144. my %cmd = (
  145. fetch => [ \&cmd_fetch, "Download new revisions from SVN",
  146. { 'revision|r=s' => \$_revision,
  147. 'fetch-all|all' => \$_fetch_all,
  148. 'parent|p' => \$_fetch_parent,
  149. %fc_opts } ],
  150. clone => [ \&cmd_clone, "Initialize and fetch revisions",
  151. { 'revision|r=s' => \$_revision,
  152. 'preserve-empty-dirs' =>
  153. \$Git::SVN::Fetcher::_preserve_empty_dirs,
  154. 'placeholder-filename=s' =>
  155. \$Git::SVN::Fetcher::_placeholder_filename,
  156. %fc_opts, %init_opts } ],
  157. init => [ \&cmd_init, "Initialize a repo for tracking" .
  158. " (requires URL argument)",
  159. \%init_opts ],
  160. 'multi-init' => [ \&cmd_multi_init,
  161. "Deprecated alias for ".
  162. "'$0 init -T<trunk> -b<branches> -t<tags>'",
  163. \%init_opts ],
  164. dcommit => [ \&cmd_dcommit,
  165. 'Commit several diffs to merge with upstream',
  166. { 'merge|m|M' => \$_merge,
  167. 'strategy|s=s' => \$_strategy,
  168. 'verbose|v' => \$_verbose,
  169. 'dry-run|n' => \$_dry_run,
  170. 'fetch-all|all' => \$_fetch_all,
  171. 'commit-url=s' => \$_commit_url,
  172. 'set-svn-props=s' => \$_set_svn_props,
  173. 'revision|r=i' => \$_revision,
  174. 'no-rebase' => \$_no_rebase,
  175. 'mergeinfo=s' => \$_merge_info,
  176. 'interactive|i' => \$_interactive,
  177. %cmt_opts, %fc_opts } ],
  178. branch => [ \&cmd_branch,
  179. 'Create a branch in the SVN repository',
  180. { 'message|m=s' => \$_message,
  181. 'destination|d=s' => \$_branch_dest,
  182. 'dry-run|n' => \$_dry_run,
  183. 'parents' => \$_parents,
  184. 'tag|t' => \$_tag,
  185. 'username=s' => \$Git::SVN::Prompt::_username,
  186. 'commit-url=s' => \$_commit_url } ],
  187. tag => [ sub { $_tag = 1; cmd_branch(@_) },
  188. 'Create a tag in the SVN repository',
  189. { 'message|m=s' => \$_message,
  190. 'destination|d=s' => \$_branch_dest,
  191. 'dry-run|n' => \$_dry_run,
  192. 'parents' => \$_parents,
  193. 'username=s' => \$Git::SVN::Prompt::_username,
  194. 'commit-url=s' => \$_commit_url } ],
  195. 'set-tree' => [ \&cmd_set_tree,
  196. "Set an SVN repository to a git tree-ish",
  197. { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
  198. 'create-ignore' => [ \&cmd_create_ignore,
  199. 'Create a .gitignore per svn:ignore',
  200. { 'revision|r=i' => \$_revision
  201. } ],
  202. 'mkdirs' => [ \&cmd_mkdirs ,
  203. "recreate empty directories after a checkout",
  204. { 'revision|r=i' => \$_revision } ],
  205. 'propget' => [ \&cmd_propget,
  206. 'Print the value of a property on a file or directory',
  207. { 'revision|r=i' => \$_revision } ],
  208. 'propset' => [ \&cmd_propset,
  209. 'Set the value of a property on a file or directory - will be set on commit',
  210. {} ],
  211. 'proplist' => [ \&cmd_proplist,
  212. 'List all properties of a file or directory',
  213. { 'revision|r=i' => \$_revision } ],
  214. 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
  215. { 'revision|r=i' => \$_revision
  216. } ],
  217. 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
  218. { 'revision|r=i' => \$_revision
  219. } ],
  220. 'multi-fetch' => [ \&cmd_multi_fetch,
  221. "Deprecated alias for $0 fetch --all",
  222. { 'revision|r=s' => \$_revision, %fc_opts } ],
  223. 'migrate' => [ sub { },
  224. # no-op, we automatically run this anyways,
  225. 'Migrate configuration/metadata/layout from
  226. previous versions of git-svn',
  227. { 'minimize' => \$Git::SVN::Migration::_minimize,
  228. %remote_opts } ],
  229. 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
  230. { 'limit=i' => \$Git::SVN::Log::limit,
  231. 'revision|r=s' => \$_revision,
  232. 'verbose|v' => \$Git::SVN::Log::verbose,
  233. 'incremental' => \$Git::SVN::Log::incremental,
  234. 'oneline' => \$Git::SVN::Log::oneline,
  235. 'show-commit' => \$Git::SVN::Log::show_commit,
  236. 'non-recursive' => \$Git::SVN::Log::non_recursive,
  237. 'authors-file|A=s' => \$_authors,
  238. 'color' => \$Git::SVN::Log::color,
  239. 'pager=s' => \$Git::SVN::Log::pager
  240. } ],
  241. 'find-rev' => [ \&cmd_find_rev,
  242. "Translate between SVN revision numbers and tree-ish",
  243. { 'B|before' => \$_before,
  244. 'A|after' => \$_after } ],
  245. 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
  246. { 'merge|m|M' => \$_merge,
  247. 'verbose|v' => \$_verbose,
  248. 'strategy|s=s' => \$_strategy,
  249. 'local|l' => \$_local,
  250. 'fetch-all|all' => \$_fetch_all,
  251. 'dry-run|n' => \$_dry_run,
  252. 'preserve-merges|p' => \$_preserve_merges,
  253. %fc_opts } ],
  254. 'commit-diff' => [ \&cmd_commit_diff,
  255. 'Commit a diff between two trees',
  256. { 'message|m=s' => \$_message,
  257. 'file|F=s' => \$_file,
  258. 'revision|r=s' => \$_revision,
  259. %cmt_opts } ],
  260. 'info' => [ \&cmd_info,
  261. "Show info about the latest SVN revision
  262. on the current branch",
  263. { 'url' => \$_url, } ],
  264. 'blame' => [ \&Git::SVN::Log::cmd_blame,
  265. "Show what revision and author last modified each line of a file",
  266. { 'git-format' => \$Git::SVN::Log::_git_format } ],
  267. 'reset' => [ \&cmd_reset,
  268. "Undo fetches back to the specified SVN revision",
  269. { 'revision|r=s' => \$_revision,
  270. 'parent|p' => \$_fetch_parent } ],
  271. 'gc' => [ \&cmd_gc,
  272. "Compress unhandled.log files in .git/svn and remove " .
  273. "index files in .git/svn",
  274. {} ],
  275. );
  276. package FakeTerm;
  277. sub new {
  278. my ($class, $reason) = @_;
  279. return bless \$reason, shift;
  280. }
  281. sub readline {
  282. my $self = shift;
  283. die "Cannot use readline on FakeTerm: $$self";
  284. }
  285. package main;
  286. my $term;
  287. sub term_init {
  288. $term = eval {
  289. require Term::ReadLine;
  290. $ENV{"GIT_SVN_NOTTY"}
  291. ? new Term::ReadLine 'git-svn', \*STDIN, \*STDOUT
  292. : new Term::ReadLine 'git-svn';
  293. };
  294. if ($@) {
  295. $term = new FakeTerm "$@: going non-interactive";
  296. }
  297. }
  298. my $cmd;
  299. for (my $i = 0; $i < @ARGV; $i++) {
  300. if (defined $cmd{$ARGV[$i]}) {
  301. $cmd = $ARGV[$i];
  302. splice @ARGV, $i, 1;
  303. last;
  304. } elsif ($ARGV[$i] eq 'help') {
  305. $cmd = $ARGV[$i+1];
  306. usage(0);
  307. }
  308. };
  309. # make sure we're always running at the top-level working directory
  310. if ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
  311. $ENV{GIT_DIR} ||= ".git";
  312. # catch the submodule case
  313. if (-f $ENV{GIT_DIR}) {
  314. open(my $fh, '<', $ENV{GIT_DIR}) or
  315. die "failed to open $ENV{GIT_DIR}: $!\n";
  316. $ENV{GIT_DIR} = $1 if <$fh> =~ /^gitdir: (.+)$/;
  317. }
  318. } elsif ($cmd) {
  319. my ($git_dir, $cdup);
  320. git_cmd_try {
  321. $git_dir = command_oneline([qw/rev-parse --git-dir/]);
  322. } "Unable to find .git directory\n";
  323. git_cmd_try {
  324. $cdup = command_oneline(qw/rev-parse --show-cdup/);
  325. chomp $cdup if ($cdup);
  326. $cdup = "." unless ($cdup && length $cdup);
  327. } "Already at toplevel, but $git_dir not found\n";
  328. $ENV{GIT_DIR} = $git_dir;
  329. chdir $cdup or die "Unable to chdir up to '$cdup'\n";
  330. $_repository = Git->repository(Repository => $ENV{GIT_DIR});
  331. }
  332. my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
  333. read_git_config(\%opts) if $ENV{GIT_DIR};
  334. if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
  335. Getopt::Long::Configure('pass_through');
  336. }
  337. my $rv = GetOptions(%opts, 'h|H' => \$_help, 'version|V' => \$_version,
  338. 'minimize-connections' => \$Git::SVN::Migration::_minimize,
  339. 'id|i=s' => \$Git::SVN::default_ref_id,
  340. 'svn-remote|remote|R=s' => sub {
  341. $Git::SVN::no_reuse_existing = 1;
  342. $Git::SVN::default_repo_id = $_[1] });
  343. exit 1 if (!$rv && $cmd && $cmd ne 'log');
  344. usage(0) if $_help;
  345. version() if $_version;
  346. usage(1) unless defined $cmd;
  347. load_authors() if $_authors;
  348. if (defined $_authors_prog) {
  349. $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
  350. }
  351. unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
  352. Git::SVN::Migration::migration_check();
  353. }
  354. Git::SVN::init_vars();
  355. eval {
  356. Git::SVN::verify_remotes_sanity();
  357. $cmd{$cmd}->[0]->(@ARGV);
  358. post_fetch_checkout();
  359. };
  360. fatal $@ if $@;
  361. exit 0;
  362. ####################### primary functions ######################
  363. sub usage {
  364. my $exit = shift || 0;
  365. my $fd = $exit ? \*STDERR : \*STDOUT;
  366. print $fd <<"";
  367. git-svn - bidirectional operations between a single Subversion tree and git
  368. usage: git svn <command> [options] [arguments]\n
  369. print $fd "Available commands:\n" unless $cmd;
  370. foreach (sort keys %cmd) {
  371. next if $cmd && $cmd ne $_;
  372. next if /^multi-/; # don't show deprecated commands
  373. print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
  374. foreach (sort keys %{$cmd{$_}->[2]}) {
  375. # mixed-case options are for .git/config only
  376. next if /[A-Z]/ && /^[a-z]+$/i;
  377. # prints out arguments as they should be passed:
  378. my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
  379. print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
  380. "--$_" : "-$_" }
  381. split /\|/,$_)," $x\n";
  382. }
  383. }
  384. print $fd <<"";
  385. \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
  386. arbitrary identifier if you're tracking multiple SVN branches/repositories in
  387. one git repository and want to keep them separate. See git-svn(1) for more
  388. information.
  389. exit $exit;
  390. }
  391. sub version {
  392. ::_req_svn();
  393. print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
  394. exit 0;
  395. }
  396. sub ask {
  397. my ($prompt, %arg) = @_;
  398. my $valid_re = $arg{valid_re};
  399. my $default = $arg{default};
  400. my $resp;
  401. my $i = 0;
  402. term_init() unless $term;
  403. if ( !( defined($term->IN)
  404. && defined( fileno($term->IN) )
  405. && defined( $term->OUT )
  406. && defined( fileno($term->OUT) ) ) ){
  407. return defined($default) ? $default : undef;
  408. }
  409. while ($i++ < 10) {
  410. $resp = $term->readline($prompt);
  411. if (!defined $resp) { # EOF
  412. print "\n";
  413. return defined $default ? $default : undef;
  414. }
  415. if ($resp eq '' and defined $default) {
  416. return $default;
  417. }
  418. if (!defined $valid_re or $resp =~ /$valid_re/) {
  419. return $resp;
  420. }
  421. }
  422. return undef;
  423. }
  424. sub do_git_init_db {
  425. unless (-d $ENV{GIT_DIR}) {
  426. my @init_db = ('init');
  427. push @init_db, "--template=$_template" if defined $_template;
  428. if (defined $_shared) {
  429. if ($_shared =~ /[a-z]/) {
  430. push @init_db, "--shared=$_shared";
  431. } else {
  432. push @init_db, "--shared";
  433. }
  434. }
  435. command_noisy(@init_db);
  436. $_repository = Git->repository(Repository => ".git");
  437. }
  438. my $set;
  439. my $pfx = "svn-remote.$Git::SVN::default_repo_id";
  440. foreach my $i (keys %icv) {
  441. die "'$set' and '$i' cannot both be set\n" if $set;
  442. next unless defined $icv{$i};
  443. command_noisy('config', "$pfx.$i", $icv{$i});
  444. $set = $i;
  445. }
  446. my $ignore_paths_regex = \$Git::SVN::Fetcher::_ignore_regex;
  447. command_noisy('config', "$pfx.ignore-paths", $$ignore_paths_regex)
  448. if defined $$ignore_paths_regex;
  449. my $include_paths_regex = \$Git::SVN::Fetcher::_include_regex;
  450. command_noisy('config', "$pfx.include-paths", $$include_paths_regex)
  451. if defined $$include_paths_regex;
  452. my $ignore_refs_regex = \$Git::SVN::Ra::_ignore_refs_regex;
  453. command_noisy('config', "$pfx.ignore-refs", $$ignore_refs_regex)
  454. if defined $$ignore_refs_regex;
  455. if (defined $Git::SVN::Fetcher::_preserve_empty_dirs) {
  456. my $fname = \$Git::SVN::Fetcher::_placeholder_filename;
  457. command_noisy('config', "$pfx.preserve-empty-dirs", 'true');
  458. command_noisy('config', "$pfx.placeholder-filename", $$fname);
  459. }
  460. }
  461. sub init_subdir {
  462. my $repo_path = shift or return;
  463. mkpath([$repo_path]) unless -d $repo_path;
  464. chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
  465. $ENV{GIT_DIR} = '.git';
  466. $_repository = Git->repository(Repository => $ENV{GIT_DIR});
  467. }
  468. sub cmd_clone {
  469. my ($url, $path) = @_;
  470. if (!$url) {
  471. die "SVN repository location required ",
  472. "as a command-line argument\n";
  473. } elsif (!defined $path &&
  474. (defined $_trunk || @_branches || @_tags ||
  475. defined $_stdlayout) &&
  476. $url !~ m#^[a-z\+]+://#) {
  477. $path = $url;
  478. }
  479. $path = basename($url) if !defined $path || !length $path;
  480. my $authors_absolute = $_authors ? File::Spec->rel2abs($_authors) : "";
  481. cmd_init($url, $path);
  482. command_oneline('config', 'svn.authorsfile', $authors_absolute)
  483. if $_authors;
  484. Git::SVN::fetch_all($Git::SVN::default_repo_id);
  485. }
  486. sub cmd_init {
  487. if (defined $_stdlayout) {
  488. $_trunk = 'trunk' if (!defined $_trunk);
  489. @_tags = 'tags' if (! @_tags);
  490. @_branches = 'branches' if (! @_branches);
  491. }
  492. if (defined $_trunk || @_branches || @_tags) {
  493. return cmd_multi_init(@_);
  494. }
  495. my $url = shift or die "SVN repository location required ",
  496. "as a command-line argument\n";
  497. $url = canonicalize_url($url);
  498. init_subdir(@_);
  499. do_git_init_db();
  500. if ($Git::SVN::_minimize_url eq 'unset') {
  501. $Git::SVN::_minimize_url = 0;
  502. }
  503. Git::SVN->init($url);
  504. }
  505. sub cmd_fetch {
  506. if (grep /^\d+=./, @_) {
  507. die "'<rev>=<commit>' fetch arguments are ",
  508. "no longer supported.\n";
  509. }
  510. my ($remote) = @_;
  511. if (@_ > 1) {
  512. die "usage: $0 fetch [--all] [--parent] [svn-remote]\n";
  513. }
  514. $Git::SVN::no_reuse_existing = undef;
  515. if ($_fetch_parent) {
  516. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  517. unless ($gs) {
  518. die "Unable to determine upstream SVN information from ",
  519. "working tree history\n";
  520. }
  521. # just fetch, don't checkout.
  522. $_no_checkout = 'true';
  523. $_fetch_all ? $gs->fetch_all : $gs->fetch;
  524. } elsif ($_fetch_all) {
  525. cmd_multi_fetch();
  526. } else {
  527. $remote ||= $Git::SVN::default_repo_id;
  528. Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
  529. }
  530. }
  531. sub cmd_set_tree {
  532. my (@commits) = @_;
  533. if ($_stdin || !@commits) {
  534. print "Reading from stdin...\n";
  535. @commits = ();
  536. while (<STDIN>) {
  537. if (/\b($sha1_short)\b/o) {
  538. unshift @commits, $1;
  539. }
  540. }
  541. }
  542. my @revs;
  543. foreach my $c (@commits) {
  544. my @tmp = command('rev-parse',$c);
  545. if (scalar @tmp == 1) {
  546. push @revs, $tmp[0];
  547. } elsif (scalar @tmp > 1) {
  548. push @revs, reverse(command('rev-list',@tmp));
  549. } else {
  550. fatal "Failed to rev-parse $c";
  551. }
  552. }
  553. my $gs = Git::SVN->new;
  554. my ($r_last, $cmt_last) = $gs->last_rev_commit;
  555. $gs->fetch;
  556. if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
  557. fatal "There are new revisions that were fetched ",
  558. "and need to be merged (or acknowledged) ",
  559. "before committing.\nlast rev: $r_last\n",
  560. " current: $gs->{last_rev}";
  561. }
  562. $gs->set_tree($_) foreach @revs;
  563. print "Done committing ",scalar @revs," revisions to SVN\n";
  564. unlink $gs->{index};
  565. }
  566. sub split_merge_info_range {
  567. my ($range) = @_;
  568. if ($range =~ /(\d+)-(\d+)/) {
  569. return (int($1), int($2));
  570. } else {
  571. return (int($range), int($range));
  572. }
  573. }
  574. sub combine_ranges {
  575. my ($in) = @_;
  576. my @fnums = ();
  577. my @arr = split(/,/, $in);
  578. for my $element (@arr) {
  579. my ($start, $end) = split_merge_info_range($element);
  580. push @fnums, $start;
  581. }
  582. my @sorted = @arr [ sort {
  583. $fnums[$a] <=> $fnums[$b]
  584. } 0..$#arr ];
  585. my @return = ();
  586. my $last = -1;
  587. my $first = -1;
  588. for my $element (@sorted) {
  589. my ($start, $end) = split_merge_info_range($element);
  590. if ($last == -1) {
  591. $first = $start;
  592. $last = $end;
  593. next;
  594. }
  595. if ($start <= $last+1) {
  596. if ($end > $last) {
  597. $last = $end;
  598. }
  599. next;
  600. }
  601. if ($first == $last) {
  602. push @return, "$first";
  603. } else {
  604. push @return, "$first-$last";
  605. }
  606. $first = $start;
  607. $last = $end;
  608. }
  609. if ($first != -1) {
  610. if ($first == $last) {
  611. push @return, "$first";
  612. } else {
  613. push @return, "$first-$last";
  614. }
  615. }
  616. return join(',', @return);
  617. }
  618. sub merge_revs_into_hash {
  619. my ($hash, $minfo) = @_;
  620. my @lines = split(' ', $minfo);
  621. for my $line (@lines) {
  622. my ($branchpath, $revs) = split(/:/, $line);
  623. if (exists($hash->{$branchpath})) {
  624. # Merge the two revision sets
  625. my $combined = "$hash->{$branchpath},$revs";
  626. $hash->{$branchpath} = combine_ranges($combined);
  627. } else {
  628. # Just do range combining for consolidation
  629. $hash->{$branchpath} = combine_ranges($revs);
  630. }
  631. }
  632. }
  633. sub merge_merge_info {
  634. my ($mergeinfo_one, $mergeinfo_two, $ignore_branch) = @_;
  635. my %result_hash = ();
  636. merge_revs_into_hash(\%result_hash, $mergeinfo_one);
  637. merge_revs_into_hash(\%result_hash, $mergeinfo_two);
  638. delete $result_hash{$ignore_branch} if $ignore_branch;
  639. my $result = '';
  640. # Sort below is for consistency's sake
  641. for my $branchname (sort keys(%result_hash)) {
  642. my $revlist = $result_hash{$branchname};
  643. $result .= "$branchname:$revlist\n"
  644. }
  645. return $result;
  646. }
  647. sub populate_merge_info {
  648. my ($d, $gs, $uuid, $linear_refs, $rewritten_parent) = @_;
  649. my %parentshash;
  650. read_commit_parents(\%parentshash, $d);
  651. my @parents = @{$parentshash{$d}};
  652. if ($#parents > 0) {
  653. # Merge commit
  654. my $all_parents_ok = 1;
  655. my $aggregate_mergeinfo = '';
  656. my $rooturl = $gs->repos_root;
  657. my ($target_branch) = $gs->full_pushurl =~ /^\Q$rooturl\E(.*)/;
  658. if (defined($rewritten_parent)) {
  659. # Replace first parent with newly-rewritten version
  660. shift @parents;
  661. unshift @parents, $rewritten_parent;
  662. }
  663. foreach my $parent (@parents) {
  664. my ($branchurl, $svnrev, $paruuid) =
  665. cmt_metadata($parent);
  666. unless (defined($svnrev)) {
  667. # Should have been caught be preflight check
  668. fatal "merge commit $d has ancestor $parent, but that change "
  669. ."does not have git-svn metadata!";
  670. }
  671. unless ($branchurl =~ /^\Q$rooturl\E(.*)/) {
  672. fatal "commit $parent git-svn metadata changed mid-run!";
  673. }
  674. my $branchpath = $1;
  675. my $ra = Git::SVN::Ra->new($branchurl);
  676. my (undef, undef, $props) =
  677. $ra->get_dir(canonicalize_path("."), $svnrev);
  678. my $par_mergeinfo = $props->{'svn:mergeinfo'};
  679. unless (defined $par_mergeinfo) {
  680. $par_mergeinfo = '';
  681. }
  682. # Merge previous mergeinfo values
  683. $aggregate_mergeinfo =
  684. merge_merge_info($aggregate_mergeinfo,
  685. $par_mergeinfo,
  686. $target_branch);
  687. next if $parent eq $parents[0]; # Skip first parent
  688. # Add new changes being placed in tree by merge
  689. my @cmd = (qw/rev-list --reverse/,
  690. $parent, qw/--not/);
  691. foreach my $par (@parents) {
  692. unless ($par eq $parent) {
  693. push @cmd, $par;
  694. }
  695. }
  696. my @revsin = ();
  697. my ($revlist, $ctx) = command_output_pipe(@cmd);
  698. while (<$revlist>) {
  699. my $irev = $_;
  700. chomp $irev;
  701. my (undef, $csvnrev, undef) =
  702. cmt_metadata($irev);
  703. unless (defined $csvnrev) {
  704. # A child is missing SVN annotations...
  705. # this might be OK, or might not be.
  706. warn "W:child $irev is merged into revision "
  707. ."$d but does not have git-svn metadata. "
  708. ."This means git-svn cannot determine the "
  709. ."svn revision numbers to place into the "
  710. ."svn:mergeinfo property. You must ensure "
  711. ."a branch is entirely committed to "
  712. ."SVN before merging it in order for "
  713. ."svn:mergeinfo population to function "
  714. ."properly";
  715. }
  716. push @revsin, $csvnrev;
  717. }
  718. command_close_pipe($revlist, $ctx);
  719. last unless $all_parents_ok;
  720. # We now have a list of all SVN revnos which are
  721. # merged by this particular parent. Integrate them.
  722. next if $#revsin == -1;
  723. my $newmergeinfo = "$branchpath:" . join(',', @revsin);
  724. $aggregate_mergeinfo =
  725. merge_merge_info($aggregate_mergeinfo,
  726. $newmergeinfo,
  727. $target_branch);
  728. }
  729. if ($all_parents_ok and $aggregate_mergeinfo) {
  730. return $aggregate_mergeinfo;
  731. }
  732. }
  733. return undef;
  734. }
  735. sub dcommit_rebase {
  736. my ($is_last, $current, $fetched_ref, $svn_error) = @_;
  737. my @diff;
  738. if ($svn_error) {
  739. print STDERR "\nERROR from SVN:\n",
  740. $svn_error->expanded_message, "\n";
  741. }
  742. unless ($_no_rebase) {
  743. # we always want to rebase against the current HEAD,
  744. # not any head that was passed to us
  745. @diff = command('diff-tree', $current,
  746. $fetched_ref, '--');
  747. my @finish;
  748. if (@diff) {
  749. @finish = rebase_cmd();
  750. print STDERR "W: $current and ", $fetched_ref,
  751. " differ, using @finish:\n",
  752. join("\n", @diff), "\n";
  753. } elsif ($is_last) {
  754. print "No changes between ", $current, " and ",
  755. $fetched_ref,
  756. "\nResetting to the latest ",
  757. $fetched_ref, "\n";
  758. @finish = qw/reset --mixed/;
  759. }
  760. command_noisy(@finish, $fetched_ref) if @finish;
  761. }
  762. if ($svn_error) {
  763. die "ERROR: Not all changes have been committed into SVN"
  764. .($_no_rebase ? ".\n" : ", however the committed\n"
  765. ."ones (if any) seem to be successfully integrated "
  766. ."into the working tree.\n")
  767. ."Please see the above messages for details.\n";
  768. }
  769. return @diff;
  770. }
  771. sub cmd_dcommit {
  772. my $head = shift;
  773. command_noisy(qw/update-index --refresh/);
  774. git_cmd_try { command_oneline(qw/diff-index --quiet HEAD --/) }
  775. 'Cannot dcommit with a dirty index. Commit your changes first, '
  776. . "or stash them with `git stash'.\n";
  777. $head ||= 'HEAD';
  778. my $old_head;
  779. if ($head ne 'HEAD') {
  780. $old_head = eval {
  781. command_oneline([qw/symbolic-ref -q HEAD/])
  782. };
  783. if ($old_head) {
  784. $old_head =~ s{^refs/heads/}{};
  785. } else {
  786. $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
  787. }
  788. command(['checkout', $head], STDERR => 0);
  789. }
  790. my @refs;
  791. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
  792. unless ($gs) {
  793. die "Unable to determine upstream SVN information from ",
  794. "$head history.\nPerhaps the repository is empty.";
  795. }
  796. if (defined $_commit_url) {
  797. $url = $_commit_url;
  798. } else {
  799. $url = eval { command_oneline('config', '--get',
  800. "svn-remote.$gs->{repo_id}.commiturl") };
  801. if (!$url) {
  802. $url = $gs->full_pushurl
  803. }
  804. }
  805. my $last_rev = $_revision if defined $_revision;
  806. if ($url) {
  807. print "Committing to $url ...\n";
  808. }
  809. my ($linear_refs, $parents) = linearize_history($gs, \@refs);
  810. if ($_no_rebase && scalar(@$linear_refs) > 1) {
  811. warn "Attempting to commit more than one change while ",
  812. "--no-rebase is enabled.\n",
  813. "If these changes depend on each other, re-running ",
  814. "without --no-rebase may be required."
  815. }
  816. if (defined $_interactive){
  817. my $ask_default = "y";
  818. foreach my $d (@$linear_refs){
  819. my ($fh, $ctx) = command_output_pipe(qw(show --summary), "$d");
  820. while (<$fh>){
  821. print $_;
  822. }
  823. command_close_pipe($fh, $ctx);
  824. $_ = ask("Commit this patch to SVN? ([y]es (default)|[n]o|[q]uit|[a]ll): ",
  825. valid_re => qr/^(?:yes|y|no|n|quit|q|all|a)/i,
  826. default => $ask_default);
  827. die "Commit this patch reply required" unless defined $_;
  828. if (/^[nq]/i) {
  829. exit(0);
  830. } elsif (/^a/i) {
  831. last;
  832. }
  833. }
  834. }
  835. my $expect_url = $url;
  836. my $push_merge_info = eval {
  837. command_oneline(qw/config --get svn.pushmergeinfo/)
  838. };
  839. if (not defined($push_merge_info)
  840. or $push_merge_info eq "false"
  841. or $push_merge_info eq "no"
  842. or $push_merge_info eq "never") {
  843. $push_merge_info = 0;
  844. }
  845. unless (defined($_merge_info) || ! $push_merge_info) {
  846. # Preflight check of changes to ensure no issues with mergeinfo
  847. # This includes check for uncommitted-to-SVN parents
  848. # (other than the first parent, which we will handle),
  849. # information from different SVN repos, and paths
  850. # which are not underneath this repository root.
  851. my $rooturl = $gs->repos_root;
  852. foreach my $d (@$linear_refs) {
  853. my %parentshash;
  854. read_commit_parents(\%parentshash, $d);
  855. my @realparents = @{$parentshash{$d}};
  856. if ($#realparents > 0) {
  857. # Merge commit
  858. shift @realparents; # Remove/ignore first parent
  859. foreach my $parent (@realparents) {
  860. my ($branchurl, $svnrev, $paruuid) = cmt_metadata($parent);
  861. unless (defined $paruuid) {
  862. # A parent is missing SVN annotations...
  863. # abort the whole operation.
  864. fatal "$parent is merged into revision $d, "
  865. ."but does not have git-svn metadata. "
  866. ."Either dcommit the branch or use a "
  867. ."local cherry-pick, FF merge, or rebase "
  868. ."instead of an explicit merge commit.";
  869. }
  870. unless ($paruuid eq $uuid) {
  871. # Parent has SVN metadata from different repository
  872. fatal "merge parent $parent for change $d has "
  873. ."git-svn uuid $paruuid, while current change "
  874. ."has uuid $uuid!";
  875. }
  876. unless ($branchurl =~ /^\Q$rooturl\E(.*)/) {
  877. # This branch is very strange indeed.
  878. fatal "merge parent $parent for $d is on branch "
  879. ."$branchurl, which is not under the "
  880. ."git-svn root $rooturl!";
  881. }
  882. }
  883. }
  884. }
  885. }
  886. my $rewritten_parent;
  887. my $current_head = command_oneline(qw/rev-parse HEAD/);
  888. Git::SVN::remove_username($expect_url);
  889. if (defined($_merge_info)) {
  890. $_merge_info =~ tr{ }{\n};
  891. }
  892. while (1) {
  893. my $d = shift @$linear_refs or last;
  894. unless (defined $last_rev) {
  895. (undef, $last_rev, undef) = cmt_metadata("$d~1");
  896. unless (defined $last_rev) {
  897. fatal "Unable to extract revision information ",
  898. "from commit $d~1";
  899. }
  900. }
  901. if ($_dry_run) {
  902. print "diff-tree $d~1 $d\n";
  903. } else {
  904. my $cmt_rev;
  905. unless (defined($_merge_info) || ! $push_merge_info) {
  906. $_merge_info = populate_merge_info($d, $gs,
  907. $uuid,
  908. $linear_refs,
  909. $rewritten_parent);
  910. }
  911. my %ed_opts = ( r => $last_rev,
  912. log => get_commit_entry($d)->{log},
  913. ra => Git::SVN::Ra->new($url),
  914. config => SVN::Core::config_get_config(
  915. $Git::SVN::Ra::config_dir
  916. ),
  917. tree_a => "$d~1",
  918. tree_b => $d,
  919. editor_cb => sub {
  920. print "Committed r$_[0]\n";
  921. $cmt_rev = $_[0];
  922. },
  923. mergeinfo => $_merge_info,
  924. svn_path => '');
  925. my $err_handler = $SVN::Error::handler;
  926. $SVN::Error::handler = sub {
  927. my $err = shift;
  928. dcommit_rebase(1, $current_head, $gs->refname,
  929. $err);
  930. };
  931. if (!Git::SVN::Editor->new(\%ed_opts)->apply_diff) {
  932. print "No changes\n$d~1 == $d\n";
  933. } elsif ($parents->{$d} && @{$parents->{$d}}) {
  934. $gs->{inject_parents_dcommit}->{$cmt_rev} =
  935. $parents->{$d};
  936. }
  937. $_fetch_all ? $gs->fetch_all : $gs->fetch;
  938. $SVN::Error::handler = $err_handler;
  939. $last_rev = $cmt_rev;
  940. next if $_no_rebase;
  941. my @diff = dcommit_rebase(@$linear_refs == 0, $d,
  942. $gs->refname, undef);
  943. $rewritten_parent = command_oneline(qw/rev-parse/,
  944. $gs->refname);
  945. if (@diff) {
  946. $current_head = command_oneline(qw/rev-parse
  947. HEAD/);
  948. @refs = ();
  949. my ($url_, $rev_, $uuid_, $gs_) =
  950. working_head_info('HEAD', \@refs);
  951. my ($linear_refs_, $parents_) =
  952. linearize_history($gs_, \@refs);
  953. if (scalar(@$linear_refs) !=
  954. scalar(@$linear_refs_)) {
  955. fatal "# of revisions changed ",
  956. "\nbefore:\n",
  957. join("\n", @$linear_refs),
  958. "\n\nafter:\n",
  959. join("\n", @$linear_refs_), "\n",
  960. 'If you are attempting to commit ',
  961. "merges, try running:\n\t",
  962. 'git rebase --interactive',
  963. '--preserve-merges ',
  964. $gs->refname,
  965. "\nBefore dcommitting";
  966. }
  967. if ($url_ ne $expect_url) {
  968. if ($url_ eq $gs->metadata_url) {
  969. print
  970. "Accepting rewritten URL:",
  971. " $url_\n";
  972. } else {
  973. fatal
  974. "URL mismatch after rebase:",
  975. " $url_ != $expect_url";
  976. }
  977. }
  978. if ($uuid_ ne $uuid) {
  979. fatal "uuid mismatch after rebase: ",
  980. "$uuid_ != $uuid";
  981. }
  982. # remap parents
  983. my (%p, @l, $i);
  984. for ($i = 0; $i < scalar @$linear_refs; $i++) {
  985. my $new = $linear_refs_->[$i] or next;
  986. $p{$new} =
  987. $parents->{$linear_refs->[$i]};
  988. push @l, $new;
  989. }
  990. $parents = \%p;
  991. $linear_refs = \@l;
  992. undef $last_rev;
  993. }
  994. }
  995. }
  996. if ($old_head) {
  997. my $new_head = command_oneline(qw/rev-parse HEAD/);
  998. my $new_is_symbolic = eval {
  999. command_oneline(qw/symbolic-ref -q HEAD/);
  1000. };
  1001. if ($new_is_symbolic) {
  1002. print "dcommitted the branch ", $head, "\n";
  1003. } else {
  1004. print "dcommitted on a detached HEAD because you gave ",
  1005. "a revision argument.\n",
  1006. "The rewritten commit is: ", $new_head, "\n";
  1007. }
  1008. command(['checkout', $old_head], STDERR => 0);
  1009. }
  1010. unlink $gs->{index};
  1011. }
  1012. sub cmd_branch {
  1013. my ($branch_name, $head) = @_;
  1014. unless (defined $branch_name && length $branch_name) {
  1015. die(($_tag ? "tag" : "branch") . " name required\n");
  1016. }
  1017. $head ||= 'HEAD';
  1018. my (undef, $rev, undef, $gs) = working_head_info($head);
  1019. my $src = $gs->full_pushurl;
  1020. my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
  1021. my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
  1022. my $glob;
  1023. if ($#{$allglobs} == 0) {
  1024. $glob = $allglobs->[0];
  1025. } else {
  1026. unless(defined $_branch_dest) {
  1027. die "Multiple ",
  1028. $_tag ? "tag" : "branch",
  1029. " paths defined for Subversion repository.\n",
  1030. "You must specify where you want to create the ",
  1031. $_tag ? "tag" : "branch",
  1032. " with the --destination argument.\n";
  1033. }
  1034. foreach my $g (@{$allglobs}) {
  1035. my $re = Git::SVN::Editor::glob2pat($g->{path}->{left});
  1036. if ($_branch_dest =~ /$re/) {
  1037. $glob = $g;
  1038. last;
  1039. }
  1040. }
  1041. unless (defined $glob) {
  1042. my $dest_re = qr/\b\Q$_branch_dest\E\b/;
  1043. foreach my $g (@{$allglobs}) {
  1044. $g->{path}->{left} =~ /$dest_re/ or next;
  1045. if (defined $glob) {
  1046. die "Ambiguous destination: ",
  1047. $_branch_dest, "\nmatches both '",
  1048. $glob->{path}->{left}, "' and '",
  1049. $g->{path}->{left}, "'\n";
  1050. }
  1051. $glob = $g;
  1052. }
  1053. unless (defined $glob) {
  1054. die "Unknown ",
  1055. $_tag ? "tag" : "branch",
  1056. " destination $_branch_dest\n";
  1057. }
  1058. }
  1059. }
  1060. my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
  1061. my $url;
  1062. if (defined $_commit_url) {
  1063. $url = $_commit_url;
  1064. } else {
  1065. $url = eval { command_oneline('config', '--get',
  1066. "svn-remote.$gs->{repo_id}.commiturl") };
  1067. if (!$url) {
  1068. $url = $remote->{pushurl} || $remote->{url};
  1069. }
  1070. }
  1071. my $dst = join '/', $url, $lft, $branch_name, ($rgt || ());
  1072. if ($dst =~ /^https:/ && $src =~ /^http:/) {
  1073. $src=~s/^http:/https:/;
  1074. }
  1075. ::_req_svn();
  1076. require SVN::Client;
  1077. my $ctx = SVN::Client->new(
  1078. config => SVN::Core::config_get_config(
  1079. $Git::SVN::Ra::config_dir
  1080. ),
  1081. log_msg => sub {
  1082. ${ $_[0] } = defined $_message
  1083. ? $_message
  1084. : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
  1085. . $branch_name;
  1086. },
  1087. );
  1088. eval {
  1089. $ctx->ls($dst, 'HEAD', 0);
  1090. } and die "branch ${branch_name} already exists\n";
  1091. if ($_parents) {
  1092. mk_parent_dirs($ctx, $dst);
  1093. }
  1094. print "Copying ${src} at r${rev} to ${dst}...\n";
  1095. $ctx->copy($src, $rev, $dst)
  1096. unless $_dry_run;
  1097. $gs->fetch_all;
  1098. }
  1099. sub mk_parent_dirs {
  1100. my ($ctx, $parent) = @_;
  1101. $parent =~ s{/[^/]*$}{};
  1102. if (!eval{$ctx->ls($parent, 'HEAD', 0)}) {
  1103. mk_parent_dirs($ctx, $parent);
  1104. print "Creating parent folder ${parent} ...\n";
  1105. $ctx->mkdir($parent) unless $_dry_run;
  1106. }
  1107. }
  1108. sub cmd_find_rev {
  1109. my $revision_or_hash = shift or die "SVN or git revision required ",
  1110. "as a command-line argument\n";
  1111. my $result;
  1112. if ($revision_or_hash =~ /^r\d+$/) {
  1113. my $head = shift;
  1114. $head ||= 'HEAD';
  1115. my @refs;
  1116. my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
  1117. unless ($gs) {
  1118. die "Unable to determine upstream SVN information from ",
  1119. "$head history\n";
  1120. }
  1121. my $desired_revision = substr($revision_or_hash, 1);
  1122. if ($_before) {
  1123. $result = $gs->find_rev_before($desired_revision, 1);
  1124. } elsif ($_after) {
  1125. $result = $gs->find_rev_after($desired_revision, 1);
  1126. } else {
  1127. $result = $gs->rev_map_get($desired_revision, $uuid);
  1128. }
  1129. } else {
  1130. my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
  1131. $result = $rev;
  1132. }
  1133. print "$result\n" if $result;
  1134. }
  1135. sub auto_create_empty_directories {
  1136. my ($gs) = @_;
  1137. my $var = eval { command_oneline('config', '--get', '--bool',
  1138. "svn-remote.$gs->{repo_id}.automkdirs") };
  1139. # By default, create empty directories by consulting the unhandled log,
  1140. # but allow setting it to 'false' to skip it.
  1141. return !($var && $var eq 'false');
  1142. }
  1143. sub cmd_rebase {
  1144. command_noisy(qw/update-index --refresh/);
  1145. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  1146. unless ($gs) {
  1147. die "Unable to determine upstream SVN information from ",
  1148. "working tree history\n";
  1149. }
  1150. if ($_dry_run) {
  1151. print "Remote Branch: " . $gs->refname . "\n";
  1152. print "SVN URL: " . $url . "\n";
  1153. return;
  1154. }
  1155. if (command(qw/diff-index HEAD --/)) {
  1156. print STDERR "Cannot rebase with uncommitted changes:\n";
  1157. command_noisy('status');
  1158. exit 1;
  1159. }
  1160. unless ($_local) {
  1161. # rebase will checkout for us, so no need to do it explicitly
  1162. $_no_checkout = 'true';
  1163. $_fetch_all ? $gs->fetch_all : $gs->fetch;
  1164. }
  1165. command_noisy(rebase_cmd(), $gs->refname);
  1166. if (auto_create_empty_directories($gs)) {
  1167. $gs->mkemptydirs;
  1168. }
  1169. }
  1170. sub cmd_show_ignore {
  1171. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  1172. $gs ||= Git::SVN->new;
  1173. my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
  1174. $gs->prop_walk($gs->path, $r, sub {
  1175. my ($gs, $path, $props) = @_;
  1176. print STDOUT "\n# $path\n";
  1177. my $s = $props->{'svn:ignore'} or return;
  1178. $s =~ s/[\r\n]+/\n/g;
  1179. $s =~ s/^\n+//;
  1180. chomp $s;
  1181. $s =~ s#^#$path#gm;
  1182. print STDOUT "$s\n";
  1183. });
  1184. }
  1185. sub cmd_show_externals {
  1186. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  1187. $gs ||= Git::SVN->new;
  1188. my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
  1189. $gs->prop_walk($gs->path, $r, sub {
  1190. my ($gs, $path, $props) = @_;
  1191. print STDOUT "\n# $path\n";
  1192. my $s = $props->{'svn:externals'} or return;
  1193. $s =~ s/[\r\n]+/\n/g;
  1194. chomp $s;
  1195. $s =~ s#^#$path#gm;
  1196. print STDOUT "$s\n";
  1197. });
  1198. }
  1199. sub cmd_create_ignore {
  1200. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  1201. $gs ||= Git::SVN->new;
  1202. my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
  1203. $gs->prop_walk($gs->path, $r, sub {
  1204. my ($gs, $path, $props) = @_;
  1205. # $path is of the form /path/to/dir/
  1206. $path = '.' . $path;
  1207. # SVN can have attributes on empty directories,
  1208. # which git won't track
  1209. mkpath([$path]) unless -d $path;
  1210. my $ignore = $path . '.gitignore';
  1211. my $s = $props->{'svn:ignore'} or return;
  1212. open(GITIGNORE, '>', $ignore)
  1213. or fatal("Failed to open `$ignore' for writing: $!");
  1214. $s =~ s/[\r\n]+/\n/g;
  1215. $s =~ s/^\n+//;
  1216. chomp $s;
  1217. # Prefix all patterns so that the ignore doesn't apply
  1218. # to sub-directories.
  1219. $s =~ s#^#/#gm;
  1220. print GITIGNORE "$s\n";
  1221. close(GITIGNORE)
  1222. or fatal("Failed to close `$ignore': $!");
  1223. command_noisy('add', '-f', $ignore);
  1224. });
  1225. }
  1226. sub cmd_mkdirs {
  1227. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  1228. $gs ||= Git::SVN->new;
  1229. $gs->mkemptydirs($_revision);
  1230. }
  1231. # get_svnprops(PATH)
  1232. # ------------------
  1233. # Helper for cmd_propget and cmd_proplist below.
  1234. sub get_svnprops {
  1235. my $path = shift;
  1236. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  1237. $gs ||= Git::SVN->new;
  1238. # prefix THE PATH by the sub-directory from which the user
  1239. # invoked us.
  1240. $path = $cmd_dir_prefix . $path;
  1241. fatal("No such file or directory: $path") unless -e $path;
  1242. my $is_dir = -d $path ? 1 : 0;
  1243. $path = join_paths($gs->path, $path);
  1244. # canonicalize the path (otherwise libsvn will abort or fail to
  1245. # find the file)
  1246. $path = canonicalize_path($path);
  1247. my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
  1248. my $props;
  1249. if ($is_dir) {
  1250. (undef, undef, $props) = $gs->ra->get_dir($path, $r);
  1251. }
  1252. else {
  1253. (undef, $props) = $gs->ra->get_file($path, $r, undef);
  1254. }
  1255. return $props;
  1256. }
  1257. # cmd_propget (PROP, PATH)
  1258. # ------------------------
  1259. # Print the SVN property PROP for PATH.
  1260. sub cmd_propget {
  1261. my ($prop, $path) = @_;
  1262. $path = '.' if not defined $path;
  1263. usage(1) if not defined $prop;
  1264. my $props = get_svnprops($path);
  1265. if (not defined $props->{$prop}) {
  1266. fatal("`$path' does not have a `$prop' SVN property.");
  1267. }
  1268. print $props->{$prop} . "\n";
  1269. }
  1270. # cmd_propset (PROPNAME, PROPVAL, PATH)
  1271. # ------------------------
  1272. # Adjust the SVN property PROPNAME to PROPVAL for PATH.
  1273. sub cmd_propset {
  1274. my ($propname, $propval, $path) = @_;
  1275. $path = '.' if not defined $path;
  1276. $path = $cmd_dir_prefix . $path;
  1277. usage(1) if not defined $propname;
  1278. usage(1) if not defined $propval;
  1279. my $file = basename($path);
  1280. my $dn = dirname($path);
  1281. my $cur_props = Git::SVN::Editor::check_attr( "svn-properties", $path );
  1282. my @new_props;
  1283. if (!$cur_props || $cur_props eq "unset" || $cur_props eq "" || $cur_props eq "set") {
  1284. push @new_props, "$propname=$propval";
  1285. } else {
  1286. # TODO: handle combining properties better
  1287. my @props = split(/;/, $cur_props);
  1288. my $replaced_prop;
  1289. foreach my $prop (@props) {
  1290. # Parse 'name=value' syntax and set the property.
  1291. if ($prop =~ /([^=]+)=(.*)/) {
  1292. my ($n,$v) = ($1,$2);
  1293. if ($n eq $propname) {
  1294. $v = $propval;
  1295. $replaced_prop = 1;
  1296. }
  1297. push @new_props, "$n=$v";
  1298. }
  1299. }
  1300. if (!$replaced_prop) {
  1301. push @new_props, "$propname=$propval";
  1302. }
  1303. }
  1304. my $attrfile = "$dn/.gitattributes";
  1305. open my $attrfh, '>>', $attrfile or die "Can't open $attrfile: $!\n";
  1306. # TODO: don't simply append here if $file already has svn-properties
  1307. my $new_props = join(';', @new_props);
  1308. print $attrfh "$file svn-properties=$new_props\n" or
  1309. die "write to $attrfile: $!\n";
  1310. close $attrfh or die "close $attrfile: $!\n";
  1311. }
  1312. # cmd_proplist (PATH)
  1313. # -------------------
  1314. # Print the list of SVN properties for PATH.
  1315. sub cmd_proplist {
  1316. my $path = shift;
  1317. $path = '.' if not defined $path;
  1318. my $props = get_svnprops($path);
  1319. print "Properties on '$path':\n";
  1320. foreach (sort keys %{$props}) {
  1321. print " $_\n";
  1322. }
  1323. }
  1324. sub cmd_multi_init {
  1325. my $url = shift;
  1326. unless (defined $_trunk || @_branches || @_tags) {
  1327. usage(1);
  1328. }
  1329. $_prefix = 'origin/' unless defined $_prefix;
  1330. if (defined $url) {
  1331. $url = canonicalize_url($url);
  1332. init_subdir(@_);
  1333. }
  1334. do_git_init_db();
  1335. if (defined $_trunk) {
  1336. $_trunk =~ s#^/+##;
  1337. my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
  1338. # try both old-style and new-style lookups:
  1339. my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
  1340. unless ($gs_trunk) {
  1341. my ($trunk_url, $trunk_path) =
  1342. complete_svn_url($url, $_trunk);
  1343. $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
  1344. undef, $trunk_ref);
  1345. }
  1346. }
  1347. return unless @_branches || @_tags;
  1348. my $ra = $url ? Git::SVN::Ra->new($url) : undef;
  1349. foreach my $path (@_branches) {
  1350. complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
  1351. }
  1352. foreach my $path (@_tags) {
  1353. complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
  1354. }
  1355. }
  1356. sub cmd_multi_fetch {
  1357. $Git::SVN::no_reuse_existing = undef;
  1358. my $remotes = Git::SVN::read_all_remotes();
  1359. foreach my $repo_id (sort keys %$remotes) {
  1360. if ($remotes->{$repo_id}->{url}) {
  1361. Git::SVN::fetch_all($repo_id, $remotes);
  1362. }
  1363. }
  1364. }
  1365. # this command is special because it requires no metadata
  1366. sub cmd_commit_diff {
  1367. my ($ta, $tb, $url) = @_;
  1368. my $usage = "usage: $0 commit-diff -r<revision> ".
  1369. "<tree-ish> <tree-ish> [<URL>]";
  1370. fatal($usage) if (!defined $ta || !defined $tb);
  1371. my $svn_path = '';
  1372. if (!defined $url) {
  1373. my $gs = eval { Git::SVN->new };
  1374. if (!$gs) {
  1375. fatal("Needed URL or usable git-svn --id in ",
  1376. "the command-line\n", $usage);
  1377. }
  1378. $url = $gs->url;
  1379. $svn_path = $gs->path;
  1380. }
  1381. unless (defined $_revision) {
  1382. fatal("-r|--revision is a required argument\n", $usage);
  1383. }
  1384. if (defined $_message && defined $_file) {
  1385. fatal("Both --message/-m and --file/-F specified ",
  1386. "for the commit message.\n",
  1387. "I have no idea what you mean");
  1388. }
  1389. if (defined $_file) {
  1390. $_message = file_to_s($_file);
  1391. } else {
  1392. $_message ||= get_commit_entry($tb)->{log};
  1393. }
  1394. my $ra ||= Git::SVN::Ra->new($url);
  1395. my $r = $_revision;
  1396. if ($r eq 'HEAD') {
  1397. $r = $ra->get_latest_revnum;
  1398. } elsif ($r !~ /^\d+$/) {
  1399. die "revision argument: $r not understood by git-svn\n";
  1400. }
  1401. my %ed_opts = ( r => $r,
  1402. log => $_message,
  1403. ra => $ra,
  1404. tree_a => $ta,
  1405. tree_b => $tb,
  1406. editor_cb => sub { print "Committed r$_[0]\n" },
  1407. svn_path => $svn_path );
  1408. if (!Git::SVN::Editor->new(\%ed_opts)->apply_diff) {
  1409. print "No changes\n$ta == $tb\n";
  1410. }
  1411. }
  1412. sub cmd_info {
  1413. my $path_arg = defined($_[0]) ? $_[0] : '.';
  1414. my $path = $path_arg;
  1415. if (File::Spec->file_name_is_absolute($path)) {
  1416. $path = canonicalize_path($path);
  1417. my $toplevel = eval {
  1418. my @cmd = qw/rev-parse --show-toplevel/;
  1419. command_oneline(\@cmd, STDERR => 0);
  1420. };
  1421. # remove $toplevel from the absolute path:
  1422. my ($vol, $dirs, $file) = File::Spec->splitpath($path);
  1423. my (undef, $tdirs, $tfile) = File::Spec->splitpath($toplevel);
  1424. my @dirs = File::Spec->splitdir($dirs);
  1425. my @tdirs = File::Spec->splitdir($tdirs);
  1426. pop @dirs if $dirs[-1] eq '';
  1427. pop @tdirs if $tdirs[-1] eq '';
  1428. push @dirs, $file;
  1429. push @tdirs, $tfile;
  1430. while (@tdirs && @dirs && $tdirs[0] eq $dirs[0]) {
  1431. shift @dirs;
  1432. shift @tdirs;
  1433. }
  1434. $dirs = File::Spec->catdir(@dirs);
  1435. $path = File::Spec->catpath($vol, $dirs);
  1436. $path = canonicalize_path($path);
  1437. } else {
  1438. $path = canonicalize_path($cmd_dir_prefix . $path);
  1439. }
  1440. if (exists $_[1]) {
  1441. die "Too many arguments specified\n";
  1442. }
  1443. my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
  1444. if (!$file_type && !$diff_status) {
  1445. print STDERR "svn: '$path' is not under version control\n";
  1446. exit 1;
  1447. }
  1448. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  1449. unless ($gs) {
  1450. die "Unable to determine upstream SVN information from ",
  1451. "working tree history\n";
  1452. }
  1453. # canonicalize_path() will return "" to make libsvn 1.5.x happy,
  1454. $path = "." if $path eq "";
  1455. my $full_url = canonicalize_url( add_path_to_url( $url, $path ) );
  1456. if ($_url) {
  1457. print "$full_url\n";
  1458. return;
  1459. }
  1460. my $result = "Path: $path_arg\n";
  1461. $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
  1462. $result .= "URL: $full_url\n";
  1463. eval {
  1464. my $repos_root = $gs->repos_root;
  1465. Git::SVN::remove_username($repos_root);
  1466. $result .= "Repository Root: " . canonicalize_url($repos_root) . "\n";
  1467. };
  1468. if ($@) {
  1469. $result .= "Repository Root: (offline)\n";
  1470. }
  1471. ::_req_svn();
  1472. $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
  1473. (::compare_svn_version('1.5.4') <= 0 || $file_type ne "dir");
  1474. $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
  1475. $result .= "Node Kind: " .
  1476. ($file_type eq "dir" ? "directory" : "file") . "\n";
  1477. my $schedule = $diff_status eq "A"
  1478. ? "add"
  1479. : ($diff_status eq "D" ? "delete" : "normal");
  1480. $result .= "Schedule: $schedule\n";
  1481. if ($diff_status eq "A") {
  1482. print $result, "\n";
  1483. return;
  1484. }
  1485. my ($lc_author, $lc_rev, $lc_date_utc);
  1486. my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $path);
  1487. my $log = command_output_pipe(@args);
  1488. my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
  1489. while (<$log>) {
  1490. if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
  1491. $lc_author = $1;
  1492. $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
  1493. } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
  1494. (undef, $lc_rev, undef) = ::extract_metadata($1);
  1495. }
  1496. }
  1497. close $log;
  1498. Git::SVN::Log::set_local_timezone();
  1499. $result .= "Last Changed Author: $lc_author\n";
  1500. $result .= "Last Changed Rev: $lc_rev\n";
  1501. $result .= "Last Changed Date: " .
  1502. Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
  1503. if ($file_type ne "dir") {
  1504. my $text_last_updated_date =
  1505. ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
  1506. $result .=
  1507. "Text Last Updated: " .
  1508. Git::SVN::Log::format_svn_date($text_last_updated_date) .
  1509. "\n";
  1510. my $checksum;
  1511. if ($diff_status eq "D") {
  1512. my ($fh, $ctx) =
  1513. command_output_pipe(qw(cat-file blob), "HEAD:$path");
  1514. if ($file_type eq "link") {
  1515. my $file_name = <$fh>;
  1516. $checksum = md5sum("link $file_name");
  1517. } else {
  1518. $checksum = md5sum($fh);
  1519. }
  1520. command_close_pipe($fh, $ctx);
  1521. } elsif ($file_type eq "link") {
  1522. my $file_name =
  1523. command(qw(cat-file blob), "HEAD:$path");
  1524. $checksum =
  1525. md5sum("link " . $file_name);
  1526. } else {
  1527. open FILE, "<", $path or die $!;
  1528. $checksum = md5sum(\*FILE);
  1529. close FILE or die $!;
  1530. }
  1531. $result .= "Checksum: " . $checksum . "\n";
  1532. }
  1533. print $result, "\n";
  1534. }
  1535. sub cmd_reset {
  1536. my $target = shift || $_revision or die "SVN revision required\n";
  1537. $target = $1 if $target =~ /^r(\d+)$/;
  1538. $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
  1539. my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
  1540. unless ($gs) {
  1541. die "Unable to determine upstream SVN information from ".
  1542. "history\n";
  1543. }
  1544. my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
  1545. die "Cannot find SVN revision $target\n" unless defined($c);
  1546. $gs->rev_map_set($r, $c, 'reset', $uuid);
  1547. print "r$r = $c ($gs->{ref_id})\n";
  1548. }
  1549. sub cmd_gc {
  1550. require File::Find;
  1551. if (!can_compress()) {
  1552. warn "Compress::Zlib could not be found; unhandled.log " .
  1553. "files will not be compressed.\n";
  1554. }
  1555. File::Find::find({ wanted => \&gc_directory, no_chdir => 1},
  1556. "$ENV{GIT_DIR}/svn");
  1557. }
  1558. ########################### utility functions #########################
  1559. sub rebase_cmd {
  1560. my @cmd = qw/rebase/;
  1561. push @cmd, '-v' if $_verbose;
  1562. push @cmd, qw/--merge/ if $_merge;
  1563. push @cmd, "--strategy=$_strategy" if $_strategy;
  1564. push

Large files files are truncated, but you can click here to view the full file