void clean()

in og/shared/src/main/java/com/google/idea/blaze/common/artifact/BuildArtifactCacheDirectory.java [450:497]


  void clean(long maxTargetSize, Instant minAgeToDelete) throws IOException {
    ImmutableList<Path> entries = list();
    int failed = 0;
    long totalSize = 0;
    PriorityQueue<Entry> queue = new PriorityQueue<>(Comparator.comparing(Entry::lastAccessTime));
    for (Path p : entries) {
      try {
        Entry e = new Entry(p, readAccessTime(p), Files.size(p));
        queue.add(e);
        totalSize += e.size();
      } catch (IOException e) {
        // If we fail read the attributes for a file, we just ignore it and clean up the rest of the
        // cache as best we can.
        failed += 1;
      }
    }
    if (failed > 0) {
      logger.warning("Failed to read attributes from " + failed + " cache files when cleaning");
    }
    logger.info("Cleaning cache " + cacheDir + "; current size = " + totalSize);
    long remainingSize = totalSize;
    int deleted = 0;
    while (!queue.isEmpty()) {
      if (remainingSize <= maxTargetSize) {
        // size target reached
        logger.info(
            String.format(
                "Reached target cache size: %d<=%d; deleted %d entries",
                remainingSize, maxTargetSize, deleted));
        return;
      }
      if (queue.peek().lastAccessTime().toInstant().isAfter(minAgeToDelete)) {
        // the oldest artifact is newer than the minimum age, so we stop deleting artifacts even
        // though the cache is bigger than the max size.
        logger.info(
            String.format(
                "Not deleting entries accessed since %s; remaining cache size=%d; deleted %d"
                    + " entries",
                minAgeToDelete, remainingSize, deleted));
        return;
      }

      Entry toDelete = queue.poll();
      remainingSize -= toDelete.size();
      deleted++;
      Files.delete(toDelete.path());
    }
  }