Skip to content

Commit

Permalink
v0.9.0 (#19)
Browse files Browse the repository at this point in the history
**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*`)
  • Loading branch information
jaandrle authored Nov 29, 2022
1 parent 350a26f commit 7a28e8b
Show file tree
Hide file tree
Showing 124 changed files with 1,713 additions and 6,500 deletions.
30 changes: 24 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,17 @@ s.run("sleep 2; echo 2");
s.run("sleep 3; echo 3");

const name= "foo bar";
s.mkdir(cli.xdg.temp(name));
s.mkdir($.xdg.temp(name));
```
…also see [examples](./examples).
…also see [examples](./examples). You can also use `nodejsscript -e`/`nodejsscript -p` in shell:
```bash
curl https://api.spacexdata.com/v4/launches/latest | nodejsscript -p 'Object.entries($.nojq).filter(([_,v])=> Array.isArray(v))'
```
…see [examples](./examples/eval_print.md) again.

## Quick links/info
- migration from *0.8.\**: see [API changes 0.8 → 0.9](#api-changes-08--09)
- potencial changes for *1.x.y*: see [issues](https://github.com/jaandrle/nodejsscript/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc)

## Installation

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

## Goods
[s #shelljs](./docs/modules/s.md)
· [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), …)
· [$](./docs/modules/.md) ([$.api() #sade](./docs/modules/.md#api), [$.read()](./docs/modules/.md#read), [$.xdg](./docs/modules/xdg_.xdg.md), …)
· [echo()](./docs/README.md#echo)
· [fetch() #node-fetch](./docs/README.md#fetch)
· [style #ansi-colors](./docs/modules/style.md)
· [pipe()](./docs/README.md#pipe)
· [cyclicLoop()](./docs/README.md#cyclicloop)

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

//current file url
//.current file url
import.meta.url;
//url to path
//.url to path
import { fileURLToPath } from "node:url";
const file_path= fileURLToPath(import.meta.url);
// url is supported! (see relative reading)
s.cat(new URL('relative_file', import.meta.url));

//.crypto utils
import { randomUUID } from "node:crypto";

//
```
…and more, see [Node.js v17.9.1 Documentation](https://nodejs.org/docs/latest-v17.x/api/documentation.html#stability-overview).
Expand Down Expand Up @@ -134,6 +148,10 @@ echo(s.cat("package.json").grep("name"));
// or
echo(s.grep("name", "package.json"));
```
## API changes *0.8* → **0.9**
1. `cli` renamed to `$`
1. `style` (`ansi-colors`) removed in favour of using “CSS” in `echo`
1. `exit` removed in favour of `$.exit`
## Contribute
- [Contributor Covenant Code of Conduc](./CODE_OF_CONDUCT.md)
Expand Down
31 changes: 13 additions & 18 deletions _index.d.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
/** @category Public */
export { echo } from './src/echo.d';
/** @category Public */
export { cli, xdg_, __sade } from './src/cli.d';
export { echo, EchoFunction, css_rules, css_colors } from './src/echo.d';
export { xdg_, __sade, _env, _exit } from './src/$.d';
/**
* Contains configuration for current script and methods
* for managing arguments.
*
* You can also use `$[0]`–`$[n]` for getting nth script argument (compare to bashs `$0`–`$n`).
* @category Public
*/
export { Dollar as $ } from './src/$.d';
/**
* Function similar to [Ramda `R.pipe`](https://ramdajs.com/docs/#pipe). Provides functional way to combine commands/functions.
*
* ```js
* pipe(
* Number,
* v=> style.greenBright(v+1),
* v=> `Result is: ${v}`,
* echo
* )(await question("Choose number:"));
Expand All @@ -27,7 +33,7 @@ export function pipe(...funs: Function[]): (input: any)=> any;
* · [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)
* · [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-)
* · [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-)
* · [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)
* · [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)
*
* ```js
* s.cat("./package.json").grep("version");
Expand All @@ -41,23 +47,12 @@ export function pipe(...funs: Function[]): (input: any)=> any;
* **Changes/recommenctions:**
* - 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")`.
* - use {@link s.RunFunction 'run()'}/{@link s.RunAsyncFunction 'runA()'} instead of `s.exec`, because of options for passing arguments in secure way.
* - use {@link s.DollarFunction '$()'} instead of `s.set()`, because `$()` allows chaining (you can also access config with {@link cli}s `.is_*` keys).
* - use {@link cli.xdg}`.temp` instead of `s.tempdir()` – the `cli.xdg.*` provides more paths than just temp directory.
* - use {@link s.DollarFunction '$()'} instead of `s.set()`, because `$()` allows chaining (you can also access config with {@link $}s `.is_*` keys).
* - use {@link $.xdg}`.temp` instead of `s.tempdir()` – the `$.xdg.*` provides more paths than just temp directory.
* @category Public
*/
export * as s from './src/shelljs.d';

import * as style from 'ansi-colors';
/**
* The [doowb/ansi-colors](https://github.com/doowb/ansi-colors) package as `style` namespace.
* ```js
* style.theme({ info: style.blue });
* echo(style.info('Hello world!'));
* ```
* @category Public
*/
export { style };

import * as __fetch from 'node-fetch';
/**
* A wrapper around the [node-fetch](https://www.npmjs.com/package/node-fetch) package.
Expand Down
99 changes: 73 additions & 26 deletions bin/cli.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,53 +2,88 @@
import { join, resolve } from "node:path";
import { argv } from "node:process";
import url from "node:url";
import "../index.js";/* global echo, exit, cli, s, style, pipe */
import { randomUUID } from "node:crypto";
import "../index.js";/* global echo, $, s, pipe */
import { stdin as key_stdin } from "../src/keys.js";

process.on('uncaughtException', printError);
(async function main(){
const candidate= argv.splice(2, 1)[0];
if(candidate[0]==="-") handleMyArgvs(candidate);
let filepath_tmp;
if(candidate[0]==="-")
filepath_tmp= handleMyArgvs(candidate);
const is_tmp= filepath_tmp !== undefined;

const filepath= candidate.startsWith('/') ? candidate : ( candidate.startsWith('file:///') ? url.fileURLToPath(candidate) : resolve(candidate) );
const filepath= is_tmp ?
filepath_tmp : (
candidate.startsWith('/') ?
candidate :
( candidate.startsWith('file:///') ?
url.fileURLToPath(candidate) :
resolve(candidate) ));
argv[1]= filepath;
$.push(...argv.slice(1));
await $.stdin[key_stdin]();
try{
if(!s.test("-f", filepath)) cli.error(`File '${candidate}' not found.`);
if(!s.test("-f", filepath)) $.error(`File '${candidate}' not found.`);
await import(url.pathToFileURL(filepath).toString());
if(is_tmp) s.rm("-f", filepath_tmp);
} catch(e){
const error= e instanceof cli.Error ? e.message : e;
console.error(error);
exit(1);
if(is_tmp) s.rm("-f", filepath_tmp);
printError(e);
}
})();

function handleMyArgvs(candidate){
if(['--version', '-v', '-V'].includes(candidate)){
echo(info("version")[0]);
return exit(0);
return $.exit(0);
}
if(['--help', '-h'].includes(candidate))
return printUsage();
if("--global-jsconfig"===candidate)
return jsconfigTypes();
if(['-e', '--eval'].includes(candidate))
return runEval(0);
if(['-p', '--print'].includes(candidate))
return runEval(1);
}
function printError(e){
if(e instanceof $.Error){
console.error(e.message);
return $.exit(1);
}
Error.print(e);
$.exit(e.exitCode || 1);
}
function printUsage(){
style.theme({ n: style.blueBright, v: style.greenBright, info: style.yellow, code: style.italic });
const [ n, v, d ]= info("name", "version", "description");
echo(`
${style.n(n)}@${style.v(v)}
${d}
${style.info("Usage")}:
${n} [options] <script>
${style.info('Options')}:
--version, -v print current zx version
--help, -h print help
--global-jsconfig [add] woraround for type checking of non-package scripts
${style.info('Examples')}:
${n} script.js
${n} --help
${style.info('Usage in scripts')}:
Just start the file with: ${style.code('#!/usr/bin/env nodejsscript')}
`);
exit(0);
const css= echo.css(
"* { margin-left: 2; }",
".n { color: lightblue; }",
".v { color: lightgreen; margin-left: 0; }",
".code { font-style: italic; margin-left: 0; }",
".H { color: yellow; }",
".T { margin-left: 4; }"
);
echo(`%c${n}@%c${v}`, css.n, css.v);
echo(`%c${d}`, css.T);
echo(`%cUsage%c:`, css.H);
echo(`%c${n} [options] <script>`, css.T);
echo(`%cOptions%c:`, css.H);
echo(`%c --version, -v print current ${n} version`, css.T);
echo("%c --help, -h print help", css.T);
echo("%c --eval, -e similar to `node -e …`", css.T);
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);
echo("%c--global-jsconfig [add] woraround for type checking of non-package scripts", css.T);
echo("%cExamples%c:", css.H);
echo(`%c${n} script.js`, css.T);
echo(`%c${n} --help`, css.T);
echo(`%cls | ${n} -p '$.stdin.text().replaceAll("A", "AAAA")'`, css.T);
echo(`%cls | ${n} -p '$.stdin.lines().filter(line=> line[0]==="R").map(line=> \`file: \${line}\`)'`, css.T);
echo("%cUsage in scripts%c:", css.H);
echo("%cJust start the file with: %c#!/usr/bin/env nodejsscript", css.T, css.code);
$.exit(0);
}
function info(...keys){
const info= s.cat(url.fileURLToPath(join(import.meta.url, "../../package.json"))).xargs(JSON.parse);
Expand All @@ -70,5 +105,17 @@ function jsconfigTypes(){
s.ShellString,
s=> s.to("jsconfig.json")
)(jsconfig_file);
exit(0);
$.exit(0);
}
function runEval(is_print){
let input= argv.splice(2, 1)[0];
if(is_print){
let out_arr= input.split(";").reverse();
if(out_arr[0].trim()==="") out_arr.shift();
out_arr[0]= `echo(${out_arr[0]})`;
input= out_arr.reverse().join(";");
}
const filepath= $.xdg.temp`nodejsscript-${randomUUID()}.mjs`;
s.echo(input).to(filepath);
return filepath;
}
Loading

0 comments on commit 7a28e8b

Please sign in to comment.