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.

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