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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498
  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 provided.
  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 provided.
  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, FS fs)
  206. 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(
  218. JGitText.get().eitherGIT_DIRorGIT_WORK_TREEmustBePassed);
  219. }
  220. this.fs = fs;
  221. userConfig = SystemReader.getInstance().openUserConfig(fs);
  222. config = new RepositoryConfig(userConfig, fs.resolve(gitDir, "config"));
  223. loadUserConfig();
  224. loadConfig();
  225. if (workDir == null) {
  226. // if the working directory was not provided explicitly,
  227. // we need to decide if this is a "bare" repository or not
  228. // first, we check the working tree configuration
  229. String workTreeConfig = getConfig().getString(
  230. ConfigConstants.CONFIG_CORE_SECTION, null,
  231. ConfigConstants.CONFIG_KEY_WORKTREE);
  232. if (workTreeConfig != null) {
  233. // the working tree configuration wins
  234. workDir = fs.resolve(d, workTreeConfig);
  235. } else if (getConfig().getString(
  236. ConfigConstants.CONFIG_CORE_SECTION, null,
  237. ConfigConstants.CONFIG_KEY_BARE) != null) {
  238. // we have asserted that a value for the "bare" flag was set
  239. if (!getConfig().getBoolean(ConfigConstants.CONFIG_CORE_SECTION,
  240. ConfigConstants.CONFIG_KEY_BARE, true))
  241. // the "bare" flag is false -> use the parent of the
  242. // meta data directory
  243. workDir = gitDir.getParentFile();
  244. else
  245. // the "bare" flag is true
  246. workDir = null;
  247. } else if (Constants.DOT_GIT.equals(gitDir.getName())) {
  248. // no value for the "bare" flag, but the meta data directory
  249. // is named ".git" -> use the parent of the meta data directory
  250. workDir = gitDir.getParentFile();
  251. } else {
  252. workDir = null;
  253. }
  254. }
  255. refs = new RefDirectory(this);
  256. if (objectDir != null)
  257. objectDatabase = new ObjectDirectory(fs.resolve(objectDir, ""),
  258. alternateObjectDir, fs);
  259. else
  260. objectDatabase = new ObjectDirectory(fs.resolve(gitDir, "objects"),
  261. alternateObjectDir, fs);
  262. if (indexFile != null)
  263. this.indexFile = indexFile;
  264. else
  265. this.indexFile = new File(gitDir, "index");
  266. if (objectDatabase.exists()) {
  267. final String repositoryFormatVersion = getConfig().getString(
  268. ConfigConstants.CONFIG_CORE_SECTION, null,
  269. ConfigConstants.CONFIG_KEY_REPO_FORMAT_VERSION);
  270. if (!"0".equals(repositoryFormatVersion)) {
  271. throw new IOException(MessageFormat.format(
  272. JGitText.get().unknownRepositoryFormat2,
  273. repositoryFormatVersion));
  274. }
  275. }
  276. }
  277. private void loadUserConfig() throws IOException {
  278. try {
  279. userConfig.load();
  280. } catch (ConfigInvalidException e1) {
  281. IOException e2 = new IOException(MessageFormat.format(JGitText
  282. .get().userConfigFileInvalid, userConfig.getFile()
  283. .getAbsolutePath(), e1));
  284. e2.initCause(e1);
  285. throw e2;
  286. }
  287. }
  288. private void loadConfig() throws IOException {
  289. try {
  290. config.load();
  291. } catch (ConfigInvalidException e1) {
  292. IOException e2 = new IOException(JGitText.get().unknownRepositoryFormat);
  293. e2.initCause(e1);
  294. throw e2;
  295. }
  296. }
  297. /**
  298. * Create a new Git repository initializing the necessary files and
  299. * directories. Repository with working tree is created using this method.
  300. *
  301. * @throws IOException
  302. * @see #create(boolean)
  303. */
  304. public synchronized void create() throws IOException {
  305. create(false);
  306. }
  307. /**
  308. * Create a new Git repository initializing the necessary files and
  309. * directories.
  310. *
  311. * @param bare
  312. * if true, a bare repository is created.
  313. *
  314. * @throws IOException
  315. * in case of IO problem
  316. */
  317. public void create(boolean bare) throws IOException {
  318. final RepositoryConfig cfg = getConfig();
  319. if (cfg.getFile().exists()) {
  320. throw new IllegalStateException(MessageFormat.format(
  321. JGitText.get().repositoryAlreadyExists, gitDir));
  322. }
  323. gitDir.mkdirs();
  324. refs.create();
  325. objectDatabase.create();
  326. new File(gitDir, "branches").mkdir();
  327. RefUpdate head = updateRef(Constants.HEAD);
  328. head.disableRefLog();
  329. head.link(Constants.R_HEADS + Constants.MASTER);
  330. cfg.setInt(ConfigConstants.CONFIG_CORE_SECTION, null,
  331. ConfigConstants.CONFIG_KEY_REPO_FORMAT_VERSION, 0);
  332. cfg.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null,
  333. ConfigConstants.CONFIG_KEY_FILEMODE, true);
  334. if (bare)
  335. cfg.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null,
  336. ConfigConstants.CONFIG_KEY_BARE, true);
  337. cfg.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null,
  338. ConfigConstants.CONFIG_KEY_LOGALLREFUPDATES, !bare);
  339. cfg.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null,
  340. ConfigConstants.CONFIG_KEY_AUTOCRLF, false);
  341. cfg.save();
  342. }
  343. /**
  344. * @return GIT_DIR
  345. */
  346. public File getDirectory() {
  347. return gitDir;
  348. }
  349. /**
  350. * @return the directory containing the objects owned by this repository.
  351. */
  352. public File getObjectsDirectory() {
  353. return objectDatabase.getDirectory();
  354. }
  355. /**
  356. * @return the object database which stores this repository's data.
  357. */
  358. public ObjectDatabase getObjectDatabase() {
  359. return objectDatabase;
  360. }
  361. /** @return the reference database which stores the reference namespace. */
  362. public RefDatabase getRefDatabase() {
  363. return refs;
  364. }
  365. /**
  366. * @return the configuration of this repository
  367. */
  368. public RepositoryConfig getConfig() {
  369. if (userConfig.isOutdated()) {
  370. try {
  371. loadUserConfig();
  372. } catch (IOException e) {
  373. throw new RuntimeException(e);
  374. }
  375. }
  376. if (config.isOutdated()) {
  377. try {
  378. loadConfig();
  379. } catch (IOException e) {
  380. throw new RuntimeException(e);
  381. }
  382. }
  383. return config;
  384. }
  385. /**
  386. * @return the used file system abstraction
  387. */
  388. public FS getFS() {
  389. return fs;
  390. }
  391. /**
  392. * Construct a filename where the loose object having a specified SHA-1
  393. * should be stored. If the object is stored in a shared repository the path
  394. * to the alternative repo will be returned. If the object is not yet store
  395. * a usable path in this repo will be returned. It is assumed that callers
  396. * will look for objects in a pack first.
  397. *
  398. * @param objectId
  399. * @return suggested file name
  400. */
  401. public File toFile(final AnyObjectId objectId) {
  402. return objectDatabase.fileFor(objectId);
  403. }
  404. /**
  405. * @param objectId
  406. * @return true if the specified object is stored in this repo or any of the
  407. * known shared repositories.
  408. */
  409. public boolean hasObject(final AnyObjectId objectId) {
  410. return objectDatabase.hasObject(objectId);
  411. }
  412. /**
  413. * @param id
  414. * SHA-1 of an object.
  415. *
  416. * @return a {@link ObjectLoader} for accessing the data of the named
  417. * object, or null if the object does not exist.
  418. * @throws IOException
  419. */
  420. public ObjectLoader openObject(final AnyObjectId id)
  421. throws IOException {
  422. final WindowCursor wc = new WindowCursor();
  423. try {
  424. return openObject(wc, id);
  425. } finally {
  426. wc.release();
  427. }
  428. }
  429. /**
  430. * @param curs
  431. * temporary working space associated with the calling thread.
  432. * @param id
  433. * SHA-1 of an object.
  434. *
  435. * @return a {@link ObjectLoader} for accessing the data of the named
  436. * object, or null if the object does not exist.
  437. * @throws IOException
  438. */
  439. public ObjectLoader openObject(final WindowCursor curs, final AnyObjectId id)
  440. throws IOException {
  441. return objectDatabase.openObject(curs, id);
  442. }
  443. /**
  444. * Open object in all packs containing specified object.
  445. *
  446. * @param objectId
  447. * id of object to search for
  448. * @param curs
  449. * temporary working space associated with the calling thread.
  450. * @return collection of loaders for this object, from all packs containing
  451. * this object
  452. * @throws IOException
  453. */
  454. public Collection<PackedObjectLoader> openObjectInAllPacks(
  455. final AnyObjectId objectId, final WindowCursor curs)
  456. throws IOException {
  457. Collection<PackedObjectLoader> result = new LinkedList<PackedObjectLoader>();
  458. openObjectInAllPacks(objectId, result, curs);
  459. return result;
  460. }
  461. /**
  462. * Open object in all packs containing specified object.
  463. *
  464. * @param objectId
  465. * id of object to search for
  466. * @param resultLoaders
  467. * result collection of loaders for this object, filled with
  468. * loaders from all packs containing specified object
  469. * @param curs
  470. * temporary working space associated with the calling thread.
  471. * @throws IOException
  472. */
  473. void openObjectInAllPacks(final AnyObjectId objectId,
  474. final Collection<PackedObjectLoader> resultLoaders,
  475. final WindowCursor curs) throws IOException {
  476. objectDatabase.openObjectInAllPacks(resultLoaders, curs, objectId);
  477. }
  478. /**
  479. * @param id
  480. * SHA'1 of a blob
  481. * @return an {@link ObjectLoader} for accessing the data of a named blob
  482. * @throws IOException
  483. */
  484. public ObjectLoader openBlob(final ObjectId id) throws IOException {
  485. return openObject(id);
  486. }
  487. /**
  488. * @param id
  489. * SHA'1 of a tree
  490. * @return an {@link ObjectLoader} for accessing the data of a named tree
  491. * @throws IOException
  492. */
  493. public ObjectLoader openTree(final ObjectId id) throws IOException {
  494. return openObject(id);
  495. }
  496. /**
  497. * Access a Commit object using a symbolic reference. This reference may
  498. * be a SHA-1 or ref in combination with a number of symbols translating
  499. * from one ref or SHA1-1 to another, such as HEAD^ etc.
  500. *
  501. * @param revstr a reference to a git commit object
  502. * @return a Commit named by the specified string
  503. * @throws IOException for I/O error or unexpected object type.
  504. *
  505. * @see #resolve(String)
  506. */
  507. public Commit mapCommit(final String revstr) throws IOException {
  508. final ObjectId id = resolve(revstr);
  509. return id != null ? mapCommit(id) : null;
  510. }
  511. /**
  512. * Access any type of Git object by id and
  513. *
  514. * @param id
  515. * SHA-1 of object to read
  516. * @param refName optional, only relevant for simple tags
  517. * @return The Git object if found or null
  518. * @throws IOException
  519. */
  520. public Object mapObject(final ObjectId id, final String refName) throws IOException {
  521. final ObjectLoader or = openObject(id);
  522. if (or == null)
  523. return null;
  524. final byte[] raw = or.getBytes();
  525. switch (or.getType()) {
  526. case Constants.OBJ_TREE:
  527. return makeTree(id, raw);
  528. case Constants.OBJ_COMMIT:
  529. return makeCommit(id, raw);
  530. case Constants.OBJ_TAG:
  531. return makeTag(id, refName, raw);
  532. case Constants.OBJ_BLOB:
  533. return raw;
  534. default:
  535. throw new IncorrectObjectTypeException(id,
  536. JGitText.get().incorrectObjectType_COMMITnorTREEnorBLOBnorTAG);
  537. }
  538. }
  539. /**
  540. * Access a Commit by SHA'1 id.
  541. * @param id
  542. * @return Commit or null
  543. * @throws IOException for I/O error or unexpected object type.
  544. */
  545. public Commit mapCommit(final ObjectId id) throws IOException {
  546. final ObjectLoader or = openObject(id);
  547. if (or == null)
  548. return null;
  549. final byte[] raw = or.getBytes();
  550. if (Constants.OBJ_COMMIT == or.getType())
  551. return new Commit(this, id, raw);
  552. throw new IncorrectObjectTypeException(id, Constants.TYPE_COMMIT);
  553. }
  554. private Commit makeCommit(final ObjectId id, final byte[] raw) {
  555. Commit ret = new Commit(this, id, raw);
  556. return ret;
  557. }
  558. /**
  559. * Access a Tree object using a symbolic reference. This reference may
  560. * be a SHA-1 or ref in combination with a number of symbols translating
  561. * from one ref or SHA1-1 to another, such as HEAD^{tree} etc.
  562. *
  563. * @param revstr a reference to a git commit object
  564. * @return a Tree named by the specified string
  565. * @throws IOException
  566. *
  567. * @see #resolve(String)
  568. */
  569. public Tree mapTree(final String revstr) throws IOException {
  570. final ObjectId id = resolve(revstr);
  571. return id != null ? mapTree(id) : null;
  572. }
  573. /**
  574. * Access a Tree by SHA'1 id.
  575. * @param id
  576. * @return Tree or null
  577. * @throws IOException for I/O error or unexpected object type.
  578. */
  579. public Tree mapTree(final ObjectId id) throws IOException {
  580. final ObjectLoader or = openObject(id);
  581. if (or == null)
  582. return null;
  583. final byte[] raw = or.getBytes();
  584. switch (or.getType()) {
  585. case Constants.OBJ_TREE:
  586. return new Tree(this, id, raw);
  587. case Constants.OBJ_COMMIT:
  588. return mapTree(ObjectId.fromString(raw, 5));
  589. default:
  590. throw new IncorrectObjectTypeException(id, Constants.TYPE_TREE);
  591. }
  592. }
  593. private Tree makeTree(final ObjectId id, final byte[] raw) throws IOException {
  594. Tree ret = new Tree(this, id, raw);
  595. return ret;
  596. }
  597. private Tag makeTag(final ObjectId id, final String refName, final byte[] raw) {
  598. Tag ret = new Tag(this, id, refName, raw);
  599. return ret;
  600. }
  601. /**
  602. * Access a tag by symbolic name.
  603. *
  604. * @param revstr
  605. * @return a Tag or null
  606. * @throws IOException on I/O error or unexpected type
  607. */
  608. public Tag mapTag(String revstr) throws IOException {
  609. final ObjectId id = resolve(revstr);
  610. return id != null ? mapTag(revstr, id) : null;
  611. }
  612. /**
  613. * Access a Tag by SHA'1 id
  614. * @param refName
  615. * @param id
  616. * @return Commit or null
  617. * @throws IOException for I/O error or unexpected object type.
  618. */
  619. public Tag mapTag(final String refName, final ObjectId id) throws IOException {
  620. final ObjectLoader or = openObject(id);
  621. if (or == null)
  622. return null;
  623. final byte[] raw = or.getBytes();
  624. if (Constants.OBJ_TAG == or.getType())
  625. return new Tag(this, id, refName, raw);
  626. return new Tag(this, id, refName, null);
  627. }
  628. /**
  629. * Create a command to update, create or delete a ref in this repository.
  630. *
  631. * @param ref
  632. * name of the ref the caller wants to modify.
  633. * @return an update command. The caller must finish populating this command
  634. * and then invoke one of the update methods to actually make a
  635. * change.
  636. * @throws IOException
  637. * a symbolic ref was passed in and could not be resolved back
  638. * to the base ref, as the symbolic ref could not be read.
  639. */
  640. public RefUpdate updateRef(final String ref) throws IOException {
  641. return updateRef(ref, false);
  642. }
  643. /**
  644. * Create a command to update, create or delete a ref in this repository.
  645. *
  646. * @param ref
  647. * name of the ref the caller wants to modify.
  648. * @param detach
  649. * true to create a detached head
  650. * @return an update command. The caller must finish populating this command
  651. * and then invoke one of the update methods to actually make a
  652. * change.
  653. * @throws IOException
  654. * a symbolic ref was passed in and could not be resolved back
  655. * to the base ref, as the symbolic ref could not be read.
  656. */
  657. public RefUpdate updateRef(final String ref, final boolean detach) throws IOException {
  658. return refs.newUpdate(ref, detach);
  659. }
  660. /**
  661. * Create a command to rename a ref in this repository
  662. *
  663. * @param fromRef
  664. * name of ref to rename from
  665. * @param toRef
  666. * name of ref to rename to
  667. * @return an update command that knows how to rename a branch to another.
  668. * @throws IOException
  669. * the rename could not be performed.
  670. *
  671. */
  672. public RefRename renameRef(final String fromRef, final String toRef) throws IOException {
  673. return refs.newRename(fromRef, toRef);
  674. }
  675. /**
  676. * Parse a git revision string and return an object id.
  677. *
  678. * Currently supported is combinations of these.
  679. * <ul>
  680. * <li>SHA-1 - a SHA-1</li>
  681. * <li>refs/... - a ref name</li>
  682. * <li>ref^n - nth parent reference</li>
  683. * <li>ref~n - distance via parent reference</li>
  684. * <li>ref@{n} - nth version of ref</li>
  685. * <li>ref^{tree} - tree references by ref</li>
  686. * <li>ref^{commit} - commit references by ref</li>
  687. * </ul>
  688. *
  689. * Not supported is
  690. * <ul>
  691. * <li>timestamps in reflogs, ref@{full or relative timestamp}</li>
  692. * <li>abbreviated SHA-1's</li>
  693. * </ul>
  694. *
  695. * @param revstr A git object references expression
  696. * @return an ObjectId or null if revstr can't be resolved to any ObjectId
  697. * @throws IOException on serious errors
  698. */
  699. public ObjectId resolve(final String revstr) throws IOException {
  700. char[] rev = revstr.toCharArray();
  701. Object ref = null;
  702. ObjectId refId = null;
  703. for (int i = 0; i < rev.length; ++i) {
  704. switch (rev[i]) {
  705. case '^':
  706. if (refId == null) {
  707. String refstr = new String(rev,0,i);
  708. refId = resolveSimple(refstr);
  709. if (refId == null)
  710. return null;
  711. }
  712. if (i + 1 < rev.length) {
  713. switch (rev[i + 1]) {
  714. case '0':
  715. case '1':
  716. case '2':
  717. case '3':
  718. case '4':
  719. case '5':
  720. case '6':
  721. case '7':
  722. case '8':
  723. case '9':
  724. int j;
  725. ref = mapObject(refId, null);
  726. while (ref instanceof Tag) {
  727. Tag tag = (Tag)ref;
  728. refId = tag.getObjId();
  729. ref = mapObject(refId, null);
  730. }
  731. if (!(ref instanceof Commit))
  732. throw new IncorrectObjectTypeException(refId, Constants.TYPE_COMMIT);
  733. for (j=i+1; j<rev.length; ++j) {
  734. if (!Character.isDigit(rev[j]))
  735. break;
  736. }
  737. String parentnum = new String(rev, i+1, j-i-1);
  738. int pnum;
  739. try {
  740. pnum = Integer.parseInt(parentnum);
  741. } catch (NumberFormatException e) {
  742. throw new RevisionSyntaxException(
  743. JGitText.get().invalidCommitParentNumber,
  744. revstr);
  745. }
  746. if (pnum != 0) {
  747. final ObjectId parents[] = ((Commit) ref)
  748. .getParentIds();
  749. if (pnum > parents.length)
  750. refId = null;
  751. else
  752. refId = parents[pnum - 1];
  753. }
  754. i = j - 1;
  755. break;
  756. case '{':
  757. int k;
  758. String item = null;
  759. for (k=i+2; k<rev.length; ++k) {
  760. if (rev[k] == '}') {
  761. item = new String(rev, i+2, k-i-2);
  762. break;
  763. }
  764. }
  765. i = k;
  766. if (item != null)
  767. if (item.equals("tree")) {
  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. if (ref instanceof Treeish)
  775. refId = ((Treeish)ref).getTreeId();
  776. else
  777. throw new IncorrectObjectTypeException(refId, Constants.TYPE_TREE);
  778. }
  779. else if (item.equals("commit")) {
  780. ref = mapObject(refId, null);
  781. while (ref instanceof Tag) {
  782. Tag t = (Tag)ref;
  783. refId = t.getObjId();
  784. ref = mapObject(refId, null);
  785. }
  786. if (!(ref instanceof Commit))
  787. throw new IncorrectObjectTypeException(refId, Constants.TYPE_COMMIT);
  788. }
  789. else if (item.equals("blob")) {
  790. ref = mapObject(refId, null);
  791. while (ref instanceof Tag) {
  792. Tag t = (Tag)ref;
  793. refId = t.getObjId();
  794. ref = mapObject(refId, null);
  795. }
  796. if (!(ref instanceof byte[]))
  797. throw new IncorrectObjectTypeException(refId, Constants.TYPE_BLOB);
  798. }
  799. else if (item.equals("")) {
  800. ref = mapObject(refId, null);
  801. while (ref instanceof Tag) {
  802. Tag t = (Tag)ref;
  803. refId = t.getObjId();
  804. ref = mapObject(refId, null);
  805. }
  806. }
  807. else
  808. throw new RevisionSyntaxException(revstr);
  809. else
  810. throw new RevisionSyntaxException(revstr);
  811. break;
  812. default:
  813. ref = mapObject(refId, null);
  814. if (ref instanceof Commit) {
  815. final ObjectId parents[] = ((Commit) ref)
  816. .getParentIds();
  817. if (parents.length == 0)
  818. refId = null;
  819. else
  820. refId = parents[0];
  821. } else
  822. throw new IncorrectObjectTypeException(refId, Constants.TYPE_COMMIT);
  823. }
  824. } else {
  825. ref = mapObject(refId, null);
  826. while (ref instanceof Tag) {
  827. Tag tag = (Tag)ref;
  828. refId = tag.getObjId();
  829. ref = mapObject(refId, null);
  830. }
  831. if (ref instanceof Commit) {
  832. final ObjectId parents[] = ((Commit) ref)
  833. .getParentIds();
  834. if (parents.length == 0)
  835. refId = null;
  836. else
  837. refId = parents[0];
  838. } else
  839. throw new IncorrectObjectTypeException(refId, Constants.TYPE_COMMIT);
  840. }
  841. break;
  842. case '~':
  843. if (ref == null) {
  844. String refstr = new String(rev,0,i);
  845. refId = resolveSimple(refstr);
  846. if (refId == null)
  847. return null;
  848. ref = mapObject(refId, null);
  849. }
  850. while (ref instanceof Tag) {
  851. Tag tag = (Tag)ref;
  852. refId = tag.getObjId();
  853. ref = mapObject(refId, null);
  854. }
  855. if (!(ref instanceof Commit))
  856. throw new IncorrectObjectTypeException(refId, Constants.TYPE_COMMIT);
  857. int l;
  858. for (l = i + 1; l < rev.length; ++l) {
  859. if (!Character.isDigit(rev[l]))
  860. break;
  861. }
  862. String distnum = new String(rev, i+1, l-i-1);
  863. int dist;
  864. try {
  865. dist = Integer.parseInt(distnum);
  866. } catch (NumberFormatException e) {
  867. throw new RevisionSyntaxException(
  868. JGitText.get().invalidAncestryLength, revstr);
  869. }
  870. while (dist > 0) {
  871. final ObjectId[] parents = ((Commit) ref).getParentIds();
  872. if (parents.length == 0) {
  873. refId = null;
  874. break;
  875. }
  876. refId = parents[0];
  877. ref = mapCommit(refId);
  878. --dist;
  879. }
  880. i = l - 1;
  881. break;
  882. case '@':
  883. int m;
  884. String time = null;
  885. for (m=i+2; m<rev.length; ++m) {
  886. if (rev[m] == '}') {
  887. time = new String(rev, i+2, m-i-2);
  888. break;
  889. }
  890. }
  891. if (time != null)
  892. throw new RevisionSyntaxException(JGitText.get().reflogsNotYetSupportedByRevisionParser, revstr);
  893. i = m - 1;
  894. break;
  895. default:
  896. if (refId != null)
  897. throw new RevisionSyntaxException(revstr);
  898. }
  899. }
  900. if (refId == null)
  901. refId = resolveSimple(revstr);
  902. return refId;
  903. }
  904. private ObjectId resolveSimple(final String revstr) throws IOException {
  905. if (ObjectId.isId(revstr))
  906. return ObjectId.fromString(revstr);
  907. final Ref r = refs.getRef(revstr);
  908. return r != null ? r.getObjectId() : null;
  909. }
  910. /** Increment the use counter by one, requiring a matched {@link #close()}. */
  911. public void incrementOpen() {
  912. useCnt.incrementAndGet();
  913. }
  914. /**
  915. * Close all resources used by this repository
  916. */
  917. public void close() {
  918. if (useCnt.decrementAndGet() == 0) {
  919. objectDatabase.close();
  920. refs.close();
  921. }
  922. }
  923. /**
  924. * Add a single existing pack to the list of available pack files.
  925. *
  926. * @param pack
  927. * path of the pack file to open.
  928. * @param idx
  929. * path of the corresponding index file.
  930. * @throws IOException
  931. * index file could not be opened, read, or is not recognized as
  932. * a Git pack file index.
  933. */
  934. public void openPack(final File pack, final File idx) throws IOException {
  935. objectDatabase.openPack(pack, idx);
  936. }
  937. public String toString() {
  938. return "Repository[" + getDirectory() + "]";
  939. }
  940. /**
  941. * Get the name of the reference that {@code HEAD} points to.
  942. * <p>
  943. * This is essentially the same as doing:
  944. *
  945. * <pre>
  946. * return getRef(Constants.HEAD).getTarget().getName()
  947. * </pre>
  948. *
  949. * Except when HEAD is detached, in which case this method returns the
  950. * current ObjectId in hexadecimal string format.
  951. *
  952. * @return name of current branch (for example {@code refs/heads/master}) or
  953. * an ObjectId in hex format if the current branch is detached.
  954. * @throws IOException
  955. */
  956. public String getFullBranch() throws IOException {
  957. Ref head = getRef(Constants.HEAD);
  958. if (head == null)
  959. return null;
  960. if (head.isSymbolic())
  961. return head.getTarget().getName();
  962. if (head.getObjectId() != null)
  963. return head.getObjectId().name();
  964. return null;
  965. }
  966. /**
  967. * Get the short name of the current branch that {@code HEAD} points to.
  968. * <p>
  969. * This is essentially the same as {@link #getFullBranch()}, except the
  970. * leading prefix {@code refs/heads/} is removed from the reference before
  971. * it is returned to the caller.
  972. *
  973. * @return name of current branch (for example {@code master}), or an
  974. * ObjectId in hex format if the current branch is detached.
  975. * @throws IOException
  976. */
  977. public String getBranch() throws IOException {
  978. String name = getFullBranch();
  979. if (name != null)
  980. return shortenRefName(name);
  981. return name;
  982. }
  983. /**
  984. * Get a ref by name.
  985. *
  986. * @param name
  987. * the name of the ref to lookup. May be a short-hand form, e.g.
  988. * "master" which is is automatically expanded to
  989. * "refs/heads/master" if "refs/heads/master" already exists.
  990. * @return the Ref with the given name, or null if it does not exist
  991. * @throws IOException
  992. */
  993. public Ref getRef(final String name) throws IOException {
  994. return refs.getRef(name);
  995. }
  996. /**
  997. * @return mutable map of all known refs (heads, tags, remotes).
  998. */
  999. public Map<String, Ref> getAllRefs() {
  1000. try {
  1001. return refs.getRefs(RefDatabase.ALL);
  1002. } catch (IOException e) {
  1003. return new HashMap<String, Ref>();
  1004. }
  1005. }
  1006. /**
  1007. * @return mutable map of all tags; key is short tag name ("v1.0") and value
  1008. * of the entry contains the ref with the full tag name
  1009. * ("refs/tags/v1.0").
  1010. */
  1011. public Map<String, Ref> getTags() {
  1012. try {
  1013. return refs.getRefs(Constants.R_TAGS);
  1014. } catch (IOException e) {
  1015. return new HashMap<String, Ref>();
  1016. }
  1017. }
  1018. /**
  1019. * Peel a possibly unpeeled reference to an annotated tag.
  1020. * <p>
  1021. * If the ref cannot be peeled (as it does not refer to an annotated tag)
  1022. * the peeled id stays null, but {@link Ref#isPeeled()} will be true.
  1023. *
  1024. * @param ref
  1025. * The ref to peel
  1026. * @return <code>ref</code> if <code>ref.isPeeled()</code> is true; else a
  1027. * new Ref object representing the same data as Ref, but isPeeled()
  1028. * will be true and getPeeledObjectId will contain the peeled object
  1029. * (or null).
  1030. */
  1031. public Ref peel(final Ref ref) {
  1032. try {
  1033. return refs.peel(ref);
  1034. } catch (IOException e) {
  1035. // Historical accident; if the reference cannot be peeled due
  1036. // to some sort of repository access problem we claim that the
  1037. // same as if the reference was not an annotated tag.
  1038. return ref;
  1039. }
  1040. }
  1041. /**
  1042. * @return a map with all objects referenced by a peeled ref.
  1043. */
  1044. public Map<AnyObjectId, Set<Ref>> getAllRefsByPeeledObjectId() {
  1045. Map<String, Ref> allRefs = getAllRefs();
  1046. Map<AnyObjectId, Set<Ref>> ret = new HashMap<AnyObjectId, Set<Ref>>(allRefs.size());
  1047. for (Ref ref : allRefs.values()) {
  1048. ref = peel(ref);
  1049. AnyObjectId target = ref.getPeeledObjectId();
  1050. if (target == null)
  1051. target = ref.getObjectId();
  1052. // We assume most Sets here are singletons
  1053. Set<Ref> oset = ret.put(target, Collections.singleton(ref));
  1054. if (oset != null) {
  1055. // that was not the case (rare)
  1056. if (oset.size() == 1) {
  1057. // Was a read-only singleton, we must copy to a new Set
  1058. oset = new HashSet<Ref>(oset);
  1059. }
  1060. ret.put(target, oset);
  1061. oset.add(ref);
  1062. }
  1063. }
  1064. return ret;
  1065. }
  1066. /**
  1067. * @return a representation of the index associated with this
  1068. * {@link Repository}
  1069. * @throws IOException
  1070. * if the index can not be read
  1071. * @throws IllegalStateException
  1072. * if this is bare (see {@link #isBare()})
  1073. */
  1074. public GitIndex getIndex() throws IOException, IllegalStateException {
  1075. if (isBare())
  1076. throw new IllegalStateException(
  1077. JGitText.get().bareRepositoryNoWorkdirAndIndex);
  1078. if (index == null) {
  1079. index = new GitIndex(this);
  1080. index.read();
  1081. } else {
  1082. index.rereadIfNecessary();
  1083. }
  1084. return index;
  1085. }
  1086. /**
  1087. * @return the index file location
  1088. * @throws IllegalStateException
  1089. * if this is bare (see {@link #isBare()})
  1090. */
  1091. public File getIndexFile() throws IllegalStateException {
  1092. if (isBare())
  1093. throw new IllegalStateException(
  1094. JGitText.get().bareRepositoryNoWorkdirAndIndex);
  1095. return indexFile;
  1096. }
  1097. static byte[] gitInternalSlash(byte[] bytes) {
  1098. if (File.separatorChar == '/')
  1099. return bytes;
  1100. for (int i=0; i<bytes.length; ++i)
  1101. if (bytes[i] == File.separatorChar)
  1102. bytes[i] = '/';
  1103. return bytes;
  1104. }
  1105. /**
  1106. * @return an important state
  1107. */
  1108. public RepositoryState getRepositoryState() {
  1109. // Pre Git-1.6 logic
  1110. if (new File(getWorkDir(), ".dotest").exists())
  1111. return RepositoryState.REBASING;
  1112. if (new File(gitDir,".dotest-merge").exists())
  1113. return RepositoryState.REBASING_INTERACTIVE;
  1114. // From 1.6 onwards
  1115. if (new File(getDirectory(),"rebase-apply/rebasing").exists())
  1116. return RepositoryState.REBASING_REBASING;
  1117. if (new File(getDirectory(),"rebase-apply/applying").exists())
  1118. return RepositoryState.APPLY;
  1119. if (new File(getDirectory(),"rebase-apply").exists())
  1120. return RepositoryState.REBASING;
  1121. if (new File(getDirectory(),"rebase-merge/interactive").exists())
  1122. return RepositoryState.REBASING_INTERACTIVE;
  1123. if (new File(getDirectory(),"rebase-merge").exists())
  1124. return RepositoryState.REBASING_MERGE;
  1125. // Both versions
  1126. if (new File(gitDir, "MERGE_HEAD").exists()) {
  1127. // we are merging - now check whether we have unmerged paths
  1128. try {
  1129. if (!DirCache.read(this).hasUnmergedPaths()) {
  1130. // no unmerged paths -> return the MERGING_RESOLVED state
  1131. return RepositoryState.MERGING_RESOLVED;
  1132. }
  1133. } catch (IOException e) {
  1134. // Can't decide whether unmerged paths exists. Return
  1135. // MERGING state to be on the safe side (in state MERGING
  1136. // you are not allow to do anything)
  1137. e.printStackTrace();
  1138. }
  1139. return RepositoryState.MERGING;
  1140. }
  1141. if (new File(gitDir,"BISECT_LOG").exists())
  1142. return RepositoryState.BISECTING;
  1143. return RepositoryState.SAFE;
  1144. }
  1145. /**
  1146. * Check validity of a ref name. It must not contain character that has
  1147. * a special meaning in a Git object reference expression. Some other
  1148. * dangerous characters are also excluded.
  1149. *
  1150. * For portability reasons '\' is excluded
  1151. *
  1152. * @param refName
  1153. *
  1154. * @return true if refName is a valid ref name
  1155. */
  1156. public static boolean isValidRefName(final String refName) {
  1157. final int len = refName.length();
  1158. if (len == 0)
  1159. return false;
  1160. if (refName.endsWith(LockFile.SUFFIX))
  1161. return false;
  1162. int components = 1;
  1163. char p = '\0';
  1164. for (int i = 0; i < len; i++) {
  1165. final char c = refName.charAt(i);
  1166. if (c <= ' ')
  1167. return false;
  1168. switch (c) {
  1169. case '.':
  1170. switch (p) {
  1171. case '\0': case '/': case '.':
  1172. return false;
  1173. }
  1174. if (i == len -1)
  1175. return false;
  1176. break;
  1177. case '/':
  1178. if (i == 0 || i == len - 1)
  1179. return false;
  1180. components++;
  1181. break;
  1182. case '{':
  1183. if (p == '@')
  1184. return false;
  1185. break;
  1186. case '~': case '^': case ':':
  1187. case '?': case '[': case '*':
  1188. case '\\':
  1189. return false;
  1190. }
  1191. p = c;
  1192. }
  1193. return components > 1;
  1194. }
  1195. /**
  1196. * Strip work dir and return normalized repository path.
  1197. *
  1198. * @param workDir Work dir
  1199. * @param file File whose path shall be stripped of its workdir
  1200. * @return normalized repository relative path or the empty
  1201. * string if the file is not relative to the work directory.
  1202. */
  1203. public static String stripWorkDir(File workDir, File file) {
  1204. final String filePath = file.getPath();
  1205. final String workDirPath = workDir.getPath();
  1206. if (filePath.length() <= workDirPath.length() ||
  1207. filePath.charAt(workDirPath.length()) != File.separatorChar ||
  1208. !filePath.startsWith(workDirPath)) {
  1209. File absWd = workDir.isAbsolute() ? workDir : workDir.getAbsoluteFile();
  1210. File absFile = file.isAbsolute() ? file : file.getAbsoluteFile();
  1211. if (absWd == workDir && absFile == file)
  1212. return "";
  1213. return stripWorkDir(absWd, absFile);
  1214. }
  1215. String relName = filePath.substring(workDirPath.length() + 1);
  1216. if (File.separatorChar != '/')
  1217. relName = relName.replace(File.separatorChar, '/');
  1218. return relName;
  1219. }
  1220. /**
  1221. * @return the "bare"-ness of this Repository
  1222. */
  1223. public boolean isBare() {
  1224. return workDir == null;
  1225. }
  1226. /**
  1227. * @return the workdir file, i.e. where the files are checked out
  1228. * @throws IllegalStateException
  1229. * if the repository is "bare"
  1230. */
  1231. public File getWorkDir() throws IllegalStateException {
  1232. if (isBare())
  1233. throw new IllegalStateException(
  1234. JGitText.get().bareRepositoryNoWorkdirAndIndex);
  1235. return workDir;
  1236. }
  1237. /**
  1238. * Override default workdir
  1239. *
  1240. * @param workTree
  1241. * the work tree directory
  1242. */
  1243. public void setWorkDir(File workTree) {
  1244. this.workDir = workTree;
  1245. }
  1246. /**
  1247. * Register a {@link RepositoryListener} which will be notified
  1248. * when ref changes are detected.
  1249. *
  1250. * @param l
  1251. */
  1252. public void addRepositoryChangedListener(final RepositoryListener l) {
  1253. listeners.add(l);
  1254. }
  1255. /**
  1256. * Remove a registered {@link RepositoryListener}
  1257. * @param l
  1258. */
  1259. public void removeRepositoryChangedListener(final RepositoryListener l) {
  1260. listeners.remove(l);
  1261. }
  1262. /**
  1263. * Register a global {@link RepositoryListener} which will be notified
  1264. * when a ref changes in any repository are detected.
  1265. *
  1266. * @param l
  1267. */
  1268. public static void addAnyRepositoryChangedListener(final RepositoryListener l) {
  1269. allListeners.add(l);
  1270. }
  1271. /**
  1272. * Remove a globally registered {@link RepositoryListener}
  1273. * @param l
  1274. */
  1275. public static void removeAnyRepositoryChangedListener(final RepositoryListener l) {
  1276. allListeners.remove(l);
  1277. }
  1278. void fireRefsChanged() {
  1279. final RefsChangedEvent event = new RefsChangedEvent(this);
  1280. List<RepositoryListener> all;
  1281. synchronized (listeners) {
  1282. all = new ArrayList<RepositoryListener>(listeners);
  1283. }
  1284. synchronized (allListeners) {
  1285. all.addAll(allListeners);
  1286. }
  1287. for (final RepositoryListener l : all) {
  1288. l.refsChanged(event);
  1289. }
  1290. }
  1291. void fireIndexChanged() {
  1292. final IndexChangedEvent event = new IndexChangedEvent(this);
  1293. List<RepositoryListener> all;
  1294. synchronized (listeners) {
  1295. all = new ArrayList<RepositoryListener>(listeners);
  1296. }
  1297. synchronized (allListeners) {
  1298. all.addAll(allListeners);
  1299. }
  1300. for (final RepositoryListener l : all) {
  1301. l.indexChanged(event);
  1302. }
  1303. }
  1304. /**
  1305. * Force a scan for changed refs.
  1306. *
  1307. * @throws IOException
  1308. */
  1309. public void scanForRepoChanges() throws IOException {
  1310. getAllRefs(); // This will look for changes to refs
  1311. if (!isBare())
  1312. getIndex(); // This will detect changes in the index
  1313. }
  1314. /**
  1315. * @param refName
  1316. *
  1317. * @return a more user friendly ref name
  1318. */
  1319. public String shortenRefName(String refName) {
  1320. if (refName.startsWith(Constants.R_HEADS))
  1321. return refName.substring(Constants.R_HEADS.length());
  1322. if (refName.startsWith(Constants.R_TAGS))
  1323. return refName.substring(Constants.R_TAGS.length());
  1324. if (refName.startsWith(Constants.R_REMOTES))
  1325. return refName.substring(Constants.R_REMOTES.length());
  1326. return refName;
  1327. }
  1328. /**
  1329. * @param refName
  1330. * @return a {@link ReflogReader} for the supplied refname, or null if the
  1331. * named ref does not exist.
  1332. * @throws IOException the ref could not be accessed.
  1333. */
  1334. public ReflogReader getReflogReader(String refName) throws IOException {
  1335. Ref ref = getRef(refName);
  1336. if (ref != null)
  1337. return new ReflogReader(this, ref.getName());
  1338. return null;
  1339. }
  1340. /**
  1341. * Return the information stored in the file $GIT_DIR/MERGE_MSG. In this
  1342. * file operations triggering a merge will store a template for the commit
  1343. * message of the merge commit.
  1344. *
  1345. * @return a String containing the content of the MERGE_MSG file or
  1346. * {@code null} if this file doesn't exist
  1347. * @throws IOException
  1348. */
  1349. public String readMergeCommitMsg() throws IOException {
  1350. File mergeMsgFile = new File(gitDir, Constants.MERGE_MSG);
  1351. try {
  1352. return new String(IO.readFully(mergeMsgFile));
  1353. } catch (FileNotFoundException e) {
  1354. // MERGE_MSG file has disappeared in the meantime
  1355. // ignore it
  1356. return null;
  1357. }
  1358. }
  1359. /**
  1360. * Return the information stored in the file $GIT_DIR/MERGE_HEAD. In this
  1361. * file operations triggering a merge will store the IDs of all heads which
  1362. * should be merged together with HEAD.
  1363. *
  1364. * @return a list of {@link Commit}s which IDs are listed in the MERGE_HEAD
  1365. * file or {@code null} if this file doesn't exist. Also if the file
  1366. * exists but is empty {@code null} will be returned
  1367. * @throws IOException
  1368. */
  1369. public List<ObjectId> readMergeHeads() throws IOException {
  1370. File mergeHeadFile = new File(gitDir, Constants.MERGE_HEAD);
  1371. byte[] raw;
  1372. try {
  1373. raw = IO.readFully(mergeHeadFile);
  1374. } catch (FileNotFoundException notFound) {
  1375. return new LinkedList<ObjectId>();
  1376. }
  1377. if (raw.length == 0)
  1378. throw new IOException("MERGE_HEAD file empty: " + mergeHeadFile);
  1379. LinkedList<ObjectId> heads = new LinkedList<ObjectId>();
  1380. for (int p = 0; p < raw.length;) {
  1381. heads.add(ObjectId.fromString(raw, p));
  1382. p = RawParseUtils
  1383. .nextLF(raw, p + Constants.OBJECT_ID_STRING_LENGTH);
  1384. }
  1385. return heads;
  1386. }
  1387. }