Added vscodium

This commit is contained in:
Kristofers Solo
2022-04-28 21:17:01 +03:00
parent 837a479d82
commit d7dddc39ef
29139 changed files with 250215 additions and 45125 deletions

View File

@@ -0,0 +1,8 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateDocstringCommand = exports.extensionID = exports.debug = exports.extensionRoot = void 0;
exports.extensionRoot = { path: "" };
exports.debug = false;
exports.extensionID = "autoDocstring";
exports.generateDocstringCommand = "autoDocstring.generateDocstring";
//# sourceMappingURL=constants.js.map

View File

@@ -0,0 +1,73 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DocstringFactory = void 0;
const mustache_1 = require("mustache");
const template_data_1 = require("./template_data");
const ts_dedent_1 = require("ts-dedent");
class DocstringFactory {
constructor(template, 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;
}
generateDocstring(docstringParts, indentation = "") {
const templateData = new template_data_1.TemplateData(docstringParts, this.guessTypes, this.includeName, this.includeDescription);
let docstring = (0, mustache_1.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;
}
toString() {
return (0, ts_dedent_1.dedent) `
DocstringFactory Configuration
quoteStyle:
${this.quoteStyle}
startOnNewLine:
${this.startOnNewLine}
guessTypes:
${this.guessTypes}
includeName:
${this.includeName}
includeDescription:
${this.includeDescription}
template:
${this.template}
`;
}
addSnippetPlaceholders(snippetString) {
let placeholderNumber = 0;
snippetString = snippetString.replace(/@@@/g, () => {
return (++placeholderNumber).toString();
});
return snippetString;
}
condenseNewLines(snippet) {
return snippet.replace(/\n{3,}/gm, "\n\n");
}
condenseTrailingNewLines(snippet) {
return snippet.replace(/\n+$/g, "\n");
}
commentText(snippet) {
if (this.startOnNewLine) {
snippet = "\n" + snippet;
}
return this.quoteStyle + snippet + this.quoteStyle;
}
indentDocstring(snippet, indentation) {
const snippetLines = snippet.split("\n");
snippetLines.forEach((line, index) => {
if (line !== "") {
snippetLines[index] = indentation + line;
}
});
return snippetLines.join("\n");
}
}
exports.DocstringFactory = DocstringFactory;
//# sourceMappingURL=docstring_factory.js.map

View File

@@ -0,0 +1,20 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCustomTemplate = exports.getTemplate = void 0;
const fs_1 = require("fs");
function getTemplate(docstringFormat) {
const fileName = docstringFormat + ".mustache";
const filePath = __dirname + "/templates/" + fileName;
// Default to docblockr
if (!(0, fs_1.existsSync)(filePath)) {
return (0, fs_1.readFileSync)(__dirname + "/templates/" + "docblockr.mustache", "utf8");
}
return (0, fs_1.readFileSync)(filePath, "utf8");
}
exports.getTemplate = getTemplate;
// TODO: handle error case
function getCustomTemplate(templateFilePath) {
return (0, fs_1.readFileSync)(templateFilePath, "utf8");
}
exports.getCustomTemplate = getCustomTemplate;
//# sourceMappingURL=get_template.js.map

View File

@@ -0,0 +1,8 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getTemplate = exports.DocstringFactory = void 0;
var docstring_factory_1 = require("./docstring_factory");
Object.defineProperty(exports, "DocstringFactory", { enumerable: true, get: function () { return docstring_factory_1.DocstringFactory; } });
var get_template_1 = require("./get_template");
Object.defineProperty(exports, "getTemplate", { enumerable: true, get: function () { return get_template_1.getTemplate; } });
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,98 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TemplateData = void 0;
class TemplateData {
constructor(docstringParts, guessTypes, includeName, includeExtendedSummary) {
this.name = docstringParts.name;
this.decorators = docstringParts.decorators;
this.args = docstringParts.args;
this.kwargs = docstringParts.kwargs;
this.exceptions = docstringParts.exceptions;
this.returns = docstringParts.returns;
this.yields = docstringParts.yields;
this.includeName = includeName;
this.includeExtendedSummary = includeExtendedSummary;
if (!guessTypes) {
this.removeTypes();
}
this.addDefaultTypePlaceholders("_type_");
}
placeholder() {
return (text, render) => {
return "${@@@:" + render(text) + "}";
};
}
summaryPlaceholder() {
if (this.includeName) {
return this.name + " ${@@@:_summary_}";
}
return "${@@@:_summary_}";
}
extendedSummaryPlaceholder() {
if (this.includeExtendedSummary) {
return "${@@@:_extended_summary_}";
}
return "";
}
typePlaceholder() {
// @ts-ignore
return "${@@@:" + this.type + "}";
}
descriptionPlaceholder() {
return "${@@@:_description_}";
}
argsExist() {
return this.args.length > 0;
}
kwargsExist() {
return this.kwargs.length > 0;
}
parametersExist() {
return this.args.length > 0 || this.kwargs.length > 0;
}
exceptionsExist() {
return this.exceptions.length > 0;
}
returnsExist() {
return this.returns !== undefined;
}
yieldsExist() {
return this.yields != undefined;
}
removeTypes() {
for (const arg of this.args) {
arg.type = undefined;
}
for (const kwarg of this.kwargs) {
kwarg.type = undefined;
}
if (this.yieldsExist()) {
this.yields.type = undefined;
}
if (this.returnsExist()) {
this.returns.type = undefined;
}
}
addDefaultTypePlaceholders(placeholder) {
for (const arg of this.args) {
if (arg.type === undefined) {
arg.type = placeholder;
}
}
for (const kwarg of this.kwargs) {
if (kwarg.type === undefined) {
kwarg.type = placeholder;
}
}
const returns = this.returns;
if (returns !== undefined && returns.type === undefined) {
returns.type = placeholder;
}
const yields = this.yields;
if (yields != undefined && yields.type == undefined) {
yields.type = placeholder;
}
}
}
exports.TemplateData = TemplateData;
//# sourceMappingURL=template_data.js.map

View File

@@ -0,0 +1,40 @@
{{! DocBlockr Docstring Template }}
{{=<% %>=}}
<%summaryPlaceholder%>
<%extendedSummaryPlaceholder%>
<%#argsExist%>
Arguments:
<%#args%>
<%var%> {<%typePlaceholder%>} -- <%descriptionPlaceholder%>
<%/args%>
<%/argsExist%>
<%#kwargsExist%>
Keyword Arguments:
<%#kwargs%>
<%var%> {<%typePlaceholder%>} -- <%descriptionPlaceholder%> (default: {<%&default%>})
<%/kwargs%>
<%/kwargsExist%>
<%#exceptionsExist%>
Raises:
<%#exceptions%>
<%type%>: <%descriptionPlaceholder%>
<%/exceptions%>
<%/exceptionsExist%>
<%#returnsExist%>
Returns:
<%#returns%>
<%typePlaceholder%> -- <%descriptionPlaceholder%>
<%/returns%>
<%/returnsExist%>
<%#yieldsExist%>
Yields:
<%#yields%>
<%typePlaceholder%> -- <%descriptionPlaceholder%>
<%/yields%>
<%/yieldsExist%>

View File

@@ -0,0 +1,35 @@
{{! Google Docstring Template without Types for Args, Returns or Yields }}
{{summaryPlaceholder}}
{{extendedSummaryPlaceholder}}
{{#parametersExist}}
Args:
{{#args}}
{{var}}: {{descriptionPlaceholder}}
{{/args}}
{{#kwargs}}
{{var}}: {{descriptionPlaceholder}}. Defaults to {{&default}}.
{{/kwargs}}
{{/parametersExist}}
{{#exceptionsExist}}
Raises:
{{#exceptions}}
{{type}}: {{descriptionPlaceholder}}
{{/exceptions}}
{{/exceptionsExist}}
{{#returnsExist}}
Returns:
{{#returns}}
{{descriptionPlaceholder}}
{{/returns}}
{{/returnsExist}}
{{#yieldsExist}}
Yields:
{{#yields}}
{{descriptionPlaceholder}}
{{/yields}}
{{/yieldsExist}}

View File

@@ -0,0 +1,35 @@
{{! Google Docstring Template }}
{{summaryPlaceholder}}
{{extendedSummaryPlaceholder}}
{{#parametersExist}}
Args:
{{#args}}
{{var}} ({{typePlaceholder}}): {{descriptionPlaceholder}}
{{/args}}
{{#kwargs}}
{{var}} ({{typePlaceholder}}, optional): {{descriptionPlaceholder}}. Defaults to {{&default}}.
{{/kwargs}}
{{/parametersExist}}
{{#exceptionsExist}}
Raises:
{{#exceptions}}
{{type}}: {{descriptionPlaceholder}}
{{/exceptions}}
{{/exceptionsExist}}
{{#returnsExist}}
Returns:
{{#returns}}
{{typePlaceholder}}: {{descriptionPlaceholder}}
{{/returns}}
{{/returnsExist}}
{{#yieldsExist}}
Yields:
{{#yields}}
{{typePlaceholder}}: {{descriptionPlaceholder}}
{{/yields}}
{{/yieldsExist}}

View File

@@ -0,0 +1,42 @@
{{! Numpy Docstring Template without Types for Args, Returns or Yields }}
{{summaryPlaceholder}}
{{extendedSummaryPlaceholder}}
{{#parametersExist}}
Parameters
----------
{{#args}}
{{var}}
{{descriptionPlaceholder}}
{{/args}}
{{#kwargs}}
{{var}}, optional
{{descriptionPlaceholder}}, by default {{&default}}
{{/kwargs}}
{{/parametersExist}}
{{#returnsExist}}
Returns
-------
{{#returns}}
{{descriptionPlaceholder}}
{{/returns}}
{{/returnsExist}}
{{#yieldsExist}}
Yields
------
{{#yields}}
{{descriptionPlaceholder}}
{{/yields}}
{{/yieldsExist}}
{{#exceptionsExist}}
Raises
------
{{#exceptions}}
{{type}}
{{descriptionPlaceholder}}
{{/exceptions}}
{{/exceptionsExist}}

View File

@@ -0,0 +1,44 @@
{{! Numpy Docstring Template }}
{{summaryPlaceholder}}
{{extendedSummaryPlaceholder}}
{{#parametersExist}}
Parameters
----------
{{#args}}
{{var}} : {{typePlaceholder}}
{{descriptionPlaceholder}}
{{/args}}
{{#kwargs}}
{{var}} : {{typePlaceholder}}, optional
{{descriptionPlaceholder}}, by default {{&default}}
{{/kwargs}}
{{/parametersExist}}
{{#returnsExist}}
Returns
-------
{{#returns}}
{{typePlaceholder}}
{{descriptionPlaceholder}}
{{/returns}}
{{/returnsExist}}
{{#yieldsExist}}
Yields
------
{{#yields}}
{{typePlaceholder}}
{{descriptionPlaceholder}}
{{/yields}}
{{/yieldsExist}}
{{#exceptionsExist}}
Raises
------
{{#exceptions}}
{{type}}
{{descriptionPlaceholder}}
{{/exceptions}}
{{/exceptionsExist}}

View File

@@ -0,0 +1,20 @@
{{! One-line RST Docstring Template }}
{{summaryPlaceholder}}
{{extendedSummaryPlaceholder}}
{{#args}}
:param {{typePlaceholder}} {{var}}: {{descriptionPlaceholder}}
{{/args}}
{{#kwargs}}
:param {{typePlaceholder}} {{var}}: {{descriptionPlaceholder}}, defaults to {{&default}}
{{/kwargs}}
{{#exceptions}}
:raises {{type}}: {{descriptionPlaceholder}}
{{/exceptions}}
{{#returns}}
:return {{typePlaceholder}}: {{descriptionPlaceholder}}
{{/returns}}
{{#yields}}
:yield {{typePlaceholder}}: {{descriptionPlaceholder}}
{{/yields}}

View File

@@ -0,0 +1,40 @@
{{! PEP257 Docstring Template }}
{{=<% %>=}}
<%summaryPlaceholder%>
<%extendedSummaryPlaceholder%>
<%#argsExist%>
Arguments:
<%#args%>
<%var%> -- <%descriptionPlaceholder%>
<%/args%>
<%/argsExist%>
<%#kwargsExist%>
Keyword Arguments:
<%#kwargs%>
<%var%> -- <%descriptionPlaceholder%> (default: {<%&default%>})
<%/kwargs%>
<%/kwargsExist%>
<%#exceptionsExist%>
Raises:
<%#exceptions%>
<%type%>: <%descriptionPlaceholder%>
<%/exceptions%>
<%/exceptionsExist%>
<%#returnsExist%>
Returns:
<%#returns%>
<%descriptionPlaceholder%>
<%/returns%>
<%/returnsExist%>
<%#yieldsExist%>
Yields:
<%#yields%>
<%descriptionPlaceholder%>
<%/yields%>
<%/yieldsExist%>

View File

@@ -0,0 +1,20 @@
{{! Sphinx Docstring Template without Types for Args, Returns or Yields }}
{{summaryPlaceholder}}
{{extendedSummaryPlaceholder}}
{{#args}}
:param {{var}}: {{descriptionPlaceholder}}
{{/args}}
{{#kwargs}}
:param {{var}}: {{descriptionPlaceholder}}, defaults to {{&default}}
{{/kwargs}}
{{#exceptions}}
:raises {{type}}: {{descriptionPlaceholder}}
{{/exceptions}}
{{#returns}}
:return: {{descriptionPlaceholder}}
{{/returns}}
{{#yields}}
:yield: {{descriptionPlaceholder}}
{{/yields}}

View File

@@ -0,0 +1,24 @@
{{! Sphinx Docstring Template }}
{{summaryPlaceholder}}
{{extendedSummaryPlaceholder}}
{{#args}}
:param {{var}}: {{descriptionPlaceholder}}
:type {{var}}: {{typePlaceholder}}
{{/args}}
{{#kwargs}}
:param {{var}}: {{descriptionPlaceholder}}, defaults to {{&default}}
:type {{var}}: {{typePlaceholder}}, optional
{{/kwargs}}
{{#exceptions}}
:raises {{type}}: {{descriptionPlaceholder}}
{{/exceptions}}
{{#returns}}
:return: {{descriptionPlaceholder}}
:rtype: {{typePlaceholder}}
{{/returns}}
{{#yields}}
:yield: {{descriptionPlaceholder}}
:rtype: {{typePlaceholder}}
{{/yields}}

View File

@@ -0,0 +1,40 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.docstringPartsToString = void 0;
const ts_dedent_1 = require("ts-dedent");
function docstringPartsToString(docstringParts) {
var _a, _b, _c, _d;
const decoratorsText = docstringParts.decorators.length
? docstringParts.decorators.map((decorator) => `${decorator.name}`).join("\n")
: "N/A";
const argsText = docstringParts.args.length
? docstringParts.args.map((argument) => `${argument.var} ${argument.type}`).join("\n")
: "N/A";
const kwargsText = docstringParts.kwargs.length
? docstringParts.kwargs.map((arg) => `${arg.var} ${arg.type} ${arg.default}`).join("\n")
: "N/A";
const exceptionsText = docstringParts.exceptions.length
? docstringParts.exceptions.map((exception) => `${exception.type}`).join("\n")
: "N/A";
const returnsText = `${(_b = (_a = docstringParts.returns) === null || _a === void 0 ? void 0 : _a.type) !== null && _b !== void 0 ? _b : "N/A"}`;
const yieldsText = `${(_d = (_c = docstringParts.yields) === null || _c === void 0 ? void 0 : _c.type) !== null && _d !== void 0 ? _d : "N/A"}`;
return (0, ts_dedent_1.default) `
Docstring parts:
Name:
${docstringParts.name}
Decorators:
${decoratorsText}
Args:
${argsText}
Kwargs:
${kwargsText}
Exceptions:
${exceptionsText}
Returns:
${returnsText}
Yields:
${yieldsText}
`;
}
exports.docstringPartsToString = docstringPartsToString;
//# sourceMappingURL=docstring_parts.js.map

View File

@@ -0,0 +1,68 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.deactivate = exports.activate = void 0;
const vs = require("vscode");
const generate_docstring_1 = require("./generate_docstring");
const parse_1 = require("./parse");
const constants_1 = require("./constants");
const telemetry_1 = require("./telemetry");
const logger_1 = require("./logger");
function activate(context) {
constants_1.extensionRoot.path = context.extensionPath;
context.subscriptions.push(vs.commands.registerCommand(constants_1.generateDocstringCommand, () => {
const editor = vs.window.activeTextEditor;
const autoDocstring = new generate_docstring_1.AutoDocstring(editor);
try {
return autoDocstring.generateDocstring();
}
catch (error) {
(0, logger_1.logError)(error + "\n\t" + (0, telemetry_1.getStackTrace)(error));
}
}));
['python', 'starlark'].map((language) => {
context.subscriptions.push(vs.languages.registerCompletionItemProvider(language, {
provideCompletionItems: (document, position, _) => {
if (validEnterActivation(document, position)) {
return [new AutoDocstringCompletionItem(document, position)];
}
},
}, "\"", "'", "#"));
});
(0, logger_1.logInfo)("autoDocstring was activated");
}
exports.activate = activate;
/**
* This method is called when the extension is deactivated
*/
function deactivate() { }
exports.deactivate = deactivate;
/**
* Checks that the preceding characters of the position is a valid docstring prefix
* and that the prefix is not part of an already closed docstring
*/
function validEnterActivation(document, position) {
const docString = document.getText();
const quoteStyle = getQuoteStyle();
return ((0, parse_1.validDocstringPrefix)(docString, position.line, position.character, quoteStyle) &&
!(0, parse_1.docstringIsClosed)(docString, position.line, position.character, quoteStyle));
}
/**
* Completion item to trigger generate docstring command on docstring prefix
*/
class AutoDocstringCompletionItem extends vs.CompletionItem {
constructor(_, position) {
super("Generate Docstring", vs.CompletionItemKind.Snippet);
this.insertText = "";
this.filterText = getQuoteStyle();
this.sortText = "\0";
this.range = new vs.Range(new vs.Position(position.line, 0), position);
this.command = {
command: constants_1.generateDocstringCommand,
title: "Generate Docstring",
};
}
}
function getQuoteStyle() {
return vs.workspace.getConfiguration(constants_1.extensionID).get("quoteStyle").toString();
}
//# sourceMappingURL=extension.js.map

View File

@@ -0,0 +1,63 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AutoDocstring = void 0;
const path = require("path");
const vs = require("vscode");
const docstring_factory_1 = require("./docstring/docstring_factory");
const get_template_1 = require("./docstring/get_template");
const parse_1 = require("./parse");
const constants_1 = require("./constants");
const logger_1 = require("./logger");
const docstring_parts_1 = require("./docstring_parts");
class AutoDocstring {
constructor(editor) {
this.editor = editor;
}
generateDocstring() {
if (this.editor == undefined) {
throw new Error("Cannot process this document. It is either too large or is not yet supported.");
}
const position = this.editor.selection.active;
const document = this.editor.document.getText();
(0, logger_1.logInfo)(`Generating Docstring at line: ${position.line}`);
const docstringSnippet = this.generateDocstringSnippet(document, position);
(0, logger_1.logInfo)(`Docstring generated:\n${docstringSnippet.value}`);
const insertPosition = position.with(undefined, 0);
(0, logger_1.logInfo)(`Inserting at position: ${insertPosition.line} ${insertPosition.character}`);
const success = this.editor.insertSnippet(docstringSnippet, insertPosition);
success.then(() => (0, logger_1.logInfo)("Successfully inserted docstring"), (reason) => {
throw new Error("Could not insert docstring: " + reason.toString());
});
return success;
}
generateDocstringSnippet(document, position) {
const config = this.getConfig();
const docstringFactory = new docstring_factory_1.DocstringFactory(this.getTemplate(), config.get("quoteStyle").toString(), config.get("startOnNewLine") === true, config.get("includeExtendedSummary") === true, config.get("includeName") === true, config.get("guessTypes") === true);
(0, logger_1.logDebug)(docstringFactory.toString());
const docstringParts = (0, parse_1.parse)(document, position.line);
(0, logger_1.logDebug)((0, docstring_parts_1.docstringPartsToString)(docstringParts));
const defaultIndentation = (0, parse_1.getDefaultIndentation)(this.editor.options.insertSpaces, this.editor.options.tabSize);
(0, logger_1.logDebug)(`Default indentation: "${defaultIndentation}"`);
const indentation = (0, parse_1.getDocstringIndentation)(document, position.line, defaultIndentation);
(0, logger_1.logDebug)(`Indentation: "${indentation}"`);
const docstring = docstringFactory.generateDocstring(docstringParts, indentation);
return new vs.SnippetString(docstring);
}
getTemplate() {
const config = this.getConfig();
let customTemplatePath = config.get("customTemplatePath").toString();
if (customTemplatePath === "") {
const docstringFormat = config.get("docstringFormat").toString();
return (0, get_template_1.getTemplate)(docstringFormat);
}
if (!path.isAbsolute(customTemplatePath)) {
customTemplatePath = path.join(vs.workspace.rootPath, customTemplatePath);
}
return (0, get_template_1.getCustomTemplate)(customTemplatePath);
}
getConfig() {
return vs.workspace.getConfiguration(constants_1.extensionID);
}
}
exports.AutoDocstring = AutoDocstring;
//# sourceMappingURL=generate_docstring.js.map

View File

@@ -0,0 +1,44 @@
"use strict";
// Copyright (c) 2015 DonJayamanne. All rights reserved.
// Licensed under the MIT License.
// Code borrowed from https://github.com/DonJayamanne/gitHistoryVSCode
Object.defineProperty(exports, "__esModule", { value: true });
exports.logDebug = exports.logInfo = exports.logError = exports.getLogChannel = void 0;
const vscode = require("vscode");
const constants_1 = require("./constants");
let outLogChannel;
const logLevel = vscode.workspace.getConfiguration(constants_1.extensionID).get("logLevel");
function getLogChannel() {
if (outLogChannel === undefined) {
outLogChannel = vscode.window.createOutputChannel("autoDocstring");
}
return outLogChannel;
}
exports.getLogChannel = getLogChannel;
function logError(error) {
getLogChannel().appendLine(`[ERROR ${getTimeAndMs()}] ${error.toString()}`);
getLogChannel().show();
vscode.window.showErrorMessage("AutoDocstring encountered an error. Please view details in the 'autoDocstring' output window");
}
exports.logError = logError;
function logInfo(message) {
if (logLevel === "Info" || logLevel === "Debug") {
getLogChannel().appendLine(`[INFO ${getTimeAndMs()}] ${message}`);
}
}
exports.logInfo = logInfo;
function logDebug(message) {
if (logLevel === "Debug") {
getLogChannel().appendLine(`[DEBUG ${getTimeAndMs()}] ${message}`);
}
}
exports.logDebug = logDebug;
function getTimeAndMs() {
const time = new Date();
const hours = `0${time.getHours()}`.slice(-2);
const minutes = `0${time.getMinutes()}`.slice(-2);
const seconds = `0${time.getSeconds()}`.slice(-2);
const milliSeconds = `00${time.getMilliseconds()}`.slice(-3);
return `${hours}:${minutes}:${seconds}.${milliSeconds}`;
}
//# sourceMappingURL=logger.js.map

View File

@@ -0,0 +1,59 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.docstringIsClosed = void 0;
const utilities_1 = require("./utilities");
function docstringIsClosed(document, linePosition, charPosition, quoteStyle) {
const lines = document.split("\n");
if (quotesCloseExistingDocstring(lines, linePosition, charPosition, quoteStyle)) {
return true;
}
if (quotesOpenExistingDocstring(lines, linePosition, charPosition, quoteStyle)) {
return true;
}
return false;
}
exports.docstringIsClosed = docstringIsClosed;
function quotesCloseExistingDocstring(lines, linePosition, charPosition, quoteStyle) {
const linesBeforePosition = sliceUpToPosition(lines, linePosition, charPosition);
let numberOfTripleQuotes = 0;
for (const line of linesBeforePosition.reverse()) {
if (line.includes("def ") || line.includes("class ")) {
break;
}
numberOfTripleQuotes += occurrences(line, quoteStyle);
}
return numberOfTripleQuotes % 2 === 0;
}
function quotesOpenExistingDocstring(lines, linePosition, charPosition, quoteStyle) {
const linesAfterPosition = sliceFromPosition(lines, linePosition, charPosition);
const originalIndentation = (0, utilities_1.indentationOf)(lines[linePosition]);
// Need to check first line separately because indentation was sliced off
if (linesAfterPosition[0].includes(quoteStyle)) {
return true;
}
for (const line of linesAfterPosition.slice(1)) {
if (line.includes(quoteStyle)) {
return true;
}
if ((!(0, utilities_1.blankLine)(line) && (0, utilities_1.indentationOf)(line) < originalIndentation) ||
line.includes("def ") ||
line.includes("class ")) {
return false;
}
}
return false;
}
function sliceUpToPosition(lines, linePosition, charPosition) {
const slicedDocument = lines.slice(0, linePosition);
slicedDocument.push(lines[linePosition].slice(0, charPosition));
return slicedDocument;
}
function sliceFromPosition(lines, linePosition, charPosition) {
let slicedDocument = [lines[linePosition].slice(charPosition)];
slicedDocument = slicedDocument.concat(lines.slice(linePosition + 1));
return slicedDocument;
}
function occurrences(str, word) {
return str.split(word).length - 1;
}
//# sourceMappingURL=docstring_is_closed.js.map

View File

@@ -0,0 +1,41 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getBody = void 0;
const utilities_1 = require("./utilities");
function getBody(document, linePosition) {
const lines = document.split("\n");
const body = [];
let currentLineNum = linePosition;
const originalIndentation = getBodyBaseIndentation(lines, linePosition);
while (currentLineNum < lines.length) {
const line = lines[currentLineNum];
if ((0, utilities_1.blankLine)(line)) {
currentLineNum++;
continue;
}
if ((0, utilities_1.indentationOf)(line) < originalIndentation) {
break;
}
body.push(line);
currentLineNum++;
}
return (0, utilities_1.preprocessLines)(body);
}
exports.getBody = getBody;
function getBodyBaseIndentation(lines, linePosition) {
let currentLineNum = linePosition;
const functionDefRegex = /\s*def \w+/;
while (currentLineNum < lines.length) {
const line = lines[currentLineNum];
if ((0, utilities_1.blankLine)(line)) {
currentLineNum++;
continue;
}
if (functionDefRegex.test(line)) {
break;
}
return (0, utilities_1.indentationOf)(line);
}
return 10000;
}
//# sourceMappingURL=get_body.js.map

View File

@@ -0,0 +1,32 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getDefinition = void 0;
const utilities_1 = require("./utilities");
function getDefinition(document, linePosition) {
const precedingLines = getPrecedingLines(document, linePosition);
const precedingText = precedingLines.join(" ");
// Don't parse if the preceding line is blank
const precedingLine = precedingLines[precedingLines.length - 1];
if (precedingLine == undefined || (0, utilities_1.blankLine)(precedingLine)) {
return "";
}
const pattern = /\b(((async\s+)?\s*def)|\s*class)\b/g;
// Get starting index of last def match in the preceding text
let index;
while (pattern.test(precedingText)) {
index = pattern.lastIndex - RegExp.lastMatch.length;
}
if (index == undefined) {
return "";
}
const lastFunctionDef = precedingText.slice(index);
return lastFunctionDef.trim();
}
exports.getDefinition = getDefinition;
function getPrecedingLines(document, linePosition) {
const lines = document.split("\n");
const rawPrecedingLines = lines.slice(0, linePosition);
const precedingLines = (0, utilities_1.preprocessLines)(rawPrecedingLines);
return precedingLines;
}
//# sourceMappingURL=get_definition.js.map

View File

@@ -0,0 +1,21 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getDocstringIndentation = void 0;
const utilities_1 = require("./utilities");
function getDocstringIndentation(document, linePosition, defaultIndentation) {
const lines = document.split("\n");
const definitionPattern = /\b(((async\s+)?\s*def)|\s*class)\b/g;
let currentLineNum = linePosition;
while (currentLineNum >= 0) {
const currentLine = lines[currentLineNum];
if (!(0, utilities_1.blankLine)(currentLine)) {
if (definitionPattern.test(currentLine)) {
return (0, utilities_1.getIndentation)(currentLine) + defaultIndentation;
}
}
currentLineNum--;
}
return defaultIndentation;
}
exports.getDocstringIndentation = getDocstringIndentation;
//# sourceMappingURL=get_docstring_indentation.js.map

View File

@@ -0,0 +1,13 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getFunctionName = void 0;
function getFunctionName(functionDefinition) {
const pattern = /(?:def|class)\s+(\w+)\s*\(/;
const match = pattern.exec(functionDefinition);
if (match == undefined || match[1] == undefined) {
return "";
}
return match[1];
}
exports.getFunctionName = getFunctionName;
//# sourceMappingURL=get_function_name.js.map

View File

@@ -0,0 +1,144 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.inArray = exports.guessType = void 0;
function guessType(parameter) {
parameter = parameter.trim();
if (hasTypeHint(parameter)) {
return getTypeFromTypeHint(parameter);
}
if (isKwarg(parameter)) {
return guessTypeFromDefaultValue(parameter);
}
return guessTypeFromName(parameter);
}
exports.guessType = guessType;
function getTypeFromTypeHint(parameter) {
const sections = parameter.split(":");
if (sections.length !== 2) {
return undefined;
}
const typeHint = sections[1];
const pattern = /\s*(['"]?\w["'\w\[\], |\.]*['"]?)/;
const typeHintRegex = pattern.exec(typeHint);
if (typeHintRegex == null) {
return undefined;
}
// Remove enclosing quotes
let type = typeHintRegex[0].trim();
type = type.replace(/^['"]|['"]$/g, "");
return type;
}
function guessTypeFromDefaultValue(parameter) {
const pattern = /\w+\s*(?::[\w\[\], \.]+)?=\s*(.+)/;
const defaultValueMatch = pattern.exec(parameter);
if (defaultValueMatch == null || defaultValueMatch.length !== 2) {
return undefined;
}
const defaultValue = defaultValueMatch[1];
if (isInteger(defaultValue)) {
return "int";
}
if (isFloat(defaultValue)) {
return "float";
}
if (isHexadecimal(defaultValue)) {
return "hexadecimal";
}
if (isString(defaultValue)) {
return "str";
}
if (isBool(defaultValue)) {
return "bool";
}
if (isList(defaultValue)) {
return "list";
}
if (isTuple(defaultValue)) {
return "tuple";
}
if (isDict(defaultValue)) {
return "dict";
}
if (isRegexp(defaultValue)) {
return "regexp";
}
if (isUnicode(defaultValue)) {
return "unicode";
}
if (isBytes(defaultValue)) {
return "bytes";
}
if (isFunction(defaultValue)) {
return "function";
}
return undefined;
}
function guessTypeFromName(parameter) {
if (parameter.startsWith("is") || parameter.startsWith("has")) {
return "bool";
}
if (inArray(parameter, ["cb", "callback", "done", "next", "fn"])) {
return "function";
}
return undefined;
}
function hasTypeHint(parameter) {
const pattern = /^\w+\s*:/;
return pattern.test(parameter);
}
function isKwarg(parameter) {
return parameter.includes("=");
}
function isInteger(value) {
const pattern = /^[-+]?[0-9]+$/;
return pattern.test(value);
}
function isFloat(value) {
const pattern = /^[-+]?[0-9]*\.[0-9]+$/;
return pattern.test(value);
}
function isHexadecimal(value) {
const pattern = /^[-+]?0x[0-9abcdef]+/;
return pattern.test(value);
}
function isString(value) {
const pattern = /^\".*\"$|^\'.*\'$/;
return pattern.test(value);
}
function isBool(value) {
const pattern = /^True$|^False$/;
return pattern.test(value);
}
function isList(value) {
const pattern = /^\[.*\]$/;
return pattern.test(value);
}
function isTuple(value) {
const pattern = /^\(.*\)$/;
return pattern.test(value);
}
function isDict(value) {
const pattern = /^\{.*\}$/;
return pattern.test(value);
}
function isRegexp(value) {
const pattern = /^[rR]/;
return pattern.test(value) && isString(value.substr(1));
}
function isUnicode(value) {
const pattern = /^[uU]/;
return pattern.test(value) && isString(value.substr(1));
}
function isBytes(value) {
const pattern = /^[bB]/;
return pattern.test(value) && isString(value.substr(1));
}
function isFunction(value) {
const pattern = /^lambda /;
return pattern.test(value);
}
function inArray(item, array) {
return array.some((x) => item === x);
}
exports.inArray = inArray;
//# sourceMappingURL=guess_type.js.map

View File

@@ -0,0 +1,26 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getDefaultIndentation = exports.tokenizeDefinition = exports.parseParameters = exports.parse = exports.validDocstringPrefix = exports.guessType = exports.getFunctionName = exports.getDocstringIndentation = exports.getDefinition = exports.getBody = exports.docstringIsClosed = void 0;
var docstring_is_closed_1 = require("./docstring_is_closed");
Object.defineProperty(exports, "docstringIsClosed", { enumerable: true, get: function () { return docstring_is_closed_1.docstringIsClosed; } });
var get_body_1 = require("./get_body");
Object.defineProperty(exports, "getBody", { enumerable: true, get: function () { return get_body_1.getBody; } });
var get_definition_1 = require("./get_definition");
Object.defineProperty(exports, "getDefinition", { enumerable: true, get: function () { return get_definition_1.getDefinition; } });
var get_docstring_indentation_1 = require("./get_docstring_indentation");
Object.defineProperty(exports, "getDocstringIndentation", { enumerable: true, get: function () { return get_docstring_indentation_1.getDocstringIndentation; } });
var get_function_name_1 = require("./get_function_name");
Object.defineProperty(exports, "getFunctionName", { enumerable: true, get: function () { return get_function_name_1.getFunctionName; } });
var guess_type_1 = require("./guess_type");
Object.defineProperty(exports, "guessType", { enumerable: true, get: function () { return guess_type_1.guessType; } });
var valid_docstring_prefix_1 = require("./valid_docstring_prefix");
Object.defineProperty(exports, "validDocstringPrefix", { enumerable: true, get: function () { return valid_docstring_prefix_1.validDocstringPrefix; } });
var parse_1 = require("./parse");
Object.defineProperty(exports, "parse", { enumerable: true, get: function () { return parse_1.parse; } });
var parse_parameters_1 = require("./parse_parameters");
Object.defineProperty(exports, "parseParameters", { enumerable: true, get: function () { return parse_parameters_1.parseParameters; } });
var tokenize_definition_1 = require("./tokenize_definition");
Object.defineProperty(exports, "tokenizeDefinition", { enumerable: true, get: function () { return tokenize_definition_1.tokenizeDefinition; } });
var utilities_1 = require("./utilities");
Object.defineProperty(exports, "getDefaultIndentation", { enumerable: true, get: function () { return utilities_1.getDefaultIndentation; } });
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,14 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parse = void 0;
const _1 = require(".");
function parse(document, positionLine) {
const definition = (0, _1.getDefinition)(document, positionLine);
const body = (0, _1.getBody)(document, positionLine);
const parameterTokens = (0, _1.tokenizeDefinition)(definition);
const functionName = (0, _1.getFunctionName)(definition);
const docstringParts = (0, _1.parseParameters)(parameterTokens, body, functionName);
return docstringParts;
}
exports.parse = parse;
//# sourceMappingURL=parse.js.map

View File

@@ -0,0 +1,128 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.inArray = exports.parseParameters = void 0;
const _1 = require(".");
function parseParameters(parameterTokens, body, functionName) {
return {
name: functionName,
decorators: parseDecorators(parameterTokens),
args: parseArguments(parameterTokens),
kwargs: parseKeywordArguments(parameterTokens),
returns: parseReturn(parameterTokens, body),
yields: parseYields(parameterTokens, body),
exceptions: parseExceptions(body),
};
}
exports.parseParameters = parseParameters;
function parseDecorators(parameters) {
const decorators = [];
const pattern = /^@(\w+)/;
for (const param of parameters) {
const match = param.trim().match(pattern);
if (match == null) {
continue;
}
decorators.push({
name: match[1],
});
}
return decorators;
}
function parseArguments(parameters) {
const args = [];
const excludedArgs = ["self", "cls"];
const pattern = /^(\w+)/;
for (const param of parameters) {
const match = param.trim().match(pattern);
if (match == null || param.includes("=") || inArray(param, excludedArgs)) {
continue;
}
args.push({
var: match[1],
type: (0, _1.guessType)(param),
});
}
return args;
}
function parseKeywordArguments(parameters) {
const kwargs = [];
const pattern = /^(\w+)(?:\s*:[^=]+)?\s*=\s*(.+)/;
for (const param of parameters) {
const match = param.trim().match(pattern);
if (match == null) {
continue;
}
kwargs.push({
var: match[1],
default: match[2],
type: (0, _1.guessType)(param),
});
}
return kwargs;
}
function parseReturn(parameters, body) {
const returnType = parseReturnFromDefinition(parameters);
if (returnType == null || isIterator(returnType.type)) {
return parseFromBody(body, /return /);
}
return returnType;
}
function parseYields(parameters, body) {
const returnType = parseReturnFromDefinition(parameters);
if (returnType != null && isIterator(returnType.type)) {
return returnType;
}
// To account for functions that yield but don't have a yield signature
const yieldType = returnType ? returnType.type : undefined;
const yieldInBody = parseFromBody(body, /yield /);
if (yieldInBody != null && yieldType != undefined) {
yieldInBody.type = `Iterator[${yieldType}]`;
}
return yieldInBody;
}
function parseReturnFromDefinition(parameters) {
const pattern = /^->\s*(["']?)(['"\w\[\], |\.]*)\1/;
for (const param of parameters) {
const match = param.trim().match(pattern);
if (match == null) {
continue;
}
// Skip "-> None" annotations
return match[2] === "None" ? null : { type: match[2] };
}
return null;
}
function parseExceptions(body) {
const exceptions = [];
const pattern = /(?<!#.*)raise\s+([\w.]+)/;
for (const line of body) {
const match = line.match(pattern);
if (match == null) {
continue;
}
exceptions.push({ type: match[1] });
}
return exceptions;
}
function inArray(item, array) {
return array.some((x) => item === x);
}
exports.inArray = inArray;
function parseFromBody(body, pattern) {
for (const line of body) {
const match = line.match(pattern);
if (match == null) {
continue;
}
return { type: undefined };
}
return undefined;
}
/**
* Check whether the annotated type is an iterator.
* @param type The annotated type
*/
function isIterator(type) {
return type.startsWith("Generator") || type.startsWith("Iterator");
}
//# sourceMappingURL=parse_parameters.js.map

View File

@@ -0,0 +1,87 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.tokenizeDefinition = void 0;
function tokenizeDefinition(functionDefinition) {
const definitionPattern = /(?:def|class)\s+\w+\s*\(([\s\S]*)\)\s*(->\s*(["']?)[\w\[\], |\.]*\3)?:\s*(?:#.*)?$/;
const match = definitionPattern.exec(functionDefinition);
if (match == undefined || match[1] == undefined) {
return [];
}
const tokens = tokenizeParameterString(match[1]);
if (match[2] != undefined) {
tokens.push(match[2]);
}
return tokens;
}
exports.tokenizeDefinition = tokenizeDefinition;
function tokenizeParameterString(parameterString) {
const stack = [];
const parameters = [];
let arg = "";
let position = parameterString.length - 1;
while (position >= 0) {
const top = stack[stack.length - 1];
let char = parameterString.charAt(position);
/* todo
'<' char,
error management
*/
switch (true) {
// 1. Check for top level comma and push arg to array
case char === "," && stack.length === 0:
parameters.unshift(arg);
arg = "";
position -= 1;
continue;
// 2. Check for closing double or single quote of string
case char === '"' && top === '"':
case char === "'" && top === "'":
stack.pop();
break;
// 3. Do nothing if quote at the top of stack
case top === '"':
case top === "'":
break;
// 4. Push single and double quotes to stack
case char === '"':
case char === "'":
stack.push(char);
break;
// 5. Check for closing of tuples, arrays, or dicts
case char === "(" && top === ")":
case char === "[" && top === "]":
case char === "{" && top === "}":
stack.pop();
break;
// 6. Do nothing if closing char but no matching char on stack
case char === "(":
case char === "[":
case char === "{":
break;
// 7. Push opening char to stack
case char === ")":
case char === "]":
case char === "}":
stack.push(char);
break;
// 8. Disregard whitespace at top level of stack
case char === " " && stack.length === 0:
case char === "\n" && stack.length === 0:
case char === "\t" && stack.length === 0:
position -= 1;
continue;
// 9. Surround pipe character with whitespace
case char === "|":
char = ` ${char}`;
arg = ` ${arg}`;
break;
}
arg = char + arg;
position -= 1;
}
if (arg.length > 0) {
parameters.unshift(arg);
}
return parameters;
}
//# sourceMappingURL=tokenize_definition.js.map

View File

@@ -0,0 +1,38 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getDefaultIndentation = exports.blankLine = exports.indentationOf = exports.preprocessLines = exports.getIndentation = void 0;
function getIndentation(line) {
const whiteSpaceMatches = line.match(/^[^\S\r]+/);
if (whiteSpaceMatches == undefined) {
return "";
}
return whiteSpaceMatches[0];
}
exports.getIndentation = getIndentation;
/**
* Preprocess an array of lines.
* For example trim spaces and discard comments
* @param lines The lines to preprocess.
*/
function preprocessLines(lines) {
return lines
.map(line => line.trim())
.filter((line) => !line.startsWith("#"));
}
exports.preprocessLines = preprocessLines;
function indentationOf(line) {
return getIndentation(line).length;
}
exports.indentationOf = indentationOf;
function blankLine(line) {
return line.match(/[^\s]/) == undefined;
}
exports.blankLine = blankLine;
function getDefaultIndentation(useSpaces, tabSize) {
if (!useSpaces) {
return "\t";
}
return " ".repeat(tabSize);
}
exports.getDefaultIndentation = getDefaultIndentation;
//# sourceMappingURL=utilities.js.map

View File

@@ -0,0 +1,16 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validDocstringPrefix = void 0;
/**
* Checks whether the 3 characters proceeding the position are the correct start
* to a docstring and that there are no other characters on the line.
*/
function validDocstringPrefix(document, linePosition, charPosition, quoteStyle) {
const lines = document.split(/\r?\n/);
const line = lines[linePosition];
const prefix = line.slice(0, charPosition + 1);
const regex = RegExp("^[^\\S\\r]*" + quoteStyle + "$");
return regex.test(line) && regex.test(prefix);
}
exports.validDocstringPrefix = validDocstringPrefix;
//# sourceMappingURL=valid_docstring_prefix.js.map

View File

@@ -0,0 +1,78 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code borrowed from https://github.com/microsoft/vscode-python
Object.defineProperty(exports, "__esModule", { value: true });
exports.getStackTrace = void 0;
const stackTrace = require("stack-trace");
const path_1 = require("path");
const constants_1 = require("./constants");
function getStackTrace(ex) {
// We aren't showing the error message (ex.message) since it might
// contain PII.
let trace = "\t";
for (const frame of stackTrace.parse(ex)) {
let filename = frame.getFileName();
if (filename) {
if (!constants_1.debug && !isExtensionFile(filename)) {
continue;
}
filename = sanitizeFilename(filename);
const lineno = frame.getLineNumber();
const colno = frame.getColumnNumber();
trace += `\n\tat ${getCallSite(frame)} ${filename}:${lineno}:${colno}`;
}
else {
trace += "\n\tat <anonymous>";
}
}
// Ensure we always use `/` as path separators.
// This way stack traces (with relative paths) coming from different OS will always look the same.
return trace.trim().replace(/\\/g, "/");
}
exports.getStackTrace = getStackTrace;
function isExtensionFile(filename) {
const extensionPath = constants_1.extensionRoot.path;
if (!extensionPath) {
return true;
}
return filename.startsWith(extensionPath);
}
function sanitizeFilename(filename) {
const extensionPath = constants_1.extensionRoot.path;
if (!extensionPath) {
return "<hidden_no_extension_root>";
}
if (filename.startsWith(extensionPath)) {
filename = `<autoDocstring>${filename.substring(extensionPath.length)}`;
}
else {
// We don't really care about files outside our extension.
filename = `<hidden>${path_1.sep}${(0, path_1.basename)(filename)}`;
}
return filename;
}
function sanitizeName(name) {
if (name.indexOf("/") === -1 && name.indexOf("\\") === -1) {
return name;
}
else {
return "<hidden>";
}
}
function getCallSite(frame) {
const parts = [];
if (typeof frame.getTypeName() === "string" && frame.getTypeName().length > 0) {
parts.push(frame.getTypeName());
}
if (typeof frame.getMethodName() === "string" && frame.getMethodName().length > 0) {
parts.push(frame.getMethodName());
}
if (typeof frame.getFunctionName() === "string" && frame.getFunctionName().length > 0) {
if (parts.length !== 2 || parts.join(".") !== frame.getFunctionName()) {
parts.push(frame.getFunctionName());
}
}
return parts.map(sanitizeName).join(".");
}
//# sourceMappingURL=telemetry.js.map