8000 added src root changes · jspython-dev/jspython-cli@554d811 · GitHub
[go: up one dir, main page]

Skip to content

Commit 554d811

Browse files
committed
added src root changes
1 parent 5fb674a commit 554d811

File tree

4 files changed

+135
-25
lines changed

4 files changed

+135
-25
lines changed

LICENSE

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
BSD 3-Clause License
2+
3+
Copyright (c) 2021, FalconSoft Ltd
4+
All rights reserved.
5+
6+
Redistribution and use in source and binary forms, with or without
7+
modification, are permitted provided that the following conditions are met:
8+
9+
1. Redistributions of source code must retain the above copyright notice, this
10+
list of conditions and the following disclaimer.
11+
12+
2. Redistributions in binary form must reproduce the above copyright notice,
13+
this list of conditions and the following disclaimer in the documentation
14+
and/or other materials provided with the distribution.
15+
16+
3. Neither the name of the copyright holder nor the names of its
17+
contributors may be used to endorse or promote products derived from
18+
this software without specific prior written permission.
19+
20+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

README.md

Lines changed: 57 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,21 +2,21 @@
22

33
We provide a command line interface to run [JSPython](https://github.com/jspython-dev/jspython) scripts
44

5-
### Install from NPM
5+
## Install from NPM
66

77
```
88
npm install -g jspython-cli
99
```
1010

11-
### Run in terminal
11+
## Run in terminal
1212
```
1313
jspython path/to/jspython/file
1414
jspython --file path/to/jspython/file
1515
jspython --file=test.jspy
1616
1717
```
1818

19-
### Pass parameters to script
19+
## Pass parameters to script
2020
In CLI
2121
```
2222
jspython --file=path/to/jspython/file --param1=value --param
@@ -28,15 +28,67 @@ params("param1") == "value" # true
2828
params("param") == false # true
2929
```
3030

31-
### Save evaluate log into file
31+
## Run file
32+
```
33+
jspython --file=path/to/jspython/file.jspy
34+
```
35+
36+
## Run file and log into file
3237
```
3338
jspython --file=path/to/jspython/file.jspy --output=path/to/log.txt
3439
```
3540

36-
### Development
41+
## Run specific function from the file
42+
```
43+
jspython --file=path/to/jspython/file.jspy --entryFunction=myFunc1
44+
```
45+
or
46+
```
47+
jspython -f=path/to/jspython/file.jspy -e=myFunc1
48+
```
49+
50+
51+
52+
## Run file when you have your source code in a nested folder
53+
```
54+
jspython --file=path/to/jspython/file.jspy --srcRoot=src
55< F438 code class="diff-text syntax-highlighted-line addition">+
```
56+
In this case it expects package.json and node_modules on the root level
57+
58+
```
59+
-|- .git
60+
-|- .vscode
61+
-|- .gitignore
62+
-|- .ws
63+
-|- node_modules
64+
-|- src
65+
-|-my_code.jspy
66+
-|- package.json
67+
```
68+
69+
Then, from a root folder you can:
70+
> jspython --file=my_code.jspy --srcRoot=src --param1=some_Value
71+
72+
or
73+
74+
> jspython -f=my_code.jspy -s=src --param1=some_Value
75+
76+
77+
## Show version
78+
79+
> jspython -v
80+
81+
or
82+
83+
> jspython --version
84+
85+
## Development
3786
Run example using node. (Works only if you have build project `npm run build`)
3887
```
3988
node ./bin/jspython --file=../jspython-examples/axios-test.jspy
4089
node ./bin/jspython --file ../jspython-examples/parse.jspy
4190
```
4291

92+
# License
93+
A permissive [BSD 3-Clause License](https://github.com/jspython-dev/jspython-cli/blob/master/LICENSE) (c) FalconSoft Ltd.
94+

package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "jspython-cli",
3-
"version": "2.0.11",
3+
"version": "2.0.14",
44
"description": "CLI for jspython. Allows you to run jspython (*.jspy) files",
55
"main": "src/index.ts",
66
"bin": {
@@ -30,7 +30,7 @@
3030
"homepage": "https://github.com/jspython-dev/jspython-cli#readme",
3131
"dependencies": {
3232
"arg": "^4.1.2",
33-
"jspython-interpreter": "~2.0.10"
33+
"jspython-interpreter": "~2.0.13"
3434
},
3535
"devDependencies": {
3636
"rollup": "^1.27.13",

src/index.ts

Lines changed: 47 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -9,21 +9,34 @@ const context: any = {
99
params: {}
1010
}
1111

12-
const appFolder = process.cwd().split('\\').join('/');
1312

1413
const initialScope: Record<string, any> = {
1514
app: {}
1615
};
1716

17+
const rootFolder = process.cwd().split('\\').join('/');
1818
const interpreter: Interpreter = jsPython() as Interpreter;
19+
const options = getOptionsFromArguments(process.argv);
1920

2021
run();
2122

22-
async function initialize() {
23+
function trimChar(text: string, charToRemove: string): string {
24+
while (text.charAt(0) == charToRemove) {
25+
text = text.substring(1);
26+
}
27+
28+
while (text.charAt(text.length - 1) == charToRemove) {
29+
text = text.substring(0, text.length - 1);
30+
}
31+
32+
return text;
33+
}
34+
35+
async function initialize(baseSource: string) {
2336
// process app.json (if exists)
2437
// add configuration to the 'app'
25-
if (fs.existsSync(`${appFolder}/app.json`)) {
26-
const app = require(`${appFolder}/app.json`);
38+
if (fs.existsSync(`${rootFolder}/${baseSource}app.json`)) {
39+
const app = require(`${rootFolder}/${baseSource}app.json`);
2740
initialScope.app = Object.assign(initialScope.app || {}, app);
2841
}
2942

@@ -33,8 +46,8 @@ async function initialize() {
3346
// - run _initAsync
3447
// - delete _initAsync
3548
// - load content into 'app'
36-
if (fs.existsSync(`${appFolder}/app.js`)) {
37-
const app = require(`${appFolder}/app.js`);
49+
if (fs.existsSync(`${rootFolder}/${baseSource}app.js`)) {
50+
const app = require(`${rootFolder}/${baseSource}app.js`);
3851

3952
if (typeof app._init == 'function') {
4053
app._init();
@@ -58,9 +71,6 @@ async function initialize() {
5871
}
5972

6073
async function run() {
61-
await initialize();
62-
63-
const options = getOptionsFromArguments(process.argv);
6474
if (options.version) {
6575
console.log(interpreter.jsPythonInfo());
6676
console.log(`JSPython cli v${(pkg || {}).version}\n`);
@@ -79,27 +89,40 @@ async function run() {
7989
console.error = console.log;
8090
}
8191

92+
await initialize(options.srcRoot);
93+
8294
if (options.file) {
95+
interpreter.registerFileLoader((jspyPath: any) => {
96+
console.log(' * file loader * ', rootFolder, jspyPath);
97+
return Promise.resolve({ sum: (x: number, y: number) => x + y });
98+
})
8399
interpreter.registerPackagesLoader(packageLoader as PackageLoader);
84-
const scripts = fs.readFileSync(options.file, 'utf8');
100+
const scripts = fs.readFileSync(`${options.srcRoot}${options.file}`, 'utf8');
85101
context.asserts.length = 0;
86102
console.log(interpreter.jsPythonInfo())
87103
console.log(`> ${options.file}`)
88-
const res = await interpreter.evaluate(scripts, initialScope, options.entryFunction || undefined, options.file);
89-
if (res !== null) {
90-
console.log(res);
104+
try {
105+
const res = await interpreter.evaluate(scripts, initialScope, options.entryFunction || undefined, options.file);
106+
if (res !== null) {
107+
console.log(res);
108+
}
109+
} catch (err) {
110+
console.log('JSPython execution failed: ', err?.message || err, err);
111+
throw err;
91112
}
92113
}
93114
}
94115

95116
function getOptionsFromArguments(rawArgs: string[]) {
96117
const args = arg({
97118
'--file': String,
119+
'--srcRoot': String,
98120
'--entryFunction': String,
99121
'--version': Boolean,
100122
'--output': String,
101123
'-f': '--file',
102-
'-ef': '--entryFunction',
124+
'-s': '--srcRoot',
125+
'-e': '--entryFunction',
103126
'-v': '--version',
104127
'-o': '--output'
105128
}, {
@@ -121,9 +144,15 @@ function getOptionsFromArguments(rawArgs: string[]) {
121144
file: args['--file'] || (rawArgs.length === 3 && !rawArgs[2].startsWith('-') ? rawArgs[2] : ''),
122145
version: args['--version'],
123146
output: args['--output'],
124-
entryFunction: args['--entryFunction'] E17D
147+
entryFunction: args['--entryFunction'],
148+
srcRoot: args['--srcRoot'] || ''
125149
};
126150

151+
res.srcRoot = trimChar(res.srcRoot || '', '/');
152+
if (res.srcRoot.length) {
153+
res.srcRoot = res.srcRoot + '/';
154+
}
155+
127156
context.params = { ...res, ...params };
128157

129158
return res;
@@ -138,13 +167,13 @@ function packageLoader(packageName: string): any {
138167
}
139168

140169
if (packageName.toLowerCase().endsWith('.js') || packageName.toLowerCase().endsWith('.json')) {
141-
return require(`${process.cwd().split('\\').join('/')}/${packageName}`)
170+
return require(`${rootFolder}/${options.srcRoot}${packageName}`)
142171
}
143172

144-
return require(`${process.cwd().split('\\').join('/')}/node_modules/${packageName}`);
173+
return require(`${rootFolder}/node_modules/${packageName}`);
145174
}
146175
catch (err) {
147-
console.log('Import Error: ', err);
176+
console.log('Import Error: ', err?.message || err);
148177
throw err;
149178
}
150179
}

0 commit comments

Comments
 (0)
0