您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

FileBasedConfig.java 9.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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.annotations.Nullable;
  57. import org.eclipse.jgit.errors.ConfigInvalidException;
  58. import org.eclipse.jgit.errors.LockFailedException;
  59. import org.eclipse.jgit.internal.JGitText;
  60. import org.eclipse.jgit.internal.storage.file.FileSnapshot;
  61. import org.eclipse.jgit.internal.storage.file.LockFile;
  62. import org.eclipse.jgit.lib.Config;
  63. import org.eclipse.jgit.lib.Constants;
  64. import org.eclipse.jgit.lib.ObjectId;
  65. import org.eclipse.jgit.lib.StoredConfig;
  66. import org.eclipse.jgit.util.FS;
  67. import org.eclipse.jgit.util.FileUtils;
  68. import org.eclipse.jgit.util.IO;
  69. import org.eclipse.jgit.util.RawParseUtils;
  70. import org.slf4j.Logger;
  71. import org.slf4j.LoggerFactory;
  72. /**
  73. * The configuration file that is stored in the file of the file system.
  74. */
  75. public class FileBasedConfig extends StoredConfig {
  76. private final static Logger LOG = LoggerFactory
  77. .getLogger(FileBasedConfig.class);
  78. private final File configFile;
  79. private final FS fs;
  80. private boolean utf8Bom;
  81. private volatile FileSnapshot snapshot;
  82. private volatile ObjectId hash;
  83. /**
  84. * Create a configuration with no default fallback.
  85. *
  86. * @param cfgLocation
  87. * the location of the configuration file on the file system
  88. * @param fs
  89. * the file system abstraction which will be necessary to perform
  90. * certain file system operations.
  91. */
  92. public FileBasedConfig(File cfgLocation, FS fs) {
  93. this(null, cfgLocation, fs);
  94. }
  95. /**
  96. * The constructor
  97. *
  98. * @param base
  99. * the base configuration file
  100. * @param cfgLocation
  101. * the location of the configuration file on the file system
  102. * @param fs
  103. * the file system abstraction which will be necessary to perform
  104. * certain file system operations.
  105. */
  106. public FileBasedConfig(Config base, File cfgLocation, FS fs) {
  107. super(base);
  108. configFile = cfgLocation;
  109. this.fs = fs;
  110. this.snapshot = FileSnapshot.DIRTY;
  111. this.hash = ObjectId.zeroId();
  112. }
  113. /** {@inheritDoc} */
  114. @Override
  115. protected boolean notifyUponTransientChanges() {
  116. // we will notify listeners upon save()
  117. return false;
  118. }
  119. /**
  120. * Get location of the configuration file on disk
  121. *
  122. * @return location of the configuration file on disk
  123. */
  124. public final File getFile() {
  125. return configFile;
  126. }
  127. /**
  128. * {@inheritDoc}
  129. * <p>
  130. * Load the configuration as a Git text style configuration file.
  131. * <p>
  132. * If the file does not exist, this configuration is cleared, and thus
  133. * behaves the same as though the file exists, but is empty.
  134. */
  135. @Override
  136. public void load() throws IOException, ConfigInvalidException {
  137. load(true);
  138. }
  139. /**
  140. * Load the configuration as a Git text style configuration file.
  141. * <p>
  142. * If the file does not exist, this configuration is cleared, and thus
  143. * behaves the same as though the file exists, but is empty.
  144. *
  145. * @param useFileSnapshotWithConfig
  146. * if {@code true} use the FileSnapshot with config, otherwise
  147. * use it without config
  148. * @throws IOException
  149. * if IO failed
  150. * @throws ConfigInvalidException
  151. * if config is invalid
  152. * @since 5.1.9
  153. */
  154. public void load(boolean useFileSnapshotWithConfig)
  155. throws IOException, ConfigInvalidException {
  156. final int maxStaleRetries = 5;
  157. int retries = 0;
  158. while (true) {
  159. final FileSnapshot oldSnapshot = snapshot;
  160. final FileSnapshot newSnapshot;
  161. if (useFileSnapshotWithConfig) {
  162. newSnapshot = FileSnapshot.save(getFile());
  163. } else {
  164. // don't use config in this snapshot to avoid endless recursion
  165. newSnapshot = FileSnapshot.saveNoConfig(getFile());
  166. }
  167. try {
  168. final byte[] in = IO.readFully(getFile());
  169. final ObjectId newHash = hash(in);
  170. if (hash.equals(newHash)) {
  171. if (oldSnapshot.equals(newSnapshot)) {
  172. oldSnapshot.setClean(newSnapshot);
  173. } else {
  174. snapshot = newSnapshot;
  175. }
  176. } else {
  177. final String decoded;
  178. if (isUtf8(in)) {
  179. decoded = RawParseUtils.decode(UTF_8,
  180. in, 3, in.length);
  181. utf8Bom = true;
  182. } else {
  183. decoded = RawParseUtils.decode(in);
  184. }
  185. fromText(decoded);
  186. snapshot = newSnapshot;
  187. hash = newHash;
  188. }
  189. return;
  190. } catch (FileNotFoundException noFile) {
  191. if (configFile.exists()) {
  192. throw noFile;
  193. }
  194. clear();
  195. snapshot = newSnapshot;
  196. return;
  197. } catch (IOException e) {
  198. if (FileUtils.isStaleFileHandle(e)
  199. && retries < maxStaleRetries) {
  200. if (LOG.isDebugEnabled()) {
  201. LOG.debug(MessageFormat.format(
  202. JGitText.get().configHandleIsStale,
  203. Integer.valueOf(retries)), e);
  204. }
  205. retries++;
  206. continue;
  207. }
  208. throw new IOException(MessageFormat
  209. .format(JGitText.get().cannotReadFile, getFile()), e);
  210. } catch (ConfigInvalidException e) {
  211. throw new ConfigInvalidException(MessageFormat
  212. .format(JGitText.get().cannotReadFile, getFile()), e);
  213. }
  214. }
  215. }
  216. /**
  217. * {@inheritDoc}
  218. * <p>
  219. * Save the configuration as a Git text style configuration file.
  220. * <p>
  221. * <b>Warning:</b> Although this method uses the traditional Git file
  222. * locking approach to protect against concurrent writes of the
  223. * configuration file, it does not ensure that the file has not been
  224. * modified since the last read, which means updates performed by other
  225. * objects accessing the same backing file may be lost.
  226. */
  227. @Override
  228. public void save() throws IOException {
  229. final byte[] out;
  230. final String text = toText();
  231. if (utf8Bom) {
  232. final ByteArrayOutputStream bos = new ByteArrayOutputStream();
  233. bos.write(0xEF);
  234. bos.write(0xBB);
  235. bos.write(0xBF);
  236. bos.write(text.getBytes(UTF_8));
  237. out = bos.toByteArray();
  238. } else {
  239. out = Constants.encode(text);
  240. }
  241. final LockFile lf = new LockFile(getFile());
  242. if (!lf.lock())
  243. throw new LockFailedException(getFile());
  244. try {
  245. lf.setNeedSnapshot(true);
  246. lf.write(out);
  247. if (!lf.commit())
  248. throw new IOException(MessageFormat.format(JGitText.get().cannotCommitWriteTo, getFile()));
  249. } finally {
  250. lf.unlock();
  251. }
  252. snapshot = lf.getCommitSnapshot();
  253. hash = hash(out);
  254. // notify the listeners
  255. fireConfigChangedEvent();
  256. }
  257. /** {@inheritDoc} */
  258. @Override
  259. public void clear() {
  260. hash = hash(new byte[0]);
  261. super.clear();
  262. }
  263. private static ObjectId hash(byte[] rawText) {
  264. return ObjectId.fromRaw(Constants.newMessageDigest().digest(rawText));
  265. }
  266. /** {@inheritDoc} */
  267. @SuppressWarnings("nls")
  268. @Override
  269. public String toString() {
  270. return getClass().getSimpleName() + "[" + getFile().getPath() + "]";
  271. }
  272. /**
  273. * Whether the currently loaded configuration file is outdated
  274. *
  275. * @return returns true if the currently loaded configuration file is older
  276. * than the file on disk
  277. */
  278. public boolean isOutdated() {
  279. return snapshot.isModified(getFile());
  280. }
  281. /**
  282. * {@inheritDoc}
  283. *
  284. * @since 4.10
  285. */
  286. @Override
  287. @Nullable
  288. protected byte[] readIncludedConfig(String relPath)
  289. throws ConfigInvalidException {
  290. final File file;
  291. if (relPath.startsWith("~/")) { //$NON-NLS-1$
  292. file = fs.resolve(fs.userHome(), relPath.substring(2));
  293. } else {
  294. file = fs.resolve(configFile.getParentFile(), relPath);
  295. }
  296. if (!file.exists()) {
  297. return null;
  298. }
  299. try {
  300. return IO.readFully(file);
  301. } catch (IOException ioe) {
  302. throw new ConfigInvalidException(MessageFormat
  303. .format(JGitText.get().cannotReadFile, relPath), ioe);
  304. }
  305. }
  306. }