const fs = require('fs');
const path = require('path');
/**
* Syncs resources between datasets based on a configuration file.
* @param {string} configPath Path to the configuration file.
*/
async function syncDatasets(configPath) {
try {
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
if (!config.datasets || !Array.isArray(config.datasets)) {
console.error("Invalid config format: 'datasets' must be an array.");
return;
}
for (const datasetName in config.datasets) {
if (!config.datasets.hasOwnProperty(datasetName)) continue;
const datasetConfig = config.datasets[datasetName];
if (!datasetConfig.source || !datasetConfig.target) {
console.warn(`Missing 'source' or 'target' in dataset config for ${datasetName}. Skipping.`);
continue;
}
const sourcePath = datasetConfig.source;
const targetPath = datasetConfig.target;
//Check if source file exists
if (!fs.existsSync(sourcePath)) {
console.warn(`Source file not found: ${sourcePath} for dataset ${datasetName}. Skipping.`);
continue;
}
try {
// Copy resources from source to target
await copyResources(sourcePath, targetPath);
console.log(`Synced resources from ${sourcePath} to ${targetPath} for dataset ${datasetName}`);
} catch (error) {
console.error(`Error syncing resources for dataset ${datasetName}:`, error);
}
}
} catch (error) {
console.error("Error reading or parsing config:", error);
}
}
/**
* Copies resources from a source path to a target path.
* @param {string} sourcePath Path to the source directory or file.
* @param {string} targetPath Path to the target directory.
*/
async function copyResources(sourcePath, targetPath) {
try {
const sourceFiles = fs.readdirSync(sourcePath);
for (const file of sourceFiles) {
const sourceFilePath = path.join(sourcePath, file);
const targetFilePath = path.join(targetPath, file);
const stat = fs.statSync(sourceFilePath);
if (stat.isFile()) {
fs.copyFileSync(sourceFilePath, targetFilePath);
console.log(`Copied file: ${sourceFilePath} to ${targetFilePath}`);
} else if (stat.isDirectory()) {
fs.mkdirSync(targetFilePath, { recursive: true }); // Create target directory if it doesn't exist
copyResources(sourceFilePath, targetFilePath); // Recursively copy contents
}
}
} catch (error) {
throw error;
}
}
// Example usage (replace with your config file path)
// syncDatasets('config.json');
module.exports = { syncDatasets };
Add your comment