LazyObjectIdSetFile.java

  1. /*
  2.  * Copyright (C) 2015, Google Inc. and others
  3.  *
  4.  * This program and the accompanying materials are made available under the
  5.  * terms of the Eclipse Distribution License v. 1.0 which is available at
  6.  * https://www.eclipse.org/org/documents/edl-v10.php.
  7.  *
  8.  * SPDX-License-Identifier: BSD-3-Clause
  9.  */

  10. package org.eclipse.jgit.internal.storage.file;

  11. import static java.nio.charset.StandardCharsets.UTF_8;

  12. import java.io.BufferedReader;
  13. import java.io.File;
  14. import java.io.FileInputStream;
  15. import java.io.IOException;
  16. import java.io.InputStreamReader;
  17. import java.io.Reader;

  18. import org.eclipse.jgit.lib.AnyObjectId;
  19. import org.eclipse.jgit.lib.MutableObjectId;
  20. import org.eclipse.jgit.lib.ObjectIdOwnerMap;
  21. import org.eclipse.jgit.lib.ObjectIdSet;

  22. /**
  23.  * Lazily loads a set of ObjectIds, one per line.
  24.  */
  25. public class LazyObjectIdSetFile implements ObjectIdSet {
  26.     private final File src;
  27.     private ObjectIdOwnerMap<Entry> set;

  28.     /**
  29.      * Create a new lazy set from a file.
  30.      *
  31.      * @param src
  32.      *            the source file.
  33.      */
  34.     public LazyObjectIdSetFile(File src) {
  35.         this.src = src;
  36.     }

  37.     /** {@inheritDoc} */
  38.     @Override
  39.     public boolean contains(AnyObjectId objectId) {
  40.         if (set == null) {
  41.             set = load();
  42.         }
  43.         return set.contains(objectId);
  44.     }

  45.     private ObjectIdOwnerMap<Entry> load() {
  46.         ObjectIdOwnerMap<Entry> r = new ObjectIdOwnerMap<>();
  47.         try (FileInputStream fin = new FileInputStream(src);
  48.                 Reader rin = new InputStreamReader(fin, UTF_8);
  49.                 BufferedReader br = new BufferedReader(rin)) {
  50.             MutableObjectId id = new MutableObjectId();
  51.             for (String line; (line = br.readLine()) != null;) {
  52.                 id.fromString(line);
  53.                 if (!r.contains(id)) {
  54.                     r.add(new Entry(id));
  55.                 }
  56.             }
  57.         } catch (IOException e) {
  58.             // Ignore IO errors accessing the lazy set.
  59.         }
  60.         return r;
  61.     }

  62.     static class Entry extends ObjectIdOwnerMap.Entry {
  63.         Entry(AnyObjectId id) {
  64.             super(id);
  65.         }
  66.     }
  67. }