'use strict'
const fs = require('fs')
const path = require('path')
const EE = require('events').EventEmitter
const Minimatch = require('minimatch').Minimatch
class Walker extends EE {
constructor (opts) {
opts = opts || {}
super(opts)
this.path = opts.path || process.cwd()
this.basename = path.basename(this.path)
this.ignoreFiles = opts.ignoreFiles || [ '.ignore' ]
this.ignoreRules = {}
this.parent = opts.parent || null
this.includeEmpty = !!opts.includeEmpty
this.root = this.parent ? this.parent.root : this.path
this.follow = !!opts.follow
this.result = this.parent ? this.parent.result : new Set()
this.entries = null
this.sawError = false
}
sort (a, b) {
return a.localeCompare(b)
}
emit (ev, data) {
let ret = false
if (!(this.sawError && ev === 'error')) {
if (ev === 'error')
this.sawError = true
else if (ev === 'done' && !this.parent) {
data = Array.from(data)
.map(e => /^@/.test(e) ? `./${e}` : e).sort(this.sort)
this.result = data
}
if (ev === 'error' && this.parent)
ret = this.parent.emit('error', data)
else
ret = super.emit(ev, data)
}
return ret
}
start () {
fs.readdir(this.path, (er, entries) =>
er ? this.emit('error', er) : this.onReaddir(entries))
return this