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.

Repository.java 50KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615
  1. /*
  2. * Copyright (C) 2007, Dave Watson <dwatson@mimvista.com>
  3. * Copyright (C) 2008-2010, Google Inc.
  4. * Copyright (C) 2006-2010, Robin Rosenberg <robin.rosenberg@dewire.com>
  5. * Copyright (C) 2006-2012, Shawn O. Pearce <spearce@spearce.org>
  6. * Copyright (C) 2012, Daniel Megert <daniel_megert@ch.ibm.com>
  7. * and other copyright owners as documented in the project's IP log.
  8. *
  9. * This program and the accompanying materials are made available
  10. * under the terms of the Eclipse Distribution License v1.0 which
  11. * accompanies this distribution, is reproduced below, and is
  12. * available at http://www.eclipse.org/org/documents/edl-v10.php
  13. *
  14. * All rights reserved.
  15. *
  16. * Redistribution and use in source and binary forms, with or
  17. * without modification, are permitted provided that the following
  18. * conditions are met:
  19. *
  20. * - Redistributions of source code must retain the above copyright
  21. * notice, this list of conditions and the following disclaimer.
  22. *
  23. * - Redistributions in binary form must reproduce the above
  24. * copyright notice, this list of conditions and the following
  25. * disclaimer in the documentation and/or other materials provided
  26. * with the distribution.
  27. *
  28. * - Neither the name of the Eclipse Foundation, Inc. nor the
  29. * names of its contributors may be used to endorse or promote
  30. * products derived from this software without specific prior
  31. * written permission.
  32. *
  33. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  34. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  35. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  36. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  37. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  38. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  39. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  40. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  41. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  42. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  43. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  44. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  45. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  46. */
  47. package org.eclipse.jgit.lib;
  48. import java.io.BufferedOutputStream;
  49. import java.io.File;
  50. import java.io.FileNotFoundException;
  51. import java.io.FileOutputStream;
  52. import java.io.IOException;
  53. import java.net.URISyntaxException;
  54. import java.text.MessageFormat;
  55. import java.util.Collection;
  56. import java.util.Collections;
  57. import java.util.HashMap;
  58. import java.util.HashSet;
  59. import java.util.LinkedList;
  60. import java.util.List;
  61. import java.util.Map;
  62. import java.util.Set;
  63. import java.util.concurrent.atomic.AtomicInteger;
  64. import org.eclipse.jgit.dircache.DirCache;
  65. import org.eclipse.jgit.dircache.DirCacheCheckout;
  66. import org.eclipse.jgit.dircache.InvalidPathException;
  67. import org.eclipse.jgit.errors.AmbiguousObjectException;
  68. import org.eclipse.jgit.errors.CorruptObjectException;
  69. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  70. import org.eclipse.jgit.errors.MissingObjectException;
  71. import org.eclipse.jgit.errors.NoWorkTreeException;
  72. import org.eclipse.jgit.errors.RevisionSyntaxException;
  73. import org.eclipse.jgit.events.IndexChangedEvent;
  74. import org.eclipse.jgit.events.IndexChangedListener;
  75. import org.eclipse.jgit.events.ListenerList;
  76. import org.eclipse.jgit.events.RepositoryEvent;
  77. import org.eclipse.jgit.internal.JGitText;
  78. import org.eclipse.jgit.revwalk.RevBlob;
  79. import org.eclipse.jgit.revwalk.RevCommit;
  80. import org.eclipse.jgit.revwalk.RevObject;
  81. import org.eclipse.jgit.revwalk.RevTree;
  82. import org.eclipse.jgit.revwalk.RevWalk;
  83. import org.eclipse.jgit.transport.RefSpec;
  84. import org.eclipse.jgit.transport.RemoteConfig;
  85. import org.eclipse.jgit.treewalk.TreeWalk;
  86. import org.eclipse.jgit.util.FS;
  87. import org.eclipse.jgit.util.FileUtils;
  88. import org.eclipse.jgit.util.IO;
  89. import org.eclipse.jgit.util.RawParseUtils;
  90. import org.eclipse.jgit.util.io.SafeBufferedOutputStream;
  91. /**
  92. * Represents a Git repository.
  93. * <p>
  94. * A repository holds all objects and refs used for managing source code (could
  95. * be any type of file, but source code is what SCM's are typically used for).
  96. * <p>
  97. * This class is thread-safe.
  98. */
  99. public abstract class Repository {
  100. private static final ListenerList globalListeners = new ListenerList();
  101. /** @return the global listener list observing all events in this JVM. */
  102. public static ListenerList getGlobalListenerList() {
  103. return globalListeners;
  104. }
  105. private final AtomicInteger useCnt = new AtomicInteger(1);
  106. /** Metadata directory holding the repository's critical files. */
  107. private final File gitDir;
  108. /** File abstraction used to resolve paths. */
  109. private final FS fs;
  110. private final ListenerList myListeners = new ListenerList();
  111. /** If not bare, the top level directory of the working files. */
  112. private final File workTree;
  113. /** If not bare, the index file caching the working file states. */
  114. private final File indexFile;
  115. /**
  116. * Initialize a new repository instance.
  117. *
  118. * @param options
  119. * options to configure the repository.
  120. */
  121. protected Repository(final BaseRepositoryBuilder options) {
  122. gitDir = options.getGitDir();
  123. fs = options.getFS();
  124. workTree = options.getWorkTree();
  125. indexFile = options.getIndexFile();
  126. }
  127. /** @return listeners observing only events on this repository. */
  128. public ListenerList getListenerList() {
  129. return myListeners;
  130. }
  131. /**
  132. * Fire an event to all registered listeners.
  133. * <p>
  134. * The source repository of the event is automatically set to this
  135. * repository, before the event is delivered to any listeners.
  136. *
  137. * @param event
  138. * the event to deliver.
  139. */
  140. public void fireEvent(RepositoryEvent<?> event) {
  141. event.setRepository(this);
  142. myListeners.dispatch(event);
  143. globalListeners.dispatch(event);
  144. }
  145. /**
  146. * Create a new Git repository.
  147. * <p>
  148. * Repository with working tree is created using this method. This method is
  149. * the same as {@code create(false)}.
  150. *
  151. * @throws IOException
  152. * @see #create(boolean)
  153. */
  154. public void create() throws IOException {
  155. create(false);
  156. }
  157. /**
  158. * Create a new Git repository initializing the necessary files and
  159. * directories.
  160. *
  161. * @param bare
  162. * if true, a bare repository (a repository without a working
  163. * directory) is created.
  164. * @throws IOException
  165. * in case of IO problem
  166. */
  167. public abstract void create(boolean bare) throws IOException;
  168. /** @return local metadata directory; null if repository isn't local. */
  169. public File getDirectory() {
  170. return gitDir;
  171. }
  172. /**
  173. * @return the object database which stores this repository's data.
  174. */
  175. public abstract ObjectDatabase getObjectDatabase();
  176. /** @return a new inserter to create objects in {@link #getObjectDatabase()} */
  177. public ObjectInserter newObjectInserter() {
  178. return getObjectDatabase().newInserter();
  179. }
  180. /** @return a new reader to read objects from {@link #getObjectDatabase()} */
  181. public ObjectReader newObjectReader() {
  182. return getObjectDatabase().newReader();
  183. }
  184. /** @return the reference database which stores the reference namespace. */
  185. public abstract RefDatabase getRefDatabase();
  186. /**
  187. * @return the configuration of this repository
  188. */
  189. public abstract StoredConfig getConfig();
  190. /**
  191. * @return the used file system abstraction
  192. */
  193. public FS getFS() {
  194. return fs;
  195. }
  196. /**
  197. * @param objectId
  198. * @return true if the specified object is stored in this repo or any of the
  199. * known shared repositories.
  200. */
  201. public boolean hasObject(AnyObjectId objectId) {
  202. try {
  203. return getObjectDatabase().has(objectId);
  204. } catch (IOException e) {
  205. // Legacy API, assume error means "no"
  206. return false;
  207. }
  208. }
  209. /**
  210. * Open an object from this repository.
  211. * <p>
  212. * This is a one-shot call interface which may be faster than allocating a
  213. * {@link #newObjectReader()} to perform the lookup.
  214. *
  215. * @param objectId
  216. * identity of the object to open.
  217. * @return a {@link ObjectLoader} for accessing the object.
  218. * @throws MissingObjectException
  219. * the object does not exist.
  220. * @throws IOException
  221. * the object store cannot be accessed.
  222. */
  223. public ObjectLoader open(final AnyObjectId objectId)
  224. throws MissingObjectException, IOException {
  225. return getObjectDatabase().open(objectId);
  226. }
  227. /**
  228. * Open an object from this repository.
  229. * <p>
  230. * This is a one-shot call interface which may be faster than allocating a
  231. * {@link #newObjectReader()} to perform the lookup.
  232. *
  233. * @param objectId
  234. * identity of the object to open.
  235. * @param typeHint
  236. * hint about the type of object being requested, e.g.
  237. * {@link Constants#OBJ_BLOB}; {@link ObjectReader#OBJ_ANY} if
  238. * the object type is not known, or does not matter to the
  239. * caller.
  240. * @return a {@link ObjectLoader} for accessing the object.
  241. * @throws MissingObjectException
  242. * the object does not exist.
  243. * @throws IncorrectObjectTypeException
  244. * typeHint was not OBJ_ANY, and the object's actual type does
  245. * not match typeHint.
  246. * @throws IOException
  247. * the object store cannot be accessed.
  248. */
  249. public ObjectLoader open(AnyObjectId objectId, int typeHint)
  250. throws MissingObjectException, IncorrectObjectTypeException,
  251. IOException {
  252. return getObjectDatabase().open(objectId, typeHint);
  253. }
  254. /**
  255. * Create a command to update, create or delete a ref in this repository.
  256. *
  257. * @param ref
  258. * name of the ref the caller wants to modify.
  259. * @return an update command. The caller must finish populating this command
  260. * and then invoke one of the update methods to actually make a
  261. * change.
  262. * @throws IOException
  263. * a symbolic ref was passed in and could not be resolved back
  264. * to the base ref, as the symbolic ref could not be read.
  265. */
  266. public RefUpdate updateRef(final String ref) throws IOException {
  267. return updateRef(ref, false);
  268. }
  269. /**
  270. * Create a command to update, create or delete a ref in this repository.
  271. *
  272. * @param ref
  273. * name of the ref the caller wants to modify.
  274. * @param detach
  275. * true to create a detached head
  276. * @return an update command. The caller must finish populating this command
  277. * and then invoke one of the update methods to actually make a
  278. * change.
  279. * @throws IOException
  280. * a symbolic ref was passed in and could not be resolved back
  281. * to the base ref, as the symbolic ref could not be read.
  282. */
  283. public RefUpdate updateRef(final String ref, final boolean detach) throws IOException {
  284. return getRefDatabase().newUpdate(ref, detach);
  285. }
  286. /**
  287. * Create a command to rename a ref in this repository
  288. *
  289. * @param fromRef
  290. * name of ref to rename from
  291. * @param toRef
  292. * name of ref to rename to
  293. * @return an update command that knows how to rename a branch to another.
  294. * @throws IOException
  295. * the rename could not be performed.
  296. *
  297. */
  298. public RefRename renameRef(final String fromRef, final String toRef) throws IOException {
  299. return getRefDatabase().newRename(fromRef, toRef);
  300. }
  301. /**
  302. * Parse a git revision string and return an object id.
  303. *
  304. * Combinations of these operators are supported:
  305. * <ul>
  306. * <li><b>HEAD</b>, <b>MERGE_HEAD</b>, <b>FETCH_HEAD</b></li>
  307. * <li><b>SHA-1</b>: a complete or abbreviated SHA-1</li>
  308. * <li><b>refs/...</b>: a complete reference name</li>
  309. * <li><b>short-name</b>: a short reference name under {@code refs/heads},
  310. * {@code refs/tags}, or {@code refs/remotes} namespace</li>
  311. * <li><b>tag-NN-gABBREV</b>: output from describe, parsed by treating
  312. * {@code ABBREV} as an abbreviated SHA-1.</li>
  313. * <li><i>id</i><b>^</b>: first parent of commit <i>id</i>, this is the same
  314. * as {@code id^1}</li>
  315. * <li><i>id</i><b>^0</b>: ensure <i>id</i> is a commit</li>
  316. * <li><i>id</i><b>^n</b>: n-th parent of commit <i>id</i></li>
  317. * <li><i>id</i><b>~n</b>: n-th historical ancestor of <i>id</i>, by first
  318. * parent. {@code id~3} is equivalent to {@code id^1^1^1} or {@code id^^^}.</li>
  319. * <li><i>id</i><b>:path</b>: Lookup path under tree named by <i>id</i></li>
  320. * <li><i>id</i><b>^{commit}</b>: ensure <i>id</i> is a commit</li>
  321. * <li><i>id</i><b>^{tree}</b>: ensure <i>id</i> is a tree</li>
  322. * <li><i>id</i><b>^{tag}</b>: ensure <i>id</i> is a tag</li>
  323. * <li><i>id</i><b>^{blob}</b>: ensure <i>id</i> is a blob</li>
  324. * </ul>
  325. *
  326. * <p>
  327. * The following operators are specified by Git conventions, but are not
  328. * supported by this method:
  329. * <ul>
  330. * <li><b>ref@{n}</b>: n-th version of ref as given by its reflog</li>
  331. * <li><b>ref@{time}</b>: value of ref at the designated time</li>
  332. * </ul>
  333. *
  334. * @param revstr
  335. * A git object references expression
  336. * @return an ObjectId or null if revstr can't be resolved to any ObjectId
  337. * @throws AmbiguousObjectException
  338. * {@code revstr} contains an abbreviated ObjectId and this
  339. * repository contains more than one object which match to the
  340. * input abbreviation.
  341. * @throws IncorrectObjectTypeException
  342. * the id parsed does not meet the type required to finish
  343. * applying the operators in the expression.
  344. * @throws RevisionSyntaxException
  345. * the expression is not supported by this implementation, or
  346. * does not meet the standard syntax.
  347. * @throws IOException
  348. * on serious errors
  349. */
  350. public ObjectId resolve(final String revstr)
  351. throws AmbiguousObjectException, IncorrectObjectTypeException,
  352. RevisionSyntaxException, IOException {
  353. RevWalk rw = new RevWalk(this);
  354. try {
  355. Object resolved = resolve(rw, revstr);
  356. if (resolved instanceof String) {
  357. return getRef((String) resolved).getLeaf().getObjectId();
  358. } else {
  359. return (ObjectId) resolved;
  360. }
  361. } finally {
  362. rw.release();
  363. }
  364. }
  365. /**
  366. * Simplify an expression, but unlike {@link #resolve(String)} it will not
  367. * resolve a branch passed or resulting from the expression, such as @{-}.
  368. * Thus this method can be used to process an expression to a method that
  369. * expects a branch or revision id.
  370. *
  371. * @param revstr
  372. * @return object id or ref name from resolved expression
  373. * @throws AmbiguousObjectException
  374. * @throws IOException
  375. */
  376. public String simplify(final String revstr)
  377. throws AmbiguousObjectException, IOException {
  378. RevWalk rw = new RevWalk(this);
  379. try {
  380. Object resolved = resolve(rw, revstr);
  381. if (resolved != null)
  382. if (resolved instanceof String)
  383. return (String) resolved;
  384. else
  385. return ((AnyObjectId) resolved).getName();
  386. return null;
  387. } finally {
  388. rw.release();
  389. }
  390. }
  391. private Object resolve(final RevWalk rw, final String revstr)
  392. throws IOException {
  393. char[] revChars = revstr.toCharArray();
  394. RevObject rev = null;
  395. String name = null;
  396. int done = 0;
  397. for (int i = 0; i < revChars.length; ++i) {
  398. switch (revChars[i]) {
  399. case '^':
  400. if (rev == null) {
  401. if (name == null)
  402. if (done == 0)
  403. name = new String(revChars, done, i);
  404. else {
  405. done = i + 1;
  406. break;
  407. }
  408. rev = parseSimple(rw, name);
  409. name = null;
  410. if (rev == null)
  411. return null;
  412. }
  413. if (i + 1 < revChars.length) {
  414. switch (revChars[i + 1]) {
  415. case '0':
  416. case '1':
  417. case '2':
  418. case '3':
  419. case '4':
  420. case '5':
  421. case '6':
  422. case '7':
  423. case '8':
  424. case '9':
  425. int j;
  426. rev = rw.parseCommit(rev);
  427. for (j = i + 1; j < revChars.length; ++j) {
  428. if (!Character.isDigit(revChars[j]))
  429. break;
  430. }
  431. String parentnum = new String(revChars, i + 1, j - i
  432. - 1);
  433. int pnum;
  434. try {
  435. pnum = Integer.parseInt(parentnum);
  436. } catch (NumberFormatException e) {
  437. throw new RevisionSyntaxException(
  438. JGitText.get().invalidCommitParentNumber,
  439. revstr);
  440. }
  441. if (pnum != 0) {
  442. RevCommit commit = (RevCommit) rev;
  443. if (pnum > commit.getParentCount())
  444. rev = null;
  445. else
  446. rev = commit.getParent(pnum - 1);
  447. }
  448. i = j - 1;
  449. done = j;
  450. break;
  451. case '{':
  452. int k;
  453. String item = null;
  454. for (k = i + 2; k < revChars.length; ++k) {
  455. if (revChars[k] == '}') {
  456. item = new String(revChars, i + 2, k - i - 2);
  457. break;
  458. }
  459. }
  460. i = k;
  461. if (item != null)
  462. if (item.equals("tree")) { //$NON-NLS-1$
  463. rev = rw.parseTree(rev);
  464. } else if (item.equals("commit")) { //$NON-NLS-1$
  465. rev = rw.parseCommit(rev);
  466. } else if (item.equals("blob")) { //$NON-NLS-1$
  467. rev = rw.peel(rev);
  468. if (!(rev instanceof RevBlob))
  469. throw new IncorrectObjectTypeException(rev,
  470. Constants.TYPE_BLOB);
  471. } else if (item.equals("")) { //$NON-NLS-1$
  472. rev = rw.peel(rev);
  473. } else
  474. throw new RevisionSyntaxException(revstr);
  475. else
  476. throw new RevisionSyntaxException(revstr);
  477. done = k;
  478. break;
  479. default:
  480. rev = rw.peel(rev);
  481. if (rev instanceof RevCommit) {
  482. RevCommit commit = ((RevCommit) rev);
  483. if (commit.getParentCount() == 0)
  484. rev = null;
  485. else
  486. rev = commit.getParent(0);
  487. } else
  488. throw new IncorrectObjectTypeException(rev,
  489. Constants.TYPE_COMMIT);
  490. }
  491. } else {
  492. rev = rw.peel(rev);
  493. if (rev instanceof RevCommit) {
  494. RevCommit commit = ((RevCommit) rev);
  495. if (commit.getParentCount() == 0)
  496. rev = null;
  497. else
  498. rev = commit.getParent(0);
  499. } else
  500. throw new IncorrectObjectTypeException(rev,
  501. Constants.TYPE_COMMIT);
  502. }
  503. done = i + 1;
  504. break;
  505. case '~':
  506. if (rev == null) {
  507. if (name == null)
  508. if (done == 0)
  509. name = new String(revChars, done, i);
  510. else {
  511. done = i + 1;
  512. break;
  513. }
  514. rev = parseSimple(rw, name);
  515. name = null;
  516. if (rev == null)
  517. return null;
  518. }
  519. rev = rw.peel(rev);
  520. if (!(rev instanceof RevCommit))
  521. throw new IncorrectObjectTypeException(rev,
  522. Constants.TYPE_COMMIT);
  523. int l;
  524. for (l = i + 1; l < revChars.length; ++l) {
  525. if (!Character.isDigit(revChars[l]))
  526. break;
  527. }
  528. int dist;
  529. if (l - i > 1) {
  530. String distnum = new String(revChars, i + 1, l - i - 1);
  531. try {
  532. dist = Integer.parseInt(distnum);
  533. } catch (NumberFormatException e) {
  534. throw new RevisionSyntaxException(
  535. JGitText.get().invalidAncestryLength, revstr);
  536. }
  537. } else
  538. dist = 1;
  539. while (dist > 0) {
  540. RevCommit commit = (RevCommit) rev;
  541. if (commit.getParentCount() == 0) {
  542. rev = null;
  543. break;
  544. }
  545. commit = commit.getParent(0);
  546. rw.parseHeaders(commit);
  547. rev = commit;
  548. --dist;
  549. }
  550. i = l - 1;
  551. done = l;
  552. break;
  553. case '@':
  554. if (rev != null)
  555. throw new RevisionSyntaxException(revstr);
  556. if (i + 1 < revChars.length && revChars[i + 1] != '{')
  557. continue;
  558. int m;
  559. String time = null;
  560. for (m = i + 2; m < revChars.length; ++m) {
  561. if (revChars[m] == '}') {
  562. time = new String(revChars, i + 2, m - i - 2);
  563. break;
  564. }
  565. }
  566. if (time != null) {
  567. if (time.equals("upstream")) { //$NON-NLS-1$
  568. if (name == null)
  569. name = new String(revChars, done, i);
  570. if (name.equals("")) //$NON-NLS-1$
  571. // Currently checked out branch, HEAD if
  572. // detached
  573. name = Constants.HEAD;
  574. if (!Repository.isValidRefName("x/" + name)) //$NON-NLS-1$
  575. throw new RevisionSyntaxException(revstr);
  576. Ref ref = getRef(name);
  577. name = null;
  578. if (ref == null)
  579. return null;
  580. if (ref.isSymbolic())
  581. ref = ref.getLeaf();
  582. name = ref.getName();
  583. RemoteConfig remoteConfig;
  584. try {
  585. remoteConfig = new RemoteConfig(getConfig(),
  586. "origin"); //$NON-NLS-1$
  587. } catch (URISyntaxException e) {
  588. throw new RevisionSyntaxException(revstr);
  589. }
  590. String remoteBranchName = getConfig()
  591. .getString(
  592. ConfigConstants.CONFIG_BRANCH_SECTION,
  593. Repository.shortenRefName(ref.getName()),
  594. ConfigConstants.CONFIG_KEY_MERGE);
  595. List<RefSpec> fetchRefSpecs = remoteConfig
  596. .getFetchRefSpecs();
  597. for (RefSpec refSpec : fetchRefSpecs) {
  598. if (refSpec.matchSource(remoteBranchName)) {
  599. RefSpec expandFromSource = refSpec
  600. .expandFromSource(remoteBranchName);
  601. name = expandFromSource.getDestination();
  602. break;
  603. }
  604. }
  605. if (name == null)
  606. throw new RevisionSyntaxException(revstr);
  607. } else if (time.matches("^-\\d+$")) { //$NON-NLS-1$
  608. if (name != null)
  609. throw new RevisionSyntaxException(revstr);
  610. else {
  611. String previousCheckout = resolveReflogCheckout(-Integer
  612. .parseInt(time));
  613. if (ObjectId.isId(previousCheckout))
  614. rev = parseSimple(rw, previousCheckout);
  615. else
  616. name = previousCheckout;
  617. }
  618. } else {
  619. if (name == null)
  620. name = new String(revChars, done, i);
  621. if (name.equals("")) //$NON-NLS-1$
  622. name = Constants.HEAD;
  623. if (!Repository.isValidRefName("x/" + name)) //$NON-NLS-1$
  624. throw new RevisionSyntaxException(revstr);
  625. Ref ref = getRef(name);
  626. name = null;
  627. if (ref == null)
  628. return null;
  629. // @{n} means current branch, not HEAD@{1} unless
  630. // detached
  631. if (ref.isSymbolic())
  632. ref = ref.getLeaf();
  633. rev = resolveReflog(rw, ref, time);
  634. }
  635. i = m;
  636. } else
  637. throw new RevisionSyntaxException(revstr);
  638. break;
  639. case ':': {
  640. RevTree tree;
  641. if (rev == null) {
  642. if (name == null)
  643. name = new String(revChars, done, i);
  644. if (name.equals("")) //$NON-NLS-1$
  645. name = Constants.HEAD;
  646. rev = parseSimple(rw, name);
  647. name = null;
  648. }
  649. if (rev == null)
  650. return null;
  651. tree = rw.parseTree(rev);
  652. if (i == revChars.length - 1)
  653. return tree.copy();
  654. TreeWalk tw = TreeWalk.forPath(rw.getObjectReader(),
  655. new String(revChars, i + 1, revChars.length - i - 1),
  656. tree);
  657. return tw != null ? tw.getObjectId(0) : null;
  658. }
  659. default:
  660. if (rev != null)
  661. throw new RevisionSyntaxException(revstr);
  662. }
  663. }
  664. if (rev != null)
  665. return rev.copy();
  666. if (name != null)
  667. return name;
  668. if (done == revstr.length())
  669. return null;
  670. name = revstr.substring(done);
  671. if (!Repository.isValidRefName("x/" + name)) //$NON-NLS-1$
  672. throw new RevisionSyntaxException(revstr);
  673. if (getRef(name) != null)
  674. return name;
  675. return resolveSimple(name);
  676. }
  677. private static boolean isHex(char c) {
  678. return ('0' <= c && c <= '9') //
  679. || ('a' <= c && c <= 'f') //
  680. || ('A' <= c && c <= 'F');
  681. }
  682. private static boolean isAllHex(String str, int ptr) {
  683. while (ptr < str.length()) {
  684. if (!isHex(str.charAt(ptr++)))
  685. return false;
  686. }
  687. return true;
  688. }
  689. private RevObject parseSimple(RevWalk rw, String revstr) throws IOException {
  690. ObjectId id = resolveSimple(revstr);
  691. return id != null ? rw.parseAny(id) : null;
  692. }
  693. private ObjectId resolveSimple(final String revstr) throws IOException {
  694. if (ObjectId.isId(revstr))
  695. return ObjectId.fromString(revstr);
  696. if (Repository.isValidRefName("x/" + revstr)) { //$NON-NLS-1$
  697. Ref r = getRefDatabase().getRef(revstr);
  698. if (r != null)
  699. return r.getObjectId();
  700. }
  701. if (AbbreviatedObjectId.isId(revstr))
  702. return resolveAbbreviation(revstr);
  703. int dashg = revstr.indexOf("-g"); //$NON-NLS-1$
  704. if ((dashg + 5) < revstr.length() && 0 <= dashg
  705. && isHex(revstr.charAt(dashg + 2))
  706. && isHex(revstr.charAt(dashg + 3))
  707. && isAllHex(revstr, dashg + 4)) {
  708. // Possibly output from git describe?
  709. String s = revstr.substring(dashg + 2);
  710. if (AbbreviatedObjectId.isId(s))
  711. return resolveAbbreviation(s);
  712. }
  713. return null;
  714. }
  715. private String resolveReflogCheckout(int checkoutNo)
  716. throws IOException {
  717. List<ReflogEntry> reflogEntries = getReflogReader(Constants.HEAD)
  718. .getReverseEntries();
  719. for (ReflogEntry entry : reflogEntries) {
  720. CheckoutEntry checkout = entry.parseCheckout();
  721. if (checkout != null)
  722. if (checkoutNo-- == 1)
  723. return checkout.getFromBranch();
  724. }
  725. return null;
  726. }
  727. private RevCommit resolveReflog(RevWalk rw, Ref ref, String time)
  728. throws IOException {
  729. int number;
  730. try {
  731. number = Integer.parseInt(time);
  732. } catch (NumberFormatException nfe) {
  733. throw new RevisionSyntaxException(MessageFormat.format(
  734. JGitText.get().invalidReflogRevision, time));
  735. }
  736. assert number >= 0;
  737. ReflogReader reader = getReflogReader(ref.getName());
  738. ReflogEntry entry = reader.getReverseEntry(number);
  739. if (entry == null)
  740. throw new RevisionSyntaxException(MessageFormat.format(
  741. JGitText.get().reflogEntryNotFound,
  742. Integer.valueOf(number), ref.getName()));
  743. return rw.parseCommit(entry.getNewId());
  744. }
  745. private ObjectId resolveAbbreviation(final String revstr) throws IOException,
  746. AmbiguousObjectException {
  747. AbbreviatedObjectId id = AbbreviatedObjectId.fromString(revstr);
  748. ObjectReader reader = newObjectReader();
  749. try {
  750. Collection<ObjectId> matches = reader.resolve(id);
  751. if (matches.size() == 0)
  752. return null;
  753. else if (matches.size() == 1)
  754. return matches.iterator().next();
  755. else
  756. throw new AmbiguousObjectException(id, matches);
  757. } finally {
  758. reader.release();
  759. }
  760. }
  761. /** Increment the use counter by one, requiring a matched {@link #close()}. */
  762. public void incrementOpen() {
  763. useCnt.incrementAndGet();
  764. }
  765. /** Decrement the use count, and maybe close resources. */
  766. public void close() {
  767. if (useCnt.decrementAndGet() == 0) {
  768. doClose();
  769. }
  770. }
  771. /**
  772. * Invoked when the use count drops to zero during {@link #close()}.
  773. * <p>
  774. * The default implementation closes the object and ref databases.
  775. */
  776. protected void doClose() {
  777. getObjectDatabase().close();
  778. getRefDatabase().close();
  779. }
  780. @SuppressWarnings("nls")
  781. public String toString() {
  782. String desc;
  783. if (getDirectory() != null)
  784. desc = getDirectory().getPath();
  785. else
  786. desc = getClass().getSimpleName() + "-" //$NON-NLS-1$
  787. + System.identityHashCode(this);
  788. return "Repository[" + desc + "]"; //$NON-NLS-1$
  789. }
  790. /**
  791. * Get the name of the reference that {@code HEAD} points to.
  792. * <p>
  793. * This is essentially the same as doing:
  794. *
  795. * <pre>
  796. * return getRef(Constants.HEAD).getTarget().getName()
  797. * </pre>
  798. *
  799. * Except when HEAD is detached, in which case this method returns the
  800. * current ObjectId in hexadecimal string format.
  801. *
  802. * @return name of current branch (for example {@code refs/heads/master}) or
  803. * an ObjectId in hex format if the current branch is detached.
  804. * @throws IOException
  805. */
  806. public String getFullBranch() throws IOException {
  807. Ref head = getRef(Constants.HEAD);
  808. if (head == null)
  809. return null;
  810. if (head.isSymbolic())
  811. return head.getTarget().getName();
  812. if (head.getObjectId() != null)
  813. return head.getObjectId().name();
  814. return null;
  815. }
  816. /**
  817. * Get the short name of the current branch that {@code HEAD} points to.
  818. * <p>
  819. * This is essentially the same as {@link #getFullBranch()}, except the
  820. * leading prefix {@code refs/heads/} is removed from the reference before
  821. * it is returned to the caller.
  822. *
  823. * @return name of current branch (for example {@code master}), or an
  824. * ObjectId in hex format if the current branch is detached.
  825. * @throws IOException
  826. */
  827. public String getBranch() throws IOException {
  828. String name = getFullBranch();
  829. if (name != null)
  830. return shortenRefName(name);
  831. return name;
  832. }
  833. /**
  834. * Objects known to exist but not expressed by {@link #getAllRefs()}.
  835. * <p>
  836. * When a repository borrows objects from another repository, it can
  837. * advertise that it safely has that other repository's references, without
  838. * exposing any other details about the other repository. This may help
  839. * a client trying to push changes avoid pushing more than it needs to.
  840. *
  841. * @return unmodifiable collection of other known objects.
  842. */
  843. public Set<ObjectId> getAdditionalHaves() {
  844. return Collections.emptySet();
  845. }
  846. /**
  847. * Get a ref by name.
  848. *
  849. * @param name
  850. * the name of the ref to lookup. May be a short-hand form, e.g.
  851. * "master" which is is automatically expanded to
  852. * "refs/heads/master" if "refs/heads/master" already exists.
  853. * @return the Ref with the given name, or null if it does not exist
  854. * @throws IOException
  855. */
  856. public Ref getRef(final String name) throws IOException {
  857. return getRefDatabase().getRef(name);
  858. }
  859. /**
  860. * @return mutable map of all known refs (heads, tags, remotes).
  861. */
  862. public Map<String, Ref> getAllRefs() {
  863. try {
  864. return getRefDatabase().getRefs(RefDatabase.ALL);
  865. } catch (IOException e) {
  866. return new HashMap<String, Ref>();
  867. }
  868. }
  869. /**
  870. * @return mutable map of all tags; key is short tag name ("v1.0") and value
  871. * of the entry contains the ref with the full tag name
  872. * ("refs/tags/v1.0").
  873. */
  874. public Map<String, Ref> getTags() {
  875. try {
  876. return getRefDatabase().getRefs(Constants.R_TAGS);
  877. } catch (IOException e) {
  878. return new HashMap<String, Ref>();
  879. }
  880. }
  881. /**
  882. * Peel a possibly unpeeled reference to an annotated tag.
  883. * <p>
  884. * If the ref cannot be peeled (as it does not refer to an annotated tag)
  885. * the peeled id stays null, but {@link Ref#isPeeled()} will be true.
  886. *
  887. * @param ref
  888. * The ref to peel
  889. * @return <code>ref</code> if <code>ref.isPeeled()</code> is true; else a
  890. * new Ref object representing the same data as Ref, but isPeeled()
  891. * will be true and getPeeledObjectId will contain the peeled object
  892. * (or null).
  893. */
  894. public Ref peel(final Ref ref) {
  895. try {
  896. return getRefDatabase().peel(ref);
  897. } catch (IOException e) {
  898. // Historical accident; if the reference cannot be peeled due
  899. // to some sort of repository access problem we claim that the
  900. // same as if the reference was not an annotated tag.
  901. return ref;
  902. }
  903. }
  904. /**
  905. * @return a map with all objects referenced by a peeled ref.
  906. */
  907. public Map<AnyObjectId, Set<Ref>> getAllRefsByPeeledObjectId() {
  908. Map<String, Ref> allRefs = getAllRefs();
  909. Map<AnyObjectId, Set<Ref>> ret = new HashMap<AnyObjectId, Set<Ref>>(allRefs.size());
  910. for (Ref ref : allRefs.values()) {
  911. ref = peel(ref);
  912. AnyObjectId target = ref.getPeeledObjectId();
  913. if (target == null)
  914. target = ref.getObjectId();
  915. // We assume most Sets here are singletons
  916. Set<Ref> oset = ret.put(target, Collections.singleton(ref));
  917. if (oset != null) {
  918. // that was not the case (rare)
  919. if (oset.size() == 1) {
  920. // Was a read-only singleton, we must copy to a new Set
  921. oset = new HashSet<Ref>(oset);
  922. }
  923. ret.put(target, oset);
  924. oset.add(ref);
  925. }
  926. }
  927. return ret;
  928. }
  929. /**
  930. * @return the index file location
  931. * @throws NoWorkTreeException
  932. * if this is bare, which implies it has no working directory.
  933. * See {@link #isBare()}.
  934. */
  935. public File getIndexFile() throws NoWorkTreeException {
  936. if (isBare())
  937. throw new NoWorkTreeException();
  938. return indexFile;
  939. }
  940. /**
  941. * Create a new in-core index representation and read an index from disk.
  942. * <p>
  943. * The new index will be read before it is returned to the caller. Read
  944. * failures are reported as exceptions and therefore prevent the method from
  945. * returning a partially populated index.
  946. *
  947. * @return a cache representing the contents of the specified index file (if
  948. * it exists) or an empty cache if the file does not exist.
  949. * @throws NoWorkTreeException
  950. * if this is bare, which implies it has no working directory.
  951. * See {@link #isBare()}.
  952. * @throws IOException
  953. * the index file is present but could not be read.
  954. * @throws CorruptObjectException
  955. * the index file is using a format or extension that this
  956. * library does not support.
  957. */
  958. public DirCache readDirCache() throws NoWorkTreeException,
  959. CorruptObjectException, IOException {
  960. return DirCache.read(this);
  961. }
  962. /**
  963. * Create a new in-core index representation, lock it, and read from disk.
  964. * <p>
  965. * The new index will be locked and then read before it is returned to the
  966. * caller. Read failures are reported as exceptions and therefore prevent
  967. * the method from returning a partially populated index.
  968. *
  969. * @return a cache representing the contents of the specified index file (if
  970. * it exists) or an empty cache if the file does not exist.
  971. * @throws NoWorkTreeException
  972. * if this is bare, which implies it has no working directory.
  973. * See {@link #isBare()}.
  974. * @throws IOException
  975. * the index file is present but could not be read, or the lock
  976. * could not be obtained.
  977. * @throws CorruptObjectException
  978. * the index file is using a format or extension that this
  979. * library does not support.
  980. */
  981. public DirCache lockDirCache() throws NoWorkTreeException,
  982. CorruptObjectException, IOException {
  983. // we want DirCache to inform us so that we can inform registered
  984. // listeners about index changes
  985. IndexChangedListener l = new IndexChangedListener() {
  986. public void onIndexChanged(IndexChangedEvent event) {
  987. notifyIndexChanged();
  988. }
  989. };
  990. return DirCache.lock(this, l);
  991. }
  992. static byte[] gitInternalSlash(byte[] bytes) {
  993. if (File.separatorChar == '/')
  994. return bytes;
  995. for (int i=0; i<bytes.length; ++i)
  996. if (bytes[i] == File.separatorChar)
  997. bytes[i] = '/';
  998. return bytes;
  999. }
  1000. /**
  1001. * @return an important state
  1002. */
  1003. public RepositoryState getRepositoryState() {
  1004. if (isBare() || getDirectory() == null)
  1005. return RepositoryState.BARE;
  1006. // Pre Git-1.6 logic
  1007. if (new File(getWorkTree(), ".dotest").exists()) //$NON-NLS-1$
  1008. return RepositoryState.REBASING;
  1009. if (new File(getDirectory(), ".dotest-merge").exists()) //$NON-NLS-1$
  1010. return RepositoryState.REBASING_INTERACTIVE;
  1011. // From 1.6 onwards
  1012. if (new File(getDirectory(),"rebase-apply/rebasing").exists()) //$NON-NLS-1$
  1013. return RepositoryState.REBASING_REBASING;
  1014. if (new File(getDirectory(),"rebase-apply/applying").exists()) //$NON-NLS-1$
  1015. return RepositoryState.APPLY;
  1016. if (new File(getDirectory(),"rebase-apply").exists()) //$NON-NLS-1$
  1017. return RepositoryState.REBASING;
  1018. if (new File(getDirectory(),"rebase-merge/interactive").exists()) //$NON-NLS-1$
  1019. return RepositoryState.REBASING_INTERACTIVE;
  1020. if (new File(getDirectory(),"rebase-merge").exists()) //$NON-NLS-1$
  1021. return RepositoryState.REBASING_MERGE;
  1022. // Both versions
  1023. if (new File(getDirectory(), Constants.MERGE_HEAD).exists()) {
  1024. // we are merging - now check whether we have unmerged paths
  1025. try {
  1026. if (!readDirCache().hasUnmergedPaths()) {
  1027. // no unmerged paths -> return the MERGING_RESOLVED state
  1028. return RepositoryState.MERGING_RESOLVED;
  1029. }
  1030. } catch (IOException e) {
  1031. // Can't decide whether unmerged paths exists. Return
  1032. // MERGING state to be on the safe side (in state MERGING
  1033. // you are not allow to do anything)
  1034. }
  1035. return RepositoryState.MERGING;
  1036. }
  1037. if (new File(getDirectory(), "BISECT_LOG").exists()) //$NON-NLS-1$
  1038. return RepositoryState.BISECTING;
  1039. if (new File(getDirectory(), Constants.CHERRY_PICK_HEAD).exists()) {
  1040. try {
  1041. if (!readDirCache().hasUnmergedPaths()) {
  1042. // no unmerged paths
  1043. return RepositoryState.CHERRY_PICKING_RESOLVED;
  1044. }
  1045. } catch (IOException e) {
  1046. // fall through to CHERRY_PICKING
  1047. }
  1048. return RepositoryState.CHERRY_PICKING;
  1049. }
  1050. if (new File(getDirectory(), Constants.REVERT_HEAD).exists()) {
  1051. try {
  1052. if (!readDirCache().hasUnmergedPaths()) {
  1053. // no unmerged paths
  1054. return RepositoryState.REVERTING_RESOLVED;
  1055. }
  1056. } catch (IOException e) {
  1057. // fall through to REVERTING
  1058. }
  1059. return RepositoryState.REVERTING;
  1060. }
  1061. return RepositoryState.SAFE;
  1062. }
  1063. /**
  1064. * Check validity of a ref name. It must not contain character that has
  1065. * a special meaning in a Git object reference expression. Some other
  1066. * dangerous characters are also excluded.
  1067. *
  1068. * For portability reasons '\' is excluded
  1069. *
  1070. * @param refName
  1071. *
  1072. * @return true if refName is a valid ref name
  1073. */
  1074. public static boolean isValidRefName(final String refName) {
  1075. final int len = refName.length();
  1076. if (len == 0)
  1077. return false;
  1078. if (refName.endsWith(".lock")) //$NON-NLS-1$
  1079. return false;
  1080. // Borrow logic for filterig out invalid paths. These
  1081. // are also invalid ref
  1082. try {
  1083. DirCacheCheckout.checkValidPath(refName);
  1084. } catch (InvalidPathException e) {
  1085. return false;
  1086. }
  1087. int components = 1;
  1088. char p = '\0';
  1089. for (int i = 0; i < len; i++) {
  1090. final char c = refName.charAt(i);
  1091. if (c <= ' ')
  1092. return false;
  1093. switch (c) {
  1094. case '.':
  1095. switch (p) {
  1096. case '\0': case '/': case '.':
  1097. return false;
  1098. }
  1099. if (i == len -1)
  1100. return false;
  1101. break;
  1102. case '/':
  1103. if (i == 0 || i == len - 1)
  1104. return false;
  1105. if (p == '/')
  1106. return false;
  1107. components++;
  1108. break;
  1109. case '{':
  1110. if (p == '@')
  1111. return false;
  1112. break;
  1113. case '~': case '^': case ':':
  1114. case '?': case '[': case '*':
  1115. case '\\':
  1116. case '\u007F':
  1117. return false;
  1118. }
  1119. p = c;
  1120. }
  1121. return components > 1;
  1122. }
  1123. /**
  1124. * Strip work dir and return normalized repository path.
  1125. *
  1126. * @param workDir Work dir
  1127. * @param file File whose path shall be stripped of its workdir
  1128. * @return normalized repository relative path or the empty
  1129. * string if the file is not relative to the work directory.
  1130. */
  1131. public static String stripWorkDir(File workDir, File file) {
  1132. final String filePath = file.getPath();
  1133. final String workDirPath = workDir.getPath();
  1134. if (filePath.length() <= workDirPath.length() ||
  1135. filePath.charAt(workDirPath.length()) != File.separatorChar ||
  1136. !filePath.startsWith(workDirPath)) {
  1137. File absWd = workDir.isAbsolute() ? workDir : workDir.getAbsoluteFile();
  1138. File absFile = file.isAbsolute() ? file : file.getAbsoluteFile();
  1139. if (absWd == workDir && absFile == file)
  1140. return ""; //$NON-NLS-1$
  1141. return stripWorkDir(absWd, absFile);
  1142. }
  1143. String relName = filePath.substring(workDirPath.length() + 1);
  1144. if (File.separatorChar != '/')
  1145. relName = relName.replace(File.separatorChar, '/');
  1146. return relName;
  1147. }
  1148. /**
  1149. * @return true if this is bare, which implies it has no working directory.
  1150. */
  1151. public boolean isBare() {
  1152. return workTree == null;
  1153. }
  1154. /**
  1155. * @return the root directory of the working tree, where files are checked
  1156. * out for viewing and editing.
  1157. * @throws NoWorkTreeException
  1158. * if this is bare, which implies it has no working directory.
  1159. * See {@link #isBare()}.
  1160. */
  1161. public File getWorkTree() throws NoWorkTreeException {
  1162. if (isBare())
  1163. throw new NoWorkTreeException();
  1164. return workTree;
  1165. }
  1166. /**
  1167. * Force a scan for changed refs.
  1168. *
  1169. * @throws IOException
  1170. */
  1171. public abstract void scanForRepoChanges() throws IOException;
  1172. /**
  1173. * Notify that the index changed
  1174. */
  1175. public abstract void notifyIndexChanged();
  1176. /**
  1177. * @param refName
  1178. *
  1179. * @return a more user friendly ref name
  1180. */
  1181. public static String shortenRefName(String refName) {
  1182. if (refName.startsWith(Constants.R_HEADS))
  1183. return refName.substring(Constants.R_HEADS.length());
  1184. if (refName.startsWith(Constants.R_TAGS))
  1185. return refName.substring(Constants.R_TAGS.length());
  1186. if (refName.startsWith(Constants.R_REMOTES))
  1187. return refName.substring(Constants.R_REMOTES.length());
  1188. return refName;
  1189. }
  1190. /**
  1191. * @param refName
  1192. * @return a {@link ReflogReader} for the supplied refname, or null if the
  1193. * named ref does not exist.
  1194. * @throws IOException
  1195. * the ref could not be accessed.
  1196. * @since 3.0
  1197. */
  1198. public abstract ReflogReader getReflogReader(String refName)
  1199. throws IOException;
  1200. /**
  1201. * Return the information stored in the file $GIT_DIR/MERGE_MSG. In this
  1202. * file operations triggering a merge will store a template for the commit
  1203. * message of the merge commit.
  1204. *
  1205. * @return a String containing the content of the MERGE_MSG file or
  1206. * {@code null} if this file doesn't exist
  1207. * @throws IOException
  1208. * @throws NoWorkTreeException
  1209. * if this is bare, which implies it has no working directory.
  1210. * See {@link #isBare()}.
  1211. */
  1212. public String readMergeCommitMsg() throws IOException, NoWorkTreeException {
  1213. return readCommitMsgFile(Constants.MERGE_MSG);
  1214. }
  1215. /**
  1216. * Write new content to the file $GIT_DIR/MERGE_MSG. In this file operations
  1217. * triggering a merge will store a template for the commit message of the
  1218. * merge commit. If <code>null</code> is specified as message the file will
  1219. * be deleted.
  1220. *
  1221. * @param msg
  1222. * the message which should be written or <code>null</code> to
  1223. * delete the file
  1224. *
  1225. * @throws IOException
  1226. */
  1227. public void writeMergeCommitMsg(String msg) throws IOException {
  1228. File mergeMsgFile = new File(gitDir, Constants.MERGE_MSG);
  1229. writeCommitMsg(mergeMsgFile, msg);
  1230. }
  1231. /**
  1232. * Return the information stored in the file $GIT_DIR/MERGE_HEAD. In this
  1233. * file operations triggering a merge will store the IDs of all heads which
  1234. * should be merged together with HEAD.
  1235. *
  1236. * @return a list of commits which IDs are listed in the MERGE_HEAD file or
  1237. * {@code null} if this file doesn't exist. Also if the file exists
  1238. * but is empty {@code null} will be returned
  1239. * @throws IOException
  1240. * @throws NoWorkTreeException
  1241. * if this is bare, which implies it has no working directory.
  1242. * See {@link #isBare()}.
  1243. */
  1244. public List<ObjectId> readMergeHeads() throws IOException, NoWorkTreeException {
  1245. if (isBare() || getDirectory() == null)
  1246. throw new NoWorkTreeException();
  1247. byte[] raw = readGitDirectoryFile(Constants.MERGE_HEAD);
  1248. if (raw == null)
  1249. return null;
  1250. LinkedList<ObjectId> heads = new LinkedList<ObjectId>();
  1251. for (int p = 0; p < raw.length;) {
  1252. heads.add(ObjectId.fromString(raw, p));
  1253. p = RawParseUtils
  1254. .nextLF(raw, p + Constants.OBJECT_ID_STRING_LENGTH);
  1255. }
  1256. return heads;
  1257. }
  1258. /**
  1259. * Write new merge-heads into $GIT_DIR/MERGE_HEAD. In this file operations
  1260. * triggering a merge will store the IDs of all heads which should be merged
  1261. * together with HEAD. If <code>null</code> is specified as list of commits
  1262. * the file will be deleted
  1263. *
  1264. * @param heads
  1265. * a list of commits which IDs should be written to
  1266. * $GIT_DIR/MERGE_HEAD or <code>null</code> to delete the file
  1267. * @throws IOException
  1268. */
  1269. public void writeMergeHeads(List<ObjectId> heads) throws IOException {
  1270. writeHeadsFile(heads, Constants.MERGE_HEAD);
  1271. }
  1272. /**
  1273. * Return the information stored in the file $GIT_DIR/CHERRY_PICK_HEAD.
  1274. *
  1275. * @return object id from CHERRY_PICK_HEAD file or {@code null} if this file
  1276. * doesn't exist. Also if the file exists but is empty {@code null}
  1277. * will be returned
  1278. * @throws IOException
  1279. * @throws NoWorkTreeException
  1280. * if this is bare, which implies it has no working directory.
  1281. * See {@link #isBare()}.
  1282. */
  1283. public ObjectId readCherryPickHead() throws IOException,
  1284. NoWorkTreeException {
  1285. if (isBare() || getDirectory() == null)
  1286. throw new NoWorkTreeException();
  1287. byte[] raw = readGitDirectoryFile(Constants.CHERRY_PICK_HEAD);
  1288. if (raw == null)
  1289. return null;
  1290. return ObjectId.fromString(raw, 0);
  1291. }
  1292. /**
  1293. * Return the information stored in the file $GIT_DIR/REVERT_HEAD.
  1294. *
  1295. * @return object id from REVERT_HEAD file or {@code null} if this file
  1296. * doesn't exist. Also if the file exists but is empty {@code null}
  1297. * will be returned
  1298. * @throws IOException
  1299. * @throws NoWorkTreeException
  1300. * if this is bare, which implies it has no working directory.
  1301. * See {@link #isBare()}.
  1302. */
  1303. public ObjectId readRevertHead() throws IOException, NoWorkTreeException {
  1304. if (isBare() || getDirectory() == null)
  1305. throw new NoWorkTreeException();
  1306. byte[] raw = readGitDirectoryFile(Constants.REVERT_HEAD);
  1307. if (raw == null)
  1308. return null;
  1309. return ObjectId.fromString(raw, 0);
  1310. }
  1311. /**
  1312. * Write cherry pick commit into $GIT_DIR/CHERRY_PICK_HEAD. This is used in
  1313. * case of conflicts to store the cherry which was tried to be picked.
  1314. *
  1315. * @param head
  1316. * an object id of the cherry commit or <code>null</code> to
  1317. * delete the file
  1318. * @throws IOException
  1319. */
  1320. public void writeCherryPickHead(ObjectId head) throws IOException {
  1321. List<ObjectId> heads = (head != null) ? Collections.singletonList(head)
  1322. : null;
  1323. writeHeadsFile(heads, Constants.CHERRY_PICK_HEAD);
  1324. }
  1325. /**
  1326. * Write revert commit into $GIT_DIR/REVERT_HEAD. This is used in case of
  1327. * conflicts to store the revert which was tried to be picked.
  1328. *
  1329. * @param head
  1330. * an object id of the revert commit or <code>null</code> to
  1331. * delete the file
  1332. * @throws IOException
  1333. */
  1334. public void writeRevertHead(ObjectId head) throws IOException {
  1335. List<ObjectId> heads = (head != null) ? Collections.singletonList(head)
  1336. : null;
  1337. writeHeadsFile(heads, Constants.REVERT_HEAD);
  1338. }
  1339. /**
  1340. * Write original HEAD commit into $GIT_DIR/ORIG_HEAD.
  1341. *
  1342. * @param head
  1343. * an object id of the original HEAD commit or <code>null</code>
  1344. * to delete the file
  1345. * @throws IOException
  1346. */
  1347. public void writeOrigHead(ObjectId head) throws IOException {
  1348. List<ObjectId> heads = head != null ? Collections.singletonList(head)
  1349. : null;
  1350. writeHeadsFile(heads, Constants.ORIG_HEAD);
  1351. }
  1352. /**
  1353. * Return the information stored in the file $GIT_DIR/ORIG_HEAD.
  1354. *
  1355. * @return object id from ORIG_HEAD file or {@code null} if this file
  1356. * doesn't exist. Also if the file exists but is empty {@code null}
  1357. * will be returned
  1358. * @throws IOException
  1359. * @throws NoWorkTreeException
  1360. * if this is bare, which implies it has no working directory.
  1361. * See {@link #isBare()}.
  1362. */
  1363. public ObjectId readOrigHead() throws IOException, NoWorkTreeException {
  1364. if (isBare() || getDirectory() == null)
  1365. throw new NoWorkTreeException();
  1366. byte[] raw = readGitDirectoryFile(Constants.ORIG_HEAD);
  1367. return raw != null ? ObjectId.fromString(raw, 0) : null;
  1368. }
  1369. /**
  1370. * Return the information stored in the file $GIT_DIR/SQUASH_MSG. In this
  1371. * file operations triggering a squashed merge will store a template for the
  1372. * commit message of the squash commit.
  1373. *
  1374. * @return a String containing the content of the SQUASH_MSG file or
  1375. * {@code null} if this file doesn't exist
  1376. * @throws IOException
  1377. * @throws NoWorkTreeException
  1378. * if this is bare, which implies it has no working directory.
  1379. * See {@link #isBare()}.
  1380. */
  1381. public String readSquashCommitMsg() throws IOException {
  1382. return readCommitMsgFile(Constants.SQUASH_MSG);
  1383. }
  1384. /**
  1385. * Write new content to the file $GIT_DIR/SQUASH_MSG. In this file
  1386. * operations triggering a squashed merge will store a template for the
  1387. * commit message of the squash commit. If <code>null</code> is specified as
  1388. * message the file will be deleted.
  1389. *
  1390. * @param msg
  1391. * the message which should be written or <code>null</code> to
  1392. * delete the file
  1393. *
  1394. * @throws IOException
  1395. */
  1396. public void writeSquashCommitMsg(String msg) throws IOException {
  1397. File squashMsgFile = new File(gitDir, Constants.SQUASH_MSG);
  1398. writeCommitMsg(squashMsgFile, msg);
  1399. }
  1400. private String readCommitMsgFile(String msgFilename) throws IOException {
  1401. if (isBare() || getDirectory() == null)
  1402. throw new NoWorkTreeException();
  1403. File mergeMsgFile = new File(getDirectory(), msgFilename);
  1404. try {
  1405. return RawParseUtils.decode(IO.readFully(mergeMsgFile));
  1406. } catch (FileNotFoundException e) {
  1407. // the file has disappeared in the meantime ignore it
  1408. return null;
  1409. }
  1410. }
  1411. private void writeCommitMsg(File msgFile, String msg) throws IOException {
  1412. if (msg != null) {
  1413. FileOutputStream fos = new FileOutputStream(msgFile);
  1414. try {
  1415. fos.write(msg.getBytes(Constants.CHARACTER_ENCODING));
  1416. } finally {
  1417. fos.close();
  1418. }
  1419. } else {
  1420. FileUtils.delete(msgFile, FileUtils.SKIP_MISSING);
  1421. }
  1422. }
  1423. /**
  1424. * Read a file from the git directory.
  1425. *
  1426. * @param filename
  1427. * @return the raw contents or null if the file doesn't exist or is empty
  1428. * @throws IOException
  1429. */
  1430. private byte[] readGitDirectoryFile(String filename) throws IOException {
  1431. File file = new File(getDirectory(), filename);
  1432. try {
  1433. byte[] raw = IO.readFully(file);
  1434. return raw.length > 0 ? raw : null;
  1435. } catch (FileNotFoundException notFound) {
  1436. return null;
  1437. }
  1438. }
  1439. /**
  1440. * Write the given heads to a file in the git directory.
  1441. *
  1442. * @param heads
  1443. * a list of object ids to write or null if the file should be
  1444. * deleted.
  1445. * @param filename
  1446. * @throws FileNotFoundException
  1447. * @throws IOException
  1448. */
  1449. private void writeHeadsFile(List<ObjectId> heads, String filename)
  1450. throws FileNotFoundException, IOException {
  1451. File headsFile = new File(getDirectory(), filename);
  1452. if (heads != null) {
  1453. BufferedOutputStream bos = new SafeBufferedOutputStream(
  1454. new FileOutputStream(headsFile));
  1455. try {
  1456. for (ObjectId id : heads) {
  1457. id.copyTo(bos);
  1458. bos.write('\n');
  1459. }
  1460. } finally {
  1461. bos.close();
  1462. }
  1463. } else {
  1464. FileUtils.delete(headsFile, FileUtils.SKIP_MISSING);
  1465. }
  1466. }
  1467. /**
  1468. * Read a file formatted like the git-rebase-todo file. The "done" file is
  1469. * also formatted like the git-rebase-todo file. These files can be found in
  1470. * .git/rebase-merge/ or .git/rebase-append/ folders.
  1471. *
  1472. * @param path
  1473. * path to the file relative to the repository's git-dir. E.g.
  1474. * "rebase-merge/git-rebase-todo" or "rebase-append/done"
  1475. * @param includeComments
  1476. * <code>true</code> if also comments should be reported
  1477. * @return the list of steps
  1478. * @throws IOException
  1479. * @since 3.2
  1480. */
  1481. public List<RebaseTodoLine> readRebaseTodo(String path,
  1482. boolean includeComments)
  1483. throws IOException {
  1484. return new RebaseTodoFile(this).readRebaseTodo(path, includeComments);
  1485. }
  1486. /**
  1487. * Write a file formatted like a git-rebase-todo file.
  1488. *
  1489. * @param path
  1490. * path to the file relative to the repository's git-dir. E.g.
  1491. * "rebase-merge/git-rebase-todo" or "rebase-append/done"
  1492. * @param steps
  1493. * the steps to be written
  1494. * @param append
  1495. * whether to append to an existing file or to write a new file
  1496. * @throws IOException
  1497. * @since 3.2
  1498. */
  1499. public void writeRebaseTodoFile(String path, List<RebaseTodoLine> steps,
  1500. boolean append)
  1501. throws IOException {
  1502. new RebaseTodoFile(this).writeRebaseTodoFile(path, steps, append);
  1503. }
  1504. }