From c133dd0472d61d51a236eb4d0b4d33d86c673da5 Mon Sep 17 00:00:00 2001 From: Romain Date: Sat, 2 Dec 2023 11:17:05 +0000 Subject: [PATCH] chore: refactor cleanup to be easier to read & test --- src/steps/step-cleanup.js | 42 ++++++++++++++++++++------------------- 1 file changed, 22 insertions(+), 20 deletions(-) diff --git a/src/steps/step-cleanup.js b/src/steps/step-cleanup.js index 18e7ff9..a31ae2c 100644 --- a/src/steps/step-cleanup.js +++ b/src/steps/step-cleanup.js @@ -6,28 +6,30 @@ const path = require('path') const readdir = require('fs-readdir-recursive') exports.run = function (fileCollection, outputRoot, dryRun) { + const obsolete = findObsolete(fileCollection, outputRoot) return new Observable(observer => { - const mediaRoot = path.join(outputRoot, 'media') - const diskFiles = readdir(mediaRoot).map(f => path.join(mediaRoot, f)) - const requiredFiles = [] - fileCollection.forEach(f => { - Object.keys(f.output).forEach(out => { - const dest = path.join(outputRoot, f.output[out].path) - requiredFiles.push(dest) - }) + obsolete.forEach(f => { + const relativePath = path.relative(outputRoot, f) + if (dryRun) { + debug(`Dry run, would delete: ${relativePath}`) + } else { + observer.next(relativePath) + fs.unlinkSync(f) + } }) - const useless = _.difference(diskFiles, requiredFiles) - if (useless.length) { - useless.forEach(f => { - const relativePath = path.relative(outputRoot, f) - if (dryRun) { - debug(`Dry run, would delete: ${relativePath}`) - } else { - observer.next(relativePath) - fs.unlinkSync(f) - } - }) - } observer.complete() }) } + +function findObsolete (fileCollection, outputRoot) { + const mediaRoot = path.join(outputRoot, 'media') + const diskFiles = readdir(mediaRoot).map(f => path.join(mediaRoot, f)) + const requiredFiles = [] + fileCollection.forEach(f => { + Object.keys(f.output).forEach(out => { + const dest = path.join(outputRoot, f.output[out].path) + requiredFiles.push(dest) + }) + }) + return _.difference(diskFiles, requiredFiles) +}