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