View Javadoc
1   /*
2    * Copyright (C) 2008, 2009, Google Inc.
3    * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
4    * Copyright (C) 2010, Matthias Sohn <matthias.sohn@sap.com>
5    * Copyright (C) 2010, 2020, Christian Halstrick <christian.halstrick@sap.com> and others
6    *
7    * This program and the accompanying materials are made available under the
8    * terms of the Eclipse Distribution License v. 1.0 which is available at
9    * https://www.eclipse.org/org/documents/edl-v10.php.
10   *
11   * SPDX-License-Identifier: BSD-3-Clause
12   */
13  
14  package org.eclipse.jgit.dircache;
15  
16  import static java.nio.charset.StandardCharsets.UTF_8;
17  
18  import java.io.ByteArrayOutputStream;
19  import java.io.EOFException;
20  import java.io.IOException;
21  import java.io.InputStream;
22  import java.io.OutputStream;
23  import java.nio.ByteBuffer;
24  import java.security.MessageDigest;
25  import java.text.MessageFormat;
26  import java.time.Instant;
27  import java.util.Arrays;
28  
29  import org.eclipse.jgit.dircache.DirCache.DirCacheVersion;
30  import org.eclipse.jgit.errors.CorruptObjectException;
31  import org.eclipse.jgit.internal.JGitText;
32  import org.eclipse.jgit.lib.AnyObjectId;
33  import org.eclipse.jgit.lib.Constants;
34  import org.eclipse.jgit.lib.FileMode;
35  import org.eclipse.jgit.lib.ObjectId;
36  import org.eclipse.jgit.util.IO;
37  import org.eclipse.jgit.util.MutableInteger;
38  import org.eclipse.jgit.util.NB;
39  import org.eclipse.jgit.util.SystemReader;
40  
41  /**
42   * A single file (or stage of a file) in a
43   * {@link org.eclipse.jgit.dircache.DirCache}.
44   * <p>
45   * An entry represents exactly one stage of a file. If a file path is unmerged
46   * then multiple DirCacheEntry instances may appear for the same path name.
47   */
48  public class DirCacheEntry {
49  	private static final byte[] nullpad = new byte[8];
50  
51  	/** The standard (fully merged) stage for an entry. */
52  	public static final int STAGE_0 = 0;
53  
54  	/** The base tree revision for an entry. */
55  	public static final int STAGE_1 = 1;
56  
57  	/** The first tree revision (usually called "ours"). */
58  	public static final int STAGE_2 = 2;
59  
60  	/** The second tree revision (usually called "theirs"). */
61  	public static final int STAGE_3 = 3;
62  
63  	private static final int P_CTIME = 0;
64  
65  	// private static final int P_CTIME_NSEC = 4;
66  
67  	private static final int P_MTIME = 8;
68  
69  	// private static final int P_MTIME_NSEC = 12;
70  
71  	// private static final int P_DEV = 16;
72  
73  	// private static final int P_INO = 20;
74  
75  	private static final int P_MODE = 24;
76  
77  	// private static final int P_UID = 28;
78  
79  	// private static final int P_GID = 32;
80  
81  	private static final int P_SIZE = 36;
82  
83  	private static final int P_OBJECTID = 40;
84  
85  	private static final int P_FLAGS = 60;
86  	private static final int P_FLAGS2 = 62;
87  
88  	/** Mask applied to data in {@link #P_FLAGS} to get the name length. */
89  	private static final int NAME_MASK = 0xfff;
90  
91  	private static final int INTENT_TO_ADD = 0x20000000;
92  	private static final int SKIP_WORKTREE = 0x40000000;
93  	private static final int EXTENDED_FLAGS = (INTENT_TO_ADD | SKIP_WORKTREE);
94  
95  	private static final int INFO_LEN = 62;
96  	private static final int INFO_LEN_EXTENDED = 64;
97  
98  	private static final int EXTENDED = 0x40;
99  	private static final int ASSUME_VALID = 0x80;
100 
101 	/** In-core flag signaling that the entry should be considered as modified. */
102 	private static final int UPDATE_NEEDED = 0x1;
103 
104 	/** (Possibly shared) header information storage. */
105 	private final byte[] info;
106 
107 	/** First location within {@link #info} where our header starts. */
108 	private final int infoOffset;
109 
110 	/** Our encoded path name, from the root of the repository. */
111 	final byte[] path;
112 
113 	/** Flags which are never stored to disk. */
114 	private byte inCoreFlags;
115 
116 	DirCacheEntry(byte[] sharedInfo, MutableInteger infoAt, InputStream in,
117 			MessageDigest md, Instant smudge, DirCacheVersion version,
118 			DirCacheEntry previous)
119 			throws IOException {
120 		info = sharedInfo;
121 		infoOffset = infoAt.value;
122 
123 		IO.readFully(in, info, infoOffset, INFO_LEN);
124 
125 		int len;
126 		if (isExtended()) {
127 			len = INFO_LEN_EXTENDED;
128 			IO.readFully(in, info, infoOffset + INFO_LEN, INFO_LEN_EXTENDED - INFO_LEN);
129 
130 			if ((getExtendedFlags() & ~EXTENDED_FLAGS) != 0)
131 				throw new IOException(MessageFormat.format(JGitText.get()
132 						.DIRCUnrecognizedExtendedFlags, String.valueOf(getExtendedFlags())));
133 		} else
134 			len = INFO_LEN;
135 
136 		infoAt.value += len;
137 		md.update(info, infoOffset, len);
138 
139 		int toRemove = 0;
140 		if (version == DirCacheVersion.DIRC_VERSION_PATHCOMPRESS) {
141 			// Read variable int and update digest
142 			int b = in.read();
143 			md.update((byte) b);
144 			toRemove = b & 0x7F;
145 			while ((b & 0x80) != 0) {
146 				toRemove++;
147 				b = in.read();
148 				md.update((byte) b);
149 				toRemove = (toRemove << 7) | (b & 0x7F);
150 			}
151 			if (toRemove < 0
152 					|| (previous != null && toRemove > previous.path.length)) {
153 				if (previous == null) {
154 					throw new IOException(MessageFormat.format(
155 							JGitText.get().DIRCCorruptLengthFirst,
156 							Integer.valueOf(toRemove)));
157 				}
158 				throw new IOException(MessageFormat.format(
159 						JGitText.get().DIRCCorruptLength,
160 						Integer.valueOf(toRemove), previous.getPathString()));
161 			}
162 		}
163 		int pathLen = NB.decodeUInt16(info, infoOffset + P_FLAGS) & NAME_MASK;
164 		int skipped = 0;
165 		if (pathLen < NAME_MASK) {
166 			path = new byte[pathLen];
167 			if (version == DirCacheVersion.DIRC_VERSION_PATHCOMPRESS
168 					&& previous != null) {
169 				System.arraycopy(previous.path, 0, path, 0,
170 						previous.path.length - toRemove);
171 				IO.readFully(in, path, previous.path.length - toRemove,
172 						pathLen - (previous.path.length - toRemove));
173 				md.update(path, previous.path.length - toRemove,
174 						pathLen - (previous.path.length - toRemove));
175 				pathLen = pathLen - (previous.path.length - toRemove);
176 			} else {
177 				IO.readFully(in, path, 0, pathLen);
178 				md.update(path, 0, pathLen);
179 			}
180 		} else if (version != DirCacheVersion.DIRC_VERSION_PATHCOMPRESS
181 				|| previous == null || toRemove == previous.path.length) {
182 			ByteArrayOutputStream tmp = new ByteArrayOutputStream();
183 			byte[] buf = new byte[NAME_MASK];
184 			IO.readFully(in, buf, 0, NAME_MASK);
185 			tmp.write(buf);
186 			readNulTerminatedString(in, tmp);
187 			path = tmp.toByteArray();
188 			pathLen = path.length;
189 			md.update(path, 0, pathLen);
190 			skipped = 1; // we already skipped 1 '\0' in readNulTerminatedString
191 			md.update((byte) 0);
192 		} else {
193 			ByteArrayOutputStream tmp = new ByteArrayOutputStream();
194 			tmp.write(previous.path, 0, previous.path.length - toRemove);
195 			pathLen = readNulTerminatedString(in, tmp);
196 			path = tmp.toByteArray();
197 			md.update(path, previous.path.length - toRemove, pathLen);
198 			skipped = 1; // we already skipped 1 '\0' in readNulTerminatedString
199 			md.update((byte) 0);
200 		}
201 
202 		try {
203 			checkPath(path);
204 		} catch (InvalidPathException e) {
205 			CorruptObjectException p =
206 				new CorruptObjectException(e.getMessage());
207 			if (e.getCause() != null)
208 				p.initCause(e.getCause());
209 			throw p;
210 		}
211 
212 		if (version == DirCacheVersion.DIRC_VERSION_PATHCOMPRESS) {
213 			if (skipped == 0) {
214 				int b = in.read();
215 				if (b < 0) {
216 					throw new EOFException(JGitText.get().shortReadOfBlock);
217 				}
218 				md.update((byte) b);
219 			}
220 		} else {
221 			// Index records are padded out to the next 8 byte alignment
222 			// for historical reasons related to how C Git read the files.
223 			//
224 			final int actLen = len + pathLen;
225 			final int expLen = (actLen + 8) & ~7;
226 			final int padLen = expLen - actLen - skipped;
227 			if (padLen > 0) {
228 				IO.skipFully(in, padLen);
229 				md.update(nullpad, 0, padLen);
230 			}
231 		}
232 		if (mightBeRacilyClean(smudge)) {
233 			smudgeRacilyClean();
234 		}
235 	}
236 
237 	/**
238 	 * Create an empty entry at stage 0.
239 	 *
240 	 * @param newPath
241 	 *            name of the cache entry.
242 	 * @throws java.lang.IllegalArgumentException
243 	 *             If the path starts or ends with "/", or contains "//" either
244 	 *             "\0". These sequences are not permitted in a git tree object
245 	 *             or DirCache file.
246 	 */
247 	public DirCacheEntry(String newPath) {
248 		this(Constants.encode(newPath), STAGE_0);
249 	}
250 
251 	/**
252 	 * Create an empty entry at the specified stage.
253 	 *
254 	 * @param newPath
255 	 *            name of the cache entry.
256 	 * @param stage
257 	 *            the stage index of the new entry.
258 	 * @throws java.lang.IllegalArgumentException
259 	 *             If the path starts or ends with "/", or contains "//" either
260 	 *             "\0". These sequences are not permitted in a git tree object
261 	 *             or DirCache file.  Or if {@code stage} is outside of the
262 	 *             range 0..3, inclusive.
263 	 */
264 	public DirCacheEntry(String newPath, int stage) {
265 		this(Constants.encode(newPath), stage);
266 	}
267 
268 	/**
269 	 * Create an empty entry at stage 0.
270 	 *
271 	 * @param newPath
272 	 *            name of the cache entry, in the standard encoding.
273 	 * @throws java.lang.IllegalArgumentException
274 	 *             If the path starts or ends with "/", or contains "//" either
275 	 *             "\0". These sequences are not permitted in a git tree object
276 	 *             or DirCache file.
277 	 */
278 	public DirCacheEntry(byte[] newPath) {
279 		this(newPath, STAGE_0);
280 	}
281 
282 	/**
283 	 * Create an empty entry at the specified stage.
284 	 *
285 	 * @param path
286 	 *            name of the cache entry, in the standard encoding.
287 	 * @param stage
288 	 *            the stage index of the new entry.
289 	 * @throws java.lang.IllegalArgumentException
290 	 *             If the path starts or ends with "/", or contains "//" either
291 	 *             "\0". These sequences are not permitted in a git tree object
292 	 *             or DirCache file.  Or if {@code stage} is outside of the
293 	 *             range 0..3, inclusive.
294 	 */
295 	@SuppressWarnings("boxing")
296 	public DirCacheEntry(byte[] path, int stage) {
297 		checkPath(path);
298 		if (stage < 0 || 3 < stage)
299 			throw new IllegalArgumentException(MessageFormat.format(
300 					JGitText.get().invalidStageForPath,
301 					stage, toString(path)));
302 
303 		info = new byte[INFO_LEN];
304 		infoOffset = 0;
305 		this.path = path;
306 
307 		int flags = ((stage & 0x3) << 12);
308 		if (path.length < NAME_MASK)
309 			flags |= path.length;
310 		else
311 			flags |= NAME_MASK;
312 		NB.encodeInt16(info, infoOffset + P_FLAGS, flags);
313 	}
314 
315 	/**
316 	 * Duplicate DirCacheEntry with same path and copied info.
317 	 * <p>
318 	 * The same path buffer is reused (avoiding copying), however a new info
319 	 * buffer is created and its contents are copied.
320 	 *
321 	 * @param src
322 	 *            entry to clone.
323 	 * @since 4.2
324 	 */
325 	public DirCacheEntryf="../../../../org/eclipse/jgit/dircache/DirCacheEntry.html#DirCacheEntry">DirCacheEntry(DirCacheEntry src) {
326 		path = src.path;
327 		info = new byte[INFO_LEN];
328 		infoOffset = 0;
329 		System.arraycopy(src.info, src.infoOffset, info, 0, INFO_LEN);
330 	}
331 
332 	private int readNulTerminatedString(InputStream in, OutputStream out)
333 			throws IOException {
334 		int n = 0;
335 		for (;;) {
336 			int c = in.read();
337 			if (c < 0) {
338 				throw new EOFException(JGitText.get().shortReadOfBlock);
339 			}
340 			if (c == 0) {
341 				break;
342 			}
343 			out.write(c);
344 			n++;
345 		}
346 		return n;
347 	}
348 
349 	void write(OutputStream os, DirCacheVersion version, DirCacheEntry previous)
350 			throws IOException {
351 		final int len = isExtended() ? INFO_LEN_EXTENDED : INFO_LEN;
352 		if (version != DirCacheVersion.DIRC_VERSION_PATHCOMPRESS) {
353 			os.write(info, infoOffset, len);
354 			os.write(path, 0, path.length);
355 			// Index records are padded out to the next 8 byte alignment
356 			// for historical reasons related to how C Git read the files.
357 			//
358 			int entryLen = len + path.length;
359 			int expLen = (entryLen + 8) & ~7;
360 			if (entryLen != expLen)
361 				os.write(nullpad, 0, expLen - entryLen);
362 		} else {
363 			int pathCommon = 0;
364 			int toRemove;
365 			if (previous != null) {
366 				// Figure out common prefix
367 				int pathLen = Math.min(path.length, previous.path.length);
368 				while (pathCommon < pathLen
369 						&& path[pathCommon] == previous.path[pathCommon]) {
370 					pathCommon++;
371 				}
372 				toRemove = previous.path.length - pathCommon;
373 			} else {
374 				toRemove = 0;
375 			}
376 			byte[] tmp = new byte[16];
377 			int n = tmp.length;
378 			tmp[--n] = (byte) (toRemove & 0x7F);
379 			while ((toRemove >>>= 7) != 0) {
380 				tmp[--n] = (byte) (0x80 | (--toRemove & 0x7F));
381 			}
382 			os.write(info, infoOffset, len);
383 			os.write(tmp, n, tmp.length - n);
384 			os.write(path, pathCommon, path.length - pathCommon);
385 			os.write(0);
386 		}
387 	}
388 
389 	/**
390 	 * Is it possible for this entry to be accidentally assumed clean?
391 	 * <p>
392 	 * The "racy git" problem happens when a work file can be updated faster
393 	 * than the filesystem records file modification timestamps. It is possible
394 	 * for an application to edit a work file, update the index, then edit it
395 	 * again before the filesystem will give the work file a new modification
396 	 * timestamp. This method tests to see if file was written out at the same
397 	 * time as the index.
398 	 *
399 	 * @param smudge_s
400 	 *            seconds component of the index's last modified time.
401 	 * @param smudge_ns
402 	 *            nanoseconds component of the index's last modified time.
403 	 * @return true if extra careful checks should be used.
404 	 * @deprecated use {@link #mightBeRacilyClean(Instant)} instead
405 	 */
406 	@Deprecated
407 	public final boolean mightBeRacilyClean(int smudge_s, int smudge_ns) {
408 		return mightBeRacilyClean(Instant.ofEpochSecond(smudge_s, smudge_ns));
409 	}
410 
411 	/**
412 	 * Is it possible for this entry to be accidentally assumed clean?
413 	 * <p>
414 	 * The "racy git" problem happens when a work file can be updated faster
415 	 * than the filesystem records file modification timestamps. It is possible
416 	 * for an application to edit a work file, update the index, then edit it
417 	 * again before the filesystem will give the work file a new modification
418 	 * timestamp. This method tests to see if file was written out at the same
419 	 * time as the index.
420 	 *
421 	 * @param smudge
422 	 *            index's last modified time.
423 	 * @return true if extra careful checks should be used.
424 	 * @since 5.1.9
425 	 */
426 	public final boolean mightBeRacilyClean(Instant smudge) {
427 		// If the index has a modification time then it came from disk
428 		// and was not generated from scratch in memory. In such cases
429 		// the entry is 'racily clean' if the entry's cached modification
430 		// time is equal to or later than the index modification time. In
431 		// such cases the work file is too close to the index to tell if
432 		// it is clean or not based on the modification time alone.
433 		//
434 		final int base = infoOffset + P_MTIME;
435 		final int mtime = NB.decodeInt32(info, base);
436 		if ((int) smudge.getEpochSecond() == mtime) {
437 			return smudge.getNano() <= NB.decodeInt32(info, base + 4);
438 		}
439 		return false;
440 	}
441 
442 	/**
443 	 * Force this entry to no longer match its working tree file.
444 	 * <p>
445 	 * This avoids the "racy git" problem by making this index entry no longer
446 	 * match the file in the working directory. Later git will be forced to
447 	 * compare the file content to ensure the file matches the working tree.
448 	 */
449 	public final void smudgeRacilyClean() {
450 		// To mark an entry racily clean we set its length to 0 (like native git
451 		// does). Entries which are not racily clean and have zero length can be
452 		// distinguished from racily clean entries by checking P_OBJECTID
453 		// against the SHA1 of empty content. When length is 0 and P_OBJECTID is
454 		// different from SHA1 of empty content we know the entry is marked
455 		// racily clean
456 		final int base = infoOffset + P_SIZE;
457 		Arrays.fill(info, base, base + 4, (byte) 0);
458 	}
459 
460 	/**
461 	 * Check whether this entry has been smudged or not
462 	 * <p>
463 	 * If a blob has length 0 we know its id, see
464 	 * {@link org.eclipse.jgit.lib.Constants#EMPTY_BLOB_ID}. If an entry has
465 	 * length 0 and an ID different from the one for empty blob we know this
466 	 * entry was smudged.
467 	 *
468 	 * @return <code>true</code> if the entry is smudged, <code>false</code>
469 	 *         otherwise
470 	 */
471 	public final boolean isSmudged() {
472 		final int base = infoOffset + P_OBJECTID;
473 		return (getLength() == 0) && (Constants.EMPTY_BLOB_ID.compareTo(info, base) != 0);
474 	}
475 
476 	final byte[] idBuffer() {
477 		return info;
478 	}
479 
480 	final int idOffset() {
481 		return infoOffset + P_OBJECTID;
482 	}
483 
484 	/**
485 	 * Is this entry always thought to be unmodified?
486 	 * <p>
487 	 * Most entries in the index do not have this flag set. Users may however
488 	 * set them on if the file system stat() costs are too high on this working
489 	 * directory, such as on NFS or SMB volumes.
490 	 *
491 	 * @return true if we must assume the entry is unmodified.
492 	 */
493 	public boolean isAssumeValid() {
494 		return (info[infoOffset + P_FLAGS] & ASSUME_VALID) != 0;
495 	}
496 
497 	/**
498 	 * Set the assume valid flag for this entry,
499 	 *
500 	 * @param assume
501 	 *            true to ignore apparent modifications; false to look at last
502 	 *            modified to detect file modifications.
503 	 */
504 	public void setAssumeValid(boolean assume) {
505 		if (assume)
506 			info[infoOffset + P_FLAGS] |= (byte) ASSUME_VALID;
507 		else
508 			info[infoOffset + P_FLAGS] &= (byte) ~ASSUME_VALID;
509 	}
510 
511 	/**
512 	 * Whether this entry should be checked for changes
513 	 *
514 	 * @return {@code true} if this entry should be checked for changes
515 	 */
516 	public boolean isUpdateNeeded() {
517 		return (inCoreFlags & UPDATE_NEEDED) != 0;
518 	}
519 
520 	/**
521 	 * Set whether this entry must be checked for changes
522 	 *
523 	 * @param updateNeeded
524 	 *            whether this entry must be checked for changes
525 	 */
526 	public void setUpdateNeeded(boolean updateNeeded) {
527 		if (updateNeeded)
528 			inCoreFlags |= (byte) UPDATE_NEEDED;
529 		else
530 			inCoreFlags &= (byte) ~UPDATE_NEEDED;
531 	}
532 
533 	/**
534 	 * Get the stage of this entry.
535 	 * <p>
536 	 * Entries have one of 4 possible stages: 0-3.
537 	 *
538 	 * @return the stage of this entry.
539 	 */
540 	public int getStage() {
541 		return (info[infoOffset + P_FLAGS] >>> 4) & 0x3;
542 	}
543 
544 	/**
545 	 * Sets the stage of an entry.
546 	 *
547 	 * @param stage
548 	 *            to set, in the range [0..3]
549 	 * @throws IllegalArgumentException
550 	 *             if the stage is outside the range [0..3]
551 	 * @since 5.10
552 	 */
553 	public void setStage(int stage) {
554 		if ((stage & ~0x3) != 0) {
555 			throw new IllegalArgumentException(
556 					"Invalid stage, must be in range [0..3]"); //$NON-NLS-1$
557 		}
558 		byte flags = info[infoOffset + P_FLAGS];
559 		info[infoOffset + P_FLAGS] = (byte) ((flags & 0xCF) | (stage << 4));
560 	}
561 
562 	/**
563 	 * Returns whether this entry should be skipped from the working tree.
564 	 *
565 	 * @return true if this entry should be skipepd.
566 	 */
567 	public boolean isSkipWorkTree() {
568 		return (getExtendedFlags() & SKIP_WORKTREE) != 0;
569 	}
570 
571 	/**
572 	 * Returns whether this entry is intent to be added to the Index.
573 	 *
574 	 * @return true if this entry is intent to add.
575 	 */
576 	public boolean isIntentToAdd() {
577 		return (getExtendedFlags() & INTENT_TO_ADD) != 0;
578 	}
579 
580 	/**
581 	 * Returns whether this entry is in the fully-merged stage (0).
582 	 *
583 	 * @return true if this entry is merged
584 	 * @since 2.2
585 	 */
586 	public boolean isMerged() {
587 		return getStage() == STAGE_0;
588 	}
589 
590 	/**
591 	 * Obtain the raw {@link org.eclipse.jgit.lib.FileMode} bits for this entry.
592 	 *
593 	 * @return mode bits for the entry.
594 	 * @see FileMode#fromBits(int)
595 	 */
596 	public int getRawMode() {
597 		return NB.decodeInt32(info, infoOffset + P_MODE);
598 	}
599 
600 	/**
601 	 * Obtain the {@link org.eclipse.jgit.lib.FileMode} for this entry.
602 	 *
603 	 * @return the file mode singleton for this entry.
604 	 */
605 	public FileMode getFileMode() {
606 		return FileMode.fromBits(getRawMode());
607 	}
608 
609 	/**
610 	 * Set the file mode for this entry.
611 	 *
612 	 * @param mode
613 	 *            the new mode constant.
614 	 * @throws java.lang.IllegalArgumentException
615 	 *             If {@code mode} is
616 	 *             {@link org.eclipse.jgit.lib.FileMode#MISSING},
617 	 *             {@link org.eclipse.jgit.lib.FileMode#TREE}, or any other type
618 	 *             code not permitted in a tree object.
619 	 */
620 	public void setFileMode(FileMode mode) {
621 		switch (mode.getBits() & FileMode.TYPE_MASK) {
622 		case FileMode.TYPE_MISSING:
623 		case FileMode.TYPE_TREE:
624 			throw new IllegalArgumentException(MessageFormat.format(
625 					JGitText.get().invalidModeForPath, mode, getPathString()));
626 		}
627 		NB.encodeInt32(info, infoOffset + P_MODE, mode.getBits());
628 	}
629 
630 	void setFileMode(int mode) {
631 		NB.encodeInt32(info, infoOffset + P_MODE, mode);
632 	}
633 
634 	/**
635 	 * Get the cached creation time of this file, in milliseconds.
636 	 *
637 	 * @return cached creation time of this file, in milliseconds since the
638 	 *         Java epoch (midnight Jan 1, 1970 UTC).
639 	 */
640 	public long getCreationTime() {
641 		return decodeTS(P_CTIME);
642 	}
643 
644 	/**
645 	 * Set the cached creation time of this file, using milliseconds.
646 	 *
647 	 * @param when
648 	 *            new cached creation time of the file, in milliseconds.
649 	 */
650 	public void setCreationTime(long when) {
651 		encodeTS(P_CTIME, when);
652 	}
653 
654 	/**
655 	 * Get the cached last modification date of this file, in milliseconds.
656 	 * <p>
657 	 * One of the indicators that the file has been modified by an application
658 	 * changing the working tree is if the last modification time for the file
659 	 * differs from the time stored in this entry.
660 	 *
661 	 * @return last modification time of this file, in milliseconds since the
662 	 *         Java epoch (midnight Jan 1, 1970 UTC).
663 	 * @deprecated use {@link #getLastModifiedInstant()} instead
664 	 */
665 	@Deprecated
666 	public long getLastModified() {
667 		return decodeTS(P_MTIME);
668 	}
669 
670 	/**
671 	 * Get the cached last modification date of this file.
672 	 * <p>
673 	 * One of the indicators that the file has been modified by an application
674 	 * changing the working tree is if the last modification time for the file
675 	 * differs from the time stored in this entry.
676 	 *
677 	 * @return last modification time of this file.
678 	 * @since 5.1.9
679 	 */
680 	public Instant getLastModifiedInstant() {
681 		return decodeTSInstant(P_MTIME);
682 	}
683 
684 	/**
685 	 * Set the cached last modification date of this file, using milliseconds.
686 	 *
687 	 * @param when
688 	 *            new cached modification date of the file, in milliseconds.
689 	 * @deprecated use {@link #setLastModified(Instant)} instead
690 	 */
691 	@Deprecated
692 	public void setLastModified(long when) {
693 		encodeTS(P_MTIME, when);
694 	}
695 
696 	/**
697 	 * Set the cached last modification date of this file.
698 	 *
699 	 * @param when
700 	 *            new cached modification date of the file.
701 	 * @since 5.1.9
702 	 */
703 	public void setLastModified(Instant when) {
704 		encodeTS(P_MTIME, when);
705 	}
706 
707 	/**
708 	 * Get the cached size (mod 4 GB) (in bytes) of this file.
709 	 * <p>
710 	 * One of the indicators that the file has been modified by an application
711 	 * changing the working tree is if the size of the file (in bytes) differs
712 	 * from the size stored in this entry.
713 	 * <p>
714 	 * Note that this is the length of the file in the working directory, which
715 	 * may differ from the size of the decompressed blob if work tree filters
716 	 * are being used, such as LF&lt;-&gt;CRLF conversion.
717 	 * <p>
718 	 * Note also that for very large files, this is the size of the on-disk file
719 	 * truncated to 32 bits, i.e. modulo 4294967296. If that value is larger
720 	 * than 2GB, it will appear negative.
721 	 *
722 	 * @return cached size of the working directory file, in bytes.
723 	 */
724 	public int getLength() {
725 		return NB.decodeInt32(info, infoOffset + P_SIZE);
726 	}
727 
728 	/**
729 	 * Set the cached size (in bytes) of this file.
730 	 *
731 	 * @param sz
732 	 *            new cached size of the file, as bytes. If the file is larger
733 	 *            than 2G, cast it to (int) before calling this method.
734 	 */
735 	public void setLength(int sz) {
736 		NB.encodeInt32(info, infoOffset + P_SIZE, sz);
737 	}
738 
739 	/**
740 	 * Set the cached size (in bytes) of this file.
741 	 *
742 	 * @param sz
743 	 *            new cached size of the file, as bytes.
744 	 */
745 	public void setLength(long sz) {
746 		setLength((int) sz);
747 	}
748 
749 	/**
750 	 * Obtain the ObjectId for the entry.
751 	 * <p>
752 	 * Using this method to compare ObjectId values between entries is
753 	 * inefficient as it causes memory allocation.
754 	 *
755 	 * @return object identifier for the entry.
756 	 */
757 	public ObjectId getObjectId() {
758 		return ObjectId.fromRaw(idBuffer(), idOffset());
759 	}
760 
761 	/**
762 	 * Set the ObjectId for the entry.
763 	 *
764 	 * @param id
765 	 *            new object identifier for the entry. May be
766 	 *            {@link org.eclipse.jgit.lib.ObjectId#zeroId()} to remove the
767 	 *            current identifier.
768 	 */
769 	public void setObjectId(AnyObjectId id) {
770 		id.copyRawTo(idBuffer(), idOffset());
771 	}
772 
773 	/**
774 	 * Set the ObjectId for the entry from the raw binary representation.
775 	 *
776 	 * @param bs
777 	 *            the raw byte buffer to read from. At least 20 bytes after p
778 	 *            must be available within this byte array.
779 	 * @param p
780 	 *            position to read the first byte of data from.
781 	 */
782 	public void setObjectIdFromRaw(byte[] bs, int p) {
783 		final int n = Constants.OBJECT_ID_LENGTH;
784 		System.arraycopy(bs, p, idBuffer(), idOffset(), n);
785 	}
786 
787 	/**
788 	 * Get the entry's complete path.
789 	 * <p>
790 	 * This method is not very efficient and is primarily meant for debugging
791 	 * and final output generation. Applications should try to avoid calling it,
792 	 * and if invoked do so only once per interesting entry, where the name is
793 	 * absolutely required for correct function.
794 	 *
795 	 * @return complete path of the entry, from the root of the repository. If
796 	 *         the entry is in a subtree there will be at least one '/' in the
797 	 *         returned string.
798 	 */
799 	public String getPathString() {
800 		return toString(path);
801 	}
802 
803 	/**
804 	 * Get a copy of the entry's raw path bytes.
805 	 *
806 	 * @return raw path bytes.
807 	 * @since 3.4
808 	 */
809 	public byte[] getRawPath() {
810 		return path.clone();
811 	}
812 
813 	/**
814 	 * {@inheritDoc}
815 	 * <p>
816 	 * Use for debugging only !
817 	 */
818 	@SuppressWarnings("nls")
819 	@Override
820 	public String toString() {
821 		return getFileMode() + " " + getLength() + " "
822 				+ getLastModifiedInstant()
823 				+ " " + getObjectId() + " " + getStage() + " "
824 				+ getPathString() + "\n";
825 	}
826 
827 	/**
828 	 * Copy the ObjectId and other meta fields from an existing entry.
829 	 * <p>
830 	 * This method copies everything except the path from one entry to another,
831 	 * supporting renaming.
832 	 *
833 	 * @param src
834 	 *            the entry to copy ObjectId and meta fields from.
835 	 */
836 	public void copyMetaData(DirCacheEntry src) {
837 		copyMetaData(src, false);
838 	}
839 
840 	/**
841 	 * Copy the ObjectId and other meta fields from an existing entry.
842 	 * <p>
843 	 * This method copies everything except the path and possibly stage from one
844 	 * entry to another, supporting renaming.
845 	 *
846 	 * @param src
847 	 *            the entry to copy ObjectId and meta fields from.
848 	 * @param keepStage
849 	 *            if true, the stage attribute will not be copied
850 	 */
851 	void copyMetaData(DirCacheEntry src, boolean keepStage) {
852 		int origflags = NB.decodeUInt16(info, infoOffset + P_FLAGS);
853 		int newflags = NB.decodeUInt16(src.info, src.infoOffset + P_FLAGS);
854 		System.arraycopy(src.info, src.infoOffset, info, infoOffset, INFO_LEN);
855 		final int pLen = origflags & NAME_MASK;
856 		final int SHIFTED_STAGE_MASK = 0x3 << 12;
857 		final int pStageShifted;
858 		if (keepStage)
859 			pStageShifted = origflags & SHIFTED_STAGE_MASK;
860 		else
861 			pStageShifted = newflags & SHIFTED_STAGE_MASK;
862 		NB.encodeInt16(info, infoOffset + P_FLAGS, pStageShifted | pLen
863 				| (newflags & ~NAME_MASK & ~SHIFTED_STAGE_MASK));
864 	}
865 
866 	/**
867 	 * @return true if the entry contains extended flags.
868 	 */
869 	boolean isExtended() {
870 		return (info[infoOffset + P_FLAGS] & EXTENDED) != 0;
871 	}
872 
873 	private long decodeTS(int pIdx) {
874 		final int base = infoOffset + pIdx;
875 		final int sec = NB.decodeInt32(info, base);
876 		final int ms = NB.decodeInt32(info, base + 4) / 1000000;
877 		return 1000L * sec + ms;
878 	}
879 
880 	private Instant decodeTSInstant(int pIdx) {
881 		final int base = infoOffset + pIdx;
882 		final int sec = NB.decodeInt32(info, base);
883 		final int nano = NB.decodeInt32(info, base + 4);
884 		return Instant.ofEpochSecond(sec, nano);
885 	}
886 
887 	private void encodeTS(int pIdx, long when) {
888 		final int base = infoOffset + pIdx;
889 		NB.encodeInt32(info, base, (int) (when / 1000));
890 		NB.encodeInt32(info, base + 4, ((int) (when % 1000)) * 1000000);
891 	}
892 
893 	private void encodeTS(int pIdx, Instant when) {
894 		final int base = infoOffset + pIdx;
895 		NB.encodeInt32(info, base, (int) when.getEpochSecond());
896 		NB.encodeInt32(info, base + 4, when.getNano());
897 	}
898 
899 	private int getExtendedFlags() {
900 		if (isExtended()) {
901 			return NB.decodeUInt16(info, infoOffset + P_FLAGS2) << 16;
902 		}
903 		return 0;
904 	}
905 
906 	private static void checkPath(byte[] path) {
907 		try {
908 			SystemReader.getInstance().checkPath(path);
909 		} catch (CorruptObjectException e) {
910 			InvalidPathException p = new InvalidPathException(toString(path));
911 			p.initCause(e);
912 			throw p;
913 		}
914 	}
915 
916 	static String toString(byte[] path) {
917 		return UTF_8.decode(ByteBuffer.wrap(path)).toString();
918 	}
919 
920 	static int getMaximumInfoLength(boolean extended) {
921 		return extended ? INFO_LEN_EXTENDED : INFO_LEN;
922 	}
923 }