InitGitDBRepo return Result<T> values

This commit is contained in:
Paul Campbell 2018-06-30 21:02:09 +01:00
parent ae852be86f
commit c4034a291f

View file

@ -51,32 +51,26 @@ class InitGitDBRepo {
* Initialise a new GitDB repo. * Initialise a new GitDB repo.
* *
* @param dbDir the directory to initialise the repo in * @param dbDir the directory to initialise the repo in
* @throws IOException if there is an error in creating the repo files
*/ */
static Result<Void> create(final Path dbDir) { static Result<Void> create(final Path dbDir) {
final InitGitDBRepo initRepo = new InitGitDBRepo(); final InitGitDBRepo initRepo = new InitGitDBRepo();
final File validDbDir; return initRepo.validDbDir(dbDir.toFile())
try { .peek(File::mkdirs)
validDbDir = initRepo.validDbDir(dbDir.toFile()); .flatMap(dir -> {
} catch (IOException e) { try (Repository repository = RepositoryCache.FileKey.exact(dir, FS.DETECTED).open(false)) {
return Result.error(e);
}
validDbDir.mkdirs();
try (Repository repository = RepositoryCache.FileKey.exact(validDbDir, FS.DETECTED).open(false)) {
repository.create(true); repository.create(true);
initRepo.createInitialBranchOnMaster(repository); initRepo.createInitialBranchOnMaster(repository);
} catch (IOException e) { } catch (IOException e) {
return Result.error(e); return Result.error(e);
} }
return Result.ok(null); return Result.ok(null);
});
} }
private File validDbDir(final File dbDir) throws IOException { private Result<File> validDbDir(final File dbDir) {
verifyIsNotAFile(dbDir); return Result.ok(dbDir)
if (dbDir.exists()) { .flatMap(this::verifyIsNotAFile)
verifyIsEmpty(dbDir); .flatMap(this::isEmptyIfExists);
}
return dbDir;
} }
private Result<Void> createInitialBranchOnMaster(final Repository repository) { private Result<Void> createInitialBranchOnMaster(final Repository repository) {
@ -91,18 +85,26 @@ class InitGitDBRepo {
})); }));
} }
private void verifyIsNotAFile(final File dbDir) throws NotDirectoryException { private Result<File> verifyIsNotAFile(final File dbDir) {
if (dbDir.isFile()) { if (dbDir.isFile()) {
throw new NotDirectoryException(dbDir.toString()); return Result.error(new NotDirectoryException(dbDir.toString()));
} }
return Result.ok(dbDir);
} }
private void verifyIsEmpty(final File dbDir) throws IOException { private Result<File> isEmptyIfExists(final File dbDir) {
if (dbDir.exists()) {
return Result.of(() -> {
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(dbDir.toPath())) { try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(dbDir.toPath())) {
if (directoryStream.iterator().hasNext()) { if (directoryStream.iterator().hasNext()) {
throw new DirectoryNotEmptyException(dbDir.toString()); throw new DirectoryNotEmptyException(dbDir.toString());
} }
} }
return dbDir;
}
);
}
return Result.ok(dbDir);
} }
private Result<Void> createBranch( private Result<Void> createBranch(