File size: 11,682 Bytes
e903a32 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 |
#!/usr/bin/env node
/**
* Template synchronization script for research-article-template
*
* This script:
* 1. Clones or updates the template repo in a temporary directory
* 2. Copies all files EXCEPT those in ./src/content which contain specific content
* 3. Preserves important local configuration files
* 4. Creates backups of files that will be overwritten
*
* Usage: npm run sync:template [--dry-run] [--backup] [--force]
*/
import { execSync } from 'child_process';
import fs from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const APP_ROOT = path.resolve(__dirname, '..');
const PROJECT_ROOT = path.resolve(APP_ROOT, '..');
const TEMP_DIR = path.join(PROJECT_ROOT, '.temp-template-sync');
const TEMPLATE_REPO = 'https://huggingface.co/spaces/tfrere/research-article-template';
// Files and directories to PRESERVE (do not overwrite)
const PRESERVE_PATHS = [
// Project-specific content
'app/src/content',
// Public data (symlink to our data) - CRITICAL: preserve this symlink
'app/public/data',
// Local configuration
'app/package-lock.json',
'app/node_modules',
// Project-specific scripts (preserve our sync script)
'app/scripts/sync-template.mjs',
// Project configuration files
'README.md',
'tools',
// Backup and temporary files
'.backup-*',
'.temp-*',
// Git
'.git',
'.gitignore'
];
// Files to handle with caution (require confirmation)
const SENSITIVE_FILES = [
'app/package.json',
'app/astro.config.mjs',
'Dockerfile',
'nginx.conf'
];
const args = process.argv.slice(2);
const isDryRun = args.includes('--dry-run');
const shouldBackup = args.includes('--backup'); // Disabled by default, use --backup to enable
const isForce = args.includes('--force');
console.log('🔄 Template synchronization script for research-article-template');
console.log(`📁 Working directory: ${PROJECT_ROOT}`);
console.log(`🎯 Template source: ${TEMPLATE_REPO}`);
if (isDryRun) console.log('🔍 DRY-RUN mode enabled - no files will be modified');
if (shouldBackup) console.log('💾 Backup enabled');
if (!shouldBackup) console.log('🚫 Backup disabled (use --backup to enable)');
console.log('');
async function executeCommand(command, options = {}) {
try {
if (isDryRun && !options.allowInDryRun) {
console.log(`[DRY-RUN] Command: ${command}`);
return '';
}
console.log(`$ ${command}`);
const result = execSync(command, {
encoding: 'utf8',
cwd: options.cwd || PROJECT_ROOT,
stdio: options.quiet ? 'pipe' : 'inherit'
});
return result;
} catch (error) {
console.error(`❌ Error during execution: ${command}`);
console.error(error.message);
throw error;
}
}
async function pathExists(filePath) {
try {
await fs.access(filePath);
return true;
} catch {
return false;
}
}
async function isPathPreserved(relativePath) {
return PRESERVE_PATHS.some(preserve =>
relativePath === preserve ||
relativePath.startsWith(preserve + '/')
);
}
async function createBackup(filePath) {
if (!shouldBackup || isDryRun) return;
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const backupPath = `${filePath}.backup-${timestamp}`;
try {
await fs.copyFile(filePath, backupPath);
console.log(`💾 Backup created: ${path.relative(PROJECT_ROOT, backupPath)}`);
} catch (error) {
console.warn(`⚠️ Unable to create backup for ${filePath}: ${error.message}`);
}
}
async function syncFile(sourcePath, targetPath) {
const relativeTarget = path.relative(PROJECT_ROOT, targetPath);
// Check if the file should be preserved
if (await isPathPreserved(relativeTarget)) {
console.log(`🔒 PRESERVED: ${relativeTarget}`);
return;
}
// Check if it's a sensitive file
if (SENSITIVE_FILES.includes(relativeTarget)) {
if (!isForce) {
console.log(`⚠️ SENSITIVE (ignored): ${relativeTarget} (use --force to overwrite)`);
return;
} else {
console.log(`⚠️ SENSITIVE (forced): ${relativeTarget}`);
}
}
// Check if target file is a symbolic link to preserve
if (await pathExists(targetPath)) {
try {
const targetStats = await fs.lstat(targetPath);
if (targetStats.isSymbolicLink()) {
console.log(`🔗 SYMLINK TARGET (preserved): ${relativeTarget}`);
return;
}
} catch (error) {
console.warn(`⚠️ Impossible de vérifier ${targetPath}: ${error.message}`);
}
}
// Create backup if file already exists (and is not a symbolic link)
if (await pathExists(targetPath)) {
try {
const stats = await fs.lstat(targetPath);
if (!stats.isSymbolicLink()) {
await createBackup(targetPath);
}
} catch (error) {
console.warn(`⚠️ Impossible de vérifier ${targetPath}: ${error.message}`);
}
}
if (isDryRun) {
console.log(`[DRY-RUN] COPY: ${relativeTarget}`);
return;
}
// Ensure the parent directory exists
await fs.mkdir(path.dirname(targetPath), { recursive: true });
// Check if source is a symbolic link
try {
const sourceStats = await fs.lstat(sourcePath);
if (sourceStats.isSymbolicLink()) {
console.log(`🔗 SYMLINK SOURCE (ignored): ${relativeTarget}`);
return;
}
} catch (error) {
console.warn(`⚠️ Unable to check source ${sourcePath}: ${error.message}`);
return;
}
// Remove target file if it exists (to handle symbolic links)
if (await pathExists(targetPath)) {
await fs.rm(targetPath, { recursive: true, force: true });
}
// Copier le fichier
await fs.copyFile(sourcePath, targetPath);
console.log(`✅ COPIED: ${relativeTarget}`);
}
async function syncDirectory(sourceDir, targetDir) {
const items = await fs.readdir(sourceDir, { withFileTypes: true });
for (const item of items) {
const sourcePath = path.join(sourceDir, item.name);
const targetPath = path.join(targetDir, item.name);
const relativeTarget = path.relative(PROJECT_ROOT, targetPath);
if (await isPathPreserved(relativeTarget)) {
console.log(`🔒 DOSSIER PRÉSERVÉ: ${relativeTarget}/`);
continue;
}
if (item.isDirectory()) {
if (!isDryRun) {
await fs.mkdir(targetPath, { recursive: true });
}
await syncDirectory(sourcePath, targetPath);
} else {
await syncFile(sourcePath, targetPath);
}
}
}
async function cloneOrUpdateTemplate() {
console.log('📥 Fetching template...');
// Nettoyer le dossier temporaire s'il existe
if (await pathExists(TEMP_DIR)) {
await fs.rm(TEMP_DIR, { recursive: true, force: true });
if (isDryRun) {
console.log(`[DRY-RUN] Suppression: ${TEMP_DIR}`);
}
}
// Clone template repo (even in dry-run to be able to compare)
await executeCommand(`git clone ${TEMPLATE_REPO} "${TEMP_DIR}"`, { allowInDryRun: true });
return TEMP_DIR;
}
async function ensureDataSymlink() {
const dataSymlinkPath = path.join(APP_ROOT, 'public', 'data');
const dataSourcePath = path.join(APP_ROOT, 'src', 'content', 'assets', 'data');
// Check if symlink exists and is correct
if (await pathExists(dataSymlinkPath)) {
try {
const stats = await fs.lstat(dataSymlinkPath);
if (stats.isSymbolicLink()) {
const target = await fs.readlink(dataSymlinkPath);
const expectedTarget = path.relative(path.dirname(dataSymlinkPath), dataSourcePath);
if (target === expectedTarget) {
console.log('🔗 Data symlink is correct');
return;
} else {
console.log(`⚠️ Data symlink points to wrong target: ${target} (expected: ${expectedTarget})`);
}
} else {
console.log('⚠️ app/public/data exists but is not a symlink');
}
} catch (error) {
console.log(`⚠️ Error checking symlink: ${error.message}`);
}
}
// Recreate symlink
if (!isDryRun) {
if (await pathExists(dataSymlinkPath)) {
await fs.rm(dataSymlinkPath, { recursive: true, force: true });
}
await fs.symlink(path.relative(path.dirname(dataSymlinkPath), dataSourcePath), dataSymlinkPath);
console.log('✅ Data symlink recreated');
} else {
console.log('[DRY-RUN] Would recreate data symlink');
}
}
async function showSummary(templateDir) {
console.log('\n📊 SYNCHRONIZATION SUMMARY');
console.log('================================');
console.log('\n🔒 Preserved files/directories:');
for (const preserve of PRESERVE_PATHS) {
const fullPath = path.join(PROJECT_ROOT, preserve);
if (await pathExists(fullPath)) {
console.log(` ✓ ${preserve}`);
} else {
console.log(` - ${preserve} (n'existe pas)`);
}
}
console.log('\n⚠️ Sensitive files (require --force):');
for (const sensitive of SENSITIVE_FILES) {
const fullPath = path.join(PROJECT_ROOT, sensitive);
if (await pathExists(fullPath)) {
console.log(` ! ${sensitive}`);
}
}
if (isDryRun) {
console.log('\n🔍 To execute for real: npm run sync:template');
console.log('🔧 To force sensitive files: npm run sync:template -- --force');
}
}
async function cleanup() {
console.log('\n🧹 Cleaning up...');
if (await pathExists(TEMP_DIR)) {
if (!isDryRun) {
await fs.rm(TEMP_DIR, { recursive: true, force: true });
}
console.log(`🗑️ Temporary directory removed: ${TEMP_DIR}`);
}
}
async function main() {
try {
// Verify we're in the correct directory
const packageJsonPath = path.join(APP_ROOT, 'package.json');
if (!(await pathExists(packageJsonPath))) {
throw new Error(`Package.json not found in ${APP_ROOT}. Are you in the correct directory?`);
}
// Clone the template
const templateDir = await cloneOrUpdateTemplate();
// Synchroniser
console.log('\n🔄 Synchronisation en cours...');
await syncDirectory(templateDir, PROJECT_ROOT);
// Ensure the data symlink is correct
console.log('\n🔗 Vérification du lien symbolique des données...');
await ensureDataSymlink();
// Display the summary
await showSummary(templateDir);
console.log('\n✅ Synchronization completed!');
} catch (error) {
console.error('\n❌ Error during synchronization:');
console.error(error.message);
process.exit(1);
} finally {
await cleanup();
}
}
// Signal handling to clean up on interruption
process.on('SIGINT', async () => {
console.log('\n\n⚠️ Interruption detected, cleaning up...');
await cleanup();
process.exit(1);
});
process.on('SIGTERM', async () => {
console.log('\n\n⚠️ Shutdown requested, cleaning up...');
await cleanup();
process.exit(1);
});
main();
|