Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

RebuildCommitGraph.java 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. /*
  2. * Copyright (C) 2009-2010, Google Inc.
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.pgm.debug;
  44. import java.io.BufferedReader;
  45. import java.io.File;
  46. import java.io.FileInputStream;
  47. import java.io.IOException;
  48. import java.io.InputStreamReader;
  49. import java.util.ArrayList;
  50. import java.util.Date;
  51. import java.util.HashMap;
  52. import java.util.List;
  53. import java.util.ListIterator;
  54. import java.util.Map;
  55. import org.kohsuke.args4j.Argument;
  56. import org.kohsuke.args4j.Option;
  57. import org.eclipse.jgit.errors.MissingObjectException;
  58. import org.eclipse.jgit.errors.ObjectWritingException;
  59. import org.eclipse.jgit.lib.Commit;
  60. import org.eclipse.jgit.lib.Constants;
  61. import org.eclipse.jgit.lib.LockFile;
  62. import org.eclipse.jgit.lib.ObjectId;
  63. import org.eclipse.jgit.lib.ObjectIdRef;
  64. import org.eclipse.jgit.lib.ObjectWriter;
  65. import org.eclipse.jgit.lib.PersonIdent;
  66. import org.eclipse.jgit.lib.ProgressMonitor;
  67. import org.eclipse.jgit.lib.Ref;
  68. import org.eclipse.jgit.lib.RefUpdate;
  69. import org.eclipse.jgit.lib.RefWriter;
  70. import org.eclipse.jgit.lib.TextProgressMonitor;
  71. import org.eclipse.jgit.lib.Tree;
  72. import org.eclipse.jgit.pgm.TextBuiltin;
  73. import org.eclipse.jgit.revwalk.RevWalk;
  74. /**
  75. * Recreates a repository from another one's commit graph.
  76. * <p>
  77. * <b>Do not run this on a repository unless you want to destroy it.</b>
  78. * <p>
  79. * To create the input files, in the source repository use:
  80. *
  81. * <pre>
  82. * git for-each-ref &gt;in.refs
  83. * git log --all '--pretty=format:%H %ct %P' &gt;in.dag
  84. * </pre>
  85. * <p>
  86. * Run the rebuild in either an empty repository, or a clone of the source. Any
  87. * missing commits (which might be the entire graph) will be created. All refs
  88. * will be modified to match the input exactly, which means some refs may be
  89. * deleted from the current repository.
  90. * <p>
  91. */
  92. class RebuildCommitGraph extends TextBuiltin {
  93. private final String REALLY = "--destroy-this-repository";
  94. @Option(name = REALLY, usage = "approve destruction of repository")
  95. boolean really;
  96. @Argument(index = 0, required = true, metaVar = "REFS", usage = "for-each-ref output")
  97. File refList;
  98. @Argument(index = 1, required = true, metaVar = "DAG", usage = "log --all '--pretty=format:%H %ct %P' output")
  99. File graph;
  100. private final ProgressMonitor pm = new TextProgressMonitor();
  101. private Map<ObjectId, ObjectId> rewrites = new HashMap<ObjectId, ObjectId>();
  102. @Override
  103. protected void run() throws Exception {
  104. if (!really && !db.getAllRefs().isEmpty()) {
  105. final StringBuilder m = new StringBuilder();
  106. m.append("fatal: ");
  107. m.append("This program will destroy the repository:");
  108. m.append("\n");
  109. m.append("fatal:\n");
  110. m.append("fatal: ");
  111. m.append(db.getDirectory().getAbsolutePath());
  112. m.append("\n");
  113. m.append("fatal:\n");
  114. m.append("fatal: ");
  115. m.append("To continue, add ");
  116. m.append(REALLY);
  117. m.append(" to the command line");
  118. m.append("\n");
  119. m.append("fatal:");
  120. System.err.println(m);
  121. throw die("Need approval to destroy current repository");
  122. }
  123. if (!refList.isFile())
  124. throw die("no such file: " + refList.getPath());
  125. if (!graph.isFile())
  126. throw die("no such file: " + graph.getPath());
  127. recreateCommitGraph();
  128. detachHead();
  129. deleteAllRefs();
  130. recreateRefs();
  131. }
  132. private void recreateCommitGraph() throws IOException {
  133. final RevWalk rw = new RevWalk(db);
  134. final Map<ObjectId, ToRewrite> toRewrite = new HashMap<ObjectId, ToRewrite>();
  135. List<ToRewrite> queue = new ArrayList<ToRewrite>();
  136. final BufferedReader br = new BufferedReader(new InputStreamReader(
  137. new FileInputStream(graph), Constants.CHARSET));
  138. try {
  139. String line;
  140. while ((line = br.readLine()) != null) {
  141. final String[] parts = line.split("[ \t]{1,}");
  142. final ObjectId oldId = ObjectId.fromString(parts[0]);
  143. try {
  144. rw.parseCommit(oldId);
  145. // We have it already. Don't rewrite it.
  146. continue;
  147. } catch (MissingObjectException mue) {
  148. // Fall through and rewrite it.
  149. }
  150. final long time = Long.parseLong(parts[1]) * 1000L;
  151. final ObjectId[] parents = new ObjectId[parts.length - 2];
  152. for (int i = 0; i < parents.length; i++) {
  153. parents[i] = ObjectId.fromString(parts[2 + i]);
  154. }
  155. final ToRewrite t = new ToRewrite(oldId, time, parents);
  156. toRewrite.put(oldId, t);
  157. queue.add(t);
  158. }
  159. } finally {
  160. br.close();
  161. }
  162. pm.beginTask("Rewriting commits", queue.size());
  163. final ObjectWriter ow = new ObjectWriter(db);
  164. final ObjectId emptyTree = ow.writeTree(new Tree(db));
  165. final PersonIdent me = new PersonIdent("jgit rebuild-commitgraph",
  166. "rebuild-commitgraph@localhost");
  167. while (!queue.isEmpty()) {
  168. final ListIterator<ToRewrite> itr = queue
  169. .listIterator(queue.size());
  170. queue = new ArrayList<ToRewrite>();
  171. REWRITE: while (itr.hasPrevious()) {
  172. final ToRewrite t = itr.previous();
  173. final ObjectId[] newParents = new ObjectId[t.oldParents.length];
  174. for (int k = 0; k < t.oldParents.length; k++) {
  175. final ToRewrite p = toRewrite.get(t.oldParents[k]);
  176. if (p != null) {
  177. if (p.newId == null) {
  178. // Must defer until after the parent is rewritten.
  179. queue.add(t);
  180. continue REWRITE;
  181. } else {
  182. newParents[k] = p.newId;
  183. }
  184. } else {
  185. // We have the old parent object. Use it.
  186. //
  187. newParents[k] = t.oldParents[k];
  188. }
  189. }
  190. final Commit newc = new Commit(db);
  191. newc.setTreeId(emptyTree);
  192. newc.setAuthor(new PersonIdent(me, new Date(t.commitTime)));
  193. newc.setCommitter(newc.getAuthor());
  194. newc.setParentIds(newParents);
  195. newc.setMessage("ORIGINAL " + t.oldId.name() + "\n");
  196. t.newId = ow.writeCommit(newc);
  197. rewrites.put(t.oldId, t.newId);
  198. pm.update(1);
  199. }
  200. }
  201. pm.endTask();
  202. }
  203. private static class ToRewrite {
  204. final ObjectId oldId;
  205. final long commitTime;
  206. final ObjectId[] oldParents;
  207. ObjectId newId;
  208. ToRewrite(final ObjectId o, final long t, final ObjectId[] p) {
  209. oldId = o;
  210. commitTime = t;
  211. oldParents = p;
  212. }
  213. }
  214. private void detachHead() throws IOException {
  215. final String head = db.getFullBranch();
  216. final ObjectId id = db.resolve(Constants.HEAD);
  217. if (!ObjectId.isId(head) && id != null) {
  218. final LockFile lf;
  219. lf = new LockFile(new File(db.getDirectory(), Constants.HEAD));
  220. if (!lf.lock())
  221. throw new IOException("Cannot lock HEAD");
  222. lf.write(id);
  223. if (!lf.commit())
  224. throw new IOException("Cannot deatch HEAD");
  225. }
  226. }
  227. private void deleteAllRefs() throws Exception {
  228. final RevWalk rw = new RevWalk(db);
  229. for (final Ref r : db.getAllRefs().values()) {
  230. if (Constants.HEAD.equals(r.getName()))
  231. continue;
  232. final RefUpdate u = db.updateRef(r.getName());
  233. u.setForceUpdate(true);
  234. u.delete(rw);
  235. }
  236. }
  237. private void recreateRefs() throws Exception {
  238. final Map<String, Ref> refs = computeNewRefs();
  239. new RefWriter(refs.values()) {
  240. @Override
  241. protected void writeFile(final String name, final byte[] content)
  242. throws IOException {
  243. final File file = new File(db.getDirectory(), name);
  244. final LockFile lck = new LockFile(file);
  245. if (!lck.lock())
  246. throw new ObjectWritingException("Can't write " + file);
  247. try {
  248. lck.write(content);
  249. } catch (IOException ioe) {
  250. throw new ObjectWritingException("Can't write " + file);
  251. }
  252. if (!lck.commit())
  253. throw new ObjectWritingException("Can't write " + file);
  254. }
  255. }.writePackedRefs();
  256. }
  257. private Map<String, Ref> computeNewRefs() throws IOException {
  258. final RevWalk rw = new RevWalk(db);
  259. final Map<String, Ref> refs = new HashMap<String, Ref>();
  260. final BufferedReader br = new BufferedReader(new InputStreamReader(
  261. new FileInputStream(refList), Constants.CHARSET));
  262. try {
  263. String line;
  264. while ((line = br.readLine()) != null) {
  265. final String[] parts = line.split("[ \t]{1,}");
  266. final ObjectId origId = ObjectId.fromString(parts[0]);
  267. final String type = parts[1];
  268. final String name = parts[2];
  269. ObjectId id = rewrites.get(origId);
  270. if (id == null)
  271. id = origId;
  272. try {
  273. rw.parseAny(id);
  274. } catch (MissingObjectException mue) {
  275. if (!Constants.TYPE_COMMIT.equals(type)) {
  276. System.err.println("skipping " + type + " " + name);
  277. continue;
  278. }
  279. throw new MissingObjectException(id, type);
  280. }
  281. refs.put(name, new ObjectIdRef.Unpeeled(Ref.Storage.PACKED,
  282. name, id));
  283. }
  284. } finally {
  285. br.close();
  286. }
  287. return refs;
  288. }
  289. }