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

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