1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46 package org.eclipse.jgit.dircache;
47
48 import static java.nio.charset.StandardCharsets.ISO_8859_1;
49
50 import java.io.BufferedInputStream;
51 import java.io.BufferedOutputStream;
52 import java.io.EOFException;
53 import java.io.File;
54 import java.io.FileNotFoundException;
55 import java.io.IOException;
56 import java.io.InputStream;
57 import java.io.OutputStream;
58 import java.security.DigestOutputStream;
59 import java.security.MessageDigest;
60 import java.text.MessageFormat;
61 import java.util.ArrayList;
62 import java.util.Arrays;
63 import java.util.Comparator;
64 import java.util.List;
65
66 import org.eclipse.jgit.errors.CorruptObjectException;
67 import org.eclipse.jgit.errors.IndexReadException;
68 import org.eclipse.jgit.errors.LockFailedException;
69 import org.eclipse.jgit.errors.UnmergedPathException;
70 import org.eclipse.jgit.events.IndexChangedEvent;
71 import org.eclipse.jgit.events.IndexChangedListener;
72 import org.eclipse.jgit.internal.JGitText;
73 import org.eclipse.jgit.internal.storage.file.FileSnapshot;
74 import org.eclipse.jgit.internal.storage.file.LockFile;
75 import org.eclipse.jgit.lib.AnyObjectId;
76 import org.eclipse.jgit.lib.Constants;
77 import org.eclipse.jgit.lib.ObjectId;
78 import org.eclipse.jgit.lib.ObjectInserter;
79 import org.eclipse.jgit.lib.ObjectReader;
80 import org.eclipse.jgit.lib.Repository;
81 import org.eclipse.jgit.treewalk.FileTreeIterator;
82 import org.eclipse.jgit.treewalk.TreeWalk;
83 import org.eclipse.jgit.treewalk.TreeWalk.OperationType;
84 import org.eclipse.jgit.treewalk.filter.PathFilterGroup;
85 import org.eclipse.jgit.util.FS;
86 import org.eclipse.jgit.util.IO;
87 import org.eclipse.jgit.util.MutableInteger;
88 import org.eclipse.jgit.util.NB;
89 import org.eclipse.jgit.util.TemporaryBuffer;
90 import org.eclipse.jgit.util.io.SilentFileInputStream;
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105 public class DirCache {
106 private static final byte[] SIG_DIRC = { 'D', 'I', 'R', 'C' };
107
108 private static final int EXT_TREE = 0x54524545 ;
109
110 private static final DirCacheEntry[] NO_ENTRIES = {};
111
112 private static final byte[] NO_CHECKSUM = {};
113
114 static final Comparator<DirCacheEntry> ENT_CMP = new Comparator<DirCacheEntry>() {
115 @Override
116 public int compare(DirCacheEntry o1, DirCacheEntry o2) {
117 final int cr = cmp(o1, o2);
118 if (cr != 0)
119 return cr;
120 return o1.getStage() - o2.getStage();
121 }
122 };
123
124 static int cmp(DirCacheEntry a, DirCacheEntry b) {
125 return cmp(a.path, a.path.length, b);
126 }
127
128 static int cmp(byte[] aPath, int aLen, DirCacheEntry b) {
129 return cmp(aPath, aLen, b.path, b.path.length);
130 }
131
132 static int cmp(final byte[] aPath, final int aLen, final byte[] bPath,
133 final int bLen) {
134 for (int cPos = 0; cPos < aLen && cPos < bLen; cPos++) {
135 final int cmp = (aPath[cPos] & 0xff) - (bPath[cPos] & 0xff);
136 if (cmp != 0)
137 return cmp;
138 }
139 return aLen - bLen;
140 }
141
142
143
144
145
146
147
148
149 public static DirCache newInCore() {
150 return new DirCache(null, null);
151 }
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166 public static DirCache read(ObjectReader reader, AnyObjectId treeId)
167 throws IOException {
168 DirCache d = newInCore();
169 DirCacheBuilder b = d.builder();
170 b.addTree(null, DirCacheEntry.STAGE_0, reader, treeId);
171 b.finish();
172 return d;
173 }
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192 public static DirCache read(Repository repository)
193 throws CorruptObjectException, IOException {
194 final DirCache c = read(repository.getIndexFile(), repository.getFS());
195 c.repository = repository;
196 return c;
197 }
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219 public static DirCache read(File indexLocation, FS fs)
220 throws CorruptObjectException, IOException {
221 final DirCache c = new DirCache(indexLocation, fs);
222 c.read();
223 return c;
224 }
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248 public static DirCache lock(File indexLocation, FS fs)
249 throws CorruptObjectException, IOException {
250 final DirCache c = new DirCache(indexLocation, fs);
251 if (!c.lock())
252 throw new LockFailedException(indexLocation);
253
254 try {
255 c.read();
256 } catch (IOException e) {
257 c.unlock();
258 throw e;
259 } catch (RuntimeException e) {
260 c.unlock();
261 throw e;
262 } catch (Error e) {
263 c.unlock();
264 throw e;
265 }
266
267 return c;
268 }
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292 public static DirCache lock(final Repository repository,
293 final IndexChangedListener indexChangedListener)
294 throws CorruptObjectException, IOException {
295 DirCache c = lock(repository.getIndexFile(), repository.getFS(),
296 indexChangedListener);
297 c.repository = repository;
298 return c;
299 }
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325 public static DirCache lock(final File indexLocation, final FS fs,
326 IndexChangedListener indexChangedListener)
327 throws CorruptObjectException,
328 IOException {
329 DirCache c = lock(indexLocation, fs);
330 c.registerIndexChangedListener(indexChangedListener);
331 return c;
332 }
333
334
335 private final File liveFile;
336
337
338 private DirCacheEntry[] sortedEntries;
339
340
341 private int entryCnt;
342
343
344 private DirCacheTree tree;
345
346
347 private LockFile myLock;
348
349
350 private FileSnapshot snapshot;
351
352
353 private byte[] readIndexChecksum;
354
355
356 private byte[] writeIndexChecksum;
357
358
359 private IndexChangedListener indexChangedListener;
360
361
362 private Repository repository;
363
364
365
366
367
368
369
370
371
372
373
374
375
376 public DirCache(File indexLocation, FS fs) {
377 liveFile = indexLocation;
378 clear();
379 }
380
381
382
383
384
385
386
387
388
389
390 public DirCacheBuilder builder() {
391 return new DirCacheBuilder(this, entryCnt + 16);
392 }
393
394
395
396
397
398
399
400
401
402
403 public DirCacheEditor editor() {
404 return new DirCacheEditor(this, entryCnt + 16);
405 }
406
407 void replace(DirCacheEntry[] e, int cnt) {
408 sortedEntries = e;
409 entryCnt = cnt;
410 tree = null;
411 }
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427 public void read() throws IOException, CorruptObjectException {
428 if (liveFile == null)
429 throw new IOException(JGitText.get().dirCacheDoesNotHaveABackingFile);
430 if (!liveFile.exists())
431 clear();
432 else if (snapshot == null || snapshot.isModified(liveFile)) {
433 try (SilentFileInputStream inStream = new SilentFileInputStream(
434 liveFile)) {
435 clear();
436 readFrom(inStream);
437 } catch (FileNotFoundException fnfe) {
438 if (liveFile.exists()) {
439
440 throw new IndexReadException(
441 MessageFormat.format(JGitText.get().cannotReadIndex,
442 liveFile.getAbsolutePath(), fnfe));
443 }
444
445
446
447 clear();
448 }
449 snapshot = FileSnapshot.save(liveFile);
450 }
451 }
452
453
454
455
456
457
458
459 public boolean isOutdated() throws IOException {
460 if (liveFile == null || !liveFile.exists())
461 return false;
462 return snapshot == null || snapshot.isModified(liveFile);
463 }
464
465
466
467
468 public void clear() {
469 snapshot = null;
470 sortedEntries = NO_ENTRIES;
471 entryCnt = 0;
472 tree = null;
473 readIndexChecksum = NO_CHECKSUM;
474 }
475
476 private void readFrom(InputStream inStream) throws IOException,
477 CorruptObjectException {
478 final BufferedInputStream in = new BufferedInputStream(inStream);
479 final MessageDigest md = Constants.newMessageDigest();
480
481
482
483 final byte[] hdr = new byte[20];
484 IO.readFully(in, hdr, 0, 12);
485 md.update(hdr, 0, 12);
486 if (!is_DIRC(hdr))
487 throw new CorruptObjectException(JGitText.get().notADIRCFile);
488 final int ver = NB.decodeInt32(hdr, 4);
489 boolean extended = false;
490 if (ver == 3)
491 extended = true;
492 else if (ver != 2)
493 throw new CorruptObjectException(MessageFormat.format(
494 JGitText.get().unknownDIRCVersion, Integer.valueOf(ver)));
495 entryCnt = NB.decodeInt32(hdr, 8);
496 if (entryCnt < 0)
497 throw new CorruptObjectException(JGitText.get().DIRCHasTooManyEntries);
498
499 snapshot = FileSnapshot.save(liveFile);
500 int smudge_s = (int) (snapshot.lastModified() / 1000);
501 int smudge_ns = ((int) (snapshot.lastModified() % 1000)) * 1000000;
502
503
504
505 final int infoLength = DirCacheEntry.getMaximumInfoLength(extended);
506 final byte[] infos = new byte[infoLength * entryCnt];
507 sortedEntries = new DirCacheEntry[entryCnt];
508
509 final MutableInteger infoAt = new MutableInteger();
510 for (int i = 0; i < entryCnt; i++)
511 sortedEntries[i] = new DirCacheEntry(infos, infoAt, in, md, smudge_s, smudge_ns);
512
513
514
515 for (;;) {
516 in.mark(21);
517 IO.readFully(in, hdr, 0, 20);
518 if (in.read() < 0) {
519
520
521 break;
522 }
523
524 in.reset();
525 md.update(hdr, 0, 8);
526 IO.skipFully(in, 8);
527
528 long sz = NB.decodeUInt32(hdr, 4);
529 switch (NB.decodeInt32(hdr, 0)) {
530 case EXT_TREE: {
531 if (Integer.MAX_VALUE < sz) {
532 throw new CorruptObjectException(MessageFormat.format(
533 JGitText.get().DIRCExtensionIsTooLargeAt,
534 formatExtensionName(hdr), Long.valueOf(sz)));
535 }
536 final byte[] raw = new byte[(int) sz];
537 IO.readFully(in, raw, 0, raw.length);
538 md.update(raw, 0, raw.length);
539 tree = new DirCacheTree(raw, new MutableInteger(), null);
540 break;
541 }
542 default:
543 if (hdr[0] >= 'A' && hdr[0] <= 'Z') {
544
545
546
547
548
549 skipOptionalExtension(in, md, hdr, sz);
550 } else {
551
552
553
554
555 throw new CorruptObjectException(MessageFormat.format(JGitText.get().DIRCExtensionNotSupportedByThisVersion
556 , formatExtensionName(hdr)));
557 }
558 }
559 }
560
561 readIndexChecksum = md.digest();
562 if (!Arrays.equals(readIndexChecksum, hdr)) {
563 throw new CorruptObjectException(JGitText.get().DIRCChecksumMismatch);
564 }
565 }
566
567 private void skipOptionalExtension(final InputStream in,
568 final MessageDigest md, final byte[] hdr, long sz)
569 throws IOException {
570 final byte[] b = new byte[4096];
571 while (0 < sz) {
572 int n = in.read(b, 0, (int) Math.min(b.length, sz));
573 if (n < 0) {
574 throw new EOFException(
575 MessageFormat.format(
576 JGitText.get().shortReadOfOptionalDIRCExtensionExpectedAnotherBytes,
577 formatExtensionName(hdr), Long.valueOf(sz)));
578 }
579 md.update(b, 0, n);
580 sz -= n;
581 }
582 }
583
584 private static String formatExtensionName(byte[] hdr) {
585 return "'" + new String(hdr, 0, 4, ISO_8859_1) + "'";
586 }
587
588 private static boolean is_DIRC(byte[] hdr) {
589 if (hdr.length < SIG_DIRC.length)
590 return false;
591 for (int i = 0; i < SIG_DIRC.length; i++)
592 if (hdr[i] != SIG_DIRC[i])
593 return false;
594 return true;
595 }
596
597
598
599
600
601
602
603
604
605
606 public boolean lock() throws IOException {
607 if (liveFile == null)
608 throw new IOException(JGitText.get().dirCacheDoesNotHaveABackingFile);
609 final LockFile tmp = new LockFile(liveFile);
610 if (tmp.lock()) {
611 tmp.setNeedStatInformation(true);
612 myLock = tmp;
613 return true;
614 }
615 return false;
616 }
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633 public void write() throws IOException {
634 final LockFile tmp = myLock;
635 requireLocked(tmp);
636 try (OutputStream o = tmp.getOutputStream();
637 OutputStream bo = new BufferedOutputStream(o)) {
638 writeTo(liveFile.getParentFile(), bo);
639 } catch (IOException err) {
640 tmp.unlock();
641 throw err;
642 } catch (RuntimeException err) {
643 tmp.unlock();
644 throw err;
645 } catch (Error err) {
646 tmp.unlock();
647 throw err;
648 }
649 }
650
651 void writeTo(File dir, OutputStream os) throws IOException {
652 final MessageDigest foot = Constants.newMessageDigest();
653 final DigestOutputStream dos = new DigestOutputStream(os, foot);
654
655 boolean extended = false;
656 for (int i = 0; i < entryCnt; i++) {
657 if (sortedEntries[i].isExtended()) {
658 extended = true;
659 break;
660 }
661 }
662
663
664
665 final byte[] tmp = new byte[128];
666 System.arraycopy(SIG_DIRC, 0, tmp, 0, SIG_DIRC.length);
667 NB.encodeInt32(tmp, 4, extended ? 3 : 2);
668 NB.encodeInt32(tmp, 8, entryCnt);
669 dos.write(tmp, 0, 12);
670
671
672
673 final int smudge_s;
674 final int smudge_ns;
675 if (myLock != null) {
676
677
678
679
680 myLock.createCommitSnapshot();
681 snapshot = myLock.getCommitSnapshot();
682 smudge_s = (int) (snapshot.lastModified() / 1000);
683 smudge_ns = ((int) (snapshot.lastModified() % 1000)) * 1000000;
684 } else {
685
686 smudge_ns = 0;
687 smudge_s = 0;
688 }
689
690
691
692 final boolean writeTree = tree != null;
693
694 if (repository != null && entryCnt > 0)
695 updateSmudgedEntries();
696
697 for (int i = 0; i < entryCnt; i++) {
698 final DirCacheEntry e = sortedEntries[i];
699 if (e.mightBeRacilyClean(smudge_s, smudge_ns))
700 e.smudgeRacilyClean();
701 e.write(dos);
702 }
703
704 if (writeTree) {
705 @SuppressWarnings("resource")
706
707 TemporaryBuffer bb = new TemporaryBuffer.LocalFile(dir, 5 << 20);
708 try {
709 tree.write(tmp, bb);
710 bb.close();
711
712 NB.encodeInt32(tmp, 0, EXT_TREE);
713 NB.encodeInt32(tmp, 4, (int) bb.length());
714 dos.write(tmp, 0, 8);
715 bb.writeTo(dos, null);
716 } finally {
717 bb.destroy();
718 }
719 }
720 writeIndexChecksum = foot.digest();
721 os.write(writeIndexChecksum);
722 os.close();
723 }
724
725
726
727
728
729
730
731
732
733
734
735
736 public boolean commit() {
737 final LockFile tmp = myLock;
738 requireLocked(tmp);
739 myLock = null;
740 if (!tmp.commit()) {
741 return false;
742 }
743 snapshot = tmp.getCommitSnapshot();
744 if (indexChangedListener != null
745 && !Arrays.equals(readIndexChecksum, writeIndexChecksum)) {
746 indexChangedListener.onIndexChanged(new IndexChangedEvent(true));
747 }
748 return true;
749 }
750
751 private void requireLocked(LockFile tmp) {
752 if (liveFile == null)
753 throw new IllegalStateException(JGitText.get().dirCacheIsNotLocked);
754 if (tmp == null)
755 throw new IllegalStateException(MessageFormat.format(JGitText.get().dirCacheFileIsNotLocked
756 , liveFile.getAbsolutePath()));
757 }
758
759
760
761
762
763
764 public void unlock() {
765 final LockFile tmp = myLock;
766 if (tmp != null) {
767 myLock = null;
768 tmp.unlock();
769 }
770 }
771
772
773
774
775
776
777
778
779
780
781
782 public int findEntry(String path) {
783 final byte[] p = Constants.encode(path);
784 return findEntry(p, p.length);
785 }
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806 public int findEntry(byte[] p, int pLen) {
807 return findEntry(0, p, pLen);
808 }
809
810 int findEntry(int low, byte[] p, int pLen) {
811 int high = entryCnt;
812 while (low < high) {
813 int mid = (low + high) >>> 1;
814 final int cmp = cmp(p, pLen, sortedEntries[mid]);
815 if (cmp < 0)
816 high = mid;
817 else if (cmp == 0) {
818 while (mid > 0 && cmp(p, pLen, sortedEntries[mid - 1]) == 0)
819 mid--;
820 return mid;
821 } else
822 low = mid + 1;
823 }
824 return -(low + 1);
825 }
826
827
828
829
830
831
832
833
834
835
836
837
838 public int nextEntry(int position) {
839 DirCacheEntry last = sortedEntries[position];
840 int nextIdx = position + 1;
841 while (nextIdx < entryCnt) {
842 final DirCacheEntry next = sortedEntries[nextIdx];
843 if (cmp(last, next) != 0)
844 break;
845 last = next;
846 nextIdx++;
847 }
848 return nextIdx;
849 }
850
851 int nextEntry(byte[] p, int pLen, int nextIdx) {
852 while (nextIdx < entryCnt) {
853 final DirCacheEntry next = sortedEntries[nextIdx];
854 if (!DirCacheTree.peq(p, next.path, pLen))
855 break;
856 nextIdx++;
857 }
858 return nextIdx;
859 }
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874 public int getEntryCount() {
875 return entryCnt;
876 }
877
878
879
880
881
882
883
884
885 public DirCacheEntry getEntry(int i) {
886 return sortedEntries[i];
887 }
888
889
890
891
892
893
894
895
896 public DirCacheEntry getEntry(String path) {
897 final int i = findEntry(path);
898 return i < 0 ? null : sortedEntries[i];
899 }
900
901
902
903
904
905
906
907
908 public DirCacheEntry[] getEntriesWithin(String path) {
909 if (path.length() == 0) {
910 DirCacheEntry[] r = new DirCacheEntry[entryCnt];
911 System.arraycopy(sortedEntries, 0, r, 0, entryCnt);
912 return r;
913 }
914 if (!path.endsWith("/"))
915 path += "/";
916 final byte[] p = Constants.encode(path);
917 final int pLen = p.length;
918
919 int eIdx = findEntry(p, pLen);
920 if (eIdx < 0)
921 eIdx = -(eIdx + 1);
922 final int lastIdx = nextEntry(p, pLen, eIdx);
923 final DirCacheEntry[] r = new DirCacheEntry[lastIdx - eIdx];
924 System.arraycopy(sortedEntries, eIdx, r, 0, r.length);
925 return r;
926 }
927
928 void toArray(final int i, final DirCacheEntry[] dst, final int off,
929 final int cnt) {
930 System.arraycopy(sortedEntries, i, dst, off, cnt);
931 }
932
933
934
935
936
937
938
939
940
941
942
943
944
945 public DirCacheTree getCacheTree(boolean build) {
946 if (build) {
947 if (tree == null)
948 tree = new DirCacheTree();
949 tree.validate(sortedEntries, entryCnt, 0, 0);
950 }
951 return tree;
952 }
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971 public ObjectId writeTree(ObjectInserter ow)
972 throws UnmergedPathException, IOException {
973 return getCacheTree(true).writeTree(sortedEntries, 0, 0, ow);
974 }
975
976
977
978
979
980
981
982
983 public boolean hasUnmergedPaths() {
984 for (int i = 0; i < entryCnt; i++) {
985 if (sortedEntries[i].getStage() > 0) {
986 return true;
987 }
988 }
989 return false;
990 }
991
992 private void registerIndexChangedListener(IndexChangedListener listener) {
993 this.indexChangedListener = listener;
994 }
995
996
997
998
999
1000
1001 private void updateSmudgedEntries() throws IOException {
1002 List<String> paths = new ArrayList<>(128);
1003 try (TreeWalk walk = new TreeWalk(repository)) {
1004 walk.setOperationType(OperationType.CHECKIN_OP);
1005 for (int i = 0; i < entryCnt; i++)
1006 if (sortedEntries[i].isSmudged())
1007 paths.add(sortedEntries[i].getPathString());
1008 if (paths.isEmpty())
1009 return;
1010 walk.setFilter(PathFilterGroup.createFromStrings(paths));
1011
1012 DirCacheIterator iIter = new DirCacheIterator(this);
1013 FileTreeIterator fIter = new FileTreeIterator(repository);
1014 walk.addTree(iIter);
1015 walk.addTree(fIter);
1016 fIter.setDirCacheIterator(walk, 0);
1017 walk.setRecursive(true);
1018 while (walk.next()) {
1019 iIter = walk.getTree(0, DirCacheIterator.class);
1020 if (iIter == null)
1021 continue;
1022 fIter = walk.getTree(1, FileTreeIterator.class);
1023 if (fIter == null)
1024 continue;
1025 DirCacheEntry entry = iIter.getDirCacheEntry();
1026 if (entry.isSmudged() && iIter.idEqual(fIter)) {
1027 entry.setLength(fIter.getEntryLength());
1028 entry.setLastModified(fIter.getEntryLastModified());
1029 }
1030 }
1031 }
1032 }
1033 }