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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190
  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-2008, 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.util.Collections;
  53. import java.util.HashMap;
  54. import java.util.HashSet;
  55. import java.util.LinkedList;
  56. import java.util.List;
  57. import java.util.Map;
  58. import java.util.Set;
  59. import java.util.concurrent.atomic.AtomicInteger;
  60. import org.eclipse.jgit.JGitText;
  61. import org.eclipse.jgit.dircache.DirCache;
  62. import org.eclipse.jgit.errors.CorruptObjectException;
  63. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  64. import org.eclipse.jgit.errors.MissingObjectException;
  65. import org.eclipse.jgit.errors.NoWorkTreeException;
  66. import org.eclipse.jgit.errors.RevisionSyntaxException;
  67. import org.eclipse.jgit.events.ListenerList;
  68. import org.eclipse.jgit.events.RepositoryEvent;
  69. import org.eclipse.jgit.revwalk.RevBlob;
  70. import org.eclipse.jgit.revwalk.RevCommit;
  71. import org.eclipse.jgit.revwalk.RevObject;
  72. import org.eclipse.jgit.revwalk.RevWalk;
  73. import org.eclipse.jgit.storage.file.ReflogReader;
  74. import org.eclipse.jgit.util.FS;
  75. import org.eclipse.jgit.util.IO;
  76. import org.eclipse.jgit.util.RawParseUtils;
  77. /**
  78. * Represents a Git repository.
  79. * <p>
  80. * A repository holds all objects and refs used for managing source code (could
  81. * be any type of file, but source code is what SCM's are typically used for).
  82. * <p>
  83. * This class is thread-safe.
  84. */
  85. public abstract class Repository {
  86. private static final ListenerList globalListeners = new ListenerList();
  87. /** @return the global listener list observing all events in this JVM. */
  88. public static ListenerList getGlobalListenerList() {
  89. return globalListeners;
  90. }
  91. private final AtomicInteger useCnt = new AtomicInteger(1);
  92. /** Metadata directory holding the repository's critical files. */
  93. private final File gitDir;
  94. /** File abstraction used to resolve paths. */
  95. private final FS fs;
  96. private GitIndex index;
  97. private final ListenerList myListeners = new ListenerList();
  98. /** If not bare, the top level directory of the working files. */
  99. private final File workTree;
  100. /** If not bare, the index file caching the working file states. */
  101. private final File indexFile;
  102. /**
  103. * Initialize a new repository instance.
  104. *
  105. * @param options
  106. * options to configure the repository.
  107. */
  108. protected Repository(final BaseRepositoryBuilder options) {
  109. gitDir = options.getGitDir();
  110. fs = options.getFS();
  111. workTree = options.getWorkTree();
  112. indexFile = options.getIndexFile();
  113. }
  114. /** @return listeners observing only events on this repository. */
  115. public ListenerList getListenerList() {
  116. return myListeners;
  117. }
  118. /**
  119. * Fire an event to all registered listeners.
  120. * <p>
  121. * The source repository of the event is automatically set to this
  122. * repository, before the event is delivered to any listeners.
  123. *
  124. * @param event
  125. * the event to deliver.
  126. */
  127. public void fireEvent(RepositoryEvent<?> event) {
  128. event.setRepository(this);
  129. myListeners.dispatch(event);
  130. globalListeners.dispatch(event);
  131. }
  132. /**
  133. * Create a new Git repository.
  134. * <p>
  135. * Repository with working tree is created using this method. This method is
  136. * the same as {@code create(false)}.
  137. *
  138. * @throws IOException
  139. * @see #create(boolean)
  140. */
  141. public void create() throws IOException {
  142. create(false);
  143. }
  144. /**
  145. * Create a new Git repository initializing the necessary files and
  146. * directories.
  147. *
  148. * @param bare
  149. * if true, a bare repository (a repository without a working
  150. * directory) is created.
  151. * @throws IOException
  152. * in case of IO problem
  153. */
  154. public abstract void create(boolean bare) throws IOException;
  155. /** @return local metadata directory; null if repository isn't local. */
  156. public File getDirectory() {
  157. return gitDir;
  158. }
  159. /**
  160. * @return the directory containing the objects owned by this repository.
  161. */
  162. public abstract File getObjectsDirectory();
  163. /**
  164. * @return the object database which stores this repository's data.
  165. */
  166. public abstract ObjectDatabase getObjectDatabase();
  167. /** @return a new inserter to create objects in {@link #getObjectDatabase()} */
  168. public ObjectInserter newObjectInserter() {
  169. return getObjectDatabase().newInserter();
  170. }
  171. /** @return a new inserter to create objects in {@link #getObjectDatabase()} */
  172. public ObjectReader newObjectReader() {
  173. return getObjectDatabase().newReader();
  174. }
  175. /** @return the reference database which stores the reference namespace. */
  176. public abstract RefDatabase getRefDatabase();
  177. /**
  178. * @return the configuration of this repository
  179. */
  180. public abstract StoredConfig getConfig();
  181. /**
  182. * @return the used file system abstraction
  183. */
  184. public FS getFS() {
  185. return fs;
  186. }
  187. /**
  188. * @param objectId
  189. * @return true if the specified object is stored in this repo or any of the
  190. * known shared repositories.
  191. */
  192. public boolean hasObject(AnyObjectId objectId) {
  193. try {
  194. return getObjectDatabase().has(objectId);
  195. } catch (IOException e) {
  196. // Legacy API, assume error means "no"
  197. return false;
  198. }
  199. }
  200. /**
  201. * Open an object from this repository.
  202. * <p>
  203. * This is a one-shot call interface which may be faster than allocating a
  204. * {@link #newObjectReader()} to perform the lookup.
  205. *
  206. * @param objectId
  207. * identity of the object to open.
  208. * @return a {@link ObjectLoader} for accessing the object.
  209. * @throws MissingObjectException
  210. * the object does not exist.
  211. * @throws IOException
  212. * the object store cannot be accessed.
  213. */
  214. public ObjectLoader open(final AnyObjectId objectId)
  215. throws MissingObjectException, IOException {
  216. return getObjectDatabase().open(objectId);
  217. }
  218. /**
  219. * Open an object from this repository.
  220. * <p>
  221. * This is a one-shot call interface which may be faster than allocating a
  222. * {@link #newObjectReader()} to perform the lookup.
  223. *
  224. * @param objectId
  225. * identity of the object to open.
  226. * @param typeHint
  227. * hint about the type of object being requested;
  228. * {@link ObjectReader#OBJ_ANY} if the object type is not known,
  229. * or does not matter to the caller.
  230. * @return a {@link ObjectLoader} for accessing the object.
  231. * @throws MissingObjectException
  232. * the object does not exist.
  233. * @throws IncorrectObjectTypeException
  234. * typeHint was not OBJ_ANY, and the object's actual type does
  235. * not match typeHint.
  236. * @throws IOException
  237. * the object store cannot be accessed.
  238. */
  239. public ObjectLoader open(AnyObjectId objectId, int typeHint)
  240. throws MissingObjectException, IncorrectObjectTypeException,
  241. IOException {
  242. return getObjectDatabase().open(objectId, typeHint);
  243. }
  244. /**
  245. * Access a Tree object using a symbolic reference. This reference may
  246. * be a SHA-1 or ref in combination with a number of symbols translating
  247. * from one ref or SHA1-1 to another, such as HEAD^{tree} etc.
  248. *
  249. * @param revstr a reference to a git commit object
  250. * @return a Tree named by the specified string
  251. * @throws IOException
  252. *
  253. * @see #resolve(String)
  254. * @deprecated Use {@link #resolve(String)} and pass its return value to
  255. * {@link org.eclipse.jgit.treewalk.TreeWalk#addTree(AnyObjectId)}.
  256. */
  257. @Deprecated
  258. public Tree mapTree(final String revstr) throws IOException {
  259. final ObjectId id = resolve(revstr);
  260. return id != null ? mapTree(id) : null;
  261. }
  262. /**
  263. * Access a Tree by SHA'1 id.
  264. * @param id
  265. * @return Tree or null
  266. * @throws IOException for I/O error or unexpected object type.
  267. * @deprecated Use {@link org.eclipse.jgit.treewalk.TreeWalk#addTree(AnyObjectId)}.
  268. */
  269. @Deprecated
  270. public Tree mapTree(final ObjectId id) throws IOException {
  271. final ObjectLoader or;
  272. try {
  273. or = open(id);
  274. } catch (MissingObjectException notFound) {
  275. return null;
  276. }
  277. final byte[] raw = or.getCachedBytes();
  278. switch (or.getType()) {
  279. case Constants.OBJ_TREE:
  280. return new Tree(this, id, raw);
  281. case Constants.OBJ_COMMIT:
  282. return mapTree(ObjectId.fromString(raw, 5));
  283. default:
  284. throw new IncorrectObjectTypeException(id, Constants.TYPE_TREE);
  285. }
  286. }
  287. /**
  288. * Access a tag by symbolic name.
  289. *
  290. * @param revstr
  291. * @return a Tag or null
  292. * @throws IOException on I/O error or unexpected type
  293. * @deprecated Use {@link #resolve(String)} and feed its return value to
  294. * {@link org.eclipse.jgit.revwalk.RevWalk#parseTag(AnyObjectId)}.
  295. */
  296. @Deprecated
  297. public Tag mapTag(String revstr) throws IOException {
  298. final ObjectId id = resolve(revstr);
  299. return id != null ? mapTag(revstr, id) : null;
  300. }
  301. /**
  302. * Access a Tag by SHA'1 id
  303. * @param refName
  304. * @param id
  305. * @return Commit or null
  306. * @throws IOException for I/O error or unexpected object type.
  307. * @deprecated Use {@link org.eclipse.jgit.revwalk.RevWalk#parseTag(AnyObjectId)}.
  308. */
  309. @Deprecated
  310. public Tag mapTag(final String refName, final ObjectId id) throws IOException {
  311. final ObjectLoader or;
  312. try {
  313. or = open(id);
  314. } catch (MissingObjectException notFound) {
  315. return null;
  316. }
  317. if (or.getType() == Constants.OBJ_TAG)
  318. return new Tag(this, id, refName, or.getCachedBytes());
  319. return new Tag(this, id, refName, null);
  320. }
  321. /**
  322. * Create a command to update, create or delete a ref in this repository.
  323. *
  324. * @param ref
  325. * name of the ref the caller wants to modify.
  326. * @return an update command. The caller must finish populating this command
  327. * and then invoke one of the update methods to actually make a
  328. * change.
  329. * @throws IOException
  330. * a symbolic ref was passed in and could not be resolved back
  331. * to the base ref, as the symbolic ref could not be read.
  332. */
  333. public RefUpdate updateRef(final String ref) throws IOException {
  334. return updateRef(ref, false);
  335. }
  336. /**
  337. * Create a command to update, create or delete a ref in this repository.
  338. *
  339. * @param ref
  340. * name of the ref the caller wants to modify.
  341. * @param detach
  342. * true to create a detached head
  343. * @return an update command. The caller must finish populating this command
  344. * and then invoke one of the update methods to actually make a
  345. * change.
  346. * @throws IOException
  347. * a symbolic ref was passed in and could not be resolved back
  348. * to the base ref, as the symbolic ref could not be read.
  349. */
  350. public RefUpdate updateRef(final String ref, final boolean detach) throws IOException {
  351. return getRefDatabase().newUpdate(ref, detach);
  352. }
  353. /**
  354. * Create a command to rename a ref in this repository
  355. *
  356. * @param fromRef
  357. * name of ref to rename from
  358. * @param toRef
  359. * name of ref to rename to
  360. * @return an update command that knows how to rename a branch to another.
  361. * @throws IOException
  362. * the rename could not be performed.
  363. *
  364. */
  365. public RefRename renameRef(final String fromRef, final String toRef) throws IOException {
  366. return getRefDatabase().newRename(fromRef, toRef);
  367. }
  368. /**
  369. * Parse a git revision string and return an object id.
  370. *
  371. * Currently supported is combinations of these.
  372. * <ul>
  373. * <li>SHA-1 - a SHA-1</li>
  374. * <li>refs/... - a ref name</li>
  375. * <li>ref^n - nth parent reference</li>
  376. * <li>ref~n - distance via parent reference</li>
  377. * <li>ref@{n} - nth version of ref</li>
  378. * <li>ref^{tree} - tree references by ref</li>
  379. * <li>ref^{commit} - commit references by ref</li>
  380. * </ul>
  381. *
  382. * Not supported is:
  383. * <ul>
  384. * <li>timestamps in reflogs, ref@{full or relative timestamp}</li>
  385. * <li>abbreviated SHA-1's</li>
  386. * </ul>
  387. *
  388. * @param revstr
  389. * A git object references expression
  390. * @return an ObjectId or null if revstr can't be resolved to any ObjectId
  391. * @throws IOException
  392. * on serious errors
  393. */
  394. public ObjectId resolve(final String revstr) throws IOException {
  395. RevWalk rw = new RevWalk(this);
  396. try {
  397. return resolve(rw, revstr);
  398. } finally {
  399. rw.release();
  400. }
  401. }
  402. private ObjectId resolve(final RevWalk rw, final String revstr) throws IOException {
  403. char[] rev = revstr.toCharArray();
  404. RevObject ref = null;
  405. for (int i = 0; i < rev.length; ++i) {
  406. switch (rev[i]) {
  407. case '^':
  408. if (ref == null) {
  409. ref = parseSimple(rw, new String(rev, 0, i));
  410. if (ref == null)
  411. return null;
  412. }
  413. if (i + 1 < rev.length) {
  414. switch (rev[i + 1]) {
  415. case '0':
  416. case '1':
  417. case '2':
  418. case '3':
  419. case '4':
  420. case '5':
  421. case '6':
  422. case '7':
  423. case '8':
  424. case '9':
  425. int j;
  426. ref = rw.parseCommit(ref);
  427. for (j = i + 1; j < rev.length; ++j) {
  428. if (!Character.isDigit(rev[j]))
  429. break;
  430. }
  431. String parentnum = new String(rev, i + 1, j - i - 1);
  432. int pnum;
  433. try {
  434. pnum = Integer.parseInt(parentnum);
  435. } catch (NumberFormatException e) {
  436. throw new RevisionSyntaxException(
  437. JGitText.get().invalidCommitParentNumber,
  438. revstr);
  439. }
  440. if (pnum != 0) {
  441. RevCommit commit = (RevCommit) ref;
  442. if (pnum > commit.getParentCount())
  443. ref = null;
  444. else
  445. ref = commit.getParent(pnum - 1);
  446. }
  447. i = j - 1;
  448. break;
  449. case '{':
  450. int k;
  451. String item = null;
  452. for (k = i + 2; k < rev.length; ++k) {
  453. if (rev[k] == '}') {
  454. item = new String(rev, i + 2, k - i - 2);
  455. break;
  456. }
  457. }
  458. i = k;
  459. if (item != null)
  460. if (item.equals("tree")) {
  461. ref = rw.parseTree(ref);
  462. } else if (item.equals("commit")) {
  463. ref = rw.parseCommit(ref);
  464. } else if (item.equals("blob")) {
  465. ref = rw.peel(ref);
  466. if (!(ref instanceof RevBlob))
  467. throw new IncorrectObjectTypeException(ref,
  468. Constants.TYPE_BLOB);
  469. } else if (item.equals("")) {
  470. ref = rw.peel(ref);
  471. } else
  472. throw new RevisionSyntaxException(revstr);
  473. else
  474. throw new RevisionSyntaxException(revstr);
  475. break;
  476. default:
  477. ref = rw.parseAny(ref);
  478. if (ref instanceof RevCommit) {
  479. RevCommit commit = ((RevCommit) ref);
  480. if (commit.getParentCount() == 0)
  481. ref = null;
  482. else
  483. ref = commit.getParent(0);
  484. } else
  485. throw new IncorrectObjectTypeException(ref,
  486. Constants.TYPE_COMMIT);
  487. }
  488. } else {
  489. ref = rw.peel(ref);
  490. if (ref instanceof RevCommit) {
  491. RevCommit commit = ((RevCommit) ref);
  492. if (commit.getParentCount() == 0)
  493. ref = null;
  494. else
  495. ref = commit.getParent(0);
  496. } else
  497. throw new IncorrectObjectTypeException(ref,
  498. Constants.TYPE_COMMIT);
  499. }
  500. break;
  501. case '~':
  502. if (ref == null) {
  503. ref = parseSimple(rw, new String(rev, 0, i));
  504. if (ref == null)
  505. return null;
  506. }
  507. ref = rw.peel(ref);
  508. if (!(ref instanceof RevCommit))
  509. throw new IncorrectObjectTypeException(ref,
  510. Constants.TYPE_COMMIT);
  511. int l;
  512. for (l = i + 1; l < rev.length; ++l) {
  513. if (!Character.isDigit(rev[l]))
  514. break;
  515. }
  516. String distnum = new String(rev, i + 1, l - i - 1);
  517. int dist;
  518. try {
  519. dist = Integer.parseInt(distnum);
  520. } catch (NumberFormatException e) {
  521. throw new RevisionSyntaxException(
  522. JGitText.get().invalidAncestryLength, revstr);
  523. }
  524. while (dist > 0) {
  525. RevCommit commit = (RevCommit) ref;
  526. if (commit.getParentCount() == 0) {
  527. ref = null;
  528. break;
  529. }
  530. commit = commit.getParent(0);
  531. rw.parseHeaders(commit);
  532. ref = commit;
  533. --dist;
  534. }
  535. i = l - 1;
  536. break;
  537. case '@':
  538. int m;
  539. String time = null;
  540. for (m = i + 2; m < rev.length; ++m) {
  541. if (rev[m] == '}') {
  542. time = new String(rev, i + 2, m - i - 2);
  543. break;
  544. }
  545. }
  546. if (time != null)
  547. throw new RevisionSyntaxException(
  548. JGitText.get().reflogsNotYetSupportedByRevisionParser,
  549. revstr);
  550. i = m - 1;
  551. break;
  552. default:
  553. if (ref != null)
  554. throw new RevisionSyntaxException(revstr);
  555. }
  556. }
  557. return ref != null ? ref.copy() : resolveSimple(revstr);
  558. }
  559. private RevObject parseSimple(RevWalk rw, String revstr) throws IOException {
  560. ObjectId id = resolveSimple(revstr);
  561. return id != null ? rw.parseAny(id) : null;
  562. }
  563. private ObjectId resolveSimple(final String revstr) throws IOException {
  564. if (ObjectId.isId(revstr))
  565. return ObjectId.fromString(revstr);
  566. final Ref r = getRefDatabase().getRef(revstr);
  567. return r != null ? r.getObjectId() : null;
  568. }
  569. /** Increment the use counter by one, requiring a matched {@link #close()}. */
  570. public void incrementOpen() {
  571. useCnt.incrementAndGet();
  572. }
  573. /** Decrement the use count, and maybe close resources. */
  574. public void close() {
  575. if (useCnt.decrementAndGet() == 0) {
  576. doClose();
  577. }
  578. }
  579. /**
  580. * Invoked when the use count drops to zero during {@link #close()}.
  581. * <p>
  582. * The default implementation closes the object and ref databases.
  583. */
  584. protected void doClose() {
  585. getObjectDatabase().close();
  586. getRefDatabase().close();
  587. }
  588. /**
  589. * Add a single existing pack to the list of available pack files.
  590. *
  591. * @param pack
  592. * path of the pack file to open.
  593. * @param idx
  594. * path of the corresponding index file.
  595. * @throws IOException
  596. * index file could not be opened, read, or is not recognized as
  597. * a Git pack file index.
  598. */
  599. public abstract void openPack(File pack, File idx) throws IOException;
  600. public String toString() {
  601. String desc;
  602. if (getDirectory() != null)
  603. desc = getDirectory().getPath();
  604. else
  605. desc = getClass().getSimpleName() + "-"
  606. + System.identityHashCode(this);
  607. return "Repository[" + desc + "]";
  608. }
  609. /**
  610. * Get the name of the reference that {@code HEAD} points to.
  611. * <p>
  612. * This is essentially the same as doing:
  613. *
  614. * <pre>
  615. * return getRef(Constants.HEAD).getTarget().getName()
  616. * </pre>
  617. *
  618. * Except when HEAD is detached, in which case this method returns the
  619. * current ObjectId in hexadecimal string format.
  620. *
  621. * @return name of current branch (for example {@code refs/heads/master}) or
  622. * an ObjectId in hex format if the current branch is detached.
  623. * @throws IOException
  624. */
  625. public String getFullBranch() throws IOException {
  626. Ref head = getRef(Constants.HEAD);
  627. if (head == null)
  628. return null;
  629. if (head.isSymbolic())
  630. return head.getTarget().getName();
  631. if (head.getObjectId() != null)
  632. return head.getObjectId().name();
  633. return null;
  634. }
  635. /**
  636. * Get the short name of the current branch that {@code HEAD} points to.
  637. * <p>
  638. * This is essentially the same as {@link #getFullBranch()}, except the
  639. * leading prefix {@code refs/heads/} is removed from the reference before
  640. * it is returned to the caller.
  641. *
  642. * @return name of current branch (for example {@code master}), or an
  643. * ObjectId in hex format if the current branch is detached.
  644. * @throws IOException
  645. */
  646. public String getBranch() throws IOException {
  647. String name = getFullBranch();
  648. if (name != null)
  649. return shortenRefName(name);
  650. return name;
  651. }
  652. /**
  653. * Objects known to exist but not expressed by {@link #getAllRefs()}.
  654. * <p>
  655. * When a repository borrows objects from another repository, it can
  656. * advertise that it safely has that other repository's references, without
  657. * exposing any other details about the other repository. This may help
  658. * a client trying to push changes avoid pushing more than it needs to.
  659. *
  660. * @return unmodifiable collection of other known objects.
  661. */
  662. public Set<ObjectId> getAdditionalHaves() {
  663. return Collections.emptySet();
  664. }
  665. /**
  666. * Get a ref by name.
  667. *
  668. * @param name
  669. * the name of the ref to lookup. May be a short-hand form, e.g.
  670. * "master" which is is automatically expanded to
  671. * "refs/heads/master" if "refs/heads/master" already exists.
  672. * @return the Ref with the given name, or null if it does not exist
  673. * @throws IOException
  674. */
  675. public Ref getRef(final String name) throws IOException {
  676. return getRefDatabase().getRef(name);
  677. }
  678. /**
  679. * @return mutable map of all known refs (heads, tags, remotes).
  680. */
  681. public Map<String, Ref> getAllRefs() {
  682. try {
  683. return getRefDatabase().getRefs(RefDatabase.ALL);
  684. } catch (IOException e) {
  685. return new HashMap<String, Ref>();
  686. }
  687. }
  688. /**
  689. * @return mutable map of all tags; key is short tag name ("v1.0") and value
  690. * of the entry contains the ref with the full tag name
  691. * ("refs/tags/v1.0").
  692. */
  693. public Map<String, Ref> getTags() {
  694. try {
  695. return getRefDatabase().getRefs(Constants.R_TAGS);
  696. } catch (IOException e) {
  697. return new HashMap<String, Ref>();
  698. }
  699. }
  700. /**
  701. * Peel a possibly unpeeled reference to an annotated tag.
  702. * <p>
  703. * If the ref cannot be peeled (as it does not refer to an annotated tag)
  704. * the peeled id stays null, but {@link Ref#isPeeled()} will be true.
  705. *
  706. * @param ref
  707. * The ref to peel
  708. * @return <code>ref</code> if <code>ref.isPeeled()</code> is true; else a
  709. * new Ref object representing the same data as Ref, but isPeeled()
  710. * will be true and getPeeledObjectId will contain the peeled object
  711. * (or null).
  712. */
  713. public Ref peel(final Ref ref) {
  714. try {
  715. return getRefDatabase().peel(ref);
  716. } catch (IOException e) {
  717. // Historical accident; if the reference cannot be peeled due
  718. // to some sort of repository access problem we claim that the
  719. // same as if the reference was not an annotated tag.
  720. return ref;
  721. }
  722. }
  723. /**
  724. * @return a map with all objects referenced by a peeled ref.
  725. */
  726. public Map<AnyObjectId, Set<Ref>> getAllRefsByPeeledObjectId() {
  727. Map<String, Ref> allRefs = getAllRefs();
  728. Map<AnyObjectId, Set<Ref>> ret = new HashMap<AnyObjectId, Set<Ref>>(allRefs.size());
  729. for (Ref ref : allRefs.values()) {
  730. ref = peel(ref);
  731. AnyObjectId target = ref.getPeeledObjectId();
  732. if (target == null)
  733. target = ref.getObjectId();
  734. // We assume most Sets here are singletons
  735. Set<Ref> oset = ret.put(target, Collections.singleton(ref));
  736. if (oset != null) {
  737. // that was not the case (rare)
  738. if (oset.size() == 1) {
  739. // Was a read-only singleton, we must copy to a new Set
  740. oset = new HashSet<Ref>(oset);
  741. }
  742. ret.put(target, oset);
  743. oset.add(ref);
  744. }
  745. }
  746. return ret;
  747. }
  748. /**
  749. * @return a representation of the index associated with this
  750. * {@link Repository}
  751. * @throws IOException
  752. * if the index can not be read
  753. * @throws NoWorkTreeException
  754. * if this is bare, which implies it has no working directory.
  755. * See {@link #isBare()}.
  756. */
  757. public GitIndex getIndex() throws IOException, NoWorkTreeException {
  758. if (isBare())
  759. throw new NoWorkTreeException();
  760. if (index == null) {
  761. index = new GitIndex(this);
  762. index.read();
  763. } else {
  764. index.rereadIfNecessary();
  765. }
  766. return index;
  767. }
  768. /**
  769. * @return the index file location
  770. * @throws NoWorkTreeException
  771. * if this is bare, which implies it has no working directory.
  772. * See {@link #isBare()}.
  773. */
  774. public File getIndexFile() throws NoWorkTreeException {
  775. if (isBare())
  776. throw new NoWorkTreeException();
  777. return indexFile;
  778. }
  779. /**
  780. * Create a new in-core index representation and read an index from disk.
  781. * <p>
  782. * The new index will be read before it is returned to the caller. Read
  783. * failures are reported as exceptions and therefore prevent the method from
  784. * returning a partially populated index.
  785. *
  786. * @return a cache representing the contents of the specified index file (if
  787. * it exists) or an empty cache if the file does not exist.
  788. * @throws NoWorkTreeException
  789. * if this is bare, which implies it has no working directory.
  790. * See {@link #isBare()}.
  791. * @throws IOException
  792. * the index file is present but could not be read.
  793. * @throws CorruptObjectException
  794. * the index file is using a format or extension that this
  795. * library does not support.
  796. */
  797. public DirCache readDirCache() throws NoWorkTreeException,
  798. CorruptObjectException, IOException {
  799. return DirCache.read(getIndexFile(), getFS());
  800. }
  801. /**
  802. * Create a new in-core index representation, lock it, and read from disk.
  803. * <p>
  804. * The new index will be locked and then read before it is returned to the
  805. * caller. Read failures are reported as exceptions and therefore prevent
  806. * the method from returning a partially populated index.
  807. *
  808. * @return a cache representing the contents of the specified index file (if
  809. * it exists) or an empty cache if the file does not exist.
  810. * @throws NoWorkTreeException
  811. * if this is bare, which implies it has no working directory.
  812. * See {@link #isBare()}.
  813. * @throws IOException
  814. * the index file is present but could not be read, or the lock
  815. * could not be obtained.
  816. * @throws CorruptObjectException
  817. * the index file is using a format or extension that this
  818. * library does not support.
  819. */
  820. public DirCache lockDirCache() throws NoWorkTreeException,
  821. CorruptObjectException, IOException {
  822. return DirCache.lock(getIndexFile(), getFS());
  823. }
  824. static byte[] gitInternalSlash(byte[] bytes) {
  825. if (File.separatorChar == '/')
  826. return bytes;
  827. for (int i=0; i<bytes.length; ++i)
  828. if (bytes[i] == File.separatorChar)
  829. bytes[i] = '/';
  830. return bytes;
  831. }
  832. /**
  833. * @return an important state
  834. */
  835. public RepositoryState getRepositoryState() {
  836. if (isBare() || getDirectory() == null)
  837. return RepositoryState.BARE;
  838. // Pre Git-1.6 logic
  839. if (new File(getWorkTree(), ".dotest").exists())
  840. return RepositoryState.REBASING;
  841. if (new File(getDirectory(), ".dotest-merge").exists())
  842. return RepositoryState.REBASING_INTERACTIVE;
  843. // From 1.6 onwards
  844. if (new File(getDirectory(),"rebase-apply/rebasing").exists())
  845. return RepositoryState.REBASING_REBASING;
  846. if (new File(getDirectory(),"rebase-apply/applying").exists())
  847. return RepositoryState.APPLY;
  848. if (new File(getDirectory(),"rebase-apply").exists())
  849. return RepositoryState.REBASING;
  850. if (new File(getDirectory(),"rebase-merge/interactive").exists())
  851. return RepositoryState.REBASING_INTERACTIVE;
  852. if (new File(getDirectory(),"rebase-merge").exists())
  853. return RepositoryState.REBASING_MERGE;
  854. // Both versions
  855. if (new File(getDirectory(), "MERGE_HEAD").exists()) {
  856. // we are merging - now check whether we have unmerged paths
  857. try {
  858. if (!readDirCache().hasUnmergedPaths()) {
  859. // no unmerged paths -> return the MERGING_RESOLVED state
  860. return RepositoryState.MERGING_RESOLVED;
  861. }
  862. } catch (IOException e) {
  863. // Can't decide whether unmerged paths exists. Return
  864. // MERGING state to be on the safe side (in state MERGING
  865. // you are not allow to do anything)
  866. e.printStackTrace();
  867. }
  868. return RepositoryState.MERGING;
  869. }
  870. if (new File(getDirectory(), "BISECT_LOG").exists())
  871. return RepositoryState.BISECTING;
  872. return RepositoryState.SAFE;
  873. }
  874. /**
  875. * Check validity of a ref name. It must not contain character that has
  876. * a special meaning in a Git object reference expression. Some other
  877. * dangerous characters are also excluded.
  878. *
  879. * For portability reasons '\' is excluded
  880. *
  881. * @param refName
  882. *
  883. * @return true if refName is a valid ref name
  884. */
  885. public static boolean isValidRefName(final String refName) {
  886. final int len = refName.length();
  887. if (len == 0)
  888. return false;
  889. if (refName.endsWith(".lock"))
  890. return false;
  891. int components = 1;
  892. char p = '\0';
  893. for (int i = 0; i < len; i++) {
  894. final char c = refName.charAt(i);
  895. if (c <= ' ')
  896. return false;
  897. switch (c) {
  898. case '.':
  899. switch (p) {
  900. case '\0': case '/': case '.':
  901. return false;
  902. }
  903. if (i == len -1)
  904. return false;
  905. break;
  906. case '/':
  907. if (i == 0 || i == len - 1)
  908. return false;
  909. components++;
  910. break;
  911. case '{':
  912. if (p == '@')
  913. return false;
  914. break;
  915. case '~': case '^': case ':':
  916. case '?': case '[': case '*':
  917. case '\\':
  918. return false;
  919. }
  920. p = c;
  921. }
  922. return components > 1;
  923. }
  924. /**
  925. * Strip work dir and return normalized repository path.
  926. *
  927. * @param workDir Work dir
  928. * @param file File whose path shall be stripped of its workdir
  929. * @return normalized repository relative path or the empty
  930. * string if the file is not relative to the work directory.
  931. */
  932. public static String stripWorkDir(File workDir, File file) {
  933. final String filePath = file.getPath();
  934. final String workDirPath = workDir.getPath();
  935. if (filePath.length() <= workDirPath.length() ||
  936. filePath.charAt(workDirPath.length()) != File.separatorChar ||
  937. !filePath.startsWith(workDirPath)) {
  938. File absWd = workDir.isAbsolute() ? workDir : workDir.getAbsoluteFile();
  939. File absFile = file.isAbsolute() ? file : file.getAbsoluteFile();
  940. if (absWd == workDir && absFile == file)
  941. return "";
  942. return stripWorkDir(absWd, absFile);
  943. }
  944. String relName = filePath.substring(workDirPath.length() + 1);
  945. if (File.separatorChar != '/')
  946. relName = relName.replace(File.separatorChar, '/');
  947. return relName;
  948. }
  949. /**
  950. * @return true if this is bare, which implies it has no working directory.
  951. */
  952. public boolean isBare() {
  953. return workTree == null;
  954. }
  955. /**
  956. * @return the root directory of the working tree, where files are checked
  957. * out for viewing and editing.
  958. * @throws NoWorkTreeException
  959. * if this is bare, which implies it has no working directory.
  960. * See {@link #isBare()}.
  961. */
  962. public File getWorkTree() throws NoWorkTreeException {
  963. if (isBare())
  964. throw new NoWorkTreeException();
  965. return workTree;
  966. }
  967. /**
  968. * Force a scan for changed refs.
  969. *
  970. * @throws IOException
  971. */
  972. public abstract void scanForRepoChanges() throws IOException;
  973. /**
  974. * @param refName
  975. *
  976. * @return a more user friendly ref name
  977. */
  978. public String shortenRefName(String refName) {
  979. if (refName.startsWith(Constants.R_HEADS))
  980. return refName.substring(Constants.R_HEADS.length());
  981. if (refName.startsWith(Constants.R_TAGS))
  982. return refName.substring(Constants.R_TAGS.length());
  983. if (refName.startsWith(Constants.R_REMOTES))
  984. return refName.substring(Constants.R_REMOTES.length());
  985. return refName;
  986. }
  987. /**
  988. * @param refName
  989. * @return a {@link ReflogReader} for the supplied refname, or null if the
  990. * named ref does not exist.
  991. * @throws IOException the ref could not be accessed.
  992. */
  993. public abstract ReflogReader getReflogReader(String refName)
  994. throws IOException;
  995. /**
  996. * Return the information stored in the file $GIT_DIR/MERGE_MSG. In this
  997. * file operations triggering a merge will store a template for the commit
  998. * message of the merge commit.
  999. *
  1000. * @return a String containing the content of the MERGE_MSG file or
  1001. * {@code null} if this file doesn't exist
  1002. * @throws IOException
  1003. * @throws NoWorkTreeException
  1004. * if this is bare, which implies it has no working directory.
  1005. * See {@link #isBare()}.
  1006. */
  1007. public String readMergeCommitMsg() throws IOException, NoWorkTreeException {
  1008. if (isBare() || getDirectory() == null)
  1009. throw new NoWorkTreeException();
  1010. File mergeMsgFile = new File(getDirectory(), Constants.MERGE_MSG);
  1011. try {
  1012. return RawParseUtils.decode(IO.readFully(mergeMsgFile));
  1013. } catch (FileNotFoundException e) {
  1014. // MERGE_MSG file has disappeared in the meantime
  1015. // ignore it
  1016. return null;
  1017. }
  1018. }
  1019. /**
  1020. * Write new content to the file $GIT_DIR/MERGE_MSG. In this file operations
  1021. * triggering a merge will store a template for the commit message of the
  1022. * merge commit. If <code>null</code> is specified as message the file will
  1023. * be deleted
  1024. *
  1025. * @param msg
  1026. * the message which should be written or <code>null</code> to
  1027. * delete the file
  1028. *
  1029. * @throws IOException
  1030. */
  1031. public void writeMergeCommitMsg(String msg) throws IOException {
  1032. File mergeMsgFile = new File(gitDir, Constants.MERGE_MSG);
  1033. if (msg != null) {
  1034. FileOutputStream fos = new FileOutputStream(mergeMsgFile);
  1035. try {
  1036. fos.write(msg.getBytes(Constants.CHARACTER_ENCODING));
  1037. } finally {
  1038. fos.close();
  1039. }
  1040. } else {
  1041. mergeMsgFile.delete();
  1042. }
  1043. }
  1044. /**
  1045. * Return the information stored in the file $GIT_DIR/MERGE_HEAD. In this
  1046. * file operations triggering a merge will store the IDs of all heads which
  1047. * should be merged together with HEAD.
  1048. *
  1049. * @return a list of {@link Commit}s which IDs are listed in the MERGE_HEAD
  1050. * file or {@code null} if this file doesn't exist. Also if the file
  1051. * exists but is empty {@code null} will be returned
  1052. * @throws IOException
  1053. * @throws NoWorkTreeException
  1054. * if this is bare, which implies it has no working directory.
  1055. * See {@link #isBare()}.
  1056. */
  1057. public List<ObjectId> readMergeHeads() throws IOException, NoWorkTreeException {
  1058. if (isBare() || getDirectory() == null)
  1059. throw new NoWorkTreeException();
  1060. File mergeHeadFile = new File(getDirectory(), Constants.MERGE_HEAD);
  1061. byte[] raw;
  1062. try {
  1063. raw = IO.readFully(mergeHeadFile);
  1064. } catch (FileNotFoundException notFound) {
  1065. return null;
  1066. }
  1067. if (raw.length == 0)
  1068. return null;
  1069. LinkedList<ObjectId> heads = new LinkedList<ObjectId>();
  1070. for (int p = 0; p < raw.length;) {
  1071. heads.add(ObjectId.fromString(raw, p));
  1072. p = RawParseUtils
  1073. .nextLF(raw, p + Constants.OBJECT_ID_STRING_LENGTH);
  1074. }
  1075. return heads;
  1076. }
  1077. /**
  1078. * Write new merge-heads into $GIT_DIR/MERGE_HEAD. In this file operations
  1079. * triggering a merge will store the IDs of all heads which should be merged
  1080. * together with HEAD. If <code>null</code> is specified as list of commits
  1081. * the file will be deleted
  1082. *
  1083. * @param heads
  1084. * a list of {@link Commit}s which IDs should be written to
  1085. * $GIT_DIR/MERGE_HEAD or <code>null</code> to delete the file
  1086. * @throws IOException
  1087. */
  1088. public void writeMergeHeads(List<ObjectId> heads) throws IOException {
  1089. File mergeHeadFile = new File(gitDir, Constants.MERGE_HEAD);
  1090. if (heads != null) {
  1091. BufferedOutputStream bos = new BufferedOutputStream(
  1092. new FileOutputStream(mergeHeadFile));
  1093. try {
  1094. for (ObjectId id : heads) {
  1095. id.copyTo(bos);
  1096. bos.write('\n');
  1097. }
  1098. } finally {
  1099. bos.close();
  1100. }
  1101. } else {
  1102. mergeHeadFile.delete();
  1103. }
  1104. }
  1105. }