79 lines
1.9 KiB
JavaScript
79 lines
1.9 KiB
JavaScript
const fs = require('fs-extra');
|
|
const path = require('path');
|
|
const { getDestinationDecision, isCadFile } = require('./router');
|
|
const { buildDestinationIndex } = require('./destinationIndex');
|
|
const { getUnroutedTarget } = require('./unrouted');
|
|
|
|
async function collectFilesRecursively(rootDir) {
|
|
const files = [];
|
|
|
|
async function walk(currentDir) {
|
|
const entries = await fs.readdir(currentDir, { withFileTypes: true });
|
|
|
|
for (const entry of entries) {
|
|
const fullPath = path.join(currentDir, entry.name);
|
|
|
|
if (entry.isDirectory()) {
|
|
await walk(fullPath);
|
|
continue;
|
|
}
|
|
|
|
if (entry.isFile()) {
|
|
files.push({ fullPath, fileName: entry.name });
|
|
}
|
|
}
|
|
}
|
|
|
|
await walk(rootDir);
|
|
return files;
|
|
}
|
|
|
|
async function processFolder(folder, config) {
|
|
const files = await collectFilesRecursively(folder);
|
|
const destinationIndex = await buildDestinationIndex(config?.destination);
|
|
const result = {
|
|
scanned: 0,
|
|
copied: 0,
|
|
skipped: 0,
|
|
unrouted: 0,
|
|
details: [],
|
|
};
|
|
|
|
for (const { fullPath, fileName } of files) {
|
|
const file = fileName;
|
|
result.scanned += 1;
|
|
|
|
if (!isCadFile(file)) {
|
|
result.skipped += 1;
|
|
continue;
|
|
}
|
|
|
|
const decision = getDestinationDecision(file, config, destinationIndex);
|
|
const destDir = decision.destination;
|
|
|
|
if (!destDir) {
|
|
const unroutedTarget = await getUnroutedTarget(file);
|
|
await fs.copy(fullPath, unroutedTarget.destinationPath, { overwrite: false });
|
|
|
|
result.copied += 1;
|
|
result.unrouted += 1;
|
|
result.details.push({
|
|
file,
|
|
destination: unroutedTarget.destinationDir,
|
|
reason: decision.reason || 'Nessuna regola trovata',
|
|
});
|
|
continue;
|
|
}
|
|
|
|
const dest = path.join(destDir, file);
|
|
await fs.copy(fullPath, dest, { overwrite: true });
|
|
|
|
result.copied += 1;
|
|
result.details.push({ file, destination: destDir });
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
module.exports = { processFolder };
|