Skip to content

Commit

Permalink
build: first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Kikobeats committed Jul 31, 2024
0 parents commit 9927626
Show file tree
Hide file tree
Showing 13 changed files with 436 additions and 0 deletions.
19 changes: 19 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# https://editorconfig.org

root = true

[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
max_line_length = 80
indent_brace_style = 1TBS
spaces_around_operators = true
quote_type = auto

[package.json]
indent_style = space
indent_size = 2
1 change: 1 addition & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* text=auto
11 changes: 11 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
version: 2
updates:
- package-ecosystem: npm
directory: '/'
schedule:
interval: daily
- package-ecosystem: 'github-actions'
directory: '/'
schedule:
# Check for updates to GitHub Actions every weekday
interval: 'daily'
36 changes: 36 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
############################
# npm
############################
node_modules
npm-debug.log
.node_history
yarn.lock
package-lock.json

############################
# tmp, editor & OS files
############################
.tmp
*.swo
*.swp
*.swn
*.swm
.DS_Store
*#
*~
.idea
*sublime*
nbproject

############################
# Tests
############################
testApp
coverage
.nyc_output

############################
# Other
############################
.env
.envrc
12 changes: 12 additions & 0 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
audit=false
fund=false
loglevel=error
package-lock=false
prefer-dedupe=true
prefer-offline=false
resolution-mode=highest
save-prefix=~
save=false
shamefully-hoist=true
strict-peer-dependencies=false
unsafe-perm=true
21 changes: 21 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright © 2024 Kiko Beats <josefrancisco.verdu@gmail.com> (kikobeats.com)

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.
57 changes: 57 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<div align="center">
<img src="https://github.com/microlinkhq/cdn/raw/master/dist/logo/banner.png#gh-light-mode-only" alt="microlink cdn">
<img src="https://github.com/microlinkhq/cdn/raw/master/dist/logo/banner-dark.png#gh-dark-mode-only" alt="microlink cdn">
<br>
<br>
</div>

![Last version](https://img.shields.io/github/tag/kikobeats/tinyrun.svg?style=flat-square)
[![Coverage Status](https://img.shields.io/coveralls/kikobeats/tinyrun.svg?style=flat-square)](https://coveralls.io/github/kikobeats/tinyrun)
[![NPM Status](https://img.shields.io/npm/dm/tinyrun.svg?style=flat-square)](https://www.npmjs.org/package/tinyrun)

**tinyrun** runs multiple commands in parallel with minimal footprint (~2KB).

It can run one-off commands:

```
tinyrun "pnpm build" "pnpm build:docs"
```

or commands that keep running in background:

```
tinyrun --names "HTTP" "node examples/server.js"
HTTP started pid=13030
HTTP Server is listening on port 3000
c^CHTTP Received shutdown signal, shutting down gracefully...
HTTP Closed out remaining connections
HTTP cmd='node examples/server.js' exitCode=0 signalCode=null duration=2s
```

## Install

```bash
$ npm install tinyrun --global
```

## Usage

### as CLI

Just `tinyrun --help` to see all the options availables.

### as module

Check [how CLI is implemented](/bin/index.js) to see how it's interacting with the core module.

## Related

- [tinyspawn](https://github.com/Kikobeats/tinyspawn) – A minimalistic wrapper around Node.js `child_process.spawn` API.

## License

**tinyrun** © [Kiko Beats](https://kikobeats.com), released under the [MIT](https://github.com/kikobeats/tinyrun/blob/master/LICENSE.md) License.<br>
Authored and maintained by [Kiko Beats](https://kikobeats.com) with help from [contributors](https://github.com/kikobeats/tinyrun/contributors).

> [kikobeats.com](https://kikobeats.com) · GitHub [Kiko Beats](https://github.com/kikobeats) · Twitter [@kikobeats](https://twitter.com/kikobeats)
11 changes: 11 additions & 0 deletions bin/help.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
Run multiple commands in parallel.

Usage
$ tinyrun [options]<commands...>

Options
--names List of custom names for the commands.

Examples
$ tinyrun --names "HTTP" "node examples/server.js"
$ tinyrun "npm run dev" "npm run build"
76 changes: 76 additions & 0 deletions bin/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
#!/usr/bin/env node

'use strict'

const { readFileSync } = require('node:fs')
const { styleText } = require('node:util')
const path = require('node:path')

const COLORS = ['yellow', 'blue', 'magenta', 'cyan']

const getColor = index => COLORS[index % COLORS.length]

const prettyMs = ms => {
const seconds = ms / 1000
if (seconds < 60) return `${Math.round(seconds)}s`
const minutes = Math.round(seconds / 60)
const remainingSeconds = seconds % 60
return `${minutes}m ${remainingSeconds.toFixed(2)}s`
}

const toStream =
stream =>
(data, { name }) =>
stream.write(split(data, name))

const split = (text, prefix) =>
text
.toString()
.split('\n')
.map(line => (line ? `${prefix} ${line}` : ''))
.join('\n')

const { _, ...flags } = require('mri')(process.argv.slice(2))

if (_.length === 0) {
console.log(readFileSync(path.resolve(__dirname, './help.txt'), 'utf8'))
process.exit(0)
}

let names = flags.names?.split(',')

if (Array.isArray(names) && names.length > 0) {
const maxNameLength = Math.max(...names.map(name => name.length))
names = names.map(name => name.padStart(maxNameLength))
}

const tasks = _.map((cmd, index) => ({
cmd,
name: styleText(getColor(index), names?.[index] ?? `[${index}]`)
}))

const stdout = toStream(process.stdout)
const start = (subprocess, task) =>
stdout(`${styleText('gray', `started pid=${subprocess.pid}`)}` + '\n', task)

const exit = ({ exitCode, signalCode, duration }, task) => {
const color = exitCode === 0 ? 'gray' : 'red'

console.log(
`${task.name} ${styleText(
color,
`cmd='${
task.cmd
}' exitCode=${exitCode} signalCode=${signalCode} duration=${prettyMs(
duration
)}`
)}`
)
}

require('tinyrun')(tasks, {
stdout,
stderr: toStream(process.stderr),
start,
exit
})
40 changes: 40 additions & 0 deletions examples/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
const http = require('http')

// Create an HTTP server
const server = http.createServer((req, res) => {
console.log(`Received request for ${req.url}`)

// Simulate a delay in response
setTimeout(() => {
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end('Hello, world!\n')
}, 1000)
})

// Define a port
const PORT = process.env.PORT || 3000

// Start the server
server.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`)
})

// Handle graceful shutdown
const gracefulShutdown = () => {
console.log('Received shutdown signal, shutting down gracefully...')

server.close(() => {
console.log('Closed out remaining connections')
process.exit(0)
})

// Force shutdown after 10 seconds
setTimeout(() => {
console.error('Forcing shutdown')
process.exit(1)
}, 10000)
}

// Listen for termination signals (e.g., SIGINT, SIGTERM)
process.on('SIGTERM', gracefulShutdown)
process.on('SIGINT', gracefulShutdown)
104 changes: 104 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
{
"name": "tinyrun",
"description": "Run multiple commands in parallel",
"homepage": "https://github.com/microlinkhq/tinyrun",
"version": "0.0.0",
"exports": {
".": "./src/index.js"
},
"bin": {
"tinyrun": "bin/index.js"
},
"author": {
"email": "josefrancisco.verdu@gmail.com",
"name": "Kiko Beats",
"url": "https://kikobeats.com"
},
"repository": {
"type": "git",
"url": "git+https://github.com/microlinkhq/tinyrun.git"
},
"bugs": {
"url": "https://github.com/microlinkhq/tinyrun/issues"
},
"keywords": [
"bash",
"command",
"concurrent",
"concurrently",
"parallel",
"sh"
],
"dependencies": {
"@kikobeats/time-span": "~1.0.5",
"mri": "~1.2.0",
"tinyspawn": "~1.3.2"
},
"devDependencies": {
"@commitlint/cli": "latest",
"@commitlint/config-conventional": "latest",
"@ksmithut/prettier-standard": "latest",
"ava": "latest",
"c8": "latest",
"finepack": "latest",
"git-authors-cli": "latest",
"github-generate-release": "latest",
"nano-staged": "latest",
"npm-check-updates": "latest",
"pretty-ms": "7",
"simple-git-hooks": "latest",
"standard": "latest",
"standard-markdown": "latest",
"standard-version": "latest"
},
"engines": {
"node": ">= 18"
},
"files": [
"bin",
"src"
],
"scripts": {
"clean": "rm -rf node_modules",
"contributors": "(npx git-authors-cli && npx finepack && git add package.json && git commit -m 'build: contributors' --no-verify) || true",
"coverage": "c8 report --reporter=text-lcov > coverage/lcov.info",
"lint": "standard-markdown README.md && standard",
"postrelease": "npm run release:tags && npm run release:github && npm publish",
"prerelease": "npm run update:check",
"pretest": "npm run lint",
"release": "standard-version -a",
"release:github": "github-generate-release",
"release:tags": "git push --follow-tags origin HEAD:master",
"test": "c8 ava",
"update": "ncu -u",
"update:check": "ncu -- --error-level 2"
},
"preferGlobal": true,
"license": "MIT",
"commitlint": {
"extends": [
"@commitlint/config-conventional"
],
"rules": {
"body-max-line-length": [
0
]
}
},
"nano-staged": {
"*.js": [
"prettier-standard",
"standard --fix"
],
"*.md": [
"standard-markdown"
],
"package.json": [
"finepack"
]
},
"simple-git-hooks": {
"commit-msg": "npx commitlint --edit",
"pre-commit": "npx nano-staged"
}
}
Loading

0 comments on commit 9927626

Please sign in to comment.