Skip to content

Commit 13a3536

Browse files
committed
🔖 v0.5.0
1 parent bf2a671 commit 13a3536

9 files changed

Lines changed: 150 additions & 118 deletions

File tree

README.md

Lines changed: 32 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -6,20 +6,18 @@ This is done by using [shelljs/shelljs](https://github.com/shelljs/shelljs) libr
66
You can compare the final script code to `zx` example:
77
```javascript
88
#!/usr/bin/env nodejsscript
9-
import { exec, exec$, grep, echo } from "nodejsscript";
10-
echo(grep("name", "package.json"));
9+
import { s, echo } from "nodejsscript";
10+
echo(s.grep("name", "package.json"));
1111

12-
const branch= exec$("git branch --show-current");
13-
exec(`dep deploy --branch=${branch}`);
12+
s.exec("git branch --show-current").xargs(s.exec, "dep deploy --branch={}");
1413

15-
exec("sleep 1; echo 1");
16-
exec("sleep 2; echo 2");
17-
exec("sleep 3; echo 3");
14+
s.exec("sleep 1; echo 1");
15+
s.exec("sleep 2; echo 2");
16+
s.exec("sleep 3; echo 3");
1817

19-
import { mkdir, tempdir } from "nodejsscript";
2018
import { join } from "node:path";
2119
const name= "foo bar";
22-
mkdir(join(tempdir(), name));
20+
s.mkdir(join(s.tempdir(), name));
2321
```
2422

2523
## Installation
@@ -29,16 +27,7 @@ mkdir(join(tempdir(), name));
2927
1. `npm install https://github.com/jaandrle/nodejsscript --global`
3028

3129
## Goods
32-
[shelljs/shelljs](https://github.com/shelljs/shelljs):
33-
[cat](https://github.com/shelljs/shelljs#catoptions-file--file-) · [cd](https://github.com/shelljs/shelljs#cddir) · [chmod](https://github.com/shelljs/shelljs#chmodoptions-octal_mode--octal_string-file) · [cp](https://github.com/shelljs/shelljs#cpoptions-source--source--dest)
34-
· [pushd](https://github.com/shelljs/shelljs#pushdoptions-dir---n--n) · [popd](https://github.com/shelljs/shelljs#popdoptions--n--n) · [dirs](https://github.com/shelljs/shelljs#dirsoptions--n---n) · [exec](https://github.com/shelljs/shelljs#execcommand--options--callback)
35-
· [find](https://github.com/shelljs/shelljs#findpath--path-) · [grep](https://github.com/shelljs/shelljs#grepoptions-regex_filter-file--file-) · [head](https://github.com/shelljs/shelljs#head-n-num-file--file-) · [ln](https://github.com/shelljs/shelljs#lnoptions-source-dest)
36-
· [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)
37-
· [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-)
38-
· [tail](https://github.com/shelljs/shelljs#tail-n-num-file--file-) · [tempdir](https://github.com/shelljs/shelljs#tempdir) · [test](https://github.com/shelljs/shelljs#testexpression) · [touch](https://github.com/shelljs/shelljs#touchoptions-file--file-)
39-
· [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)
40-
| another libs: [cli()](#cli) · [chalk](#chalk-package) · [fetch()](#fetch)
41-
| this lib: [xarg()](#xarg) · [pipe()](#pipe) · [question()](#question) · [echo()](#echo) · [exec$()](#exec$) · [stdin()](#stdin) · [config](#config)
30+
[s (shelljs)](#shelljs) · [cli()](#cli) · [chalk](#chalk-package) · [fetch()](#fetch) · [pipe()](#pipe) · [question()](#question) · [echo()](#echo) · [stdin()](#stdin) · [config](#config)
4231

4332

4433
## Documentation
@@ -69,29 +58,39 @@ All function (`shelljs`, `fetch`, …) are exported by library, so use:
6958
import { … } from "nodejsscript";
7059
```
7160

72-
### `xarg()`
73-
Simplify version of `xargs` allowing passing one argument. For now only "-I" argument is allowed.
74-
By default `{}` will be replaced, if not presented the argument is append as last one.
61+
### shelljs
62+
The `shelljs` extension is available as `s`. For docs visits [shelljs/shelljs](https://github.com/shelljs/shelljs).
63+
You can pipe commands when make sense by changing see **[Pipes](https://github.com/shelljs/shelljs#pipes)**.
7564

7665
```js
77-
pipe(
78-
exec$.bind(null, "git branch --show-current"),
79-
xarg(exec, "echo deploy --branch={}")
80-
)();
81-
pipe(
82-
exec$.bind(null, "git branch --show-current"),
83-
xarg("-I §", exec, "echo deploy --branch=§")
84-
)();
66+
s.cat("./package.json").grep("version");
67+
```
68+
… this library adds two function `xargs` and `$`:
69+
#### `xargs(cmd, ...cmd_args)`
70+
#### `xargs("-I", pattern, cmd, ...cmd_args)`
71+
```js
72+
s.exec("git branch --show-current").xargs(s.exec, "dep deploy --branch={}");
73+
s.exec("git branch --show-current").xargs("-I", "§", s.exec, "dep deploy --branch=§");
74+
```
75+
76+
#### `$()`
77+
#### `$("-svf")`
78+
Modifies config for next command in chain. The `$()` runs next command in silent mode (compare to bash `var=$(echo Hi)`).
79+
80+
```js
81+
const branch= s.$().exec("git branch --show-current");
82+
echo(branch);
83+
84+
s.$("-vf").exec("gyt branch --show-current");
8585
```
8686

8787
### `pipe()`
8888
Function similar to [Ramda `R.pipe`](https://ramdajs.com/docs/#pipe)). Provides functional way to combine commands/functions.
89-
Can be used with [xarg()](#xarg). **Some functions from shelljs also allow you to combine them, see [Pipes](https://github.com/shelljs/shelljs#pipes)**.
9089

9190
```js
9291
pipe(
9392
Number,
94-
v=> s.greenBright(v+1),
93+
v=> chalk.greenBright(v+1),
9594
v=> `Result is: ${v}`,
9695
echo
9796
)(await question("Choose number:"));
@@ -125,15 +124,6 @@ A wrapper around the [readline](https://nodejs.org/api/readline.html) package.
125124
const bear= await question('What kind of bear is best? ')
126125
```
127126

128-
### `exec$()`
129-
A wrapper around the [exec](https://github.com/shelljs/shelljs#execcommand--options--callback) function.
130-
Runs in silent mode and handle text to be used as variables.
131-
132-
```js
133-
const branch= exec$("git branch --show-current");
134-
echo('Current branch is', branch);
135-
```
136-
137127
### `echo()`
138128
A `console.log()` alternative optimized for scripting.
139129

@@ -166,11 +156,10 @@ const config.assign({ verbose: true, silent: false });
166156
```
167157

168158
### `chalk` package
169-
The [chalk](https://www.npmjs.com/package/chalk) package. Also as shorthand **s**.
159+
The [chalk](https://www.npmjs.com/package/chalk) package.
170160

171161
```js
172162
echo(chalk.blue('Hello world!'));
173-
echo(s.blue('Hello world!'));
174163
```
175164

176165
[^node]: Alternatively `curl -sL install-node.vercel.app/17.0.1 | bash`

examples/background-process.mjs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
#!/usr/bin/env nodejsscript
22
/* jshint esversion: 8,-W097, -W040, node: true, expr: true, undef: true */
3-
import { echo, exec, fetch, exit } from "nodejsscript";
3+
import { echo, s, fetch, exit } from "nodejsscript";
44

5-
const serve= exec("npx serve", { async: true });
5+
const serve= s.exec("npx serve", { async: true });
66
for await (const chunk of serve.stdout)
77
if (chunk.includes('Accepting connections')) break;
88

examples/backup-github.mjs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
#!/usr/bin/env nodejsscript
2-
import { cd, echo, exec, mkdir, question } from "nodejsscript";
2+
import { s, echo, question, fetch } from "/home/jaandrle/.nvm/versions/node/v17.0.1/lib/node_modules/nodejsscript/index.js";
33

44
const username= await question('What is your GitHub username?');
55
const token= await question('Do you have GitHub token in env?', {
@@ -15,8 +15,8 @@ if (process.env[token]) {
1515
const data= await fetch(`https://api.github.com/users/${username}/repos?per_page=1000`, { headers }).then(res=> res.json());
1616
const urls= data.map(x=> x.git_url.replace('git://github.com/', 'git@github.com:'));
1717

18-
mkdir("-p", "backups");
19-
cd("./backups");
18+
s.mkdir("-p", "backups");
19+
s.cd("./backups");
2020

2121
for(const url of urls)
22-
exec(`git clone ${url}`);
22+
s.exec(`git clone ${url}`);

examples/cli.mjs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,19 @@
11
#!/usr/bin/env nodejsscript
2-
import { cli, echo, mkdir, pipe, rm, tempdir, test, xarg } from "nodejsscript";
2+
import { cli, s, echo, pipe } from "nodejsscript";
33
import { join } from "node:path";
44

55
cli("", true)
66
.version("0.1.0")
77
.describe("NodeJS Script cli test")
88
.option("--clear", "Clears cerated temp dir")
99
.action(function main({ clear }){
10-
const name= join(tempdir(), "foo bar");
11-
mkdir("-p", name);
10+
const name= join(s.tempdir(), "foo bar");
11+
s.mkdir("-p", name);
1212

13-
const testDir= pipe(xarg(test, "-d"), echo);
13+
const testDir= pipe(s.test.bind(null, "-d"), echo);
1414
testDir(name);
1515

16-
if(clear) rm("-R", name);
16+
if(clear) s.rm("-R", name);
1717
testDir(name);
1818
})
1919
.parse(process.argv);

index.js

Lines changed: 16 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -1,83 +1,39 @@
11
export const pipe= (...funs)=> input=> Array.prototype.reduce.call(funs, (out, f)=> f(out), input);
2-
function parseOptions(candidate, initial= {}){
3-
if(typeof candidate!=="string") return Object.assign({}, initial, candidate);
4-
return candidate.split(" -").reduce(function parse(out, curr, i){
5-
const space_i= curr.indexOf(" ");
6-
const name= ( i ? "-" : "" )+curr.slice(0, space_i);
7-
Reflect.set(out, name, curr.slice(space_i+1));
8-
return out;
9-
}, initial);
10-
}
11-
export function xarg(...params){
12-
const options_default= { "-I": "{}" };
13-
const options= typeof params[0]!=="function" ? parseOptions(params.shift()) : options_default;
14-
const needle= options["-I"];
15-
const [ cmd, ...args ]= params;
16-
return function call(arg){
17-
let replaced= 0;
18-
const args_final= args.map(a=> a.replaceAll(needle, ()=> ( replaced+= 1, arg )));
19-
if(!replaced) args_final.push(arg);
20-
return cmd.apply(null, args_final);
21-
};
22-
}
23-
24-
import shelljs from "shelljs";
25-
export const {
26-
ls, find, dirs,
27-
cd, pwd, pushd, popd,
28-
cp, rm, mv, mkdir, ln, touch, tempdir,
29-
chmod,
30-
test, error,
31-
cat, sed, grep, sort, head, tail, uniq,
32-
which,
33-
exit, env,
34-
exec
35-
}= shelljs;
36-
/**
37-
* Silent execution of {@link exec} to be used with pipeing or as variable.
38-
* @param {string} command The command to execute.
39-
* @param {object} options
40-
* @param {boolean} [options.fatal] Exit when command return code is non-zero.
41-
* @param {string} [options.encoding] Character encoding to use.
42-
* @example
43-
* const out= exec$("cmd");
44-
*/
45-
export function exec$(command, options= {}){
46-
return exec(command, Object.assign({}, options, { async: false, silent: true })).replace(/\n$/g, "");
47-
}
482

49-
const _config= shelljs.config;
3+
import s from "./src/shelljs.js";
4+
export { s };
5+
export const exit= s.exit;
506
export const config= {
517
/**
528
* Suppresses all command output if `true`, except for `echo()` call.
539
* @default false
5410
* */
55-
get silent(){ return _config.silent; },
56-
set silent(v){ _config.silent= v; },
11+
get silent(){ return s.config.silent; },
12+
set silent(v){ s.config.silent= v; },
5713
/**
5814
* Will print each executed command to the screen.
5915
* @default false
6016
* */
61-
get verbose(){ return _config.verbose; },
62-
set verbose(v){ return (_config.verbose= v); },
17+
get verbose(){ return s.config.verbose; },
18+
set verbose(v){ return (s.config.verbose= v); },
6319
/**
6420
* If `true`, the script will throw a JavaScript error when any `shell.js` command encounters an error. This is analogous to Bash's `set -e`.
6521
* @default false
6622
* */
67-
get fatal(){ return _config.fatal; },
68-
set fatal(v){ return (_config.fatal= v); },
23+
get fatal(){ return s.config.fatal; },
24+
set fatal(v){ return (s.config.fatal= v); },
6925
/**
7026
* Disable filename expansion (globbing)
7127
* @default false
7228
* */
73-
get noglob(){ return _config.noglob; },
74-
set noglob(v){ return (_config.noglob= v); },
29+
get noglob(){ return s.config.noglob; },
30+
set noglob(v){ return (s.config.noglob= v); },
7531
/**
7632
* Options for [`glob.sync()`](https://github.com/isaacs/node-glob/tree/af57da21c7722bb6edb687ccd4ad3b99d3e7a333#options).
7733
* @default {}
7834
* */
79-
get globOptions(){ return _config.globOptions; },
80-
set globOptions(v){ return (_config.globOptions= v); },
35+
get globOptions(){ return s.config.globOptions; },
36+
set globOptions(v){ return (s.config.globOptions= v); },
8137

8238
/** Set multiple options with one command.
8339
* @param {...Record<"verbose"|"fatal"|"noglob"|"silent",boolean>} c
@@ -86,7 +42,7 @@ export const config= {
8642
};
8743

8844
import chalk from "chalk";
89-
export { chalk, chalk as s };
45+
export { chalk };
9046

9147
import nodeFetch from 'node-fetch';
9248
/**
@@ -96,14 +52,14 @@ import nodeFetch from 'node-fetch';
9652
* @return {Promise<import('node-fetch').Response>}
9753
*/
9854
export function fetch(url, init){
99-
if(config.verbose) echo("fetch(", url, ",", init, ")");
55+
if(s.config.verbose) echo("fetch(", url, ",", init, ")");
10056
return nodeFetch(url, init);
10157
}
10258

10359
import { log } from "node:console";
10460
export function echo(...messages){
10561
log(...messages.map(v=>
106-
v instanceof Error && config.verbose ? v :
62+
v instanceof Error && s.config.verbose ? v :
10763
( String(v)==="[object Object]" ? v : String(v).replaceAll("\t", " ") )));
10864
}
10965

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "nodejsscript",
3-
"version": "0.2.0",
3+
"version": "0.5.0",
44
"author": "Jan Andrle <andrle.jan@centrum.cz>",
55
"license": "MIT",
66
"description": "A tool for writing better scripts",

src/shelljs.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import shelljs, {ShellString} from "shelljs";
2+
import plugin from "shelljs/plugin.js";
3+
4+
plugin.register("xargs", xargs, {
5+
canReceivePipe: true,
6+
wrapOutput: false,
7+
cmdOptions: {
8+
I: 'needle'
9+
}
10+
});
11+
plugin.register("$", $, {
12+
canReceivePipe: true,
13+
wrapOutput: false
14+
});
15+
16+
export default shelljs;
17+
18+
function xargs({ needle }, ...args){
19+
if(!needle) needle= "{}";
20+
else needle= args.shift();
21+
const [ cmd, ...cmd_args ]= args;
22+
if(typeof cmd!=="function")
23+
plugin.error("xargs needs one of the `shelljs` commands as first argument");
24+
25+
const pipe= plugin.readFromPipe();
26+
let replaced= 0;
27+
const args_final= cmd_args.map(a=> typeof a !== "string" ? a : a.replaceAll(needle, ()=> ( replaced+= 1, pipe )));
28+
if(!replaced) args_final.push(pipe);
29+
return cmd.apply(null, args_final);
30+
}
31+
function $(config_next= "-s"){
32+
config_next= plugin.parseOptions(config_next, {
33+
v: "verbose",
34+
f: "fatal",
35+
s: "silent"
36+
});
37+
return new Proxy(this, {
38+
get(target, p){
39+
return function(...args){
40+
const { silent, verbose, fatal }= shelljs.config;
41+
Object.assign(shelljs.config, config_next);
42+
const out= target[p].apply(target, args);
43+
Object.assign(shelljs.config, { silent, verbose, fatal });
44+
return out instanceof String && Reflect.has(out, "stdout") ? new shelljs.ShellString(out.replace(/\n$/g, ""), out.stderr, out.code) : out;
45+
};
46+
}
47+
});
48+
}

types/index.d.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1+
export * from './types/shelljs.d.ts';
12
export {
2-
/* shelljs */ ls, find, dirs, cd, pwd, pushd, popd, cp, rm, mv, mkdir, ln, touch, tempdir, chmod, test, error, cat, sed, grep, sort, head, tail, uniq, which, exit, env, set, exec, config,
3-
chalk, s, fetch,
4-
echo, question, stdin, cli, exec$, xarg
3+
chalk, fetch,
4+
echo, question, stdin, cli
55
} from "./index.js";

0 commit comments

Comments
 (0)