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

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