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