-
Notifications
You must be signed in to change notification settings - Fork 371
feat: [python] add api.md generation support #10854
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
Draft
iscai-msft
wants to merge
5
commits into
microsoft:main
Choose a base branch
from
iscai-msft:feat/python-api-md
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+352
−1
Draft
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
817d1a1
feat: add api.md generation support to Python emitter
06519bc
Merge remote-tracking branch 'upstream/main' into feat/python-api-md
ea96ce0
fix: address PR review comments for api.md generation
d7812da
feat: enable generate-api-md by default
c2fb2f9
feat: install apiview-stub-generator in prepare.py
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| --- | ||
| changeKind: feature | ||
| packages: | ||
| - "@typespec/http-client-python" | ||
| --- | ||
|
|
||
| Add `generate-api-md` emitter option to generate an `api.md` file containing the public API surface. When enabled, the emitter runs `apiview-stub-generator` to produce a token JSON file and converts it to markdown. Requires `apiview-stub-generator` to be installed in the Python environment. | ||
|
|
||
| ```yaml | ||
| # tspconfig.yaml | ||
| options: | ||
| "@typespec/http-client-python": | ||
| generate-api-md: true | ||
| ``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
148 changes: 148 additions & 0 deletions
148
packages/http-client-python/emitter/test/emitter.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,148 @@ | ||
| import { ok, strictEqual } from "assert"; | ||
| import { execFileSync } from "child_process"; | ||
| import fs from "fs"; | ||
| import os from "os"; | ||
| import path from "path"; | ||
| import { afterEach, beforeEach, describe, it } from "vitest"; | ||
|
|
||
| describe("export_apiview_markdown.py", () => { | ||
| const root = path.resolve(import.meta.dirname, "../.."); | ||
| const scriptPath = path.join(root, "eng/scripts/setup/export_apiview_markdown.py"); | ||
| let tmpDir: string; | ||
|
|
||
| beforeEach(() => { | ||
| tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "apimd-test-")); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| fs.rmSync(tmpDir, { recursive: true, force: true }); | ||
| }); | ||
|
|
||
| function writeTokenJson(data: object): string { | ||
| const tokenPath = path.join(tmpDir, "token.json"); | ||
| fs.writeFileSync(tokenPath, JSON.stringify(data)); | ||
| return tokenPath; | ||
| } | ||
|
|
||
| it("generates api.md from a simple token file", () => { | ||
| const tokenPath = writeTokenJson({ | ||
| Language: "Python", | ||
| ReviewLines: [ | ||
| { | ||
| Tokens: [ | ||
| { Value: "class", HasSuffixSpace: true }, | ||
| { Value: "MyClient", HasPrefixSpace: false }, | ||
| ], | ||
| }, | ||
| { | ||
| Tokens: [ | ||
| { Value: "def", HasSuffixSpace: true }, | ||
| { Value: "send(self)", HasPrefixSpace: false }, | ||
| ], | ||
| Children: [ | ||
| { | ||
| Tokens: [{ Value: "..." }], | ||
| }, | ||
| ], | ||
| }, | ||
| ], | ||
| }); | ||
|
|
||
| const outDir = path.join(tmpDir, "output"); | ||
| fs.mkdirSync(outDir); | ||
| execFileSync("python3", [scriptPath, tokenPath, outDir]); | ||
|
|
||
| const apiMd = fs.readFileSync(path.join(outDir, "api.md"), "utf-8"); | ||
| ok(apiMd.startsWith("```py"), "Should start with python code fence"); | ||
| ok(apiMd.includes("class"), "Should contain class token"); | ||
| ok(apiMd.includes("MyClient"), "Should contain MyClient token"); | ||
| ok(apiMd.endsWith("```"), "Should end with code fence"); | ||
| }); | ||
|
|
||
| it("writes api.md directly when output path is a .md file", () => { | ||
| const tokenPath = writeTokenJson({ | ||
| Language: "Python", | ||
| ReviewLines: [{ Tokens: [{ Value: "class Foo" }] }], | ||
| }); | ||
|
|
||
| const outFile = path.join(tmpDir, "custom.md"); | ||
| execFileSync("python3", [scriptPath, tokenPath, outFile]); | ||
| ok(fs.existsSync(outFile), "Should write to the specified .md file"); | ||
| const content = fs.readFileSync(outFile, "utf-8"); | ||
| ok(content.includes("class Foo")); | ||
| }); | ||
|
|
||
| it("exits with error for empty ReviewLines", () => { | ||
| const tokenPath = writeTokenJson({ | ||
| Language: "Python", | ||
| ReviewLines: [], | ||
| }); | ||
|
|
||
| const outDir = path.join(tmpDir, "output"); | ||
| fs.mkdirSync(outDir); | ||
| // Empty ReviewLines is treated as missing by the script | ||
| let threw = false; | ||
| try { | ||
| execFileSync("python3", [scriptPath, tokenPath, outDir], { stdio: "pipe" }); | ||
| } catch { | ||
| threw = true; | ||
| } | ||
| ok(threw, "Should exit with error for empty ReviewLines"); | ||
| }); | ||
|
|
||
| it("resolves language aliases correctly", () => { | ||
| const tokenPath = writeTokenJson({ | ||
| Language: "JavaScript", | ||
| ReviewLines: [{ Tokens: [{ Value: "function foo() {}" }] }], | ||
| }); | ||
|
|
||
| const outDir = path.join(tmpDir, "output"); | ||
| fs.mkdirSync(outDir); | ||
| execFileSync("python3", [scriptPath, tokenPath, outDir]); | ||
|
|
||
| const apiMd = fs.readFileSync(path.join(outDir, "api.md"), "utf-8"); | ||
| ok(apiMd.startsWith("```js"), "Should use 'js' alias for JavaScript"); | ||
| }); | ||
|
|
||
| it("renders nested children with indentation", () => { | ||
| const tokenPath = writeTokenJson({ | ||
| Language: "Python", | ||
| ReviewLines: [ | ||
| { | ||
| Tokens: [{ Value: "class Foo:" }], | ||
| Children: [ | ||
| { | ||
| Tokens: [{ Value: "def bar(self):" }], | ||
| Children: [{ Tokens: [{ Value: "pass" }] }], | ||
| }, | ||
| ], | ||
| }, | ||
| ], | ||
| }); | ||
|
|
||
| const outDir = path.join(tmpDir, "output"); | ||
| fs.mkdirSync(outDir); | ||
| execFileSync("python3", [scriptPath, tokenPath, outDir]); | ||
|
|
||
| const apiMd = fs.readFileSync(path.join(outDir, "api.md"), "utf-8"); | ||
| const lines = apiMd.split("\n"); | ||
| // Children should be indented | ||
| ok( | ||
| lines.some((l: string) => l.startsWith(" ") && l.includes("def bar")), | ||
| "First-level children should have 4-space indent", | ||
| ); | ||
| ok( | ||
| lines.some((l: string) => l.startsWith(" ") && l.includes("pass")), | ||
| "Second-level children should have 8-space indent", | ||
| ); | ||
| }); | ||
| }); | ||
|
|
||
| describe("generateApiMd token file lookup", () => { | ||
| it("expected token filename follows {package_name}_python.json pattern", () => { | ||
| // Verify the naming convention used by apistubgen | ||
| const packageName = "azure-ai-inference"; | ||
| const expectedFilename = `${packageName}_python.json`; | ||
| strictEqual(expectedFilename, "azure-ai-inference_python.json"); | ||
| }); | ||
| }); |
101 changes: 101 additions & 0 deletions
101
packages/http-client-python/eng/scripts/setup/export_apiview_markdown.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,101 @@ | ||
| #!/usr/bin/env python | ||
| # ------------------------------------------------------------------------- | ||
| # Copyright (c) Microsoft Corporation. All rights reserved. | ||
| # Licensed under the MIT License. See License.txt in the project root for | ||
| # license information. | ||
| # -------------------------------------------------------------------------- | ||
| """Convert an APIView token JSON file to a markdown file. | ||
| This is a Python port of Export-APIViewMarkdown.ps1 from azure-sdk-tools, | ||
| so that api.md generation does not require PowerShell to be installed. | ||
| """ | ||
|
|
||
| import json | ||
| import os | ||
| import sys | ||
|
|
||
|
|
||
| LANGUAGE_ALIASES = { | ||
| "python": "py", | ||
| "javascript": "js", | ||
| "typescript": "ts", | ||
| } | ||
|
|
||
|
|
||
| def render_token(token): | ||
| prefix = " " if token.get("HasPrefixSpace") else "" | ||
| suffix = " " if token.get("HasSuffixSpace") else "" | ||
| return f"{prefix}{token.get('Value', '')}{suffix}" | ||
|
|
||
|
|
||
| def render_review_lines(review_lines, indent_level=0): | ||
| result = [] | ||
| indent = " " * indent_level | ||
|
|
||
| for line in review_lines: | ||
| tokens = line.get("Tokens", []) | ||
| if not tokens: | ||
| result.append("") | ||
| else: | ||
| line_text = "".join(render_token(t) for t in tokens) | ||
| if line_text.strip(): | ||
| result.append(f"{indent}{line_text}") | ||
| else: | ||
| result.append("") | ||
|
|
||
| children = line.get("Children") | ||
| if children: | ||
| child_lines = render_review_lines(children, indent_level + 1) | ||
| result.extend(child_lines) | ||
|
|
||
| return result | ||
|
|
||
|
|
||
| def main(): | ||
| if len(sys.argv) < 3: | ||
| print("Usage: export_apiview_markdown.py <token_json_path> <output_path>", file=sys.stderr) | ||
| sys.exit(1) | ||
|
|
||
| token_json_path = sys.argv[1] | ||
| output_path = sys.argv[2] | ||
|
|
||
| if not os.path.exists(token_json_path): | ||
| print(f"Token JSON file not found: {token_json_path}", file=sys.stderr) | ||
| sys.exit(1) | ||
|
|
||
| with open(token_json_path, "r", encoding="utf-8") as f: | ||
| token_json = json.load(f) | ||
|
|
||
| review_lines = token_json.get("ReviewLines") | ||
| if not review_lines: | ||
| print("The token JSON file does not contain a 'ReviewLines' property.", file=sys.stderr) | ||
| sys.exit(1) | ||
|
|
||
| # Resolve output path | ||
| if os.path.isdir(output_path): | ||
| output_path = os.path.join(output_path, "api.md") | ||
| elif not os.path.splitext(output_path)[1]: | ||
| output_path = os.path.join(output_path, "api.md") | ||
|
|
||
| # Get language for code fence | ||
| language = (token_json.get("Language") or "").lower() | ||
| language = LANGUAGE_ALIASES.get(language, language) | ||
|
|
||
| rendered_lines = render_review_lines(review_lines) | ||
|
|
||
| output_lines = [f"```{language}"] | ||
| output_lines.extend(rendered_lines) | ||
| output_lines.append("```") | ||
|
|
||
| output_dir = os.path.dirname(output_path) | ||
| if output_dir and not os.path.exists(output_dir): | ||
| os.makedirs(output_dir, exist_ok=True) | ||
|
|
||
| with open(output_path, "w", encoding="utf-8", newline="\n") as f: | ||
| f.write("\n".join(output_lines)) | ||
|
|
||
| print(f"Generated markdown: {output_path}") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Better to add test cases for the new option.