Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 89fd1e4

Browse filesBrowse files
committed
added params and prettier
1 parent 9bddd2d commit 89fd1e4
Copy full SHA for 89fd1e4

File tree

6 files changed

+129
-77
lines changed
Filter options

6 files changed

+129
-77
lines changed

‎.prettierrc

Copy file name to clipboard
+8Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"printWidth": 100,
3+
"trailingComma": "none",
4+
"arrowParens": "avoid",
5+
"parser": "typescript",
6+
"singleQuote": true,
7+
"tabWidth": 2
8+
}

‎README.md

Copy file name to clipboardExpand all lines: README.md
+2-3Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ Then, from a root folder you can:
7373
7474
or
7575

76-
> jspython -f=my_code.jspy -s=src --param1=some_Value
76+
> jspython -f my_code.jspy -s src --param1=some_Value
7777
7878

7979
### Version info
@@ -87,8 +87,7 @@ or
8787
## Development
8888
Run example using node. (Works only if you have build project `npm run build`)
8989
```
90-
node ./bin/jspython --file=../jspython-examples/axios-test.jspy
91-
node ./bin/jspython --file ../jspython-examples/parse.jspy
90+
node ./bin/jspython --file=../jspython-examples/test.jspy
9291
node ./bin/jspython --file=test.jspy --srcRoot=../jspython-examples/
9392
```
9493

‎package.json

Copy file name to clipboardExpand all lines: package.json
+5-2Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "jspython-cli",
3-
"version": "2.1.9",
3+
"version": "2.1.10",
44
"description": "CLI for jspython. Allows you to run jspython (*.jspy) files",
55
"main": "./lib/public-api.js",
66
"bin": {
@@ -31,12 +31,15 @@
3131
"homepage": "https://github.com/jspython-dev/jspython-cli#readme",
3232
"dependencies": {
3333
"arg": "^5.0.1",
34-
"jspython-interpreter": "^2.1.7"
34+
"jspython-interpreter": "^2.1.8"
3535
},
3636
"devDependencies": {
3737
"rollup": "^2.70.1",
3838
"rollup-plugin-copy": "^3.4.0",
3939
"rollup-plugin-typescript2": "^0.31.2",
40+
"eslint-config-prettier": "^8.3.0",
41+
"eslint-plugin-prettier": "^4.0.0",
42+
"prettier": "^2.5.1",
4043
"typescript": "^4.6.3"
4144
}
4245
}

‎src/cli.ts

Copy file name to clipboardExpand all lines: src/cli.ts
+58-40Lines changed: 58 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -19,30 +19,30 @@ process
1919
process.exit(1);
2020
});
2121

22+
const options = getOptionsFromArguments(process.argv);
2223
const initialScope: Record<string, any> = {
23-
app: {},
24-
session: {}
24+
session: {},
25+
params: options.params
2526
};
2627

27-
const options = getOptionsFromArguments(process.argv);
2828
const interpreter: Interpreter = jsPythonForNode(options) as Interpreter;
2929

3030
function getOptionsFromArguments(rawArgs: string[]): InterpreterOptions {
31-
const args = arg({
32-
'--file': String,
33-
'--srcRoot': String,
34-
'--entryFunction': String,
35-
'--version': Boolean,
36-
'--output': String,
37-
'-f': '--file',
38-
'-s': '--srcRoot',
39-
'-e': '--entryFunction',
40-
'-v': '--version',
41-
'-o': '--output'
42-
}, {
43-
argv: rawArgs.slice(2),
44-
permissive: true
45-
});
31+
const args = arg(
32+
{
33+
'--file': String,
34+
'--srcRoot': String,
35+
'--entryFunction': String,
36+
'--version': Boolean,
37+
'--output': String,
38+
'-f': '--file',
39+
'-s': '--srcRoot',
40+
'-e': '--entryFunction',
41+
'-v': '--version',
42+
'-o': '--output'
43+
},
44+
{ permissive: true, argv: process.argv.slice(2) }
45+
);
4646

4747
const params = args._.reduce((obj: { [key: string]: any }, a: string) => {
4848
const kv = a.replace('--', '');
@@ -55,15 +55,23 @@ function getOptionsFromArguments(rawArgs: string[]): InterpreterOptions {
5555
}, {});
5656

5757
const res: InterpreterOptions = {
58-
file: args['--file'] || (rawArgs.length === 3 && !rawArgs[2].startsWith('-') ? rawArgs[2] : ''),
59-
version: args['--version'],
60-
output: args['--output'],
61-
entryFunction: args['--entryFunction'],
62-
srcRoot: args['--srcRoot'] || ''
58+
file: args['--file'] || (rawArgs.length === 3 && !rawArgs[2].startsWith('-') ? rawArgs[2] : '')
6359
};
6460

65-
res.srcRoot = trimChar(res.srcRoot || '', '/');
66-
if (res.srcRoot.length) {
61+
if (args['--version']) {
62+
res.version = args['--version'];
63+
}
64+
if (args['--output']) {
65+
res.output = args['--output'];
66+
}
67+
if (args['--entryFunction']) {
68+
res.entryFunction = args['--entryFunction'];
69+
}
70+
if (args['--srcRoot']) {
71+
res.srcRoot = args['--srcRoot'];
72+
}
73+
74+
if (trimChar(res.srcRoot || '', '/').length) {
6775
res.srcRoot = res.srcRoot + '/';
6876
}
6977

@@ -73,20 +81,21 @@ function getOptionsFromArguments(rawArgs: string[]): InterpreterOptions {
7381
}
7482

7583
async function main() {
76-
if (!options.file && !options.version) {
84+
if (options.version) {
7785
console.log(interpreter.jsPythonInfo());
7886
console.log(`JSPython cli v${(pkg || {}).version}\n`);
79-
console.log(` :\> jspython (fileName.jspy)`);
80-
console.log(` :\> jspython -f=(fileName.jspy)`);
81-
console.log(` :\> jspython --file=(fileName.jspy)`);
82-
console.log(` :\> jspython --file=(fileName.jspy) --srcRoot=src`);
83-
console.log(' ');
8487
return;
8588
}
8689

87-
if (options.version) {
90+
if (!options.file) {
8891
console.log(interpreter.jsPythonInfo());
8992
console.log(`JSPython cli v${(pkg || {}).version}\n`);
93+
console.log(` :\> jspython (fileName.jspy)`);
94+
console.log(` :\> jspython -f (fileName.jspy)`);
95+
console.log(` :\> jspython --file=(fileName.jspy)`);
96+
console.log(` :\> jspython --file=(fileName.jspy) --srcRoot=src`);
97+
console.log(' ');
98+
return;
9099
}
91100

92101
if (options.output) {
@@ -95,25 +104,35 @@ async function main() {
95104

96105
console.log = function () {
97106
const req = new RegExp('\\x1b\\[\\d\\dm', 'g');
98-
logFile.write(util.format.apply(null, Array.from(arguments).map(a => a && a.replace ? a.replace(req, '') : a)) + '\n');
107+
logFile.write(
108+
util.format.apply(
109+
null,
110+
Array.from(arguments).map(a => (a && a.replace ? a.replace(req, '') : a))
111+
) + '\n'
112+
);
99113
logStdout.write(util.format.apply(null, arguments) + '\n');
100-
}
114+
};
101115
console.error = console.log;
102116
}
103117

104118
if (options.file) {
105-
let fileName = `${options.srcRoot}${options.file}`;
119+
let fileName = `${options.srcRoot || ''}${options.file}`;
106120

107121
// try to check if file exists in 'src' folder
108122
if (!fs.existsSync(fileName)) {
109123
fileName = `src/${options.file}`;
110124
}
111125

112126
const scripts = fs.readFileSync(fileName, 'utf8');
113-
console.log(interpreter.jsPythonInfo())
114-
console.log(`> ${options.file}`)
127+
console.log(interpreter.jsPythonInfo());
128+
console.log(`> ${options.file}`);
115129
try {
116-
const res = await interpreter.evaluate(scripts, initialScope, options.entryFunction || undefined, options.file);
130+
const res = await interpreter.evaluate(
131+
scripts,
132+
initialScope,
133+
options.entryFunction || undefined,
134+
options.file
135+
);
117136

118137
if (!!res || res === 0) {
119138
console.log('>', res);
@@ -125,5 +144,4 @@ async function main() {
125144
}
126145
}
127146

128-
main()
129-
.catch(e => console.log('error:', e?.message || e))
147+
main().catch(e => console.log('error:', e?.message || e));

‎src/jspython-node.ts

Copy file name to clipboardExpand all lines: src/jspython-node.ts
+55-31Lines changed: 55 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -11,18 +11,21 @@ type NodeJsInterpreter = Interpreter & { evaluateFile: (fileName: string) => Pro
1111
const context: any = {
1212
asserts: [],
1313
params: {}
14-
}
15-
16-
initialScope.assert = (condition: boolean, name?: string, description?: string) => context.asserts.push({ condition, name, description });
17-
initialScope.showAsserts = () => console.table(context.asserts);
18-
initialScope.params = (name: string) => {
19-
const value = context.params[name];
20-
return value === undefined ? null : value;
14+
};
15+
16+
initialScope.assert = (condition: boolean, name?: string, description?: string) =>
17+
context.asserts.push({ condition, name, description });
18+
initialScope.showAsserts = () => console.table(context.asserts);
19+
initialScope.params = (name: string) => {
20+
const value = context.params[name];
21+
return value === undefined ? null : value;
22+
};
23+
24+
export function jsPythonForNode(
25+
options: InterpreterOptions = {
26+
srcRoot: ''
2127
}
22-
23-
export function jsPythonForNode(options: InterpreterOptions = {
24-
srcRoot: ''
25-
}): NodeJsInterpreter {
28+
): NodeJsInterpreter {
2629
const interpreter: NodeJsInterpreter = jsPython() as NodeJsInterpreter;
2730
Object.assign(context.params, options.params);
2831

@@ -32,26 +35,30 @@ export function jsPythonForNode(options: InterpreterOptions = {
3235

3336
const evaluate = interpreter.evaluate;
3437

35-
interpreter.evaluate = async function(script: string, evaluationContext?: object | undefined, entryFunctionName?: string | undefined, moduleName?: string | undefined) {
38+
interpreter.evaluate = async function (
39+
script: string,
40+
evaluationContext?: object | undefined,
41+
entryFunctionName?: string | undefined,
42+
moduleName?: string | undefined
43+
) {
3644
context.asserts.length = 0;
37-
await initialize(options.srcRoot);
45+
await initialize(options.srcRoot || '');
3846
return evaluate.call(interpreter, script, evaluationContext, entryFunctionName, moduleName);
39-
}
47+
};
4048

41-
interpreter.evaluateFile = function(filePath: string, context = {}) {
49+
interpreter.evaluateFile = function (filePath: string, context = {}) {
4250
const script = getScript(filePath);
4351
return interpreter.evaluate(script, context, options.entryFunction);
44-
}
52+
};
4553

4654
return interpreter;
4755

48-
4956
function moduleLoader(filePath: string): Promise<string> {
5057
filePath = trimChar(trimChar(filePath, '/'), '.');
51-
let fileName = `${options.srcRoot}${filePath}.jspy`;
58+
let fileName = `${options.srcRoot || ''}${filePath}.jspy`;
5259

5360
if (!fs.existsSync(fileName)) {
54-
fileName = `${options.srcRoot}${filePath}`;
61+
fileName = `${options.srcRoot || ''}${filePath}`;
5562
}
5663

5764
if (!fs.existsSync(fileName)) {
@@ -62,26 +69,44 @@ export function jsPythonForNode(options: InterpreterOptions = {
6269
const script = fs.readFileSync(fileName, 'utf8');
6370
return Promise.resolve(script);
6471
} catch (e) {
65-
console.log('* module loader error ', (e as Error)?.message || e)
72+
console.log('* module loader error ', (e as Error)?.message || e);
6673
return Promise.reject(e);
6774
}
6875
}
6976

7077
/**@type {PackageLoader} */
7178
function packageLoader(packageName: string): any {
7279
try {
73-
if (['fs', 'path', 'readline', 'timers', 'child_process', 'util', 'zlib', 'stream', 'net', 'https', 'http', 'events', 'os', 'buffer']
74-
.includes(packageName)) {
75-
return require(packageName)
80+
if (
81+
[
82+
'fs',
83+
'path',
84+
'readline',
85+
'timers',
86+
'child_process',
87+
'util',
88+
'zlib',
89+
'stream',
90+
'net',
91+
'https',
92+
'http',
93+
'events',
94+
'os',
95+
'buffer'
96+
].includes(packageName)
97+
) {
98+
return require(packageName);
7699
}
77100

78-
if (packageName.toLowerCase().endsWith('.js') || packageName.toLowerCase().endsWith('.json')) {
79-
return require(`${rootFolder}/${options.srcRoot}${packageName}`)
101+
if (
102+
packageName.toLowerCase().endsWith('.js') ||
103+
packageName.toLowerCase().endsWith('.json')
104+
) {
105+
return require(`${rootFolder}/${options.srcRoot || ''}${packageName}`);
80106
}
81107

82108
return require(`${rootFolder}/node_modules/${packageName}`);
83-
}
84-
catch (err) {
109+
} catch (err) {
85110
console.log('Import Error: ', (err as Error)?.message ?? err);
86111
throw err;
87112
}
@@ -90,15 +115,14 @@ export function jsPythonForNode(options: InterpreterOptions = {
90115

91116
function getScript(fileName: string): string {
92117
if (!fs.existsSync(fileName)) {
93-
throw Error(`File not found`)
118+
throw Error(`File not found`);
94119
}
95120

96121
const scripts = fs.readFileSync(fileName, 'utf8');
97122
return scripts;
98123
}
99124

100125
async function initialize(baseSource: string) {
101-
102126
// process app.js (if exists)
103127
// - run _init
104128
// - delete _ init
@@ -107,9 +131,9 @@ async function initialize(baseSource: string) {
107131
// - load content into 'app'
108132

109133
let appJsPath = `${rootFolder}/${baseSource}app.js`;
110-
console.log({ rootFolder, baseSource })
134+
console.log({ rootFolder, baseSource });
111135
if (!fs.existsSync(appJsPath)) {
112-
appJsPath = `${rootFolder}/src/app.js`
136+
appJsPath = `${rootFolder}/src/app.js`;
113137
}
114138

115139
if (fs.existsSync(appJsPath)) {

‎src/types.ts

Copy file name to clipboardExpand all lines: src/types.ts
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
export interface InterpreterOptions {
22
file?: string;
3-
srcRoot: string;
3+
srcRoot?: string;
44
entryFunction?: string;
55
version?: boolean;
66
output?: string;

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.