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