THIS IS A TEST INSTANCE ONLY! REPOSITORIES CAN BE DELETED AT ANY TIME!

Git Source Code Mirror - This is a publish-only repository and all pull requests are ignored. Please follow Documentation/SubmittingPatches procedure for any of your improvements.
git
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

1135 行
36KB

  1. #!/usr/bin/perl
  2. #
  3. # This tool is copyright (c) 2005, Martin Langhoff.
  4. # It is released under the Gnu Public License, version 2.
  5. #
  6. # The basic idea is to walk the output of tla abrowse,
  7. # fetch the changesets and apply them.
  8. #
  9. =head1 Invocation
  10. git archimport [ -h ] [ -v ] [ -o ] [ -a ] [ -f ] [ -T ]
  11. [ -D depth] [ -t tempdir ] <archive>/<branch> [ <archive>/<branch> ]
  12. Imports a project from one or more Arch repositories. It will follow branches
  13. and repositories within the namespaces defined by the <archive/branch>
  14. parameters supplied. If it cannot find the remote branch a merge comes from
  15. it will just import it as a regular commit. If it can find it, it will mark it
  16. as a merge whenever possible.
  17. See man (1) git-archimport for more details.
  18. =head1 TODO
  19. - create tag objects instead of ref tags
  20. - audit shell-escaping of filenames
  21. - hide our private tags somewhere smarter
  22. - find a way to make "cat *patches | patch" safe even when patchfiles are missing newlines
  23. - sort and apply patches by graphing ancestry relations instead of just
  24. relying in dates supplied in the changeset itself.
  25. tla ancestry-graph -m could be helpful here...
  26. =head1 Devel tricks
  27. Add print in front of the shell commands invoked via backticks.
  28. =head1 Devel Notes
  29. There are several places where Arch and git terminology are intermixed
  30. and potentially confused.
  31. The notion of a "branch" in git is approximately equivalent to
  32. a "archive/category--branch--version" in Arch. Also, it should be noted
  33. that the "--branch" portion of "archive/category--branch--version" is really
  34. optional in Arch although not many people (nor tools!) seem to know this.
  35. This means that "archive/category--version" is also a valid "branch"
  36. in git terms.
  37. We always refer to Arch names by their fully qualified variant (which
  38. means the "archive" name is prefixed.
  39. For people unfamiliar with Arch, an "archive" is the term for "repository",
  40. and can contain multiple, unrelated branches.
  41. =cut
  42. use 5.008;
  43. use strict;
  44. use warnings;
  45. use Getopt::Std;
  46. use File::Temp qw(tempdir);
  47. use File::Path qw(mkpath rmtree);
  48. use File::Basename qw(basename dirname);
  49. use Data::Dumper qw/ Dumper /;
  50. use IPC::Open2;
  51. $SIG{'PIPE'}="IGNORE";
  52. $ENV{'TZ'}="UTC";
  53. my $git_dir = $ENV{"GIT_DIR"} || ".git";
  54. $ENV{"GIT_DIR"} = $git_dir;
  55. my $ptag_dir = "$git_dir/archimport/tags";
  56. our($opt_h,$opt_f,$opt_v,$opt_T,$opt_t,$opt_D,$opt_a,$opt_o);
  57. sub usage() {
  58. print STDERR <<END;
  59. usage: git archimport # fetch/update GIT from Arch
  60. [ -h ] [ -v ] [ -o ] [ -a ] [ -f ] [ -T ] [ -D depth ] [ -t tempdir ]
  61. repository/arch-branch [ repository/arch-branch] ...
  62. END
  63. exit(1);
  64. }
  65. getopts("fThvat:D:") or usage();
  66. usage if $opt_h;
  67. @ARGV >= 1 or usage();
  68. # $arch_branches:
  69. # values associated with keys:
  70. # =1 - Arch version / git 'branch' detected via abrowse on a limit
  71. # >1 - Arch version / git 'branch' of an auxiliary branch we've merged
  72. my %arch_branches = map { my $branch = $_; $branch =~ s/:[^:]*$//; $branch => 1 } @ARGV;
  73. # $branch_name_map:
  74. # maps arch branches to git branch names
  75. my %branch_name_map = map { m/^(.*):([^:]*)$/; $1 => $2 } grep { m/:/ } @ARGV;
  76. $ENV{'TMPDIR'} = $opt_t if $opt_t; # $ENV{TMPDIR} will affect tempdir() calls:
  77. my $tmp = tempdir('git-archimport-XXXXXX', TMPDIR => 1, CLEANUP => 1);
  78. $opt_v && print "+ Using $tmp as temporary directory\n";
  79. unless (-d $git_dir) { # initial import needs empty directory
  80. opendir DIR, '.' or die "Unable to open current directory: $!\n";
  81. while (my $entry = readdir DIR) {
  82. $entry =~ /^\.\.?$/ or
  83. die "Initial import needs an empty current working directory.\n"
  84. }
  85. closedir DIR
  86. }
  87. my $default_archive; # default Arch archive
  88. my %reachable = (); # Arch repositories we can access
  89. my %unreachable = (); # Arch repositories we can't access :<
  90. my @psets = (); # the collection
  91. my %psets = (); # the collection, by name
  92. my %stats = ( # Track which strategy we used to import:
  93. get_tag => 0, replay => 0, get_new => 0, get_delta => 0,
  94. simple_changeset => 0, import_or_tag => 0
  95. );
  96. my %rptags = (); # my reverse private tags
  97. # to map a SHA1 to a commitid
  98. my $TLA = $ENV{'ARCH_CLIENT'} || 'tla';
  99. sub do_abrowse {
  100. my $stage = shift;
  101. while (my ($limit, $level) = each %arch_branches) {
  102. next unless $level == $stage;
  103. open ABROWSE, "$TLA abrowse -fkD --merges $limit |"
  104. or die "Problems with tla abrowse: $!";
  105. my %ps = (); # the current one
  106. my $lastseen = '';
  107. while (<ABROWSE>) {
  108. chomp;
  109. # first record padded w 8 spaces
  110. if (s/^\s{8}\b//) {
  111. my ($id, $type) = split(m/\s+/, $_, 2);
  112. my %last_ps;
  113. # store the record we just captured
  114. if (%ps && !exists $psets{ $ps{id} }) {
  115. %last_ps = %ps; # break references
  116. push (@psets, \%last_ps);
  117. $psets{ $last_ps{id} } = \%last_ps;
  118. }
  119. my $branch = extract_versionname($id);
  120. %ps = ( id => $id, branch => $branch );
  121. if (%last_ps && ($last_ps{branch} eq $branch)) {
  122. $ps{parent_id} = $last_ps{id};
  123. }
  124. $arch_branches{$branch} = 1;
  125. $lastseen = 'id';
  126. # deal with types (should work with baz or tla):
  127. if ($type =~ m/\(.*changeset\)/) {
  128. $ps{type} = 's';
  129. } elsif ($type =~ /\(.*import\)/) {
  130. $ps{type} = 'i';
  131. } elsif ($type =~ m/\(tag.*?(\S+\@\S+).*?\)/) {
  132. $ps{type} = 't';
  133. # read which revision we've tagged when we parse the log
  134. $ps{tag} = $1;
  135. } else {
  136. warn "Unknown type $type";
  137. }
  138. $arch_branches{$branch} = 1;
  139. $lastseen = 'id';
  140. } elsif (s/^\s{10}//) {
  141. # 10 leading spaces or more
  142. # indicate commit metadata
  143. # date
  144. if ($lastseen eq 'id' && m/^(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d)/){
  145. $ps{date} = $1;
  146. $lastseen = 'date';
  147. } elsif ($_ eq 'merges in:') {
  148. $ps{merges} = [];
  149. $lastseen = 'merges';
  150. } elsif ($lastseen eq 'merges' && s/^\s{2}//) {
  151. my $id = $_;
  152. push (@{$ps{merges}}, $id);
  153. # aggressive branch finding:
  154. if ($opt_D) {
  155. my $branch = extract_versionname($id);
  156. my $repo = extract_reponame($branch);
  157. if (archive_reachable($repo) &&
  158. !defined $arch_branches{$branch}) {
  159. $arch_branches{$branch} = $stage + 1;
  160. }
  161. }
  162. } else {
  163. warn "more metadata after merges!?: $_\n" unless /^\s*$/;
  164. }
  165. }
  166. }
  167. if (%ps && !exists $psets{ $ps{id} }) {
  168. my %temp = %ps; # break references
  169. if (@psets && $psets[$#psets]{branch} eq $ps{branch}) {
  170. $temp{parent_id} = $psets[$#psets]{id};
  171. }
  172. push (@psets, \%temp);
  173. $psets{ $temp{id} } = \%temp;
  174. }
  175. close ABROWSE or die "$TLA abrowse failed on $limit\n";
  176. }
  177. } # end foreach $root
  178. do_abrowse(1);
  179. my $depth = 2;
  180. $opt_D ||= 0;
  181. while ($depth <= $opt_D) {
  182. do_abrowse($depth);
  183. $depth++;
  184. }
  185. ## Order patches by time
  186. # FIXME see if we can find a more optimal way to do this by graphing
  187. # the ancestry data and walking it, that way we won't have to rely on
  188. # client-supplied dates
  189. @psets = sort {$a->{date}.$b->{id} cmp $b->{date}.$b->{id}} @psets;
  190. #print Dumper \@psets;
  191. ##
  192. ## TODO cleanup irrelevant patches
  193. ## and put an initial import
  194. ## or a full tag
  195. my $import = 0;
  196. unless (-d $git_dir) { # initial import
  197. if ($psets[0]{type} eq 'i' || $psets[0]{type} eq 't') {
  198. print "Starting import from $psets[0]{id}\n";
  199. `git-init`;
  200. die $! if $?;
  201. $import = 1;
  202. } else {
  203. die "Need to start from an import or a tag -- cannot use $psets[0]{id}";
  204. }
  205. } else { # progressing an import
  206. # load the rptags
  207. opendir(DIR, $ptag_dir)
  208. || die "can't opendir: $!";
  209. while (my $file = readdir(DIR)) {
  210. # skip non-interesting-files
  211. next unless -f "$ptag_dir/$file";
  212. # convert first '--' to '/' from old git-archimport to use
  213. # as an archivename/c--b--v private tag
  214. if ($file !~ m!,!) {
  215. my $oldfile = $file;
  216. $file =~ s!--!,!;
  217. print STDERR "converting old tag $oldfile to $file\n";
  218. rename("$ptag_dir/$oldfile", "$ptag_dir/$file") or die $!;
  219. }
  220. my $sha = ptag($file);
  221. chomp $sha;
  222. $rptags{$sha} = $file;
  223. }
  224. closedir DIR;
  225. }
  226. # process patchsets
  227. # extract the Arch repository name (Arch "archive" in Arch-speak)
  228. sub extract_reponame {
  229. my $fq_cvbr = shift; # archivename/[[[[category]branch]version]revision]
  230. return (split(/\//, $fq_cvbr))[0];
  231. }
  232. sub extract_versionname {
  233. my $name = shift;
  234. $name =~ s/--(?:patch|version(?:fix)?|base)-\d+$//;
  235. return $name;
  236. }
  237. # convert a fully-qualified revision or version to a unique dirname:
  238. # normalperson@yhbt.net-05/mpd--uclinux--1--patch-2
  239. # becomes: normalperson@yhbt.net-05,mpd--uclinux--1
  240. #
  241. # the git notion of a branch is closer to
  242. # archive/category--branch--version than archive/category--branch, so we
  243. # use this to convert to git branch names.
  244. # Also, keep archive names but replace '/' with ',' since it won't require
  245. # subdirectories, and is safer than swapping '--' which could confuse
  246. # reverse-mapping when dealing with bastard branches that
  247. # are just archive/category--version (no --branch)
  248. sub tree_dirname {
  249. my $revision = shift;
  250. my $name = extract_versionname($revision);
  251. $name =~ s#/#,#;
  252. return $name;
  253. }
  254. # old versions of git-archimport just use the <category--branch> part:
  255. sub old_style_branchname {
  256. my $id = shift;
  257. my $ret = safe_pipe_capture($TLA,'parse-package-name','-p',$id);
  258. chomp $ret;
  259. return $ret;
  260. }
  261. *git_default_branchname = $opt_o ? *old_style_branchname : *tree_dirname;
  262. # retrieve default archive, since $branch_name_map keys might not include it
  263. sub get_default_archive {
  264. if (!defined $default_archive) {
  265. $default_archive = safe_pipe_capture($TLA,'my-default-archive');
  266. chomp $default_archive;
  267. }
  268. return $default_archive;
  269. }
  270. sub git_branchname {
  271. my $revision = shift;
  272. my $name = extract_versionname($revision);
  273. if (exists $branch_name_map{$name}) {
  274. return $branch_name_map{$name};
  275. } elsif ($name =~ m#^([^/]*)/(.*)$#
  276. && $1 eq get_default_archive()
  277. && exists $branch_name_map{$2}) {
  278. # the names given in the command-line lacked the archive.
  279. return $branch_name_map{$2};
  280. } else {
  281. return git_default_branchname($revision);
  282. }
  283. }
  284. sub process_patchset_accurate {
  285. my $ps = shift;
  286. # switch to that branch if we're not already in that branch:
  287. if (-e "$git_dir/refs/heads/$ps->{branch}") {
  288. system('git-checkout','-f',$ps->{branch}) == 0 or die "$! $?\n";
  289. # remove any old stuff that got leftover:
  290. my $rm = safe_pipe_capture('git-ls-files','--others','-z');
  291. rmtree(split(/\0/,$rm)) if $rm;
  292. }
  293. # Apply the import/changeset/merge into the working tree
  294. my $dir = sync_to_ps($ps);
  295. # read the new log entry:
  296. my @commitlog = safe_pipe_capture($TLA,'cat-log','-d',$dir,$ps->{id});
  297. die "Error in cat-log: $!" if $?;
  298. chomp @commitlog;
  299. # grab variables we want from the log, new fields get added to $ps:
  300. # (author, date, email, summary, message body ...)
  301. parselog($ps, \@commitlog);
  302. if ($ps->{id} =~ /--base-0$/ && $ps->{id} ne $psets[0]{id}) {
  303. # this should work when importing continuations
  304. if ($ps->{tag} && (my $branchpoint = eval { ptag($ps->{tag}) })) {
  305. # find where we are supposed to branch from
  306. if (! -e "$git_dir/refs/heads/$ps->{branch}") {
  307. system('git-branch',$ps->{branch},$branchpoint) == 0 or die "$! $?\n";
  308. # We trust Arch with the fact that this is just a tag,
  309. # and it does not affect the state of the tree, so
  310. # we just tag and move on. If the user really wants us
  311. # to consolidate more branches into one, don't tag because
  312. # the tag name would be already taken.
  313. tag($ps->{id}, $branchpoint);
  314. ptag($ps->{id}, $branchpoint);
  315. print " * Tagged $ps->{id} at $branchpoint\n";
  316. }
  317. system('git-checkout','-f',$ps->{branch}) == 0 or die "$! $?\n";
  318. # remove any old stuff that got leftover:
  319. my $rm = safe_pipe_capture('git-ls-files','--others','-z');
  320. rmtree(split(/\0/,$rm)) if $rm;
  321. return 0;
  322. } else {
  323. warn "Tagging from unknown id unsupported\n" if $ps->{tag};
  324. }
  325. # allow multiple bases/imports here since Arch supports cherry-picks
  326. # from unrelated trees
  327. }
  328. # update the index with all the changes we got
  329. system('git-diff-files --name-only -z | '.
  330. 'git-update-index --remove -z --stdin') == 0 or die "$! $?\n";
  331. system('git-ls-files --others -z | '.
  332. 'git-update-index --add -z --stdin') == 0 or die "$! $?\n";
  333. return 1;
  334. }
  335. # the native changeset processing strategy. This is very fast, but
  336. # does not handle permissions or any renames involving directories
  337. sub process_patchset_fast {
  338. my $ps = shift;
  339. #
  340. # create the branch if needed
  341. #
  342. if ($ps->{type} eq 'i' && !$import) {
  343. die "Should not have more than one 'Initial import' per GIT import: $ps->{id}";
  344. }
  345. unless ($import) { # skip for import
  346. if ( -e "$git_dir/refs/heads/$ps->{branch}") {
  347. # we know about this branch
  348. system('git-checkout',$ps->{branch});
  349. } else {
  350. # new branch! we need to verify a few things
  351. die "Branch on a non-tag!" unless $ps->{type} eq 't';
  352. my $branchpoint = ptag($ps->{tag});
  353. die "Tagging from unknown id unsupported: $ps->{tag}"
  354. unless $branchpoint;
  355. # find where we are supposed to branch from
  356. if (! -e "$git_dir/refs/heads/$ps->{branch}") {
  357. system('git-branch',$ps->{branch},$branchpoint) == 0 or die "$! $?\n";
  358. # We trust Arch with the fact that this is just a tag,
  359. # and it does not affect the state of the tree, so
  360. # we just tag and move on. If the user really wants us
  361. # to consolidate more branches into one, don't tag because
  362. # the tag name would be already taken.
  363. tag($ps->{id}, $branchpoint);
  364. ptag($ps->{id}, $branchpoint);
  365. print " * Tagged $ps->{id} at $branchpoint\n";
  366. }
  367. system('git-checkout',$ps->{branch}) == 0 or die "$! $?\n";
  368. return 0;
  369. }
  370. die $! if $?;
  371. }
  372. #
  373. # Apply the import/changeset/merge into the working tree
  374. #
  375. if ($ps->{type} eq 'i' || $ps->{type} eq 't') {
  376. apply_import($ps) or die $!;
  377. $stats{import_or_tag}++;
  378. $import=0;
  379. } elsif ($ps->{type} eq 's') {
  380. apply_cset($ps);
  381. $stats{simple_changeset}++;
  382. }
  383. #
  384. # prepare update git's index, based on what arch knows
  385. # about the pset, resolve parents, etc
  386. #
  387. my @commitlog = safe_pipe_capture($TLA,'cat-archive-log',$ps->{id});
  388. die "Error in cat-archive-log: $!" if $?;
  389. parselog($ps,\@commitlog);
  390. # imports don't give us good info
  391. # on added files. Shame on them
  392. if ($ps->{type} eq 'i' || $ps->{type} eq 't') {
  393. system('git-ls-files --deleted -z | '.
  394. 'git-update-index --remove -z --stdin') == 0 or die "$! $?\n";
  395. system('git-ls-files --others -z | '.
  396. 'git-update-index --add -z --stdin') == 0 or die "$! $?\n";
  397. }
  398. # TODO: handle removed_directories and renamed_directories:
  399. if (my $del = $ps->{removed_files}) {
  400. unlink @$del;
  401. while (@$del) {
  402. my @slice = splice(@$del, 0, 100);
  403. system('git-update-index','--remove','--',@slice) == 0 or
  404. die "Error in git-update-index --remove: $! $?\n";
  405. }
  406. }
  407. if (my $ren = $ps->{renamed_files}) { # renamed
  408. if (@$ren % 2) {
  409. die "Odd number of entries in rename!?";
  410. }
  411. while (@$ren) {
  412. my $from = shift @$ren;
  413. my $to = shift @$ren;
  414. unless (-d dirname($to)) {
  415. mkpath(dirname($to)); # will die on err
  416. }
  417. # print "moving $from $to";
  418. rename($from, $to) or die "Error renaming '$from' '$to': $!\n";
  419. system('git-update-index','--remove','--',$from) == 0 or
  420. die "Error in git-update-index --remove: $! $?\n";
  421. system('git-update-index','--add','--',$to) == 0 or
  422. die "Error in git-update-index --add: $! $?\n";
  423. }
  424. }
  425. if (my $add = $ps->{new_files}) {
  426. while (@$add) {
  427. my @slice = splice(@$add, 0, 100);
  428. system('git-update-index','--add','--',@slice) == 0 or
  429. die "Error in git-update-index --add: $! $?\n";
  430. }
  431. }
  432. if (my $mod = $ps->{modified_files}) {
  433. while (@$mod) {
  434. my @slice = splice(@$mod, 0, 100);
  435. system('git-update-index','--',@slice) == 0 or
  436. die "Error in git-update-index: $! $?\n";
  437. }
  438. }
  439. return 1; # we successfully applied the changeset
  440. }
  441. if ($opt_f) {
  442. print "Will import patchsets using the fast strategy\n",
  443. "Renamed directories and permission changes will be missed\n";
  444. *process_patchset = *process_patchset_fast;
  445. } else {
  446. print "Using the default (accurate) import strategy.\n",
  447. "Things may be a bit slow\n";
  448. *process_patchset = *process_patchset_accurate;
  449. }
  450. foreach my $ps (@psets) {
  451. # process patchsets
  452. $ps->{branch} = git_branchname($ps->{id});
  453. #
  454. # ensure we have a clean state
  455. #
  456. if (my $dirty = `git-diff-files`) {
  457. die "Unclean tree when about to process $ps->{id} " .
  458. " - did we fail to commit cleanly before?\n$dirty";
  459. }
  460. die $! if $?;
  461. #
  462. # skip commits already in repo
  463. #
  464. if (ptag($ps->{id})) {
  465. $opt_v && print " * Skipping already imported: $ps->{id}\n";
  466. next;
  467. }
  468. print " * Starting to work on $ps->{id}\n";
  469. process_patchset($ps) or next;
  470. # warn "errors when running git-update-index! $!";
  471. my $tree = `git-write-tree`;
  472. die "cannot write tree $!" if $?;
  473. chomp $tree;
  474. #
  475. # Who's your daddy?
  476. #
  477. my @par;
  478. if ( -e "$git_dir/refs/heads/$ps->{branch}") {
  479. if (open HEAD, "<","$git_dir/refs/heads/$ps->{branch}") {
  480. my $p = <HEAD>;
  481. close HEAD;
  482. chomp $p;
  483. push @par, '-p', $p;
  484. } else {
  485. if ($ps->{type} eq 's') {
  486. warn "Could not find the right head for the branch $ps->{branch}";
  487. }
  488. }
  489. }
  490. if ($ps->{merges}) {
  491. push @par, find_parents($ps);
  492. }
  493. #
  494. # Commit, tag and clean state
  495. #
  496. $ENV{TZ} = 'GMT';
  497. $ENV{GIT_AUTHOR_NAME} = $ps->{author};
  498. $ENV{GIT_AUTHOR_EMAIL} = $ps->{email};
  499. $ENV{GIT_AUTHOR_DATE} = $ps->{date};
  500. $ENV{GIT_COMMITTER_NAME} = $ps->{author};
  501. $ENV{GIT_COMMITTER_EMAIL} = $ps->{email};
  502. $ENV{GIT_COMMITTER_DATE} = $ps->{date};
  503. my $pid = open2(*READER, *WRITER,'git-commit-tree',$tree,@par)
  504. or die $!;
  505. print WRITER $ps->{summary},"\n\n";
  506. # only print message if it's not empty, to avoid a spurious blank line;
  507. # also append an extra newline, so there's a blank line before the
  508. # following "git-archimport-id:" line.
  509. print WRITER $ps->{message},"\n\n" if ($ps->{message} ne "");
  510. # make it easy to backtrack and figure out which Arch revision this was:
  511. print WRITER 'git-archimport-id: ',$ps->{id},"\n";
  512. close WRITER;
  513. my $commitid = <READER>; # read
  514. chomp $commitid;
  515. close READER;
  516. waitpid $pid,0; # close;
  517. if (length $commitid != 40) {
  518. die "Something went wrong with the commit! $! $commitid";
  519. }
  520. #
  521. # Update the branch
  522. #
  523. open HEAD, ">","$git_dir/refs/heads/$ps->{branch}";
  524. print HEAD $commitid;
  525. close HEAD;
  526. system('git-update-ref', 'HEAD', "$ps->{branch}");
  527. # tag accordingly
  528. ptag($ps->{id}, $commitid); # private tag
  529. if ($opt_T || $ps->{type} eq 't' || $ps->{type} eq 'i') {
  530. tag($ps->{id}, $commitid);
  531. }
  532. print " * Committed $ps->{id}\n";
  533. print " + tree $tree\n";
  534. print " + commit $commitid\n";
  535. $opt_v && print " + commit date is $ps->{date} \n";
  536. $opt_v && print " + parents: ",join(' ',@par),"\n";
  537. }
  538. if ($opt_v) {
  539. foreach (sort keys %stats) {
  540. print" $_: $stats{$_}\n";
  541. }
  542. }
  543. exit 0;
  544. # used by the accurate strategy:
  545. sub sync_to_ps {
  546. my $ps = shift;
  547. my $tree_dir = $tmp.'/'.tree_dirname($ps->{id});
  548. $opt_v && print "sync_to_ps($ps->{id}) method: ";
  549. if (-d $tree_dir) {
  550. if ($ps->{type} eq 't') {
  551. $opt_v && print "get (tag)\n";
  552. # looks like a tag-only or (worse,) a mixed tags/changeset branch,
  553. # can't rely on replay to work correctly on these
  554. rmtree($tree_dir);
  555. safe_pipe_capture($TLA,'get','--no-pristine',$ps->{id},$tree_dir);
  556. $stats{get_tag}++;
  557. } else {
  558. my $tree_id = arch_tree_id($tree_dir);
  559. if ($ps->{parent_id} && ($ps->{parent_id} eq $tree_id)) {
  560. # the common case (hopefully)
  561. $opt_v && print "replay\n";
  562. safe_pipe_capture($TLA,'replay','-d',$tree_dir,$ps->{id});
  563. $stats{replay}++;
  564. } else {
  565. # getting one tree is usually faster than getting two trees
  566. # and applying the delta ...
  567. rmtree($tree_dir);
  568. $opt_v && print "apply-delta\n";
  569. safe_pipe_capture($TLA,'get','--no-pristine',
  570. $ps->{id},$tree_dir);
  571. $stats{get_delta}++;
  572. }
  573. }
  574. } else {
  575. # new branch work
  576. $opt_v && print "get (new tree)\n";
  577. safe_pipe_capture($TLA,'get','--no-pristine',$ps->{id},$tree_dir);
  578. $stats{get_new}++;
  579. }
  580. # added -I flag to rsync since we're going to fast! AIEEEEE!!!!
  581. system('rsync','-aI','--delete','--exclude',$git_dir,
  582. # '--exclude','.arch-inventory',
  583. '--exclude','.arch-ids','--exclude','{arch}',
  584. '--exclude','+*','--exclude',',*',
  585. "$tree_dir/",'./') == 0 or die "Cannot rsync $tree_dir: $! $?";
  586. return $tree_dir;
  587. }
  588. sub apply_import {
  589. my $ps = shift;
  590. my $bname = git_branchname($ps->{id});
  591. mkpath($tmp);
  592. safe_pipe_capture($TLA,'get','-s','--no-pristine',$ps->{id},"$tmp/import");
  593. die "Cannot get import: $!" if $?;
  594. system('rsync','-aI','--delete', '--exclude',$git_dir,
  595. '--exclude','.arch-ids','--exclude','{arch}',
  596. "$tmp/import/", './');
  597. die "Cannot rsync import:$!" if $?;
  598. rmtree("$tmp/import");
  599. die "Cannot remove tempdir: $!" if $?;
  600. return 1;
  601. }
  602. sub apply_cset {
  603. my $ps = shift;
  604. mkpath($tmp);
  605. # get the changeset
  606. safe_pipe_capture($TLA,'get-changeset',$ps->{id},"$tmp/changeset");
  607. die "Cannot get changeset: $!" if $?;
  608. # apply patches
  609. if (`find $tmp/changeset/patches -type f -name '*.patch'`) {
  610. # this can be sped up considerably by doing
  611. # (find | xargs cat) | patch
  612. # but that can get mucked up by patches
  613. # with missing trailing newlines or the standard
  614. # 'missing newline' flag in the patch - possibly
  615. # produced with an old/buggy diff.
  616. # slow and safe, we invoke patch once per patchfile
  617. `find $tmp/changeset/patches -type f -name '*.patch' -print0 | grep -zv '{arch}' | xargs -iFILE -0 --no-run-if-empty patch -p1 --forward -iFILE`;
  618. die "Problem applying patches! $!" if $?;
  619. }
  620. # apply changed binary files
  621. if (my @modified = `find $tmp/changeset/patches -type f -name '*.modified'`) {
  622. foreach my $mod (@modified) {
  623. chomp $mod;
  624. my $orig = $mod;
  625. $orig =~ s/\.modified$//; # lazy
  626. $orig =~ s!^\Q$tmp\E/changeset/patches/!!;
  627. #print "rsync -p '$mod' '$orig'";
  628. system('rsync','-p',$mod,"./$orig");
  629. die "Problem applying binary changes! $!" if $?;
  630. }
  631. }
  632. # bring in new files
  633. system('rsync','-aI','--exclude',$git_dir,
  634. '--exclude','.arch-ids',
  635. '--exclude', '{arch}',
  636. "$tmp/changeset/new-files-archive/",'./');
  637. # deleted files are hinted from the commitlog processing
  638. rmtree("$tmp/changeset");
  639. }
  640. # =for reference
  641. # notes: *-files/-directories keys cannot have spaces, they're always
  642. # pika-escaped. Everything after the first newline
  643. # A log entry looks like:
  644. # Revision: moodle-org--moodle--1.3.3--patch-15
  645. # Archive: arch-eduforge@catalyst.net.nz--2004
  646. # Creator: Penny Leach <penny@catalyst.net.nz>
  647. # Date: Wed May 25 14:15:34 NZST 2005
  648. # Standard-date: 2005-05-25 02:15:34 GMT
  649. # New-files: lang/de/.arch-ids/block_glossary_random.php.id
  650. # lang/de/.arch-ids/block_html.php.id
  651. # New-directories: lang/de/help/questionnaire
  652. # lang/de/help/questionnaire/.arch-ids
  653. # Renamed-files: .arch-ids/db_sears.sql.id db/.arch-ids/db_sears.sql.id
  654. # db_sears.sql db/db_sears.sql
  655. # Removed-files: lang/be/docs/.arch-ids/release.html.id
  656. # lang/be/docs/.arch-ids/releaseold.html.id
  657. # Modified-files: admin/cron.php admin/delete.php
  658. # admin/editor.html backup/lib.php backup/restore.php
  659. # New-patches: arch-eduforge@catalyst.net.nz--2004/moodle-org--moodle--1.3.3--patch-15
  660. # Summary: Updating to latest from MOODLE_14_STABLE (1.4.5+)
  661. # summary can be multiline with a leading space just like the above fields
  662. # Keywords:
  663. #
  664. # Updating yadda tadda tadda madda
  665. sub parselog {
  666. my ($ps, $log) = @_;
  667. my $key = undef;
  668. # headers we want that contain filenames:
  669. my %want_headers = (
  670. new_files => 1,
  671. modified_files => 1,
  672. renamed_files => 1,
  673. renamed_directories => 1,
  674. removed_files => 1,
  675. removed_directories => 1,
  676. );
  677. chomp (@$log);
  678. while ($_ = shift @$log) {
  679. if (/^Continuation-of:\s*(.*)/) {
  680. $ps->{tag} = $1;
  681. $key = undef;
  682. } elsif (/^Summary:\s*(.*)$/ ) {
  683. # summary can be multiline as long as it has a leading space.
  684. # we squeeze it onto a single line, though.
  685. $ps->{summary} = [ $1 ];
  686. $key = 'summary';
  687. } elsif (/^Creator: (.*)\s*<([^\>]+)>/) {
  688. $ps->{author} = $1;
  689. $ps->{email} = $2;
  690. $key = undef;
  691. # any *-files or *-directories can be read here:
  692. } elsif (/^([A-Z][a-z\-]+):\s*(.*)$/) {
  693. my $val = $2;
  694. $key = lc $1;
  695. $key =~ tr/-/_/; # too lazy to quote :P
  696. if ($want_headers{$key}) {
  697. push @{$ps->{$key}}, split(/\s+/, $val);
  698. } else {
  699. $key = undef;
  700. }
  701. } elsif (/^$/) {
  702. last; # remainder of @$log that didn't get shifted off is message
  703. } elsif ($key) {
  704. if (/^\s+(.*)$/) {
  705. if ($key eq 'summary') {
  706. push @{$ps->{$key}}, $1;
  707. } else { # files/directories:
  708. push @{$ps->{$key}}, split(/\s+/, $1);
  709. }
  710. } else {
  711. $key = undef;
  712. }
  713. }
  714. }
  715. # drop leading empty lines from the log message
  716. while (@$log && $log->[0] eq '') {
  717. shift @$log;
  718. }
  719. if (exists $ps->{summary} && @{$ps->{summary}}) {
  720. $ps->{summary} = join(' ', @{$ps->{summary}});
  721. }
  722. elsif (@$log == 0) {
  723. $ps->{summary} = 'empty commit message';
  724. } else {
  725. $ps->{summary} = $log->[0] . '...';
  726. }
  727. $ps->{message} = join("\n",@$log);
  728. # skip Arch control files, unescape pika-escaped files
  729. foreach my $k (keys %want_headers) {
  730. next unless (defined $ps->{$k});
  731. my @tmp = ();
  732. foreach my $t (@{$ps->{$k}}) {
  733. next unless length ($t);
  734. next if $t =~ m!\{arch\}/!;
  735. next if $t =~ m!\.arch-ids/!;
  736. # should we skip this?
  737. next if $t =~ m!\.arch-inventory$!;
  738. # tla cat-archive-log will give us filenames with spaces as file\(sp)name - why?
  739. # we can assume that any filename with \ indicates some pika escaping that we want to get rid of.
  740. if ($t =~ /\\/ ){
  741. $t = (safe_pipe_capture($TLA,'escape','--unescaped',$t))[0];
  742. }
  743. push @tmp, $t;
  744. }
  745. $ps->{$k} = \@tmp;
  746. }
  747. }
  748. # write/read a tag
  749. sub tag {
  750. my ($tag, $commit) = @_;
  751. if ($opt_o) {
  752. $tag =~ s|/|--|g;
  753. } else {
  754. my $patchname = $tag;
  755. $patchname =~ s/.*--//;
  756. $tag = git_branchname ($tag) . '--' . $patchname;
  757. }
  758. if ($commit) {
  759. open(C,">","$git_dir/refs/tags/$tag")
  760. or die "Cannot create tag $tag: $!\n";
  761. print C "$commit\n"
  762. or die "Cannot write tag $tag: $!\n";
  763. close(C)
  764. or die "Cannot write tag $tag: $!\n";
  765. print " * Created tag '$tag' on '$commit'\n" if $opt_v;
  766. } else { # read
  767. open(C,"<","$git_dir/refs/tags/$tag")
  768. or die "Cannot read tag $tag: $!\n";
  769. $commit = <C>;
  770. chomp $commit;
  771. die "Error reading tag $tag: $!\n" unless length $commit == 40;
  772. close(C)
  773. or die "Cannot read tag $tag: $!\n";
  774. return $commit;
  775. }
  776. }
  777. # write/read a private tag
  778. # reads fail softly if the tag isn't there
  779. sub ptag {
  780. my ($tag, $commit) = @_;
  781. # don't use subdirs for tags yet, it could screw up other porcelains
  782. $tag =~ s|/|,|g;
  783. my $tag_file = "$ptag_dir/$tag";
  784. my $tag_branch_dir = dirname($tag_file);
  785. mkpath($tag_branch_dir) unless (-d $tag_branch_dir);
  786. if ($commit) { # write
  787. open(C,">",$tag_file)
  788. or die "Cannot create tag $tag: $!\n";
  789. print C "$commit\n"
  790. or die "Cannot write tag $tag: $!\n";
  791. close(C)
  792. or die "Cannot write tag $tag: $!\n";
  793. $rptags{$commit} = $tag
  794. unless $tag =~ m/--base-0$/;
  795. } else { # read
  796. # if the tag isn't there, return 0
  797. unless ( -s $tag_file) {
  798. return 0;
  799. }
  800. open(C,"<",$tag_file)
  801. or die "Cannot read tag $tag: $!\n";
  802. $commit = <C>;
  803. chomp $commit;
  804. die "Error reading tag $tag: $!\n" unless length $commit == 40;
  805. close(C)
  806. or die "Cannot read tag $tag: $!\n";
  807. unless (defined $rptags{$commit}) {
  808. $rptags{$commit} = $tag;
  809. }
  810. return $commit;
  811. }
  812. }
  813. sub find_parents {
  814. #
  815. # Identify what branches are merging into me
  816. # and whether we are fully merged
  817. # git-merge-base <headsha> <headsha> should tell
  818. # me what the base of the merge should be
  819. #
  820. my $ps = shift;
  821. my %branches; # holds an arrayref per branch
  822. # the arrayref contains a list of
  823. # merged patches between the base
  824. # of the merge and the current head
  825. my @parents; # parents found for this commit
  826. # simple loop to split the merges
  827. # per branch
  828. foreach my $merge (@{$ps->{merges}}) {
  829. my $branch = git_branchname($merge);
  830. unless (defined $branches{$branch} ){
  831. $branches{$branch} = [];
  832. }
  833. push @{$branches{$branch}}, $merge;
  834. }
  835. #
  836. # foreach branch find a merge base and walk it to the
  837. # head where we are, collecting the merged patchsets that
  838. # Arch has recorded. Keep that in @have
  839. # Compare that with the commits on the other branch
  840. # between merge-base and the tip of the branch (@need)
  841. # and see if we have a series of consecutive patches
  842. # starting from the merge base. The tip of the series
  843. # of consecutive patches merged is our new parent for
  844. # that branch.
  845. #
  846. foreach my $branch (keys %branches) {
  847. # check that we actually know about the branch
  848. next unless -e "$git_dir/refs/heads/$branch";
  849. my $mergebase = safe_pipe_capture(qw(git-merge-base), $branch, $ps->{branch});
  850. if ($?) {
  851. # Don't die here, Arch supports one-way cherry-picking
  852. # between branches with no common base (or any relationship
  853. # at all beforehand)
  854. warn "Cannot find merge base for $branch and $ps->{branch}";
  855. next;
  856. }
  857. chomp $mergebase;
  858. # now walk up to the mergepoint collecting what patches we have
  859. my $branchtip = git_rev_parse($ps->{branch});
  860. my @ancestors = `git-rev-list --topo-order $branchtip ^$mergebase`;
  861. my %have; # collected merges this branch has
  862. foreach my $merge (@{$ps->{merges}}) {
  863. $have{$merge} = 1;
  864. }
  865. my %ancestorshave;
  866. foreach my $par (@ancestors) {
  867. $par = commitid2pset($par);
  868. if (defined $par->{merges}) {
  869. foreach my $merge (@{$par->{merges}}) {
  870. $ancestorshave{$merge}=1;
  871. }
  872. }
  873. }
  874. # print "++++ Merges in $ps->{id} are....\n";
  875. # my @have = sort keys %have; print Dumper(\@have);
  876. # merge what we have with what ancestors have
  877. %have = (%have, %ancestorshave);
  878. # see what the remote branch has - these are the merges we
  879. # will want to have in a consecutive series from the mergebase
  880. my $otherbranchtip = git_rev_parse($branch);
  881. my @needraw = `git-rev-list --topo-order $otherbranchtip ^$mergebase`;
  882. my @need;
  883. foreach my $needps (@needraw) { # get the psets
  884. $needps = commitid2pset($needps);
  885. # git-rev-list will also
  886. # list commits merged in via earlier
  887. # merges. we are only interested in commits
  888. # from the branch we're looking at
  889. if ($branch eq $needps->{branch}) {
  890. push @need, $needps->{id};
  891. }
  892. }
  893. # print "++++ Merges from $branch we want are....\n";
  894. # print Dumper(\@need);
  895. my $newparent;
  896. while (my $needed_commit = pop @need) {
  897. if ($have{$needed_commit}) {
  898. $newparent = $needed_commit;
  899. } else {
  900. last; # break out of the while
  901. }
  902. }
  903. if ($newparent) {
  904. push @parents, $newparent;
  905. }
  906. } # end foreach branch
  907. # prune redundant parents
  908. my %parents;
  909. foreach my $p (@parents) {
  910. $parents{$p} = 1;
  911. }
  912. foreach my $p (@parents) {
  913. next unless exists $psets{$p}{merges};
  914. next unless ref $psets{$p}{merges};
  915. my @merges = @{$psets{$p}{merges}};
  916. foreach my $merge (@merges) {
  917. if ($parents{$merge}) {
  918. delete $parents{$merge};
  919. }
  920. }
  921. }
  922. @parents = ();
  923. foreach (keys %parents) {
  924. push @parents, '-p', ptag($_);
  925. }
  926. return @parents;
  927. }
  928. sub git_rev_parse {
  929. my $name = shift;
  930. my $val = safe_pipe_capture(qw(git-rev-parse), $name);
  931. die "Error: git-rev-parse $name" if $?;
  932. chomp $val;
  933. return $val;
  934. }
  935. # resolve a SHA1 to a known patchset
  936. sub commitid2pset {
  937. my $commitid = shift;
  938. chomp $commitid;
  939. my $name = $rptags{$commitid}
  940. || die "Cannot find reverse tag mapping for $commitid";
  941. $name =~ s|,|/|;
  942. my $ps = $psets{$name}
  943. || (print Dumper(sort keys %psets)) && die "Cannot find patchset for $name";
  944. return $ps;
  945. }
  946. # an alternative to `command` that allows input to be passed as an array
  947. # to work around shell problems with weird characters in arguments
  948. sub safe_pipe_capture {
  949. my @output;
  950. if (my $pid = open my $child, '-|') {
  951. @output = (<$child>);
  952. close $child or die join(' ',@_).": $! $?";
  953. } else {
  954. exec(@_) or die "$! $?"; # exec() can fail the executable can't be found
  955. }
  956. return wantarray ? @output : join('',@output);
  957. }
  958. # `tla logs -rf -d <dir> | head -n1` or `baz tree-id <dir>`
  959. sub arch_tree_id {
  960. my $dir = shift;
  961. chomp( my $ret = (safe_pipe_capture($TLA,'logs','-rf','-d',$dir))[0] );
  962. return $ret;
  963. }
  964. sub archive_reachable {
  965. my $archive = shift;
  966. return 1 if $reachable{$archive};
  967. return 0 if $unreachable{$archive};
  968. if (system "$TLA whereis-archive $archive >/dev/null") {
  969. if ($opt_a && (system($TLA,'register-archive',
  970. "http://mirrors.sourcecontrol.net/$archive") == 0)) {
  971. $reachable{$archive} = 1;
  972. return 1;
  973. }
  974. print STDERR "Archive is unreachable: $archive\n";
  975. $unreachable{$archive} = 1;
  976. return 0;
  977. } else {
  978. $reachable{$archive} = 1;
  979. return 1;
  980. }
  981. }