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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441
  1. /*
  2. * Copyright (C) 2007, Dave Watson <dwatson@mimvista.com>
  3. * Copyright (C) 2008-2010, Google Inc.
  4. * Copyright (C) 2006-2010, Robin Rosenberg <robin.rosenberg@dewire.com>
  5. * Copyright (C) 2006-2008, Shawn O. Pearce <spearce@spearce.org>
  6. * and other copyright owners as documented in the project's IP log.
  7. *
  8. * This program and the accompanying materials are made available
  9. * under the terms of the Eclipse Distribution License v1.0 which
  10. * accompanies this distribution, is reproduced below, and is
  11. * available at http://www.eclipse.org/org/documents/edl-v10.php
  12. *
  13. * All rights reserved.
  14. *
  15. * Redistribution and use in source and binary forms, with or
  16. * without modification, are permitted provided that the following
  17. * conditions are met:
  18. *
  19. * - Redistributions of source code must retain the above copyright
  20. * notice, this list of conditions and the following disclaimer.
  21. *
  22. * - Redistributions in binary form must reproduce the above
  23. * copyright notice, this list of conditions and the following
  24. * disclaimer in the documentation and/or other materials provided
  25. * with the distribution.
  26. *
  27. * - Neither the name of the Eclipse Foundation, Inc. nor the
  28. * names of its contributors may be used to endorse or promote
  29. * products derived from this software without specific prior
  30. * written permission.
  31. *
  32. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  33. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  34. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  35. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  36. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  37. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  38. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  39. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  40. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  41. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  42. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  43. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  44. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  45. */
  46. package org.eclipse.jgit.lib;
  47. import java.io.File;
  48. import java.io.FileNotFoundException;
  49. import java.io.IOException;
  50. import java.text.MessageFormat;
  51. import java.util.ArrayList;
  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.Vector;
  61. import java.util.concurrent.atomic.AtomicInteger;
  62. import org.eclipse.jgit.JGitText;
  63. import org.eclipse.jgit.dircache.DirCache;
  64. import org.eclipse.jgit.errors.ConfigInvalidException;
  65. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  66. import org.eclipse.jgit.errors.RevisionSyntaxException;
  67. import org.eclipse.jgit.util.FS;
  68. import org.eclipse.jgit.util.IO;
  69. import org.eclipse.jgit.util.RawParseUtils;
  70. import org.eclipse.jgit.util.SystemReader;
  71. /**
  72. * Represents a Git repository. A repository holds all objects and refs used for
  73. * managing source code (could by any type of file, but source code is what
  74. * SCM's are typically used for).
  75. *
  76. * In Git terms all data is stored in GIT_DIR, typically a directory called
  77. * .git. A work tree is maintained unless the repository is a bare repository.
  78. * Typically the .git directory is located at the root of the work dir.
  79. *
  80. * <ul>
  81. * <li>GIT_DIR
  82. * <ul>
  83. * <li>objects/ - objects</li>
  84. * <li>refs/ - tags and heads</li>
  85. * <li>config - configuration</li>
  86. * <li>info/ - more configurations</li>
  87. * </ul>
  88. * </li>
  89. * </ul>
  90. * <p>
  91. * This class is thread-safe.
  92. * <p>
  93. * This implementation only handles a subtly undocumented subset of git features.
  94. *
  95. */
  96. public class Repository {
  97. private final AtomicInteger useCnt = new AtomicInteger(1);
  98. private final File gitDir;
  99. private final FS fs;
  100. private final FileBasedConfig userConfig;
  101. private final RepositoryConfig config;
  102. private final RefDatabase refs;
  103. private final ObjectDirectory objectDatabase;
  104. private GitIndex index;
  105. private final List<RepositoryListener> listeners = new Vector<RepositoryListener>(); // thread safe
  106. static private final List<RepositoryListener> allListeners = new Vector<RepositoryListener>(); // thread safe
  107. private File workDir;
  108. private File indexFile;
  109. /**
  110. * Construct a representation of a Git repository.
  111. *
  112. * The work tree, object directory, alternate object directories and index
  113. * file locations are deduced from the given git directory and the default
  114. * rules.
  115. *
  116. * @param d
  117. * GIT_DIR (the location of the repository metadata).
  118. * @throws IOException
  119. * the repository appears to already exist but cannot be
  120. * accessed.
  121. */
  122. public Repository(final File d) throws IOException {
  123. this(d, null, null, null, null); // go figure it out
  124. }
  125. /**
  126. * Construct a representation of a Git repository.
  127. *
  128. * The work tree, object directory, alternate object directories and index
  129. * file locations are deduced from the given git directory and the default
  130. * rules.
  131. *
  132. * @param d
  133. * GIT_DIR (the location of the repository metadata). May be
  134. * null work workTree is set
  135. * @param workTree
  136. * GIT_WORK_TREE (the root of the checkout). May be null for
  137. * default value.
  138. * @throws IOException
  139. * the repository appears to already exist but cannot be
  140. * accessed.
  141. */
  142. public Repository(final File d, final File workTree) throws IOException {
  143. this(d, workTree, null, null, null); // go figure it out
  144. }
  145. /**
  146. * Construct a representation of a Git repository using the given parameters
  147. * possibly overriding default conventions.
  148. *
  149. * @param d
  150. * GIT_DIR (the location of the repository metadata). May be null
  151. * for default value in which case it depends on GIT_WORK_TREE.
  152. * @param workTree
  153. * GIT_WORK_TREE (the root of the checkout). May be null for
  154. * default value if GIT_DIR is
  155. * @param objectDir
  156. * GIT_OBJECT_DIRECTORY (where objects and are stored). May be
  157. * null for default value. Relative names ares resolved against
  158. * GIT_WORK_TREE
  159. * @param alternateObjectDir
  160. * GIT_ALTERNATE_OBJECT_DIRECTORIES (where more objects are read
  161. * from). May be null for default value. Relative names ares
  162. * resolved against GIT_WORK_TREE
  163. * @param indexFile
  164. * GIT_INDEX_FILE (the location of the index file). May be null
  165. * for default value. Relative names ares resolved against
  166. * GIT_WORK_TREE.
  167. * @throws IOException
  168. * the repository appears to already exist but cannot be
  169. * accessed.
  170. */
  171. public Repository(final File d, final File workTree, final File objectDir,
  172. final File[] alternateObjectDir, final File indexFile) throws IOException {
  173. this(d, workTree, objectDir, alternateObjectDir, indexFile, FS.DETECTED);
  174. }
  175. /**
  176. * Construct a representation of a Git repository using the given parameters
  177. * possibly overriding default conventions.
  178. *
  179. * @param d
  180. * GIT_DIR (the location of the repository metadata). May be null
  181. * for default value in which case it depends on GIT_WORK_TREE.
  182. * @param workTree
  183. * GIT_WORK_TREE (the root of the checkout). May be null for
  184. * default value if GIT_DIR is
  185. * @param objectDir
  186. * GIT_OBJECT_DIRECTORY (where objects and are stored). May be
  187. * null for default value. Relative names ares resolved against
  188. * GIT_WORK_TREE
  189. * @param alternateObjectDir
  190. * GIT_ALTERNATE_OBJECT_DIRECTORIES (where more objects are read
  191. * from). May be null for default value. Relative names ares
  192. * resolved against GIT_WORK_TREE
  193. * @param indexFile
  194. * GIT_INDEX_FILE (the location of the index file). May be null
  195. * for default value. Relative names ares resolved against
  196. * GIT_WORK_TREE.
  197. * @param fs
  198. * the file system abstraction which will be necessary to
  199. * perform certain file system operations.
  200. * @throws IOException
  201. * the repository appears to already exist but cannot be
  202. * accessed.
  203. */
  204. public Repository(final File d, final File workTree, final File objectDir,
  205. final File[] alternateObjectDir, final File indexFile,
  206. FS fs) throws IOException {
  207. if (workTree != null) {
  208. workDir = workTree;
  209. if (d == null)
  210. gitDir = new File(workTree, Constants.DOT_GIT);
  211. else
  212. gitDir = d;
  213. } else {
  214. if (d != null)
  215. gitDir = d;
  216. else
  217. throw new IllegalArgumentException(JGitText.get().eitherGIT_DIRorGIT_WORK_TREEmustBePassed);
  218. }
  219. this.fs = fs;
  220. userConfig = SystemReader.getInstance().openUserConfig(fs);
  221. config = new RepositoryConfig(userConfig, fs.resolve(gitDir, "config"));
  222. loadUserConfig();
  223. loadConfig();
  224. if (workDir == null) {
  225. String workTreeConfig = getConfig().getString("core", null, "worktree");
  226. if (workTreeConfig != null) {
  227. workDir = fs.resolve(d, workTreeConfig);
  228. } else {
  229. workDir = gitDir.getParentFile();
  230. }
  231. }
  232. refs = new RefDirectory(this);
  233. if (objectDir != null)
  234. objectDatabase = new ObjectDirectory(fs.resolve(objectDir, ""),
  235. alternateObjectDir, fs);
  236. else
  237. objectDatabase = new ObjectDirectory(fs.resolve(gitDir, "objects"),
  238. alternateObjectDir, fs);
  239. if (indexFile != null)
  240. this.indexFile = indexFile;
  241. else
  242. this.indexFile = new File(gitDir, "index");
  243. if (objectDatabase.exists()) {
  244. final String repositoryFormatVersion = getConfig().getString(
  245. "core", null, "repositoryFormatVersion");
  246. if (!"0".equals(repositoryFormatVersion)) {
  247. throw new IOException(MessageFormat.format(
  248. JGitText.get().unknownRepositoryFormat2, repositoryFormatVersion));
  249. }
  250. }
  251. }
  252. private void loadUserConfig() throws IOException {
  253. try {
  254. userConfig.load();
  255. } catch (ConfigInvalidException e1) {
  256. IOException e2 = new IOException(MessageFormat.format(
  257. JGitText.get().userConfigFileInvalid, userConfig.getFile().getAbsolutePath(), e1));
  258. e2.initCause(e1);
  259. throw e2;
  260. }
  261. }
  262. private void loadConfig() throws IOException {
  263. try {
  264. config.load();
  265. } catch (ConfigInvalidException e1) {
  266. IOException e2 = new IOException(JGitText.get().unknownRepositoryFormat);
  267. e2.initCause(e1);
  268. throw e2;
  269. }
  270. }
  271. /**
  272. * Create a new Git repository initializing the necessary files and
  273. * directories. Repository with working tree is created using this method.
  274. *
  275. * @throws IOException
  276. * @see #create(boolean)
  277. */
  278. public synchronized void create() throws IOException {
  279. create(false);
  280. }
  281. /**
  282. * Create a new Git repository initializing the necessary files and
  283. * directories.
  284. *
  285. * @param bare
  286. * if true, a bare repository is created.
  287. *
  288. * @throws IOException
  289. * in case of IO problem
  290. */
  291. public void create(boolean bare) throws IOException {
  292. final RepositoryConfig cfg = getConfig();
  293. if (cfg.getFile().exists()) {
  294. throw new IllegalStateException(MessageFormat.format(JGitText.get().repositoryAlreadyExists, gitDir));
  295. }
  296. gitDir.mkdirs();
  297. refs.create();
  298. objectDatabase.create();
  299. new File(gitDir, "branches").mkdir();
  300. RefUpdate head = updateRef(Constants.HEAD);
  301. head.disableRefLog();
  302. head.link(Constants.R_HEADS + Constants.MASTER);
  303. cfg.setInt("core", null, "repositoryformatversion", 0);
  304. cfg.setBoolean("core", null, "filemode", true);
  305. if (bare)
  306. cfg.setBoolean("core", null, "bare", true);
  307. cfg.setBoolean("core", null, "logallrefupdates", !bare);
  308. cfg.setBoolean("core", null, "autocrlf", false);
  309. cfg.save();
  310. }
  311. /**
  312. * @return GIT_DIR
  313. */
  314. public File getDirectory() {
  315. return gitDir;
  316. }
  317. /**
  318. * @return the directory containing the objects owned by this repository.
  319. */
  320. public File getObjectsDirectory() {
  321. return objectDatabase.getDirectory();
  322. }
  323. /**
  324. * @return the object database which stores this repository's data.
  325. */
  326. public ObjectDatabase getObjectDatabase() {
  327. return objectDatabase;
  328. }
  329. /** @return the reference database which stores the reference namespace. */
  330. public RefDatabase getRefDatabase() {
  331. return refs;
  332. }
  333. /**
  334. * @return the configuration of this repository
  335. */
  336. public RepositoryConfig getConfig() {
  337. if (userConfig.isOutdated()) {
  338. try {
  339. loadUserConfig();
  340. } catch (IOException e) {
  341. throw new RuntimeException(e);
  342. }
  343. }
  344. if (config.isOutdated()) {
  345. try {
  346. loadConfig();
  347. } catch (IOException e) {
  348. throw new RuntimeException(e);
  349. }
  350. }
  351. return config;
  352. }
  353. /**
  354. * @return the used file system abstraction
  355. */
  356. public FS getFS() {
  357. return fs;
  358. }
  359. /**
  360. * Construct a filename where the loose object having a specified SHA-1
  361. * should be stored. If the object is stored in a shared repository the path
  362. * to the alternative repo will be returned. If the object is not yet store
  363. * a usable path in this repo will be returned. It is assumed that callers
  364. * will look for objects in a pack first.
  365. *
  366. * @param objectId
  367. * @return suggested file name
  368. */
  369. public File toFile(final AnyObjectId objectId) {
  370. return objectDatabase.fileFor(objectId);
  371. }
  372. /**
  373. * @param objectId
  374. * @return true if the specified object is stored in this repo or any of the
  375. * known shared repositories.
  376. */
  377. public boolean hasObject(final AnyObjectId objectId) {
  378. return objectDatabase.hasObject(objectId);
  379. }
  380. /**
  381. * @param id
  382. * SHA-1 of an object.
  383. *
  384. * @return a {@link ObjectLoader} for accessing the data of the named
  385. * object, or null if the object does not exist.
  386. * @throws IOException
  387. */
  388. public ObjectLoader openObject(final AnyObjectId id)
  389. throws IOException {
  390. final WindowCursor wc = new WindowCursor();
  391. try {
  392. return openObject(wc, id);
  393. } finally {
  394. wc.release();
  395. }
  396. }
  397. /**
  398. * @param curs
  399. * temporary working space associated with the calling thread.
  400. * @param id
  401. * SHA-1 of an object.
  402. *
  403. * @return a {@link ObjectLoader} for accessing the data of the named
  404. * object, or null if the object does not exist.
  405. * @throws IOException
  406. */
  407. public ObjectLoader openObject(final WindowCursor curs, final AnyObjectId id)
  408. throws IOException {
  409. return objectDatabase.openObject(curs, id);
  410. }
  411. /**
  412. * Open object in all packs containing specified object.
  413. *
  414. * @param objectId
  415. * id of object to search for
  416. * @param curs
  417. * temporary working space associated with the calling thread.
  418. * @return collection of loaders for this object, from all packs containing
  419. * this object
  420. * @throws IOException
  421. */
  422. public Collection<PackedObjectLoader> openObjectInAllPacks(
  423. final AnyObjectId objectId, final WindowCursor curs)
  424. throws IOException {
  425. Collection<PackedObjectLoader> result = new LinkedList<PackedObjectLoader>();
  426. openObjectInAllPacks(objectId, result, curs);
  427. return result;
  428. }
  429. /**
  430. * Open object in all packs containing specified object.
  431. *
  432. * @param objectId
  433. * id of object to search for
  434. * @param resultLoaders
  435. * result collection of loaders for this object, filled with
  436. * loaders from all packs containing specified object
  437. * @param curs
  438. * temporary working space associated with the calling thread.
  439. * @throws IOException
  440. */
  441. void openObjectInAllPacks(final AnyObjectId objectId,
  442. final Collection<PackedObjectLoader> resultLoaders,
  443. final WindowCursor curs) throws IOException {
  444. objectDatabase.openObjectInAllPacks(resultLoaders, curs, objectId);
  445. }
  446. /**
  447. * @param id
  448. * SHA'1 of a blob
  449. * @return an {@link ObjectLoader} for accessing the data of a named blob
  450. * @throws IOException
  451. */
  452. public ObjectLoader openBlob(final ObjectId id) throws IOException {
  453. return openObject(id);
  454. }
  455. /**
  456. * @param id
  457. * SHA'1 of a tree
  458. * @return an {@link ObjectLoader} for accessing the data of a named tree
  459. * @throws IOException
  460. */
  461. public ObjectLoader openTree(final ObjectId id) throws IOException {
  462. return openObject(id);
  463. }
  464. /**
  465. * Access a Commit object using a symbolic reference. This reference may
  466. * be a SHA-1 or ref in combination with a number of symbols translating
  467. * from one ref or SHA1-1 to another, such as HEAD^ etc.
  468. *
  469. * @param revstr a reference to a git commit object
  470. * @return a Commit named by the specified string
  471. * @throws IOException for I/O error or unexpected object type.
  472. *
  473. * @see #resolve(String)
  474. */
  475. public Commit mapCommit(final String revstr) throws IOException {
  476. final ObjectId id = resolve(revstr);
  477. return id != null ? mapCommit(id) : null;
  478. }
  479. /**
  480. * Access any type of Git object by id and
  481. *
  482. * @param id
  483. * SHA-1 of object to read
  484. * @param refName optional, only relevant for simple tags
  485. * @return The Git object if found or null
  486. * @throws IOException
  487. */
  488. public Object mapObject(final ObjectId id, final String refName) throws IOException {
  489. final ObjectLoader or = openObject(id);
  490. if (or == null)
  491. return null;
  492. final byte[] raw = or.getBytes();
  493. switch (or.getType()) {
  494. case Constants.OBJ_TREE:
  495. return makeTree(id, raw);
  496. case Constants.OBJ_COMMIT:
  497. return makeCommit(id, raw);
  498. case Constants.OBJ_TAG:
  499. return makeTag(id, refName, raw);
  500. case Constants.OBJ_BLOB:
  501. return raw;
  502. default:
  503. throw new IncorrectObjectTypeException(id,
  504. JGitText.get().incorrectObjectType_COMMITnorTREEnorBLOBnorTAG);
  505. }
  506. }
  507. /**
  508. * Access a Commit by SHA'1 id.
  509. * @param id
  510. * @return Commit or null
  511. * @throws IOException for I/O error or unexpected object type.
  512. */
  513. public Commit mapCommit(final ObjectId id) throws IOException {
  514. final ObjectLoader or = openObject(id);
  515. if (or == null)
  516. return null;
  517. final byte[] raw = or.getBytes();
  518. if (Constants.OBJ_COMMIT == or.getType())
  519. return new Commit(this, id, raw);
  520. throw new IncorrectObjectTypeException(id, Constants.TYPE_COMMIT);
  521. }
  522. private Commit makeCommit(final ObjectId id, final byte[] raw) {
  523. Commit ret = new Commit(this, id, raw);
  524. return ret;
  525. }
  526. /**
  527. * Access a Tree object using a symbolic reference. This reference may
  528. * be a SHA-1 or ref in combination with a number of symbols translating
  529. * from one ref or SHA1-1 to another, such as HEAD^{tree} etc.
  530. *
  531. * @param revstr a reference to a git commit object
  532. * @return a Tree named by the specified string
  533. * @throws IOException
  534. *
  535. * @see #resolve(String)
  536. */
  537. public Tree mapTree(final String revstr) throws IOException {
  538. final ObjectId id = resolve(revstr);
  539. return id != null ? mapTree(id) : null;
  540. }
  541. /**
  542. * Access a Tree by SHA'1 id.
  543. * @param id
  544. * @return Tree or null
  545. * @throws IOException for I/O error or unexpected object type.
  546. */
  547. public Tree mapTree(final ObjectId id) throws IOException {
  548. final ObjectLoader or = openObject(id);
  549. if (or == null)
  550. return null;
  551. final byte[] raw = or.getBytes();
  552. switch (or.getType()) {
  553. case Constants.OBJ_TREE:
  554. return new Tree(this, id, raw);
  555. case Constants.OBJ_COMMIT:
  556. return mapTree(ObjectId.fromString(raw, 5));
  557. default:
  558. throw new IncorrectObjectTypeException(id, Constants.TYPE_TREE);
  559. }
  560. }
  561. private Tree makeTree(final ObjectId id, final byte[] raw) throws IOException {
  562. Tree ret = new Tree(this, id, raw);
  563. return ret;
  564. }
  565. private Tag makeTag(final ObjectId id, final String refName, final byte[] raw) {
  566. Tag ret = new Tag(this, id, refName, raw);
  567. return ret;
  568. }
  569. /**
  570. * Access a tag by symbolic name.
  571. *
  572. * @param revstr
  573. * @return a Tag or null
  574. * @throws IOException on I/O error or unexpected type
  575. */
  576. public Tag mapTag(String revstr) throws IOException {
  577. final ObjectId id = resolve(revstr);
  578. return id != null ? mapTag(revstr, id) : null;
  579. }
  580. /**
  581. * Access a Tag by SHA'1 id
  582. * @param refName
  583. * @param id
  584. * @return Commit or null
  585. * @throws IOException for I/O error or unexpected object type.
  586. */
  587. public Tag mapTag(final String refName, final ObjectId id) throws IOException {
  588. final ObjectLoader or = openObject(id);
  589. if (or == null)
  590. return null;
  591. final byte[] raw = or.getBytes();
  592. if (Constants.OBJ_TAG == or.getType())
  593. return new Tag(this, id, refName, raw);
  594. return new Tag(this, id, refName, null);
  595. }
  596. /**
  597. * Create a command to update, create or delete a ref in this repository.
  598. *
  599. * @param ref
  600. * name of the ref the caller wants to modify.
  601. * @return an update command. The caller must finish populating this command
  602. * and then invoke one of the update methods to actually make a
  603. * change.
  604. * @throws IOException
  605. * a symbolic ref was passed in and could not be resolved back
  606. * to the base ref, as the symbolic ref could not be read.
  607. */
  608. public RefUpdate updateRef(final String ref) throws IOException {
  609. return updateRef(ref, false);
  610. }
  611. /**
  612. * Create a command to update, create or delete a ref in this repository.
  613. *
  614. * @param ref
  615. * name of the ref the caller wants to modify.
  616. * @param detach
  617. * true to create a detached head
  618. * @return an update command. The caller must finish populating this command
  619. * and then invoke one of the update methods to actually make a
  620. * change.
  621. * @throws IOException
  622. * a symbolic ref was passed in and could not be resolved back
  623. * to the base ref, as the symbolic ref could not be read.
  624. */
  625. public RefUpdate updateRef(final String ref, final boolean detach) throws IOException {
  626. return refs.newUpdate(ref, detach);
  627. }
  628. /**
  629. * Create a command to rename a ref in this repository
  630. *
  631. * @param fromRef
  632. * name of ref to rename from
  633. * @param toRef
  634. * name of ref to rename to
  635. * @return an update command that knows how to rename a branch to another.
  636. * @throws IOException
  637. * the rename could not be performed.
  638. *
  639. */
  640. public RefRename renameRef(final String fromRef, final String toRef) throws IOException {
  641. return refs.newRename(fromRef, toRef);
  642. }
  643. /**
  644. * Parse a git revision string and return an object id.
  645. *
  646. * Currently supported is combinations of these.
  647. * <ul>
  648. * <li>SHA-1 - a SHA-1</li>
  649. * <li>refs/... - a ref name</li>
  650. * <li>ref^n - nth parent reference</li>
  651. * <li>ref~n - distance via parent reference</li>
  652. * <li>ref@{n} - nth version of ref</li>
  653. * <li>ref^{tree} - tree references by ref</li>
  654. * <li>ref^{commit} - commit references by ref</li>
  655. * </ul>
  656. *
  657. * Not supported is
  658. * <ul>
  659. * <li>timestamps in reflogs, ref@{full or relative timestamp}</li>
  660. * <li>abbreviated SHA-1's</li>
  661. * </ul>
  662. *
  663. * @param revstr A git object references expression
  664. * @return an ObjectId or null if revstr can't be resolved to any ObjectId
  665. * @throws IOException on serious errors
  666. */
  667. public ObjectId resolve(final String revstr) throws IOException {
  668. char[] rev = revstr.toCharArray();
  669. Object ref = null;
  670. ObjectId refId = null;
  671. for (int i = 0; i < rev.length; ++i) {
  672. switch (rev[i]) {
  673. case '^':
  674. if (refId == null) {
  675. String refstr = new String(rev,0,i);
  676. refId = resolveSimple(refstr);
  677. if (refId == null)
  678. return null;
  679. }
  680. if (i + 1 < rev.length) {
  681. switch (rev[i + 1]) {
  682. case '0':
  683. case '1':
  684. case '2':
  685. case '3':
  686. case '4':
  687. case '5':
  688. case '6':
  689. case '7':
  690. case '8':
  691. case '9':
  692. int j;
  693. ref = mapObject(refId, null);
  694. while (ref instanceof Tag) {
  695. Tag tag = (Tag)ref;
  696. refId = tag.getObjId();
  697. ref = mapObject(refId, null);
  698. }
  699. if (!(ref instanceof Commit))
  700. throw new IncorrectObjectTypeException(refId, Constants.TYPE_COMMIT);
  701. for (j=i+1; j<rev.length; ++j) {
  702. if (!Character.isDigit(rev[j]))
  703. break;
  704. }
  705. String parentnum = new String(rev, i+1, j-i-1);
  706. int pnum;
  707. try {
  708. pnum = Integer.parseInt(parentnum);
  709. } catch (NumberFormatException e) {
  710. throw new RevisionSyntaxException(
  711. JGitText.get().invalidCommitParentNumber,
  712. revstr);
  713. }
  714. if (pnum != 0) {
  715. final ObjectId parents[] = ((Commit) ref)
  716. .getParentIds();
  717. if (pnum > parents.length)
  718. refId = null;
  719. else
  720. refId = parents[pnum - 1];
  721. }
  722. i = j - 1;
  723. break;
  724. case '{':
  725. int k;
  726. String item = null;
  727. for (k=i+2; k<rev.length; ++k) {
  728. if (rev[k] == '}') {
  729. item = new String(rev, i+2, k-i-2);
  730. break;
  731. }
  732. }
  733. i = k;
  734. if (item != null)
  735. if (item.equals("tree")) {
  736. ref = mapObject(refId, null);
  737. while (ref instanceof Tag) {
  738. Tag t = (Tag)ref;
  739. refId = t.getObjId();
  740. ref = mapObject(refId, null);
  741. }
  742. if (ref instanceof Treeish)
  743. refId = ((Treeish)ref).getTreeId();
  744. else
  745. throw new IncorrectObjectTypeException(refId, Constants.TYPE_TREE);
  746. }
  747. else if (item.equals("commit")) {
  748. ref = mapObject(refId, null);
  749. while (ref instanceof Tag) {
  750. Tag t = (Tag)ref;
  751. refId = t.getObjId();
  752. ref = mapObject(refId, null);
  753. }
  754. if (!(ref instanceof Commit))
  755. throw new IncorrectObjectTypeException(refId, Constants.TYPE_COMMIT);
  756. }
  757. else if (item.equals("blob")) {
  758. ref = mapObject(refId, null);
  759. while (ref instanceof Tag) {
  760. Tag t = (Tag)ref;
  761. refId = t.getObjId();
  762. ref = mapObject(refId, null);
  763. }
  764. if (!(ref instanceof byte[]))
  765. throw new IncorrectObjectTypeException(refId, Constants.TYPE_BLOB);
  766. }
  767. else if (item.equals("")) {
  768. ref = mapObject(refId, null);
  769. while (ref instanceof Tag) {
  770. Tag t = (Tag)ref;
  771. refId = t.getObjId();
  772. ref = mapObject(refId, null);
  773. }
  774. }
  775. else
  776. throw new RevisionSyntaxException(revstr);
  777. else
  778. throw new RevisionSyntaxException(revstr);
  779. break;
  780. default:
  781. ref = mapObject(refId, null);
  782. if (ref instanceof Commit) {
  783. final ObjectId parents[] = ((Commit) ref)
  784. .getParentIds();
  785. if (parents.length == 0)
  786. refId = null;
  787. else
  788. refId = parents[0];
  789. } else
  790. throw new IncorrectObjectTypeException(refId, Constants.TYPE_COMMIT);
  791. }
  792. } else {
  793. ref = mapObject(refId, null);
  794. while (ref instanceof Tag) {
  795. Tag tag = (Tag)ref;
  796. refId = tag.getObjId();
  797. ref = mapObject(refId, null);
  798. }
  799. if (ref instanceof Commit) {
  800. final ObjectId parents[] = ((Commit) ref)
  801. .getParentIds();
  802. if (parents.length == 0)
  803. refId = null;
  804. else
  805. refId = parents[0];
  806. } else
  807. throw new IncorrectObjectTypeException(refId, Constants.TYPE_COMMIT);
  808. }
  809. break;
  810. case '~':
  811. if (ref == null) {
  812. String refstr = new String(rev,0,i);
  813. refId = resolveSimple(refstr);
  814. if (refId == null)
  815. return null;
  816. ref = mapObject(refId, null);
  817. }
  818. while (ref instanceof Tag) {
  819. Tag tag = (Tag)ref;
  820. refId = tag.getObjId();
  821. ref = mapObject(refId, null);
  822. }
  823. if (!(ref instanceof Commit))
  824. throw new IncorrectObjectTypeException(refId, Constants.TYPE_COMMIT);
  825. int l;
  826. for (l = i + 1; l < rev.length; ++l) {
  827. if (!Character.isDigit(rev[l]))
  828. break;
  829. }
  830. String distnum = new String(rev, i+1, l-i-1);
  831. int dist;
  832. try {
  833. dist = Integer.parseInt(distnum);
  834. } catch (NumberFormatException e) {
  835. throw new RevisionSyntaxException(
  836. JGitText.get().invalidAncestryLength, revstr);
  837. }
  838. while (dist > 0) {
  839. final ObjectId[] parents = ((Commit) ref).getParentIds();
  840. if (parents.length == 0) {
  841. refId = null;
  842. break;
  843. }
  844. refId = parents[0];
  845. ref = mapCommit(refId);
  846. --dist;
  847. }
  848. i = l - 1;
  849. break;
  850. case '@':
  851. int m;
  852. String time = null;
  853. for (m=i+2; m<rev.length; ++m) {
  854. if (rev[m] == '}') {
  855. time = new String(rev, i+2, m-i-2);
  856. break;
  857. }
  858. }
  859. if (time != null)
  860. throw new RevisionSyntaxException(JGitText.get().reflogsNotYetSupportedByRevisionParser, revstr);
  861. i = m - 1;
  862. break;
  863. default:
  864. if (refId != null)
  865. throw new RevisionSyntaxException(revstr);
  866. }
  867. }
  868. if (refId == null)
  869. refId = resolveSimple(revstr);
  870. return refId;
  871. }
  872. private ObjectId resolveSimple(final String revstr) throws IOException {
  873. if (ObjectId.isId(revstr))
  874. return ObjectId.fromString(revstr);
  875. final Ref r = refs.getRef(revstr);
  876. return r != null ? r.getObjectId() : null;
  877. }
  878. /** Increment the use counter by one, requiring a matched {@link #close()}. */
  879. public void incrementOpen() {
  880. useCnt.incrementAndGet();
  881. }
  882. /**
  883. * Close all resources used by this repository
  884. */
  885. public void close() {
  886. if (useCnt.decrementAndGet() == 0) {
  887. objectDatabase.close();
  888. refs.close();
  889. }
  890. }
  891. /**
  892. * Add a single existing pack to the list of available pack files.
  893. *
  894. * @param pack
  895. * path of the pack file to open.
  896. * @param idx
  897. * path of the corresponding index file.
  898. * @throws IOException
  899. * index file could not be opened, read, or is not recognized as
  900. * a Git pack file index.
  901. */
  902. public void openPack(final File pack, final File idx) throws IOException {
  903. objectDatabase.openPack(pack, idx);
  904. }
  905. public String toString() {
  906. return "Repository[" + getDirectory() + "]";
  907. }
  908. /**
  909. * Get the name of the reference that {@code HEAD} points to.
  910. * <p>
  911. * This is essentially the same as doing:
  912. *
  913. * <pre>
  914. * return getRef(Constants.HEAD).getTarget().getName()
  915. * </pre>
  916. *
  917. * Except when HEAD is detached, in which case this method returns the
  918. * current ObjectId in hexadecimal string format.
  919. *
  920. * @return name of current branch (for example {@code refs/heads/master}) or
  921. * an ObjectId in hex format if the current branch is detached.
  922. * @throws IOException
  923. */
  924. public String getFullBranch() throws IOException {
  925. Ref head = getRef(Constants.HEAD);
  926. if (head == null)
  927. return null;
  928. if (head.isSymbolic())
  929. return head.getTarget().getName();
  930. if (head.getObjectId() != null)
  931. return head.getObjectId().name();
  932. return null;
  933. }
  934. /**
  935. * Get the short name of the current branch that {@code HEAD} points to.
  936. * <p>
  937. * This is essentially the same as {@link #getFullBranch()}, except the
  938. * leading prefix {@code refs/heads/} is removed from the reference before
  939. * it is returned to the caller.
  940. *
  941. * @return name of current branch (for example {@code master}), or an
  942. * ObjectId in hex format if the current branch is detached.
  943. * @throws IOException
  944. */
  945. public String getBranch() throws IOException {
  946. String name = getFullBranch();
  947. if (name != null)
  948. return shortenRefName(name);
  949. return name;
  950. }
  951. /**
  952. * Get a ref by name.
  953. *
  954. * @param name
  955. * the name of the ref to lookup. May be a short-hand form, e.g.
  956. * "master" which is is automatically expanded to
  957. * "refs/heads/master" if "refs/heads/master" already exists.
  958. * @return the Ref with the given name, or null if it does not exist
  959. * @throws IOException
  960. */
  961. public Ref getRef(final String name) throws IOException {
  962. return refs.getRef(name);
  963. }
  964. /**
  965. * @return mutable map of all known refs (heads, tags, remotes).
  966. */
  967. public Map<String, Ref> getAllRefs() {
  968. try {
  969. return refs.getRefs(RefDatabase.ALL);
  970. } catch (IOException e) {
  971. return new HashMap<String, Ref>();
  972. }
  973. }
  974. /**
  975. * @return mutable map of all tags; key is short tag name ("v1.0") and value
  976. * of the entry contains the ref with the full tag name
  977. * ("refs/tags/v1.0").
  978. */
  979. public Map<String, Ref> getTags() {
  980. try {
  981. return refs.getRefs(Constants.R_TAGS);
  982. } catch (IOException e) {
  983. return new HashMap<String, Ref>();
  984. }
  985. }
  986. /**
  987. * Peel a possibly unpeeled reference to an annotated tag.
  988. * <p>
  989. * If the ref cannot be peeled (as it does not refer to an annotated tag)
  990. * the peeled id stays null, but {@link Ref#isPeeled()} will be true.
  991. *
  992. * @param ref
  993. * The ref to peel
  994. * @return <code>ref</code> if <code>ref.isPeeled()</code> is true; else a
  995. * new Ref object representing the same data as Ref, but isPeeled()
  996. * will be true and getPeeledObjectId will contain the peeled object
  997. * (or null).
  998. */
  999. public Ref peel(final Ref ref) {
  1000. try {
  1001. return refs.peel(ref);
  1002. } catch (IOException e) {
  1003. // Historical accident; if the reference cannot be peeled due
  1004. // to some sort of repository access problem we claim that the
  1005. // same as if the reference was not an annotated tag.
  1006. return ref;
  1007. }
  1008. }
  1009. /**
  1010. * @return a map with all objects referenced by a peeled ref.
  1011. */
  1012. public Map<AnyObjectId, Set<Ref>> getAllRefsByPeeledObjectId() {
  1013. Map<String, Ref> allRefs = getAllRefs();
  1014. Map<AnyObjectId, Set<Ref>> ret = new HashMap<AnyObjectId, Set<Ref>>(allRefs.size());
  1015. for (Ref ref : allRefs.values()) {
  1016. ref = peel(ref);
  1017. AnyObjectId target = ref.getPeeledObjectId();
  1018. if (target == null)
  1019. target = ref.getObjectId();
  1020. // We assume most Sets here are singletons
  1021. Set<Ref> oset = ret.put(target, Collections.singleton(ref));
  1022. if (oset != null) {
  1023. // that was not the case (rare)
  1024. if (oset.size() == 1) {
  1025. // Was a read-only singleton, we must copy to a new Set
  1026. oset = new HashSet<Ref>(oset);
  1027. }
  1028. ret.put(target, oset);
  1029. oset.add(ref);
  1030. }
  1031. }
  1032. return ret;
  1033. }
  1034. /**
  1035. * @return a representation of the index associated with this repo
  1036. * @throws IOException
  1037. */
  1038. public GitIndex getIndex() throws IOException {
  1039. if (index == null) {
  1040. index = new GitIndex(this);
  1041. index.read();
  1042. } else {
  1043. index.rereadIfNecessary();
  1044. }
  1045. return index;
  1046. }
  1047. /**
  1048. * @return the index file location
  1049. */
  1050. public File getIndexFile() {
  1051. return indexFile;
  1052. }
  1053. static byte[] gitInternalSlash(byte[] bytes) {
  1054. if (File.separatorChar == '/')
  1055. return bytes;
  1056. for (int i=0; i<bytes.length; ++i)
  1057. if (bytes[i] == File.separatorChar)
  1058. bytes[i] = '/';
  1059. return bytes;
  1060. }
  1061. /**
  1062. * @return an important state
  1063. */
  1064. public RepositoryState getRepositoryState() {
  1065. // Pre Git-1.6 logic
  1066. if (new File(getWorkDir(), ".dotest").exists())
  1067. return RepositoryState.REBASING;
  1068. if (new File(gitDir,".dotest-merge").exists())
  1069. return RepositoryState.REBASING_INTERACTIVE;
  1070. // From 1.6 onwards
  1071. if (new File(getDirectory(),"rebase-apply/rebasing").exists())
  1072. return RepositoryState.REBASING_REBASING;
  1073. if (new File(getDirectory(),"rebase-apply/applying").exists())
  1074. return RepositoryState.APPLY;
  1075. if (new File(getDirectory(),"rebase-apply").exists())
  1076. return RepositoryState.REBASING;
  1077. if (new File(getDirectory(),"rebase-merge/interactive").exists())
  1078. return RepositoryState.REBASING_INTERACTIVE;
  1079. if (new File(getDirectory(),"rebase-merge").exists())
  1080. return RepositoryState.REBASING_MERGE;
  1081. // Both versions
  1082. if (new File(gitDir, "MERGE_HEAD").exists()) {
  1083. // we are merging - now check whether we have unmerged paths
  1084. try {
  1085. if (!DirCache.read(this).hasUnmergedPaths()) {
  1086. // no unmerged paths -> return the MERGING_RESOLVED state
  1087. return RepositoryState.MERGING_RESOLVED;
  1088. }
  1089. } catch (IOException e) {
  1090. // Can't decide whether unmerged paths exists. Return
  1091. // MERGING state to be on the safe side (in state MERGING
  1092. // you are not allow to do anything)
  1093. e.printStackTrace();
  1094. }
  1095. return RepositoryState.MERGING;
  1096. }
  1097. if (new File(gitDir,"BISECT_LOG").exists())
  1098. return RepositoryState.BISECTING;
  1099. return RepositoryState.SAFE;
  1100. }
  1101. /**
  1102. * Check validity of a ref name. It must not contain character that has
  1103. * a special meaning in a Git object reference expression. Some other
  1104. * dangerous characters are also excluded.
  1105. *
  1106. * For portability reasons '\' is excluded
  1107. *
  1108. * @param refName
  1109. *
  1110. * @return true if refName is a valid ref name
  1111. */
  1112. public static boolean isValidRefName(final String refName) {
  1113. final int len = refName.length();
  1114. if (len == 0)
  1115. return false;
  1116. if (refName.endsWith(LockFile.SUFFIX))
  1117. return false;
  1118. int components = 1;
  1119. char p = '\0';
  1120. for (int i = 0; i < len; i++) {
  1121. final char c = refName.charAt(i);
  1122. if (c <= ' ')
  1123. return false;
  1124. switch (c) {
  1125. case '.':
  1126. switch (p) {
  1127. case '\0': case '/': case '.':
  1128. return false;
  1129. }
  1130. if (i == len -1)
  1131. return false;
  1132. break;
  1133. case '/':
  1134. if (i == 0 || i == len - 1)
  1135. return false;
  1136. components++;
  1137. break;
  1138. case '{':
  1139. if (p == '@')
  1140. return false;
  1141. break;
  1142. case '~': case '^': case ':':
  1143. case '?': case '[': case '*':
  1144. case '\\':
  1145. return false;
  1146. }
  1147. p = c;
  1148. }
  1149. return components > 1;
  1150. }
  1151. /**
  1152. * Strip work dir and return normalized repository path.
  1153. *
  1154. * @param workDir Work dir
  1155. * @param file File whose path shall be stripped of its workdir
  1156. * @return normalized repository relative path or the empty
  1157. * string if the file is not relative to the work directory.
  1158. */
  1159. public static String stripWorkDir(File workDir, File file) {
  1160. final String filePath = file.getPath();
  1161. final String workDirPath = workDir.getPath();
  1162. if (filePath.length() <= workDirPath.length() ||
  1163. filePath.charAt(workDirPath.length()) != File.separatorChar ||
  1164. !filePath.startsWith(workDirPath)) {
  1165. File absWd = workDir.isAbsolute() ? workDir : workDir.getAbsoluteFile();
  1166. File absFile = file.isAbsolute() ? file : file.getAbsoluteFile();
  1167. if (absWd == workDir && absFile == file)
  1168. return "";
  1169. return stripWorkDir(absWd, absFile);
  1170. }
  1171. String relName = filePath.substring(workDirPath.length() + 1);
  1172. if (File.separatorChar != '/')
  1173. relName = relName.replace(File.separatorChar, '/');
  1174. return relName;
  1175. }
  1176. /**
  1177. * @return the workdir file, i.e. where the files are checked out
  1178. */
  1179. public File getWorkDir() {
  1180. return workDir;
  1181. }
  1182. /**
  1183. * Override default workdir
  1184. *
  1185. * @param workTree
  1186. * the work tree directory
  1187. */
  1188. public void setWorkDir(File workTree) {
  1189. this.workDir = workTree;
  1190. }
  1191. /**
  1192. * Register a {@link RepositoryListener} which will be notified
  1193. * when ref changes are detected.
  1194. *
  1195. * @param l
  1196. */
  1197. public void addRepositoryChangedListener(final RepositoryListener l) {
  1198. listeners.add(l);
  1199. }
  1200. /**
  1201. * Remove a registered {@link RepositoryListener}
  1202. * @param l
  1203. */
  1204. public void removeRepositoryChangedListener(final RepositoryListener l) {
  1205. listeners.remove(l);
  1206. }
  1207. /**
  1208. * Register a global {@link RepositoryListener} which will be notified
  1209. * when a ref changes in any repository are detected.
  1210. *
  1211. * @param l
  1212. */
  1213. public static void addAnyRepositoryChangedListener(final RepositoryListener l) {
  1214. allListeners.add(l);
  1215. }
  1216. /**
  1217. * Remove a globally registered {@link RepositoryListener}
  1218. * @param l
  1219. */
  1220. public static void removeAnyRepositoryChangedListener(final RepositoryListener l) {
  1221. allListeners.remove(l);
  1222. }
  1223. void fireRefsChanged() {
  1224. final RefsChangedEvent event = new RefsChangedEvent(this);
  1225. List<RepositoryListener> all;
  1226. synchronized (listeners) {
  1227. all = new ArrayList<RepositoryListener>(listeners);
  1228. }
  1229. synchronized (allListeners) {
  1230. all.addAll(allListeners);
  1231. }
  1232. for (final RepositoryListener l : all) {
  1233. l.refsChanged(event);
  1234. }
  1235. }
  1236. void fireIndexChanged() {
  1237. final IndexChangedEvent event = new IndexChangedEvent(this);
  1238. List<RepositoryListener> all;
  1239. synchronized (listeners) {
  1240. all = new ArrayList<RepositoryListener>(listeners);
  1241. }
  1242. synchronized (allListeners) {
  1243. all.addAll(allListeners);
  1244. }
  1245. for (final RepositoryListener l : all) {
  1246. l.indexChanged(event);
  1247. }
  1248. }
  1249. /**
  1250. * Force a scan for changed refs.
  1251. *
  1252. * @throws IOException
  1253. */
  1254. public void scanForRepoChanges() throws IOException {
  1255. getAllRefs(); // This will look for changes to refs
  1256. getIndex(); // This will detect changes in the index
  1257. }
  1258. /**
  1259. * @param refName
  1260. *
  1261. * @return a more user friendly ref name
  1262. */
  1263. public String shortenRefName(String refName) {
  1264. if (refName.startsWith(Constants.R_HEADS))
  1265. return refName.substring(Constants.R_HEADS.length());
  1266. if (refName.startsWith(Constants.R_TAGS))
  1267. return refName.substring(Constants.R_TAGS.length());
  1268. if (refName.startsWith(Constants.R_REMOTES))
  1269. return refName.substring(Constants.R_REMOTES.length());
  1270. return refName;
  1271. }
  1272. /**
  1273. * @param refName
  1274. * @return a {@link ReflogReader} for the supplied refname, or null if the
  1275. * named ref does not exist.
  1276. * @throws IOException the ref could not be accessed.
  1277. */
  1278. public ReflogReader getReflogReader(String refName) throws IOException {
  1279. Ref ref = getRef(refName);
  1280. if (ref != null)
  1281. return new ReflogReader(this, ref.getName());
  1282. return null;
  1283. }
  1284. /**
  1285. * Return the information stored in the file $GIT_DIR/MERGE_MSG. In this
  1286. * file operations triggering a merge will store a template for the commit
  1287. * message of the merge commit.
  1288. *
  1289. * @return a String containing the content of the MERGE_MSG file or
  1290. * {@code null} if this file doesn't exist
  1291. * @throws IOException
  1292. */
  1293. public String readMergeCommitMsg() throws IOException {
  1294. File mergeMsgFile = new File(gitDir, Constants.MERGE_MSG);
  1295. try {
  1296. return new String(IO.readFully(mergeMsgFile));
  1297. } catch (FileNotFoundException e) {
  1298. // MERGE_MSG file has disappeared in the meantime
  1299. // ignore it
  1300. return null;
  1301. }
  1302. }
  1303. /**
  1304. * Return the information stored in the file $GIT_DIR/MERGE_HEAD. In this
  1305. * file operations triggering a merge will store the IDs of all heads which
  1306. * should be merged together with HEAD.
  1307. *
  1308. * @return a list of {@link Commit}s which IDs are listed in the MERGE_HEAD
  1309. * file or {@code null} if this file doesn't exist. Also if the file
  1310. * exists but is empty {@code null} will be returned
  1311. * @throws IOException
  1312. */
  1313. public List<ObjectId> readMergeHeads() throws IOException {
  1314. File mergeHeadFile = new File(gitDir, Constants.MERGE_HEAD);
  1315. byte[] raw;
  1316. try {
  1317. raw = IO.readFully(mergeHeadFile);
  1318. } catch (FileNotFoundException notFound) {
  1319. return new LinkedList<ObjectId>();
  1320. }
  1321. if (raw.length == 0)
  1322. throw new IOException("MERGE_HEAD file empty: " + mergeHeadFile);
  1323. LinkedList<ObjectId> heads = new LinkedList<ObjectId>();
  1324. for (int p = 0; p < raw.length;) {
  1325. heads.add(ObjectId.fromString(raw, p));
  1326. p = RawParseUtils
  1327. .nextLF(raw, p + Constants.OBJECT_ID_STRING_LENGTH);
  1328. }
  1329. return heads;
  1330. }
  1331. }