Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add validation events decorators #1774

Merged
merged 8 commits into from
May 24, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -47,5 +47,7 @@ public final class ColorTheme {
public static final Style DIFF_TITLE = Style.of(Style.BG_BRIGHT_BLACK, Style.WHITE);
public static final Style DIFF_EVENT_TITLE = Style.of(Style.BG_BRIGHT_BLUE, Style.BLACK);

public static final Style HINT_TITLE = Style.of(Style.BRIGHT_GREEN);

private ColorTheme() {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,13 @@ public String format(ValidationEvent event) {

writeMessage(writer, event.getMessage());
writer.append(ls);
event.getHint().ifPresent(hint -> {
String hintLabel = "HINT: ";
writer.append(ls);
colors.style(writer, hintLabel, ColorTheme.HINT_TITLE);
writer.append(StyleHelper.formatMessage(hint, LINE_LENGTH - hintLabel.length(), colors));
writer.append(ls);
});

return writer.toString();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,23 +51,60 @@ public void formatsEventsWithNoColors() {
}

@Test
public void formatsEventsWithColors() {
PrettyAnsiValidationFormatter pretty = createFormatter(AnsiColorFormatter.FORCE_COLOR);
String formatted = formatTestEventWithSeverity(pretty, Severity.ERROR);
public void formatsEventsWithHintWithNoColors() {
PrettyAnsiValidationFormatter pretty = createFormatter(AnsiColorFormatter.NO_COLOR);
String formatted = formatTestEventWithSeverity(pretty, Severity.ERROR, "Some hint");

assertThat(formatted, equalTo(
"\n"
+ "\u001B[31m── \u001B[0m\u001B[41;30m ERROR \u001B[0m\u001B[31m ───────────────────────────────────────────────────────────────── \u001B[0mFoo\n"
+ "\u001B[90mShape: \u001B[0m\u001B[95msmithy.example#Foo\u001B[0m\n"
+ "\u001B[90mFile: \u001B[0m\u001B[90mbuild/resources/test/software/amazon/smithy/cli/commands/valid-model.smithy:5:1\u001B[0m\n"
+ "── ERROR ───────────────────────────────────────────────────────────────── Foo\n"
+ "Shape: smithy.example#Foo\n"
+ "File: build/resources/test/software/amazon/smithy/cli/commands/valid-model.smithy:5:1\n"
+ "\n"
+ "\u001B[90m4| \u001B[0m\n"
+ "\u001B[90m5| \u001B[0mresource Foo {\n"
+ "\u001B[90m |\u001B[0m \u001B[31m^\u001B[0m\n"
+ "4| \n"
+ "5| resource Foo {\n"
+ " | ^\n"
+ "\n"
+ "Hello, \u001B[36mthere\u001B[0m\n"));
+ "Hello, `there`\n\n"
+ "HINT: Some hint\n")); // keeps ticks because formatting is disabled.
}

@Test
public void formatsEventsWithColors() {
PrettyAnsiValidationFormatter pretty = createFormatter(AnsiColorFormatter.FORCE_COLOR);
String formatted = formatTestEventWithSeverity(pretty, Severity.ERROR);

assertThat(formatted, equalTo(
"\n"
+ "\u001B[31m── \u001B[0m\u001B[41;30m ERROR \u001B[0m\u001B[31m ───────────────────────────────────────────────────────────────── \u001B[0mFoo\n"
+ "\u001B[90mShape: \u001B[0m\u001B[95msmithy.example#Foo\u001B[0m\n"
+ "\u001B[90mFile: \u001B[0m\u001B[90mbuild/resources/test/software/amazon/smithy/cli/commands/valid-model.smithy:5:1\u001B[0m\n"
+ "\n"
+ "\u001B[90m4| \u001B[0m\n"
+ "\u001B[90m5| \u001B[0mresource Foo {\n"
+ "\u001B[90m |\u001B[0m \u001B[31m^\u001B[0m\n"
+ "\n"
+ "Hello, \u001B[36mthere\u001B[0m\n"));
}

@Test
public void formatsEventsWithHintWithColors() {
PrettyAnsiValidationFormatter pretty = createFormatter(AnsiColorFormatter.FORCE_COLOR);
String formatted = formatTestEventWithSeverity(pretty, Severity.ERROR, "Some hint");

assertThat(formatted, equalTo(
"\n"
+ "\u001B[31m── \u001B[0m\u001B[41;30m ERROR \u001B[0m\u001B[31m ───────────────────────────────────────────────────────────────── \u001B[0mFoo\n"
+ "\u001B[90mShape: \u001B[0m\u001B[95msmithy.example#Foo\u001B[0m\n"
+ "\u001B[90mFile: \u001B[0m\u001B[90mbuild/resources/test/software/amazon/smithy/cli/commands/valid-model.smithy:5:1\u001B[0m\n"
+ "\n"
+ "\u001B[90m4| \u001B[0m\n"
+ "\u001B[90m5| \u001B[0mresource Foo {\n"
+ "\u001B[90m |\u001B[0m \u001B[31m^\u001B[0m\n"
+ "\n"
+ "Hello, \u001B[36mthere\u001B[0m\n\n"
+ "\u001B[92mHINT: \u001B[0mSome hint\n"));
}
@Test
public void doesNotIncludeSourceLocationNoneInOutput() {
PrettyAnsiValidationFormatter pretty = createFormatter(AnsiColorFormatter.NO_COLOR);
Expand Down Expand Up @@ -116,12 +153,17 @@ private PrettyAnsiValidationFormatter createFormatter(ColorFormatter colors) {
}

private String formatTestEventWithSeverity(PrettyAnsiValidationFormatter pretty, Severity severity) {
return formatTestEventWithSeverity(pretty, severity, null);
}

private String formatTestEventWithSeverity(PrettyAnsiValidationFormatter pretty, Severity severity, String hint) {
Model model = Model.assembler().addImport(getClass().getResource("valid-model.smithy")).assemble().unwrap();
ValidationEvent event = ValidationEvent.builder()
.id("Foo")
.severity(severity)
.shape(model.expectShape(ShapeId.from("smithy.example#Foo")))
.message("Hello, `there`")
.hint(hint)
.build();
return normalizeLinesAndFiles(pretty.format(event));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
final class LoaderTraitMap {

private static final Logger LOGGER = Logger.getLogger(LoaderTraitMap.class.getName());
private static final String UNRESOLVED_TRAIT_SUFFIX = ".UnresolvedTrait";

private final TraitFactory traitFactory;
private final Map<ShapeId, Map<ShapeId, Node>> traits = new HashMap<>();
Expand Down Expand Up @@ -114,7 +115,7 @@ private void validateTraitIsKnown(ShapeId target, ShapeId traitId, Trait trait,
if (!shapeMap.isRootShapeDefined(traitId) && (trait == null || !trait.isSynthetic())) {
Severity severity = allowUnknownTraits ? Severity.WARNING : Severity.ERROR;
events.add(ValidationEvent.builder()
.id(Validator.MODEL_ERROR)
.id(Validator.MODEL_ERROR + UNRESOLVED_TRAIT_SUFFIX)
.severity(severity)
.sourceLocation(sourceLocation)
.shapeId(target)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@
import software.amazon.smithy.model.validation.Severity;
import software.amazon.smithy.model.validation.ValidatedResult;
import software.amazon.smithy.model.validation.ValidationEvent;
import software.amazon.smithy.model.validation.ValidationEventDecorator;
import software.amazon.smithy.model.validation.ValidationEventDecoratorFactory;
import software.amazon.smithy.model.validation.Validator;
import software.amazon.smithy.model.validation.ValidatorFactory;
import software.amazon.smithy.utils.Pair;
Expand Down Expand Up @@ -93,9 +95,11 @@ public final class ModelAssembler {

private TraitFactory traitFactory;
private ValidatorFactory validatorFactory;
private ValidationEventDecoratorFactory validationEventDecoratorFactory;
private boolean disableValidation;
private final Map<String, Supplier<InputStream>> inputStreamModels = new LinkedHashMap<>();
private final List<Validator> validators = new ArrayList<>();
private final List<ValidationEventDecorator> validationEventDecorators = new ArrayList<>();
private final List<Node> documentNodes = new ArrayList<>();
private final List<Model> mergeModels = new ArrayList<>();
private final List<Shape> shapes = new ArrayList<>();
Expand All @@ -111,6 +115,12 @@ static final class LazyTraitFactoryHolder {
static final TraitFactory INSTANCE = TraitFactory.createServiceFactory(ModelAssembler.class.getClassLoader());
}

// Lazy initialization holder class idiom to hold a default event validation decorator factory.
static final class LazyValidationEventDecoratorFactoryHolder {
static final ValidationEventDecoratorFactory INSTANCE =
ValidationEventDecoratorFactory.createServiceFactory(ModelAssembler.class.getClassLoader());
}

/**
* Creates a copy of the current model assembler.
*
Expand All @@ -120,8 +130,10 @@ public ModelAssembler copy() {
ModelAssembler assembler = new ModelAssembler();
assembler.traitFactory = traitFactory;
assembler.validatorFactory = validatorFactory;
assembler.validationEventDecoratorFactory = validationEventDecoratorFactory;
assembler.inputStreamModels.putAll(inputStreamModels);
assembler.validators.addAll(validators);
assembler.validationEventDecorators.addAll(validationEventDecorators);
assembler.documentNodes.addAll(documentNodes);
assembler.mergeModels.addAll(mergeModels);
assembler.shapes.addAll(shapes);
Expand Down Expand Up @@ -165,6 +177,7 @@ public ModelAssembler reset() {
mergeModels.clear();
inputStreamModels.clear();
validators.clear();
validationEventDecorators.clear();
documentNodes.clear();
disablePrelude = false;
disableValidation = false;
Expand Down Expand Up @@ -198,6 +211,22 @@ public ModelAssembler validatorFactory(ValidatorFactory validatorFactory) {
return this;
}

/**
* Sets a custom {@link ValidationEventDecoratorFactory} used to resolve validation event decorator definitions.
*
* <p>Note that if you do not provide an explicit decoratorFactory, a
* default factory is utilized that uses service discovery.
*
* @param validationEventDecoratorFactory ValidationEventDecorator factory to use.
* @return Returns the assembler.
*/
public ModelAssembler validationEventDecoratorFactory(
ValidationEventDecoratorFactory validationEventDecoratorFactory
) {
this.validationEventDecoratorFactory = Objects.requireNonNull(validationEventDecoratorFactory);
return this;
}

/**
* Registers a validator to be used when validating the model.
*
Expand All @@ -209,6 +238,17 @@ public ModelAssembler addValidator(Validator validator) {
return this;
}

/**
* Registers a validation event decorator to be used when validating the model.
*
* @param decorator Decorator to register.
* @return Returns the assembler.
*/
public ModelAssembler addValidationEventDecorator(ValidationEventDecorator decorator) {
validationEventDecorators.add(Objects.requireNonNull(decorator));
return this;
}

/**
* Adds a string containing an unparsed model to the assembler.
*
Expand Down Expand Up @@ -509,6 +549,9 @@ public ValidatedResult<Model> assemble() {
if (traitFactory == null) {
traitFactory = LazyTraitFactoryHolder.INSTANCE;
}
if (validationEventDecoratorFactory == null) {
validationEventDecoratorFactory = LazyValidationEventDecoratorFactoryHolder.INSTANCE;
}

Model prelude = disablePrelude ? null : Prelude.getPreludeModel();
LoadOperationProcessor processor = new LoadOperationProcessor(
Expand Down Expand Up @@ -572,7 +615,7 @@ public ValidatedResult<Model> assemble() {
// If ERROR validation events occur while loading, then performing more
// granular semantic validation will only obscure the root cause of errors.
if (LoaderUtils.containsErrorEvents(events)) {
return returnOnlyErrors(transformed, events);
return returnOnlyErrors(transformed, events, resolveDecorators());
}

if (disableValidation) {
Expand All @@ -587,23 +630,36 @@ public ValidatedResult<Model> assemble() {
}
}

private List<ValidationEventDecorator> resolveDecorators() {
List<ValidationEventDecorator> resolvedDecorators =
new ArrayList<>(validationEventDecoratorFactory.loadDecorators());
resolvedDecorators.addAll(validationEventDecorators);
return resolvedDecorators;
}

private void addMetadataToProcessor(Map<String, Node> metadataMap, LoadOperationProcessor processor) {
for (Map.Entry<String, Node> entry : metadataMap.entrySet()) {
processor.accept(new LoadOperation.PutMetadata(Version.UNKNOWN, entry.getKey(), entry.getValue()));
}
}

private ValidatedResult<Model> returnOnlyErrors(Model model, List<ValidationEvent> events) {
return new ValidatedResult<>(model, events.stream()
.filter(event -> event.getSeverity() == Severity.ERROR)
.collect(Collectors.toList()));
private ValidatedResult<Model> returnOnlyErrors(
Model model,
List<ValidationEvent> events,
List<ValidationEventDecorator> decorators
) {
List<ValidationEvent> filteredEvents = events.stream()
.filter(event -> event.getSeverity() == Severity.ERROR)
.collect(Collectors.toList());
return new ValidatedResult<>(model, ModelValidator.decorateEvents(decorators, filteredEvents));
sugmanue marked this conversation as resolved.
Show resolved Hide resolved
}

private ValidatedResult<Model> validate(Model model, List<ValidationEvent> events) {
// Validate the model based on the explicit validators and model metadata.
// Note the ModelValidator handles emitting events to the validationEventListener.
List<ValidationEvent> mergedEvents = new ModelValidator()
.validators(validators)
.validationEventDecorators(resolveDecorators())
.validatorFactory(validatorFactory)
.eventListener(validationEventListener)
.includeEvents(events)
Expand Down
Loading