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 AtomicReference<PackList> packList;
136
137 private final FS fs;
138
139 private final AtomicReference<AlternateHandle[]> alternates;
140
141 private final UnpackedObjectCache unpackedObjectCache;
142
143 private final File shallowFile;
144
145 private FileSnapshot shallowFileSnapshot = FileSnapshot.DIRTY;
146
147 private Set<ObjectId> shallowCommitsIds;
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(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(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 removePack(p);
364 }
365 }
366 } while (searchPacksAgain(pList));
367 return false;
368 }
369
370 @Override
371 void resolve(Set<ObjectId> matches, AbbreviatedObjectId id)
372 throws IOException {
373 resolve(matches, id, null);
374 }
375
376 private void resolve(Set<ObjectId> matches, AbbreviatedObjectId id,
377 Set<AlternateHandle.Id> skips)
378 throws IOException {
379
380
381 int oldSize = matches.size();
382 PackList pList;
383 do {
384 pList = packList.get();
385 for (PackFile p : pList.packs) {
386 try {
387 p.resolve(matches, id, RESOLVE_ABBREV_LIMIT);
388 p.resetTransientErrorCount();
389 } catch (IOException e) {
390 handlePackError(e, p);
391 }
392 if (matches.size() > RESOLVE_ABBREV_LIMIT)
393 return;
394 }
395 } while (matches.size() == oldSize && searchPacksAgain(pList));
396
397 String fanOut = id.name().substring(0, 2);
398 String[] entries = new File(getDirectory(), fanOut).list();
399 if (entries != null) {
400 for (String e : entries) {
401 if (e.length() != Constants.OBJECT_ID_STRING_LENGTH - 2)
402 continue;
403 try {
404 ObjectId entId = ObjectId.fromString(fanOut + e);
405 if (id.prefixCompare(entId) == 0)
406 matches.add(entId);
407 } catch (IllegalArgumentException notId) {
408 continue;
409 }
410 if (matches.size() > RESOLVE_ABBREV_LIMIT)
411 return;
412 }
413 }
414
415 skips = addMe(skips);
416 for (AlternateHandle alt : myAlternates()) {
417 if (!skips.contains(alt.getId())) {
418 alt.db.resolve(matches, id, skips);
419 if (matches.size() > RESOLVE_ABBREV_LIMIT) {
420 return;
421 }
422 }
423 }
424 }
425
426 @Override
427 ObjectLoader openObject(WindowCursor curs, AnyObjectId objectId)
428 throws IOException {
429 if (unpackedObjectCache.isUnpacked(objectId)) {
430 ObjectLoader ldr = openLooseObject(curs, objectId);
431 if (ldr != null) {
432 return ldr;
433 }
434 }
435 ObjectLoader ldr = openPackedFromSelfOrAlternate(curs, objectId, null);
436 if (ldr != null) {
437 return ldr;
438 }
439 return openLooseFromSelfOrAlternate(curs, objectId, null);
440 }
441
442 private ObjectLoader openPackedFromSelfOrAlternate(WindowCursor curs,
443 AnyObjectId objectId, Set<AlternateHandle.Id> skips) {
444 ObjectLoader ldr = openPackedObject(curs, objectId);
445 if (ldr != null) {
446 return ldr;
447 }
448 skips = addMe(skips);
449 for (AlternateHandle alt : myAlternates()) {
450 if (!skips.contains(alt.getId())) {
451 ldr = alt.db.openPackedFromSelfOrAlternate(curs, objectId, skips);
452 if (ldr != null) {
453 return ldr;
454 }
455 }
456 }
457 return null;
458 }
459
460 private ObjectLoader openLooseFromSelfOrAlternate(WindowCursor curs,
461 AnyObjectId objectId, Set<AlternateHandle.Id> skips)
462 throws IOException {
463 ObjectLoader ldr = openLooseObject(curs, objectId);
464 if (ldr != null) {
465 return ldr;
466 }
467 skips = addMe(skips);
468 for (AlternateHandle alt : myAlternates()) {
469 if (!skips.contains(alt.getId())) {
470 ldr = alt.db.openLooseFromSelfOrAlternate(curs, objectId, skips);
471 if (ldr != null) {
472 return ldr;
473 }
474 }
475 }
476 return null;
477 }
478
479 ObjectLoader openPackedObject(WindowCursor curs, AnyObjectId objectId) {
480 PackList pList;
481 do {
482 SEARCH: for (;;) {
483 pList = packList.get();
484 for (PackFile p : pList.packs) {
485 try {
486 ObjectLoader ldr = p.get(curs, objectId);
487 p.resetTransientErrorCount();
488 if (ldr != null)
489 return ldr;
490 } catch (PackMismatchException e) {
491
492 if (searchPacksAgain(pList))
493 continue SEARCH;
494 } catch (IOException e) {
495 handlePackError(e, p);
496 }
497 }
498 break SEARCH;
499 }
500 } while (searchPacksAgain(pList));
501 return null;
502 }
503
504 @Override
505 ObjectLoader openLooseObject(WindowCursor curs, AnyObjectId id)
506 throws IOException {
507 File path = fileFor(id);
508 try (FileInputStream in = new FileInputStream(path)) {
509 unpackedObjectCache.add(id);
510 return UnpackedObject.open(in, path, id, curs);
511 } catch (FileNotFoundException noFile) {
512 if (path.exists()) {
513 throw noFile;
514 }
515 unpackedObjectCache.remove(id);
516 return null;
517 }
518 }
519
520 @Override
521 long getObjectSize(WindowCursor curs, AnyObjectId id)
522 throws IOException {
523 if (unpackedObjectCache.isUnpacked(id)) {
524 long len = getLooseObjectSize(curs, id);
525 if (0 <= len) {
526 return len;
527 }
528 }
529 long len = getPackedSizeFromSelfOrAlternate(curs, id, null);
530 if (0 <= len) {
531 return len;
532 }
533 return getLooseSizeFromSelfOrAlternate(curs, id, null);
534 }
535
536 private long getPackedSizeFromSelfOrAlternate(WindowCursor curs,
537 AnyObjectId id, Set<AlternateHandle.Id> skips) {
538 long len = getPackedObjectSize(curs, id);
539 if (0 <= len) {
540 return len;
541 }
542 skips = addMe(skips);
543 for (AlternateHandle alt : myAlternates()) {
544 if (!skips.contains(alt.getId())) {
545 len = alt.db.getPackedSizeFromSelfOrAlternate(curs, id, skips);
546 if (0 <= len) {
547 return len;
548 }
549 }
550 }
551 return -1;
552 }
553
554 private long getLooseSizeFromSelfOrAlternate(WindowCursor curs,
555 AnyObjectId id, Set<AlternateHandle.Id> skips) throws IOException {
556 long len = getLooseObjectSize(curs, id);
557 if (0 <= len) {
558 return len;
559 }
560 skips = addMe(skips);
561 for (AlternateHandle alt : myAlternates()) {
562 if (!skips.contains(alt.getId())) {
563 len = alt.db.getLooseSizeFromSelfOrAlternate(curs, id, skips);
564 if (0 <= len) {
565 return len;
566 }
567 }
568 }
569 return -1;
570 }
571
572 private long getPackedObjectSize(WindowCursor curs, AnyObjectId id) {
573 PackList pList;
574 do {
575 SEARCH: for (;;) {
576 pList = packList.get();
577 for (PackFile p : pList.packs) {
578 try {
579 long len = p.getObjectSize(curs, id);
580 p.resetTransientErrorCount();
581 if (0 <= len)
582 return len;
583 } catch (PackMismatchException e) {
584
585 if (searchPacksAgain(pList))
586 continue SEARCH;
587 } catch (IOException e) {
588 handlePackError(e, p);
589 }
590 }
591 break SEARCH;
592 }
593 } while (searchPacksAgain(pList));
594 return -1;
595 }
596
597 private long getLooseObjectSize(WindowCursor curs, AnyObjectId id)
598 throws IOException {
599 File f = fileFor(id);
600 try (FileInputStream in = new FileInputStream(f)) {
601 unpackedObjectCache.add(id);
602 return UnpackedObject.getSize(in, id, curs);
603 } catch (FileNotFoundException noFile) {
604 if (f.exists()) {
605 throw noFile;
606 }
607 unpackedObjectCache.remove(id);
608 return -1;
609 }
610 }
611
612 @Override
613 void selectObjectRepresentation(PackWriter packer, ObjectToPack otp,
614 WindowCursor curs) throws IOException {
615 selectObjectRepresentation(packer, otp, curs, null);
616 }
617
618 private void selectObjectRepresentation(PackWriter packer, ObjectToPack otp,
619 WindowCursor curs, Set<AlternateHandle.Id> skips) throws IOException {
620 PackList pList = packList.get();
621 SEARCH: for (;;) {
622 for (PackFile p : pList.packs) {
623 try {
624 LocalObjectRepresentation rep = p.representation(curs, otp);
625 p.resetTransientErrorCount();
626 if (rep != null)
627 packer.select(otp, rep);
628 } catch (PackMismatchException e) {
629
630
631 pList = scanPacks(pList);
632 continue SEARCH;
633 } catch (IOException e) {
634 handlePackError(e, p);
635 }
636 }
637 break SEARCH;
638 }
639
640 skips = addMe(skips);
641 for (AlternateHandle h : myAlternates()) {
642 if (!skips.contains(h.getId())) {
643 h.db.selectObjectRepresentation(packer, otp, curs, skips);
644 }
645 }
646 }
647
648 private void handlePackError(IOException e, PackFile p) {
649 String warnTmpl = null;
650 int transientErrorCount = 0;
651 String errTmpl = JGitText.get().exceptionWhileReadingPack;
652 if ((e instanceof CorruptObjectException)
653 || (e instanceof PackInvalidException)) {
654 warnTmpl = JGitText.get().corruptPack;
655
656 removePack(p);
657 } else if (e instanceof FileNotFoundException) {
658 if (p.getPackFile().exists()) {
659 errTmpl = JGitText.get().packInaccessible;
660 transientErrorCount = p.incrementTransientErrorCount();
661 } else {
662 warnTmpl = JGitText.get().packWasDeleted;
663 removePack(p);
664 }
665 } else if (FileUtils.isStaleFileHandleInCausalChain(e)) {
666 warnTmpl = JGitText.get().packHandleIsStale;
667 removePack(p);
668 } else {
669 transientErrorCount = p.incrementTransientErrorCount();
670 }
671 if (warnTmpl != null) {
672 if (LOG.isDebugEnabled()) {
673 LOG.debug(MessageFormat.format(warnTmpl,
674 p.getPackFile().getAbsolutePath()), e);
675 } else {
676 LOG.warn(MessageFormat.format(warnTmpl,
677 p.getPackFile().getAbsolutePath()));
678 }
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 private 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(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(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(PackFile[] list, 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(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(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 (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 PackFile oldPack = forReuse.remove(packName);
914 if (oldPack != null) {
915 list.add(oldPack);
916 continue;
917 }
918
919 final File packFile = new File(packDirectory, packName);
920 list.add(new PackFile(packFile, extensions));
921 foundNew = true;
922 }
923
924
925
926
927
928
929 if (!foundNew && forReuse.isEmpty() && snapshot.equals(old.snapshot)) {
930 old.snapshot.setClean(snapshot);
931 return old;
932 }
933
934 for (PackFile p : forReuse.values()) {
935 p.close();
936 }
937
938 if (list.isEmpty())
939 return new PackList(snapshot, NO_PACKS.packs);
940
941 final PackFile[] r = list.toArray(new PackFile[0]);
942 Arrays.sort(r, PackFile.SORT);
943 return new PackList(snapshot, r);
944 }
945
946 private static Map<String, PackFile> reuseMap(PackList old) {
947 final Map<String, PackFile> forReuse = new HashMap<>();
948 for (PackFile p : old.packs) {
949 if (p.invalid()) {
950
951
952
953 p.close();
954 continue;
955 }
956
957 final PackFile prior = forReuse.put(p.getPackFile().getName(), p);
958 if (prior != null) {
959
960
961
962
963
964
965 forReuse.put(prior.getPackFile().getName(), prior);
966 p.close();
967 }
968 }
969 return forReuse;
970 }
971
972 private Set<String> listPackDirectory() {
973 final String[] nameList = packDirectory.list();
974 if (nameList == null)
975 return Collections.emptySet();
976 final Set<String> nameSet = new HashSet<>(nameList.length << 1);
977 for (String name : nameList) {
978 if (name.startsWith("pack-"))
979 nameSet.add(name);
980 }
981 return nameSet;
982 }
983
984 void closeAllPackHandles(File packFile) {
985
986
987
988
989 if (packFile.exists()) {
990 for (PackFile p : getPacks()) {
991 if (packFile.getPath().equals(p.getPackFile().getPath())) {
992 p.close();
993 break;
994 }
995 }
996 }
997 }
998
999 AlternateHandle[] myAlternates() {
1000 AlternateHandle[] alt = alternates.get();
1001 if (alt == null) {
1002 synchronized (alternates) {
1003 alt = alternates.get();
1004 if (alt == null) {
1005 try {
1006 alt = loadAlternates();
1007 } catch (IOException e) {
1008 alt = new AlternateHandle[0];
1009 }
1010 alternates.set(alt);
1011 }
1012 }
1013 }
1014 return alt;
1015 }
1016
1017 Set<AlternateHandle.Id> addMe(Set<AlternateHandle.Id> skips) {
1018 if (skips == null) {
1019 skips = new HashSet<>();
1020 }
1021 skips.add(handle.getId());
1022 return skips;
1023 }
1024
1025 private AlternateHandle[] loadAlternates() throws IOException {
1026 final List<AlternateHandle> l = new ArrayList<>(4);
1027 try (BufferedReader br = open(alternatesFile)) {
1028 String line;
1029 while ((line = br.readLine()) != null) {
1030 l.add(openAlternate(line));
1031 }
1032 }
1033 return l.toArray(new AlternateHandle[0]);
1034 }
1035
1036 private static BufferedReader open(File f)
1037 throws FileNotFoundException {
1038 return new BufferedReader(new FileReader(f));
1039 }
1040
1041 private AlternateHandle openAlternate(String location)
1042 throws IOException {
1043 final File objdir = fs.resolve(objects, location);
1044 return openAlternate(objdir);
1045 }
1046
1047 private AlternateHandle openAlternate(File objdir) throws IOException {
1048 final File parent = objdir.getParentFile();
1049 if (FileKey.isGitRepository(parent, fs)) {
1050 FileKey key = FileKey.exact(parent, fs);
1051 FileRepository db = (FileRepository) RepositoryCache.open(key);
1052 return new AlternateRepository(db);
1053 }
1054
1055 ObjectDirectory db = new ObjectDirectory(config, objdir, null, fs, null);
1056 return new AlternateHandle(db);
1057 }
1058
1059
1060
1061
1062
1063
1064 @Override
1065 public File fileFor(AnyObjectId objectId) {
1066 String n = objectId.name();
1067 String d = n.substring(0, 2);
1068 String f = n.substring(2);
1069 return new File(new File(getDirectory(), d), f);
1070 }
1071
1072 private static final class PackList {
1073
1074 final FileSnapshot snapshot;
1075
1076
1077 final PackFile[] packs;
1078
1079 PackList(FileSnapshot monitor, PackFile[] packs) {
1080 this.snapshot = monitor;
1081 this.packs = packs;
1082 }
1083 }
1084
1085 static class AlternateHandle {
1086 static class Id {
1087 String alternateId;
1088
1089 public Id(File object) {
1090 try {
1091 this.alternateId = object.getCanonicalPath();
1092 } catch (Exception e) {
1093 alternateId = null;
1094 }
1095 }
1096
1097 @Override
1098 public boolean equals(Object o) {
1099 if (o == this) {
1100 return true;
1101 }
1102 if (o == null || !(o instanceof Id)) {
1103 return false;
1104 }
1105 Id aId = (Id) o;
1106 return Objects.equals(alternateId, aId.alternateId);
1107 }
1108
1109 @Override
1110 public int hashCode() {
1111 if (alternateId == null) {
1112 return 1;
1113 }
1114 return alternateId.hashCode();
1115 }
1116 }
1117
1118 final ObjectDirectory db;
1119
1120 AlternateHandle(ObjectDirectory db) {
1121 this.db = db;
1122 }
1123
1124 void close() {
1125 db.close();
1126 }
1127
1128 public Id getId(){
1129 return db.getAlternateId();
1130 }
1131 }
1132
1133 static class AlternateRepository extends AlternateHandle {
1134 final FileRepository repository;
1135
1136 AlternateRepository(FileRepository r) {
1137 super(r.getObjectDatabase());
1138 repository = r;
1139 }
1140
1141 @Override
1142 void close() {
1143 repository.close();
1144 }
1145 }
1146
1147
1148 @Override
1149 public ObjectDatabase newCachedDatabase() {
1150 return newCachedFileObjectDatabase();
1151 }
1152
1153 CachedObjectDirectory newCachedFileObjectDatabase() {
1154 return new CachedObjectDirectory(this);
1155 }
1156
1157 AlternateHandle.Id getAlternateId() {
1158 return new AlternateHandle.Id(objects);
1159 }
1160 }