Skip to content

Commit 213c7a5

Browse files
committed
💥 pipe, xarg, 💥 types, 💡
1 parent 4242603 commit 213c7a5

7 files changed

Lines changed: 224 additions & 56 deletions

File tree

README.md

Lines changed: 66 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,21 @@ mkdir(tempdir()+"/"+name);
2828
1. `npm install https://github.com/jaandrle/nodejsscript --global`
2929

3030
## Goods
31-
[shelljs/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](https://github.com/shelljs/shelljs#tempdir)
31+
· [shelljs/shelljs:](https://github.com/shelljs/shelljs)
32+
[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)
33+
· [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)
34+
· [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)
35+
· [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)
36+
· [rm](https://github.com/shelljs/shelljs#rmoptions-file--file-) · [sed](https://github.com/shelljs/shelljs#sedoptions-search_regex-replacement-file--file-) · [set](https://github.com/shelljs/shelljs#setoptions) · [sort](https://github.com/shelljs/shelljs#sortoptions-file--file-)
37+
· [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-)
38+
· [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)
39+
· [cli()](#cli)
40+
· [xarg()](#xarg)
41+
· [pipe()](#pipe)
3242
· [fetch()](#fetch)
3343
· [question()](#question)
3444
· [echo()](#echo)
45+
· [exec$()](#exec$)
3546
· [stdin()](#stdin)
3647
· [chalk](#chalk-package)
3748

@@ -64,6 +75,46 @@ All function (`shelljs`, `fetch`, …) are exported by library, so use:
6475
import { … } from "nodejsscript";
6576
```
6677

78+
### `xarg()`
79+
Simplify version of `xargs` allowing passing one argument. For now only "-I" argument is allowed.
80+
By default `{}` will be replaced, if not presented the argument is append as last one.
81+
82+
```js
83+
pipe(
84+
exec$.bind(null, "git branch --show-current"),
85+
xarg(exec, "echo deploy --branch={}")
86+
)();
87+
pipe(
88+
exec$.bind(null, "git branch --show-current"),
89+
xarg("-I §", exec, "echo deploy --branch=§")
90+
)();
91+
```
92+
93+
### `pipe()`
94+
Function similar to [Ramda `R.pipe`](https://ramdajs.com/docs/#pipe)). Provides functional way to combine commands/functions.
95+
Can be used with [xarg()](#xarg). **Some functions from shelljs also allow you to combine them, see [Pipes](https://github.com/shelljs/shelljs#pipes)**.
96+
97+
```js
98+
pipe(
99+
Number,
100+
v=> s.greenBright(v+1),
101+
v=> `Result is: ${v}`,
102+
echo
103+
)(await question("Choose number:"));
104+
105+
```
106+
107+
### `cli()`
108+
A wrapper around the [lukeed/sade: Smooth (CLI) Operator 🎶](https://github.com/lukeed/sade) package.
109+
In addition to the origin, `cli()` supports to fill script name from script file name.
110+
111+
```js
112+
cli("", true)
113+
.version("0.1.0")
114+
.describe("NodeJS Script cli test")
115+
.action(echo);
116+
```
117+
67118
### `fetch()`
68119
A wrapper around the [node-fetch](https://www.npmjs.com/package/node-fetch) package.
69120

@@ -77,22 +128,32 @@ A wrapper around the [readline](https://nodejs.org/api/readline.html) package.
77128
```js
78129
const bear= await question('What kind of bear is best? ')
79130
```
131+
132+
### `exec$()`
133+
A wrapper around the [exec](https://github.com/shelljs/shelljs#execcommand--options--callback) function.
134+
Runs in silent mode and handle text to be used as variables.
135+
136+
```js
137+
const branch= exec$("git branch --show-current");
138+
echo('Current branch is', branch);
139+
```
140+
80141
### `echo()`
81-
A `console.log()` alternative optimalozed for scripting.
142+
A `console.log()` alternative optimalized for scripting.
82143

83144
```js
84-
const branch= exec("git branch --show-current");
145+
const branch= exec$("git branch --show-current");
85146
echo('Current branch is', branch);
86147
```
87148

88149
### `stdin()`
89150
Returns the stdin as a string.
90151

91152
```js
92-
const content= JSON.parse(await stdin())
153+
const content= JSON.parse(await stdin());
93154
```
94155

95-
### `chalk`
156+
### `chalk` package
96157
The [chalk](https://www.npmjs.com/package/chalk) package. Also as shorthand **s**.
97158

98159
```js

index.js

Lines changed: 46 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,26 @@
1+
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.push(arg);
20+
return cmd.apply(null, args_final);
21+
};
22+
}
23+
124
import shelljs from "shelljs";
225
export const {
326
ls, find, dirs,
@@ -11,6 +34,18 @@ export const {
1134
exec,
1235
config
1336
}= shelljs;
37+
/**
38+
* Silent execution of {@link exec} to be used with pipeing or as variable.
39+
* @param {string} command The command to execute.
40+
* @param {object} options
41+
* @param {boolean} [options.fatal] Exit when command return code is non-zero.
42+
* @param {string} [options.encoding] Character encoding to use.
43+
* @example
44+
* const out= exec$("cmd");
45+
*/
46+
export function exec$(command, options= {}){
47+
return exec(command, Object.assign({}, options, { async: false, silent: true })).replace(/\n$/g, "");
48+
}
1449

1550
import chalk from "chalk";
1651
export { chalk, chalk as s };
@@ -25,41 +60,19 @@ export function echo(...messages){
2560
( String(v)==="[object Object]" ? v : String(v).replaceAll("\t", " ") )));
2661
}
2762

63+
import sade from "sade";
2864
/**
29-
* Returns object representation of given arguments. Script name is under `_name` key, arguments without `-`/`--` are under `_` key.
30-
* @param {NodeJS.Process.argv} argv
31-
* @param {Record<string, any>} initial Initial values
32-
* @returns {{ _name: string, _: string[] } & Record<string, any>}
33-
* @example
34-
* script arg1 --arg2=val -arg3 val --arg4
35-
* => { _name: "script", _: [ "arg1" ], arg2: "val", arg3: "val", arg4: true }
65+
* @param {string} usage The script name and usage (`[optional]`/`<required>`). If no `name`, then the script file name will be used.
66+
* @param {boolean} [is_single] See {@link sade}
67+
* @returns {sade.Sade}
3668
* */
37-
export function parseArgsMinimal(initial= {}, argv= process.argv){
38-
const out= Object.create(initial);
39-
out._name= argv[1].slice(argv[1].lastIndexOf("/")+1);
40-
out._= [];
41-
const args= argv.slice(2);
42-
for(let i= 0, { length }= args; i<length; i+= 1){
43-
const item= args[i];
44-
if(0===item.indexOf("--")){
45-
const [ name, value= true ]= item.slice(2).split("=");
46-
Reflect.set(out, name, value);
47-
continue;
48-
}
49-
if(0!==item.indexOf("-")){
50-
out._.push(item);
51-
continue;
52-
}
53-
let next= args[i+1];
54-
if(!next || !next.indexOf("-"))
55-
next= true;
56-
Reflect.set(out, item.slice(1), next);
57-
if(next!==true)
58-
i+= 1;
59-
}
60-
if(!out._.length && initial._ && initial._.length)
61-
out._= initial._;
62-
return out;
69+
export function cli(usage, is_single= false){
70+
if(usage && !/^[\[<]/.test(usage))
71+
return sade(usage, is_single);
72+
73+
const script= process.argv[1];
74+
const name= script.slice(script.lastIndexOf("/")+1);
75+
return sade(name+(usage ? " "+usage : ""), is_single);
6376
}
6477

6578
import { createInterface } from 'node:readline';

package-lock.json

Lines changed: 63 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "nodejsscript",
3-
"version": "0.1.0",
3+
"version": "0.2.0",
44
"author": "Jan Andrle <andrle.jan@centrum.cz>",
55
"license": "MIT",
66
"description": "A tool for writing better scripts",
@@ -24,6 +24,14 @@
2424
"bin/cli.mjs",
2525
"index.js"
2626
],
27+
"types": "types/index.d.ts",
28+
"typesVersions": {
29+
"*": {
30+
".": [
31+
"./types/index.d.ts"
32+
]
33+
}
34+
},
2735
"scripts": {
2836
"test": "echo \"Error: no test specified\" && exit 1"
2937
},
@@ -45,9 +53,11 @@
4553
"maxcomplexity": 11
4654
},
4755
"dependencies": {
56+
"@types/sade": "^1.7.4",
4857
"@types/shelljs": "^0.8.11",
4958
"chalk": "^5.0.1",
5059
"node-fetch": "^3.2.10",
60+
"sade": "^1.8.1",
5161
"shelljs": ">=v0.8.5"
5262
}
5363
}

test/run.js

Lines changed: 0 additions & 17 deletions
This file was deleted.

0 commit comments

Comments
 (0)