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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616
  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. final Ref ref = getRef((String)resolved);
  358. return ref != null ? ref.getLeaf().getObjectId() : null;
  359. } else {
  360. return (ObjectId) resolved;
  361. }
  362. } finally {
  363. rw.release();
  364. }
  365. }
  366. /**
  367. * Simplify an expression, but unlike {@link #resolve(String)} it will not
  368. * resolve a branch passed or resulting from the expression, such as @{-}.
  369. * Thus this method can be used to process an expression to a method that
  370. * expects a branch or revision id.
  371. *
  372. * @param revstr
  373. * @return object id or ref name from resolved expression
  374. * @throws AmbiguousObjectException
  375. * @throws IOException
  376. */
  377. public String simplify(final String revstr)
  378. throws AmbiguousObjectException, IOException {
  379. RevWalk rw = new RevWalk(this);
  380. try {
  381. Object resolved = resolve(rw, revstr);
  382. if (resolved != null)
  383. if (resolved instanceof String)
  384. return (String) resolved;
  385. else
  386. return ((AnyObjectId) resolved).getName();
  387. return null;
  388. } finally {
  389. rw.release();
  390. }
  391. }
  392. private Object resolve(final RevWalk rw, final String revstr)
  393. throws IOException {
  394. char[] revChars = revstr.toCharArray();
  395. RevObject rev = null;
  396. String name = null;
  397. int done = 0;
  398. for (int i = 0; i < revChars.length; ++i) {
  399. switch (revChars[i]) {
  400. case '^':
  401. if (rev == null) {
  402. if (name == null)
  403. if (done == 0)
  404. name = new String(revChars, done, i);
  405. else {
  406. done = i + 1;
  407. break;
  408. }
  409. rev = parseSimple(rw, name);
  410. name = null;
  411. if (rev == null)
  412. return null;
  413. }
  414. if (i + 1 < revChars.length) {
  415. switch (revChars[i + 1]) {
  416. case '0':
  417. case '1':
  418. case '2':
  419. case '3':
  420. case '4':
  421. case '5':
  422. case '6':
  423. case '7':
  424. case '8':
  425. case '9':
  426. int j;
  427. rev = rw.parseCommit(rev);
  428. for (j = i + 1; j < revChars.length; ++j) {
  429. if (!Character.isDigit(revChars[j]))
  430. break;
  431. }
  432. String parentnum = new String(revChars, i + 1, j - i
  433. - 1);
  434. int pnum;
  435. try {
  436. pnum = Integer.parseInt(parentnum);
  437. } catch (NumberFormatException e) {
  438. throw new RevisionSyntaxException(
  439. JGitText.get().invalidCommitParentNumber,
  440. revstr);
  441. }
  442. if (pnum != 0) {
  443. RevCommit commit = (RevCommit) rev;
  444. if (pnum > commit.getParentCount())
  445. rev = null;
  446. else
  447. rev = commit.getParent(pnum - 1);
  448. }
  449. i = j - 1;
  450. done = j;
  451. break;
  452. case '{':
  453. int k;
  454. String item = null;
  455. for (k = i + 2; k < revChars.length; ++k) {
  456. if (revChars[k] == '}') {
  457. item = new String(revChars, i + 2, k - i - 2);
  458. break;
  459. }
  460. }
  461. i = k;
  462. if (item != null)
  463. if (item.equals("tree")) { //$NON-NLS-1$
  464. rev = rw.parseTree(rev);
  465. } else if (item.equals("commit")) { //$NON-NLS-1$
  466. rev = rw.parseCommit(rev);
  467. } else if (item.equals("blob")) { //$NON-NLS-1$
  468. rev = rw.peel(rev);
  469. if (!(rev instanceof RevBlob))
  470. throw new IncorrectObjectTypeException(rev,
  471. Constants.TYPE_BLOB);
  472. } else if (item.equals("")) { //$NON-NLS-1$
  473. rev = rw.peel(rev);
  474. } else
  475. throw new RevisionSyntaxException(revstr);
  476. else
  477. throw new RevisionSyntaxException(revstr);
  478. done = k;
  479. break;
  480. default:
  481. rev = rw.peel(rev);
  482. if (rev instanceof RevCommit) {
  483. RevCommit commit = ((RevCommit) rev);
  484. if (commit.getParentCount() == 0)
  485. rev = null;
  486. else
  487. rev = commit.getParent(0);
  488. } else
  489. throw new IncorrectObjectTypeException(rev,
  490. Constants.TYPE_COMMIT);
  491. }
  492. } else {
  493. rev = rw.peel(rev);
  494. if (rev instanceof RevCommit) {
  495. RevCommit commit = ((RevCommit) rev);
  496. if (commit.getParentCount() == 0)
  497. rev = null;
  498. else
  499. rev = commit.getParent(0);
  500. } else
  501. throw new IncorrectObjectTypeException(rev,
  502. Constants.TYPE_COMMIT);
  503. }
  504. done = i + 1;
  505. break;
  506. case '~':
  507. if (rev == null) {
  508. if (name == null)
  509. if (done == 0)
  510. name = new String(revChars, done, i);
  511. else {
  512. done = i + 1;
  513. break;
  514. }
  515. rev = parseSimple(rw, name);
  516. name = null;
  517. if (rev == null)
  518. return null;
  519. }
  520. rev = rw.peel(rev);
  521. if (!(rev instanceof RevCommit))
  522. throw new IncorrectObjectTypeException(rev,
  523. Constants.TYPE_COMMIT);
  524. int l;
  525. for (l = i + 1; l < revChars.length; ++l) {
  526. if (!Character.isDigit(revChars[l]))
  527. break;
  528. }
  529. int dist;
  530. if (l - i > 1) {
  531. String distnum = new String(revChars, i + 1, l - i - 1);
  532. try {
  533. dist = Integer.parseInt(distnum);
  534. } catch (NumberFormatException e) {
  535. throw new RevisionSyntaxException(
  536. JGitText.get().invalidAncestryLength, revstr);
  537. }
  538. } else
  539. dist = 1;
  540. while (dist > 0) {
  541. RevCommit commit = (RevCommit) rev;
  542. if (commit.getParentCount() == 0) {
  543. rev = null;
  544. break;
  545. }
  546. commit = commit.getParent(0);
  547. rw.parseHeaders(commit);
  548. rev = commit;
  549. --dist;
  550. }
  551. i = l - 1;
  552. done = l;
  553. break;
  554. case '@':
  555. if (rev != null)
  556. throw new RevisionSyntaxException(revstr);
  557. if (i + 1 < revChars.length && revChars[i + 1] != '{')
  558. continue;
  559. int m;
  560. String time = null;
  561. for (m = i + 2; m < revChars.length; ++m) {
  562. if (revChars[m] == '}') {
  563. time = new String(revChars, i + 2, m - i - 2);
  564. break;
  565. }
  566. }
  567. if (time != null) {
  568. if (time.equals("upstream")) { //$NON-NLS-1$
  569. if (name == null)
  570. name = new String(revChars, done, i);
  571. if (name.equals("")) //$NON-NLS-1$
  572. // Currently checked out branch, HEAD if
  573. // detached
  574. name = Constants.HEAD;
  575. if (!Repository.isValidRefName("x/" + name)) //$NON-NLS-1$
  576. throw new RevisionSyntaxException(revstr);
  577. Ref ref = getRef(name);
  578. name = null;
  579. if (ref == null)
  580. return null;
  581. if (ref.isSymbolic())
  582. ref = ref.getLeaf();
  583. name = ref.getName();
  584. RemoteConfig remoteConfig;
  585. try {
  586. remoteConfig = new RemoteConfig(getConfig(),
  587. "origin"); //$NON-NLS-1$
  588. } catch (URISyntaxException e) {
  589. throw new RevisionSyntaxException(revstr);
  590. }
  591. String remoteBranchName = getConfig()
  592. .getString(
  593. ConfigConstants.CONFIG_BRANCH_SECTION,
  594. Repository.shortenRefName(ref.getName()),
  595. ConfigConstants.CONFIG_KEY_MERGE);
  596. List<RefSpec> fetchRefSpecs = remoteConfig
  597. .getFetchRefSpecs();
  598. for (RefSpec refSpec : fetchRefSpecs) {
  599. if (refSpec.matchSource(remoteBranchName)) {
  600. RefSpec expandFromSource = refSpec
  601. .expandFromSource(remoteBranchName);
  602. name = expandFromSource.getDestination();
  603. break;
  604. }
  605. }
  606. if (name == null)
  607. throw new RevisionSyntaxException(revstr);
  608. } else if (time.matches("^-\\d+$")) { //$NON-NLS-1$
  609. if (name != null)
  610. throw new RevisionSyntaxException(revstr);
  611. else {
  612. String previousCheckout = resolveReflogCheckout(-Integer
  613. .parseInt(time));
  614. if (ObjectId.isId(previousCheckout))
  615. rev = parseSimple(rw, previousCheckout);
  616. else
  617. name = previousCheckout;
  618. }
  619. } else {
  620. if (name == null)
  621. name = new String(revChars, done, i);
  622. if (name.equals("")) //$NON-NLS-1$
  623. name = Constants.HEAD;
  624. if (!Repository.isValidRefName("x/" + name)) //$NON-NLS-1$
  625. throw new RevisionSyntaxException(revstr);
  626. Ref ref = getRef(name);
  627. name = null;
  628. if (ref == null)
  629. return null;
  630. // @{n} means current branch, not HEAD@{1} unless
  631. // detached
  632. if (ref.isSymbolic())
  633. ref = ref.getLeaf();
  634. rev = resolveReflog(rw, ref, time);
  635. }
  636. i = m;
  637. } else
  638. throw new RevisionSyntaxException(revstr);
  639. break;
  640. case ':': {
  641. RevTree tree;
  642. if (rev == null) {
  643. if (name == null)
  644. name = new String(revChars, done, i);
  645. if (name.equals("")) //$NON-NLS-1$
  646. name = Constants.HEAD;
  647. rev = parseSimple(rw, name);
  648. name = null;
  649. }
  650. if (rev == null)
  651. return null;
  652. tree = rw.parseTree(rev);
  653. if (i == revChars.length - 1)
  654. return tree.copy();
  655. TreeWalk tw = TreeWalk.forPath(rw.getObjectReader(),
  656. new String(revChars, i + 1, revChars.length - i - 1),
  657. tree);
  658. return tw != null ? tw.getObjectId(0) : null;
  659. }
  660. default:
  661. if (rev != null)
  662. throw new RevisionSyntaxException(revstr);
  663. }
  664. }
  665. if (rev != null)
  666. return rev.copy();
  667. if (name != null)
  668. return name;
  669. if (done == revstr.length())
  670. return null;
  671. name = revstr.substring(done);
  672. if (!Repository.isValidRefName("x/" + name)) //$NON-NLS-1$
  673. throw new RevisionSyntaxException(revstr);
  674. if (getRef(name) != null)
  675. return name;
  676. return resolveSimple(name);
  677. }
  678. private static boolean isHex(char c) {
  679. return ('0' <= c && c <= '9') //
  680. || ('a' <= c && c <= 'f') //
  681. || ('A' <= c && c <= 'F');
  682. }
  683. private static boolean isAllHex(String str, int ptr) {
  684. while (ptr < str.length()) {
  685. if (!isHex(str.charAt(ptr++)))
  686. return false;
  687. }
  688. return true;
  689. }
  690. private RevObject parseSimple(RevWalk rw, String revstr) throws IOException {
  691. ObjectId id = resolveSimple(revstr);
  692. return id != null ? rw.parseAny(id) : null;
  693. }
  694. private ObjectId resolveSimple(final String revstr) throws IOException {
  695. if (ObjectId.isId(revstr))
  696. return ObjectId.fromString(revstr);
  697. if (Repository.isValidRefName("x/" + revstr)) { //$NON-NLS-1$
  698. Ref r = getRefDatabase().getRef(revstr);
  699. if (r != null)
  700. return r.getObjectId();
  701. }
  702. if (AbbreviatedObjectId.isId(revstr))
  703. return resolveAbbreviation(revstr);
  704. int dashg = revstr.indexOf("-g"); //$NON-NLS-1$
  705. if ((dashg + 5) < revstr.length() && 0 <= dashg
  706. && isHex(revstr.charAt(dashg + 2))
  707. && isHex(revstr.charAt(dashg + 3))
  708. && isAllHex(revstr, dashg + 4)) {
  709. // Possibly output from git describe?
  710. String s = revstr.substring(dashg + 2);
  711. if (AbbreviatedObjectId.isId(s))
  712. return resolveAbbreviation(s);
  713. }
  714. return null;
  715. }
  716. private String resolveReflogCheckout(int checkoutNo)
  717. throws IOException {
  718. List<ReflogEntry> reflogEntries = getReflogReader(Constants.HEAD)
  719. .getReverseEntries();
  720. for (ReflogEntry entry : reflogEntries) {
  721. CheckoutEntry checkout = entry.parseCheckout();
  722. if (checkout != null)
  723. if (checkoutNo-- == 1)
  724. return checkout.getFromBranch();
  725. }
  726. return null;
  727. }
  728. private RevCommit resolveReflog(RevWalk rw, Ref ref, String time)
  729. throws IOException {
  730. int number;
  731. try {
  732. number = Integer.parseInt(time);
  733. } catch (NumberFormatException nfe) {
  734. throw new RevisionSyntaxException(MessageFormat.format(
  735. JGitText.get().invalidReflogRevision, time));
  736. }
  737. assert number >= 0;
  738. ReflogReader reader = getReflogReader(ref.getName());
  739. ReflogEntry entry = reader.getReverseEntry(number);
  740. if (entry == null)
  741. throw new RevisionSyntaxException(MessageFormat.format(
  742. JGitText.get().reflogEntryNotFound,
  743. Integer.valueOf(number), ref.getName()));
  744. return rw.parseCommit(entry.getNewId());
  745. }
  746. private ObjectId resolveAbbreviation(final String revstr) throws IOException,
  747. AmbiguousObjectException {
  748. AbbreviatedObjectId id = AbbreviatedObjectId.fromString(revstr);
  749. ObjectReader reader = newObjectReader();
  750. try {
  751. Collection<ObjectId> matches = reader.resolve(id);
  752. if (matches.size() == 0)
  753. return null;
  754. else if (matches.size() == 1)
  755. return matches.iterator().next();
  756. else
  757. throw new AmbiguousObjectException(id, matches);
  758. } finally {
  759. reader.release();
  760. }
  761. }
  762. /** Increment the use counter by one, requiring a matched {@link #close()}. */
  763. public void incrementOpen() {
  764. useCnt.incrementAndGet();
  765. }
  766. /** Decrement the use count, and maybe close resources. */
  767. public void close() {
  768. if (useCnt.decrementAndGet() == 0) {
  769. doClose();
  770. }
  771. }
  772. /**
  773. * Invoked when the use count drops to zero during {@link #close()}.
  774. * <p>
  775. * The default implementation closes the object and ref databases.
  776. */
  777. protected void doClose() {
  778. getObjectDatabase().close();
  779. getRefDatabase().close();
  780. }
  781. @SuppressWarnings("nls")
  782. public String toString() {
  783. String desc;
  784. if (getDirectory() != null)
  785. desc = getDirectory().getPath();
  786. else
  787. desc = getClass().getSimpleName() + "-" //$NON-NLS-1$
  788. + System.identityHashCode(this);
  789. return "Repository[" + desc + "]"; //$NON-NLS-1$
  790. }
  791. /**
  792. * Get the name of the reference that {@code HEAD} points to.
  793. * <p>
  794. * This is essentially the same as doing:
  795. *
  796. * <pre>
  797. * return getRef(Constants.HEAD).getTarget().getName()
  798. * </pre>
  799. *
  800. * Except when HEAD is detached, in which case this method returns the
  801. * current ObjectId in hexadecimal string format.
  802. *
  803. * @return name of current branch (for example {@code refs/heads/master}) or
  804. * an ObjectId in hex format if the current branch is detached.
  805. * @throws IOException
  806. */
  807. public String getFullBranch() throws IOException {
  808. Ref head = getRef(Constants.HEAD);
  809. if (head == null)
  810. return null;
  811. if (head.isSymbolic())
  812. return head.getTarget().getName();
  813. if (head.getObjectId() != null)
  814. return head.getObjectId().name();
  815. return null;
  816. }
  817. /**
  818. * Get the short name of the current branch that {@code HEAD} points to.
  819. * <p>
  820. * This is essentially the same as {@link #getFullBranch()}, except the
  821. * leading prefix {@code refs/heads/} is removed from the reference before
  822. * it is returned to the caller.
  823. *
  824. * @return name of current branch (for example {@code master}), or an
  825. * ObjectId in hex format if the current branch is detached.
  826. * @throws IOException
  827. */
  828. public String getBranch() throws IOException {
  829. String name = getFullBranch();
  830. if (name != null)
  831. return shortenRefName(name);
  832. return name;
  833. }
  834. /**
  835. * Objects known to exist but not expressed by {@link #getAllRefs()}.
  836. * <p>
  837. * When a repository borrows objects from another repository, it can
  838. * advertise that it safely has that other repository's references, without
  839. * exposing any other details about the other repository. This may help
  840. * a client trying to push changes avoid pushing more than it needs to.
  841. *
  842. * @return unmodifiable collection of other known objects.
  843. */
  844. public Set<ObjectId> getAdditionalHaves() {
  845. return Collections.emptySet();
  846. }
  847. /**
  848. * Get a ref by name.
  849. *
  850. * @param name
  851. * the name of the ref to lookup. May be a short-hand form, e.g.
  852. * "master" which is is automatically expanded to
  853. * "refs/heads/master" if "refs/heads/master" already exists.
  854. * @return the Ref with the given name, or null if it does not exist
  855. * @throws IOException
  856. */
  857. public Ref getRef(final String name) throws IOException {
  858. return getRefDatabase().getRef(name);
  859. }
  860. /**
  861. * @return mutable map of all known refs (heads, tags, remotes).
  862. */
  863. public Map<String, Ref> getAllRefs() {
  864. try {
  865. return getRefDatabase().getRefs(RefDatabase.ALL);
  866. } catch (IOException e) {
  867. return new HashMap<String, Ref>();
  868. }
  869. }
  870. /**
  871. * @return mutable map of all tags; key is short tag name ("v1.0") and value
  872. * of the entry contains the ref with the full tag name
  873. * ("refs/tags/v1.0").
  874. */
  875. public Map<String, Ref> getTags() {
  876. try {
  877. return getRefDatabase().getRefs(Constants.R_TAGS);
  878. } catch (IOException e) {
  879. return new HashMap<String, Ref>();
  880. }
  881. }
  882. /**
  883. * Peel a possibly unpeeled reference to an annotated tag.
  884. * <p>
  885. * If the ref cannot be peeled (as it does not refer to an annotated tag)
  886. * the peeled id stays null, but {@link Ref#isPeeled()} will be true.
  887. *
  888. * @param ref
  889. * The ref to peel
  890. * @return <code>ref</code> if <code>ref.isPeeled()</code> is true; else a
  891. * new Ref object representing the same data as Ref, but isPeeled()
  892. * will be true and getPeeledObjectId will contain the peeled object
  893. * (or null).
  894. */
  895. public Ref peel(final Ref ref) {
  896. try {
  897. return getRefDatabase().peel(ref);
  898. } catch (IOException e) {
  899. // Historical accident; if the reference cannot be peeled due
  900. // to some sort of repository access problem we claim that the
  901. // same as if the reference was not an annotated tag.
  902. return ref;
  903. }
  904. }
  905. /**
  906. * @return a map with all objects referenced by a peeled ref.
  907. */
  908. public Map<AnyObjectId, Set<Ref>> getAllRefsByPeeledObjectId() {
  909. Map<String, Ref> allRefs = getAllRefs();
  910. Map<AnyObjectId, Set<Ref>> ret = new HashMap<AnyObjectId, Set<Ref>>(allRefs.size());
  911. for (Ref ref : allRefs.values()) {
  912. ref = peel(ref);
  913. AnyObjectId target = ref.getPeeledObjectId();
  914. if (target == null)
  915. target = ref.getObjectId();
  916. // We assume most Sets here are singletons
  917. Set<Ref> oset = ret.put(target, Collections.singleton(ref));
  918. if (oset != null) {
  919. // that was not the case (rare)
  920. if (oset.size() == 1) {
  921. // Was a read-only singleton, we must copy to a new Set
  922. oset = new HashSet<Ref>(oset);
  923. }
  924. ret.put(target, oset);
  925. oset.add(ref);
  926. }
  927. }
  928. return ret;
  929. }
  930. /**
  931. * @return the index file location
  932. * @throws NoWorkTreeException
  933. * if this is bare, which implies it has no working directory.
  934. * See {@link #isBare()}.
  935. */
  936. public File getIndexFile() throws NoWorkTreeException {
  937. if (isBare())
  938. throw new NoWorkTreeException();
  939. return indexFile;
  940. }
  941. /**
  942. * Create a new in-core index representation and read an index from disk.
  943. * <p>
  944. * The new index will be read before it is returned to the caller. Read
  945. * failures are reported as exceptions and therefore prevent the method from
  946. * returning a partially populated index.
  947. *
  948. * @return a cache representing the contents of the specified index file (if
  949. * it exists) or an empty cache if the file does not exist.
  950. * @throws NoWorkTreeException
  951. * if this is bare, which implies it has no working directory.
  952. * See {@link #isBare()}.
  953. * @throws IOException
  954. * the index file is present but could not be read.
  955. * @throws CorruptObjectException
  956. * the index file is using a format or extension that this
  957. * library does not support.
  958. */
  959. public DirCache readDirCache() throws NoWorkTreeException,
  960. CorruptObjectException, IOException {
  961. return DirCache.read(this);
  962. }
  963. /**
  964. * Create a new in-core index representation, lock it, and read from disk.
  965. * <p>
  966. * The new index will be locked and then read before it is returned to the
  967. * caller. Read failures are reported as exceptions and therefore prevent
  968. * the method from returning a partially populated index.
  969. *
  970. * @return a cache representing the contents of the specified index file (if
  971. * it exists) or an empty cache if the file does not exist.
  972. * @throws NoWorkTreeException
  973. * if this is bare, which implies it has no working directory.
  974. * See {@link #isBare()}.
  975. * @throws IOException
  976. * the index file is present but could not be read, or the lock
  977. * could not be obtained.
  978. * @throws CorruptObjectException
  979. * the index file is using a format or extension that this
  980. * library does not support.
  981. */
  982. public DirCache lockDirCache() throws NoWorkTreeException,
  983. CorruptObjectException, IOException {
  984. // we want DirCache to inform us so that we can inform registered
  985. // listeners about index changes
  986. IndexChangedListener l = new IndexChangedListener() {
  987. public void onIndexChanged(IndexChangedEvent event) {
  988. notifyIndexChanged();
  989. }
  990. };
  991. return DirCache.lock(this, l);
  992. }
  993. static byte[] gitInternalSlash(byte[] bytes) {
  994. if (File.separatorChar == '/')
  995. return bytes;
  996. for (int i=0; i<bytes.length; ++i)
  997. if (bytes[i] == File.separatorChar)
  998. bytes[i] = '/';
  999. return bytes;
  1000. }
  1001. /**
  1002. * @return an important state
  1003. */
  1004. public RepositoryState getRepositoryState() {
  1005. if (isBare() || getDirectory() == null)
  1006. return RepositoryState.BARE;
  1007. // Pre Git-1.6 logic
  1008. if (new File(getWorkTree(), ".dotest").exists()) //$NON-NLS-1$
  1009. return RepositoryState.REBASING;
  1010. if (new File(getDirectory(), ".dotest-merge").exists()) //$NON-NLS-1$
  1011. return RepositoryState.REBASING_INTERACTIVE;
  1012. // From 1.6 onwards
  1013. if (new File(getDirectory(),"rebase-apply/rebasing").exists()) //$NON-NLS-1$
  1014. return RepositoryState.REBASING_REBASING;
  1015. if (new File(getDirectory(),"rebase-apply/applying").exists()) //$NON-NLS-1$
  1016. return RepositoryState.APPLY;
  1017. if (new File(getDirectory(),"rebase-apply").exists()) //$NON-NLS-1$
  1018. return RepositoryState.REBASING;
  1019. if (new File(getDirectory(),"rebase-merge/interactive").exists()) //$NON-NLS-1$
  1020. return RepositoryState.REBASING_INTERACTIVE;
  1021. if (new File(getDirectory(),"rebase-merge").exists()) //$NON-NLS-1$
  1022. return RepositoryState.REBASING_MERGE;
  1023. // Both versions
  1024. if (new File(getDirectory(), Constants.MERGE_HEAD).exists()) {
  1025. // we are merging - now check whether we have unmerged paths
  1026. try {
  1027. if (!readDirCache().hasUnmergedPaths()) {
  1028. // no unmerged paths -> return the MERGING_RESOLVED state
  1029. return RepositoryState.MERGING_RESOLVED;
  1030. }
  1031. } catch (IOException e) {
  1032. // Can't decide whether unmerged paths exists. Return
  1033. // MERGING state to be on the safe side (in state MERGING
  1034. // you are not allow to do anything)
  1035. }
  1036. return RepositoryState.MERGING;
  1037. }
  1038. if (new File(getDirectory(), "BISECT_LOG").exists()) //$NON-NLS-1$
  1039. return RepositoryState.BISECTING;
  1040. if (new File(getDirectory(), Constants.CHERRY_PICK_HEAD).exists()) {
  1041. try {
  1042. if (!readDirCache().hasUnmergedPaths()) {
  1043. // no unmerged paths
  1044. return RepositoryState.CHERRY_PICKING_RESOLVED;
  1045. }
  1046. } catch (IOException e) {
  1047. // fall through to CHERRY_PICKING
  1048. }
  1049. return RepositoryState.CHERRY_PICKING;
  1050. }
  1051. if (new File(getDirectory(), Constants.REVERT_HEAD).exists()) {
  1052. try {
  1053. if (!readDirCache().hasUnmergedPaths()) {
  1054. // no unmerged paths
  1055. return RepositoryState.REVERTING_RESOLVED;
  1056. }
  1057. } catch (IOException e) {
  1058. // fall through to REVERTING
  1059. }
  1060. return RepositoryState.REVERTING;
  1061. }
  1062. return RepositoryState.SAFE;
  1063. }
  1064. /**
  1065. * Check validity of a ref name. It must not contain character that has
  1066. * a special meaning in a Git object reference expression. Some other
  1067. * dangerous characters are also excluded.
  1068. *
  1069. * For portability reasons '\' is excluded
  1070. *
  1071. * @param refName
  1072. *
  1073. * @return true if refName is a valid ref name
  1074. */
  1075. public static boolean isValidRefName(final String refName) {
  1076. final int len = refName.length();
  1077. if (len == 0)
  1078. return false;
  1079. if (refName.endsWith(".lock")) //$NON-NLS-1$
  1080. return false;
  1081. // Borrow logic for filterig out invalid paths. These
  1082. // are also invalid ref
  1083. try {
  1084. DirCacheCheckout.checkValidPath(refName);
  1085. } catch (InvalidPathException e) {
  1086. return false;
  1087. }
  1088. int components = 1;
  1089. char p = '\0';
  1090. for (int i = 0; i < len; i++) {
  1091. final char c = refName.charAt(i);
  1092. if (c <= ' ')
  1093. return false;
  1094. switch (c) {
  1095. case '.':
  1096. switch (p) {
  1097. case '\0': case '/': case '.':
  1098. return false;
  1099. }
  1100. if (i == len -1)
  1101. return false;
  1102. break;
  1103. case '/':
  1104. if (i == 0 || i == len - 1)
  1105. return false;
  1106. if (p == '/')
  1107. return false;
  1108. components++;
  1109. break;
  1110. case '{':
  1111. if (p == '@')
  1112. return false;
  1113. break;
  1114. case '~': case '^': case ':':
  1115. case '?': case '[': case '*':
  1116. case '\\':
  1117. case '\u007F':
  1118. return false;
  1119. }
  1120. p = c;
  1121. }
  1122. return components > 1;
  1123. }
  1124. /**
  1125. * Strip work dir and return normalized repository path.
  1126. *
  1127. * @param workDir Work dir
  1128. * @param file File whose path shall be stripped of its workdir
  1129. * @return normalized repository relative path or the empty
  1130. * string if the file is not relative to the work directory.
  1131. */
  1132. public static String stripWorkDir(File workDir, File file) {
  1133. final String filePath = file.getPath();
  1134. final String workDirPath = workDir.getPath();
  1135. if (filePath.length() <= workDirPath.length() ||
  1136. filePath.charAt(workDirPath.length()) != File.separatorChar ||
  1137. !filePath.startsWith(workDirPath)) {
  1138. File absWd = workDir.isAbsolute() ? workDir : workDir.getAbsoluteFile();
  1139. File absFile = file.isAbsolute() ? file : file.getAbsoluteFile();
  1140. if (absWd == workDir && absFile == file)
  1141. return ""; //$NON-NLS-1$
  1142. return stripWorkDir(absWd, absFile);
  1143. }
  1144. String relName = filePath.substring(workDirPath.length() + 1);
  1145. if (File.separatorChar != '/')
  1146. relName = relName.replace(File.separatorChar, '/');
  1147. return relName;
  1148. }
  1149. /**
  1150. * @return true if this is bare, which implies it has no working directory.
  1151. */
  1152. public boolean isBare() {
  1153. return workTree == null;
  1154. }
  1155. /**
  1156. * @return the root directory of the working tree, where files are checked
  1157. * out for viewing and editing.
  1158. * @throws NoWorkTreeException
  1159. * if this is bare, which implies it has no working directory.
  1160. * See {@link #isBare()}.
  1161. */
  1162. public File getWorkTree() throws NoWorkTreeException {
  1163. if (isBare())
  1164. throw new NoWorkTreeException();
  1165. return workTree;
  1166. }
  1167. /**
  1168. * Force a scan for changed refs.
  1169. *
  1170. * @throws IOException
  1171. */
  1172. public abstract void scanForRepoChanges() throws IOException;
  1173. /**
  1174. * Notify that the index changed
  1175. */
  1176. public abstract void notifyIndexChanged();
  1177. /**
  1178. * @param refName
  1179. *
  1180. * @return a more user friendly ref name
  1181. */
  1182. public static String shortenRefName(String refName) {
  1183. if (refName.startsWith(Constants.R_HEADS))
  1184. return refName.substring(Constants.R_HEADS.length());
  1185. if (refName.startsWith(Constants.R_TAGS))
  1186. return refName.substring(Constants.R_TAGS.length());
  1187. if (refName.startsWith(Constants.R_REMOTES))
  1188. return refName.substring(Constants.R_REMOTES.length());
  1189. return refName;
  1190. }
  1191. /**
  1192. * @param refName
  1193. * @return a {@link ReflogReader} for the supplied refname, or null if the
  1194. * named ref does not exist.
  1195. * @throws IOException
  1196. * the ref could not be accessed.
  1197. * @since 3.0
  1198. */
  1199. public abstract ReflogReader getReflogReader(String refName)
  1200. throws IOException;
  1201. /**
  1202. * Return the information stored in the file $GIT_DIR/MERGE_MSG. In this
  1203. * file operations triggering a merge will store a template for the commit
  1204. * message of the merge commit.
  1205. *
  1206. * @return a String containing the content of the MERGE_MSG file or
  1207. * {@code null} if this file doesn't exist
  1208. * @throws IOException
  1209. * @throws NoWorkTreeException
  1210. * if this is bare, which implies it has no working directory.
  1211. * See {@link #isBare()}.
  1212. */
  1213. public String readMergeCommitMsg() throws IOException, NoWorkTreeException {
  1214. return readCommitMsgFile(Constants.MERGE_MSG);
  1215. }
  1216. /**
  1217. * Write new content to the file $GIT_DIR/MERGE_MSG. In this file operations
  1218. * triggering a merge will store a template for the commit message of the
  1219. * merge commit. If <code>null</code> is specified as message the file will
  1220. * be deleted.
  1221. *
  1222. * @param msg
  1223. * the message which should be written or <code>null</code> to
  1224. * delete the file
  1225. *
  1226. * @throws IOException
  1227. */
  1228. public void writeMergeCommitMsg(String msg) throws IOException {
  1229. File mergeMsgFile = new File(gitDir, Constants.MERGE_MSG);
  1230. writeCommitMsg(mergeMsgFile, msg);
  1231. }
  1232. /**
  1233. * Return the information stored in the file $GIT_DIR/MERGE_HEAD. In this
  1234. * file operations triggering a merge will store the IDs of all heads which
  1235. * should be merged together with HEAD.
  1236. *
  1237. * @return a list of commits which IDs are listed in the MERGE_HEAD file or
  1238. * {@code null} if this file doesn't exist. Also if the file exists
  1239. * but is empty {@code null} will be returned
  1240. * @throws IOException
  1241. * @throws NoWorkTreeException
  1242. * if this is bare, which implies it has no working directory.
  1243. * See {@link #isBare()}.
  1244. */
  1245. public List<ObjectId> readMergeHeads() throws IOException, NoWorkTreeException {
  1246. if (isBare() || getDirectory() == null)
  1247. throw new NoWorkTreeException();
  1248. byte[] raw = readGitDirectoryFile(Constants.MERGE_HEAD);
  1249. if (raw == null)
  1250. return null;
  1251. LinkedList<ObjectId> heads = new LinkedList<ObjectId>();
  1252. for (int p = 0; p < raw.length;) {
  1253. heads.add(ObjectId.fromString(raw, p));
  1254. p = RawParseUtils
  1255. .nextLF(raw, p + Constants.OBJECT_ID_STRING_LENGTH);
  1256. }
  1257. return heads;
  1258. }
  1259. /**
  1260. * Write new merge-heads into $GIT_DIR/MERGE_HEAD. In this file operations
  1261. * triggering a merge will store the IDs of all heads which should be merged
  1262. * together with HEAD. If <code>null</code> is specified as list of commits
  1263. * the file will be deleted
  1264. *
  1265. * @param heads
  1266. * a list of commits which IDs should be written to
  1267. * $GIT_DIR/MERGE_HEAD or <code>null</code> to delete the file
  1268. * @throws IOException
  1269. */
  1270. public void writeMergeHeads(List<ObjectId> heads) throws IOException {
  1271. writeHeadsFile(heads, Constants.MERGE_HEAD);
  1272. }
  1273. /**
  1274. * Return the information stored in the file $GIT_DIR/CHERRY_PICK_HEAD.
  1275. *
  1276. * @return object id from CHERRY_PICK_HEAD file or {@code null} if this file
  1277. * doesn't exist. Also if the file exists but is empty {@code null}
  1278. * will be returned
  1279. * @throws IOException
  1280. * @throws NoWorkTreeException
  1281. * if this is bare, which implies it has no working directory.
  1282. * See {@link #isBare()}.
  1283. */
  1284. public ObjectId readCherryPickHead() throws IOException,
  1285. NoWorkTreeException {
  1286. if (isBare() || getDirectory() == null)
  1287. throw new NoWorkTreeException();
  1288. byte[] raw = readGitDirectoryFile(Constants.CHERRY_PICK_HEAD);
  1289. if (raw == null)
  1290. return null;
  1291. return ObjectId.fromString(raw, 0);
  1292. }
  1293. /**
  1294. * Return the information stored in the file $GIT_DIR/REVERT_HEAD.
  1295. *
  1296. * @return object id from REVERT_HEAD file or {@code null} if this file
  1297. * doesn't exist. Also if the file exists but is empty {@code null}
  1298. * will be returned
  1299. * @throws IOException
  1300. * @throws NoWorkTreeException
  1301. * if this is bare, which implies it has no working directory.
  1302. * See {@link #isBare()}.
  1303. */
  1304. public ObjectId readRevertHead() throws IOException, NoWorkTreeException {
  1305. if (isBare() || getDirectory() == null)
  1306. throw new NoWorkTreeException();
  1307. byte[] raw = readGitDirectoryFile(Constants.REVERT_HEAD);
  1308. if (raw == null)
  1309. return null;
  1310. return ObjectId.fromString(raw, 0);
  1311. }
  1312. /**
  1313. * Write cherry pick commit into $GIT_DIR/CHERRY_PICK_HEAD. This is used in
  1314. * case of conflicts to store the cherry which was tried to be picked.
  1315. *
  1316. * @param head
  1317. * an object id of the cherry commit or <code>null</code> to
  1318. * delete the file
  1319. * @throws IOException
  1320. */
  1321. public void writeCherryPickHead(ObjectId head) throws IOException {
  1322. List<ObjectId> heads = (head != null) ? Collections.singletonList(head)
  1323. : null;
  1324. writeHeadsFile(heads, Constants.CHERRY_PICK_HEAD);
  1325. }
  1326. /**
  1327. * Write revert commit into $GIT_DIR/REVERT_HEAD. This is used in case of
  1328. * conflicts to store the revert which was tried to be picked.
  1329. *
  1330. * @param head
  1331. * an object id of the revert commit or <code>null</code> to
  1332. * delete the file
  1333. * @throws IOException
  1334. */
  1335. public void writeRevertHead(ObjectId head) throws IOException {
  1336. List<ObjectId> heads = (head != null) ? Collections.singletonList(head)
  1337. : null;
  1338. writeHeadsFile(heads, Constants.REVERT_HEAD);
  1339. }
  1340. /**
  1341. * Write original HEAD commit into $GIT_DIR/ORIG_HEAD.
  1342. *
  1343. * @param head
  1344. * an object id of the original HEAD commit or <code>null</code>
  1345. * to delete the file
  1346. * @throws IOException
  1347. */
  1348. public void writeOrigHead(ObjectId head) throws IOException {
  1349. List<ObjectId> heads = head != null ? Collections.singletonList(head)
  1350. : null;
  1351. writeHeadsFile(heads, Constants.ORIG_HEAD);
  1352. }
  1353. /**
  1354. * Return the information stored in the file $GIT_DIR/ORIG_HEAD.
  1355. *
  1356. * @return object id from ORIG_HEAD file or {@code null} if this file
  1357. * doesn't exist. Also if the file exists but is empty {@code null}
  1358. * will be returned
  1359. * @throws IOException
  1360. * @throws NoWorkTreeException
  1361. * if this is bare, which implies it has no working directory.
  1362. * See {@link #isBare()}.
  1363. */
  1364. public ObjectId readOrigHead() throws IOException, NoWorkTreeException {
  1365. if (isBare() || getDirectory() == null)
  1366. throw new NoWorkTreeException();
  1367. byte[] raw = readGitDirectoryFile(Constants.ORIG_HEAD);
  1368. return raw != null ? ObjectId.fromString(raw, 0) : null;
  1369. }
  1370. /**
  1371. * Return the information stored in the file $GIT_DIR/SQUASH_MSG. In this
  1372. * file operations triggering a squashed merge will store a template for the
  1373. * commit message of the squash commit.
  1374. *
  1375. * @return a String containing the content of the SQUASH_MSG file or
  1376. * {@code null} if this file doesn't exist
  1377. * @throws IOException
  1378. * @throws NoWorkTreeException
  1379. * if this is bare, which implies it has no working directory.
  1380. * See {@link #isBare()}.
  1381. */
  1382. public String readSquashCommitMsg() throws IOException {
  1383. return readCommitMsgFile(Constants.SQUASH_MSG);
  1384. }
  1385. /**
  1386. * Write new content to the file $GIT_DIR/SQUASH_MSG. In this file
  1387. * operations triggering a squashed merge will store a template for the
  1388. * commit message of the squash commit. If <code>null</code> is specified as
  1389. * message the file will be deleted.
  1390. *
  1391. * @param msg
  1392. * the message which should be written or <code>null</code> to
  1393. * delete the file
  1394. *
  1395. * @throws IOException
  1396. */
  1397. public void writeSquashCommitMsg(String msg) throws IOException {
  1398. File squashMsgFile = new File(gitDir, Constants.SQUASH_MSG);
  1399. writeCommitMsg(squashMsgFile, msg);
  1400. }
  1401. private String readCommitMsgFile(String msgFilename) throws IOException {
  1402. if (isBare() || getDirectory() == null)
  1403. throw new NoWorkTreeException();
  1404. File mergeMsgFile = new File(getDirectory(), msgFilename);
  1405. try {
  1406. return RawParseUtils.decode(IO.readFully(mergeMsgFile));
  1407. } catch (FileNotFoundException e) {
  1408. // the file has disappeared in the meantime ignore it
  1409. return null;
  1410. }
  1411. }
  1412. private void writeCommitMsg(File msgFile, String msg) throws IOException {
  1413. if (msg != null) {
  1414. FileOutputStream fos = new FileOutputStream(msgFile);
  1415. try {
  1416. fos.write(msg.getBytes(Constants.CHARACTER_ENCODING));
  1417. } finally {
  1418. fos.close();
  1419. }
  1420. } else {
  1421. FileUtils.delete(msgFile, FileUtils.SKIP_MISSING);
  1422. }
  1423. }
  1424. /**
  1425. * Read a file from the git directory.
  1426. *
  1427. * @param filename
  1428. * @return the raw contents or null if the file doesn't exist or is empty
  1429. * @throws IOException
  1430. */
  1431. private byte[] readGitDirectoryFile(String filename) throws IOException {
  1432. File file = new File(getDirectory(), filename);
  1433. try {
  1434. byte[] raw = IO.readFully(file);
  1435. return raw.length > 0 ? raw : null;
  1436. } catch (FileNotFoundException notFound) {
  1437. return null;
  1438. }
  1439. }
  1440. /**
  1441. * Write the given heads to a file in the git directory.
  1442. *
  1443. * @param heads
  1444. * a list of object ids to write or null if the file should be
  1445. * deleted.
  1446. * @param filename
  1447. * @throws FileNotFoundException
  1448. * @throws IOException
  1449. */
  1450. private void writeHeadsFile(List<ObjectId> heads, String filename)
  1451. throws FileNotFoundException, IOException {
  1452. File headsFile = new File(getDirectory(), filename);
  1453. if (heads != null) {
  1454. BufferedOutputStream bos = new SafeBufferedOutputStream(
  1455. new FileOutputStream(headsFile));
  1456. try {
  1457. for (ObjectId id : heads) {
  1458. id.copyTo(bos);
  1459. bos.write('\n');
  1460. }
  1461. } finally {
  1462. bos.close();
  1463. }
  1464. } else {
  1465. FileUtils.delete(headsFile, FileUtils.SKIP_MISSING);
  1466. }
  1467. }
  1468. /**
  1469. * Read a file formatted like the git-rebase-todo file. The "done" file is
  1470. * also formatted like the git-rebase-todo file. These files can be found in
  1471. * .git/rebase-merge/ or .git/rebase-append/ folders.
  1472. *
  1473. * @param path
  1474. * path to the file relative to the repository's git-dir. E.g.
  1475. * "rebase-merge/git-rebase-todo" or "rebase-append/done"
  1476. * @param includeComments
  1477. * <code>true</code> if also comments should be reported
  1478. * @return the list of steps
  1479. * @throws IOException
  1480. * @since 3.2
  1481. */
  1482. public List<RebaseTodoLine> readRebaseTodo(String path,
  1483. boolean includeComments)
  1484. throws IOException {
  1485. return new RebaseTodoFile(this).readRebaseTodo(path, includeComments);
  1486. }
  1487. /**
  1488. * Write a file formatted like a git-rebase-todo file.
  1489. *
  1490. * @param path
  1491. * path to the file relative to the repository's git-dir. E.g.
  1492. * "rebase-merge/git-rebase-todo" or "rebase-append/done"
  1493. * @param steps
  1494. * the steps to be written
  1495. * @param append
  1496. * whether to append to an existing file or to write a new file
  1497. * @throws IOException
  1498. * @since 3.2
  1499. */
  1500. public void writeRebaseTodoFile(String path, List<RebaseTodoLine> steps,
  1501. boolean append)
  1502. throws IOException {
  1503. new RebaseTodoFile(this).writeRebaseTodoFile(path, steps, append);
  1504. }
  1505. }