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

feat: Preprocessor can return Promise #3376

Merged
merged 1 commit into from Oct 11, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
51 changes: 30 additions & 21 deletions lib/preprocessor.js
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