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

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