i18n:Update the translation tool guide

This commit is contained in:
月月
2025-07-13 13:19:53 +08:00
parent 99af57fbc6
commit bdb7657e22
@@ -1,246 +1,287 @@
# Translation Management Tool Suite
This tool suite is used to manage project translation files, automatically extract translatable texts, compare differences between different language files, and provide maintenance functions.
This suite is used to manage project translation files, automatically extract translatable texts, compare differences between language files, and provide maintenance functions.
## Tool Components
### 1. `translation-manager.py` - Main Translation Manager
- Extract translatable texts
- Compare and update translation files
- Interactive adding/removing translation keys
- Interactive addition/removal of translation keys
### 2. `translation-cleaner.py` - Translation File Maintenance Tool
- Clean unused translation keys
- Sync key structure across different language files
- Synchronize key structure across different language files
### 3. `manage-translations.sh` - Convenient Wrapper Script
- Provide unified command-line interface
- Display translation status
- Simplify common operations
- Provides a unified command-line interface
- Displays translation status
- Simplifies common operations
## Quick Start
### Check Translation Status
### Using the Wrapper Script (Recommended)
```bash
# Enter the tools directory
cd .config/quickshell/translations/tools
# Show help
./manage-translations.sh --help
# Show current translation status
./manage-translations.sh status
```
### Extract Translatable Texts
```bash
# Extract translatable texts
./manage-translations.sh extract
```
### Update Translation Files
```bash
# Update all languages
# Update all translation files
./manage-translations.sh update
# Update specific language
# Update a specific language
./manage-translations.sh update -l zh_CN
```
### Clean Unused Keys
```bash
# Clean unused keys
./manage-translations.sh clean
# Synchronize keys across all language files
./manage-translations.sh sync
```
### Sync Keys Across Languages
Or run from the project root:
```bash
./manage-translations.sh sync
# Run from the project root
.config/quickshell/translations/tools/manage-translations.sh status
.config/quickshell/translations/tools/manage-translations.sh update
```
## Detailed Usage
### translation-manager.py
### Translation Manager (`translation-manager.py`)
The main translation management tool that extracts translatable texts from source code and manages translation files.
#### Command Line Options
Basic usage:
```bash
python3 translation-manager.py [options]
# Process all languages
./translation-manager.py
Options:
-h, --help Show help message
-t, --translations-dir DIR Translation files directory (default: .config/quickshell/translations)
-s, --source-dir DIR Source code directory (default: .config/quickshell)
-l, --language LANG Specify language code to process (e.g., zh_CN)
-e, --extract-only Only extract translatable texts to temporary file
--show-temp Show temporary extracted file content
# Specify a particular language
./translation-manager.py --language zh_CN
# Extract translatable texts only
./translation-manager.py --extract-only
# Show extracted texts
./translation-manager.py --extract-only --show-temp
```
#### Features
1. **Text Extraction**: Uses regex patterns to extract translatable texts from QML and JavaScript files
2. **Smart Filtering**: Automatically removes duplicates and cleans up extracted texts
3. **Interactive Updates**: Guides users through adding missing keys and removing extra ones
4. **Backup Support**: Creates backups before making changes
Parameter description:
- `--translations-dir`, `-t`: Translation files directory (default: `.config/quickshell/translations`)
- `--source-dir`, `-s`: Source code directory (default: `.config/quickshell`)
- `--language`, `-l`: Specify the language code to process
- `--extract-only`, `-e`: Only extract translatable texts
- `--show-temp`: Show the content of the temporary extraction file
#### Supported Text Patterns
- `qsTr("text")` and `qsTr('text')`
- `i18n.t("text")` and `i18n.t('text')`
- Supports nested quotes and escape characters
- Handles multiline strings
### Translation Cleaner (`translation-cleaner.py`)
### translation-cleaner.py
A maintenance tool for cleaning up and synchronizing translation files.
#### Command Line Options
```bash
python3 translation-cleaner.py [options]
# Clean unused translation keys
./translation-cleaner.py --clean
Options:
-h, --help Show help message
-t, --translations-dir DIR Translation files directory
-s, --source-dir DIR Source code directory
-c, --clean Clean unused translation keys
--sync Sync translation keys
--source-lang LANG Source language for syncing (default: en_US)
--no-backup Do not create backup files when cleaning
# Synchronize translation keys (using en_US as the base)
./translation-cleaner.py --sync
# Specify a different source language for syncing
./translation-cleaner.py --sync --source-lang zh_CN
# Clean without creating backups
./translation-cleaner.py --clean --no-backup
```
#### Features
1. **Unused Key Cleanup**: Identifies and removes translation keys that are no longer used in the source code
2. **Key Synchronization**: Ensures all language files have the same set of keys
3. **Backup Protection**: Creates backup files before making destructive changes
4. **Interactive Confirmation**: Asks for user confirmation before deleting keys
## Workflow
### manage-translations.sh
### Regular Translation Update Workflow
A convenient wrapper script that provides a unified interface to all translation tools.
1. **Check status**:
```bash
./manage-translations.sh status
```
2. **Update translations**:
```bash
./manage-translations.sh update
```
3. **Clean unused keys** (optional):
```bash
./manage-translations.sh clean
```
### Adding a New Language
1. **Create a new language file**:
```bash
./manage-translations.sh update -l new_lang
```
2. **Synchronize key structure**:
```bash
./manage-translations.sh sync
```
### Cleanup After Large Refactoring
1. **Backup translation files**:
```bash
cp -r .config/quickshell/translations .config/quickshell/translations.backup
```
2. **Clean unused keys**:
```bash
./manage-translations.sh clean
```
3. **Synchronize all languages**:
```bash
./manage-translations.sh sync
```
## Supported Translatable Text Formats
The tool recognizes the following formats for translatable texts:
```qml
// Basic format
Translation.tr("Hello, world!")
Translation.tr('Hello, world!')
Translation.tr(`Hello, world!`)
// With line breaks
Translation.tr("Line 1\nLine 2")
// With escape characters
Translation.tr("Say \"Hello\"")
// With parameter placeholders
Translation.tr("Hello, %1!").arg(name)
Translation.tr("{0} files selected").arg(count)
```
## Example Output
### Status Display
```
$ ./manage-translations.sh status
Analyzing translation status...
=== Current Project Status ===
166 translatable texts extracted
=== Translation File Status ===
en_US: 470 keys
zh_CN: 470 keys
```
### Update Translations
```
$ ./manage-translations.sh update -l zh_CN
Updating translation files...
==================================================
Processing language: zh_CN
==================================================
Analysis result:
Missing keys: 5
Extra keys: 20
Found 5 missing translation keys:
1. "New feature text"
2. "Another new text"
...
Add these 5 missing keys? (y/n): y
5 keys added
Found 20 extra translation keys:
1. "Removed old text" -> "已删除的旧文本"
...
Delete these 20 extra keys? (y/n): y
20 keys deleted
Translation file saved
```
### Clean Unused Keys
```
$ ./manage-translations.sh clean
Cleaning unused translation keys...
Processing language: zh_CN
Found 50 unused keys:
1. "old_unused_text"
2. "deprecated_message"
...
Delete these 50 unused keys? (y/n): y
50 keys deleted
Original key count: 470, after cleaning: 420
```
## Advanced Features
### Custom Directory Structure
#### Commands
```bash
./manage-translations.sh [options] <command>
Commands:
extract Extract translatable texts to temporary file
update Update translation files (add missing/remove extra keys)
clean Clean unused translation keys
sync Sync keys across all language files
status Show translation status
Options:
-l, --lang LANG Specify language (e.g.: zh_CN)
-t, --trans-dir DIR Translation files directory
-s, --source-dir DIR Source code directory
-h, --help Show help message
# Use custom directories
./translation-manager.py \
--translations-dir /path/to/translations \
--source-dir /path/to/source
```
## Workflow Examples
### Batch Processing
### Initial Setup
1. Create translation directory structure
2. Extract all translatable texts: `./manage-translations.sh extract`
3. Create initial translation files: `./manage-translations.sh update`
```bash
# Create a processing script
cat > update-all-translations.sh << 'EOF'
#!/bin/bash
for lang in zh_CN ja_JP ko_KR; do
echo "Processing $lang..."
./manage-translations.sh update -l $lang
done
EOF
### Regular Maintenance
1. Check status: `./manage-translations.sh status`
2. Update translations after code changes: `./manage-translations.sh update`
3. Clean up unused keys periodically: `./manage-translations.sh clean`
### Adding New Language
1. Create new language file: `./manage-translations.sh update -l new_lang`
2. Sync keys if needed: `./manage-translations.sh sync`
## File Structure
```
translations/
├── tools/ # Translation management tools
│ ├── translation-manager.py # Main extraction and update tool
│ ├── translation-cleaner.py # Cleanup and sync tool
│ ├── manage-translations.sh # Wrapper script
│ └── translation-tools-guide.md # This documentation
├── en_US.json # English translations (reference)
├── zh_CN.json # Chinese translations
└── [other_lang].json # Other language files
chmod +x update-all-translations.sh
./update-all-translations.sh
```
## Configuration
## Notes
### Text Extraction Patterns
1. **Backup is important**: The tool automatically creates backups before cleaning, but it is recommended to manually back up important files
The tool uses regex patterns to identify translatable texts. Current patterns include:
2. **Text extraction limitations**:
- Only supports static strings, not dynamically constructed strings
- Must use the `Translation.tr()` format
1. **QML qsTr patterns**:
- `qsTr("text")` and `qsTr('text')`
- Supports escaped quotes and nested quotes
3. **File encoding**: All files must use UTF-8 encoding
2. **JavaScript i18n patterns**:
- `i18n.t("text")` and `i18n.t('text')`
- Supports template literals and complex expressions
3. **Custom patterns** can be added by modifying the patterns list in `translation-manager.py`
### File Extensions
By default, the tool processes:
- `.qml` files (QML/QtQuick)
- `.js` files (JavaScript)
Additional file types can be added by modifying the file extension filters.
## Best Practices
1. **Regular Updates**: Run `./manage-translations.sh status` regularly to check for new translatable texts
2. **Clean Periodically**: Use `./manage-translations.sh clean` to remove unused keys
3. **Backup Important**: Always backup translation files before major changes
4. **Consistent Patterns**: Use consistent function calls (`qsTr`, `i18n.t`) for translatable texts
5. **Review Changes**: Always review the changes before confirming deletions or additions
4. **Key naming conventions**: It is recommended to use English for key names and avoid special characters
## Troubleshooting
### Common Issues
1. **Missing Texts**: If some translatable texts are not extracted, check if they match the supported patterns
2. **Path Issues**: Ensure the source and translation directory paths are correct
3. **Permission Errors**: Make sure the script has write permissions to the translation directory
4. **Encoding Issues**: All files should be saved in UTF-8 encoding
**Q: The number of extracted texts does not match expectations?**
A: Check whether all translatable texts use the `Translation.tr()` format and ensure there are no dynamically constructed strings.
### Getting Help
**Q: Some translations are missing after syncing?**
A: Check whether the source language file contains all necessary keys, and consider using a different source language for syncing.
For additional help:
- Use `--help` option with any tool
- Check the console output for error messages
- Verify file paths and permissions
**Q: The cleaning operation deleted needed keys?**
A: Restore from the automatically created backup file and check whether `Translation.tr()` is used correctly in the source code.
## Advanced Usage
### Custom Regex Patterns
To add support for new translation function patterns, modify the `patterns` list in `TranslationManager.extract_translatable_texts()`:
```python
patterns = [
# Existing patterns...
r'customTranslate\s*\(\s*(["\'])((?:\\.|(?!\1)[^\\])*?)\1\s*\)', # Custom pattern
]
```
### Batch Processing
For processing multiple projects or directories:
### Restore Backup
```bash
# Process multiple directories
for dir in project1 project2 project3; do
./manage-translations.sh -s "$dir" -t "$dir/translations" update
done
# Restore a single file
cp .config/quickshell/translations/zh_CN.json.backup .config/quickshell/translations/zh_CN.json
# Restore all files
cp .config/quickshell/translations.backup/* .config/quickshell/translations/
```
### Integration with Build Systems
The tools can be integrated into build systems to automatically update translations:
```bash
# In your build script
./manage-translations.sh update --non-interactive
```
## Version History
- **v1.0**: Initial version with basic extraction and update functionality
- **v1.1**: Added improved regex patterns for better text extraction
- **v1.2**: Added cleaning and synchronization tools
- **v1.3**: Added English output and improved user interface
- **v1.4**: Moved all tools to dedicated tools directory and improved documentation