Skip to content

Commit 7a28e8b

Browse files
authored
v0.9.0 (#19)
**Main changes**: 1. `cli` renamed to `$` 1. `style` (`ansi-colors`) removed in favour of using “CSS” in `echo` 1. `exit` removed in favour of `$.exit` 1. `$.stdin` (`$.no*`)
1 parent 350a26f commit 7a28e8b

File tree

124 files changed

+1713
-6500
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

124 files changed

+1713
-6500
lines changed

README.md

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,17 @@ s.run("sleep 2; echo 2");
1919
s.run("sleep 3; echo 3");
2020

2121
const name= "foo bar";
22-
s.mkdir(cli.xdg.temp(name));
22+
s.mkdir($.xdg.temp(name));
2323
```
24-
…also see [examples](./examples).
24+
…also see [examples](./examples). You can also use `nodejsscript -e`/`nodejsscript -p` in shell:
25+
```bash
26+
curl https://api.spacexdata.com/v4/launches/latest | nodejsscript -p 'Object.entries($.nojq).filter(([_,v])=> Array.isArray(v))'
27+
```
28+
…see [examples](./examples/eval_print.md) again.
29+
30+
## Quick links/info
31+
- migration from *0.8.\**: see [API changes 0.8 → 0.9](#api-changes-08--09)
32+
- potencial changes for *1.x.y*: see [issues](https://github.com/jaandrle/nodejsscript/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc)
2533

2634
## Installation
2735

@@ -30,10 +38,9 @@ s.mkdir(cli.xdg.temp(name));
3038

3139
## Goods
3240
[s #shelljs](./docs/modules/s.md)
33-
· [cli](./docs/modules/cli.md) ([cli.api() #sade](./docs/modules/cli.md#api), [cli.read()](./docs/modules/cli.md#read), [cli.xdg](./docs/modules/xdg_.xdg.md), …)
41+
· [$](./docs/modules/.md) ([$.api() #sade](./docs/modules/.md#api), [$.read()](./docs/modules/.md#read), [$.xdg](./docs/modules/xdg_.xdg.md), …)
3442
· [echo()](./docs/README.md#echo)
3543
· [fetch() #node-fetch](./docs/README.md#fetch)
36-
· [style #ansi-colors](./docs/modules/style.md)
3744
· [pipe()](./docs/README.md#pipe)
3845
· [cyclicLoop()](./docs/README.md#cyclicloop)
3946

@@ -79,11 +86,18 @@ Note that there are also built-in `'node:*'` modules:
7986
import { setTimeout } from "node:timers/promises";
8087
import { join, resolve } from "node:path";
8188

82-
//current file url
89+
//.current file url
8390
import.meta.url;
84-
//url to path
91+
//.url to path
8592
import { fileURLToPath } from "node:url";
8693
const file_path= fileURLToPath(import.meta.url);
94+
// url is supported! (see relative reading)
95+
s.cat(new URL('relative_file', import.meta.url));
96+
97+
//.crypto utils
98+
import { randomUUID } from "node:crypto";
99+
100+
//
87101
```
88102
…and more, see [Node.js v17.9.1 Documentation](https://nodejs.org/docs/latest-v17.x/api/documentation.html#stability-overview).
89103
@@ -134,6 +148,10 @@ echo(s.cat("package.json").grep("name"));
134148
// or
135149
echo(s.grep("name", "package.json"));
136150
```
151+
## API changes *0.8* → **0.9**
152+
1. `cli` renamed to `$`
153+
1. `style` (`ansi-colors`) removed in favour of using “CSS” in `echo`
154+
1. `exit` removed in favour of `$.exit`
137155
138156
## Contribute
139157
- [Contributor Covenant Code of Conduc](./CODE_OF_CONDUCT.md)

_index.d.ts

Lines changed: 13 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,20 @@
11
/** @category Public */
2-
export { echo } from './src/echo.d';
3-
/** @category Public */
4-
export { cli, xdg_, __sade } from './src/cli.d';
2+
export { echo, EchoFunction, css_rules, css_colors } from './src/echo.d';
3+
export { xdg_, __sade, _env, _exit } from './src/$.d';
4+
/**
5+
* Contains configuration for current script and methods
6+
* for managing arguments.
7+
*
8+
* You can also use `$[0]`–`$[n]` for getting nth script argument (compare to bashs `$0`–`$n`).
9+
* @category Public
10+
*/
11+
export { Dollar as $ } from './src/$.d';
512
/**
613
* Function similar to [Ramda `R.pipe`](https://ramdajs.com/docs/#pipe). Provides functional way to combine commands/functions.
714
*
815
* ```js
916
* pipe(
1017
* Number,
11-
* v=> style.greenBright(v+1),
1218
* v=> `Result is: ${v}`,
1319
* echo
1420
* )(await question("Choose number:"));
@@ -27,7 +33,7 @@ export function pipe(...funs: Function[]): (input: any)=> any;
2733
* · [ls](https://github.com/shelljs/shelljs#lsoptions-path-) · [mkdir](https://github.com/shelljs/shelljs#mkdiroptions-dir--dir-) · [mv](https://github.com/shelljs/shelljs#mvoptions--source--source--dest) · [pwd](https://github.com/shelljs/shelljs#pwd)
2834
* · [rm](https://github.com/shelljs/shelljs#rmoptions-file--file-) · [sed](https://github.com/shelljs/shelljs#sedoptions-search_regex-replacement-file--file-) · [sort](https://github.com/shelljs/shelljs#sortoptions-file--file-)
2935
* · [tail](https://github.com/shelljs/shelljs#tail-n-num-file--file-) · [test](https://github.com/shelljs/shelljs#testexpression) · [touch](https://github.com/shelljs/shelljs#touchoptions-file--file-)
30-
* · [uniq](https://github.com/shelljs/shelljs#uniqoptions-input-output) · [which](https://github.com/shelljs/shelljs#whichcommand) · [exit](https://github.com/shelljs/shelljs#exitcode) · [error](https://github.com/shelljs/shelljs#error) · [errorCode](https://github.com/shelljs/shelljs#errorcode)
36+
* · [uniq](https://github.com/shelljs/shelljs#uniqoptions-input-output) · [which](https://github.com/shelljs/shelljs#whichcommand) · [error](https://github.com/shelljs/shelljs#error) · [errorCode](https://github.com/shelljs/shelljs#errorcode)
3137
*
3238
* ```js
3339
* s.cat("./package.json").grep("version");
@@ -41,23 +47,12 @@ export function pipe(...funs: Function[]): (input: any)=> any;
4147
* **Changes/recommenctions:**
4248
* - use {@link echo} instead of `s.echo`, this was changed to `s.ShellString` for easy file writing without logging to console `s.echo("Data").to("file.txt")`.
4349
* - use {@link s.RunFunction 'run()'}/{@link s.RunAsyncFunction 'runA()'} instead of `s.exec`, because of options for passing arguments in secure way.
44-
* - use {@link s.DollarFunction '$()'} instead of `s.set()`, because `$()` allows chaining (you can also access config with {@link cli}s `.is_*` keys).
45-
* - use {@link cli.xdg}`.temp` instead of `s.tempdir()` – the `cli.xdg.*` provides more paths than just temp directory.
50+
* - use {@link s.DollarFunction '$()'} instead of `s.set()`, because `$()` allows chaining (you can also access config with {@link $}s `.is_*` keys).
51+
* - use {@link $.xdg}`.temp` instead of `s.tempdir()` – the `$.xdg.*` provides more paths than just temp directory.
4652
* @category Public
4753
*/
4854
export * as s from './src/shelljs.d';
4955

50-
import * as style from 'ansi-colors';
51-
/**
52-
* The [doowb/ansi-colors](https://github.com/doowb/ansi-colors) package as `style` namespace.
53-
* ```js
54-
* style.theme({ info: style.blue });
55-
* echo(style.info('Hello world!'));
56-
* ```
57-
* @category Public
58-
*/
59-
export { style };
60-
6156
import * as __fetch from 'node-fetch';
6257
/**
6358
* A wrapper around the [node-fetch](https://www.npmjs.com/package/node-fetch) package.

bin/cli.mjs

Lines changed: 73 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -2,53 +2,88 @@
22
import { join, resolve } from "node:path";
33
import { argv } from "node:process";
44
import url from "node:url";
5-
import "../index.js";/* global echo, exit, cli, s, style, pipe */
5+
import { randomUUID } from "node:crypto";
6+
import "../index.js";/* global echo, $, s, pipe */
7+
import { stdin as key_stdin } from "../src/keys.js";
68

9+
process.on('uncaughtException', printError);
710
(async function main(){
811
const candidate= argv.splice(2, 1)[0];
9-
if(candidate[0]==="-") handleMyArgvs(candidate);
12+
let filepath_tmp;
13+
if(candidate[0]==="-")
14+
filepath_tmp= handleMyArgvs(candidate);
15+
const is_tmp= filepath_tmp !== undefined;
1016

11-
const filepath= candidate.startsWith('/') ? candidate : ( candidate.startsWith('file:///') ? url.fileURLToPath(candidate) : resolve(candidate) );
17+
const filepath= is_tmp ?
18+
filepath_tmp : (
19+
candidate.startsWith('/') ?
20+
candidate :
21+
( candidate.startsWith('file:///') ?
22+
url.fileURLToPath(candidate) :
23+
resolve(candidate) ));
1224
argv[1]= filepath;
25+
$.push(...argv.slice(1));
26+
await $.stdin[key_stdin]();
1327
try{
14-
if(!s.test("-f", filepath)) cli.error(`File '${candidate}' not found.`);
28+
if(!s.test("-f", filepath)) $.error(`File '${candidate}' not found.`);
1529
await import(url.pathToFileURL(filepath).toString());
30+
if(is_tmp) s.rm("-f", filepath_tmp);
1631
} catch(e){
17-
const error= e instanceof cli.Error ? e.message : e;
18-
console.error(error);
19-
exit(1);
32+
if(is_tmp) s.rm("-f", filepath_tmp);
33+
printError(e);
2034
}
2135
})();
2236

2337
function handleMyArgvs(candidate){
2438
if(['--version', '-v', '-V'].includes(candidate)){
2539
echo(info("version")[0]);
26-
return exit(0);
40+
return $.exit(0);
2741
}
2842
if(['--help', '-h'].includes(candidate))
2943
return printUsage();
3044
if("--global-jsconfig"===candidate)
3145
return jsconfigTypes();
46+
if(['-e', '--eval'].includes(candidate))
47+
return runEval(0);
48+
if(['-p', '--print'].includes(candidate))
49+
return runEval(1);
50+
}
51+
function printError(e){
52+
if(e instanceof $.Error){
53+
console.error(e.message);
54+
return $.exit(1);
55+
}
56+
Error.print(e);
57+
$.exit(e.exitCode || 1);
3258
}
3359
function printUsage(){
34-
style.theme({ n: style.blueBright, v: style.greenBright, info: style.yellow, code: style.italic });
3560
const [ n, v, d ]= info("name", "version", "description");
36-
echo(`
37-
${style.n(n)}@${style.v(v)}
38-
${d}
39-
${style.info("Usage")}:
40-
${n} [options] <script>
41-
${style.info('Options')}:
42-
--version, -v print current zx version
43-
--help, -h print help
44-
--global-jsconfig [add] woraround for type checking of non-package scripts
45-
${style.info('Examples')}:
46-
${n} script.js
47-
${n} --help
48-
${style.info('Usage in scripts')}:
49-
Just start the file with: ${style.code('#!/usr/bin/env nodejsscript')}
50-
`);
51-
exit(0);
61+
const css= echo.css(
62+
"* { margin-left: 2; }",
63+
".n { color: lightblue; }",
64+
".v { color: lightgreen; margin-left: 0; }",
65+
".code { font-style: italic; margin-left: 0; }",
66+
".H { color: yellow; }",
67+
".T { margin-left: 4; }"
68+
);
69+
echo(`%c${n}@%c${v}`, css.n, css.v);
70+
echo(`%c${d}`, css.T);
71+
echo(`%cUsage%c:`, css.H);
72+
echo(`%c${n} [options] <script>`, css.T);
73+
echo(`%cOptions%c:`, css.H);
74+
echo(`%c --version, -v print current ${n} version`, css.T);
75+
echo("%c --help, -h print help", css.T);
76+
echo("%c --eval, -e similar to `node -e …`", css.T);
77+
echo("%c --print, -p similar to `node -p …`, infact (for now?) it wraps argument by `echo` function (splits givent string by ';' and wraps last non-empty part)", css.T);
78+
echo("%c--global-jsconfig [add] woraround for type checking of non-package scripts", css.T);
79+
echo("%cExamples%c:", css.H);
80+
echo(`%c${n} script.js`, css.T);
81+
echo(`%c${n} --help`, css.T);
82+
echo(`%cls | ${n} -p '$.stdin.text().replaceAll("A", "AAAA")'`, css.T);
83+
echo(`%cls | ${n} -p '$.stdin.lines().filter(line=> line[0]==="R").map(line=> \`file: \${line}\`)'`, css.T);
84+
echo("%cUsage in scripts%c:", css.H);
85+
echo("%cJust start the file with: %c#!/usr/bin/env nodejsscript", css.T, css.code);
86+
$.exit(0);
5287
}
5388
function info(...keys){
5489
const info= s.cat(url.fileURLToPath(join(import.meta.url, "../../package.json"))).xargs(JSON.parse);
@@ -70,5 +105,17 @@ function jsconfigTypes(){
70105
s.ShellString,
71106
s=> s.to("jsconfig.json")
72107
)(jsconfig_file);
73-
exit(0);
108+
$.exit(0);
109+
}
110+
function runEval(is_print){
111+
let input= argv.splice(2, 1)[0];
112+
if(is_print){
113+
let out_arr= input.split(";").reverse();
114+
if(out_arr[0].trim()==="") out_arr.shift();
115+
out_arr[0]= `echo(${out_arr[0]})`;
116+
input= out_arr.reverse().join(";");
117+
}
118+
const filepath= $.xdg.temp`nodejsscript-${randomUUID()}.mjs`;
119+
s.echo(input).to(filepath);
120+
return filepath;
74121
}

0 commit comments

Comments
 (0)