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 42KB

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