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