-
-
Notifications
You must be signed in to change notification settings - Fork 166
Expand file tree
/
Copy pathdocstring_factory.ts
More file actions
89 lines (71 loc) · 2.54 KB
/
docstring_factory.ts
File metadata and controls
89 lines (71 loc) · 2.54 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
import { render } from "mustache";
import { DocstringParts } from "../docstring_parts";
import { TemplateData } from "./template_data";
export class DocstringFactory {
private template: string;
private quoteStyle: string;
private startOnNewLine: boolean;
private includeDescription: boolean;
private includeName: boolean;
private guessTypes: boolean;
constructor(
template: string,
quoteStyle = '"""',
startOnNewLine = false,
includeDescription = true,
includeName = false,
guessTypes = true,
) {
this.quoteStyle = quoteStyle;
this.startOnNewLine = startOnNewLine;
this.guessTypes = guessTypes;
this.includeName = includeName;
this.includeDescription = includeDescription;
this.template = template;
// console.log('template')
// console.log(this.template)
}
public generateDocstring(docstringParts: DocstringParts, indentation = ""): string {
const templateData = new TemplateData(
docstringParts,
this.guessTypes,
this.includeName,
this.includeDescription,
);
let docstring = render(this.template, templateData);
docstring = this.addSnippetPlaceholders(docstring);
docstring = this.condenseNewLines(docstring);
docstring = this.condenseTrailingNewLines(docstring);
docstring = this.commentText(docstring);
docstring = this.indentDocstring(docstring, indentation);
return docstring;
}
private addSnippetPlaceholders(snippetString: string): string {
let placeholderNumber = 0;
snippetString = snippetString.replace(/@@@/g, () => {
return (++placeholderNumber).toString();
});
return snippetString;
}
private condenseNewLines(snippet: string): string {
return snippet.replace(/\n{3,}/gm, "\n\n");
}
private condenseTrailingNewLines(snippet: string): string {
return snippet.replace(/\n+$/g, "\n");
}
private commentText(snippet: string): string {
if (this.startOnNewLine) {
snippet = "\n" + snippet;
}
return this.quoteStyle + snippet + this.quoteStyle;
}
private indentDocstring(snippet: string, indentation): string {
const snippetLines = snippet.split("\n");
snippetLines.forEach((line, index) => {
if (line !== "") {
snippetLines[index] = indentation + line;
}
});
return snippetLines.join("\n");
}
}