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

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