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 a
1055 	 * client trying to push changes avoid pushing more than it needs to.
1056 	 *
1057 	 * @return unmodifiable collection of other known objects.
1058 	 * @throws IOException
1059 	 */
1060 	@NonNull
1061 	public Set<ObjectId> getAdditionalHaves() throws IOException {
1062 		return Collections.emptySet();
1063 	}
1064 
1065 	/**
1066 	 * Get a ref by name.
1067 	 *
1068 	 * @param name
1069 	 *            the name of the ref to lookup. Must not be a short-hand
1070 	 *            form; e.g., "master" is not automatically expanded to
1071 	 *            "refs/heads/master".
1072 	 * @return the Ref with the given name, or {@code null} if it does not exist
1073 	 * @throws java.io.IOException
1074 	 * @since 4.2
1075 	 */
1076 	@Nullable
1077 	public final Ref exactRef(String name) throws IOException {
1078 		return getRefDatabase().exactRef(name);
1079 	}
1080 
1081 	/**
1082 	 * Search for a ref by (possibly abbreviated) name.
1083 	 *
1084 	 * @param name
1085 	 *            the name of the ref to lookup. May be a short-hand form, e.g.
1086 	 *            "master" which is automatically expanded to
1087 	 *            "refs/heads/master" if "refs/heads/master" already exists.
1088 	 * @return the Ref with the given name, or {@code null} if it does not exist
1089 	 * @throws java.io.IOException
1090 	 * @since 4.2
1091 	 */
1092 	@Nullable
1093 	public final Ref findRef(String name) throws IOException {
1094 		return getRefDatabase().findRef(name);
1095 	}
1096 
1097 	/**
1098 	 * Get mutable map of all known refs, including symrefs like HEAD that may
1099 	 * not point to any object yet.
1100 	 *
1101 	 * @return mutable map of all known refs (heads, tags, remotes).
1102 	 * @deprecated use {@code getRefDatabase().getRefs()} instead.
1103 	 */
1104 	@Deprecated
1105 	@NonNull
1106 	public Map<String, Ref> getAllRefs() {
1107 		try {
1108 			return getRefDatabase().getRefs(RefDatabase.ALL);
1109 		} catch (IOException e) {
1110 			throw new UncheckedIOException(e);
1111 		}
1112 	}
1113 
1114 	/**
1115 	 * Get mutable map of all tags
1116 	 *
1117 	 * @return mutable map of all tags; key is short tag name ("v1.0") and value
1118 	 *         of the entry contains the ref with the full tag name
1119 	 *         ("refs/tags/v1.0").
1120 	 * @deprecated use {@code getRefDatabase().getRefsByPrefix(R_TAGS)} instead
1121 	 */
1122 	@Deprecated
1123 	@NonNull
1124 	public Map<String, Ref> getTags() {
1125 		try {
1126 			return getRefDatabase().getRefs(Constants.R_TAGS);
1127 		} catch (IOException e) {
1128 			throw new UncheckedIOException(e);
1129 		}
1130 	}
1131 
1132 	/**
1133 	 * Peel a possibly unpeeled reference to an annotated tag.
1134 	 * <p>
1135 	 * If the ref cannot be peeled (as it does not refer to an annotated tag)
1136 	 * the peeled id stays null, but {@link org.eclipse.jgit.lib.Ref#isPeeled()}
1137 	 * will be true.
1138 	 *
1139 	 * @param ref
1140 	 *            The ref to peel
1141 	 * @return <code>ref</code> if <code>ref.isPeeled()</code> is true; else a
1142 	 *         new Ref object representing the same data as Ref, but isPeeled()
1143 	 *         will be true and getPeeledObjectId will contain the peeled object
1144 	 *         (or null).
1145 	 * @deprecated use {@code getRefDatabase().peel(ref)} instead.
1146 	 */
1147 	@Deprecated
1148 	@NonNull
1149 	public Ref peel(Ref ref) {
1150 		try {
1151 			return getRefDatabase().peel(ref);
1152 		} catch (IOException e) {
1153 			// Historical accident; if the reference cannot be peeled due
1154 			// to some sort of repository access problem we claim that the
1155 			// same as if the reference was not an annotated tag.
1156 			return ref;
1157 		}
1158 	}
1159 
1160 	/**
1161 	 * Get a map with all objects referenced by a peeled ref.
1162 	 *
1163 	 * @return a map with all objects referenced by a peeled ref.
1164 	 * @throws IOException
1165 	 */
1166 	@NonNull
1167 	public Map<AnyObjectId, Set<Ref>> getAllRefsByPeeledObjectId()
1168 			throws IOException {
1169 		List<Ref> allRefs = getRefDatabase().getRefs();
1170 		Map<AnyObjectId, Set<Ref>> ret = new HashMap<>(allRefs.size());
1171 		for (Ref ref : allRefs) {
1172 			ref = peel(ref);
1173 			AnyObjectId target = ref.getPeeledObjectId();
1174 			if (target == null)
1175 				target = ref.getObjectId();
1176 			// We assume most Sets here are singletons
1177 			Set<Ref> oset = ret.put(target, Collections.singleton(ref));
1178 			if (oset != null) {
1179 				// that was not the case (rare)
1180 				if (oset.size() == 1) {
1181 					// Was a read-only singleton, we must copy to a new Set
1182 					oset = new HashSet<>(oset);
1183 				}
1184 				ret.put(target, oset);
1185 				oset.add(ref);
1186 			}
1187 		}
1188 		return ret;
1189 	}
1190 
1191 	/**
1192 	 * Get the index file location or {@code null} if repository isn't local.
1193 	 *
1194 	 * @return the index file location or {@code null} if repository isn't
1195 	 *         local.
1196 	 * @throws org.eclipse.jgit.errors.NoWorkTreeException
1197 	 *             if this is bare, which implies it has no working directory.
1198 	 *             See {@link #isBare()}.
1199 	 */
1200 	@NonNull
1201 	public File getIndexFile() throws NoWorkTreeException {
1202 		if (isBare())
1203 			throw new NoWorkTreeException();
1204 		return indexFile;
1205 	}
1206 
1207 	/**
1208 	 * Locate a reference to a commit and immediately parse its content.
1209 	 * <p>
1210 	 * This method only returns successfully if the commit object exists,
1211 	 * is verified to be a commit, and was parsed without error.
1212 	 *
1213 	 * @param id
1214 	 *            name of the commit object.
1215 	 * @return reference to the commit object. Never null.
1216 	 * @throws org.eclipse.jgit.errors.MissingObjectException
1217 	 *             the supplied commit does not exist.
1218 	 * @throws org.eclipse.jgit.errors.IncorrectObjectTypeException
1219 	 *             the supplied id is not a commit or an annotated tag.
1220 	 * @throws java.io.IOException
1221 	 *             a pack file or loose object could not be read.
1222 	 * @since 4.8
1223 	 */
1224 	public RevCommit parseCommit(AnyObjectId id) throws IncorrectObjectTypeException,
1225 			IOException, MissingObjectException {
1226 		if (id instanceof RevCommit && ((RevCommit) id).getRawBuffer() != null) {
1227 			return (RevCommit) id;
1228 		}
1229 		try (RevWalk walk = new RevWalk(this)) {
1230 			return walk.parseCommit(id);
1231 		}
1232 	}
1233 
1234 	/**
1235 	 * Create a new in-core index representation and read an index from disk.
1236 	 * <p>
1237 	 * The new index will be read before it is returned to the caller. Read
1238 	 * failures are reported as exceptions and therefore prevent the method from
1239 	 * returning a partially populated index.
1240 	 *
1241 	 * @return a cache representing the contents of the specified index file (if
1242 	 *         it exists) or an empty cache if the file does not exist.
1243 	 * @throws org.eclipse.jgit.errors.NoWorkTreeException
1244 	 *             if this is bare, which implies it has no working directory.
1245 	 *             See {@link #isBare()}.
1246 	 * @throws java.io.IOException
1247 	 *             the index file is present but could not be read.
1248 	 * @throws org.eclipse.jgit.errors.CorruptObjectException
1249 	 *             the index file is using a format or extension that this
1250 	 *             library does not support.
1251 	 */
1252 	@NonNull
1253 	public DirCache readDirCache() throws NoWorkTreeException,
1254 			CorruptObjectException, IOException {
1255 		return DirCache.read(this);
1256 	}
1257 
1258 	/**
1259 	 * Create a new in-core index representation, lock it, and read from disk.
1260 	 * <p>
1261 	 * The new index will be locked and then read before it is returned to the
1262 	 * caller. Read failures are reported as exceptions and therefore prevent
1263 	 * the method from returning a partially populated index.
1264 	 *
1265 	 * @return a cache representing the contents of the specified index file (if
1266 	 *         it exists) or an empty cache if the file does not exist.
1267 	 * @throws org.eclipse.jgit.errors.NoWorkTreeException
1268 	 *             if this is bare, which implies it has no working directory.
1269 	 *             See {@link #isBare()}.
1270 	 * @throws java.io.IOException
1271 	 *             the index file is present but could not be read, or the lock
1272 	 *             could not be obtained.
1273 	 * @throws org.eclipse.jgit.errors.CorruptObjectException
1274 	 *             the index file is using a format or extension that this
1275 	 *             library does not support.
1276 	 */
1277 	@NonNull
1278 	public DirCache lockDirCache() throws NoWorkTreeException,
1279 			CorruptObjectException, IOException {
1280 		// we want DirCache to inform us so that we can inform registered
1281 		// listeners about index changes
1282 		IndexChangedListener l = (IndexChangedEvent event) -> {
1283 			notifyIndexChanged(true);
1284 		};
1285 		return DirCache.lock(this, l);
1286 	}
1287 
1288 	/**
1289 	 * Get the repository state
1290 	 *
1291 	 * @return the repository state
1292 	 */
1293 	@NonNull
1294 	public RepositoryState getRepositoryState() {
1295 		if (isBare() || getDirectory() == null)
1296 			return RepositoryState.BARE;
1297 
1298 		// Pre Git-1.6 logic
1299 		if (new File(getWorkTree(), ".dotest").exists()) //$NON-NLS-1$
1300 			return RepositoryState.REBASING;
1301 		if (new File(getDirectory(), ".dotest-merge").exists()) //$NON-NLS-1$
1302 			return RepositoryState.REBASING_INTERACTIVE;
1303 
1304 		// From 1.6 onwards
1305 		if (new File(getDirectory(),"rebase-apply/rebasing").exists()) //$NON-NLS-1$
1306 			return RepositoryState.REBASING_REBASING;
1307 		if (new File(getDirectory(),"rebase-apply/applying").exists()) //$NON-NLS-1$
1308 			return RepositoryState.APPLY;
1309 		if (new File(getDirectory(),"rebase-apply").exists()) //$NON-NLS-1$
1310 			return RepositoryState.REBASING;
1311 
1312 		if (new File(getDirectory(),"rebase-merge/interactive").exists()) //$NON-NLS-1$
1313 			return RepositoryState.REBASING_INTERACTIVE;
1314 		if (new File(getDirectory(),"rebase-merge").exists()) //$NON-NLS-1$
1315 			return RepositoryState.REBASING_MERGE;
1316 
1317 		// Both versions
1318 		if (new File(getDirectory(), Constants.MERGE_HEAD).exists()) {
1319 			// we are merging - now check whether we have unmerged paths
1320 			try {
1321 				if (!readDirCache().hasUnmergedPaths()) {
1322 					// no unmerged paths -> return the MERGING_RESOLVED state
1323 					return RepositoryState.MERGING_RESOLVED;
1324 				}
1325 			} catch (IOException e) {
1326 				throw new UncheckedIOException(e);
1327 			}
1328 			return RepositoryState.MERGING;
1329 		}
1330 
1331 		if (new File(getDirectory(), "BISECT_LOG").exists()) //$NON-NLS-1$
1332 			return RepositoryState.BISECTING;
1333 
1334 		if (new File(getDirectory(), Constants.CHERRY_PICK_HEAD).exists()) {
1335 			try {
1336 				if (!readDirCache().hasUnmergedPaths()) {
1337 					// no unmerged paths
1338 					return RepositoryState.CHERRY_PICKING_RESOLVED;
1339 				}
1340 			} catch (IOException e) {
1341 				throw new UncheckedIOException(e);
1342 			}
1343 
1344 			return RepositoryState.CHERRY_PICKING;
1345 		}
1346 
1347 		if (new File(getDirectory(), Constants.REVERT_HEAD).exists()) {
1348 			try {
1349 				if (!readDirCache().hasUnmergedPaths()) {
1350 					// no unmerged paths
1351 					return RepositoryState.REVERTING_RESOLVED;
1352 				}
1353 			} catch (IOException e) {
1354 				throw new UncheckedIOException(e);
1355 			}
1356 
1357 			return RepositoryState.REVERTING;
1358 		}
1359 
1360 		return RepositoryState.SAFE;
1361 	}
1362 
1363 	/**
1364 	 * Check validity of a ref name. It must not contain character that has
1365 	 * a special meaning in a Git object reference expression. Some other
1366 	 * dangerous characters are also excluded.
1367 	 *
1368 	 * For portability reasons '\' is excluded
1369 	 *
1370 	 * @param refName a {@link java.lang.String} object.
1371 	 * @return true if refName is a valid ref name
1372 	 */
1373 	public static boolean isValidRefName(String refName) {
1374 		final int len = refName.length();
1375 		if (len == 0) {
1376 			return false;
1377 		}
1378 		if (refName.endsWith(LOCK_SUFFIX)) {
1379 			return false;
1380 		}
1381 
1382 		// Refs may be stored as loose files so invalid paths
1383 		// on the local system must also be invalid refs.
1384 		try {
1385 			SystemReader.getInstance().checkPath(refName);
1386 		} catch (CorruptObjectException e) {
1387 			return false;
1388 		}
1389 
1390 		int components = 1;
1391 		char p = '\0';
1392 		for (int i = 0; i < len; i++) {
1393 			final char c = refName.charAt(i);
1394 			if (c <= ' ')
1395 				return false;
1396 			switch (c) {
1397 			case '.':
1398 				switch (p) {
1399 				case '\0': case '/': case '.':
1400 					return false;
1401 				}
1402 				if (i == len -1)
1403 					return false;
1404 				break;
1405 			case '/':
1406 				if (i == 0 || i == len - 1)
1407 					return false;
1408 				if (p == '/')
1409 					return false;
1410 				components++;
1411 				break;
1412 			case '{':
1413 				if (p == '@')
1414 					return false;
1415 				break;
1416 			case '~': case '^': case ':':
1417 			case '?': case '[': case '*':
1418 			case '\\':
1419 			case '\u007F':
1420 				return false;
1421 			}
1422 			p = c;
1423 		}
1424 		return components > 1;
1425 	}
1426 
1427 	/**
1428 	 * Normalizes the passed branch name into a possible valid branch name. The
1429 	 * validity of the returned name should be checked by a subsequent call to
1430 	 * {@link #isValidRefName(String)}.
1431 	 * <p>
1432 	 * Future implementations of this method could be more restrictive or more
1433 	 * lenient about the validity of specific characters in the returned name.
1434 	 * <p>
1435 	 * The current implementation returns the trimmed input string if this is
1436 	 * already a valid branch name. Otherwise it returns a trimmed string with
1437 	 * special characters not allowed by {@link #isValidRefName(String)}
1438 	 * replaced by hyphens ('-') and blanks replaced by underscores ('_').
1439 	 * Leading and trailing slashes, dots, hyphens, and underscores are removed.
1440 	 *
1441 	 * @param name
1442 	 *            to normalize
1443 	 * @return The normalized name or an empty String if it is {@code null} or
1444 	 *         empty.
1445 	 * @since 4.7
1446 	 * @see #isValidRefName(String)
1447 	 */
1448 	public static String normalizeBranchName(String name) {
1449 		if (name == null || name.isEmpty()) {
1450 			return ""; //$NON-NLS-1$
1451 		}
1452 		String result = name.trim();
1453 		String fullName = result.startsWith(Constants.R_HEADS) ? result
1454 				: Constants.R_HEADS + result;
1455 		if (isValidRefName(fullName)) {
1456 			return result;
1457 		}
1458 
1459 		// All Unicode blanks to underscore
1460 		result = result.replaceAll("(?:\\h|\\v)+", "_"); //$NON-NLS-1$ //$NON-NLS-2$
1461 		StringBuilder b = new StringBuilder();
1462 		char p = '/';
1463 		for (int i = 0, len = result.length(); i < len; i++) {
1464 			char c = result.charAt(i);
1465 			if (c < ' ' || c == 127) {
1466 				continue;
1467 			}
1468 			// Substitute a dash for problematic characters
1469 			switch (c) {
1470 			case '\\':
1471 			case '^':
1472 			case '~':
1473 			case ':':
1474 			case '?':
1475 			case '*':
1476 			case '[':
1477 			case '@':
1478 			case '<':
1479 			case '>':
1480 			case '|':
1481 			case '"':
1482 				c = '-';
1483 				break;
1484 			default:
1485 				break;
1486 			}
1487 			// Collapse multiple slashes, dashes, dots, underscores, and omit
1488 			// dashes, dots, and underscores following a slash.
1489 			switch (c) {
1490 			case '/':
1491 				if (p == '/') {
1492 					continue;
1493 				}
1494 				p = '/';
1495 				break;
1496 			case '.':
1497 			case '_':
1498 			case '-':
1499 				if (p == '/' || p == '-') {
1500 					continue;
1501 				}
1502 				p = '-';
1503 				break;
1504 			default:
1505 				p = c;
1506 				break;
1507 			}
1508 			b.append(c);
1509 		}
1510 		// Strip trailing special characters, and avoid the .lock extension
1511 		result = b.toString().replaceFirst("[/_.-]+$", "") //$NON-NLS-1$ //$NON-NLS-2$
1512 				.replaceAll("\\.lock($|/)", "_lock$1"); //$NON-NLS-1$ //$NON-NLS-2$
1513 		return FORBIDDEN_BRANCH_NAME_COMPONENTS.matcher(result)
1514 				.replaceAll("$1+$2$3"); //$NON-NLS-1$
1515 	}
1516 
1517 	/**
1518 	 * Strip work dir and return normalized repository path.
1519 	 *
1520 	 * @param workDir
1521 	 *            Work dir
1522 	 * @param file
1523 	 *            File whose path shall be stripped of its workdir
1524 	 * @return normalized repository relative path or the empty string if the
1525 	 *         file is not relative to the work directory.
1526 	 */
1527 	@NonNull
1528 	public static String stripWorkDir(File workDir, File file) {
1529 		final String filePath = file.getPath();
1530 		final String workDirPath = workDir.getPath();
1531 
1532 		if (filePath.length() <= workDirPath.length()
1533 				|| filePath.charAt(workDirPath.length()) != File.separatorChar
1534 				|| !filePath.startsWith(workDirPath)) {
1535 			File absWd = workDir.isAbsolute() ? workDir
1536 					: workDir.getAbsoluteFile();
1537 			File absFile = file.isAbsolute() ? file : file.getAbsoluteFile();
1538 			if (absWd.equals(workDir) && absFile.equals(file)) {
1539 				return ""; //$NON-NLS-1$
1540 			}
1541 			return stripWorkDir(absWd, absFile);
1542 		}
1543 
1544 		String relName = filePath.substring(workDirPath.length() + 1);
1545 		if (File.separatorChar != '/') {
1546 			relName = relName.replace(File.separatorChar, '/');
1547 		}
1548 		return relName;
1549 	}
1550 
1551 	/**
1552 	 * Whether this repository is bare
1553 	 *
1554 	 * @return true if this is bare, which implies it has no working directory.
1555 	 */
1556 	public boolean isBare() {
1557 		return workTree == null;
1558 	}
1559 
1560 	/**
1561 	 * Get the root directory of the working tree, where files are checked out
1562 	 * for viewing and editing.
1563 	 *
1564 	 * @return the root directory of the working tree, where files are checked
1565 	 *         out for viewing and editing.
1566 	 * @throws org.eclipse.jgit.errors.NoWorkTreeException
1567 	 *             if this is bare, which implies it has no working directory.
1568 	 *             See {@link #isBare()}.
1569 	 */
1570 	@NonNull
1571 	public File getWorkTree() throws NoWorkTreeException {
1572 		if (isBare())
1573 			throw new NoWorkTreeException();
1574 		return workTree;
1575 	}
1576 
1577 	/**
1578 	 * Force a scan for changed refs. Fires an IndexChangedEvent(false) if
1579 	 * changes are detected.
1580 	 *
1581 	 * @throws java.io.IOException
1582 	 */
1583 	public abstract void scanForRepoChanges() throws IOException;
1584 
1585 	/**
1586 	 * Notify that the index changed by firing an IndexChangedEvent.
1587 	 *
1588 	 * @param internal
1589 	 *                     {@code true} if the index was changed by the same
1590 	 *                     JGit process
1591 	 * @since 5.0
1592 	 */
1593 	public abstract void notifyIndexChanged(boolean internal);
1594 
1595 	/**
1596 	 * Get a shortened more user friendly ref name
1597 	 *
1598 	 * @param refName
1599 	 *            a {@link java.lang.String} object.
1600 	 * @return a more user friendly ref name
1601 	 */
1602 	@NonNull
1603 	public static String shortenRefName(String refName) {
1604 		if (refName.startsWith(Constants.R_HEADS))
1605 			return refName.substring(Constants.R_HEADS.length());
1606 		if (refName.startsWith(Constants.R_TAGS))
1607 			return refName.substring(Constants.R_TAGS.length());
1608 		if (refName.startsWith(Constants.R_REMOTES))
1609 			return refName.substring(Constants.R_REMOTES.length());
1610 		return refName;
1611 	}
1612 
1613 	/**
1614 	 * Get a shortened more user friendly remote tracking branch name
1615 	 *
1616 	 * @param refName
1617 	 *            a {@link java.lang.String} object.
1618 	 * @return the remote branch name part of <code>refName</code>, i.e. without
1619 	 *         the <code>refs/remotes/&lt;remote&gt;</code> prefix, if
1620 	 *         <code>refName</code> represents a remote tracking branch;
1621 	 *         otherwise {@code null}.
1622 	 * @since 3.4
1623 	 */
1624 	@Nullable
1625 	public String shortenRemoteBranchName(String refName) {
1626 		for (String remote : getRemoteNames()) {
1627 			String remotePrefix = Constants.R_REMOTES + remote + "/"; //$NON-NLS-1$
1628 			if (refName.startsWith(remotePrefix))
1629 				return refName.substring(remotePrefix.length());
1630 		}
1631 		return null;
1632 	}
1633 
1634 	/**
1635 	 * Get remote name
1636 	 *
1637 	 * @param refName
1638 	 *            a {@link java.lang.String} object.
1639 	 * @return the remote name part of <code>refName</code>, i.e. without the
1640 	 *         <code>refs/remotes/&lt;remote&gt;</code> prefix, if
1641 	 *         <code>refName</code> represents a remote tracking branch;
1642 	 *         otherwise {@code null}.
1643 	 * @since 3.4
1644 	 */
1645 	@Nullable
1646 	public String getRemoteName(String refName) {
1647 		for (String remote : getRemoteNames()) {
1648 			String remotePrefix = Constants.R_REMOTES + remote + "/"; //$NON-NLS-1$
1649 			if (refName.startsWith(remotePrefix))
1650 				return remote;
1651 		}
1652 		return null;
1653 	}
1654 
1655 	/**
1656 	 * Read the {@code GIT_DIR/description} file for gitweb.
1657 	 *
1658 	 * @return description text; null if no description has been configured.
1659 	 * @throws java.io.IOException
1660 	 *             description cannot be accessed.
1661 	 * @since 4.6
1662 	 */
1663 	@Nullable
1664 	public String getGitwebDescription() throws IOException {
1665 		return null;
1666 	}
1667 
1668 	/**
1669 	 * Set the {@code GIT_DIR/description} file for gitweb.
1670 	 *
1671 	 * @param description
1672 	 *            new description; null to clear the description.
1673 	 * @throws java.io.IOException
1674 	 *             description cannot be persisted.
1675 	 * @since 4.6
1676 	 */
1677 	public void setGitwebDescription(@Nullable String description)
1678 			throws IOException {
1679 		throw new IOException(JGitText.get().unsupportedRepositoryDescription);
1680 	}
1681 
1682 	/**
1683 	 * Get the reflog reader
1684 	 *
1685 	 * @param refName
1686 	 *            a {@link java.lang.String} object.
1687 	 * @return a {@link org.eclipse.jgit.lib.ReflogReader} for the supplied
1688 	 *         refname, or {@code null} if the named ref does not exist.
1689 	 * @throws java.io.IOException
1690 	 *             the ref could not be accessed.
1691 	 * @since 3.0
1692 	 */
1693 	@Nullable
1694 	public abstract ReflogReader getReflogReader(String refName)
1695 			throws IOException;
1696 
1697 	/**
1698 	 * Return the information stored in the file $GIT_DIR/MERGE_MSG. In this
1699 	 * file operations triggering a merge will store a template for the commit
1700 	 * message of the merge commit.
1701 	 *
1702 	 * @return a String containing the content of the MERGE_MSG file or
1703 	 *         {@code null} if this file doesn't exist
1704 	 * @throws java.io.IOException
1705 	 * @throws org.eclipse.jgit.errors.NoWorkTreeException
1706 	 *             if this is bare, which implies it has no working directory.
1707 	 *             See {@link #isBare()}.
1708 	 */
1709 	@Nullable
1710 	public String readMergeCommitMsg() throws IOException, NoWorkTreeException {
1711 		return readCommitMsgFile(Constants.MERGE_MSG);
1712 	}
1713 
1714 	/**
1715 	 * Write new content to the file $GIT_DIR/MERGE_MSG. In this file operations
1716 	 * triggering a merge will store a template for the commit message of the
1717 	 * merge commit. If <code>null</code> is specified as message the file will
1718 	 * be deleted.
1719 	 *
1720 	 * @param msg
1721 	 *            the message which should be written or <code>null</code> to
1722 	 *            delete the file
1723 	 * @throws java.io.IOException
1724 	 */
1725 	public void writeMergeCommitMsg(String msg) throws IOException {
1726 		File mergeMsgFile = new File(gitDir, Constants.MERGE_MSG);
1727 		writeCommitMsg(mergeMsgFile, msg);
1728 	}
1729 
1730 	/**
1731 	 * Return the information stored in the file $GIT_DIR/COMMIT_EDITMSG. In
1732 	 * this file hooks triggered by an operation may read or modify the current
1733 	 * commit message.
1734 	 *
1735 	 * @return a String containing the content of the COMMIT_EDITMSG file or
1736 	 *         {@code null} if this file doesn't exist
1737 	 * @throws java.io.IOException
1738 	 * @throws org.eclipse.jgit.errors.NoWorkTreeException
1739 	 *             if this is bare, which implies it has no working directory.
1740 	 *             See {@link #isBare()}.
1741 	 * @since 4.0
1742 	 */
1743 	@Nullable
1744 	public String readCommitEditMsg() throws IOException, NoWorkTreeException {
1745 		return readCommitMsgFile(Constants.COMMIT_EDITMSG);
1746 	}
1747 
1748 	/**
1749 	 * Write new content to the file $GIT_DIR/COMMIT_EDITMSG. In this file hooks
1750 	 * triggered by an operation may read or modify the current commit message.
1751 	 * If {@code null} is specified as message the file will be deleted.
1752 	 *
1753 	 * @param msg
1754 	 *            the message which should be written or {@code null} to delete
1755 	 *            the file
1756 	 * @throws java.io.IOException
1757 	 * @since 4.0
1758 	 */
1759 	public void writeCommitEditMsg(String msg) throws IOException {
1760 		File commiEditMsgFile = new File(gitDir, Constants.COMMIT_EDITMSG);
1761 		writeCommitMsg(commiEditMsgFile, msg);
1762 	}
1763 
1764 	/**
1765 	 * Return the information stored in the file $GIT_DIR/MERGE_HEAD. In this
1766 	 * file operations triggering a merge will store the IDs of all heads which
1767 	 * should be merged together with HEAD.
1768 	 *
1769 	 * @return a list of commits which IDs are listed in the MERGE_HEAD file or
1770 	 *         {@code null} if this file doesn't exist. Also if the file exists
1771 	 *         but is empty {@code null} will be returned
1772 	 * @throws java.io.IOException
1773 	 * @throws org.eclipse.jgit.errors.NoWorkTreeException
1774 	 *             if this is bare, which implies it has no working directory.
1775 	 *             See {@link #isBare()}.
1776 	 */
1777 	@Nullable
1778 	public List<ObjectId> readMergeHeads() throws IOException, NoWorkTreeException {
1779 		if (isBare() || getDirectory() == null)
1780 			throw new NoWorkTreeException();
1781 
1782 		byte[] raw = readGitDirectoryFile(Constants.MERGE_HEAD);
1783 		if (raw == null)
1784 			return null;
1785 
1786 		LinkedList<ObjectId> heads = new LinkedList<>();
1787 		for (int p = 0; p < raw.length;) {
1788 			heads.add(ObjectId.fromString(raw, p));
1789 			p = RawParseUtils
1790 					.nextLF(raw, p + Constants.OBJECT_ID_STRING_LENGTH);
1791 		}
1792 		return heads;
1793 	}
1794 
1795 	/**
1796 	 * Write new merge-heads into $GIT_DIR/MERGE_HEAD. In this file operations
1797 	 * triggering a merge will store the IDs of all heads which should be merged
1798 	 * together with HEAD. If <code>null</code> is specified as list of commits
1799 	 * the file will be deleted
1800 	 *
1801 	 * @param heads
1802 	 *            a list of commits which IDs should be written to
1803 	 *            $GIT_DIR/MERGE_HEAD or <code>null</code> to delete the file
1804 	 * @throws java.io.IOException
1805 	 */
1806 	public void writeMergeHeads(List<? extends ObjectId> heads) throws IOException {
1807 		writeHeadsFile(heads, Constants.MERGE_HEAD);
1808 	}
1809 
1810 	/**
1811 	 * Return the information stored in the file $GIT_DIR/CHERRY_PICK_HEAD.
1812 	 *
1813 	 * @return object id from CHERRY_PICK_HEAD file or {@code null} if this file
1814 	 *         doesn't exist. Also if the file exists but is empty {@code null}
1815 	 *         will be returned
1816 	 * @throws java.io.IOException
1817 	 * @throws org.eclipse.jgit.errors.NoWorkTreeException
1818 	 *             if this is bare, which implies it has no working directory.
1819 	 *             See {@link #isBare()}.
1820 	 */
1821 	@Nullable
1822 	public ObjectId readCherryPickHead() throws IOException,
1823 			NoWorkTreeException {
1824 		if (isBare() || getDirectory() == null)
1825 			throw new NoWorkTreeException();
1826 
1827 		byte[] raw = readGitDirectoryFile(Constants.CHERRY_PICK_HEAD);
1828 		if (raw == null)
1829 			return null;
1830 
1831 		return ObjectId.fromString(raw, 0);
1832 	}
1833 
1834 	/**
1835 	 * Return the information stored in the file $GIT_DIR/REVERT_HEAD.
1836 	 *
1837 	 * @return object id from REVERT_HEAD file or {@code null} if this file
1838 	 *         doesn't exist. Also if the file exists but is empty {@code null}
1839 	 *         will be returned
1840 	 * @throws java.io.IOException
1841 	 * @throws org.eclipse.jgit.errors.NoWorkTreeException
1842 	 *             if this is bare, which implies it has no working directory.
1843 	 *             See {@link #isBare()}.
1844 	 */
1845 	@Nullable
1846 	public ObjectId readRevertHead() throws IOException, NoWorkTreeException {
1847 		if (isBare() || getDirectory() == null)
1848 			throw new NoWorkTreeException();
1849 
1850 		byte[] raw = readGitDirectoryFile(Constants.REVERT_HEAD);
1851 		if (raw == null)
1852 			return null;
1853 		return ObjectId.fromString(raw, 0);
1854 	}
1855 
1856 	/**
1857 	 * Write cherry pick commit into $GIT_DIR/CHERRY_PICK_HEAD. This is used in
1858 	 * case of conflicts to store the cherry which was tried to be picked.
1859 	 *
1860 	 * @param head
1861 	 *            an object id of the cherry commit or <code>null</code> to
1862 	 *            delete the file
1863 	 * @throws java.io.IOException
1864 	 */
1865 	public void writeCherryPickHead(ObjectId head) throws IOException {
1866 		List<ObjectId> heads = (head != null) ? Collections.singletonList(head)
1867 				: null;
1868 		writeHeadsFile(heads, Constants.CHERRY_PICK_HEAD);
1869 	}
1870 
1871 	/**
1872 	 * Write revert commit into $GIT_DIR/REVERT_HEAD. This is used in case of
1873 	 * conflicts to store the revert which was tried to be picked.
1874 	 *
1875 	 * @param head
1876 	 *            an object id of the revert commit or <code>null</code> to
1877 	 *            delete the file
1878 	 * @throws java.io.IOException
1879 	 */
1880 	public void writeRevertHead(ObjectId head) throws IOException {
1881 		List<ObjectId> heads = (head != null) ? Collections.singletonList(head)
1882 				: null;
1883 		writeHeadsFile(heads, Constants.REVERT_HEAD);
1884 	}
1885 
1886 	/**
1887 	 * Write original HEAD commit into $GIT_DIR/ORIG_HEAD.
1888 	 *
1889 	 * @param head
1890 	 *            an object id of the original HEAD commit or <code>null</code>
1891 	 *            to delete the file
1892 	 * @throws java.io.IOException
1893 	 */
1894 	public void writeOrigHead(ObjectId head) throws IOException {
1895 		List<ObjectId> heads = head != null ? Collections.singletonList(head)
1896 				: null;
1897 		writeHeadsFile(heads, Constants.ORIG_HEAD);
1898 	}
1899 
1900 	/**
1901 	 * Return the information stored in the file $GIT_DIR/ORIG_HEAD.
1902 	 *
1903 	 * @return object id from ORIG_HEAD file or {@code null} if this file
1904 	 *         doesn't exist. Also if the file exists but is empty {@code null}
1905 	 *         will be returned
1906 	 * @throws java.io.IOException
1907 	 * @throws org.eclipse.jgit.errors.NoWorkTreeException
1908 	 *             if this is bare, which implies it has no working directory.
1909 	 *             See {@link #isBare()}.
1910 	 */
1911 	@Nullable
1912 	public ObjectId readOrigHead() throws IOException, NoWorkTreeException {
1913 		if (isBare() || getDirectory() == null)
1914 			throw new NoWorkTreeException();
1915 
1916 		byte[] raw = readGitDirectoryFile(Constants.ORIG_HEAD);
1917 		return raw != null ? ObjectId.fromString(raw, 0) : null;
1918 	}
1919 
1920 	/**
1921 	 * Return the information stored in the file $GIT_DIR/SQUASH_MSG. In this
1922 	 * file operations triggering a squashed merge will store a template for the
1923 	 * commit message of the squash commit.
1924 	 *
1925 	 * @return a String containing the content of the SQUASH_MSG file or
1926 	 *         {@code null} if this file doesn't exist
1927 	 * @throws java.io.IOException
1928 	 * @throws NoWorkTreeException
1929 	 *             if this is bare, which implies it has no working directory.
1930 	 *             See {@link #isBare()}.
1931 	 */
1932 	@Nullable
1933 	public String readSquashCommitMsg() throws IOException {
1934 		return readCommitMsgFile(Constants.SQUASH_MSG);
1935 	}
1936 
1937 	/**
1938 	 * Write new content to the file $GIT_DIR/SQUASH_MSG. In this file
1939 	 * operations triggering a squashed merge will store a template for the
1940 	 * commit message of the squash commit. If <code>null</code> is specified as
1941 	 * message the file will be deleted.
1942 	 *
1943 	 * @param msg
1944 	 *            the message which should be written or <code>null</code> to
1945 	 *            delete the file
1946 	 * @throws java.io.IOException
1947 	 */
1948 	public void writeSquashCommitMsg(String msg) throws IOException {
1949 		File squashMsgFile = new File(gitDir, Constants.SQUASH_MSG);
1950 		writeCommitMsg(squashMsgFile, msg);
1951 	}
1952 
1953 	@Nullable
1954 	private String readCommitMsgFile(String msgFilename) throws IOException {
1955 		if (isBare() || getDirectory() == null)
1956 			throw new NoWorkTreeException();
1957 
1958 		File mergeMsgFile = new File(getDirectory(), msgFilename);
1959 		try {
1960 			return RawParseUtils.decode(IO.readFully(mergeMsgFile));
1961 		} catch (FileNotFoundException e) {
1962 			if (mergeMsgFile.exists()) {
1963 				throw e;
1964 			}
1965 			// the file has disappeared in the meantime ignore it
1966 			return null;
1967 		}
1968 	}
1969 
1970 	private void writeCommitMsg(File msgFile, String msg) throws IOException {
1971 		if (msg != null) {
1972 			try (FileOutputStream fos = new FileOutputStream(msgFile)) {
1973 				fos.write(msg.getBytes(UTF_8));
1974 			}
1975 		} else {
1976 			FileUtils.delete(msgFile, FileUtils.SKIP_MISSING);
1977 		}
1978 	}
1979 
1980 	/**
1981 	 * Read a file from the git directory.
1982 	 *
1983 	 * @param filename
1984 	 * @return the raw contents or {@code null} if the file doesn't exist or is
1985 	 *         empty
1986 	 * @throws IOException
1987 	 */
1988 	private byte[] readGitDirectoryFile(String filename) throws IOException {
1989 		File file = new File(getDirectory(), filename);
1990 		try {
1991 			byte[] raw = IO.readFully(file);
1992 			return raw.length > 0 ? raw : null;
1993 		} catch (FileNotFoundException notFound) {
1994 			if (file.exists()) {
1995 				throw notFound;
1996 			}
1997 			return null;
1998 		}
1999 	}
2000 
2001 	/**
2002 	 * Write the given heads to a file in the git directory.
2003 	 *
2004 	 * @param heads
2005 	 *            a list of object ids to write or null if the file should be
2006 	 *            deleted.
2007 	 * @param filename
2008 	 * @throws FileNotFoundException
2009 	 * @throws IOException
2010 	 */
2011 	private void writeHeadsFile(List<? extends ObjectId> heads, String filename)
2012 			throws FileNotFoundException, IOException {
2013 		File headsFile = new File(getDirectory(), filename);
2014 		if (heads != null) {
2015 			try (OutputStream bos = new BufferedOutputStream(
2016 					new FileOutputStream(headsFile))) {
2017 				for (ObjectId id : heads) {
2018 					id.copyTo(bos);
2019 					bos.write('\n');
2020 				}
2021 			}
2022 		} else {
2023 			FileUtils.delete(headsFile, FileUtils.SKIP_MISSING);
2024 		}
2025 	}
2026 
2027 	/**
2028 	 * Read a file formatted like the git-rebase-todo file. The "done" file is
2029 	 * also formatted like the git-rebase-todo file. These files can be found in
2030 	 * .git/rebase-merge/ or .git/rebase-append/ folders.
2031 	 *
2032 	 * @param path
2033 	 *            path to the file relative to the repository's git-dir. E.g.
2034 	 *            "rebase-merge/git-rebase-todo" or "rebase-append/done"
2035 	 * @param includeComments
2036 	 *            <code>true</code> if also comments should be reported
2037 	 * @return the list of steps
2038 	 * @throws java.io.IOException
2039 	 * @since 3.2
2040 	 */
2041 	@NonNull
2042 	public List<RebaseTodoLine> readRebaseTodo(String path,
2043 			boolean includeComments)
2044 			throws IOException {
2045 		return new RebaseTodoFile(this).readRebaseTodo(path, includeComments);
2046 	}
2047 
2048 	/**
2049 	 * Write a file formatted like a git-rebase-todo file.
2050 	 *
2051 	 * @param path
2052 	 *            path to the file relative to the repository's git-dir. E.g.
2053 	 *            "rebase-merge/git-rebase-todo" or "rebase-append/done"
2054 	 * @param steps
2055 	 *            the steps to be written
2056 	 * @param append
2057 	 *            whether to append to an existing file or to write a new file
2058 	 * @throws java.io.IOException
2059 	 * @since 3.2
2060 	 */
2061 	public void writeRebaseTodoFile(String path, List<RebaseTodoLine> steps,
2062 			boolean append)
2063 			throws IOException {
2064 		new RebaseTodoFile(this).writeRebaseTodoFile(path, steps, append);
2065 	}
2066 
2067 	/**
2068 	 * Get the names of all known remotes
2069 	 *
2070 	 * @return the names of all known remotes
2071 	 * @since 3.4
2072 	 */
2073 	@NonNull
2074 	public Set<String> getRemoteNames() {
2075 		return getConfig()
2076 				.getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION);
2077 	}
2078 
2079 	/**
2080 	 * Check whether any housekeeping is required; if yes, run garbage
2081 	 * collection; if not, exit without performing any work. Some JGit commands
2082 	 * run autoGC after performing operations that could create many loose
2083 	 * objects.
2084 	 * <p>
2085 	 * Currently this option is supported for repositories of type
2086 	 * {@code FileRepository} only. See
2087 	 * {@link org.eclipse.jgit.internal.storage.file.GC#setAuto(boolean)} for
2088 	 * configuration details.
2089 	 *
2090 	 * @param monitor
2091 	 *            to report progress
2092 	 * @since 4.6
2093 	 */
2094 	public void autoGC(ProgressMonitor monitor) {
2095 		// default does nothing
2096 	}
2097 }