Skip to content

Commit

Permalink
feat: Preprocessor can return Promise (#3376)
Browse files Browse the repository at this point in the history
preprocessor plugins can execute 'done()' or return a Promise
  • Loading branch information
anthony-redFox authored and johnjbarton committed Oct 11, 2019
1 parent f8005c6 commit 3ffcd83
Showing 1 changed file with 30 additions and 21 deletions.
51 changes: 30 additions & 21 deletions lib/preprocessor.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,29 +8,39 @@ const CryptoUtils = require('./utils/crypto-utils')

const log = require('./logger').create('preprocess')

function createNextProcessor (preprocessors, file, done) {
return function nextPreprocessor (error, content) {
// normalize B-C
if (arguments.length === 1 && typeof error === 'string') {
content = error
error = null
}

if (error) {
file.content = null
file.contentPath = null
return done(error)
function executeProcessor (process, file, content) {
let done = null
const donePromise = new Promise((resolve, reject) => {
done = function (error, content) {
// normalize B-C
if (arguments.length === 1 && typeof error === 'string') {
content = error
error = null
}
if (error) {
reject(error)
} else {
resolve(content)
}
}
})
return process(content, file, done) || donePromise
}

if (!preprocessors.length) {
file.contentPath = null
file.content = content
file.sha = CryptoUtils.sha1(content)
return done()
async function runProcessors (preprocessors, file, content) {
try {
for (let process of preprocessors) {
content = await executeProcessor(process, file, content)
}

preprocessors.shift()(content, file, nextPreprocessor)
} catch (error) {
file.contentPath = null
file.content = null
throw error
}

file.contentPath = null
file.content = content
file.sha = CryptoUtils.sha1(content)
}

function createPriorityPreprocessor (config, preprocessorPriority, basePath, injector) {
Expand Down Expand Up @@ -103,7 +113,6 @@ function createPriorityPreprocessor (config, preprocessorPriority, basePath, inj
.map((duo) => duo[0])

let preprocessors = []
const nextPreprocessor = createNextProcessor(preprocessors, file, done)
sortedPreprocessorNames.forEach((name) => {
const p = instances[name] || instantiatePreprocessor(name)

Expand All @@ -124,7 +133,7 @@ function createPriorityPreprocessor (config, preprocessorPriority, basePath, inj
}
})

nextPreprocessor(null, isBinary ? buffer : buffer.toString())
runProcessors(preprocessors, file, isBinary ? buffer : buffer.toString()).then(done, done)
})
}
return fs.readFile(file.originalPath, readFileCallback)
Expand Down

0 comments on commit 3ffcd83

Please sign in to comment.