Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Write maid scripts to package.json #26

Closed
wants to merge 13 commits into from
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 29 additions & 27 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@

# maid

[![NPM version](https://img.shields.io/npm/v/maid.svg?style=flat)](https://npmjs.com/package/maid) [![NPM downloads](https://img.shields.io/npm/dm/maid.svg?style=flat)](https://npmjs.com/package/maid) [![CircleCI](https://circleci.com/gh/egoist/maid/tree/master.svg?style=shield)](https://circleci.com/gh/egoist/maid/tree/master) [![donate](https://img.shields.io/badge/$-donate-ff69b4.svg?maxAge=2592000&style=flat)](https://github.com/egoist/donate) [![chat](https://img.shields.io/badge/chat-on%20discord-7289DA.svg?style=flat)](https://chat.egoist.moe)
[![NPM version](https://img.shields.io/npm/v/maid.svg?style=flat)](https://npmjs.com/package/maid) [![NPM downloads](https://img.shields.io/npm/dm/maid.svg?style=flat)](https://npmjs.com/package/maid) [![CircleCI](https://circleci.com/gh/egoist/maid/tree/master.svg?style=shield)](https://circleci.com/gh/egoist/maid/tree/master) [![donate](https://img.shields.io/badge/$-donate-ff69b4.svg?maxAge=2592000&style=flat)](https://github.com/egoist/donate) [![chat](https://img.shields.io/badge/chat-on%20discord-7289DA.svg?style=flat)](https://chat.egoist.moe)

> Markdown driven task runner.

## Table of Contents

<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->

<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->

- [Install](#install)
- [What is a maidfile?](#what-is-a-maidfile)
Expand Down Expand Up @@ -52,13 +51,13 @@ npm i -D maid
yarn add maid --dev
```

<small>__PRO TIP__: you can use `npx` or `yarn` command to run any locally installed executable that is inside `node_modules/.bin/`, e.g. use `yarn maid` to run the locally installed maid command.</small>
<small>**PRO TIP**: you can use `npx` or `yarn` command to run any locally installed executable that is inside `node_modules/.bin/`, e.g. use `yarn maid` to run the locally installed maid command.</small>

## What is a maidfile?

A maidfile is where you define tasks, in Markdown!

📝 __maidfile.md__:
📝 **maidfile.md**:

````markdown
## lint
Expand All @@ -74,6 +73,7 @@ eslint --fix
Build our main app

<!-- Following line is a maid command for running task -->

Run task `build:demo` after this

```bash
Expand All @@ -90,20 +90,21 @@ You can use JavaScript to write to task script too!
const webpack = require('webpack')

// Async task should return a Promise
module.exports = () => new Promise((resolve, reject) => {
const compiler = webpack(require('./webpack.config'))
compiler.run((err, stats) => {
if (err) return reject(err)
console.log(stats.toString('minimal'))
resolve()
module.exports = () =>
new Promise((resolve, reject) => {
const compiler = webpack(require('./webpack.config'))
compiler.run((err, stats) => {
if (err) return reject(err)
console.log(stats.toString('minimal'))
resolve()
})
})
})
```
````

Each task is defined using `h2` header and its child contents, the value of `h2` header will be used as task name, its following paragraphs (optional) will be used as task description, and following code block (optional) will be used as task script.
Each task is defined using `h2` header and its child contents, the value of `h2` header will be used as task name, its following paragraphs (optional) will be used as task description, and following code block (optional) will be used as task script.

Currently the code block languages are `sh` `bash` `js` `javascript` [and more](#code-block-languages)!.
Currently the code block languages are `sh` `bash` `js` `javascript` [and more](#code-block-languages)!.

Now run `maid help` to display the help for this maidfile:

Expand Down Expand Up @@ -157,21 +158,21 @@ gh-pages -d dist
```
````

Basically expressions like ``Run task `deploy` after this`` is treated specially, in this case if you run `maid build`, it will also run `deploy` task when `build` task is finished.
Basically expressions like `` Run task `deploy` after this `` is treated specially, in this case if you run `maid build`, it will also run `deploy` task when `build` task is finished.

The syntax is simple: `Run tasks? <taskNames> (before|after) this (in parallel)?` where each task name is surrounded by a pair of backticks: <code>`</code>.

Examples:

- ``Run task `build` after this.``
- ``Run tasks `build:app` `start:server` before this.``
- ``Run tasks `build:server` `build:client` before this in parallel.``
- `` Run task `build` after this. ``
- `` Run tasks `build:app` `start:server` before this. ``
- `` Run tasks `build:server` `build:client` before this in parallel. ``

### Task hooks

Like npm scripts, when you run a command called `build`, when it's finished we will also run `postbuild` task.

Hook syntax:
Hook syntax:

- `pre<taskName>`: Run before a specific task.
- `post<taskName>`: Run after a specific task.
Expand Down Expand Up @@ -281,6 +282,8 @@ If you want to automatically fix lint errors, try adding `--fix` plugin to the c

Use [AVA](https://github.com/avajs/ava) to run unit tests.

Run task `lint` before this.

```bash
yarn ava "${@:1}"
```
Expand All @@ -289,24 +292,23 @@ Similar to the `lint` task, you can append any flags for `ava` command directly

### toc

Generate a __table of contents__ section in the README.md file.
Generate a **table of contents** section in the README.md file.

```bash
yarn doctoc README.md
```

## Contributing

1. Fork it!
2. Create your feature branch: `git checkout -b my-new-feature`
3. Commit your changes: `git commit -am 'Add some feature'`
4. Push to the branch: `git push origin my-new-feature`
5. Submit a pull request :D

1. Fork it!
2. Create your feature branch: `git checkout -b my-new-feature`
3. Commit your changes: `git commit -am 'Add some feature'`
4. Push to the branch: `git push origin my-new-feature`
5. Submit a pull request :D

## Author

**maid** © [egoist](https://github.com/egoist), Released under the [MIT](./LICENSE) License.<br>
Authored and maintained by egoist with help from contributors ([list](https://github.com/egoist/maid/contributors)).

> [github.com/egoist](https://github.com/egoist) · GitHub [@egoist](https://github.com/egoist) · Twitter [@_egoistlily](https://twitter.com/_egoistlily)
> [github.com/egoist](https://github.com/egoist) · GitHub [@egoist](https://github.com/egoist) · Twitter [@\_egoistlily](https://twitter.com/_egoistlily)
15 changes: 15 additions & 0 deletions bin/cli.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,18 @@
#!/usr/bin/env node
const cli = require('cac')()
const chalk = require('chalk')
const MaidError = require('../lib/MaidError')

cli.command('*', 'Run a task in current working directory', (input, flags) => {
if (flags.updateScripts && input[0]) {
throw new MaidError('Cannot run task and update scripts')
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This really gives me pause... the more I think about it the more I think this should be a command

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why disallow this 🤔

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in the updateScripts method, I'm passing all the arguments through transparently. If I allowed this I'd have to find the input and remove it before writing to the package.json.

So... laziness. I can remove it. Point might be moot if this turns into its own command though.

} else if (flags.updateScripts) {
const runner = require('..')(flags)
const updateScripts = require('../lib/updateScripts')
updateScripts(runner)
return
}

const taskName = input[0]
if (!taskName) {
return cli.showHelp()
Expand Down Expand Up @@ -44,4 +54,9 @@ cli.option('section', {
alias: 's'
})

cli.option('update-scripts', {
desc: 'Write maid tasks to package.json scripts',
type: 'boolean'
})

cli.parse()
8 changes: 8 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,14 @@ class Maid {
}
}

listTasks() {
return this.maidfile.tasks.map(task => task.name)
}

getFilepath() {
return this.maidfile.filepath
}

async runTasks(taskNames, inParallel) {
if (!taskNames || taskNames.length === 0) return

Expand Down
53 changes: 53 additions & 0 deletions lib/updateScripts.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
const loadFile = require('./loadFile')
const MaidError = require('./MaidError')
const fs = require('fs')
const path = require('path')

const flattenObj = (a, b) => ({
...a,
...b
})

module.exports = maid => {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I should probably break this function down.

const { path: pkgPath, data: pkg } = loadFile.loadSync(['package.json'])
if (!pkgPath) return null

const maidExec = process.argv[1].endsWith('.js')
? `node ${path.relative(process.cwd(), process.argv[1])}`
: 'maid'

const { scripts = {} } = pkg
const tasks = maid.listTasks()

const passThroughArgs = process.argv
.slice(2)
.filter(arg => arg !== '--update-scripts')
.join(' ')

const baseScripts = Object.keys(scripts)
.filter(task => !scripts[task].startsWith(maidExec))
.map(task => ({ [task]: scripts[task] }))
.reduce(flattenObj, {})

const conflictingTasks = tasks.filter(task =>
Object.keys(baseScripts).includes(task)
)

if (conflictingTasks.length) {
throw new MaidError(
`Conflicts between maidfile and package.json. Please check these scripts: \n\t
${conflictingTasks.join(', ')}`
)
}

const finalScripts = tasks
.map(task => ({
[task]: `${maidExec} ${passThroughArgs} ${task}`.replace(/\s+/g, ' ')
}))
.reduce(flattenObj, baseScripts)

fs.writeFileSync(
pkgPath,
JSON.stringify({ ...pkg, ...{ scripts: finalScripts } }, null, 2)
)
}
6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@
"lib"
],
"scripts": {
"test": "node bin/cli lint && node bin/cli test"
"lint": "node bin/cli.js lint",
"test": "node bin/cli.js test",
"toc": "node bin/cli.js toc"
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎉 AUTOMAGICALLY GENERATED 🎉

},
"author": "egoist <[email protected]>",
"license": "MIT",
Expand Down Expand Up @@ -66,4 +68,4 @@
"git add"
]
}
}
}