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

Adding support for autorest for loading example files from nested sub-folders. #1627

Merged
merged 5 commits into from
Sep 30, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
7 changes: 7 additions & 0 deletions .chronus/changes/azhang_NestedExamples-2024-8-27-21-2-20.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
changeKind: feature
packages:
- "@azure-tools/typespec-autorest"
---

Adding support for loading example files from nested sub-folders.
18 changes: 18 additions & 0 deletions packages/samples/specs/misc/x-ms-examples/nested/main.tsp
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import "@typespec/http";

using Http;

@service
namespace XmsExamples;

model Pet {
name: string;
age: int32;
}

interface Pets {
// This operation should automatically get the ./examples/read.json file connected in x-ms-examples
read(): Pet;
// This operation should automatically get the ./examples/write.json file connected in x-ms-examples
write(@body pet: Pet): void;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
emit:
- "@azure-tools/typespec-autorest"
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"title": "Read pet",
"operationId": "Pets_Read",
"description": "Read pet example",
"parameters": {},
"responses": {
"200": {
"body": {
"name": "Rex",
"age": 3
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"title": "Write pet",
"operationId": "Pets_Write",
"description": "Read pet example",
"parameters": {
"body": {
"name": "Rex",
"age": 3
}
},
"responses": {
"200": {}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"title": "Read pet",
"operationId": "Pets_Read",
"description": "Read pet example",
"parameters": {},
"responses": {
"200": {
"body": {
"name": "Rex",
"age": 3
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"title": "Write pet",
"operationId": "Pets_Write",
"description": "Read pet example",
"parameters": {
"body": {
"name": "Rex",
"age": 3
}
},
"responses": {
"200": {}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
{
"swagger": "2.0",
"info": {
"title": "(title)",
"version": "0000-00-00",
"x-typespec-generated": [
{
"emitter": "@azure-tools/typespec-autorest"
}
]
},
"schemes": [
"https"
],
"produces": [
"application/json"
],
"consumes": [
"application/json"
],
"tags": [],
"paths": {
"/": {
"get": {
"operationId": "Pets_Read",
"parameters": [],
"responses": {
"200": {
"description": "The request has succeeded.",
"schema": {
"$ref": "#/definitions/Pet"
}
}
},
"x-ms-examples": {
"Read pet": {
"$ref": "./examples/read/read.json"
}
}
},
"post": {
"operationId": "Pets_Write",
"parameters": [
{
"name": "pet",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/Pet"
}
}
],
"responses": {
"204": {
"description": "There is no content to send for this request, but the headers may be useful. "
}
},
"x-ms-examples": {
"Write pet": {
"$ref": "./examples/write/write.json"
}
}
}
}
},
"definitions": {
"Pet": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"age": {
"type": "integer",
"format": "int32"
}
},
"required": [
"name",
"age"
]
}
},
"parameters": {}
}
32 changes: 31 additions & 1 deletion packages/typespec-autorest/src/openapi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ import {
createDiagnosticCollector,
explainStringTemplateNotSerializable,
getAllTags,
getAnyExtensionFromPath,
getDirectoryPath,
getDiscriminator,
getDoc,
Expand Down Expand Up @@ -87,7 +88,9 @@ import {
isTemplateDeclaration,
isTemplateDeclarationOrInstance,
isVoidType,
joinPaths,
navigateTypesInNamespace,
normalizePath,
reportDeprecated,
resolveEncodedName,
resolvePath,
Expand Down Expand Up @@ -2554,6 +2557,33 @@ async function checkExamplesDirExists(host: CompilerHost, dir: string) {
}
}

async function searchExampleJsonFiles(program: Program, exampleDir: string): Promise<string[]> {
const host = program.host;
const exampleFiles: string[] = [];

// Recursive file search
async function recursiveSearch(dir: string): Promise<void> {
const fileItems = await host.readDir(dir);

for (const item of fileItems) {
const fullPath = joinPaths(dir, item);
const relativePath = getRelativePathFromDirectory(exampleDir, fullPath, false);

if ((await host.stat(fullPath)).isDirectory()) {
await recursiveSearch(fullPath);
} else if (
(await host.stat(fullPath)).isFile() &&
getAnyExtensionFromPath(item) === ".json"
) {
exampleFiles.push(normalizePath(relativePath));
}
}
}

await recursiveSearch(exampleDir);
return exampleFiles;
}

async function loadExamples(
program: Program,
options: AutorestDocumentEmitterOptions,
Expand All @@ -2579,7 +2609,7 @@ async function loadExamples(
}

const map = new Map<string, Record<string, LoadedExample>>();
const exampleFiles = await host.readDir(exampleDir);
const exampleFiles = await searchExampleJsonFiles(program, exampleDir);
for (const fileName of exampleFiles) {
try {
const exampleFile = await host.readFile(resolvePath(exampleDir, fileName));
Expand Down
34 changes: 34 additions & 0 deletions packages/typespec-autorest/test/x-ms-examples.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,21 @@ describe("explicit example", () => {
expect(host.fs.has(resolveVirtualPath("./tsp-output/examples/getPet.json"))).toBe(true);
});

it("read nested examples from {project-root}/examples", async () => {
addExampleFile("./examples/pets/getPet.json", { operationId: "Pets_get", title: "Get a pet" });

const openapi = await compileOpenAPI(`@operationId("Pets_get") op read(): void;`, {
host,
});

deepStrictEqual(openapi.paths["/"]?.get?.["x-ms-examples"], {
"Get a pet": {
$ref: "./examples/pets/getPet.json",
},
});
expect(host.fs.has(resolveVirtualPath("./tsp-output/examples/pets/getPet.json"))).toBe(true);
});

it("read examples from examples-dir", async () => {
addExampleFile("./my-examples/getPet.json", { operationId: "Pets_get", title: "Get a pet" });

Expand All @@ -169,6 +184,25 @@ describe("explicit example", () => {
expect(host.fs.has(resolveVirtualPath("./tsp-output/examples/getPet.json"))).toBe(true);
});

it("read nested examples from examples-dir", async () => {
addExampleFile("./my-examples/pets/getPet.json", {
operationId: "Pets_get",
title: "Get a pet",
});

const openapi = await compileOpenAPI(`@operationId("Pets_get") op read(): void;`, {
host,
options: { "examples-dir": resolveVirtualPath("./my-examples") },
});

deepStrictEqual(openapi.paths["/"]?.get?.["x-ms-examples"], {
"Get a pet": {
$ref: "./examples/pets/getPet.json",
},
});
expect(host.fs.has(resolveVirtualPath("./tsp-output/examples/pets/getPet.json"))).toBe(true);
});

it("emit diagnostic when example files use same operation id", async () => {
const runner = await createAutorestTestRunner(host, {
"examples-dir": resolveVirtualPath("./examples"),
Expand Down
Loading