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

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