refactor: py/js entry func name (#31)

This commit is contained in:
sigoden
2024-06-07 16:10:05 +08:00
committed by GitHub
parent 739a832d87
commit e1d895cc9a
9 changed files with 32 additions and 24 deletions
+13 -9
View File
@@ -2,19 +2,23 @@
const fs = require("fs"); const fs = require("fs");
function main() { const TOOL_ENTRY_FUNC = "run";
function main(isTool = true) {
const scriptfile = process.argv[2]; const scriptfile = process.argv[2];
const contents = fs.readFileSync(process.argv[2], "utf8"); const contents = fs.readFileSync(process.argv[2], "utf8");
const functions = extractFunctions(contents); const functions = extractFunctions(contents, isTool);
let declarations = functions.map(({ funcName, jsdoc }) => { let declarations = functions.map(({ funcName, jsdoc }) => {
const { description, params } = parseJsDoc(jsdoc, funcName); const { description, params } = parseJsDoc(jsdoc, funcName);
const declaration = buildDeclaration(funcName, description, params); const declaration = buildDeclaration(funcName, description, params);
return declaration; return declaration;
}); });
const name = getBasename(scriptfile); if (isTool) {
if (declarations.length > 0) { const name = getBasename(scriptfile);
declarations = declarations.slice(0, 1); if (declarations.length > 0) {
declarations[0].name = name; declarations = declarations.slice(0, 1);
declarations[0].name = name;
}
} }
console.log(JSON.stringify(declarations, null, 2)); console.log(JSON.stringify(declarations, null, 2));
} }
@@ -23,7 +27,7 @@ function main() {
* @param {string} contents * @param {string} contents
* @param {bool} isTool * @param {bool} isTool
*/ */
function extractFunctions(contents, isTool = true) { function extractFunctions(contents, isTool) {
const output = []; const output = [];
const lines = contents.split("\n"); const lines = contents.split("\n");
let isInComment = false; let isInComment = false;
@@ -45,9 +49,9 @@ function extractFunctions(contents, isTool = true) {
continue; continue;
} }
if (isTool) { if (isTool) {
if (/function main/.test(line)) { if (new RegExp(`function ${TOOL_ENTRY_FUNC}`).test(line)) {
output.push({ output.push({
funcName: "main", funcName: TOOL_ENTRY_FUNC,
jsdoc, jsdoc,
}); });
} }
+11 -7
View File
@@ -7,13 +7,14 @@ import re
import sys import sys
from collections import OrderedDict from collections import OrderedDict
TOOL_ENTRY_FUNC = "run"
def main(): def main(is_tool = True):
scriptfile = sys.argv[1] scriptfile = sys.argv[1]
with open(scriptfile, "r", encoding="utf-8") as f: with open(scriptfile, "r", encoding="utf-8") as f:
contents = f.read() contents = f.read()
functions = extract_functions(contents) functions = extract_functions(contents, is_tool)
declarations = [] declarations = []
for function in functions: for function in functions:
func_name, docstring, func_args = function func_name, docstring, func_args = function
@@ -22,15 +23,16 @@ def main():
build_declaration(func_name, description, params, func_args) build_declaration(func_name, description, params, func_args)
) )
name = os.path.splitext(os.path.basename(scriptfile))[0] if is_tool:
if declarations: name = os.path.splitext(os.path.basename(scriptfile))[0]
declarations = declarations[0:1] if declarations:
declarations[0]["name"] = name declarations = declarations[0:1]
declarations[0]["name"] = name
print(json.dumps(declarations, indent=2)) print(json.dumps(declarations, indent=2))
def extract_functions(contents: str): def extract_functions(contents: str, is_tool: bool):
tree = ast.parse(contents) tree = ast.parse(contents)
output = [] output = []
for node in ast.walk(tree): for node in ast.walk(tree):
@@ -39,6 +41,8 @@ def extract_functions(contents: str):
func_name = node.name func_name = node.name
if func_name.startswith("_"): if func_name.startswith("_"):
continue continue
if is_tool and func_name != TOOL_ENTRY_FUNC:
continue
docstring = ast.get_docstring(node) or "" docstring = ast.get_docstring(node) or ""
func_args = OrderedDict() func_args = OrderedDict()
for arg in node.args.args: for arg in node.args.args:
+1 -1
View File
@@ -75,7 +75,7 @@ create_js() {
* @typedef {Object} Args${properties} * @typedef {Object} Args${properties}
* @param {Args} args * @param {Args} args
*/ */
exports.main = function main(args) { exports.run = function run(args) {
console.log(args); console.log(args);
} }
EOF EOF
+2 -2
View File
@@ -71,5 +71,5 @@ try {
process.exit(1); process.exit(1);
} }
const { main } = loadFunc(funcName); const { run } = loadFunc(funcName);
main(args); run(args);
+1 -1
View File
@@ -72,4 +72,4 @@ except (json.JSONDecodeError, TypeError):
sys.exit(1) sys.exit(1)
module = load_func(func_name) module = load_func(func_name)
module.main(**args) module.run(**args)
+1 -1
View File
@@ -11,6 +11,6 @@
* @property {string[]} [array_optional] - Define a optional string array property * @property {string[]} [array_optional] - Define a optional string array property
* @param {Args} args * @param {Args} args
*/ */
exports.main = function main(args) { exports.run = function run(args) {
console.log(args); console.log(args);
} }
+1 -1
View File
@@ -1,7 +1,7 @@
from typing import List, Literal, Optional from typing import List, Literal, Optional
def main( def run(
boolean: bool, boolean: bool,
string: str, string: str,
string_enum: Literal["foo", "bar"], string_enum: Literal["foo", "bar"],
+1 -1
View File
@@ -4,6 +4,6 @@
* @property {string} code - Javascript code to execute, such as `console.log("hello world")` * @property {string} code - Javascript code to execute, such as `console.log("hello world")`
* @param {Args} args * @param {Args} args
*/ */
exports.main = function main({ code }) { exports.run = function run({ code }) {
eval(code); eval(code);
} }
+1 -1
View File
@@ -1,4 +1,4 @@
def main(code: str): def run(code: str):
"""Runs the python code. """Runs the python code.
Args: Args:
code: Python code to execute, such as `print("hello world")` code: Python code to execute, such as `print("hello world")`