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