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

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