Skip to content

Commit

Permalink
validate upgraded models in MigrateCommand
Browse files Browse the repository at this point in the history
  • Loading branch information
AndrewFossAWS committed May 4, 2023
1 parent 7cd402b commit 5acd208
Showing 1 changed file with 29 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,9 @@
import software.amazon.smithy.model.traits.Trait;
import software.amazon.smithy.model.transform.ModelTransformer;
import software.amazon.smithy.model.validation.Severity;
import software.amazon.smithy.model.validation.ValidatedResultException;
import software.amazon.smithy.utils.IoUtils;
import software.amazon.smithy.utils.Pair;
import software.amazon.smithy.utils.SimpleParser;
import software.amazon.smithy.utils.StringUtils;

Expand Down Expand Up @@ -171,8 +173,31 @@ private int run(Arguments arguments, Env env) {
smithyBuild.build(resultConsumer, resultConsumer);
Model finalizedModel = resultConsumer.getResult().getModel();

for (Path modelFile : resolveModelFiles(finalizedModel, models)) {
writeMigratedFile(finalizedModel, modelFile);
List<Path> resolvedModelFiles = resolveModelFiles(finalizedModel, models);

// Validate upgraded models before writing
ModelAssembler assembler = ModelBuilder.createModelAssembler(classLoader);
smithyBuildConfig.getImports().forEach(assembler::addImport);

List<Pair<Path, String>> upgradedModels = new ArrayList<>();
for (Path modelFilePath : resolvedModelFiles) {
String upgradedModelString = upgradeFile(finalizedModel, modelFilePath);
upgradedModels.add(Pair.of(modelFilePath, upgradedModelString));
// Replace existing models with upgraded models for a Smithy IDL model file
assembler.addUnparsedModel(modelFilePath.toAbsolutePath().toString(), upgradedModelString);
}


try {
assembler.assemble().validate();
} catch (ValidatedResultException e) {
throw new RuntimeException("Upgraded Smithy models are invalid. "
+ "Please report the following errors to Smithy team.\n"
+ e.getMessage());
}

for (Pair<Path, String> upgradedModel : upgradedModels) {
writeMigratedFile(upgradedModel.right, upgradedModel.left);
}

return 0;
Expand Down Expand Up @@ -204,9 +229,9 @@ private List<Path> resolveModelFiles(Model model, List<String> modelFilesOrDirec
.collect(Collectors.toList());
}

private void writeMigratedFile(Model completeModel, Path filePath) {
private void writeMigratedFile(String upgradeFileString, Path filePath) {
try {
Files.write(filePath, upgradeFile(completeModel, filePath).getBytes(StandardCharsets.UTF_8));
Files.write(filePath, upgradeFileString.getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
throw new CliError(format("Unable to write migrated model file to %s: %s", filePath, e));
}
Expand Down

0 comments on commit 5acd208

Please sign in to comment.