Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

FileRepository.java 14KB

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