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

feat(python): render multiple signatures with @overload decorator #44

Merged
merged 3 commits into from
Jan 22, 2025
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
2 changes: 1 addition & 1 deletion packages/plugin/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@apify/docusaurus-plugin-typedoc-api",
"version": "4.3.9",
"version": "4.3.10",
"description": "Docusaurus plugin that provides source code API documentation powered by TypeDoc. ",
"keywords": [
"docusaurus",
Expand Down
135 changes: 84 additions & 51 deletions packages/plugin/src/plugin/python/transformation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import type {
TypeDocObject,
TypeDocType,
} from './types';
import { getGroupName, getOID, isHidden, projectUsesDocsGroupDecorator, sortChildren } from './utils';
import { getGroupName, getOID, isHidden, isOverload, projectUsesDocsGroupDecorator, sortChildren } from './utils';

interface TransformObjectOptions {
/**
Expand Down Expand Up @@ -139,6 +139,55 @@ export class DocspecTransformer {
}
}

private makeMethodSignature(docspecObject: DocspecObject, docstring: TypeDocDocstring): TypeDocObject['signatures'][number] {
return {
comment: docstring.text
? {
blockTags: docstring?.returns
? [{ content: [{ kind: 'text', text: docstring.returns }], tag: '@returns' }]
: undefined,
summary: [
{
kind: 'text',
text: docstring?.text,
},
],
}
: undefined,
flags: {},
id: getOID(),
kind: 4096,
kindString: 'Call signature',
modifiers: docspecObject.modifiers ?? [],
name: docspecObject.name,
parameters: docspecObject.args
?.filter((arg) => arg.name !== 'self' && arg.name !== 'cls')
.map((arg) => ({
comment: docstring.args?.[arg.name]
? {
summary: [
{
kind: 'text',
text: docstring.args[arg.name],
},
],
}
: undefined,
defaultValue: arg.default_value as string,
flags: {
isOptional: arg.datatype?.includes('Optional') || arg.default_value !== undefined,
'keyword-only': arg.type === 'KEYWORD_ONLY',
},
id: getOID(),
kind: 32_768,
kindString: 'Parameter',
name: arg.name,
type: this.pythonTypeResolver.registerType(arg.datatype),
})),
type: this.pythonTypeResolver.registerType(docspecObject.return_type),
};
}

/**
* Given a docspec object outputted by `pydoc-markdown`, transforms this object into the Typedoc structure,
* and appends it as a child of the `parentTypeDoc` Typedoc object (which serves as an accumulator for the recursion).
Expand Down Expand Up @@ -166,8 +215,16 @@ export class DocspecTransformer {

const { typedocType, typedocKind } = this.getTypedocType(currentDocspecNode, parentTypeDoc);
const { filePathInRepo } = this.getGitHubUrls(currentDocspecNode);
currentDocspecNode.parsedDocstring = this.parseDocstring(currentDocspecNode);

const isOverloadedMethod = typedocKind.kindString === 'Method' && isOverload(currentDocspecNode);

if (isOverloadedMethod) {
parentTypeDoc.overloads ??= [];
parentTypeDoc.overloads.push(currentDocspecNode);
return;
}

const docstring = this.parseDocstring(currentDocspecNode);
const currentId = getOID();

this.symbolIdMap[currentId] = {
Expand All @@ -189,12 +246,12 @@ export class DocspecTransformer {
const currentTypedocNode: TypeDocObject = {
...typedocKind,
children: [],
comment: docstring
comment: currentDocspecNode.parsedDocstring
? {
summary: [
{
kind: 'text',
text: docstring.text,
text: currentDocspecNode.parsedDocstring.text,
},
],
}
Expand All @@ -205,6 +262,7 @@ export class DocspecTransformer {
id: currentId,
module: moduleName, // This is an extension to the original Typedoc structure, to support showing where the member is exported from
name: currentDocspecNode.name,
parsedDocstring: currentDocspecNode.parsedDocstring,
sources: [
{
character: 1,
Expand All @@ -217,57 +275,12 @@ export class DocspecTransformer {

if (currentTypedocNode.kindString === 'Method') {
currentTypedocNode.signatures = [
{
comment: docstring.text
? {
blockTags: docstring?.returns
? [{ content: [{ kind: 'text', text: docstring.returns }], tag: '@returns' }]
: undefined,
summary: [
{
kind: 'text',
text: docstring?.text,
},
],
}
: undefined,
flags: {},
id: getOID(),
kind: 4096,
kindString: 'Call signature',
modifiers: currentDocspecNode.modifiers ?? [],
name: currentDocspecNode.name,
parameters: currentDocspecNode.args
?.filter((arg) => arg.name !== 'self' && arg.name !== 'cls')
.map((arg) => ({
comment: docstring.args?.[arg.name]
? {
summary: [
{
kind: 'text',
text: docstring.args[arg.name],
},
],
}
: undefined,
defaultValue: arg.default_value as string,
flags: {
isOptional: arg.datatype?.includes('Optional') || arg.default_value !== undefined,
'keyword-only': arg.type === 'KEYWORD_ONLY',
},
id: getOID(),
kind: 32_768,
kindString: 'Parameter',
name: arg.name,
type: this.pythonTypeResolver.registerType(arg.datatype),
})),
type: this.pythonTypeResolver.registerType(currentDocspecNode.return_type),
},
this.makeMethodSignature(currentDocspecNode, currentDocspecNode.parsedDocstring),
];
}

if (currentTypedocNode.kindString === 'Class') {
this.newContext(docstring);
this.newContext(currentDocspecNode.parsedDocstring);
}

for (const docspecMember of currentDocspecNode.members ?? []) {
Expand All @@ -289,6 +302,25 @@ export class DocspecTransformer {
}
}

for (const overload of currentTypedocNode.overloads ?? []) {
const baseMethod = currentTypedocNode.children?.find((child) => child.name === overload.name && child.kindString === 'Method' && child.decorations.every((d) => d.name !== 'overload'));

if (baseMethod) {
baseMethod.signatures?.push(
this.makeMethodSignature(
overload,
overload.parsedDocstring.text.length > 0 ?
overload.parsedDocstring :
baseMethod.parsedDocstring
),
);
} else {
console.warn(`Method ${overload.name} not found in class ${currentTypedocNode.name} (but overload ${overload.name} exists).`);
}
}

currentTypedocNode.overloads = undefined;

this.inheritanceGraph.registerNode(currentTypedocNode);
}

Expand All @@ -299,6 +331,7 @@ export class DocspecTransformer {
(!this.settings.useDocsGroup ||
groupSource === 'decorator' ||
parentTypeDoc.kindString !== 'Project')
&& !isOverloadedMethod
) {
const group = parentTypeDoc.groups?.find((g) => g.title === groupName);
if (group) {
Expand Down
3 changes: 3 additions & 0 deletions packages/plugin/src/plugin/python/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ export interface TypeDocObject {
extendedBy?: TypeDocType[];
modifiers?: any[];
parameters?: TypeDocObject[];
overloads?: DocspecObject[];
parsedDocstring?: TypeDocDocstring;
}

export interface DocspecObject {
Expand All @@ -56,6 +58,7 @@ export interface DocspecObject {
return_type?: DocspecType;
value?: any;
docstring?: { content: string };
parsedDocstring?: TypeDocDocstring;
modifiers?: DocspecType[];
args?: { name: string; type: DocspecType; default_value: any; datatype: DocspecType }[];
}
Expand Down
4 changes: 4 additions & 0 deletions packages/plugin/src/plugin/python/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,10 @@ export function isHidden(member: DocspecObject): boolean {
);
}

export function isOverload(member: DocspecObject): boolean {
return member.decorations?.some((d) => d.name === 'overload');
}

/**
* Comparator for enforcing the documentation groups order (examples of groups in {@link GROUP_ORDER}).
*
Expand Down
22 changes: 22 additions & 0 deletions playground/python/src/foo.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,27 @@ def bar_param(self, param):

print("bar", param)

@overload
def foo(self, param: str):
print("foo")

@overload
def foo(self, param: str, param2: int):
"""
Other signature of the foo method. Note that unlike in the first signature, the second parameter is required here

Args:
param: This is the first parameter of the overloaded foo method.
param2: This is the second parameter of the overloaded foo method.
"""
print("foo")

def foo(self, param: str, param2: int = 0, **kwargs: Unpack[FooFooArguments]):
"""This is the foo method of the Foo class.

Args:
param: This is the first parameter of the foo method.
param2: This is the second parameter of the foo method.
**kwargs: This is a dictionary of additional arguments.
"""
print("foo")
Loading