Skip to content

Instantly share code, notes, and snippets.

@alibalbars
Created June 23, 2025 13:34
Show Gist options
  • Save alibalbars/658b9c6899e68691586f836a088430cd to your computer and use it in GitHub Desktop.
Save alibalbars/658b9c6899e68691586f836a088430cd to your computer and use it in GitHub Desktop.
test3.js
console.log('--- Running Fetch Translations Script ---');
const fs = require('fs');
const path = require('path');
const {execSync} = require('child_process');
const fetchScriptPath = path.resolve(process.cwd(), 'scripts/locale/fetch-translations.js');
const MAGENTA = '\x1b[35m';
const RESET = '\x1b[0m';
const RED = '\x1b[38;5;197m';
const DEBUG_PREFIX = 'DEBUG_LOG: ';
function fileExists(filePath) {
return fs.existsSync(filePath);
}
function isTranslationsFileEmptyOrInvalid(filePath) {
if (!fileExists(filePath)) {
console.log(DEBUG_PREFIX + 'Condition: !fileExists(filePath) is true');
console.log(`File not found: ${filePath}`);
return true;
}
console.log(DEBUG_PREFIX + 'Condition: !fileExists(filePath) is false');
try {
const content = fs.readFileSync(filePath, 'utf8');
console.log(DEBUG_PREFIX + `Content of ${filePath}:`);
console.log(content);
if (content.trim() === '') {
console.log(DEBUG_PREFIX + "Condition: content.trim() === '' is true");
console.log(`File is empty: ${filePath}`);
return true;
}
console.log(DEBUG_PREFIX + "Condition: content.trim() === '' is false");
const obj = JSON.parse(content);
console.log(DEBUG_PREFIX + 'Parsed object (obj):', obj);
console.log(DEBUG_PREFIX + 'Keys of parsed object (Object.keys(obj)):', Object.keys(obj));
console.log(DEBUG_PREFIX + 'Number of keys (Object.keys(obj).length):', Object.keys(obj).length);
const isEmptyObject = Object.keys(obj).length === 0;
if (isEmptyObject) {
console.log(DEBUG_PREFIX + 'Condition: isEmptyObject is true');
console.log(`File contains an empty JSON object: ${filePath}`);
} else {
console.log(DEBUG_PREFIX + 'Condition: isEmptyObject is false');
}
return isEmptyObject;
} catch (error) {
console.log(DEBUG_PREFIX + 'Catch block in isTranslationsFileEmptyOrInvalid entered');
console.error(`Error parsing JSON from ${filePath}:`, error.message);
console.warn('Treating file as invalid/empty due to parsing error. Will attempt to fetch.');
return true;
}
}
function runFetchScript() {
if (!fileExists(fetchScriptPath)) {
console.log(DEBUG_PREFIX + 'Condition: !fileExists(fetchScriptPath) is true');
console.error(`${MAGENTA}ERROR: Fetch script not found at ${fetchScriptPath}${RESET}`);
throw new Error(`Fetch script not found at ${fetchScriptPath}`);
}
console.log(DEBUG_PREFIX + 'Condition: !fileExists(fetchScriptPath) is false');
try {
console.log(`Executing: node ${fetchScriptPath}`);
execSync(`node ${fetchScriptPath}`, {stdio: 'inherit'}); // stdio: 'inherit' will show the script's output
console.log('Fetch script executed successfully.');
} catch (error) {
console.log(DEBUG_PREFIX + 'Catch block in runFetchScript entered');
console.error(`${MAGENTA}ERROR: Failed to execute fetch script: ${fetchScriptPath}${RESET}`);
console.error(error.message);
if (error.stdout) {
console.log(DEBUG_PREFIX + 'Condition: error.stdout is true');
console.error('STDOUT:', error.stdout.toString());
}
if (error.stderr) {
console.log(DEBUG_PREFIX + 'Condition: error.stderr is true');
console.error('STDERR:', error.stderr.toString());
}
throw new Error(`Failed to execute fetch script: ${fetchScriptPath}`);
}
}
function fetchCdnJson(url) {
console.log(DEBUG_PREFIX + `Fetching CDN JSON from: ${url}`);
try {
const jsonString = execSync(`curl -sSLf "${url}"`, {encoding: 'utf8'});
const parsedJson = JSON.parse(jsonString);
console.log(DEBUG_PREFIX + 'Successfully fetched and parsed CDN JSON.');
return parsedJson;
} catch (error) {
console.error(`${RED}ERROR: Failed to fetch or parse JSON from CDN: ${url}${RESET}`);
if (error.message) {
console.error(error.message);
}
if (error.stderr && error.stderr.toString().trim() !== '') {
console.error('STDERR (curl):', error.stderr.toString());
}
if (error.stdout && error.stdout.toString().trim() !== '') {
console.error('STDOUT (curl):', error.stdout.toString());
}
return null;
}
}
function compareTrKeysAndFailIfNeeded() {
const cdnTrFileUrl = process.env.TRANSLATION_SOURCE_FILE_CDN_PATH;
const localTrFilePath = path.resolve(process.cwd(), 'src/locales/messages.tr-tr.src.json');
if (!cdnTrFileUrl) {
console.log(
`${MAGENTA}Skipping Turkish translation key comparison: TRANSLATION_SOURCE_FILE_CDN_PATH environment variable is not set.${RESET}`
);
return;
}
console.log(DEBUG_PREFIX + `TRANSLATION_SOURCE_FILE_CDN_PATH: ${cdnTrFileUrl}`);
console.log(DEBUG_PREFIX + `Local TR file path: ${localTrFilePath}`);
if (!fileExists(localTrFilePath)) {
console.warn(
`${MAGENTA}WARNING: Local Turkish translation file not found at ${localTrFilePath}. Cannot perform key comparison.${RESET}`
);
return;
}
let localTrJson;
try {
const localTrContent = fs.readFileSync(localTrFilePath, 'utf8');
localTrJson = JSON.parse(localTrContent);
} catch (error) {
console.error(`${RED}ERROR: Failed to read or parse local Turkish translation file: ${localTrFilePath}${RESET}`);
console.error(error.message);
throw new Error(`Failed to read or parse local Turkish translation file: ${localTrFilePath}`);
}
const cdnTrJson = fetchCdnJson(cdnTrFileUrl);
if (!cdnTrJson) {
console.error(
`${RED}Failed to proceed with comparison due to error fetching/parsing CDN TR JSON. Please check CDN URL and file content.${RESET}`
);
throw new Error('Failed to fetch/parse CDN TR JSON.');
}
const localKeys = Object.keys(localTrJson);
const cdnKeys = new Set(Object.keys(cdnTrJson));
const missingKeysInCdn = localKeys.filter(key => !cdnKeys.has(key));
if (missingKeysInCdn.length > 0) {
console.error(
`${RED}ERROR: Missing keys in CDN Turkish translation file (${cdnTrFileUrl}) compared to local file (${localTrFilePath}).${RESET}`
);
console.error(
`${RED}The following keys exist locally in '${path.basename(
localTrFilePath
)}' but are missing in the CDN version from the translations repository:${RESET}`
);
missingKeysInCdn.forEach(key => console.error(`${RED}- ${key}${RESET}`));
console.error(
`${RED}Please add these message keys and their Turkish translations into the translation repository to resolve this issue.${RESET}`
);
throw new Error('Missing keys in CDN Turkish translation file.');
} else {
console.log(
`${MAGENTA}Turkish translation key comparison successful: All keys from local '${path.basename(
localTrFilePath
)}' are present in the CDN version.${RESET}`
);
}
}
function logFinalTranslations(filePath) {
console.log(`${MAGENTA}--- Final content of ${path.basename(filePath)} being used: ---${RESET}`);
try {
if (fileExists(filePath)) {
const content = fs.readFileSync(filePath, 'utf8');
console.log(content);
} else {
console.log(`${RED}File not found: ${filePath}. Cannot log its content.${RESET}`);
}
} catch (error) {
console.error(`${RED}Error reading ${filePath} to log its content: ${error.message}${RESET}`);
}
console.log(`${MAGENTA}--- End of ${path.basename(filePath)} content ---${RESET}`);
}
// --- Main logic ---
const enTranslationsFilePath = path.resolve(process.cwd(), 'src/locales/messages.en-us.json');
const arTranslationsFilePath = path.resolve(process.cwd(), 'src/locales/messages.ar-ae.json');
const translationsToProcess = [
{name: 'English', path: enTranslationsFilePath},
{name: 'Arabic', path: arTranslationsFilePath},
];
const needsFetching = translationsToProcess.some(file => {
const isInvalid = isTranslationsFileEmptyOrInvalid(file.path);
if (isInvalid) {
console.log(
DEBUG_PREFIX + `File ${path.basename(file.path)} is empty or invalid. Translation fetching is required.`
);
}
return isInvalid;
});
if (needsFetching) {
console.log(`${MAGENTA}MODE: Fetch from CDN for required translations.${RESET}`);
runFetchScript();
} else {
console.log(`${MAGENTA}MODE: Using local files for all translations.${RESET}`);
}
translationsToProcess.forEach(file => {
logFinalTranslations(file.path);
console.log(`${file.name} translation file check complete.`);
});
console.log(`${MAGENTA}--- Running Turkish Translation Key Comparison ---${RESET}`);
compareTrKeysAndFailIfNeeded();
console.log('All translation checks complete.');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment