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.

FileBasedConfig.java 9.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. /*
  2. * Copyright (C) 2009, Constantine Plotnikov <constantine.plotnikov@gmail.com>
  3. * Copyright (C) 2007, Dave Watson <dwatson@mimvista.com>
  4. * Copyright (C) 2009, Google Inc.
  5. * Copyright (C) 2009, JetBrains s.r.o.
  6. * Copyright (C) 2008-2009, Robin Rosenberg <robin.rosenberg@dewire.com>
  7. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
  8. * Copyright (C) 2008, Thad Hughes <thadh@thad.corp.google.com>
  9. * and other copyright owners as documented in the project's IP log.
  10. *
  11. * This program and the accompanying materials are made available
  12. * under the terms of the Eclipse Distribution License v1.0 which
  13. * accompanies this distribution, is reproduced below, and is
  14. * available at http://www.eclipse.org/org/documents/edl-v10.php
  15. *
  16. * All rights reserved.
  17. *
  18. * Redistribution and use in source and binary forms, with or
  19. * without modification, are permitted provided that the following
  20. * conditions are met:
  21. *
  22. * - Redistributions of source code must retain the above copyright
  23. * notice, this list of conditions and the following disclaimer.
  24. *
  25. * - Redistributions in binary form must reproduce the above
  26. * copyright notice, this list of conditions and the following
  27. * disclaimer in the documentation and/or other materials provided
  28. * with the distribution.
  29. *
  30. * - Neither the name of the Eclipse Foundation, Inc. nor the
  31. * names of its contributors may be used to endorse or promote
  32. * products derived from this software without specific prior
  33. * written permission.
  34. *
  35. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  36. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  37. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  38. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  39. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  40. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  41. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  42. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  43. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  44. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  45. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  46. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  47. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  48. */
  49. package org.eclipse.jgit.storage.file;
  50. import static java.nio.charset.StandardCharsets.UTF_8;
  51. import java.io.ByteArrayOutputStream;
  52. import java.io.File;
  53. import java.io.FileNotFoundException;
  54. import java.io.IOException;
  55. import java.text.MessageFormat;
  56. import org.eclipse.jgit.errors.ConfigInvalidException;
  57. import org.eclipse.jgit.errors.LockFailedException;
  58. import org.eclipse.jgit.internal.JGitText;
  59. import org.eclipse.jgit.internal.storage.file.FileSnapshot;
  60. import org.eclipse.jgit.internal.storage.file.LockFile;
  61. import org.eclipse.jgit.lib.Config;
  62. import org.eclipse.jgit.lib.Constants;
  63. import org.eclipse.jgit.lib.ObjectId;
  64. import org.eclipse.jgit.lib.StoredConfig;
  65. import org.eclipse.jgit.util.FS;
  66. import org.eclipse.jgit.util.FileUtils;
  67. import org.eclipse.jgit.util.IO;
  68. import org.eclipse.jgit.util.RawParseUtils;
  69. import org.slf4j.Logger;
  70. import org.slf4j.LoggerFactory;
  71. /**
  72. * The configuration file that is stored in the file of the file system.
  73. */
  74. public class FileBasedConfig extends StoredConfig {
  75. private final static Logger LOG = LoggerFactory
  76. .getLogger(FileBasedConfig.class);
  77. private final File configFile;
  78. private final FS fs;
  79. private boolean utf8Bom;
  80. private volatile FileSnapshot snapshot;
  81. private volatile ObjectId hash;
  82. /**
  83. * Create a configuration with no default fallback.
  84. *
  85. * @param cfgLocation
  86. * the location of the configuration file on the file system
  87. * @param fs
  88. * the file system abstraction which will be necessary to perform
  89. * certain file system operations.
  90. */
  91. public FileBasedConfig(File cfgLocation, FS fs) {
  92. this(null, cfgLocation, fs);
  93. }
  94. /**
  95. * The constructor
  96. *
  97. * @param base
  98. * the base configuration file
  99. * @param cfgLocation
  100. * the location of the configuration file on the file system
  101. * @param fs
  102. * the file system abstraction which will be necessary to perform
  103. * certain file system operations.
  104. */
  105. public FileBasedConfig(Config base, File cfgLocation, FS fs) {
  106. super(base);
  107. configFile = cfgLocation;
  108. this.fs = fs;
  109. this.snapshot = FileSnapshot.DIRTY;
  110. this.hash = ObjectId.zeroId();
  111. }
  112. /** {@inheritDoc} */
  113. @Override
  114. protected boolean notifyUponTransientChanges() {
  115. // we will notify listeners upon save()
  116. return false;
  117. }
  118. /**
  119. * Get location of the configuration file on disk
  120. *
  121. * @return location of the configuration file on disk
  122. */
  123. public final File getFile() {
  124. return configFile;
  125. }
  126. /**
  127. * {@inheritDoc}
  128. * <p>
  129. * Load the configuration as a Git text style configuration file.
  130. * <p>
  131. * If the file does not exist, this configuration is cleared, and thus
  132. * behaves the same as though the file exists, but is empty.
  133. */
  134. @Override
  135. public void load() throws IOException, ConfigInvalidException {
  136. load(true);
  137. }
  138. /**
  139. * Load the configuration as a Git text style configuration file.
  140. * <p>
  141. * If the file does not exist, this configuration is cleared, and thus
  142. * behaves the same as though the file exists, but is empty.
  143. *
  144. * @param useFileSnapshotWithConfig
  145. * if {@code true} use the FileSnapshot with config, otherwise
  146. * use it without config
  147. * @throws IOException
  148. * if IO failed
  149. * @throws ConfigInvalidException
  150. * if config is invalid
  151. * @since 5.1.9
  152. */
  153. public void load(boolean useFileSnapshotWithConfig)
  154. throws IOException, ConfigInvalidException {
  155. final int maxStaleRetries = 5;
  156. int retries = 0;
  157. while (true) {
  158. final FileSnapshot oldSnapshot = snapshot;
  159. final FileSnapshot newSnapshot;
  160. if (useFileSnapshotWithConfig) {
  161. newSnapshot = FileSnapshot.save(getFile());
  162. } else {
  163. // don't use config in this snapshot to avoid endless recursion
  164. newSnapshot = FileSnapshot.saveNoConfig(getFile());
  165. }
  166. try {
  167. final byte[] in = IO.readFully(getFile());
  168. final ObjectId newHash = hash(in);
  169. if (hash.equals(newHash)) {
  170. if (oldSnapshot.equals(newSnapshot)) {
  171. oldSnapshot.setClean(newSnapshot);
  172. } else {
  173. snapshot = newSnapshot;
  174. }
  175. } else {
  176. final String decoded;
  177. if (isUtf8(in)) {
  178. decoded = RawParseUtils.decode(UTF_8,
  179. in, 3, in.length);
  180. utf8Bom = true;
  181. } else {
  182. decoded = RawParseUtils.decode(in);
  183. }
  184. fromText(decoded);
  185. snapshot = newSnapshot;
  186. hash = newHash;
  187. }
  188. return;
  189. } catch (FileNotFoundException noFile) {
  190. if (configFile.exists()) {
  191. throw noFile;
  192. }
  193. clear();
  194. snapshot = newSnapshot;
  195. return;
  196. } catch (IOException e) {
  197. if (FileUtils.isStaleFileHandle(e)
  198. && retries < maxStaleRetries) {
  199. if (LOG.isDebugEnabled()) {
  200. LOG.debug(MessageFormat.format(
  201. JGitText.get().configHandleIsStale,
  202. Integer.valueOf(retries)), e);
  203. }
  204. retries++;
  205. continue;
  206. }
  207. throw new IOException(MessageFormat
  208. .format(JGitText.get().cannotReadFile, getFile()), e);
  209. } catch (ConfigInvalidException e) {
  210. throw new ConfigInvalidException(MessageFormat
  211. .format(JGitText.get().cannotReadFile, getFile()), e);
  212. }
  213. }
  214. }
  215. /**
  216. * {@inheritDoc}
  217. * <p>
  218. * Save the configuration as a Git text style configuration file.
  219. * <p>
  220. * <b>Warning:</b> Although this method uses the traditional Git file
  221. * locking approach to protect against concurrent writes of the
  222. * configuration file, it does not ensure that the file has not been
  223. * modified since the last read, which means updates performed by other
  224. * objects accessing the same backing file may be lost.
  225. */
  226. @Override
  227. public void save() throws IOException {
  228. final byte[] out;
  229. final String text = toText();
  230. if (utf8Bom) {
  231. final ByteArrayOutputStream bos = new ByteArrayOutputStream();
  232. bos.write(0xEF);
  233. bos.write(0xBB);
  234. bos.write(0xBF);
  235. bos.write(text.getBytes(UTF_8));
  236. out = bos.toByteArray();
  237. } else {
  238. out = Constants.encode(text);
  239. }
  240. final LockFile lf = new LockFile(getFile());
  241. if (!lf.lock())
  242. throw new LockFailedException(getFile());
  243. try {
  244. lf.setNeedSnapshot(true);
  245. lf.write(out);
  246. if (!lf.commit())
  247. throw new IOException(MessageFormat.format(JGitText.get().cannotCommitWriteTo, getFile()));
  248. } finally {
  249. lf.unlock();
  250. }
  251. snapshot = lf.getCommitSnapshot();
  252. hash = hash(out);
  253. // notify the listeners
  254. fireConfigChangedEvent();
  255. }
  256. /** {@inheritDoc} */
  257. @Override
  258. public void clear() {
  259. hash = hash(new byte[0]);
  260. super.clear();
  261. }
  262. private static ObjectId hash(byte[] rawText) {
  263. return ObjectId.fromRaw(Constants.newMessageDigest().digest(rawText));
  264. }
  265. /** {@inheritDoc} */
  266. @SuppressWarnings("nls")
  267. @Override
  268. public String toString() {
  269. return getClass().getSimpleName() + "[" + getFile().getPath() + "]";
  270. }
  271. /**
  272. * Whether the currently loaded configuration file is outdated
  273. *
  274. * @return returns true if the currently loaded configuration file is older
  275. * than the file on disk
  276. */
  277. public boolean isOutdated() {
  278. return snapshot.isModified(getFile());
  279. }
  280. /**
  281. * {@inheritDoc}
  282. *
  283. * @since 4.10
  284. */
  285. @Override
  286. protected byte[] readIncludedConfig(String relPath)
  287. throws ConfigInvalidException {
  288. final File file;
  289. if (relPath.startsWith("~/")) { //$NON-NLS-1$
  290. file = fs.resolve(fs.userHome(), relPath.substring(2));
  291. } else {
  292. file = fs.resolve(configFile.getParentFile(), relPath);
  293. }
  294. if (!file.exists()) {
  295. return null;
  296. }
  297. try {
  298. return IO.readFully(file);
  299. } catch (IOException ioe) {
  300. throw new ConfigInvalidException(MessageFormat
  301. .format(JGitText.get().cannotReadFile, relPath), ioe);
  302. }
  303. }
  304. }