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