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 org.eclipse.jgit.lib.Constants.CHARSET;
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 = FileSnapshot.save(getFile());
157 			try {
158 				final byte[] in = IO.readFully(getFile());
159 				final ObjectId newHash = hash(in);
160 				if (hash.equals(newHash)) {
161 					if (oldSnapshot.equals(newSnapshot)) {
162 						oldSnapshot.setClean(newSnapshot);
163 					} else {
164 						snapshot = newSnapshot;
165 					}
166 				} else {
167 					final String decoded;
168 					if (isUtf8(in)) {
169 						decoded = RawParseUtils.decode(CHARSET,
170 								in, 3, in.length);
171 						utf8Bom = true;
172 					} else {
173 						decoded = RawParseUtils.decode(in);
174 					}
175 					fromText(decoded);
176 					snapshot = newSnapshot;
177 					hash = newHash;
178 				}
179 				return;
180 			} catch (FileNotFoundException noFile) {
181 				if (configFile.exists()) {
182 					throw noFile;
183 				}
184 				clear();
185 				snapshot = newSnapshot;
186 				return;
187 			} catch (IOException e) {
188 				if (FileUtils.isStaleFileHandle(e)
189 						&& retries < maxStaleRetries) {
190 					if (LOG.isDebugEnabled()) {
191 						LOG.debug(MessageFormat.format(
192 								JGitText.get().configHandleIsStale,
193 								Integer.valueOf(retries)), e);
194 					}
195 					retries++;
196 					continue;
197 				}
198 				throw new IOException(MessageFormat
199 						.format(JGitText.get().cannotReadFile, getFile()), e);
200 			} catch (ConfigInvalidException e) {
201 				throw new ConfigInvalidException(MessageFormat
202 						.format(JGitText.get().cannotReadFile, getFile()), e);
203 			}
204 		}
205 	}
206 
207 	/**
208 	 * {@inheritDoc}
209 	 * <p>
210 	 * Save the configuration as a Git text style configuration file.
211 	 * <p>
212 	 * <b>Warning:</b> Although this method uses the traditional Git file
213 	 * locking approach to protect against concurrent writes of the
214 	 * configuration file, it does not ensure that the file has not been
215 	 * modified since the last read, which means updates performed by other
216 	 * objects accessing the same backing file may be lost.
217 	 */
218 	@Override
219 	public void save() throws IOException {
220 		final byte[] out;
221 		final String text = toText();
222 		if (utf8Bom) {
223 			final ByteArrayOutputStream bos = new ByteArrayOutputStream();
224 			bos.write(0xEF);
225 			bos.write(0xBB);
226 			bos.write(0xBF);
227 			bos.write(text.getBytes(CHARSET));
228 			out = bos.toByteArray();
229 		} else {
230 			out = Constants.encode(text);
231 		}
232 
233 		final LockFile lf = new LockFile(getFile());
234 		if (!lf.lock())
235 			throw new LockFailedException(getFile());
236 		try {
237 			lf.setNeedSnapshot(true);
238 			lf.write(out);
239 			if (!lf.commit())
240 				throw new IOException(MessageFormat.format(JGitText.get().cannotCommitWriteTo, getFile()));
241 		} finally {
242 			lf.unlock();
243 		}
244 		snapshot = lf.getCommitSnapshot();
245 		hash = hash(out);
246 		// notify the listeners
247 		fireConfigChangedEvent();
248 	}
249 
250 	/** {@inheritDoc} */
251 	@Override
252 	public void clear() {
253 		hash = hash(new byte[0]);
254 		super.clear();
255 	}
256 
257 	private static ObjectId hash(byte[] rawText) {
258 		return ObjectId.fromRaw(Constants.newMessageDigest().digest(rawText));
259 	}
260 
261 	/** {@inheritDoc} */
262 	@SuppressWarnings("nls")
263 	@Override
264 	public String toString() {
265 		return getClass().getSimpleName() + "[" + getFile().getPath() + "]";
266 	}
267 
268 	/**
269 	 * Whether the currently loaded configuration file is outdated
270 	 *
271 	 * @return returns true if the currently loaded configuration file is older
272 	 *         than the file on disk
273 	 */
274 	public boolean isOutdated() {
275 		return snapshot.isModified(getFile());
276 	}
277 
278 	/**
279 	 * {@inheritDoc}
280 	 *
281 	 * @since 4.10
282 	 */
283 	@Override
284 	@Nullable
285 	protected byte[] readIncludedConfig(String relPath)
286 			throws ConfigInvalidException {
287 		final File file;
288 		if (relPath.startsWith("~/")) { //$NON-NLS-1$
289 			file = fs.resolve(fs.userHome(), relPath.substring(2));
290 		} else {
291 			file = fs.resolve(configFile.getParentFile(), relPath);
292 		}
293 
294 		if (!file.exists()) {
295 			return null;
296 		}
297 
298 		try {
299 			return IO.readFully(file);
300 		} catch (IOException ioe) {
301 			throw new ConfigInvalidException(MessageFormat
302 					.format(JGitText.get().cannotReadFile, relPath), ioe);
303 		}
304 	}
305 }