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.

FileRepository.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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.storage.file;
  47. import java.io.File;
  48. import java.io.IOException;
  49. import java.text.MessageFormat;
  50. import java.util.HashSet;
  51. import java.util.Set;
  52. import org.eclipse.jgit.errors.ConfigInvalidException;
  53. import org.eclipse.jgit.events.ConfigChangedEvent;
  54. import org.eclipse.jgit.events.ConfigChangedListener;
  55. import org.eclipse.jgit.events.IndexChangedEvent;
  56. import org.eclipse.jgit.internal.JGitText;
  57. import org.eclipse.jgit.lib.BaseRepositoryBuilder;
  58. import org.eclipse.jgit.lib.ConfigConstants;
  59. import org.eclipse.jgit.lib.Constants;
  60. import org.eclipse.jgit.lib.ObjectId;
  61. import org.eclipse.jgit.lib.Ref;
  62. import org.eclipse.jgit.lib.RefDatabase;
  63. import org.eclipse.jgit.lib.RefUpdate;
  64. import org.eclipse.jgit.lib.Repository;
  65. import org.eclipse.jgit.storage.file.FileObjectDatabase.AlternateHandle;
  66. import org.eclipse.jgit.storage.file.FileObjectDatabase.AlternateRepository;
  67. import org.eclipse.jgit.util.FileUtils;
  68. import org.eclipse.jgit.util.SystemReader;
  69. /**
  70. * Represents a Git repository. A repository holds all objects and refs used for
  71. * managing source code (could by any type of file, but source code is what
  72. * SCM's are typically used for).
  73. *
  74. * In Git terms all data is stored in GIT_DIR, typically a directory called
  75. * .git. A work tree is maintained unless the repository is a bare repository.
  76. * Typically the .git directory is located at the root of the work dir.
  77. *
  78. * <ul>
  79. * <li>GIT_DIR
  80. * <ul>
  81. * <li>objects/ - objects</li>
  82. * <li>refs/ - tags and heads</li>
  83. * <li>config - configuration</li>
  84. * <li>info/ - more configurations</li>
  85. * </ul>
  86. * </li>
  87. * </ul>
  88. * <p>
  89. * This class is thread-safe.
  90. * <p>
  91. * This implementation only handles a subtly undocumented subset of git features.
  92. *
  93. */
  94. public class FileRepository extends Repository {
  95. private final FileBasedConfig systemConfig;
  96. private final FileBasedConfig userConfig;
  97. private final FileBasedConfig repoConfig;
  98. private final RefDatabase refs;
  99. private final ObjectDirectory objectDatabase;
  100. private FileSnapshot snapshot;
  101. /**
  102. * Construct a representation of a Git repository.
  103. * <p>
  104. * The work tree, object directory, alternate object directories and index
  105. * file locations are deduced from the given git directory and the default
  106. * rules by running {@link FileRepositoryBuilder}. This constructor is the
  107. * same as saying:
  108. *
  109. * <pre>
  110. * new FileRepositoryBuilder().setGitDir(gitDir).build()
  111. * </pre>
  112. *
  113. * @param gitDir
  114. * GIT_DIR (the location of the repository metadata).
  115. * @throws IOException
  116. * the repository appears to already exist but cannot be
  117. * accessed.
  118. * @see FileRepositoryBuilder
  119. */
  120. public FileRepository(final File gitDir) throws IOException {
  121. this(new FileRepositoryBuilder().setGitDir(gitDir).setup());
  122. }
  123. /**
  124. * A convenience API for {@link #FileRepository(File)}.
  125. *
  126. * @param gitDir
  127. * GIT_DIR (the location of the repository metadata).
  128. * @throws IOException
  129. * the repository appears to already exist but cannot be
  130. * accessed.
  131. * @see FileRepositoryBuilder
  132. */
  133. public FileRepository(final String gitDir) throws IOException {
  134. this(new File(gitDir));
  135. }
  136. /**
  137. * Create a repository using the local file system.
  138. *
  139. * @param options
  140. * description of the repository's important paths.
  141. * @throws IOException
  142. * the user configuration file or repository configuration file
  143. * cannot be accessed.
  144. */
  145. public FileRepository(final BaseRepositoryBuilder options) throws IOException {
  146. super(options);
  147. systemConfig = SystemReader.getInstance().openSystemConfig(null, getFS());
  148. userConfig = SystemReader.getInstance().openUserConfig(systemConfig,
  149. getFS());
  150. repoConfig = new FileBasedConfig(userConfig, getFS().resolve(
  151. getDirectory(), Constants.CONFIG),
  152. getFS());
  153. loadSystemConfig();
  154. loadUserConfig();
  155. loadRepoConfig();
  156. repoConfig.addChangeListener(new ConfigChangedListener() {
  157. public void onConfigChanged(ConfigChangedEvent event) {
  158. fireEvent(event);
  159. }
  160. });
  161. refs = new RefDirectory(this);
  162. objectDatabase = new ObjectDirectory(repoConfig, //
  163. options.getObjectDirectory(), //
  164. options.getAlternateObjectDirectories(), //
  165. getFS());
  166. if (objectDatabase.exists()) {
  167. final long repositoryFormatVersion = getConfig().getLong(
  168. ConfigConstants.CONFIG_CORE_SECTION, null,
  169. ConfigConstants.CONFIG_KEY_REPO_FORMAT_VERSION, 0);
  170. if (repositoryFormatVersion > 0)
  171. throw new IOException(MessageFormat.format(
  172. JGitText.get().unknownRepositoryFormat2,
  173. Long.valueOf(repositoryFormatVersion)));
  174. }
  175. if (!isBare())
  176. snapshot = FileSnapshot.save(getIndexFile());
  177. }
  178. private void loadSystemConfig() throws IOException {
  179. try {
  180. systemConfig.load();
  181. } catch (ConfigInvalidException e1) {
  182. IOException e2 = new IOException(MessageFormat.format(JGitText
  183. .get().systemConfigFileInvalid, systemConfig.getFile()
  184. .getAbsolutePath(), e1));
  185. e2.initCause(e1);
  186. throw e2;
  187. }
  188. }
  189. private void loadUserConfig() throws IOException {
  190. try {
  191. userConfig.load();
  192. } catch (ConfigInvalidException e1) {
  193. IOException e2 = new IOException(MessageFormat.format(JGitText
  194. .get().userConfigFileInvalid, userConfig.getFile()
  195. .getAbsolutePath(), e1));
  196. e2.initCause(e1);
  197. throw e2;
  198. }
  199. }
  200. private void loadRepoConfig() throws IOException {
  201. try {
  202. repoConfig.load();
  203. } catch (ConfigInvalidException e1) {
  204. IOException e2 = new IOException(JGitText.get().unknownRepositoryFormat);
  205. e2.initCause(e1);
  206. throw e2;
  207. }
  208. }
  209. /**
  210. * Create a new Git repository initializing the necessary files and
  211. * directories.
  212. *
  213. * @param bare
  214. * if true, a bare repository is created.
  215. *
  216. * @throws IOException
  217. * in case of IO problem
  218. */
  219. public void create(boolean bare) throws IOException {
  220. final FileBasedConfig cfg = getConfig();
  221. if (cfg.getFile().exists()) {
  222. throw new IllegalStateException(MessageFormat.format(
  223. JGitText.get().repositoryAlreadyExists, getDirectory()));
  224. }
  225. FileUtils.mkdirs(getDirectory(), true);
  226. refs.create();
  227. objectDatabase.create();
  228. FileUtils.mkdir(new File(getDirectory(), "branches"));
  229. FileUtils.mkdir(new File(getDirectory(), "hooks"));
  230. RefUpdate head = updateRef(Constants.HEAD);
  231. head.disableRefLog();
  232. head.link(Constants.R_HEADS + Constants.MASTER);
  233. final boolean fileMode;
  234. if (getFS().supportsExecute()) {
  235. File tmp = File.createTempFile("try", "execute", getDirectory());
  236. getFS().setExecute(tmp, true);
  237. final boolean on = getFS().canExecute(tmp);
  238. getFS().setExecute(tmp, false);
  239. final boolean off = getFS().canExecute(tmp);
  240. FileUtils.delete(tmp);
  241. fileMode = on && !off;
  242. } else {
  243. fileMode = false;
  244. }
  245. cfg.setInt(ConfigConstants.CONFIG_CORE_SECTION, null,
  246. ConfigConstants.CONFIG_KEY_REPO_FORMAT_VERSION, 0);
  247. cfg.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null,
  248. ConfigConstants.CONFIG_KEY_FILEMODE, fileMode);
  249. if (bare)
  250. cfg.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null,
  251. ConfigConstants.CONFIG_KEY_BARE, true);
  252. cfg.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null,
  253. ConfigConstants.CONFIG_KEY_LOGALLREFUPDATES, !bare);
  254. cfg.save();
  255. }
  256. /**
  257. * @return the directory containing the objects owned by this repository.
  258. */
  259. public File getObjectsDirectory() {
  260. return objectDatabase.getDirectory();
  261. }
  262. /**
  263. * @return the object database which stores this repository's data.
  264. */
  265. public ObjectDirectory getObjectDatabase() {
  266. return objectDatabase;
  267. }
  268. /** @return the reference database which stores the reference namespace. */
  269. public RefDatabase getRefDatabase() {
  270. return refs;
  271. }
  272. /**
  273. * @return the configuration of this repository
  274. */
  275. public FileBasedConfig getConfig() {
  276. if (systemConfig.isOutdated()) {
  277. try {
  278. loadSystemConfig();
  279. } catch (IOException e) {
  280. throw new RuntimeException(e);
  281. }
  282. }
  283. if (userConfig.isOutdated()) {
  284. try {
  285. loadUserConfig();
  286. } catch (IOException e) {
  287. throw new RuntimeException(e);
  288. }
  289. }
  290. if (repoConfig.isOutdated()) {
  291. try {
  292. loadRepoConfig();
  293. } catch (IOException e) {
  294. throw new RuntimeException(e);
  295. }
  296. }
  297. return repoConfig;
  298. }
  299. /**
  300. * Objects known to exist but not expressed by {@link #getAllRefs()}.
  301. * <p>
  302. * When a repository borrows objects from another repository, it can
  303. * advertise that it safely has that other repository's references, without
  304. * exposing any other details about the other repository. This may help
  305. * a client trying to push changes avoid pushing more than it needs to.
  306. *
  307. * @return unmodifiable collection of other known objects.
  308. */
  309. public Set<ObjectId> getAdditionalHaves() {
  310. HashSet<ObjectId> r = new HashSet<ObjectId>();
  311. for (AlternateHandle d : objectDatabase. myAlternates()) {
  312. if (d instanceof AlternateRepository) {
  313. Repository repo;
  314. repo = ((AlternateRepository) d).repository;
  315. for (Ref ref : repo.getAllRefs().values()) {
  316. if (ref.getObjectId() != null)
  317. r.add(ref.getObjectId());
  318. if (ref.getPeeledObjectId() != null)
  319. r.add(ref.getPeeledObjectId());
  320. }
  321. r.addAll(repo.getAdditionalHaves());
  322. }
  323. }
  324. return r;
  325. }
  326. /**
  327. * Add a single existing pack to the list of available pack files.
  328. *
  329. * @param pack
  330. * path of the pack file to open.
  331. * @param idx
  332. * path of the corresponding index file.
  333. * @throws IOException
  334. * index file could not be opened, read, or is not recognized as
  335. * a Git pack file index.
  336. */
  337. public void openPack(final File pack, final File idx) throws IOException {
  338. objectDatabase.openPack(pack, idx);
  339. }
  340. @Override
  341. public void scanForRepoChanges() throws IOException {
  342. getAllRefs(); // This will look for changes to refs
  343. detectIndexChanges();
  344. }
  345. /**
  346. * Detect index changes.
  347. */
  348. private void detectIndexChanges() {
  349. if (isBare())
  350. return;
  351. File indexFile = getIndexFile();
  352. if (snapshot == null)
  353. snapshot = FileSnapshot.save(indexFile);
  354. else if (snapshot.isModified(indexFile))
  355. notifyIndexChanged();
  356. }
  357. @Override
  358. public void notifyIndexChanged() {
  359. snapshot = FileSnapshot.save(getIndexFile());
  360. fireEvent(new IndexChangedEvent());
  361. }
  362. /**
  363. * @param refName
  364. * @return a {@link ReflogReader} for the supplied refname, or null if the
  365. * named ref does not exist.
  366. * @throws IOException the ref could not be accessed.
  367. */
  368. public ReflogReader getReflogReader(String refName) throws IOException {
  369. Ref ref = getRef(refName);
  370. if (ref != null)
  371. return new ReflogReader(this, ref.getName());
  372. return null;
  373. }
  374. }