khy_admin/deploy.js

175 lines
5 KiB
JavaScript

#!/usr/bin/env node
/**
* Deploy Script for KHY Admin Dashboard
*
* This script copies the updated products.json and any other changes
* from the admin directory to the main website directory.
*
* Usage: node deploy.js [target-directory]
*/
const fs = require("fs");
const path = require("path");
const { exec } = require("child_process");
const config = require("./deploy-config");
// Configuration
const ADMIN_DIR = __dirname;
// Get target directory from command line or use default
const TARGET_DIR = process.argv[2] || config.targets[config.defaultTarget];
const TARGET_PATH = path.resolve(ADMIN_DIR, TARGET_DIR);
console.log("KHY Admin Deploy Script");
console.log("=======================");
console.log(`Admin Directory: ${ADMIN_DIR}`);
console.log(`Target Directory: ${TARGET_PATH}`);
console.log("");
// Files to copy from admin to main website (from config)
const FILES_TO_COPY = config.filesToCopy;
// Function to copy file or directory
function copyFileOrDir(source, target, isDirectory = false) {
const sourcePath = path.join(ADMIN_DIR, source);
const targetPath = path.join(TARGET_PATH, target);
try {
if (isDirectory) {
// Copy directory recursively
if (fs.existsSync(targetPath)) {
fs.rmSync(targetPath, { recursive: true, force: true });
}
fs.cpSync(sourcePath, targetPath, { recursive: true });
} else {
// Copy file
const targetDir = path.dirname(targetPath);
if (!fs.existsSync(targetDir)) {
fs.mkdirSync(targetDir, { recursive: true });
}
fs.copyFileSync(sourcePath, targetPath);
}
return true;
} catch (error) {
console.error(`❌ Error copying ${source}:`, error.message);
return false;
}
}
// Function to create backup
function createBackup() {
const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
const backupDir = path.join(ADMIN_DIR, "backups", timestamp);
try {
fs.mkdirSync(backupDir, { recursive: true });
// Backup current products.json from target
const targetProducts = path.join(TARGET_PATH, "data/products.json");
if (fs.existsSync(targetProducts)) {
fs.copyFileSync(targetProducts, path.join(backupDir, "products.json"));
console.log(`📦 Backup created: ${backupDir}`);
return true;
}
} catch (error) {
console.error("❌ Error creating backup:", error.message);
}
return false;
}
// Function to kill preview server
function killPreviewServer() {
return new Promise((resolve) => {
console.log("Stopping preview server...");
exec("node kill-server.js", (error, stdout, stderr) => {
if (error) {
console.log("No preview server running");
} else {
console.log("Preview server stopped");
}
resolve();
});
});
}
// Main deploy function
async function deploy() {
console.log("Checking target directory...");
// Kill preview server first
await killPreviewServer();
console.log("");
// Check if target directory exists
if (!fs.existsSync(TARGET_PATH)) {
console.error(`Target directory does not exist: ${TARGET_PATH}`);
console.log("Make sure you're running this from the admin directory");
console.log(
"Or specify the correct target directory: node deploy.js /path/to/main/website"
);
process.exit(1);
}
// Check if target has the expected structure
const expectedFiles = config.requiredTargetFiles;
const missingFiles = expectedFiles.filter(
(file) => !fs.existsSync(path.join(TARGET_PATH, file))
);
if (missingFiles.length > 0) {
console.error(
`Target directory missing required files: ${missingFiles.join(", ")}`
);
console.log(
"Make sure you're pointing to the correct main website directory"
);
process.exit(1);
}
console.log("Target directory validated");
console.log("");
// Create backup
console.log("Creating backup...");
createBackup();
console.log("");
// Copy files
console.log("Copying files...");
let successCount = 0;
let totalCount = FILES_TO_COPY.length;
for (const file of FILES_TO_COPY) {
console.log(`${file.description}...`);
const success = copyFileOrDir(file.source, file.target, file.isDirectory);
if (success) {
console.log(` ${file.source}${file.target}`);
successCount++;
} else {
console.log(` Failed to copy ${file.source}`);
}
}
console.log("");
console.log("Deploy Summary");
console.log("==============");
console.log(`Successfully copied: ${successCount}/${totalCount} files`);
if (successCount === totalCount) {
console.log("Deploy completed successfully!");
console.log("");
console.log("Your website has been updated with the latest changes.");
console.log("You can now visit your main website to see the changes.");
} else {
console.log("Deploy completed with some errors.");
console.log("Check the error messages above and try again.");
process.exit(1);
}
}
// Run deploy
deploy().catch((error) => {
console.error("Deploy failed:", error.message);
process.exit(1);
});