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

watch Command - watch files/dirs and rerun task on change #33

Closed
wants to merge 21 commits into from
Closed
Show file tree
Hide file tree
Changes from 18 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
82 changes: 82 additions & 0 deletions lib/FileWatcher.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
const chokidar = require('chokidar')
const logger = require('./logger')

Array.prototype.asyncForEach = async function(callback) { // eslint-disable-line
Copy link
Contributor

@tunnckoCore tunnckoCore Jun 6, 2018

Choose a reason for hiding this comment

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

Ouch, why? I just really can't believe what i'm looking 🤣

p-map-series or p-map is probably better fit.

Copy link
Contributor

Choose a reason for hiding this comment

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

Hmm... I missed that. Yeah, probably don't want to modify the prototype.

Copy link
Author

Choose a reason for hiding this comment

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

okay thanks @olstenlarck

for (let index = 0; index < this.length; index++) {
await callback(this[index], index, this)
}
}
class FileWatcher {
constructor() {
this.runner = []
this.watcher = []
this.watchedTasks = {}
}

init(runner) {
this.watcher.push(
chokidar.watch(['file, dir, glob'], {
ignored: /(^|[/\\])\../,
persistent: true,
ignoreInitial: true
})
)

this.watcher[0]
.on('add', path =>
this.getTaskNames(path).forEach(async taskName => {
await runner.runFile(taskName)
})
flxwu marked this conversation as resolved.
Show resolved Hide resolved
)
.on('change', path =>
this.getTaskNames(path).forEach(async taskName => {
await runner.runFile(taskName)
})
)
.on('unlink', path =>
this.getTaskNames(path).forEach(async taskName => {
await runner.runFile(taskName)
})
)
.on('error', error => logger.log(`Watcher error: ${error}`))
}

getTaskNames(path) {
let foundTask = null
Object.keys(this.watchedTasks).forEach(taskName => {
if (this.watchedTasks[taskName] === path) {
foundTask = taskName
} else {
let pathRegex = this.watchedTasks[taskName].replace('*', '(.*?)')
pathRegex =
pathRegex.charAt(pathRegex.length - 1) === '/'
? pathRegex.concat('(.*?)')
: pathRegex
if (new RegExp(pathRegex).test(path)) {
foundTask = taskName
}
}
})

return foundTask.split(',')
}

watch(file, taskName) {
this.watcher[0].add(file)
this.watchedTasks[taskName] = file
}

unwatch(file) {
this.watcher[0].unwatch(file)
}

close() {
this.watcher[0].close()
}
}

// Singleton
const instance = new FileWatcher()
Object.freeze(instance)

module.exports = instance
174 changes: 174 additions & 0 deletions lib/MaidRunner.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
const path = require('path')
const chalk = require('chalk')
const mm = require('micromatch')
const requireFromString = require('require-from-string')
const logger = require('./logger')
const readMaidFile = require('./readMaidFile')
const MaidError = require('./MaidError')
const runCLICommand = require('./runCLICommand')
const FileWatcher = require('./FileWatcher')

class MaidRunner {
constructor(opts = {}) {
this.maidfile = readMaidFile(opts.section)
logger.setOptions({ quiet: opts.quiet })

if (!this.maidfile) {
throw new MaidError('No maidfile was found. Stop.')
}
this.firstTask = true
this.alreadyWatching = {}
}

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

if (inParallel) {
await Promise.all(
taskNames.map(taskName => {
return this.runTask(taskName)
})
)
} else {
for (const taskName of taskNames) {
await this.runTask(taskName)
}
}
}

async runFile(taskName) {
await this.runTask('beforeAll', false)
await this.runTask(taskName)
await this.runTask('afterAll', false)
}

async runTask(taskName, throwWhenNoMatchedTask = true) {
const task =
taskName &&
this.maidfile &&
this.maidfile.tasks.find(task => task.name === taskName)

if (!task) {
if (throwWhenNoMatchedTask) {
throw new MaidError(`No task called "${taskName}" was found. Stop.`)
} else {
return
}
}

await this.runTaskHooks(task, 'before')

const start = Date.now()

logger.log(`Starting '${chalk.cyan(task.name)}'...`)
await new Promise((resolve, reject) => {
const handleError = err => {
throw new MaidError(`Task '${task.name}' failed.\n${err.stack}`)
}
if (checkTypes(task, ['sh', 'bash'])) {
return runCLICommand({ task, resolve, reject })
}
if (checkTypes(task, ['py', 'python'])) {
return runCLICommand({ type: 'python', task, resolve, reject })
}
if (checkTypes(task, ['js', 'javascript'])) {
let res
try {
res = requireFromString(task.script, this.maidfile.filepath)
} catch (err) {
return handleError(err)
}
res = res.default || res
return resolve(
typeof res === 'function'
? Promise.resolve(res()).catch(handleError)
: res
)
}

return resolve()
})

logger.log(
`Finished '${chalk.cyan(task.name)}' ${chalk.magenta(
`after ${Date.now() - start} ms`
)}...`
)
await this.runTaskHooks(task, 'after')
}

async runTaskHooks(task, when) {
const prefix = when === 'before' ? 'pre' : 'post'
const tasks = this.maidfile.tasks.filter(({ name }) => {
return name === `${prefix}${task.name}`
})
await this.runTasks(tasks.map(task => task.name))
for (const item of task[when]) {
const { taskNames, inParallel, watchTargets } = item
// if this is the overall first task, init the watcher
if (watchTargets) {
if (this.firstTask) {
FileWatcher.init(this)
this.firstTask = false
}
// log watching on first run of each task
if (!this.alreadyWatching[taskNames]) {
logger.log(
`'${chalk.cyan(taskNames)}' is watching ${chalk.magenta(
watchTargets
)}...`
)
FileWatcher.watch(watchTargets, taskNames)
this.alreadyWatching[taskNames] = true
}
}

await this.runTasks(taskNames, inParallel)
}
}

getHelp(patterns) {
patterns = [].concat(patterns)
const tasks =
patterns.length > 0
? this.maidfile.tasks.filter(task => {
return mm.some(task.name, patterns)
})
: this.maidfile.tasks

if (tasks.length === 0) {
throw new MaidError(
`No tasks for pattern "${patterns.join(' ')}" was found. Stop.`
)
}

console.log(
`\n ${chalk.magenta.bold(
`Task${tasks.length > 1 ? 's' : ''} in ${path.relative(
process.cwd(),
this.maidfile.filepath
)}:`
)}\n\n` +
tasks
.map(
task =>
` ${chalk.bold(task.name)}\n${chalk.dim(
task.description
? task.description
.split('\n')
.map(v => ` ${v.trim()}`)
.join('\n')
: ' No description'
)}`
)
.join('\n\n') +
'\n'
)
}
}

function checkTypes(task, types) {
return types.some(type => type === task.type)
}

module.exports = MaidRunner
Loading