PageRenderTime 64ms CodeModel.GetById 21ms RepoModel.GetById 1ms 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

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

  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

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