Skip to content

Commit

Permalink
Refactor install hook method into smaller methods with fewer responsi…
Browse files Browse the repository at this point in the history
…bilities.
  • Loading branch information
rudikershaw committed Apr 5, 2021
1 parent 664ff51 commit 5008ea8
Showing 1 changed file with 34 additions and 22 deletions.
56 changes: 34 additions & 22 deletions src/main/java/com/rudikershaw/gitbuildhook/InstallMojo.java
Original file line number Diff line number Diff line change
Expand Up @@ -61,36 +61,48 @@ public void execute() throws MojoFailureException {
* @param hooksDirectory the directory in which to install the hook.
*/
private void installGitHook(final String hookName, final String filePath, final String hooksDirectory) {
if (Objects.isNull(filePath)) {
return;
}
final String gitHookPathStr = String.format("%s/%s", hooksDirectory, hookName);
if (Paths.get(filePath)
.toFile()
.isFile()) {
try {
Files.copy(Paths.get(filePath), Paths.get(gitHookPathStr),
StandardCopyOption.REPLACE_EXISTING);
} catch (final IOException e) {
getLog().warn("Could not move file into .git/hooks directory", e);
if (Objects.nonNull(filePath)) {
final String gitHookPathStr = hooksDirectory + File.separator + hookName;
if (Paths.get(filePath).toFile().isFile()) {
copyFromFile(filePath, gitHookPathStr);
} else {
copyFromClasspath(filePath, gitHookPathStr);
}
}
}

} else {
final URL resource = this.getClass().getClassLoader().getResource(filePath);
if (Objects.isNull(resource)) {
getLog().warn("Could not find file on filesytem or classpath");
return;
}
/**
* Copies the specified file from the file system into the the default hooks directory.
*
* @param filePath path to the file to use as the hook.
* @param gitHookPathStr the location to move the file to.
*/
private void copyFromFile(final String filePath, final String gitHookPathStr) {
try {
Files.copy(Paths.get(filePath), Paths.get(gitHookPathStr), StandardCopyOption.REPLACE_EXISTING);
} catch (final IOException e) {
getLog().warn("Could not move file into .git/hooks directory", e);
}
}

/**
* Copies the specified file from the classpath into the the default hooks directory.
*
* @param filePath path to the file to use as the hook.
* @param gitHookPathStr the location to move the file to.
*/
private void copyFromClasspath(final String filePath, final String gitHookPathStr) {
final URL resource = this.getClass().getClassLoader().getResource(filePath);
if (Objects.isNull(resource)) {
getLog().warn("Could not find file on filesystem or classpath");
} else {
try {
final File gitHookFile = Paths.get(gitHookPathStr)
.toFile();
final File gitHookFile = Paths.get(gitHookPathStr).toFile();
IOUtils.copy(resource.openStream(), new FileOutputStream(gitHookFile));
gitHookFile.setExecutable(true);
} catch (IOException e) {
} catch (final IOException e) {
getLog().warn("Could not move file from classpath into .git/hooks directory", e);
}
}
}

}

0 comments on commit 5008ea8

Please sign in to comment.