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

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