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 package org.eclipse.jgit.internal.storage.file;
45
46 import static org.eclipse.jgit.internal.storage.pack.PackExt.INDEX;
47 import static org.eclipse.jgit.internal.storage.pack.PackExt.PACK;
48
49 import java.io.BufferedReader;
50 import java.io.File;
51 import java.io.FileInputStream;
52 import java.io.FileNotFoundException;
53 import java.io.FileReader;
54 import java.io.IOException;
55 import java.nio.file.AtomicMoveNotSupportedException;
56 import java.nio.file.Files;
57 import java.nio.file.StandardCopyOption;
58 import java.text.MessageFormat;
59 import java.util.ArrayList;
60 import java.util.Arrays;
61 import java.util.Collection;
62 import java.util.Collections;
63 import java.util.HashMap;
64 import java.util.HashSet;
65 import java.util.List;
66 import java.util.Map;
67 import java.util.Objects;
68 import java.util.Set;
69 import java.util.concurrent.atomic.AtomicReference;
70
71 import org.eclipse.jgit.errors.CorruptObjectException;
72 import org.eclipse.jgit.errors.PackInvalidException;
73 import org.eclipse.jgit.errors.PackMismatchException;
74 import org.eclipse.jgit.internal.JGitText;
75 import org.eclipse.jgit.internal.storage.pack.ObjectToPack;
76 import org.eclipse.jgit.internal.storage.pack.PackExt;
77 import org.eclipse.jgit.internal.storage.pack.PackWriter;
78 import org.eclipse.jgit.lib.AbbreviatedObjectId;
79 import org.eclipse.jgit.lib.AnyObjectId;
80 import org.eclipse.jgit.lib.Config;
81 import org.eclipse.jgit.lib.ConfigConstants;
82 import org.eclipse.jgit.lib.Constants;
83 import org.eclipse.jgit.lib.ObjectDatabase;
84 import org.eclipse.jgit.lib.ObjectId;
85 import org.eclipse.jgit.lib.ObjectLoader;
86 import org.eclipse.jgit.lib.RepositoryCache;
87 import org.eclipse.jgit.lib.RepositoryCache.FileKey;
88 import org.eclipse.jgit.util.FS;
89 import org.eclipse.jgit.util.FileUtils;
90 import org.slf4j.Logger;
91 import org.slf4j.LoggerFactory;
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111 public class ObjectDirectory extends FileObjectDatabase {
112 private final static Logger LOG = LoggerFactory
113 .getLogger(ObjectDirectory.class);
114
115 private static final PackList NO_PACKS = new PackList(
116 FileSnapshot.DIRTY, new PackFile[0]);
117
118
119 private static final int RESOLVE_ABBREV_LIMIT = 256;
120
121 private final AlternateHandle handle = new AlternateHandle(this);
122
123 private final Config config;
124
125 private final File objects;
126
127 private final File infoDirectory;
128
129 private final File packDirectory;
130
131 private final File preservedDirectory;
132
133 private final File alternatesFile;
134
135 private final FS fs;
136
137 private final AtomicReference<AlternateHandle[]> alternates;
138
139 private final UnpackedObjectCache unpackedObjectCache;
140
141 private final File shallowFile;
142
143 private FileSnapshot shallowFileSnapshot = FileSnapshot.DIRTY;
144
145 private Set<ObjectId> shallowCommitsIds;
146
147 final AtomicReference<PackList> packList;
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167 public ObjectDirectory(final Config cfg, final File dir,
168 File[] alternatePaths, FS fs, File shallowFile) throws IOException {
169 config = cfg;
170 objects = dir;
171 infoDirectory = new File(objects, "info");
172 packDirectory = new File(objects, "pack");
173 preservedDirectory = new File(packDirectory, "preserved");
174 alternatesFile = new File(infoDirectory, "alternates");
175 packList = new AtomicReference<>(NO_PACKS);
176 unpackedObjectCache = new UnpackedObjectCache();
177 this.fs = fs;
178 this.shallowFile = shallowFile;
179
180 alternates = new AtomicReference<>();
181 if (alternatePaths != null) {
182 AlternateHandle[] alt;
183
184 alt = new AlternateHandle[alternatePaths.length];
185 for (int i = 0; i < alternatePaths.length; i++)
186 alt[i] = openAlternate(alternatePaths[i]);
187 alternates.set(alt);
188 }
189 }
190
191
192 @Override
193 public final File getDirectory() {
194 return objects;
195 }
196
197
198
199
200
201
202
203 public final File getPackDirectory() {
204 return packDirectory;
205 }
206
207
208
209
210
211
212 public final File getPreservedDirectory() {
213 return preservedDirectory;
214 }
215
216
217 @Override
218 public boolean exists() {
219 return fs.exists(objects);
220 }
221
222
223 @Override
224 public void create() throws IOException {
225 FileUtils.mkdirs(objects);
226 FileUtils.mkdir(infoDirectory);
227 FileUtils.mkdir(packDirectory);
228 }
229
230
231 @Override
232 public ObjectDirectoryInserter newInserter() {
233 return new ObjectDirectoryInserter(this, config);
234 }
235
236
237
238
239
240
241
242 public PackInserter newPackInserter() {
243 return new PackInserter(this);
244 }
245
246
247 @Override
248 public void close() {
249 unpackedObjectCache.clear();
250
251 final PackList packs = packList.get();
252 if (packs != NO_PACKS && packList.compareAndSet(packs, NO_PACKS)) {
253 for (PackFile p : packs.packs)
254 p.close();
255 }
256
257
258 AlternateHandle[] alt = alternates.get();
259 if (alt != null && alternates.compareAndSet(alt, null)) {
260 for(final AlternateHandle od : alt)
261 od.close();
262 }
263 }
264
265
266 @Override
267 public Collection<PackFile> getPacks() {
268 PackList list = packList.get();
269 if (list == NO_PACKS)
270 list = scanPacks(list);
271 PackFile[] packs = list.packs;
272 return Collections.unmodifiableCollection(Arrays.asList(packs));
273 }
274
275
276
277
278
279
280 @Override
281 public PackFile openPack(final File pack)
282 throws IOException {
283 final String p = pack.getName();
284 if (p.length() != 50 || !p.startsWith("pack-") || !p.endsWith(".pack"))
285 throw new IOException(MessageFormat.format(JGitText.get().notAValidPack, pack));
286
287
288
289
290 int extensions = PACK.getBit() | INDEX.getBit();
291 final String base = p.substring(0, p.length() - 4);
292 for (PackExt ext : PackExt.values()) {
293 if ((extensions & ext.getBit()) == 0) {
294 final String name = base + ext.getExtension();
295 if (new File(pack.getParentFile(), name).exists())
296 extensions |= ext.getBit();
297 }
298 }
299
300 PackFile res = new PackFile(pack, extensions);
301 insertPack(res);
302 return res;
303 }
304
305
306 @Override
307 public String toString() {
308 return "ObjectDirectory[" + getDirectory() + "]";
309 }
310
311
312 @Override
313 public boolean has(AnyObjectId objectId) {
314 return unpackedObjectCache.isUnpacked(objectId)
315 || hasPackedInSelfOrAlternate(objectId, null)
316 || hasLooseInSelfOrAlternate(objectId, null);
317 }
318
319 private boolean hasPackedInSelfOrAlternate(AnyObjectId objectId,
320 Set<AlternateHandle.Id> skips) {
321 if (hasPackedObject(objectId)) {
322 return true;
323 }
324 skips = addMe(skips);
325 for (AlternateHandle alt : myAlternates()) {
326 if (!skips.contains(alt.getId())) {
327 if (alt.db.hasPackedInSelfOrAlternate(objectId, skips)) {
328 return true;
329 }
330 }
331 }
332 return false;
333 }
334
335 private boolean hasLooseInSelfOrAlternate(AnyObjectId objectId,
336 Set<AlternateHandle.Id> skips) {
337 if (fileFor(objectId).exists()) {
338 return true;
339 }
340 skips = addMe(skips);
341 for (AlternateHandle alt : myAlternates()) {
342 if (!skips.contains(alt.getId())) {
343 if (alt.db.hasLooseInSelfOrAlternate(objectId, skips)) {
344 return true;
345 }
346 }
347 }
348 return false;
349 }
350
351 boolean hasPackedObject(AnyObjectId objectId) {
352 PackList pList;
353 do {
354 pList = packList.get();
355 for (PackFile p : pList.packs) {
356 try {
357 if (p.hasObject(objectId))
358 return true;
359 } catch (IOException e) {
360
361
362
363 LOG.warn(MessageFormat.format(
364 JGitText.get().unableToReadPackfile,
365 p.getPackFile().getAbsolutePath()), e);
366 removePack(p);
367 }
368 }
369 } while (searchPacksAgain(pList));
370 return false;
371 }
372
373 @Override
374 void resolve(Set<ObjectId> matches, AbbreviatedObjectId id)
375 throws IOException {
376 resolve(matches, id, null);
377 }
378
379 private void resolve(Set<ObjectId> matches, AbbreviatedObjectId id,
380 Set<AlternateHandle.Id> skips)
381 throws IOException {
382
383
384 int oldSize = matches.size();
385 PackList pList;
386 do {
387 pList = packList.get();
388 for (PackFile p : pList.packs) {
389 try {
390 p.resolve(matches, id, RESOLVE_ABBREV_LIMIT);
391 p.resetTransientErrorCount();
392 } catch (IOException e) {
393 handlePackError(e, p);
394 }
395 if (matches.size() > RESOLVE_ABBREV_LIMIT)
396 return;
397 }
398 } while (matches.size() == oldSize && searchPacksAgain(pList));
399
400 String fanOut = id.name().substring(0, 2);
401 String[] entries = new File(getDirectory(), fanOut).list();
402 if (entries != null) {
403 for (String e : entries) {
404 if (e.length() != Constants.OBJECT_ID_STRING_LENGTH - 2)
405 continue;
406 try {
407 ObjectId entId = ObjectId.fromString(fanOut + e);
408 if (id.prefixCompare(entId) == 0)
409 matches.add(entId);
410 } catch (IllegalArgumentException notId) {
411 continue;
412 }
413 if (matches.size() > RESOLVE_ABBREV_LIMIT)
414 return;
415 }
416 }
417
418 skips = addMe(skips);
419 for (AlternateHandle alt : myAlternates()) {
420 if (!skips.contains(alt.getId())) {
421 alt.db.resolve(matches, id, skips);
422 if (matches.size() > RESOLVE_ABBREV_LIMIT) {
423 return;
424 }
425 }
426 }
427 }
428
429 @Override
430 ObjectLoader openObject(WindowCursor curs, AnyObjectId objectId)
431 throws IOException {
432 if (unpackedObjectCache.isUnpacked(objectId)) {
433 ObjectLoader ldr = openLooseObject(curs, objectId);
434 if (ldr != null) {
435 return ldr;
436 }
437 }
438 ObjectLoader ldr = openPackedFromSelfOrAlternate(curs, objectId, null);
439 if (ldr != null) {
440 return ldr;
441 }
442 return openLooseFromSelfOrAlternate(curs, objectId, null);
443 }
444
445 private ObjectLoader openPackedFromSelfOrAlternate(WindowCursor curs,
446 AnyObjectId objectId, Set<AlternateHandle.Id> skips) {
447 ObjectLoader ldr = openPackedObject(curs, objectId);
448 if (ldr != null) {
449 return ldr;
450 }
451 skips = addMe(skips);
452 for (AlternateHandle alt : myAlternates()) {
453 if (!skips.contains(alt.getId())) {
454 ldr = alt.db.openPackedFromSelfOrAlternate(curs, objectId, skips);
455 if (ldr != null) {
456 return ldr;
457 }
458 }
459 }
460 return null;
461 }
462
463 private ObjectLoader openLooseFromSelfOrAlternate(WindowCursor curs,
464 AnyObjectId objectId, Set<AlternateHandle.Id> skips)
465 throws IOException {
466 ObjectLoader ldr = openLooseObject(curs, objectId);
467 if (ldr != null) {
468 return ldr;
469 }
470 skips = addMe(skips);
471 for (AlternateHandle alt : myAlternates()) {
472 if (!skips.contains(alt.getId())) {
473 ldr = alt.db.openLooseFromSelfOrAlternate(curs, objectId, skips);
474 if (ldr != null) {
475 return ldr;
476 }
477 }
478 }
479 return null;
480 }
481
482 ObjectLoader openPackedObject(WindowCursor curs, AnyObjectId objectId) {
483 PackList pList;
484 do {
485 SEARCH: for (;;) {
486 pList = packList.get();
487 for (PackFile p : pList.packs) {
488 try {
489 ObjectLoader ldr = p.get(curs, objectId);
490 p.resetTransientErrorCount();
491 if (ldr != null)
492 return ldr;
493 } catch (PackMismatchException e) {
494
495 if (searchPacksAgain(pList))
496 continue SEARCH;
497 } catch (IOException e) {
498 handlePackError(e, p);
499 }
500 }
501 break SEARCH;
502 }
503 } while (searchPacksAgain(pList));
504 return null;
505 }
506
507 @Override
508 ObjectLoader openLooseObject(WindowCursor curs, AnyObjectId id)
509 throws IOException {
510 File path = fileFor(id);
511 try (FileInputStream in = new FileInputStream(path)) {
512 unpackedObjectCache.add(id);
513 return UnpackedObject.open(in, path, id, curs);
514 } catch (FileNotFoundException noFile) {
515 if (path.exists()) {
516 throw noFile;
517 }
518 unpackedObjectCache.remove(id);
519 return null;
520 }
521 }
522
523 @Override
524 long getObjectSize(WindowCursor curs, AnyObjectId id)
525 throws IOException {
526 if (unpackedObjectCache.isUnpacked(id)) {
527 long len = getLooseObjectSize(curs, id);
528 if (0 <= len) {
529 return len;
530 }
531 }
532 long len = getPackedSizeFromSelfOrAlternate(curs, id, null);
533 if (0 <= len) {
534 return len;
535 }
536 return getLooseSizeFromSelfOrAlternate(curs, id, null);
537 }
538
539 private long getPackedSizeFromSelfOrAlternate(WindowCursor curs,
540 AnyObjectId id, Set<AlternateHandle.Id> skips) {
541 long len = getPackedObjectSize(curs, id);
542 if (0 <= len) {
543 return len;
544 }
545 skips = addMe(skips);
546 for (AlternateHandle alt : myAlternates()) {
547 if (!skips.contains(alt.getId())) {
548 len = alt.db.getPackedSizeFromSelfOrAlternate(curs, id, skips);
549 if (0 <= len) {
550 return len;
551 }
552 }
553 }
554 return -1;
555 }
556
557 private long getLooseSizeFromSelfOrAlternate(WindowCursor curs,
558 AnyObjectId id, Set<AlternateHandle.Id> skips) throws IOException {
559 long len = getLooseObjectSize(curs, id);
560 if (0 <= len) {
561 return len;
562 }
563 skips = addMe(skips);
564 for (AlternateHandle alt : myAlternates()) {
565 if (!skips.contains(alt.getId())) {
566 len = alt.db.getLooseSizeFromSelfOrAlternate(curs, id, skips);
567 if (0 <= len) {
568 return len;
569 }
570 }
571 }
572 return -1;
573 }
574
575 private long getPackedObjectSize(WindowCursor curs, AnyObjectId id) {
576 PackList pList;
577 do {
578 SEARCH: for (;;) {
579 pList = packList.get();
580 for (PackFile p : pList.packs) {
581 try {
582 long len = p.getObjectSize(curs, id);
583 p.resetTransientErrorCount();
584 if (0 <= len)
585 return len;
586 } catch (PackMismatchException e) {
587
588 if (searchPacksAgain(pList))
589 continue SEARCH;
590 } catch (IOException e) {
591 handlePackError(e, p);
592 }
593 }
594 break SEARCH;
595 }
596 } while (searchPacksAgain(pList));
597 return -1;
598 }
599
600 private long getLooseObjectSize(WindowCursor curs, AnyObjectId id)
601 throws IOException {
602 File f = fileFor(id);
603 try (FileInputStream in = new FileInputStream(f)) {
604 unpackedObjectCache.add(id);
605 return UnpackedObject.getSize(in, id, curs);
606 } catch (FileNotFoundException noFile) {
607 if (f.exists()) {
608 throw noFile;
609 }
610 unpackedObjectCache.remove(id);
611 return -1;
612 }
613 }
614
615 @Override
616 void selectObjectRepresentation(PackWriter packer, ObjectToPack otp,
617 WindowCursor curs) throws IOException {
618 selectObjectRepresentation(packer, otp, curs, null);
619 }
620
621 private void selectObjectRepresentation(PackWriter packer, ObjectToPack otp,
622 WindowCursor curs, Set<AlternateHandle.Id> skips) throws IOException {
623 PackList pList = packList.get();
624 SEARCH: for (;;) {
625 for (final PackFile p : pList.packs) {
626 try {
627 LocalObjectRepresentation rep = p.representation(curs, otp);
628 p.resetTransientErrorCount();
629 if (rep != null)
630 packer.select(otp, rep);
631 } catch (PackMismatchException e) {
632
633
634 pList = scanPacks(pList);
635 continue SEARCH;
636 } catch (IOException e) {
637 handlePackError(e, p);
638 }
639 }
640 break SEARCH;
641 }
642
643 skips = addMe(skips);
644 for (AlternateHandle h : myAlternates()) {
645 if (!skips.contains(h.getId())) {
646 h.db.selectObjectRepresentation(packer, otp, curs, skips);
647 }
648 }
649 }
650
651 private void handlePackError(IOException e, PackFile p) {
652 String warnTmpl = null;
653 int transientErrorCount = 0;
654 String errTmpl = JGitText.get().exceptionWhileReadingPack;
655 if ((e instanceof CorruptObjectException)
656 || (e instanceof PackInvalidException)) {
657 warnTmpl = JGitText.get().corruptPack;
658 LOG.warn(MessageFormat.format(warnTmpl,
659 p.getPackFile().getAbsolutePath()), e);
660
661 removePack(p);
662 } else if (e instanceof FileNotFoundException) {
663 if (p.getPackFile().exists()) {
664 errTmpl = JGitText.get().packInaccessible;
665 transientErrorCount = p.incrementTransientErrorCount();
666 } else {
667 warnTmpl = JGitText.get().packWasDeleted;
668 removePack(p);
669 }
670 } else if (FileUtils.isStaleFileHandleInCausalChain(e)) {
671 warnTmpl = JGitText.get().packHandleIsStale;
672 removePack(p);
673 } else {
674 transientErrorCount = p.incrementTransientErrorCount();
675 }
676 if (warnTmpl != null) {
677 LOG.warn(MessageFormat.format(warnTmpl,
678 p.getPackFile().getAbsolutePath()), e);
679 } else {
680 if (doLogExponentialBackoff(transientErrorCount)) {
681
682
683 LOG.error(MessageFormat.format(errTmpl,
684 p.getPackFile().getAbsolutePath(),
685 Integer.valueOf(transientErrorCount)), e);
686 }
687 }
688 }
689
690
691
692
693
694
695 private boolean doLogExponentialBackoff(int n) {
696 return (n & (n - 1)) == 0;
697 }
698
699 @Override
700 InsertLooseObjectResult insertUnpackedObject(File tmp, ObjectId id,
701 boolean createDuplicate) throws IOException {
702
703
704 if (unpackedObjectCache.isUnpacked(id)) {
705 FileUtils.delete(tmp, FileUtils.RETRY);
706 return InsertLooseObjectResult.EXISTS_LOOSE;
707 }
708 if (!createDuplicate && has(id)) {
709 FileUtils.delete(tmp, FileUtils.RETRY);
710 return InsertLooseObjectResult.EXISTS_PACKED;
711 }
712
713 final File dst = fileFor(id);
714 if (dst.exists()) {
715
716
717
718
719 FileUtils.delete(tmp, FileUtils.RETRY);
720 return InsertLooseObjectResult.EXISTS_LOOSE;
721 }
722 try {
723 Files.move(FileUtils.toPath(tmp), FileUtils.toPath(dst),
724 StandardCopyOption.ATOMIC_MOVE);
725 dst.setReadOnly();
726 unpackedObjectCache.add(id);
727 return InsertLooseObjectResult.INSERTED;
728 } catch (AtomicMoveNotSupportedException e) {
729 LOG.error(e.getMessage(), e);
730 } catch (IOException e) {
731
732 }
733
734
735
736
737
738 FileUtils.mkdir(dst.getParentFile(), true);
739 try {
740 Files.move(FileUtils.toPath(tmp), FileUtils.toPath(dst),
741 StandardCopyOption.ATOMIC_MOVE);
742 dst.setReadOnly();
743 unpackedObjectCache.add(id);
744 return InsertLooseObjectResult.INSERTED;
745 } catch (AtomicMoveNotSupportedException e) {
746 LOG.error(e.getMessage(), e);
747 } catch (IOException e) {
748 LOG.debug(e.getMessage(), e);
749 }
750
751 if (!createDuplicate && has(id)) {
752 FileUtils.delete(tmp, FileUtils.RETRY);
753 return InsertLooseObjectResult.EXISTS_PACKED;
754 }
755
756
757
758
759
760
761 FileUtils.delete(tmp, FileUtils.RETRY);
762 return InsertLooseObjectResult.FAILURE;
763 }
764
765 boolean searchPacksAgain(PackList old) {
766
767
768
769
770
771
772 boolean trustFolderStat = config.getBoolean(
773 ConfigConstants.CONFIG_CORE_SECTION,
774 ConfigConstants.CONFIG_KEY_TRUSTFOLDERSTAT, true);
775
776 return ((!trustFolderStat) || old.snapshot.isModified(packDirectory))
777 && old != scanPacks(old);
778 }
779
780 @Override
781 Config getConfig() {
782 return config;
783 }
784
785 @Override
786 FS getFS() {
787 return fs;
788 }
789
790 @Override
791 Set<ObjectId> getShallowCommits() throws IOException {
792 if (shallowFile == null || !shallowFile.isFile())
793 return Collections.emptySet();
794
795 if (shallowFileSnapshot == null
796 || shallowFileSnapshot.isModified(shallowFile)) {
797 shallowCommitsIds = new HashSet<>();
798
799 try (BufferedReader reader = open(shallowFile)) {
800 String line;
801 while ((line = reader.readLine()) != null) {
802 try {
803 shallowCommitsIds.add(ObjectId.fromString(line));
804 } catch (IllegalArgumentException ex) {
805 throw new IOException(MessageFormat
806 .format(JGitText.get().badShallowLine, line));
807 }
808 }
809 }
810
811 shallowFileSnapshot = FileSnapshot.save(shallowFile);
812 }
813
814 return shallowCommitsIds;
815 }
816
817 private void insertPack(final PackFile pf) {
818 PackList o, n;
819 do {
820 o = packList.get();
821
822
823
824
825
826 final PackFile[] oldList = o.packs;
827 final String name = pf.getPackFile().getName();
828 for (PackFile p : oldList) {
829 if (name.equals(p.getPackFile().getName()))
830 return;
831 }
832
833 final PackFile[] newList = new PackFile[1 + oldList.length];
834 newList[0] = pf;
835 System.arraycopy(oldList, 0, newList, 1, oldList.length);
836 n = new PackList(o.snapshot, newList);
837 } while (!packList.compareAndSet(o, n));
838 }
839
840 private void removePack(final PackFile deadPack) {
841 PackList o, n;
842 do {
843 o = packList.get();
844
845 final PackFile[] oldList = o.packs;
846 final int j = indexOf(oldList, deadPack);
847 if (j < 0)
848 break;
849
850 final PackFile[] newList = new PackFile[oldList.length - 1];
851 System.arraycopy(oldList, 0, newList, 0, j);
852 System.arraycopy(oldList, j + 1, newList, j, newList.length - j);
853 n = new PackList(o.snapshot, newList);
854 } while (!packList.compareAndSet(o, n));
855 deadPack.close();
856 }
857
858 private static int indexOf(final PackFile[] list, final PackFile pack) {
859 for (int i = 0; i < list.length; i++) {
860 if (list[i] == pack)
861 return i;
862 }
863 return -1;
864 }
865
866 private PackList scanPacks(final PackList original) {
867 synchronized (packList) {
868 PackList o, n;
869 do {
870 o = packList.get();
871 if (o != original) {
872
873
874
875 return o;
876 }
877 n = scanPacksImpl(o);
878 if (n == o)
879 return n;
880 } while (!packList.compareAndSet(o, n));
881 return n;
882 }
883 }
884
885 private PackList scanPacksImpl(final PackList old) {
886 final Map<String, PackFile> forReuse = reuseMap(old);
887 final FileSnapshot snapshot = FileSnapshot.save(packDirectory);
888 final Set<String> names = listPackDirectory();
889 final List<PackFile> list = new ArrayList<>(names.size() >> 2);
890 boolean foundNew = false;
891 for (final String indexName : names) {
892
893
894 if (indexName.length() != 49 || !indexName.endsWith(".idx"))
895 continue;
896
897 final String base = indexName.substring(0, indexName.length() - 3);
898 int extensions = 0;
899 for (PackExt ext : PackExt.values()) {
900 if (names.contains(base + ext.getExtension()))
901 extensions |= ext.getBit();
902 }
903
904 if ((extensions & PACK.getBit()) == 0) {
905
906
907
908
909 continue;
910 }
911
912 final String packName = base + PACK.getExtension();
913 final File packFile = new File(packDirectory, packName);
914 final PackFile oldPack = forReuse.remove(packName);
915 if (oldPack != null
916 && !oldPack.getFileSnapshot().isModified(packFile)) {
917 list.add(oldPack);
918 continue;
919 }
920
921 list.add(new PackFile(packFile, extensions));
922 foundNew = true;
923 }
924
925
926
927
928
929
930 if (!foundNew && forReuse.isEmpty() && snapshot.equals(old.snapshot)) {
931 old.snapshot.setClean(snapshot);
932 return old;
933 }
934
935 for (final PackFile p : forReuse.values()) {
936 p.close();
937 }
938
939 if (list.isEmpty())
940 return new PackList(snapshot, NO_PACKS.packs);
941
942 final PackFile[] r = list.toArray(new PackFile[list.size()]);
943 Arrays.sort(r, PackFile.SORT);
944 return new PackList(snapshot, r);
945 }
946
947 private static Map<String, PackFile> reuseMap(final PackList old) {
948 final Map<String, PackFile> forReuse = new HashMap<>();
949 for (final PackFile p : old.packs) {
950 if (p.invalid()) {
951
952
953
954 p.close();
955 continue;
956 }
957
958 final PackFile prior = forReuse.put(p.getPackFile().getName(), p);
959 if (prior != null) {
960
961
962
963
964
965
966 forReuse.put(prior.getPackFile().getName(), prior);
967 p.close();
968 }
969 }
970 return forReuse;
971 }
972
973 private Set<String> listPackDirectory() {
974 final String[] nameList = packDirectory.list();
975 if (nameList == null)
976 return Collections.emptySet();
977 final Set<String> nameSet = new HashSet<>(nameList.length << 1);
978 for (final String name : nameList) {
979 if (name.startsWith("pack-"))
980 nameSet.add(name);
981 }
982 return nameSet;
983 }
984
985 void closeAllPackHandles(File packFile) {
986
987
988
989
990 if (packFile.exists()) {
991 for (PackFile p : getPacks()) {
992 if (packFile.getPath().equals(p.getPackFile().getPath())) {
993 p.close();
994 break;
995 }
996 }
997 }
998 }
999
1000 AlternateHandle[] myAlternates() {
1001 AlternateHandle[] alt = alternates.get();
1002 if (alt == null) {
1003 synchronized (alternates) {
1004 alt = alternates.get();
1005 if (alt == null) {
1006 try {
1007 alt = loadAlternates();
1008 } catch (IOException e) {
1009 alt = new AlternateHandle[0];
1010 }
1011 alternates.set(alt);
1012 }
1013 }
1014 }
1015 return alt;
1016 }
1017
1018 Set<AlternateHandle.Id> addMe(Set<AlternateHandle.Id> skips) {
1019 if (skips == null) {
1020 skips = new HashSet<>();
1021 }
1022 skips.add(handle.getId());
1023 return skips;
1024 }
1025
1026 private AlternateHandle[] loadAlternates() throws IOException {
1027 final List<AlternateHandle> l = new ArrayList<>(4);
1028 try (BufferedReader br = open(alternatesFile)) {
1029 String line;
1030 while ((line = br.readLine()) != null) {
1031 l.add(openAlternate(line));
1032 }
1033 }
1034 return l.toArray(new AlternateHandle[l.size()]);
1035 }
1036
1037 private static BufferedReader open(final File f)
1038 throws FileNotFoundException {
1039 return new BufferedReader(new FileReader(f));
1040 }
1041
1042 private AlternateHandle openAlternate(final String location)
1043 throws IOException {
1044 final File objdir = fs.resolve(objects, location);
1045 return openAlternate(objdir);
1046 }
1047
1048 private AlternateHandle openAlternate(File objdir) throws IOException {
1049 final File parent = objdir.getParentFile();
1050 if (FileKey.isGitRepository(parent, fs)) {
1051 FileKey key = FileKey.exact(parent, fs);
1052 FileRepository db = (FileRepository) RepositoryCache.open(key);
1053 return new AlternateRepository(db);
1054 }
1055
1056 ObjectDirectory db = new ObjectDirectory(config, objdir, null, fs, null);
1057 return new AlternateHandle(db);
1058 }
1059
1060
1061
1062
1063
1064
1065 @Override
1066 public File fileFor(AnyObjectId objectId) {
1067 String n = objectId.name();
1068 String d = n.substring(0, 2);
1069 String f = n.substring(2);
1070 return new File(new File(getDirectory(), d), f);
1071 }
1072
1073 static final class PackList {
1074
1075 final FileSnapshot snapshot;
1076
1077
1078 final PackFile[] packs;
1079
1080 PackList(final FileSnapshot monitor, final PackFile[] packs) {
1081 this.snapshot = monitor;
1082 this.packs = packs;
1083 }
1084 }
1085
1086 static class AlternateHandle {
1087 static class Id {
1088 String alternateId;
1089
1090 public Id(File object) {
1091 try {
1092 this.alternateId = object.getCanonicalPath();
1093 } catch (Exception e) {
1094 alternateId = null;
1095 }
1096 }
1097
1098 @Override
1099 public boolean equals(Object o) {
1100 if (o == this) {
1101 return true;
1102 }
1103 if (o == null || !(o instanceof Id)) {
1104 return false;
1105 }
1106 Id aId = (Id) o;
1107 return Objects.equals(alternateId, aId.alternateId);
1108 }
1109
1110 @Override
1111 public int hashCode() {
1112 if (alternateId == null) {
1113 return 1;
1114 }
1115 return alternateId.hashCode();
1116 }
1117 }
1118
1119 final ObjectDirectory db;
1120
1121 AlternateHandle(ObjectDirectory db) {
1122 this.db = db;
1123 }
1124
1125 void close() {
1126 db.close();
1127 }
1128
1129 public Id getId(){
1130 return db.getAlternateId();
1131 }
1132 }
1133
1134 static class AlternateRepository extends AlternateHandle {
1135 final FileRepository repository;
1136
1137 AlternateRepository(FileRepository r) {
1138 super(r.getObjectDatabase());
1139 repository = r;
1140 }
1141
1142 @Override
1143 void close() {
1144 repository.close();
1145 }
1146 }
1147
1148
1149 @Override
1150 public ObjectDatabase newCachedDatabase() {
1151 return newCachedFileObjectDatabase();
1152 }
1153
1154 CachedObjectDirectory newCachedFileObjectDatabase() {
1155 return new CachedObjectDirectory(this);
1156 }
1157
1158 AlternateHandle.Id getAlternateId() {
1159 return new AlternateHandle.Id(objects);
1160 }
1161 }