Skip to content

Commit

Permalink
Format smithy-docgen
Browse files Browse the repository at this point in the history
  • Loading branch information
haydenbaker committed Dec 18, 2024
1 parent 8c7a647 commit 733426a
Show file tree
Hide file tree
Showing 90 changed files with 267 additions and 373 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/

package software.amazon.smithy.docgen;

import software.amazon.smithy.codegen.core.SymbolProvider;
Expand Down Expand Up @@ -41,12 +40,11 @@ public SymbolProvider createSymbolProvider(CreateSymbolProviderDirective<DocSett
@Override
public DocGenerationContext createContext(CreateContextDirective<DocSettings, DocIntegration> directive) {
return new DocGenerationContext(
directive.model(),
directive.settings(),
directive.symbolProvider(),
directive.fileManifest(),
directive.integrations()
);
directive.model(),
directive.settings(),
directive.symbolProvider(),
directive.fileManifest(),
directive.integrations());
}

@Override
Expand Down Expand Up @@ -86,8 +84,10 @@ public void generateEnumShape(GenerateEnumDirective<DocGenerationContext, DocSet
@Override
public void generateIntEnumShape(GenerateIntEnumDirective<DocGenerationContext, DocSettings> directive) {
var shape = directive.shape();
var intEnum = shape.asIntEnumShape().orElseThrow(() -> new ExpectationNotMetException(
"Expected an intEnum shape, but found " + shape, shape));
var intEnum = shape.asIntEnumShape()
.orElseThrow(() -> new ExpectationNotMetException(
"Expected an intEnum shape, but found " + shape,
shape));
new StructuredShapeGenerator(directive.context()).accept(intEnum, MemberListingType.OPTIONS);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/

package software.amazon.smithy.docgen;

import software.amazon.smithy.codegen.core.SymbolWriter;
Expand All @@ -23,5 +22,4 @@
* format.
*/
@SmithyUnstableApi
public record DocFormat(String name, String extension, SymbolWriter.Factory<DocWriter> writerFactory) {
}
public record DocFormat(String name, String extension, SymbolWriter.Factory<DocWriter> writerFactory) {}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/

package software.amazon.smithy.docgen;

import java.util.LinkedHashSet;
Expand Down Expand Up @@ -66,9 +65,9 @@ public DocGenerationContext(
}
if (resolvedFormat == null) {
throw new CodegenException(String.format(
"Unknown doc format `%s`. You may be missing a dependency. Currently available formats: [%s]",
docSettings.format(), String.join(", ", availableFormats)
));
"Unknown doc format `%s`. You may be missing a dependency. Currently available formats: [%s]",
docSettings.format(),
String.join(", ", availableFormats)));
}

this.docFormat = resolvedFormat;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/

package software.amazon.smithy.docgen;

import java.util.List;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/

package software.amazon.smithy.docgen;

import java.util.Map;
Expand Down Expand Up @@ -45,15 +44,17 @@ public record DocSettings(ShapeId service, String format, Map<ShapeId, String> r
* @return loaded settings based on the given node.
*/
public static DocSettings fromNode(ObjectNode pluginSettings) {
var references = pluginSettings.getObjectMember("references").orElse(ObjectNode.objectNode())
.getMembers().entrySet().stream()
var references = pluginSettings.getObjectMember("references")
.orElse(ObjectNode.objectNode())
.getMembers()
.entrySet()
.stream()
.collect(Collectors.toMap(
e -> ShapeId.from(e.getKey().getValue()),
e -> e.getValue().expectStringNode().getValue()));
return new DocSettings(
pluginSettings.expectStringMember("service").expectShapeId(),
pluginSettings.getStringMemberOrDefault("format", "sphinx-markdown"),
references
);
references);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/

package software.amazon.smithy.docgen;

import static java.lang.String.format;
Expand Down Expand Up @@ -180,8 +179,8 @@ public Symbol toSymbol(Shape shape) {
@Override
public Symbol serviceShape(ServiceShape shape) {
return getSymbolBuilder(shape)
.definitionFile(getDefinitionFile(SERVICE_FILE))
.build();
.definitionFile(getDefinitionFile(SERVICE_FILE))
.build();
}

@Override
Expand Down Expand Up @@ -277,8 +276,8 @@ private String getDefinitionFile(String path) {
private String getShapeName(ServiceShape serviceShape, Shape shape) {
if (shape.isServiceShape()) {
return shape.getTrait(TitleTrait.class)
.map(StringTrait::getValue)
.orElse(shape.getId().getName());
.map(StringTrait::getValue)
.orElse(shape.getId().getName());
}
if (shape.isMemberShape()) {
return toMemberName(shape.asMemberShape().get());
Expand Down Expand Up @@ -326,9 +325,9 @@ public Symbol toSymbol(Shape shape) {
return symbol;
}
return symbol.toBuilder()
.definitionFile(addExtension(symbol.getDefinitionFile()))
.declarationFile(addExtension(symbol.getDeclarationFile()))
.build();
.definitionFile(addExtension(symbol.getDefinitionFile()))
.declarationFile(addExtension(symbol.getDeclarationFile()))
.build();
}

private String addExtension(String path) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/

package software.amazon.smithy.docgen;

import static java.lang.String.format;
Expand Down Expand Up @@ -48,9 +47,9 @@ private DocgenUtils() {}
public static String runCommand(String command, Path directory) {
String[] finalizedCommand;
if (System.getProperty("os.name").toLowerCase().startsWith("windows")) {
finalizedCommand = new String[]{"cmd.exe", "/c", command};
finalizedCommand = new String[] {"cmd.exe", "/c", command};
} else {
finalizedCommand = new String[]{"sh", "-c", command};
finalizedCommand = new String[] {"sh", "-c", command};
}

ProcessBuilder processBuilder = new ProcessBuilder(finalizedCommand)
Expand All @@ -63,7 +62,8 @@ public static String runCommand(String command, Path directory) {

// Capture output for reporting.
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
process.getInputStream(), Charset.defaultCharset()))) {
process.getInputStream(),
Charset.defaultCharset()))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
LOGGER.finest(line);
Expand All @@ -77,7 +77,9 @@ public static String runCommand(String command, Path directory) {
String joinedOutput = String.join(System.lineSeparator(), output);
if (process.exitValue() != 0) {
throw new CodegenException(format(
"Command `%s` failed with output:%n%n%s", command, joinedOutput));
"Command `%s` failed with output:%n%n%s",
command,
joinedOutput));
}
return joinedOutput;
} catch (InterruptedException | IOException e) {
Expand Down Expand Up @@ -115,8 +117,9 @@ public static Optional<String> getSymbolLink(Symbol symbol, Path relativeTo) {
return Optional.empty();
}
return Optional.of(format(
"./%s#%s", relativeToParent.relativize(Paths.get(symbol.getDefinitionFile())), linkId.get()
));
"./%s#%s",
relativeToParent.relativize(Paths.get(symbol.getDefinitionFile())),
linkId.get()));
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,8 @@
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/

package software.amazon.smithy.docgen;


import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
Expand Down Expand Up @@ -39,8 +37,7 @@ public String getName() {
@Override
public void execute(PluginContext pluginContext) {
LOGGER.fine("Beginning documentation generation.");
CodegenDirector<DocWriter, DocIntegration, DocGenerationContext, DocSettings> runner
= new CodegenDirector<>();
CodegenDirector<DocWriter, DocIntegration, DocGenerationContext, DocSettings> runner = new CodegenDirector<>();

runner.directedCodegen(new DirectedDocGen());
runner.integrationClass(DocIntegration.class);
Expand All @@ -59,7 +56,8 @@ private ValidatedResult<Model> getValidatedModel(Model model) {

// This will discover and apply suppressions from the model.
Optional<ValidationEventDecorator> modelDecorator = new ModelBasedEventDecorator()
.createDecorator(model).getResult();
.createDecorator(model)
.getResult();
if (modelDecorator.isPresent()) {
eventDecorator = ValidationEventDecorator.compose(List.of(modelDecorator.get(), eventDecorator));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/

package software.amazon.smithy.docgen.generators;

import java.util.List;
Expand Down Expand Up @@ -50,7 +49,8 @@ static void generateOperationListing(
return;
}

var parentLinkId = context.symbolProvider().toSymbol(shape)
var parentLinkId = context.symbolProvider()
.toSymbol(shape)
.expectProperty(DocSymbolProvider.LINK_ID_PROPERTY, String.class);
writer.openHeading("Operations", parentLinkId + "-operations");
writer.openList(ListType.UNORDERED);
Expand Down Expand Up @@ -79,7 +79,8 @@ static void generateResourceListing(
return;
}

var parentLinkId = context.symbolProvider().toSymbol(shape)
var parentLinkId = context.symbolProvider()
.toSymbol(shape)
.expectProperty(DocSymbolProvider.LINK_ID_PROPERTY, String.class);
var heading = shape.isServiceShape() ? "Resources" : "Sub-Resources";
writer.openHeading(heading, parentLinkId + "-" + heading.toLowerCase(Locale.ENGLISH));
Expand Down Expand Up @@ -141,8 +142,9 @@ private static void writeProtocolSection(
AtomicReference<String> tabContents = new AtomicReference<>();
var tab = capture(writer, tabWriter -> {
tabWriter.openTab(protocolSymbol.getName());
tabContents.set(capture(tabWriter, w2 -> tabWriter.injectSection(
new ProtocolSection(context, shape, protocol))));
tabContents.set(capture(tabWriter,
w2 -> tabWriter.injectSection(
new ProtocolSection(context, shape, protocol))));
tabWriter.closeTab();
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/

package software.amazon.smithy.docgen.generators;

import java.util.Collection;
Expand Down Expand Up @@ -141,10 +140,12 @@ private Collection<MemberShape> getMembers() {
return switch (listingType) {
case INPUT -> context.model()
.expectShape(shape.asOperationShape().get().getInputShape())
.getAllMembers().values();
.getAllMembers()
.values();
case OUTPUT -> context.model()
.expectShape(shape.asOperationShape().get().getOutputShape())
.getAllMembers().values();
.getAllMembers()
.values();
case RESOURCE_IDENTIFIERS -> synthesizeResourceMembers(shape.asResourceShape().get().getIdentifiers());
case RESOURCE_PROPERTIES -> synthesizeResourceMembers(shape.asResourceShape().get().getProperties());
default -> shape.getAllMembers().values();
Expand All @@ -154,7 +155,8 @@ private Collection<MemberShape> getMembers() {
// Resource identifiers and properties aren't actually members, but they're close
// enough that we can treat them like they are for the purposes of the doc generator.
private List<MemberShape> synthesizeResourceMembers(Map<String, ShapeId> properties) {
return properties.entrySet().stream()
return properties.entrySet()
.stream()
.map(entry -> MemberShape.builder()
.id(shape.getId().withMember(entry.getKey()))
.target(entry.getValue())
Expand Down Expand Up @@ -236,7 +238,9 @@ private static class MemberTypeVisitor extends ShapeVisitor.Default<Void> {
@Override
protected Void getDefault(Shape shape) {
throw new CodegenException(String.format(
"Unexpected member %s of type %s", shape.getId(), shape.getType()));
"Unexpected member %s of type %s",
shape.getId(),
shape.getType()));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/

package software.amazon.smithy.docgen.generators;

import java.util.List;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/

package software.amazon.smithy.docgen.generators;

import java.util.HashSet;
Expand Down Expand Up @@ -116,7 +115,9 @@ public void accept(DocGenerationContext context, ResourceShape resource) {
new MemberGenerator(context, writer, resource, MemberListingType.RESOURCE_IDENTIFIERS).run();
new MemberGenerator(context, writer, resource, MemberListingType.RESOURCE_PROPERTIES).run();

var subResources = resource.getResources().stream().sorted()
var subResources = resource.getResources()
.stream()
.sorted()
.map(id -> context.model().expectShape(id, ResourceShape.class))
.toList();
GeneratorUtils.generateResourceListing(context, writer, resource, subResources);
Expand All @@ -125,7 +126,8 @@ public void accept(DocGenerationContext context, ResourceShape resource) {

var operationIds = new HashSet<>(resource.getOperations());
operationIds.addAll(resource.getCollectionOperations());
var operations = operationIds.stream().sorted()
var operations = operationIds.stream()
.sorted()
.map(id -> context.model().expectShape(id, OperationShape.class))
.toList();
GeneratorUtils.generateOperationListing(context, writer, resource, operations);
Expand All @@ -141,7 +143,8 @@ private void generateLifecycleDocs(DocGenerationContext context, DocWriter write
writer.popState();
return;
}
var linkId = context.symbolProvider().toSymbol(resource)
var linkId = context.symbolProvider()
.toSymbol(resource)
.expectProperty(DocSymbolProvider.LINK_ID_PROPERTY, String.class);
writer.openHeading("Lifecycle Operations", linkId + "-lifecycle-operations");
writer.openDefinitionList();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/

package software.amazon.smithy.docgen.generators;

import java.util.function.Consumer;
Expand Down Expand Up @@ -122,8 +121,9 @@ private void writeAuthSection(DocGenerationContext context, DocWriter writer, Se
writer.openHeading("Auth");

var index = ServiceIndex.of(context.model());
writer.putContext("optional", index.getEffectiveAuthSchemes(service, AuthSchemeMode.NO_AUTH_AWARE)
.containsKey(NoAuthTrait.ID));
writer.putContext("optional",
index.getEffectiveAuthSchemes(service, AuthSchemeMode.NO_AUTH_AWARE)
.containsKey(NoAuthTrait.ID));
writer.putContext("multipleSchemes", authSchemes.size() > 1);
writer.write("""
Operations on the service ${?optional}may optionally${/optional}${^optional}MUST${/optional} \
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/

package software.amazon.smithy.docgen.generators;

import java.util.function.BiConsumer;
Expand Down
Loading

0 comments on commit 733426a

Please sign in to comment.