forked from apify/apify-client-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransformDocs.js
More file actions
380 lines (330 loc) · 13.9 KB
/
transformDocs.js
File metadata and controls
380 lines (330 loc) · 13.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
/* eslint-disable */
const fs = require('fs');
const { spawnSync } = require('child_process');
const moduleShortcuts = require('./module_shortcuts.json');
const REPO_ROOT_PLACEHOLDER = 'REPO_ROOT_PLACEHOLDER';
const APIFY_CLIENT_REPO_URL = 'https://github.com/apify/apify-client-python';
const APIFY_SDK_REPO_URL = 'https://github.com/apify/apify-sdk-python';
const APIFY_SHARED_REPO_URL = 'https://github.com/apify/apify-shared-python';
const REPO_URL_PER_PACKAGE = {
'apify': APIFY_SDK_REPO_URL,
'apify_client': APIFY_CLIENT_REPO_URL,
'apify_shared': APIFY_SHARED_REPO_URL,
};
// For each package, get the installed version, and set the tag to the corresponding version
const TAG_PER_PACKAGE = {};
for (const pkg of ['apify', 'apify_client', 'apify_shared']) {
const spawnResult = spawnSync('python', ['-c', `import ${pkg}; print(${pkg}.__version__)`]);
if (spawnResult.status === 0) {
TAG_PER_PACKAGE[pkg] = `v${spawnResult.stdout.toString().trim()}`;
}
}
// For the current package, set the tag to 'master'
const thisPackagePyprojectToml = fs.readFileSync('../pyproject.toml', 'utf8');
const thisPackageName = thisPackagePyprojectToml.match(/^name = "(.+)"$/m)[1];
TAG_PER_PACKAGE[thisPackageName] = 'master';
// Taken from https://github.com/TypeStrong/typedoc/blob/v0.23.24/src/lib/models/reflections/kind.ts, modified
const TYPEDOC_KINDS = {
'class': {
kind: 128,
kindString: 'Class',
},
'function': {
kind: 2048,
kindString: 'Method',
},
'data': {
kind: 1024,
kindString: 'Property',
},
'enum': {
kind: 8,
kindString: 'Enumeration',
},
'enumValue': {
kind: 16,
kindString: 'Enumeration Member',
},
}
const GROUP_ORDER = [
'Main Classes',
'Main Clients',
'Resource Clients',
'Async Resource Clients',
'Helper Classes',
'Errors',
'Constructors',
'Methods',
'Properties',
'Constants',
'Enumeration Members'
];
const groupSort = (g1, g2) => {
if(GROUP_ORDER.includes(g1) && GROUP_ORDER.includes(g2)){
return GROUP_ORDER.indexOf(g1) - GROUP_ORDER.indexOf(g2)
}
return g1.localeCompare(g2);
};
function getGroupName(object) {
const groupPredicates = {
'Errors': (x) => x.name.toLowerCase().includes('error'),
'Main Classes': (x) => ['Actor', 'Dataset', 'KeyValueStore', 'RequestQueue'].includes(x.name),
'Main Clients': (x) => ['ApifyClient', 'ApifyClientAsync'].includes(x.name),
'Async Resource Clients': (x) => x.name.toLowerCase().includes('async'),
'Resource Clients': (x) => x.kindString === 'Class' && x.name.toLowerCase().includes('client'),
'Helper Classes': (x) => x.kindString === 'Class',
'Methods': (x) => x.kindString === 'Method',
'Constructors': (x) => x.kindString === 'Constructor',
'Properties': (x) => x.kindString === 'Property',
'Constants': (x) => x.kindString === 'Enumeration',
'Enumeration Members': (x) => x.kindString === 'Enumeration Member',
};
const [group] = Object.entries(groupPredicates).find(
([_, predicate]) => predicate(object)
);
return group;
}
// Strips the Optional[] type from the type string, and replaces generic types with just the main type
function getBaseType(type) {
return type?.replace(/Optional\[(.*)\]/g, '$1').replace('ListPage[Dict]', 'ListPage');
}
// Returns whether a type is a custom class, or a primitive type
function isCustomClass(type) {
return !['dict', 'list', 'str', 'int', 'float', 'bool'].includes(type.toLowerCase());
}
// Infer the Typedoc type from the docspec type
function inferTypedocType(docspecType) {
const typeWithoutOptional = getBaseType(docspecType);
if (!typeWithoutOptional) {
return undefined;
}
// Typically, if a type is a custom class, it will be a reference in Typedoc
return isCustomClass(typeWithoutOptional) ? {
type: 'reference',
name: docspecType
} : {
type: 'intrinsic',
name: docspecType,
}
}
// Sorts the groups of a Typedoc member, and sorts the children of each group
function sortChildren(typedocMember) {
for (let group of typedocMember.groups) {
group.children
.sort((a, b) => {
const firstName = typedocMember.children.find(x => x.id === a).name;
const secondName = typedocMember.children.find(x => x.id === b).name;
return firstName.localeCompare(secondName);
});
}
typedocMember.groups.sort((a, b) => groupSort(a.title, b.title));
}
// Parses the arguments and return value description of a method from its docstring
function extractArgsAndReturns(docstring) {
const parameters = (docstring
.split('Args:')[1] ?? '').split('Returns:')[0] // Get the part between Args: and Returns:
.split(/(^|\n)\s*([\w]+)\s*\(.*?\)\s*:\s*/) // Magic regex which splits the arguments into an array, and removes the argument types
.filter(x => x.length > 1) // Remove empty strings
.reduce((acc, curr, idx, arr) => { // Collect the argument names and types into an object
if(idx % 2 === 0){
return {...acc, [curr]: arr[idx+1]} // If the index is even, the current string is an argument name, and the next string is its type
}
return acc;
}, {});
const returns = (docstring
.split('Returns:')[1] ?? '').split('Raises:')[0] // Get the part between Returns: and Raises:
.split(':')[1]?.trim() || undefined; // Split the return value into its type and description, return description
return { parameters, returns };
}
// Objects with decorators named 'ignore_docs' or with empty docstrings will be ignored
function isHidden(member) {
return member.decorations?.some(d => d.name === 'ignore_docs') || member.name === 'ignore_docs' || !member.docstring?.content;
}
// Each object in the Typedoc structure has an unique ID,
// we'll just increment it for each object we convert
let oid = 1;
// Converts a docspec object to a Typedoc object, including all its children
function convertObject(obj, parent, module) {
const rootModuleName = module.name.split('.')[0];
for (let member of obj.members ?? []) {
let typedocKind = TYPEDOC_KINDS[member.type];
if(member.bases?.includes('Enum')) {
typedocKind = TYPEDOC_KINDS['enum'];
}
if (member.decorations?.some(d => d.name === 'dualproperty')) {
typedocKind = TYPEDOC_KINDS['data'];
}
let typedocType = inferTypedocType(member.datatype);
if(parent.kindString === 'Enumeration') {
typedocKind = TYPEDOC_KINDS['enumValue'];
typedocType = {
type: 'literal',
value: member.value,
}
}
if(member.type in TYPEDOC_KINDS && !isHidden(member)) {
// Get the URL of the member in GitHub
const repoBaseUrl = `${REPO_URL_PER_PACKAGE[rootModuleName]}/blob/${TAG_PER_PACKAGE[rootModuleName]}`;
const filePathInRepo = member.location.filename.replace(REPO_ROOT_PLACEHOLDER, '');
const fileGitHubUrl = member.location.filename.replace(REPO_ROOT_PLACEHOLDER, repoBaseUrl);
const memberGitHubUrl = `${fileGitHubUrl}#L${member.location.lineno}`;
// Get the module name of the member, and check if it has a shortcut (reexport from an ancestor module)
const fullName = `${module.name}.${member.name}`;
let moduleName = module.name;
if (fullName in moduleShortcuts) {
moduleName = moduleShortcuts[fullName].replace(`.${member.name}`, '');
}
// Create the Typedoc member object
let typedocMember = {
id: oid++,
name: member.name,
module: moduleName, // This is an extension to the original Typedoc structure, to support showing where the member is exported from
...typedocKind,
flags: {},
comment: member.docstring ? {
summary: [{
kind: 'text',
text: member.docstring?.content,
}],
} : undefined,
type: typedocType,
children: [],
groups: [],
sources: [{
filename: filePathInRepo,
line: member.location.lineno,
character: 1,
url: memberGitHubUrl,
}],
};
if(typedocMember.kindString === 'Method') {
const { parameters, returns } = extractArgsAndReturns(member.docstring?.content ?? '');
typedocMember.signatures = [{
id: oid++,
name: member.name,
modifiers: member.modifiers ?? [],
kind: 4096,
kindString: 'Call signature',
flags: {},
comment: member.docstring ? {
summary: [{
kind: 'text',
text: member.docstring?.content
.replace(/\**(Args|Arguments|Returns)[\s\S]+/, ''),
}],
blockTags: returns ? [
{ tag: '@returns', content: [{ kind: 'text', text: returns }] },
] : undefined,
} : undefined,
type: inferTypedocType(member.return_type),
parameters: member.args.filter((arg) => (arg.name !== 'self' && arg.name !== 'cls')).map((arg) => ({
id: oid++,
name: arg.name,
kind: 32768,
kindString: 'Parameter',
flags: {
isOptional: arg.datatype?.includes('Optional') ? 'true' : undefined,
'keyword-only': arg.type === 'KEYWORD_ONLY' ? 'true' : undefined,
},
type: inferTypedocType(arg.datatype),
comment: parameters[arg.name] ? {
summary: [{
kind: 'text',
text: parameters[arg.name]
}]
} : undefined,
defaultValue: arg.default_value,
})),
}];
}
if(typedocMember.name === '__init__') {
typedocMember.kind = 512;
typedocMember.kindString = 'Constructor';
}
convertObject(member, typedocMember, module);
const groupName = getGroupName(typedocMember);
const group = parent.groups.find((g) => g.title === groupName);
if (group) {
group.children.push(typedocMember.id);
} else {
parent.groups.push({
title: groupName,
children: [typedocMember.id],
});
}
sortChildren(typedocMember);
parent.children.push(typedocMember);
}
}
}
function main() {
// Root object of the Typedoc structure
const typedocApiReference = {
'id': 0,
'name': 'apify-client',
'kind': 1,
'kindString': 'Project',
'flags': {},
'originalName': '',
'children': [],
'groups': [],
'sources': [
{
'fileName': 'src/index.ts',
'line': 1,
'character': 0,
'url': `http://example.com/blob/123456/src/dummy.py`,
}
]
};
// Load the docspec dump files of this module and of apify-shared
const thisPackageDocspecDump = fs.readFileSync('docspec-dump.jsonl', 'utf8');
const thisPackageModules = thisPackageDocspecDump.split('\n').filter((line) => line !== '');
const apifySharedDocspecDump = fs.readFileSync('apify-shared-docspec-dump.jsonl', 'utf8');
const apifySharedModules = apifySharedDocspecDump.split('\n').filter((line) => line !== '');
// Convert all the modules, store them in the root object
for (const module of [...thisPackageModules, ...apifySharedModules]) {
const parsedModule = JSON.parse(module);
convertObject(parsedModule, typedocApiReference, parsedModule);
};
// Recursively fix references (collect names->ids of all the named entities and then inject those in the reference objects)
const namesToIds = {};
function collectIds(obj) {
for (const child of obj.children ?? []) {
namesToIds[child.name] = child.id;
collectIds(child);
}
}
collectIds(typedocApiReference);
function fixRefs(obj) {
for (const child of obj.children ?? []) {
if (child.type?.type === 'reference') {
child.type.id = namesToIds[child.type.name];
}
if (child.signatures) {
for (const sig of child.signatures) {
for (const param of sig.parameters ?? []) {
if (param.type?.type === 'reference') {
param.type.id = namesToIds[param.type.name];
}
}
if (sig.type?.type === 'reference') {
sig.type.id = namesToIds[sig.type.name];
}
}
}
fixRefs(child);
}
}
fixRefs(typedocApiReference);
// Sort the children of the root object
sortChildren(typedocApiReference);
// Write the Typedoc structure to the output file
fs.writeFileSync('./api-typedoc-generated.json', JSON.stringify(typedocApiReference, null, 4));
}
if (require.main === module) {
main();
}
module.exports = {
groupSort,
}