@NotNull private String createLocalFile(@NotNull ObjectId id, @NotNull ObjectLoader loader) throws IOException { // Create LFS stream. final File tmpFile = new File(tempPath, UUID.randomUUID().toString()); final MessageDigest md = createSha256(); try (InputStream istream = loader.openStream(); OutputStream ostream = new FileOutputStream(tmpFile)) { byte[] buffer = new byte[0x10000]; while (true) { int size = istream.read(buffer); if (size <= 0) break; ostream.write(buffer, 0, size); md.update(buffer, 0, size); } } final String hash = new String(Hex.encodeHex(md.digest(), true)); cacheSha256.putIfAbsent(id.name(), hash); cache.commit(); // Rename file. final File lfsFile = new File( basePath, "lfs/objects/" + hash.substring(0, 2) + "/" + hash.substring(2, 4) + "/" + hash); makeParentDirs(lfsFile.getParentFile()); if (lfsFile.exists()) { if (!tmpFile.delete()) { log.warn("Can't delete temporary file: {}", lfsFile.getAbsolutePath()); } } else if (!tmpFile.renameTo(lfsFile)) { throw new IOException("Can't rename file: " + tmpFile + " -> " + lfsFile); } return hash; }
private void makeParentDirs(@NotNull File path) throws IOException { if (!path.mkdirs() && !path.exists()) { throw new IOException("Can't create directory: " + path.getAbsolutePath()); } }