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