Skip to content

Commit

Permalink
Check for existing directory when creating template with init (#1885)
Browse files Browse the repository at this point in the history
This commit updates the Smithy Init CLI command to fail before attempting to clone the template folder when the target 
output directory already exists.

---------
Co-authored-by: Michael Dowling <[email protected]>
  • Loading branch information
hpmellema authored Jul 27, 2023
1 parent 4bffd8e commit 1f80a10
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,30 @@ public void withListArg() {
});
}

@Test
public void outputDirectoryAlreadyExists() {
IntegUtils.withProject(PROJECT_NAME, templatesDir -> {
setupTemplatesDirectory(templatesDir);

IntegUtils.withTempDir("existingOutputDir", dir -> {
Path existingPath = null;
RunResult result;
try {
existingPath = Files.createDirectory(dir.resolve("quickstart-cli"));
result = IntegUtils.run(
dir, ListUtils.of("init", "-t", "quickstart-cli", "-u", templatesDir.toString()));
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
IoUtils.rmdir(existingPath);
}

assertThat(result.getOutput(), containsString("Output directory `quickstart-cli` already exists."));
assertThat(result.getExitCode(), is(1));
});
});
}

private static void run(List<String> args, Path root) {
StringBuilder output = new StringBuilder();
int result = IoUtils.runCommand(args, root, output, Collections.emptyMap());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,15 @@ private void cloneTemplate(Path temp, ObjectNode smithyTemplatesNode, String tem
throw new IllegalArgumentException("Please specify a template name using `--template` or `-t`");
}

// Use templateName if directory is not specified
if (directory == null) {
directory = template;
}
final Path dest = Paths.get(directory);
if (Files.exists(dest)) {
throw new CliError("Output directory `" + directory + "` already exists.");
}

ObjectNode templatesNode = getTemplatesNode(smithyTemplatesNode);
if (!templatesNode.containsMember(template)) {
throw new IllegalArgumentException(String.format(
Expand All @@ -180,12 +189,8 @@ private void cloneTemplate(Path temp, ObjectNode smithyTemplatesNode, String tem
}
exec(ListUtils.of("git", "checkout"), temp);

// Use templateName if directory is not specified
if (directory == null) {
directory = template;
}

final Path dest = Paths.get(directory);

IoUtils.copyDir(Paths.get(temp.toString(), templatePath), dest);
copyIncludedFiles(temp.toString(), dest.toString(), includedFiles, template, env);

Expand Down

0 comments on commit 1f80a10

Please sign in to comment.