Skip to content

Commit

Permalink
feat: Initial implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
coreyfarrell committed Dec 15, 2019
0 parents commit 39123b4
Show file tree
Hide file tree
Showing 12 changed files with 490 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .gitignore
@@ -0,0 +1,5 @@
*.tgz
node_modules
coverage
.nyc_output
package
7 changes: 7 additions & 0 deletions .npmignore
@@ -0,0 +1,7 @@
*.tgz
.taprc
.travis.yml
.nyc_output/
nyc.config.js
fixtures/
test/
1 change: 1 addition & 0 deletions .npmrc
@@ -0,0 +1 @@
package-lock=false
5 changes: 5 additions & 0 deletions .taprc
@@ -0,0 +1,5 @@
esm: false
100: true
timeout: 60000
nyc-arg:
- "--all"
11 changes: 11 additions & 0 deletions .travis.yml
@@ -0,0 +1,11 @@
os:
- windows
- linux
- osx

language: node_js

node_js:
- 12
- 10
- 8
21 changes: 21 additions & 0 deletions LICENSE
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2019 CFWare, LLC

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
64 changes: 64 additions & 0 deletions README.md
@@ -0,0 +1,64 @@
# process-on-spawn

[![Travis CI][travis-image]][travis-url]
[![Greenkeeper badge][gk-image]](https://greenkeeper.io/)
[![NPM Version][npm-image]][npm-url]
[![NPM Downloads][downloads-image]][downloads-url]
[![MIT][license-image]](LICENSE)

Execute callbacks when child processes are spawned.

## Usage

```js
'use strict';

const processOnSpawn = require('process-on-spawn');
processOnSpawn.addListener(opts => {
opts.env.CHILD_VARIABLE = 'value';
});
```

### listener(opts)

* `options` \<[Object]\>
* `execPath` \<[string]\> The command to run.
* `args` \<[string\[\]][string]\> Arguments of the child process.
* `cwd` \<[string]\> Current working directory of the child process.
* `detached` \<[boolean]\> The child will be prepared to run independently of its parent process.
* `uid` \<[number]\> The user identity to be used by the child.
* `gid` \<[number]\> The group identity to be used by the child.
* `windowsVerbatimArguments` \<[boolean]\> No quoting or escaping of arguments will be done on Windows.
* `windowsHide` \<[boolean]\> The subprocess console window that would normally be created on Windows systems will be hidden.

All properties except `env` are read-only.

### processOnSpawn.addListener(listener)

Add a listener to be called after any listeners already attached.

### processOnSpawn.prependListener(listener)

Insert a listener to be called before any listeners already attached.

### processOnSpawn.removeListener(listener)

Remove the specified listener. If the listener was added multiple times only
the first is removed.

### processOnSpawn.removeAllListeners()

Remove all attached listeners.

[npm-image]: https://img.shields.io/npm/v/process-on-spawn.svg
[npm-url]: https://npmjs.org/package/process-on-spawn
[travis-image]: https://travis-ci.org/cfware/process-on-spawn.svg?branch=master
[travis-url]: https://travis-ci.org/cfware/process-on-spawn
[gk-image]: https://badges.greenkeeper.io/cfware/process-on-spawn.svg
[downloads-image]: https://img.shields.io/npm/dm/process-on-spawn.svg
[downloads-url]: https://npmjs.org/package/process-on-spawn
[license-image]: https://img.shields.io/npm/l/process-on-spawn.svg
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type
[boolean]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type
[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type
11 changes: 11 additions & 0 deletions fixtures/dump-env.js
@@ -0,0 +1,11 @@
#!/usr/bin/env node
'use strict';

const env = {...process.env};
for (const key of Object.keys(env)) {
if (/^path$/i.test(key)) {
delete env[key];
}
}

console.log(JSON.stringify(env));
112 changes: 112 additions & 0 deletions index.js
@@ -0,0 +1,112 @@
'use strict';

/* Drop this dependency once node.js 12 is required. */
const fromEntries = require('fromentries');

const state = getState(1);

function getState(version) {
const stateId = Symbol.for('process-on-spawn@*:singletonId');

/* istanbul ignore next: cannot cover this once nyc depends on this module */
if (stateId in global === false) {
/* Hopefully version and unwrap forward compatibility is never actually needed */
Object.defineProperty(global, stateId, {
writable: true,
value: {
version,
listeners: [],
unwrap: wrapSpawnFunctions()
}
});
}

return global[stateId];
}

function wrappedSpawnFunction(fn) {
return function (options) {
let env = fromEntries(
options.envPairs.map(nvp => nvp.split(/^([^=]*)=/).slice(1))
);

const opts = Object.create(null, {
env: {
enumerable: true,
get() {
return env;
},
set(value) {
if (!value || typeof value !== 'object') {
throw new TypeError('env must be an object');
}

env = value;
}
},
cwd: {
enumerable: true,
get() {
return options.cwd || process.cwd();
}
}
});

const args = [...options.args];
Object.freeze(args);
Object.assign(opts, {
execPath: options.file,
args,
detached: Boolean(options.detached),
uid: options.uid,
gid: options.gid,
windowsVerbatimArguments: Boolean(options.windowsVerbatimArguments),
windowsHide: Boolean(options.windowsHide)
});
Object.freeze(opts);

state.listeners.forEach(listener => {
listener(opts);
});

options.envPairs = Object.entries(opts.env).map(([name, value]) => `${name}=${value}`);

return fn.call(this, options);
};
}

function wrapSpawnFunctions() {
const {ChildProcess} = require('child_process');

/* eslint-disable-next-line node/no-deprecated-api */
const spawnSyncBinding = process.binding('spawn_sync');
const originalSync = spawnSyncBinding.spawn;
const originalAsync = ChildProcess.prototype.spawn;

spawnSyncBinding.spawn = wrappedSpawnFunction(spawnSyncBinding.spawn);
ChildProcess.prototype.spawn = wrappedSpawnFunction(ChildProcess.prototype.spawn);

/* istanbul ignore next: forward compatibility code */
return () => {
spawnSyncBinding.spawn = originalSync;
ChildProcess.prototype.spawn = originalAsync;
};
}

module.exports = {
addListener(listener) {
state.listeners.push(listener);
},
prependListener(listener) {
state.listeners.unshift(listener);
},
removeListener(listener) {
const idx = state.listeners.indexOf(listener);
if (idx !== -1) {
state.listeners.splice(idx, 1);
}
},
removeAllListeners() {
state.listeners = [];
}
};
5 changes: 5 additions & 0 deletions nyc.config.js
@@ -0,0 +1,5 @@
'use strict';

module.exports = {
include: ['*.js']
};
31 changes: 31 additions & 0 deletions package.json
@@ -0,0 +1,31 @@
{
"name": "process-on-spawn",
"version": "1.0.0",
"description": "Execute callbacks when child processes are spawned",
"scripts": {
"release": "standard-version --sign",
"pretest": "xo",
"test": "tap"
},
"engines": {
"node": ">=8"
},
"author": "Corey Farrell",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/cfware/process-on-spawn.git"
},
"bugs": {
"url": "https://github.com/cfware/process-on-spawn/issues"
},
"homepage": "https://github.com/cfware/process-on-spawn#readme",
"dependencies": {
"fromentries": "^1.2.0"
},
"devDependencies": {
"standard-version": "^7.0.0",
"tap": "=14.10.2-unbundled",
"xo": "^0.25.3"
}
}

0 comments on commit 39123b4

Please sign in to comment.