You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RebuildCommitGraph.java 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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.text.MessageFormat;
  50. import java.util.ArrayList;
  51. import java.util.Date;
  52. import java.util.HashMap;
  53. import java.util.List;
  54. import java.util.ListIterator;
  55. import java.util.Map;
  56. import org.kohsuke.args4j.Argument;
  57. import org.kohsuke.args4j.Option;
  58. import org.eclipse.jgit.errors.MissingObjectException;
  59. import org.eclipse.jgit.errors.ObjectWritingException;
  60. import org.eclipse.jgit.lib.Commit;
  61. import org.eclipse.jgit.lib.Constants;
  62. import org.eclipse.jgit.lib.LockFile;
  63. import org.eclipse.jgit.lib.ObjectId;
  64. import org.eclipse.jgit.lib.ObjectIdRef;
  65. import org.eclipse.jgit.lib.ObjectWriter;
  66. import org.eclipse.jgit.lib.PersonIdent;
  67. import org.eclipse.jgit.lib.ProgressMonitor;
  68. import org.eclipse.jgit.lib.Ref;
  69. import org.eclipse.jgit.lib.RefUpdate;
  70. import org.eclipse.jgit.lib.RefWriter;
  71. import org.eclipse.jgit.lib.TextProgressMonitor;
  72. import org.eclipse.jgit.lib.Tree;
  73. import org.eclipse.jgit.pgm.CLIText;
  74. import org.eclipse.jgit.pgm.TextBuiltin;
  75. import org.eclipse.jgit.revwalk.RevWalk;
  76. /**
  77. * Recreates a repository from another one's commit graph.
  78. * <p>
  79. * <b>Do not run this on a repository unless you want to destroy it.</b>
  80. * <p>
  81. * To create the input files, in the source repository use:
  82. *
  83. * <pre>
  84. * git for-each-ref &gt;in.refs
  85. * git log --all '--pretty=format:%H %ct %P' &gt;in.dag
  86. * </pre>
  87. * <p>
  88. * Run the rebuild in either an empty repository, or a clone of the source. Any
  89. * missing commits (which might be the entire graph) will be created. All refs
  90. * will be modified to match the input exactly, which means some refs may be
  91. * deleted from the current repository.
  92. * <p>
  93. */
  94. class RebuildCommitGraph extends TextBuiltin {
  95. private final String REALLY = "--destroy-this-repository";
  96. @Option(name = REALLY, usage = "usage_approveDestructionOfRepository")
  97. boolean really;
  98. @Argument(index = 0, required = true, metaVar = "metaVar_refs", usage = "usage_forEachRefOutput")
  99. File refList;
  100. @Argument(index = 1, required = true, metaVar = "metaVar_refs", usage = "usage_logAllPretty")
  101. File graph;
  102. private final ProgressMonitor pm = new TextProgressMonitor();
  103. private Map<ObjectId, ObjectId> rewrites = new HashMap<ObjectId, ObjectId>();
  104. @Override
  105. protected void run() throws Exception {
  106. if (!really && !db.getAllRefs().isEmpty()) {
  107. System.err.println(
  108. MessageFormat.format(CLIText.get().fatalThisProgramWillDestroyTheRepository
  109. , db.getDirectory().getAbsolutePath(), REALLY));
  110. throw die(CLIText.get().needApprovalToDestroyCurrentRepository);
  111. }
  112. if (!refList.isFile())
  113. throw die(MessageFormat.format(CLIText.get().noSuchFile, refList.getPath()));
  114. if (!graph.isFile())
  115. throw die(MessageFormat.format(CLIText.get().noSuchFile, graph.getPath()));
  116. recreateCommitGraph();
  117. detachHead();
  118. deleteAllRefs();
  119. recreateRefs();
  120. }
  121. private void recreateCommitGraph() throws IOException {
  122. final RevWalk rw = new RevWalk(db);
  123. final Map<ObjectId, ToRewrite> toRewrite = new HashMap<ObjectId, ToRewrite>();
  124. List<ToRewrite> queue = new ArrayList<ToRewrite>();
  125. final BufferedReader br = new BufferedReader(new InputStreamReader(
  126. new FileInputStream(graph), Constants.CHARSET));
  127. try {
  128. String line;
  129. while ((line = br.readLine()) != null) {
  130. final String[] parts = line.split("[ \t]{1,}");
  131. final ObjectId oldId = ObjectId.fromString(parts[0]);
  132. try {
  133. rw.parseCommit(oldId);
  134. // We have it already. Don't rewrite it.
  135. continue;
  136. } catch (MissingObjectException mue) {
  137. // Fall through and rewrite it.
  138. }
  139. final long time = Long.parseLong(parts[1]) * 1000L;
  140. final ObjectId[] parents = new ObjectId[parts.length - 2];
  141. for (int i = 0; i < parents.length; i++) {
  142. parents[i] = ObjectId.fromString(parts[2 + i]);
  143. }
  144. final ToRewrite t = new ToRewrite(oldId, time, parents);
  145. toRewrite.put(oldId, t);
  146. queue.add(t);
  147. }
  148. } finally {
  149. br.close();
  150. }
  151. pm.beginTask("Rewriting commits", queue.size());
  152. final ObjectWriter ow = new ObjectWriter(db);
  153. final ObjectId emptyTree = ow.writeTree(new Tree(db));
  154. final PersonIdent me = new PersonIdent("jgit rebuild-commitgraph",
  155. "rebuild-commitgraph@localhost");
  156. while (!queue.isEmpty()) {
  157. final ListIterator<ToRewrite> itr = queue
  158. .listIterator(queue.size());
  159. queue = new ArrayList<ToRewrite>();
  160. REWRITE: while (itr.hasPrevious()) {
  161. final ToRewrite t = itr.previous();
  162. final ObjectId[] newParents = new ObjectId[t.oldParents.length];
  163. for (int k = 0; k < t.oldParents.length; k++) {
  164. final ToRewrite p = toRewrite.get(t.oldParents[k]);
  165. if (p != null) {
  166. if (p.newId == null) {
  167. // Must defer until after the parent is rewritten.
  168. queue.add(t);
  169. continue REWRITE;
  170. } else {
  171. newParents[k] = p.newId;
  172. }
  173. } else {
  174. // We have the old parent object. Use it.
  175. //
  176. newParents[k] = t.oldParents[k];
  177. }
  178. }
  179. final Commit newc = new Commit(db);
  180. newc.setTreeId(emptyTree);
  181. newc.setAuthor(new PersonIdent(me, new Date(t.commitTime)));
  182. newc.setCommitter(newc.getAuthor());
  183. newc.setParentIds(newParents);
  184. newc.setMessage("ORIGINAL " + t.oldId.name() + "\n");
  185. t.newId = ow.writeCommit(newc);
  186. rewrites.put(t.oldId, t.newId);
  187. pm.update(1);
  188. }
  189. }
  190. pm.endTask();
  191. }
  192. private static class ToRewrite {
  193. final ObjectId oldId;
  194. final long commitTime;
  195. final ObjectId[] oldParents;
  196. ObjectId newId;
  197. ToRewrite(final ObjectId o, final long t, final ObjectId[] p) {
  198. oldId = o;
  199. commitTime = t;
  200. oldParents = p;
  201. }
  202. }
  203. private void detachHead() throws IOException {
  204. final String head = db.getFullBranch();
  205. final ObjectId id = db.resolve(Constants.HEAD);
  206. if (!ObjectId.isId(head) && id != null) {
  207. final LockFile lf;
  208. lf = new LockFile(new File(db.getDirectory(), Constants.HEAD));
  209. if (!lf.lock())
  210. throw new IOException(MessageFormat.format(CLIText.get().cannotLock, Constants.HEAD));
  211. lf.write(id);
  212. if (!lf.commit())
  213. throw new IOException(CLIText.get().cannotDeatchHEAD);
  214. }
  215. }
  216. private void deleteAllRefs() throws Exception {
  217. final RevWalk rw = new RevWalk(db);
  218. for (final Ref r : db.getAllRefs().values()) {
  219. if (Constants.HEAD.equals(r.getName()))
  220. continue;
  221. final RefUpdate u = db.updateRef(r.getName());
  222. u.setForceUpdate(true);
  223. u.delete(rw);
  224. }
  225. }
  226. private void recreateRefs() throws Exception {
  227. final Map<String, Ref> refs = computeNewRefs();
  228. new RefWriter(refs.values()) {
  229. @Override
  230. protected void writeFile(final String name, final byte[] content)
  231. throws IOException {
  232. final File file = new File(db.getDirectory(), name);
  233. final LockFile lck = new LockFile(file);
  234. if (!lck.lock())
  235. throw new ObjectWritingException(MessageFormat.format(CLIText.get().cantWrite, file));
  236. try {
  237. lck.write(content);
  238. } catch (IOException ioe) {
  239. throw new ObjectWritingException(MessageFormat.format(CLIText.get().cantWrite, file));
  240. }
  241. if (!lck.commit())
  242. throw new ObjectWritingException(MessageFormat.format(CLIText.get().cantWrite, file));
  243. }
  244. }.writePackedRefs();
  245. }
  246. private Map<String, Ref> computeNewRefs() throws IOException {
  247. final RevWalk rw = new RevWalk(db);
  248. final Map<String, Ref> refs = new HashMap<String, Ref>();
  249. final BufferedReader br = new BufferedReader(new InputStreamReader(
  250. new FileInputStream(refList), Constants.CHARSET));
  251. try {
  252. String line;
  253. while ((line = br.readLine()) != null) {
  254. final String[] parts = line.split("[ \t]{1,}");
  255. final ObjectId origId = ObjectId.fromString(parts[0]);
  256. final String type = parts[1];
  257. final String name = parts[2];
  258. ObjectId id = rewrites.get(origId);
  259. if (id == null)
  260. id = origId;
  261. try {
  262. rw.parseAny(id);
  263. } catch (MissingObjectException mue) {
  264. if (!Constants.TYPE_COMMIT.equals(type)) {
  265. System.err.println(MessageFormat.format(CLIText.get().skippingObject, type, name));
  266. continue;
  267. }
  268. throw new MissingObjectException(id, type);
  269. }
  270. refs.put(name, new ObjectIdRef.Unpeeled(Ref.Storage.PACKED,
  271. name, id));
  272. }
  273. } finally {
  274. br.close();
  275. }
  276. return refs;
  277. }
  278. }