View Javadoc
1   /*
2    * Copyright (C) 2007, Dave Watson <dwatson@mimvista.com>
3    * Copyright (C) 2008-2010, Google Inc.
4    * Copyright (C) 2006-2010, Robin Rosenberg <robin.rosenberg@dewire.com>
5    * Copyright (C) 2006-2012, Shawn O. Pearce <spearce@spearce.org>
6    * Copyright (C) 2012, Daniel Megert <daniel_megert@ch.ibm.com>
7    * Copyright (C) 2017, Wim Jongman <wim.jongman@remainsoftware.com>
8    * and other copyright owners as documented in the project's IP log.
9    *
10   * This program and the accompanying materials are made available
11   * under the terms of the Eclipse Distribution License v1.0 which
12   * accompanies this distribution, is reproduced below, and is
13   * available at http://www.eclipse.org/org/documents/edl-v10.php
14   *
15   * All rights reserved.
16   *
17   * Redistribution and use in source and binary forms, with or
18   * without modification, are permitted provided that the following
19   * conditions are met:
20   *
21   * - Redistributions of source code must retain the above copyright
22   *   notice, this list of conditions and the following disclaimer.
23   *
24   * - Redistributions in binary form must reproduce the above
25   *   copyright notice, this list of conditions and the following
26   *   disclaimer in the documentation and/or other materials provided
27   *   with the distribution.
28   *
29   * - Neither the name of the Eclipse Foundation, Inc. nor the
30   *   names of its contributors may be used to endorse or promote
31   *   products derived from this software without specific prior
32   *   written permission.
33   *
34   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
35   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
36   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
38   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
39   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
41   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
42   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
43   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
44   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
45   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
46   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
47   */
48  
49  package org.eclipse.jgit.lib;
50  
51  import static org.eclipse.jgit.lib.Constants.LOCK_SUFFIX;
52  import static java.nio.charset.StandardCharsets.UTF_8;
53  
54  import java.io.BufferedOutputStream;
55  import java.io.File;
56  import java.io.FileNotFoundException;
57  import java.io.FileOutputStream;
58  import java.io.IOException;
59  import java.io.OutputStream;
60  import java.io.UncheckedIOException;
61  import java.net.URISyntaxException;
62  import java.text.MessageFormat;
63  import java.util.Collection;
64  import java.util.Collections;
65  import java.util.HashMap;
66  import java.util.HashSet;
67  import java.util.LinkedList;
68  import java.util.List;
69  import java.util.Map;
70  import java.util.Set;
71  import java.util.concurrent.atomic.AtomicInteger;
72  import java.util.concurrent.atomic.AtomicLong;
73  import java.util.regex.Pattern;
74  
75  import org.eclipse.jgit.annotations.NonNull;
76  import org.eclipse.jgit.annotations.Nullable;
77  import org.eclipse.jgit.attributes.AttributesNodeProvider;
78  import org.eclipse.jgit.dircache.DirCache;
79  import org.eclipse.jgit.errors.AmbiguousObjectException;
80  import org.eclipse.jgit.errors.CorruptObjectException;
81  import org.eclipse.jgit.errors.IncorrectObjectTypeException;
82  import org.eclipse.jgit.errors.MissingObjectException;
83  import org.eclipse.jgit.errors.NoWorkTreeException;
84  import org.eclipse.jgit.errors.RevisionSyntaxException;
85  import org.eclipse.jgit.events.IndexChangedEvent;
86  import org.eclipse.jgit.events.IndexChangedListener;
87  import org.eclipse.jgit.events.ListenerList;
88  import org.eclipse.jgit.events.RepositoryEvent;
89  import org.eclipse.jgit.internal.JGitText;
90  import org.eclipse.jgit.revwalk.RevBlob;
91  import org.eclipse.jgit.revwalk.RevCommit;
92  import org.eclipse.jgit.revwalk.RevObject;
93  import org.eclipse.jgit.revwalk.RevTree;
94  import org.eclipse.jgit.revwalk.RevWalk;
95  import org.eclipse.jgit.transport.RefSpec;
96  import org.eclipse.jgit.transport.RemoteConfig;
97  import org.eclipse.jgit.treewalk.TreeWalk;
98  import org.eclipse.jgit.util.FS;
99  import org.eclipse.jgit.util.FileUtils;
100 import org.eclipse.jgit.util.IO;
101 import org.eclipse.jgit.util.RawParseUtils;
102 import org.eclipse.jgit.util.SystemReader;
103 import org.slf4j.Logger;
104 import org.slf4j.LoggerFactory;
105 
106 /**
107  * Represents a Git repository.
108  * <p>
109  * A repository holds all objects and refs used for managing source code (could
110  * be any type of file, but source code is what SCM's are typically used for).
111  * <p>
112  * The thread-safety of a {@link org.eclipse.jgit.lib.Repository} very much
113  * depends on the concrete implementation. Applications working with a generic
114  * {@code Repository} type must not assume the instance is thread-safe.
115  * <ul>
116  * <li>{@code FileRepository} is thread-safe.
117  * <li>{@code DfsRepository} thread-safety is determined by its subclass.
118  * </ul>
119  */
120 public abstract class Repository implements AutoCloseable {
121 	private static final Logger LOG = LoggerFactory.getLogger(Repository.class);
122 	private static final ListenerLististenerList">ListenerList globalListeners = new ListenerList();
123 
124 	/**
125 	 * Branch names containing slashes should not have a name component that is
126 	 * one of the reserved device names on Windows.
127 	 *
128 	 * @see #normalizeBranchName(String)
129 	 */
130 	private static final Pattern FORBIDDEN_BRANCH_NAME_COMPONENTS = Pattern
131 			.compile(
132 					"(^|/)(aux|com[1-9]|con|lpt[1-9]|nul|prn)(\\.[^/]*)?", //$NON-NLS-1$
133 					Pattern.CASE_INSENSITIVE);
134 
135 	/**
136 	 * Get the global listener list observing all events in this JVM.
137 	 *
138 	 * @return the global listener list observing all events in this JVM.
139 	 */
140 	public static ListenerList getGlobalListenerList() {
141 		return globalListeners;
142 	}
143 
144 	/** Use counter */
145 	final AtomicInteger useCnt = new AtomicInteger(1);
146 
147 	final AtomicLong closedAt = new AtomicLong();
148 
149 	/** Metadata directory holding the repository's critical files. */
150 	private final File gitDir;
151 
152 	/** File abstraction used to resolve paths. */
153 	private final FS fs;
154 
155 	private final ListenerListml#ListenerList">ListenerList myListeners = new ListenerList();
156 
157 	/** If not bare, the top level directory of the working files. */
158 	private final File workTree;
159 
160 	/** If not bare, the index file caching the working file states. */
161 	private final File indexFile;
162 
163 	/**
164 	 * Initialize a new repository instance.
165 	 *
166 	 * @param options
167 	 *            options to configure the repository.
168 	 */
169 	protected Repository(BaseRepositoryBuilder options) {
170 		gitDir = options.getGitDir();
171 		fs = options.getFS();
172 		workTree = options.getWorkTree();
173 		indexFile = options.getIndexFile();
174 	}
175 
176 	/**
177 	 * Get listeners observing only events on this repository.
178 	 *
179 	 * @return listeners observing only events on this repository.
180 	 */
181 	@NonNull
182 	public ListenerList getListenerList() {
183 		return myListeners;
184 	}
185 
186 	/**
187 	 * Fire an event to all registered listeners.
188 	 * <p>
189 	 * The source repository of the event is automatically set to this
190 	 * repository, before the event is delivered to any listeners.
191 	 *
192 	 * @param event
193 	 *            the event to deliver.
194 	 */
195 	public void fireEvent(RepositoryEvent<?> event) {
196 		event.setRepository(this);
197 		myListeners.dispatch(event);
198 		globalListeners.dispatch(event);
199 	}
200 
201 	/**
202 	 * Create a new Git repository.
203 	 * <p>
204 	 * Repository with working tree is created using this method. This method is
205 	 * the same as {@code create(false)}.
206 	 *
207 	 * @throws java.io.IOException
208 	 * @see #create(boolean)
209 	 */
210 	public void create() throws IOException {
211 		create(false);
212 	}
213 
214 	/**
215 	 * Create a new Git repository initializing the necessary files and
216 	 * directories.
217 	 *
218 	 * @param bare
219 	 *            if true, a bare repository (a repository without a working
220 	 *            directory) is created.
221 	 * @throws java.io.IOException
222 	 *             in case of IO problem
223 	 */
224 	public abstract void create(boolean bare) throws IOException;
225 
226 	/**
227 	 * Get local metadata directory
228 	 *
229 	 * @return local metadata directory; {@code null} if repository isn't local.
230 	 */
231 	/*
232 	 * TODO This method should be annotated as Nullable, because in some
233 	 * specific configurations metadata is not located in the local file system
234 	 * (for example in memory databases). In "usual" repositories this
235 	 * annotation would only cause compiler errors at places where the actual
236 	 * directory can never be null.
237 	 */
238 	public File getDirectory() {
239 		return gitDir;
240 	}
241 
242 	/**
243 	 * Get the object database which stores this repository's data.
244 	 *
245 	 * @return the object database which stores this repository's data.
246 	 */
247 	@NonNull
248 	public abstract ObjectDatabase getObjectDatabase();
249 
250 	/**
251 	 * Create a new inserter to create objects in {@link #getObjectDatabase()}.
252 	 *
253 	 * @return a new inserter to create objects in {@link #getObjectDatabase()}.
254 	 */
255 	@NonNull
256 	public ObjectInserter newObjectInserter() {
257 		return getObjectDatabase().newInserter();
258 	}
259 
260 	/**
261 	 * Create a new reader to read objects from {@link #getObjectDatabase()}.
262 	 *
263 	 * @return a new reader to read objects from {@link #getObjectDatabase()}.
264 	 */
265 	@NonNull
266 	public ObjectReader newObjectReader() {
267 		return getObjectDatabase().newReader();
268 	}
269 
270 	/**
271 	 * Get the reference database which stores the reference namespace.
272 	 *
273 	 * @return the reference database which stores the reference namespace.
274 	 */
275 	@NonNull
276 	public abstract RefDatabase getRefDatabase();
277 
278 	/**
279 	 * Get the configuration of this repository.
280 	 *
281 	 * @return the configuration of this repository.
282 	 */
283 	@NonNull
284 	public abstract StoredConfig getConfig();
285 
286 	/**
287 	 * Create a new {@link org.eclipse.jgit.attributes.AttributesNodeProvider}.
288 	 *
289 	 * @return a new {@link org.eclipse.jgit.attributes.AttributesNodeProvider}.
290 	 *         This {@link org.eclipse.jgit.attributes.AttributesNodeProvider}
291 	 *         is lazy loaded only once. It means that it will not be updated
292 	 *         after loading. Prefer creating new instance for each use.
293 	 * @since 4.2
294 	 */
295 	@NonNull
296 	public abstract AttributesNodeProvider createAttributesNodeProvider();
297 
298 	/**
299 	 * Get the used file system abstraction.
300 	 *
301 	 * @return the used file system abstraction, or {@code null} if
302 	 *         repository isn't local.
303 	 */
304 	/*
305 	 * TODO This method should be annotated as Nullable, because in some
306 	 * specific configurations metadata is not located in the local file system
307 	 * (for example in memory databases). In "usual" repositories this
308 	 * annotation would only cause compiler errors at places where the actual
309 	 * directory can never be null.
310 	 */
311 	public FS getFS() {
312 		return fs;
313 	}
314 
315 	/**
316 	 * Whether the specified object is stored in this repo or any of the known
317 	 * shared repositories.
318 	 *
319 	 * @param objectId
320 	 *            a {@link org.eclipse.jgit.lib.AnyObjectId} object.
321 	 * @return true if the specified object is stored in this repo or any of the
322 	 *         known shared repositories.
323 	 * @deprecated use {@code getObjectDatabase().has(objectId)}
324 	 */
325 	@Deprecated
326 	public boolean hasObject(AnyObjectId objectId) {
327 		try {
328 			return getObjectDatabase().has(objectId);
329 		} catch (IOException e) {
330 			throw new UncheckedIOException(e);
331 		}
332 	}
333 
334 	/**
335 	 * Open an object from this repository.
336 	 * <p>
337 	 * This is a one-shot call interface which may be faster than allocating a
338 	 * {@link #newObjectReader()} to perform the lookup.
339 	 *
340 	 * @param objectId
341 	 *            identity of the object to open.
342 	 * @return a {@link org.eclipse.jgit.lib.ObjectLoader} for accessing the
343 	 *         object.
344 	 * @throws org.eclipse.jgit.errors.MissingObjectException
345 	 *             the object does not exist.
346 	 * @throws java.io.IOException
347 	 *             the object store cannot be accessed.
348 	 */
349 	@NonNull
350 	public ObjectLoader open(AnyObjectId objectId)
351 			throws MissingObjectException, IOException {
352 		return getObjectDatabase().open(objectId);
353 	}
354 
355 	/**
356 	 * Open an object from this repository.
357 	 * <p>
358 	 * This is a one-shot call interface which may be faster than allocating a
359 	 * {@link #newObjectReader()} to perform the lookup.
360 	 *
361 	 * @param objectId
362 	 *            identity of the object to open.
363 	 * @param typeHint
364 	 *            hint about the type of object being requested, e.g.
365 	 *            {@link org.eclipse.jgit.lib.Constants#OBJ_BLOB};
366 	 *            {@link org.eclipse.jgit.lib.ObjectReader#OBJ_ANY} if the
367 	 *            object type is not known, or does not matter to the caller.
368 	 * @return a {@link org.eclipse.jgit.lib.ObjectLoader} for accessing the
369 	 *         object.
370 	 * @throws org.eclipse.jgit.errors.MissingObjectException
371 	 *             the object does not exist.
372 	 * @throws org.eclipse.jgit.errors.IncorrectObjectTypeException
373 	 *             typeHint was not OBJ_ANY, and the object's actual type does
374 	 *             not match typeHint.
375 	 * @throws java.io.IOException
376 	 *             the object store cannot be accessed.
377 	 */
378 	@NonNull
379 	public ObjectLoader open(AnyObjectId objectId, int typeHint)
380 			throws MissingObjectException, IncorrectObjectTypeException,
381 			IOException {
382 		return getObjectDatabase().open(objectId, typeHint);
383 	}
384 
385 	/**
386 	 * Create a command to update, create or delete a ref in this repository.
387 	 *
388 	 * @param ref
389 	 *            name of the ref the caller wants to modify.
390 	 * @return an update command. The caller must finish populating this command
391 	 *         and then invoke one of the update methods to actually make a
392 	 *         change.
393 	 * @throws java.io.IOException
394 	 *             a symbolic ref was passed in and could not be resolved back
395 	 *             to the base ref, as the symbolic ref could not be read.
396 	 */
397 	@NonNull
398 	public RefUpdate updateRef(String ref) throws IOException {
399 		return updateRef(ref, false);
400 	}
401 
402 	/**
403 	 * Create a command to update, create or delete a ref in this repository.
404 	 *
405 	 * @param ref
406 	 *            name of the ref the caller wants to modify.
407 	 * @param detach
408 	 *            true to create a detached head
409 	 * @return an update command. The caller must finish populating this command
410 	 *         and then invoke one of the update methods to actually make a
411 	 *         change.
412 	 * @throws java.io.IOException
413 	 *             a symbolic ref was passed in and could not be resolved back
414 	 *             to the base ref, as the symbolic ref could not be read.
415 	 */
416 	@NonNull
417 	public RefUpdate updateRef(String ref, boolean detach) throws IOException {
418 		return getRefDatabase().newUpdate(ref, detach);
419 	}
420 
421 	/**
422 	 * Create a command to rename a ref in this repository
423 	 *
424 	 * @param fromRef
425 	 *            name of ref to rename from
426 	 * @param toRef
427 	 *            name of ref to rename to
428 	 * @return an update command that knows how to rename a branch to another.
429 	 * @throws java.io.IOException
430 	 *             the rename could not be performed.
431 	 */
432 	@NonNull
433 	public RefRename renameRef(String fromRef, String toRef) throws IOException {
434 		return getRefDatabase().newRename(fromRef, toRef);
435 	}
436 
437 	/**
438 	 * Parse a git revision string and return an object id.
439 	 *
440 	 * Combinations of these operators are supported:
441 	 * <ul>
442 	 * <li><b>HEAD</b>, <b>MERGE_HEAD</b>, <b>FETCH_HEAD</b></li>
443 	 * <li><b>SHA-1</b>: a complete or abbreviated SHA-1</li>
444 	 * <li><b>refs/...</b>: a complete reference name</li>
445 	 * <li><b>short-name</b>: a short reference name under {@code refs/heads},
446 	 * {@code refs/tags}, or {@code refs/remotes} namespace</li>
447 	 * <li><b>tag-NN-gABBREV</b>: output from describe, parsed by treating
448 	 * {@code ABBREV} as an abbreviated SHA-1.</li>
449 	 * <li><i>id</i><b>^</b>: first parent of commit <i>id</i>, this is the same
450 	 * as {@code id^1}</li>
451 	 * <li><i>id</i><b>^0</b>: ensure <i>id</i> is a commit</li>
452 	 * <li><i>id</i><b>^n</b>: n-th parent of commit <i>id</i></li>
453 	 * <li><i>id</i><b>~n</b>: n-th historical ancestor of <i>id</i>, by first
454 	 * parent. {@code id~3} is equivalent to {@code id^1^1^1} or {@code id^^^}.</li>
455 	 * <li><i>id</i><b>:path</b>: Lookup path under tree named by <i>id</i></li>
456 	 * <li><i>id</i><b>^{commit}</b>: ensure <i>id</i> is a commit</li>
457 	 * <li><i>id</i><b>^{tree}</b>: ensure <i>id</i> is a tree</li>
458 	 * <li><i>id</i><b>^{tag}</b>: ensure <i>id</i> is a tag</li>
459 	 * <li><i>id</i><b>^{blob}</b>: ensure <i>id</i> is a blob</li>
460 	 * </ul>
461 	 *
462 	 * <p>
463 	 * The following operators are specified by Git conventions, but are not
464 	 * supported by this method:
465 	 * <ul>
466 	 * <li><b>ref@{n}</b>: n-th version of ref as given by its reflog</li>
467 	 * <li><b>ref@{time}</b>: value of ref at the designated time</li>
468 	 * </ul>
469 	 *
470 	 * @param revstr
471 	 *            A git object references expression
472 	 * @return an ObjectId or {@code null} if revstr can't be resolved to any
473 	 *         ObjectId
474 	 * @throws org.eclipse.jgit.errors.AmbiguousObjectException
475 	 *             {@code revstr} contains an abbreviated ObjectId and this
476 	 *             repository contains more than one object which match to the
477 	 *             input abbreviation.
478 	 * @throws org.eclipse.jgit.errors.IncorrectObjectTypeException
479 	 *             the id parsed does not meet the type required to finish
480 	 *             applying the operators in the expression.
481 	 * @throws org.eclipse.jgit.errors.RevisionSyntaxException
482 	 *             the expression is not supported by this implementation, or
483 	 *             does not meet the standard syntax.
484 	 * @throws java.io.IOException
485 	 *             on serious errors
486 	 */
487 	@Nullable
488 	public ObjectId resolve(String revstr)
489 			throws AmbiguousObjectException, IncorrectObjectTypeException,
490 			RevisionSyntaxException, IOException {
491 		try (RevWalkRevWalk.html#RevWalk">RevWalk rw = new RevWalk(this)) {
492 			Object resolved = resolve(rw, revstr);
493 			if (resolved instanceof String) {
494 				final Ref ref = findRef((String) resolved);
495 				return ref != null ? ref.getLeaf().getObjectId() : null;
496 			} else {
497 				return (ObjectId) resolved;
498 			}
499 		}
500 	}
501 
502 	/**
503 	 * Simplify an expression, but unlike {@link #resolve(String)} it will not
504 	 * resolve a branch passed or resulting from the expression, such as @{-}.
505 	 * Thus this method can be used to process an expression to a method that
506 	 * expects a branch or revision id.
507 	 *
508 	 * @param revstr a {@link java.lang.String} object.
509 	 * @return object id or ref name from resolved expression or {@code null} if
510 	 *         given expression cannot be resolved
511 	 * @throws org.eclipse.jgit.errors.AmbiguousObjectException
512 	 * @throws java.io.IOException
513 	 */
514 	@Nullable
515 	public String simplify(String revstr)
516 			throws AmbiguousObjectException, IOException {
517 		try (RevWalkRevWalk.html#RevWalk">RevWalk rw = new RevWalk(this)) {
518 			Object resolved = resolve(rw, revstr);
519 			if (resolved != null)
520 				if (resolved instanceof String)
521 					return (String) resolved;
522 				else
523 					return ((AnyObjectId) resolved).getName();
524 			return null;
525 		}
526 	}
527 
528 	@Nullable
529 	private Object resolve(RevWalk rw, String revstr)
530 			throws IOException {
531 		char[] revChars = revstr.toCharArray();
532 		RevObject rev = null;
533 		String name = null;
534 		int done = 0;
535 		for (int i = 0; i < revChars.length; ++i) {
536 			switch (revChars[i]) {
537 			case '^':
538 				if (rev == null) {
539 					if (name == null)
540 						if (done == 0)
541 							name = new String(revChars, done, i);
542 						else {
543 							done = i + 1;
544 							break;
545 						}
546 					rev = parseSimple(rw, name);
547 					name = null;
548 					if (rev == null)
549 						return null;
550 				}
551 				if (i + 1 < revChars.length) {
552 					switch (revChars[i + 1]) {
553 					case '0':
554 					case '1':
555 					case '2':
556 					case '3':
557 					case '4':
558 					case '5':
559 					case '6':
560 					case '7':
561 					case '8':
562 					case '9':
563 						int j;
564 						rev = rw.parseCommit(rev);
565 						for (j = i + 1; j < revChars.length; ++j) {
566 							if (!Character.isDigit(revChars[j]))
567 								break;
568 						}
569 						String parentnum = new String(revChars, i + 1, j - i
570 								- 1);
571 						int pnum;
572 						try {
573 							pnum = Integer.parseInt(parentnum);
574 						} catch (NumberFormatException e) {
575 							throw new RevisionSyntaxException(
576 									JGitText.get().invalidCommitParentNumber,
577 									revstr);
578 						}
579 						if (pnum != 0) {
580 							RevCommit commit = (RevCommit) rev;
581 							if (pnum > commit.getParentCount())
582 								rev = null;
583 							else
584 								rev = commit.getParent(pnum - 1);
585 						}
586 						i = j - 1;
587 						done = j;
588 						break;
589 					case '{':
590 						int k;
591 						String item = null;
592 						for (k = i + 2; k < revChars.length; ++k) {
593 							if (revChars[k] == '}') {
594 								item = new String(revChars, i + 2, k - i - 2);
595 								break;
596 							}
597 						}
598 						i = k;
599 						if (item != null)
600 							if (item.equals("tree")) { //$NON-NLS-1$
601 								rev = rw.parseTree(rev);
602 							} else if (item.equals("commit")) { //$NON-NLS-1$
603 								rev = rw.parseCommit(rev);
604 							} else if (item.equals("blob")) { //$NON-NLS-1$
605 								rev = rw.peel(rev);
606 								if (!(rev instanceof RevBlob))
607 									throw new IncorrectObjectTypeException(rev,
608 											Constants.TYPE_BLOB);
609 							} else if (item.equals("")) { //$NON-NLS-1$
610 								rev = rw.peel(rev);
611 							} else
612 								throw new RevisionSyntaxException(revstr);
613 						else
614 							throw new RevisionSyntaxException(revstr);
615 						done = k;
616 						break;
617 					default:
618 						rev = rw.peel(rev);
619 						if (rev instanceof RevCommit) {
620 							RevCommit commit = ((RevCommit) rev);
621 							if (commit.getParentCount() == 0)
622 								rev = null;
623 							else
624 								rev = commit.getParent(0);
625 						} else
626 							throw new IncorrectObjectTypeException(rev,
627 									Constants.TYPE_COMMIT);
628 					}
629 				} else {
630 					rev = rw.peel(rev);
631 					if (rev instanceof RevCommit) {
632 						RevCommit commit = ((RevCommit) rev);
633 						if (commit.getParentCount() == 0)
634 							rev = null;
635 						else
636 							rev = commit.getParent(0);
637 					} else
638 						throw new IncorrectObjectTypeException(rev,
639 								Constants.TYPE_COMMIT);
640 				}
641 				done = i + 1;
642 				break;
643 			case '~':
644 				if (rev == null) {
645 					if (name == null)
646 						if (done == 0)
647 							name = new String(revChars, done, i);
648 						else {
649 							done = i + 1;
650 							break;
651 						}
652 					rev = parseSimple(rw, name);
653 					name = null;
654 					if (rev == null)
655 						return null;
656 				}
657 				rev = rw.peel(rev);
658 				if (!(rev instanceof RevCommit))
659 					throw new IncorrectObjectTypeException(rev,
660 							Constants.TYPE_COMMIT);
661 				int l;
662 				for (l = i + 1; l < revChars.length; ++l) {
663 					if (!Character.isDigit(revChars[l]))
664 						break;
665 				}
666 				int dist;
667 				if (l - i > 1) {
668 					String distnum = new String(revChars, i + 1, l - i - 1);
669 					try {
670 						dist = Integer.parseInt(distnum);
671 					} catch (NumberFormatException e) {
672 						throw new RevisionSyntaxException(
673 								JGitText.get().invalidAncestryLength, revstr);
674 					}
675 				} else
676 					dist = 1;
677 				while (dist > 0) {
678 					RevCommit commit = (RevCommit) rev;
679 					if (commit.getParentCount() == 0) {
680 						rev = null;
681 						break;
682 					}
683 					commit = commit.getParent(0);
684 					rw.parseHeaders(commit);
685 					rev = commit;
686 					--dist;
687 				}
688 				i = l - 1;
689 				done = l;
690 				break;
691 			case '@':
692 				if (rev != null)
693 					throw new RevisionSyntaxException(revstr);
694 				if (i + 1 == revChars.length)
695 					continue;
696 				if (i + 1 < revChars.length && revChars[i + 1] != '{')
697 					continue;
698 				int m;
699 				String time = null;
700 				for (m = i + 2; m < revChars.length; ++m) {
701 					if (revChars[m] == '}') {
702 						time = new String(revChars, i + 2, m - i - 2);
703 						break;
704 					}
705 				}
706 				if (time != null) {
707 					if (time.equals("upstream")) { //$NON-NLS-1$
708 						if (name == null)
709 							name = new String(revChars, done, i);
710 						if (name.equals("")) //$NON-NLS-1$
711 							// Currently checked out branch, HEAD if
712 							// detached
713 							name = Constants.HEAD;
714 						if (!Repository.isValidRefName("x/" + name)) //$NON-NLS-1$
715 							throw new RevisionSyntaxException(MessageFormat
716 									.format(JGitText.get().invalidRefName,
717 											name),
718 									revstr);
719 						Ref ref = findRef(name);
720 						name = null;
721 						if (ref == null)
722 							return null;
723 						if (ref.isSymbolic())
724 							ref = ref.getLeaf();
725 						name = ref.getName();
726 
727 						RemoteConfig remoteConfig;
728 						try {
729 							remoteConfig = new RemoteConfig(getConfig(),
730 									"origin"); //$NON-NLS-1$
731 						} catch (URISyntaxException e) {
732 							throw new RevisionSyntaxException(revstr);
733 						}
734 						String remoteBranchName = getConfig()
735 								.getString(
736 										ConfigConstants.CONFIG_BRANCH_SECTION,
737 								Repository.shortenRefName(ref.getName()),
738 										ConfigConstants.CONFIG_KEY_MERGE);
739 						List<RefSpec> fetchRefSpecs = remoteConfig
740 								.getFetchRefSpecs();
741 						for (RefSpec refSpec : fetchRefSpecs) {
742 							if (refSpec.matchSource(remoteBranchName)) {
743 								RefSpec expandFromSource = refSpec
744 										.expandFromSource(remoteBranchName);
745 								name = expandFromSource.getDestination();
746 								break;
747 							}
748 						}
749 						if (name == null)
750 							throw new RevisionSyntaxException(revstr);
751 					} else if (time.matches("^-\\d+$")) { //$NON-NLS-1$
752 						if (name != null)
753 							throw new RevisionSyntaxException(revstr);
754 						else {
755 							String previousCheckout = resolveReflogCheckout(-Integer
756 									.parseInt(time));
757 							if (ObjectId.isId(previousCheckout))
758 								rev = parseSimple(rw, previousCheckout);
759 							else
760 								name = previousCheckout;
761 						}
762 					} else {
763 						if (name == null)
764 							name = new String(revChars, done, i);
765 						if (name.equals("")) //$NON-NLS-1$
766 							name = Constants.HEAD;
767 						if (!Repository.isValidRefName("x/" + name)) //$NON-NLS-1$
768 							throw new RevisionSyntaxException(MessageFormat
769 									.format(JGitText.get().invalidRefName,
770 											name),
771 									revstr);
772 						Ref ref = findRef(name);
773 						name = null;
774 						if (ref == null)
775 							return null;
776 						// @{n} means current branch, not HEAD@{1} unless
777 						// detached
778 						if (ref.isSymbolic())
779 							ref = ref.getLeaf();
780 						rev = resolveReflog(rw, ref, time);
781 					}
782 					i = m;
783 				} else
784 					throw new RevisionSyntaxException(revstr);
785 				break;
786 			case ':': {
787 				RevTree tree;
788 				if (rev == null) {
789 					if (name == null)
790 						name = new String(revChars, done, i);
791 					if (name.equals("")) //$NON-NLS-1$
792 						name = Constants.HEAD;
793 					rev = parseSimple(rw, name);
794 					name = null;
795 				}
796 				if (rev == null)
797 					return null;
798 				tree = rw.parseTree(rev);
799 				if (i == revChars.length - 1)
800 					return tree.copy();
801 
802 				TreeWalk tw = TreeWalk.forPath(rw.getObjectReader(),
803 						new String(revChars, i + 1, revChars.length - i - 1),
804 						tree);
805 				return tw != null ? tw.getObjectId(0) : null;
806 			}
807 			default:
808 				if (rev != null)
809 					throw new RevisionSyntaxException(revstr);
810 			}
811 		}
812 		if (rev != null)
813 			return rev.copy();
814 		if (name != null)
815 			return name;
816 		if (done == revstr.length())
817 			return null;
818 		name = revstr.substring(done);
819 		if (!Repository.isValidRefName("x/" + name)) //$NON-NLS-1$
820 			throw new RevisionSyntaxException(
821 					MessageFormat.format(JGitText.get().invalidRefName, name),
822 					revstr);
823 		if (findRef(name) != null)
824 			return name;
825 		return resolveSimple(name);
826 	}
827 
828 	private static boolean isHex(char c) {
829 		return ('0' <= c && c <= '9') //
830 				|| ('a' <= c && c <= 'f') //
831 				|| ('A' <= c && c <= 'F');
832 	}
833 
834 	private static boolean isAllHex(String str, int ptr) {
835 		while (ptr < str.length()) {
836 			if (!isHex(str.charAt(ptr++)))
837 				return false;
838 		}
839 		return true;
840 	}
841 
842 	@Nullable
843 	private RevObject parseSimple(RevWalk rw, String revstr) throws IOException {
844 		ObjectId id = resolveSimple(revstr);
845 		return id != null ? rw.parseAny(id) : null;
846 	}
847 
848 	@Nullable
849 	private ObjectId resolveSimple(String revstr) throws IOException {
850 		if (ObjectId.isId(revstr))
851 			return ObjectId.fromString(revstr);
852 
853 		if (Repository.isValidRefName("x/" + revstr)) { //$NON-NLS-1$
854 			Ref r = getRefDatabase().findRef(revstr);
855 			if (r != null)
856 				return r.getObjectId();
857 		}
858 
859 		if (AbbreviatedObjectId.isId(revstr))
860 			return resolveAbbreviation(revstr);
861 
862 		int dashg = revstr.indexOf("-g"); //$NON-NLS-1$
863 		if ((dashg + 5) < revstr.length() && 0 <= dashg
864 				&& isHex(revstr.charAt(dashg + 2))
865 				&& isHex(revstr.charAt(dashg + 3))
866 				&& isAllHex(revstr, dashg + 4)) {
867 			// Possibly output from git describe?
868 			String s = revstr.substring(dashg + 2);
869 			if (AbbreviatedObjectId.isId(s))
870 				return resolveAbbreviation(s);
871 		}
872 
873 		return null;
874 	}
875 
876 	@Nullable
877 	private String resolveReflogCheckout(int checkoutNo)
878 			throws IOException {
879 		ReflogReader reader = getReflogReader(Constants.HEAD);
880 		if (reader == null) {
881 			return null;
882 		}
883 		List<ReflogEntry> reflogEntries = reader.getReverseEntries();
884 		for (ReflogEntry entry : reflogEntries) {
885 			CheckoutEntry checkout = entry.parseCheckout();
886 			if (checkout != null)
887 				if (checkoutNo-- == 1)
888 					return checkout.getFromBranch();
889 		}
890 		return null;
891 	}
892 
893 	private RevCommit resolveReflog(RevWalk rw, Ref ref, String time)
894 			throws IOException {
895 		int number;
896 		try {
897 			number = Integer.parseInt(time);
898 		} catch (NumberFormatException nfe) {
899 			throw new RevisionSyntaxException(MessageFormat.format(
900 					JGitText.get().invalidReflogRevision, time));
901 		}
902 		assert number >= 0;
903 		ReflogReader reader = getReflogReader(ref.getName());
904 		if (reader == null) {
905 			throw new RevisionSyntaxException(
906 					MessageFormat.format(JGitText.get().reflogEntryNotFound,
907 							Integer.valueOf(number), ref.getName()));
908 		}
909 		ReflogEntry entry = reader.getReverseEntry(number);
910 		if (entry == null)
911 			throw new RevisionSyntaxException(MessageFormat.format(
912 					JGitText.get().reflogEntryNotFound,
913 					Integer.valueOf(number), ref.getName()));
914 
915 		return rw.parseCommit(entry.getNewId());
916 	}
917 
918 	@Nullable
919 	private ObjectId resolveAbbreviation(String revstr) throws IOException,
920 			AmbiguousObjectException {
921 		AbbreviatedObjectId id = AbbreviatedObjectId.fromString(revstr);
922 		try (ObjectReader reader = newObjectReader()) {
923 			Collection<ObjectId> matches = reader.resolve(id);
924 			if (matches.size() == 0)
925 				return null;
926 			else if (matches.size() == 1)
927 				return matches.iterator().next();
928 			else
929 				throw new AmbiguousObjectException(id, matches);
930 		}
931 	}
932 
933 	/**
934 	 * Increment the use counter by one, requiring a matched {@link #close()}.
935 	 */
936 	public void incrementOpen() {
937 		useCnt.incrementAndGet();
938 	}
939 
940 	/**
941 	 * {@inheritDoc}
942 	 * <p>
943 	 * Decrement the use count, and maybe close resources.
944 	 */
945 	@Override
946 	public void close() {
947 		int newCount = useCnt.decrementAndGet();
948 		if (newCount == 0) {
949 			if (RepositoryCache.isCached(this)) {
950 				closedAt.set(System.currentTimeMillis());
951 			} else {
952 				doClose();
953 			}
954 		} else if (newCount == -1) {
955 			// should not happen, only log when useCnt became negative to
956 			// minimize number of log entries
957 			String message = MessageFormat.format(JGitText.get().corruptUseCnt,
958 					toString());
959 			if (LOG.isDebugEnabled()) {
960 				LOG.debug(message, new IllegalStateException());
961 			} else {
962 				LOG.warn(message);
963 			}
964 			if (RepositoryCache.isCached(this)) {
965 				closedAt.set(System.currentTimeMillis());
966 			}
967 		}
968 	}
969 
970 	/**
971 	 * Invoked when the use count drops to zero during {@link #close()}.
972 	 * <p>
973 	 * The default implementation closes the object and ref databases.
974 	 */
975 	protected void doClose() {
976 		getObjectDatabase().close();
977 		getRefDatabase().close();
978 	}
979 
980 	/** {@inheritDoc} */
981 	@Override
982 	@NonNull
983 	public String toString() {
984 		String desc;
985 		File directory = getDirectory();
986 		if (directory != null)
987 			desc = directory.getPath();
988 		else
989 			desc = getClass().getSimpleName() + "-" //$NON-NLS-1$
990 					+ System.identityHashCode(this);
991 		return "Repository[" + desc + "]"; //$NON-NLS-1$ //$NON-NLS-2$
992 	}
993 
994 	/**
995 	 * Get the name of the reference that {@code HEAD} points to.
996 	 * <p>
997 	 * This is essentially the same as doing:
998 	 *
999 	 * <pre>
1000 	 * return exactRef(Constants.HEAD).getTarget().getName()
1001 	 * </pre>
1002 	 *
1003 	 * Except when HEAD is detached, in which case this method returns the
1004 	 * current ObjectId in hexadecimal string format.
1005 	 *
1006 	 * @return name of current branch (for example {@code refs/heads/master}),
1007 	 *         an ObjectId in hex format if the current branch is detached, or
1008 	 *         {@code null} if the repository is corrupt and has no HEAD
1009 	 *         reference.
1010 	 * @throws java.io.IOException
1011 	 */
1012 	@Nullable
1013 	public String getFullBranch() throws IOException {
1014 		Ref head = exactRef(Constants.HEAD);
1015 		if (head == null) {
1016 			return null;
1017 		}
1018 		if (head.isSymbolic()) {
1019 			return head.getTarget().getName();
1020 		}
1021 		ObjectId objectId = head.getObjectId();
1022 		if (objectId != null) {
1023 			return objectId.name();
1024 		}
1025 		return null;
1026 	}
1027 
1028 	/**
1029 	 * Get the short name of the current branch that {@code HEAD} points to.
1030 	 * <p>
1031 	 * This is essentially the same as {@link #getFullBranch()}, except the
1032 	 * leading prefix {@code refs/heads/} is removed from the reference before
1033 	 * it is returned to the caller.
1034 	 *
1035 	 * @return name of current branch (for example {@code master}), an ObjectId
1036 	 *         in hex format if the current branch is detached, or {@code null}
1037 	 *         if the repository is corrupt and has no HEAD reference.
1038 	 * @throws java.io.IOException
1039 	 */
1040 	@Nullable
1041 	public String getBranch() throws IOException {
1042 		String name = getFullBranch();
1043 		if (name != null)
1044 			return shortenRefName(name);
1045 		return null;
1046 	}
1047 
1048 	/**
1049 	 * Objects known to exist but not expressed by {@link #getAllRefs()}.
1050 	 * <p>
1051 	 * When a repository borrows objects from another repository, it can
1052 	 * advertise that it safely has that other repository's references, without
1053 	 * exposing any other details about the other repository.  This may help
1054 	 * a client trying to push changes avoid pushing more than it needs to.
1055 	 *
1056 	 * @return unmodifiable collection of other known objects.
1057 	 */
1058 	@NonNull
1059 	public Set<ObjectId> getAdditionalHaves() {
1060 		return Collections.emptySet();
1061 	}
1062 
1063 	/**
1064 	 * Get a ref by name.
1065 	 *
1066 	 * @param name
1067 	 *            the name of the ref to lookup. Must not be a short-hand
1068 	 *            form; e.g., "master" is not automatically expanded to
1069 	 *            "refs/heads/master".
1070 	 * @return the Ref with the given name, or {@code null} if it does not exist
1071 	 * @throws java.io.IOException
1072 	 * @since 4.2
1073 	 */
1074 	@Nullable
1075 	public final Ref exactRef(String name) throws IOException {
1076 		return getRefDatabase().exactRef(name);
1077 	}
1078 
1079 	/**
1080 	 * Search for a ref by (possibly abbreviated) name.
1081 	 *
1082 	 * @param name
1083 	 *            the name of the ref to lookup. May be a short-hand form, e.g.
1084 	 *            "master" which is automatically expanded to
1085 	 *            "refs/heads/master" if "refs/heads/master" already exists.
1086 	 * @return the Ref with the given name, or {@code null} if it does not exist
1087 	 * @throws java.io.IOException
1088 	 * @since 4.2
1089 	 */
1090 	@Nullable
1091 	public final Ref findRef(String name) throws IOException {
1092 		return getRefDatabase().findRef(name);
1093 	}
1094 
1095 	/**
1096 	 * Get mutable map of all known refs, including symrefs like HEAD that may
1097 	 * not point to any object yet.
1098 	 *
1099 	 * @return mutable map of all known refs (heads, tags, remotes).
1100 	 * @deprecated use {@code getRefDatabase().getRefs()} instead.
1101 	 */
1102 	@Deprecated
1103 	@NonNull
1104 	public Map<String, Ref> getAllRefs() {
1105 		try {
1106 			return getRefDatabase().getRefs(RefDatabase.ALL);
1107 		} catch (IOException e) {
1108 			throw new UncheckedIOException(e);
1109 		}
1110 	}
1111 
1112 	/**
1113 	 * Get mutable map of all tags
1114 	 *
1115 	 * @return mutable map of all tags; key is short tag name ("v1.0") and value
1116 	 *         of the entry contains the ref with the full tag name
1117 	 *         ("refs/tags/v1.0").
1118 	 * @deprecated use {@code getRefDatabase().getRefsByPrefix(R_TAGS)} instead
1119 	 */
1120 	@Deprecated
1121 	@NonNull
1122 	public Map<String, Ref> getTags() {
1123 		try {
1124 			return getRefDatabase().getRefs(Constants.R_TAGS);
1125 		} catch (IOException e) {
1126 			throw new UncheckedIOException(e);
1127 		}
1128 	}
1129 
1130 	/**
1131 	 * Peel a possibly unpeeled reference to an annotated tag.
1132 	 * <p>
1133 	 * If the ref cannot be peeled (as it does not refer to an annotated tag)
1134 	 * the peeled id stays null, but {@link org.eclipse.jgit.lib.Ref#isPeeled()}
1135 	 * will be true.
1136 	 *
1137 	 * @param ref
1138 	 *            The ref to peel
1139 	 * @return <code>ref</code> if <code>ref.isPeeled()</code> is true; else a
1140 	 *         new Ref object representing the same data as Ref, but isPeeled()
1141 	 *         will be true and getPeeledObjectId will contain the peeled object
1142 	 *         (or null).
1143 	 * @deprecated use {@code getRefDatabase().peel(ref)} instead.
1144 	 */
1145 	@Deprecated
1146 	@NonNull
1147 	public Ref" href="../../../../org/eclipse/jgit/lib/Ref.html#Ref">Ref peel(Ref ref) {
1148 		try {
1149 			return getRefDatabase().peel(ref);
1150 		} catch (IOException e) {
1151 			// Historical accident; if the reference cannot be peeled due
1152 			// to some sort of repository access problem we claim that the
1153 			// same as if the reference was not an annotated tag.
1154 			return ref;
1155 		}
1156 	}
1157 
1158 	/**
1159 	 * Get a map with all objects referenced by a peeled ref.
1160 	 *
1161 	 * @return a map with all objects referenced by a peeled ref.
1162 	 */
1163 	@NonNull
1164 	public Map<AnyObjectId, Set<Ref>> getAllRefsByPeeledObjectId() {
1165 		Map<String, Ref> allRefs = getAllRefs();
1166 		Map<AnyObjectId, Set<Ref>> ret = new HashMap<>(allRefs.size());
1167 		for (Ref ref : allRefs.values()) {
1168 			ref = peel(ref);
1169 			AnyObjectId target = ref.getPeeledObjectId();
1170 			if (target == null)
1171 				target = ref.getObjectId();
1172 			// We assume most Sets here are singletons
1173 			Set<Ref> oset = ret.put(target, Collections.singleton(ref));
1174 			if (oset != null) {
1175 				// that was not the case (rare)
1176 				if (oset.size() == 1) {
1177 					// Was a read-only singleton, we must copy to a new Set
1178 					oset = new HashSet<>(oset);
1179 				}
1180 				ret.put(target, oset);
1181 				oset.add(ref);
1182 			}
1183 		}
1184 		return ret;
1185 	}
1186 
1187 	/**
1188 	 * Get the index file location or {@code null} if repository isn't local.
1189 	 *
1190 	 * @return the index file location or {@code null} if repository isn't
1191 	 *         local.
1192 	 * @throws org.eclipse.jgit.errors.NoWorkTreeException
1193 	 *             if this is bare, which implies it has no working directory.
1194 	 *             See {@link #isBare()}.
1195 	 */
1196 	@NonNull
1197 	public File getIndexFile() throws NoWorkTreeException {
1198 		if (isBare())
1199 			throw new NoWorkTreeException();
1200 		return indexFile;
1201 	}
1202 
1203 	/**
1204 	 * Locate a reference to a commit and immediately parse its content.
1205 	 * <p>
1206 	 * This method only returns successfully if the commit object exists,
1207 	 * is verified to be a commit, and was parsed without error.
1208 	 *
1209 	 * @param id
1210 	 *            name of the commit object.
1211 	 * @return reference to the commit object. Never null.
1212 	 * @throws org.eclipse.jgit.errors.MissingObjectException
1213 	 *             the supplied commit does not exist.
1214 	 * @throws org.eclipse.jgit.errors.IncorrectObjectTypeException
1215 	 *             the supplied id is not a commit or an annotated tag.
1216 	 * @throws java.io.IOException
1217 	 *             a pack file or loose object could not be read.
1218 	 * @since 4.8
1219 	 */
1220 	public RevCommit parseCommit(AnyObjectId id) throws IncorrectObjectTypeException,
1221 			IOException, MissingObjectException {
1222 		if (id instanceof RevCommit../../org/eclipse/jgit/revwalk/RevCommit.html#RevCommit">RevCommit && ((RevCommit) id).getRawBuffer() != null) {
1223 			return (RevCommit) id;
1224 		}
1225 		try (RevWalkvWalk.html#RevWalk">RevWalk walk = new RevWalk(this)) {
1226 			return walk.parseCommit(id);
1227 		}
1228 	}
1229 
1230 	/**
1231 	 * Create a new in-core index representation and read an index from disk.
1232 	 * <p>
1233 	 * The new index will be read before it is returned to the caller. Read
1234 	 * failures are reported as exceptions and therefore prevent the method from
1235 	 * returning a partially populated index.
1236 	 *
1237 	 * @return a cache representing the contents of the specified index file (if
1238 	 *         it exists) or an empty cache if the file does not exist.
1239 	 * @throws org.eclipse.jgit.errors.NoWorkTreeException
1240 	 *             if this is bare, which implies it has no working directory.
1241 	 *             See {@link #isBare()}.
1242 	 * @throws java.io.IOException
1243 	 *             the index file is present but could not be read.
1244 	 * @throws org.eclipse.jgit.errors.CorruptObjectException
1245 	 *             the index file is using a format or extension that this
1246 	 *             library does not support.
1247 	 */
1248 	@NonNull
1249 	public DirCache readDirCache() throws NoWorkTreeException,
1250 			CorruptObjectException, IOException {
1251 		return DirCache.read(this);
1252 	}
1253 
1254 	/**
1255 	 * Create a new in-core index representation, lock it, and read from disk.
1256 	 * <p>
1257 	 * The new index will be locked and then read before it is returned to the
1258 	 * caller. Read failures are reported as exceptions and therefore prevent
1259 	 * the method from returning a partially populated index.
1260 	 *
1261 	 * @return a cache representing the contents of the specified index file (if
1262 	 *         it exists) or an empty cache if the file does not exist.
1263 	 * @throws org.eclipse.jgit.errors.NoWorkTreeException
1264 	 *             if this is bare, which implies it has no working directory.
1265 	 *             See {@link #isBare()}.
1266 	 * @throws java.io.IOException
1267 	 *             the index file is present but could not be read, or the lock
1268 	 *             could not be obtained.
1269 	 * @throws org.eclipse.jgit.errors.CorruptObjectException
1270 	 *             the index file is using a format or extension that this
1271 	 *             library does not support.
1272 	 */
1273 	@NonNull
1274 	public DirCache lockDirCache() throws NoWorkTreeException,
1275 			CorruptObjectException, IOException {
1276 		// we want DirCache to inform us so that we can inform registered
1277 		// listeners about index changes
1278 		IndexChangedListener l = new IndexChangedListener() {
1279 			@Override
1280 			public void onIndexChanged(IndexChangedEvent event) {
1281 				notifyIndexChanged(true);
1282 			}
1283 		};
1284 		return DirCache.lock(this, l);
1285 	}
1286 
1287 	/**
1288 	 * Get the repository state
1289 	 *
1290 	 * @return the repository state
1291 	 */
1292 	@NonNull
1293 	public RepositoryState getRepositoryState() {
1294 		if (isBare() || getDirectory() == null)
1295 			return RepositoryState.BARE;
1296 
1297 		// Pre Git-1.6 logic
1298 		if (new File(getWorkTree(), ".dotest").exists()) //$NON-NLS-1$
1299 			return RepositoryState.REBASING;
1300 		if (new File(getDirectory(), ".dotest-merge").exists()) //$NON-NLS-1$
1301 			return RepositoryState.REBASING_INTERACTIVE;
1302 
1303 		// From 1.6 onwards
1304 		if (new File(getDirectory(),"rebase-apply/rebasing").exists()) //$NON-NLS-1$
1305 			return RepositoryState.REBASING_REBASING;
1306 		if (new File(getDirectory(),"rebase-apply/applying").exists()) //$NON-NLS-1$
1307 			return RepositoryState.APPLY;
1308 		if (new File(getDirectory(),"rebase-apply").exists()) //$NON-NLS-1$
1309 			return RepositoryState.REBASING;
1310 
1311 		if (new File(getDirectory(),"rebase-merge/interactive").exists()) //$NON-NLS-1$
1312 			return RepositoryState.REBASING_INTERACTIVE;
1313 		if (new File(getDirectory(),"rebase-merge").exists()) //$NON-NLS-1$
1314 			return RepositoryState.REBASING_MERGE;
1315 
1316 		// Both versions
1317 		if (new File(getDirectory(), Constants.MERGE_HEAD).exists()) {
1318 			// we are merging - now check whether we have unmerged paths
1319 			try {
1320 				if (!readDirCache().hasUnmergedPaths()) {
1321 					// no unmerged paths -> return the MERGING_RESOLVED state
1322 					return RepositoryState.MERGING_RESOLVED;
1323 				}
1324 			} catch (IOException e) {
1325 				throw new UncheckedIOException(e);
1326 			}
1327 			return RepositoryState.MERGING;
1328 		}
1329 
1330 		if (new File(getDirectory(), "BISECT_LOG").exists()) //$NON-NLS-1$
1331 			return RepositoryState.BISECTING;
1332 
1333 		if (new File(getDirectory(), Constants.CHERRY_PICK_HEAD).exists()) {
1334 			try {
1335 				if (!readDirCache().hasUnmergedPaths()) {
1336 					// no unmerged paths
1337 					return RepositoryState.CHERRY_PICKING_RESOLVED;
1338 				}
1339 			} catch (IOException e) {
1340 				throw new UncheckedIOException(e);
1341 			}
1342 
1343 			return RepositoryState.CHERRY_PICKING;
1344 		}
1345 
1346 		if (new File(getDirectory(), Constants.REVERT_HEAD).exists()) {
1347 			try {
1348 				if (!readDirCache().hasUnmergedPaths()) {
1349 					// no unmerged paths
1350 					return RepositoryState.REVERTING_RESOLVED;
1351 				}
1352 			} catch (IOException e) {
1353 				throw new UncheckedIOException(e);
1354 			}
1355 
1356 			return RepositoryState.REVERTING;
1357 		}
1358 
1359 		return RepositoryState.SAFE;
1360 	}
1361 
1362 	/**
1363 	 * Check validity of a ref name. It must not contain character that has
1364 	 * a special meaning in a Git object reference expression. Some other
1365 	 * dangerous characters are also excluded.
1366 	 *
1367 	 * For portability reasons '\' is excluded
1368 	 *
1369 	 * @param refName a {@link java.lang.String} object.
1370 	 * @return true if refName is a valid ref name
1371 	 */
1372 	public static boolean isValidRefName(String refName) {
1373 		final int len = refName.length();
1374 		if (len == 0) {
1375 			return false;
1376 		}
1377 		if (refName.endsWith(LOCK_SUFFIX)) {
1378 			return false;
1379 		}
1380 
1381 		// Refs may be stored as loose files so invalid paths
1382 		// on the local system must also be invalid refs.
1383 		try {
1384 			SystemReader.getInstance().checkPath(refName);
1385 		} catch (CorruptObjectException e) {
1386 			return false;
1387 		}
1388 
1389 		int components = 1;
1390 		char p = '\0';
1391 		for (int i = 0; i < len; i++) {
1392 			final char c = refName.charAt(i);
1393 			if (c <= ' ')
1394 				return false;
1395 			switch (c) {
1396 			case '.':
1397 				switch (p) {
1398 				case '\0': case '/': case '.':
1399 					return false;
1400 				}
1401 				if (i == len -1)
1402 					return false;
1403 				break;
1404 			case '/':
1405 				if (i == 0 || i == len - 1)
1406 					return false;
1407 				if (p == '/')
1408 					return false;
1409 				components++;
1410 				break;
1411 			case '{':
1412 				if (p == '@')
1413 					return false;
1414 				break;
1415 			case '~': case '^': case ':':
1416 			case '?': case '[': case '*':
1417 			case '\\':
1418 			case '\u007F':
1419 				return false;
1420 			}
1421 			p = c;
1422 		}
1423 		return components > 1;
1424 	}
1425 
1426 	/**
1427 	 * Normalizes the passed branch name into a possible valid branch name. The
1428 	 * validity of the returned name should be checked by a subsequent call to
1429 	 * {@link #isValidRefName(String)}.
1430 	 * <p>
1431 	 * Future implementations of this method could be more restrictive or more
1432 	 * lenient about the validity of specific characters in the returned name.
1433 	 * <p>
1434 	 * The current implementation returns the trimmed input string if this is
1435 	 * already a valid branch name. Otherwise it returns a trimmed string with
1436 	 * special characters not allowed by {@link #isValidRefName(String)}
1437 	 * replaced by hyphens ('-') and blanks replaced by underscores ('_').
1438 	 * Leading and trailing slashes, dots, hyphens, and underscores are removed.
1439 	 *
1440 	 * @param name
1441 	 *            to normalize
1442 	 * @return The normalized name or an empty String if it is {@code null} or
1443 	 *         empty.
1444 	 * @since 4.7
1445 	 * @see #isValidRefName(String)
1446 	 */
1447 	public static String normalizeBranchName(String name) {
1448 		if (name == null || name.isEmpty()) {
1449 			return ""; //$NON-NLS-1$
1450 		}
1451 		String result = name.trim();
1452 		String fullName = result.startsWith(Constants.R_HEADS) ? result
1453 				: Constants.R_HEADS + result;
1454 		if (isValidRefName(fullName)) {
1455 			return result;
1456 		}
1457 
1458 		// All Unicode blanks to underscore
1459 		result = result.replaceAll("(?:\\h|\\v)+", "_"); //$NON-NLS-1$ //$NON-NLS-2$
1460 		StringBuilder b = new StringBuilder();
1461 		char p = '/';
1462 		for (int i = 0, len = result.length(); i < len; i++) {
1463 			char c = result.charAt(i);
1464 			if (c < ' ' || c == 127) {
1465 				continue;
1466 			}
1467 			// Substitute a dash for problematic characters
1468 			switch (c) {
1469 			case '\\':
1470 			case '^':
1471 			case '~':
1472 			case ':':
1473 			case '?':
1474 			case '*':
1475 			case '[':
1476 			case '@':
1477 			case '<':
1478 			case '>':
1479 			case '|':
1480 			case '"':
1481 				c = '-';
1482 				break;
1483 			default:
1484 				break;
1485 			}
1486 			// Collapse multiple slashes, dashes, dots, underscores, and omit
1487 			// dashes, dots, and underscores following a slash.
1488 			switch (c) {
1489 			case '/':
1490 				if (p == '/') {
1491 					continue;
1492 				}
1493 				p = '/';
1494 				break;
1495 			case '.':
1496 			case '_':
1497 			case '-':
1498 				if (p == '/' || p == '-') {
1499 					continue;
1500 				}
1501 				p = '-';
1502 				break;
1503 			default:
1504 				p = c;
1505 				break;
1506 			}
1507 			b.append(c);
1508 		}
1509 		// Strip trailing special characters, and avoid the .lock extension
1510 		result = b.toString().replaceFirst("[/_.-]+$", "") //$NON-NLS-1$ //$NON-NLS-2$
1511 				.replaceAll("\\.lock($|/)", "_lock$1"); //$NON-NLS-1$ //$NON-NLS-2$
1512 		return FORBIDDEN_BRANCH_NAME_COMPONENTS.matcher(result)
1513 				.replaceAll("$1+$2$3"); //$NON-NLS-1$
1514 	}
1515 
1516 	/**
1517 	 * Strip work dir and return normalized repository path.
1518 	 *
1519 	 * @param workDir
1520 	 *            Work dir
1521 	 * @param file
1522 	 *            File whose path shall be stripped of its workdir
1523 	 * @return normalized repository relative path or the empty string if the
1524 	 *         file is not relative to the work directory.
1525 	 */
1526 	@NonNull
1527 	public static String stripWorkDir(File workDir, File file) {
1528 		final String filePath = file.getPath();
1529 		final String workDirPath = workDir.getPath();
1530 
1531 		if (filePath.length() <= workDirPath.length() ||
1532 		    filePath.charAt(workDirPath.length()) != File.separatorChar ||
1533 		    !filePath.startsWith(workDirPath)) {
1534 			File absWd = workDir.isAbsolute() ? workDir : workDir.getAbsoluteFile();
1535 			File absFile = file.isAbsolute() ? file : file.getAbsoluteFile();
1536 			if (absWd == workDir && absFile == file)
1537 				return ""; //$NON-NLS-1$
1538 			return stripWorkDir(absWd, absFile);
1539 		}
1540 
1541 		String relName = filePath.substring(workDirPath.length() + 1);
1542 		if (File.separatorChar != '/')
1543 			relName = relName.replace(File.separatorChar, '/');
1544 		return relName;
1545 	}
1546 
1547 	/**
1548 	 * Whether this repository is bare
1549 	 *
1550 	 * @return true if this is bare, which implies it has no working directory.
1551 	 */
1552 	public boolean isBare() {
1553 		return workTree == null;
1554 	}
1555 
1556 	/**
1557 	 * Get the root directory of the working tree, where files are checked out
1558 	 * for viewing and editing.
1559 	 *
1560 	 * @return the root directory of the working tree, where files are checked
1561 	 *         out for viewing and editing.
1562 	 * @throws org.eclipse.jgit.errors.NoWorkTreeException
1563 	 *             if this is bare, which implies it has no working directory.
1564 	 *             See {@link #isBare()}.
1565 	 */
1566 	@NonNull
1567 	public File getWorkTree() throws NoWorkTreeException {
1568 		if (isBare())
1569 			throw new NoWorkTreeException();
1570 		return workTree;
1571 	}
1572 
1573 	/**
1574 	 * Force a scan for changed refs. Fires an IndexChangedEvent(false) if
1575 	 * changes are detected.
1576 	 *
1577 	 * @throws java.io.IOException
1578 	 */
1579 	public abstract void scanForRepoChanges() throws IOException;
1580 
1581 	/**
1582 	 * Notify that the index changed by firing an IndexChangedEvent.
1583 	 *
1584 	 * @param internal
1585 	 *                     {@code true} if the index was changed by the same
1586 	 *                     JGit process
1587 	 * @since 5.0
1588 	 */
1589 	public abstract void notifyIndexChanged(boolean internal);
1590 
1591 	/**
1592 	 * Get a shortened more user friendly ref name
1593 	 *
1594 	 * @param refName
1595 	 *            a {@link java.lang.String} object.
1596 	 * @return a more user friendly ref name
1597 	 */
1598 	@NonNull
1599 	public static String shortenRefName(String refName) {
1600 		if (refName.startsWith(Constants.R_HEADS))
1601 			return refName.substring(Constants.R_HEADS.length());
1602 		if (refName.startsWith(Constants.R_TAGS))
1603 			return refName.substring(Constants.R_TAGS.length());
1604 		if (refName.startsWith(Constants.R_REMOTES))
1605 			return refName.substring(Constants.R_REMOTES.length());
1606 		return refName;
1607 	}
1608 
1609 	/**
1610 	 * Get a shortened more user friendly remote tracking branch name
1611 	 *
1612 	 * @param refName
1613 	 *            a {@link java.lang.String} object.
1614 	 * @return the remote branch name part of <code>refName</code>, i.e. without
1615 	 *         the <code>refs/remotes/&lt;remote&gt;</code> prefix, if
1616 	 *         <code>refName</code> represents a remote tracking branch;
1617 	 *         otherwise {@code null}.
1618 	 * @since 3.4
1619 	 */
1620 	@Nullable
1621 	public String shortenRemoteBranchName(String refName) {
1622 		for (String remote : getRemoteNames()) {
1623 			String remotePrefix = Constants.R_REMOTES + remote + "/"; //$NON-NLS-1$
1624 			if (refName.startsWith(remotePrefix))
1625 				return refName.substring(remotePrefix.length());
1626 		}
1627 		return null;
1628 	}
1629 
1630 	/**
1631 	 * Get remote name
1632 	 *
1633 	 * @param refName
1634 	 *            a {@link java.lang.String} object.
1635 	 * @return the remote name part of <code>refName</code>, i.e. without the
1636 	 *         <code>refs/remotes/&lt;remote&gt;</code> prefix, if
1637 	 *         <code>refName</code> represents a remote tracking branch;
1638 	 *         otherwise {@code null}.
1639 	 * @since 3.4
1640 	 */
1641 	@Nullable
1642 	public String getRemoteName(String refName) {
1643 		for (String remote : getRemoteNames()) {
1644 			String remotePrefix = Constants.R_REMOTES + remote + "/"; //$NON-NLS-1$
1645 			if (refName.startsWith(remotePrefix))
1646 				return remote;
1647 		}
1648 		return null;
1649 	}
1650 
1651 	/**
1652 	 * Read the {@code GIT_DIR/description} file for gitweb.
1653 	 *
1654 	 * @return description text; null if no description has been configured.
1655 	 * @throws java.io.IOException
1656 	 *             description cannot be accessed.
1657 	 * @since 4.6
1658 	 */
1659 	@Nullable
1660 	public String getGitwebDescription() throws IOException {
1661 		return null;
1662 	}
1663 
1664 	/**
1665 	 * Set the {@code GIT_DIR/description} file for gitweb.
1666 	 *
1667 	 * @param description
1668 	 *            new description; null to clear the description.
1669 	 * @throws java.io.IOException
1670 	 *             description cannot be persisted.
1671 	 * @since 4.6
1672 	 */
1673 	public void setGitwebDescription(@Nullable String description)
1674 			throws IOException {
1675 		throw new IOException(JGitText.get().unsupportedRepositoryDescription);
1676 	}
1677 
1678 	/**
1679 	 * Get the reflog reader
1680 	 *
1681 	 * @param refName
1682 	 *            a {@link java.lang.String} object.
1683 	 * @return a {@link org.eclipse.jgit.lib.ReflogReader} for the supplied
1684 	 *         refname, or {@code null} if the named ref does not exist.
1685 	 * @throws java.io.IOException
1686 	 *             the ref could not be accessed.
1687 	 * @since 3.0
1688 	 */
1689 	@Nullable
1690 	public abstract ReflogReader getReflogReader(String refName)
1691 			throws IOException;
1692 
1693 	/**
1694 	 * Return the information stored in the file $GIT_DIR/MERGE_MSG. In this
1695 	 * file operations triggering a merge will store a template for the commit
1696 	 * message of the merge commit.
1697 	 *
1698 	 * @return a String containing the content of the MERGE_MSG file or
1699 	 *         {@code null} if this file doesn't exist
1700 	 * @throws java.io.IOException
1701 	 * @throws org.eclipse.jgit.errors.NoWorkTreeException
1702 	 *             if this is bare, which implies it has no working directory.
1703 	 *             See {@link #isBare()}.
1704 	 */
1705 	@Nullable
1706 	public String readMergeCommitMsg() throws IOException, NoWorkTreeException {
1707 		return readCommitMsgFile(Constants.MERGE_MSG);
1708 	}
1709 
1710 	/**
1711 	 * Write new content to the file $GIT_DIR/MERGE_MSG. In this file operations
1712 	 * triggering a merge will store a template for the commit message of the
1713 	 * merge commit. If <code>null</code> is specified as message the file will
1714 	 * be deleted.
1715 	 *
1716 	 * @param msg
1717 	 *            the message which should be written or <code>null</code> to
1718 	 *            delete the file
1719 	 * @throws java.io.IOException
1720 	 */
1721 	public void writeMergeCommitMsg(String msg) throws IOException {
1722 		File mergeMsgFile = new File(gitDir, Constants.MERGE_MSG);
1723 		writeCommitMsg(mergeMsgFile, msg);
1724 	}
1725 
1726 	/**
1727 	 * Return the information stored in the file $GIT_DIR/COMMIT_EDITMSG. In
1728 	 * this file hooks triggered by an operation may read or modify the current
1729 	 * commit message.
1730 	 *
1731 	 * @return a String containing the content of the COMMIT_EDITMSG file or
1732 	 *         {@code null} if this file doesn't exist
1733 	 * @throws java.io.IOException
1734 	 * @throws org.eclipse.jgit.errors.NoWorkTreeException
1735 	 *             if this is bare, which implies it has no working directory.
1736 	 *             See {@link #isBare()}.
1737 	 * @since 4.0
1738 	 */
1739 	@Nullable
1740 	public String readCommitEditMsg() throws IOException, NoWorkTreeException {
1741 		return readCommitMsgFile(Constants.COMMIT_EDITMSG);
1742 	}
1743 
1744 	/**
1745 	 * Write new content to the file $GIT_DIR/COMMIT_EDITMSG. In this file hooks
1746 	 * triggered by an operation may read or modify the current commit message.
1747 	 * If {@code null} is specified as message the file will be deleted.
1748 	 *
1749 	 * @param msg
1750 	 *            the message which should be written or {@code null} to delete
1751 	 *            the file
1752 	 * @throws java.io.IOException
1753 	 * @since 4.0
1754 	 */
1755 	public void writeCommitEditMsg(String msg) throws IOException {
1756 		File commiEditMsgFile = new File(gitDir, Constants.COMMIT_EDITMSG);
1757 		writeCommitMsg(commiEditMsgFile, msg);
1758 	}
1759 
1760 	/**
1761 	 * Return the information stored in the file $GIT_DIR/MERGE_HEAD. In this
1762 	 * file operations triggering a merge will store the IDs of all heads which
1763 	 * should be merged together with HEAD.
1764 	 *
1765 	 * @return a list of commits which IDs are listed in the MERGE_HEAD file or
1766 	 *         {@code null} if this file doesn't exist. Also if the file exists
1767 	 *         but is empty {@code null} will be returned
1768 	 * @throws java.io.IOException
1769 	 * @throws org.eclipse.jgit.errors.NoWorkTreeException
1770 	 *             if this is bare, which implies it has no working directory.
1771 	 *             See {@link #isBare()}.
1772 	 */
1773 	@Nullable
1774 	public List<ObjectId> readMergeHeads() throws IOException, NoWorkTreeException {
1775 		if (isBare() || getDirectory() == null)
1776 			throw new NoWorkTreeException();
1777 
1778 		byte[] raw = readGitDirectoryFile(Constants.MERGE_HEAD);
1779 		if (raw == null)
1780 			return null;
1781 
1782 		LinkedList<ObjectId> heads = new LinkedList<>();
1783 		for (int p = 0; p < raw.length;) {
1784 			heads.add(ObjectId.fromString(raw, p));
1785 			p = RawParseUtils
1786 					.nextLF(raw, p + Constants.OBJECT_ID_STRING_LENGTH);
1787 		}
1788 		return heads;
1789 	}
1790 
1791 	/**
1792 	 * Write new merge-heads into $GIT_DIR/MERGE_HEAD. In this file operations
1793 	 * triggering a merge will store the IDs of all heads which should be merged
1794 	 * together with HEAD. If <code>null</code> is specified as list of commits
1795 	 * the file will be deleted
1796 	 *
1797 	 * @param heads
1798 	 *            a list of commits which IDs should be written to
1799 	 *            $GIT_DIR/MERGE_HEAD or <code>null</code> to delete the file
1800 	 * @throws java.io.IOException
1801 	 */
1802 	public void writeMergeHeads(List<? extends ObjectId> heads) throws IOException {
1803 		writeHeadsFile(heads, Constants.MERGE_HEAD);
1804 	}
1805 
1806 	/**
1807 	 * Return the information stored in the file $GIT_DIR/CHERRY_PICK_HEAD.
1808 	 *
1809 	 * @return object id from CHERRY_PICK_HEAD file or {@code null} if this file
1810 	 *         doesn't exist. Also if the file exists but is empty {@code null}
1811 	 *         will be returned
1812 	 * @throws java.io.IOException
1813 	 * @throws org.eclipse.jgit.errors.NoWorkTreeException
1814 	 *             if this is bare, which implies it has no working directory.
1815 	 *             See {@link #isBare()}.
1816 	 */
1817 	@Nullable
1818 	public ObjectId readCherryPickHead() throws IOException,
1819 			NoWorkTreeException {
1820 		if (isBare() || getDirectory() == null)
1821 			throw new NoWorkTreeException();
1822 
1823 		byte[] raw = readGitDirectoryFile(Constants.CHERRY_PICK_HEAD);
1824 		if (raw == null)
1825 			return null;
1826 
1827 		return ObjectId.fromString(raw, 0);
1828 	}
1829 
1830 	/**
1831 	 * Return the information stored in the file $GIT_DIR/REVERT_HEAD.
1832 	 *
1833 	 * @return object id from REVERT_HEAD file or {@code null} if this file
1834 	 *         doesn't exist. Also if the file exists but is empty {@code null}
1835 	 *         will be returned
1836 	 * @throws java.io.IOException
1837 	 * @throws org.eclipse.jgit.errors.NoWorkTreeException
1838 	 *             if this is bare, which implies it has no working directory.
1839 	 *             See {@link #isBare()}.
1840 	 */
1841 	@Nullable
1842 	public ObjectId readRevertHead() throws IOException, NoWorkTreeException {
1843 		if (isBare() || getDirectory() == null)
1844 			throw new NoWorkTreeException();
1845 
1846 		byte[] raw = readGitDirectoryFile(Constants.REVERT_HEAD);
1847 		if (raw == null)
1848 			return null;
1849 		return ObjectId.fromString(raw, 0);
1850 	}
1851 
1852 	/**
1853 	 * Write cherry pick commit into $GIT_DIR/CHERRY_PICK_HEAD. This is used in
1854 	 * case of conflicts to store the cherry which was tried to be picked.
1855 	 *
1856 	 * @param head
1857 	 *            an object id of the cherry commit or <code>null</code> to
1858 	 *            delete the file
1859 	 * @throws java.io.IOException
1860 	 */
1861 	public void writeCherryPickHead(ObjectId head) throws IOException {
1862 		List<ObjectId> heads = (head != null) ? Collections.singletonList(head)
1863 				: null;
1864 		writeHeadsFile(heads, Constants.CHERRY_PICK_HEAD);
1865 	}
1866 
1867 	/**
1868 	 * Write revert commit into $GIT_DIR/REVERT_HEAD. This is used in case of
1869 	 * conflicts to store the revert which was tried to be picked.
1870 	 *
1871 	 * @param head
1872 	 *            an object id of the revert commit or <code>null</code> to
1873 	 *            delete the file
1874 	 * @throws java.io.IOException
1875 	 */
1876 	public void writeRevertHead(ObjectId head) throws IOException {
1877 		List<ObjectId> heads = (head != null) ? Collections.singletonList(head)
1878 				: null;
1879 		writeHeadsFile(heads, Constants.REVERT_HEAD);
1880 	}
1881 
1882 	/**
1883 	 * Write original HEAD commit into $GIT_DIR/ORIG_HEAD.
1884 	 *
1885 	 * @param head
1886 	 *            an object id of the original HEAD commit or <code>null</code>
1887 	 *            to delete the file
1888 	 * @throws java.io.IOException
1889 	 */
1890 	public void writeOrigHead(ObjectId head) throws IOException {
1891 		List<ObjectId> heads = head != null ? Collections.singletonList(head)
1892 				: null;
1893 		writeHeadsFile(heads, Constants.ORIG_HEAD);
1894 	}
1895 
1896 	/**
1897 	 * Return the information stored in the file $GIT_DIR/ORIG_HEAD.
1898 	 *
1899 	 * @return object id from ORIG_HEAD file or {@code null} if this file
1900 	 *         doesn't exist. Also if the file exists but is empty {@code null}
1901 	 *         will be returned
1902 	 * @throws java.io.IOException
1903 	 * @throws org.eclipse.jgit.errors.NoWorkTreeException
1904 	 *             if this is bare, which implies it has no working directory.
1905 	 *             See {@link #isBare()}.
1906 	 */
1907 	@Nullable
1908 	public ObjectId readOrigHead() throws IOException, NoWorkTreeException {
1909 		if (isBare() || getDirectory() == null)
1910 			throw new NoWorkTreeException();
1911 
1912 		byte[] raw = readGitDirectoryFile(Constants.ORIG_HEAD);
1913 		return raw != null ? ObjectId.fromString(raw, 0) : null;
1914 	}
1915 
1916 	/**
1917 	 * Return the information stored in the file $GIT_DIR/SQUASH_MSG. In this
1918 	 * file operations triggering a squashed merge will store a template for the
1919 	 * commit message of the squash commit.
1920 	 *
1921 	 * @return a String containing the content of the SQUASH_MSG file or
1922 	 *         {@code null} if this file doesn't exist
1923 	 * @throws java.io.IOException
1924 	 * @throws NoWorkTreeException
1925 	 *             if this is bare, which implies it has no working directory.
1926 	 *             See {@link #isBare()}.
1927 	 */
1928 	@Nullable
1929 	public String readSquashCommitMsg() throws IOException {
1930 		return readCommitMsgFile(Constants.SQUASH_MSG);
1931 	}
1932 
1933 	/**
1934 	 * Write new content to the file $GIT_DIR/SQUASH_MSG. In this file
1935 	 * operations triggering a squashed merge will store a template for the
1936 	 * commit message of the squash commit. If <code>null</code> is specified as
1937 	 * message the file will be deleted.
1938 	 *
1939 	 * @param msg
1940 	 *            the message which should be written or <code>null</code> to
1941 	 *            delete the file
1942 	 * @throws java.io.IOException
1943 	 */
1944 	public void writeSquashCommitMsg(String msg) throws IOException {
1945 		File squashMsgFile = new File(gitDir, Constants.SQUASH_MSG);
1946 		writeCommitMsg(squashMsgFile, msg);
1947 	}
1948 
1949 	@Nullable
1950 	private String readCommitMsgFile(String msgFilename) throws IOException {
1951 		if (isBare() || getDirectory() == null)
1952 			throw new NoWorkTreeException();
1953 
1954 		File mergeMsgFile = new File(getDirectory(), msgFilename);
1955 		try {
1956 			return RawParseUtils.decode(IO.readFully(mergeMsgFile));
1957 		} catch (FileNotFoundException e) {
1958 			if (mergeMsgFile.exists()) {
1959 				throw e;
1960 			}
1961 			// the file has disappeared in the meantime ignore it
1962 			return null;
1963 		}
1964 	}
1965 
1966 	private void writeCommitMsg(File msgFile, String msg) throws IOException {
1967 		if (msg != null) {
1968 			try (FileOutputStream fos = new FileOutputStream(msgFile)) {
1969 				fos.write(msg.getBytes(UTF_8));
1970 			}
1971 		} else {
1972 			FileUtils.delete(msgFile, FileUtils.SKIP_MISSING);
1973 		}
1974 	}
1975 
1976 	/**
1977 	 * Read a file from the git directory.
1978 	 *
1979 	 * @param filename
1980 	 * @return the raw contents or {@code null} if the file doesn't exist or is
1981 	 *         empty
1982 	 * @throws IOException
1983 	 */
1984 	private byte[] readGitDirectoryFile(String filename) throws IOException {
1985 		File file = new File(getDirectory(), filename);
1986 		try {
1987 			byte[] raw = IO.readFully(file);
1988 			return raw.length > 0 ? raw : null;
1989 		} catch (FileNotFoundException notFound) {
1990 			if (file.exists()) {
1991 				throw notFound;
1992 			}
1993 			return null;
1994 		}
1995 	}
1996 
1997 	/**
1998 	 * Write the given heads to a file in the git directory.
1999 	 *
2000 	 * @param heads
2001 	 *            a list of object ids to write or null if the file should be
2002 	 *            deleted.
2003 	 * @param filename
2004 	 * @throws FileNotFoundException
2005 	 * @throws IOException
2006 	 */
2007 	private void writeHeadsFile(List<? extends ObjectId> heads, String filename)
2008 			throws FileNotFoundException, IOException {
2009 		File headsFile = new File(getDirectory(), filename);
2010 		if (heads != null) {
2011 			try (OutputStream bos = new BufferedOutputStream(
2012 					new FileOutputStream(headsFile))) {
2013 				for (ObjectId id : heads) {
2014 					id.copyTo(bos);
2015 					bos.write('\n');
2016 				}
2017 			}
2018 		} else {
2019 			FileUtils.delete(headsFile, FileUtils.SKIP_MISSING);
2020 		}
2021 	}
2022 
2023 	/**
2024 	 * Read a file formatted like the git-rebase-todo file. The "done" file is
2025 	 * also formatted like the git-rebase-todo file. These files can be found in
2026 	 * .git/rebase-merge/ or .git/rebase-append/ folders.
2027 	 *
2028 	 * @param path
2029 	 *            path to the file relative to the repository's git-dir. E.g.
2030 	 *            "rebase-merge/git-rebase-todo" or "rebase-append/done"
2031 	 * @param includeComments
2032 	 *            <code>true</code> if also comments should be reported
2033 	 * @return the list of steps
2034 	 * @throws java.io.IOException
2035 	 * @since 3.2
2036 	 */
2037 	@NonNull
2038 	public List<RebaseTodoLine> readRebaseTodo(String path,
2039 			boolean includeComments)
2040 			throws IOException {
2041 		return new RebaseTodoFile(this).readRebaseTodo(path, includeComments);
2042 	}
2043 
2044 	/**
2045 	 * Write a file formatted like a git-rebase-todo file.
2046 	 *
2047 	 * @param path
2048 	 *            path to the file relative to the repository's git-dir. E.g.
2049 	 *            "rebase-merge/git-rebase-todo" or "rebase-append/done"
2050 	 * @param steps
2051 	 *            the steps to be written
2052 	 * @param append
2053 	 *            whether to append to an existing file or to write a new file
2054 	 * @throws java.io.IOException
2055 	 * @since 3.2
2056 	 */
2057 	public void writeRebaseTodoFile(String path, List<RebaseTodoLine> steps,
2058 			boolean append)
2059 			throws IOException {
2060 		new RebaseTodoFile(this).writeRebaseTodoFile(path, steps, append);
2061 	}
2062 
2063 	/**
2064 	 * Get the names of all known remotes
2065 	 *
2066 	 * @return the names of all known remotes
2067 	 * @since 3.4
2068 	 */
2069 	@NonNull
2070 	public Set<String> getRemoteNames() {
2071 		return getConfig()
2072 				.getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION);
2073 	}
2074 
2075 	/**
2076 	 * Check whether any housekeeping is required; if yes, run garbage
2077 	 * collection; if not, exit without performing any work. Some JGit commands
2078 	 * run autoGC after performing operations that could create many loose
2079 	 * objects.
2080 	 * <p>
2081 	 * Currently this option is supported for repositories of type
2082 	 * {@code FileRepository} only. See
2083 	 * {@link org.eclipse.jgit.internal.storage.file.GC#setAuto(boolean)} for
2084 	 * configuration details.
2085 	 *
2086 	 * @param monitor
2087 	 *            to report progress
2088 	 * @since 4.6
2089 	 */
2090 	public void autoGC(ProgressMonitor monitor) {
2091 		// default does nothing
2092 	}
2093 }