lingotags
Version:
[](https://opensource.org/licenses/MIT) [](https://www.npmjs.com/package/lingotags)
151 lines (143 loc) • 6.87 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateTranslationTags = generateTranslationTags;
const fs_1 = __importDefault(require("fs"));
const glob_1 = require("glob");
const path_1 = __importDefault(require("path"));
const searchPatterns_1 = require("./utils/searchPatterns");
const utils_1 = require("./utils/utils");
async function generateTranslationTags(config) {
const finalConfig = {
filePattern: "**/*.{html,tsx,jsx,js,ts}",
verbose: false,
...config,
manifest: path_1.default.resolve(process.cwd(), config.manifest || "lingotags-manifest.json"),
};
try {
const searchPath = path_1.default.resolve(process.cwd(), finalConfig.searchDirectory);
console.log("Resolved search path:", searchPath);
console.log("Directory contents:");
try {
const contents = fs_1.default.readdirSync(searchPath, { recursive: true });
console.log(contents);
}
catch (error) {
console.error("Error reading directory:", error);
}
if (!fs_1.default.existsSync(searchPath)) {
throw new Error(`Target directory not found: ${searchPath}`);
}
try {
const contents = fs_1.default.readdirSync(searchPath, { recursive: true });
(0, utils_1.logVerbose)(finalConfig.verbose, `📂 Processing directory: ${searchPath}`);
(0, utils_1.logVerbose)(finalConfig.verbose, `📄 Found ${contents.length} items: ${contents.join(", ")}`);
}
catch (error) {
console.error(`❌ Error reading directory ${searchPath}: ${error.message}`);
throw error;
}
const pattern = finalConfig.filePattern?.replace(/\\/g, "/") || "**/*.html";
console.log("Search pattern:", pattern);
const allFiles = await (0, glob_1.glob)(pattern, {
cwd: searchPath,
absolute: true,
windowsPathsNoEscape: true,
});
(0, utils_1.initializeKeyCounter)(allFiles);
const initialKeyCounter = (0, utils_1.getGlobalKeyCounter)();
console.log(`🔑 Initialized key counter at: ${initialKeyCounter}`);
const output = {};
const fileChanges = [];
allFiles.forEach((filePath) => {
try {
(0, utils_1.logVerbose)(finalConfig.verbose, `🔍 Scanning file: ${filePath}`);
const fileContent = fs_1.default.readFileSync(filePath, "utf-8");
if (!fileContent.trim()) {
(0, utils_1.logVerbose)(finalConfig.verbose, `⏩ Skipped empty file: ${filePath}`);
return;
}
const { modifiedContent, matches, originalContent } = (0, utils_1.processFileContent)(fileContent, searchPatterns_1.searchPatterns);
if (matches.length === 0) {
(0, utils_1.logVerbose)(finalConfig.verbose, `➖ No tags found in ${path_1.default.basename(filePath)}`);
return;
}
(0, utils_1.logVerbose)(finalConfig.verbose, `✅ Found ${matches.length} tags in ${path_1.default.basename(filePath)}`);
output[filePath] = matches;
if (modifiedContent !== originalContent) {
fs_1.default.writeFileSync(filePath, modifiedContent, "utf-8");
(0, utils_1.logVerbose)(finalConfig.verbose, `💾 Saved changes to ${path_1.default.basename(filePath)}`);
}
fileChanges.push({
filePath,
original: originalContent,
modified: modifiedContent,
});
(0, utils_1.logVerbose)(finalConfig.verbose, `Processed ${matches.length} tags in ${filePath}`);
if (matches.length > (0, utils_1.getGlobalKeyCounter)()) {
(0, utils_1.setGlobalKeyCounter)(matches.length);
}
}
catch (error) {
console.error(`❌ Error processing ${filePath}: ${error.message}`);
throw error;
}
});
(0, utils_1.writeManifest)(finalConfig.manifest, initialKeyCounter, fileChanges);
console.log(`📦 Manifest file created: ${finalConfig.manifest}`);
(0, utils_1.writeOutputFile)(finalConfig.outputFile, output);
console.log("Translation tags generated successfully. " +
`Output file: ${finalConfig.outputFile}`);
// After processing all files, create locale file
const localesDir = path_1.default.join(process.cwd(), "locales");
if (!fs_1.default.existsSync(localesDir)) {
fs_1.default.mkdirSync(localesDir, { recursive: true });
}
const langFile = path_1.default.join(localesDir, `${config.defaultLanguage || "en"}.json`);
const translations = {};
// Flatten all translations into single object
Object.values(output).forEach((matches) => {
matches.forEach((match) => {
translations[match.key] = match.content;
});
});
// Use the new exportTranslations function
(0, utils_1.exportTranslations)(langFile, translations, true);
console.log(`🌐 Updated language file: ${langFile}`);
// Also create a README.md with instructions for the locales directory if it doesn't exist
const readmePath = path_1.default.join(localesDir, "README.md");
if (!fs_1.default.existsSync(readmePath)) {
const readmeContent = `# Translation Files
This directory contains the translation files for your application.
## Usage
To use these translations in your React components:
\`\`\`jsx
// Import the translation function
import { useTranslation } from 'your-translation-library'; // e.g., react-i18next
function MyComponent() {
// Initialize the translation function
const { t } = useTranslation();
return (
<div>
<h1>{t('unique_key_1')}</h1>
<p>{t('unique_key_2')}</p>
</div>
);
}
\`\`\`
## Adding New Languages
To add a new language, create a new JSON file with the language code as the filename, for example \`fr.json\` for French.
Copy the content from \`${config.defaultLanguage || "en"}.json\` and translate the values.
`;
fs_1.default.writeFileSync(readmePath, readmeContent, "utf-8");
console.log(`📘 Created README for translations: ${readmePath}`);
}
}
catch (error) {
console.error(`🚨 Translation generation failed: ${error.message}`);
process.exit(1);
}
}
//# sourceMappingURL=translationGenerator.js.map