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 # 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 ## Tool Components
### 1. `translation-manager.py` - Main Translation Manager ### 1. `translation-manager.py` - Main Translation Manager
- Extract translatable texts - Extract translatable texts
- Compare and update translation files - Compare and update translation files
- Interactive adding/removing translation keys - Interactive addition/removal of translation keys
### 2. `translation-cleaner.py` - Translation File Maintenance Tool ### 2. `translation-cleaner.py` - Translation File Maintenance Tool
- Clean unused translation keys - 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 ### 3. `manage-translations.sh` - Convenient Wrapper Script
- Provide unified command-line interface - Provides a unified command-line interface
- Display translation status - Displays translation status
- Simplify common operations - Simplifies common operations
## Quick Start ## Quick Start
### Check Translation Status ### Using the Wrapper Script (Recommended)
```bash ```bash
# Enter the tools directory
cd .config/quickshell/translations/tools
# Show help
./manage-translations.sh --help
# Show current translation status
./manage-translations.sh status ./manage-translations.sh status
```
### Extract Translatable Texts # Extract translatable texts
```bash
./manage-translations.sh extract ./manage-translations.sh extract
```
### Update Translation Files # Update all translation files
```bash
# Update all languages
./manage-translations.sh update ./manage-translations.sh update
# Update specific language # Update a specific language
./manage-translations.sh update -l zh_CN ./manage-translations.sh update -l zh_CN
```
### Clean Unused Keys # Clean unused keys
```bash
./manage-translations.sh clean ./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 ```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 ## 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. Basic usage:
#### Command Line Options
```bash ```bash
python3 translation-manager.py [options] # Process all languages
./translation-manager.py
Options: # Specify a particular language
-h, --help Show help message ./translation-manager.py --language zh_CN
-t, --translations-dir DIR Translation files directory (default: .config/quickshell/translations)
-s, --source-dir DIR Source code directory (default: .config/quickshell) # Extract translatable texts only
-l, --language LANG Specify language code to process (e.g., zh_CN) ./translation-manager.py --extract-only
-e, --extract-only Only extract translatable texts to temporary file
--show-temp Show temporary extracted file content # Show extracted texts
./translation-manager.py --extract-only --show-temp
``` ```
#### Features Parameter description:
1. **Text Extraction**: Uses regex patterns to extract translatable texts from QML and JavaScript files - `--translations-dir`, `-t`: Translation files directory (default: `.config/quickshell/translations`)
2. **Smart Filtering**: Automatically removes duplicates and cleans up extracted texts - `--source-dir`, `-s`: Source code directory (default: `.config/quickshell`)
3. **Interactive Updates**: Guides users through adding missing keys and removing extra ones - `--language`, `-l`: Specify the language code to process
4. **Backup Support**: Creates backups before making changes - `--extract-only`, `-e`: Only extract translatable texts
- `--show-temp`: Show the content of the temporary extraction file
#### Supported Text Patterns ### Translation Cleaner (`translation-cleaner.py`)
- `qsTr("text")` and `qsTr('text')`
- `i18n.t("text")` and `i18n.t('text')`
- Supports nested quotes and escape characters
- Handles multiline strings
### translation-cleaner.py
A maintenance tool for cleaning up and synchronizing translation files.
#### Command Line Options
```bash ```bash
python3 translation-cleaner.py [options] # Clean unused translation keys
./translation-cleaner.py --clean
Options: # Synchronize translation keys (using en_US as the base)
-h, --help Show help message ./translation-cleaner.py --sync
-t, --translations-dir DIR Translation files directory
-s, --source-dir DIR Source code directory # Specify a different source language for syncing
-c, --clean Clean unused translation keys ./translation-cleaner.py --sync --source-lang zh_CN
--sync Sync translation keys
--source-lang LANG Source language for syncing (default: en_US) # Clean without creating backups
--no-backup Do not create backup files when cleaning ./translation-cleaner.py --clean --no-backup
``` ```
#### Features ## Workflow
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
### 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 ```bash
./manage-translations.sh [options] <command> # Use custom directories
./translation-manager.py \
Commands: --translations-dir /path/to/translations \
extract Extract translatable texts to temporary file --source-dir /path/to/source
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
``` ```
## Workflow Examples ### Batch Processing
### Initial Setup ```bash
1. Create translation directory structure # Create a processing script
2. Extract all translatable texts: `./manage-translations.sh extract` cat > update-all-translations.sh << 'EOF'
3. Create initial translation files: `./manage-translations.sh update` #!/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 chmod +x update-all-translations.sh
1. Check status: `./manage-translations.sh status` ./update-all-translations.sh
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
``` ```
## 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**: 3. **File encoding**: All files must use UTF-8 encoding
- `qsTr("text")` and `qsTr('text')`
- Supports escaped quotes and nested quotes
2. **JavaScript i18n patterns**: 4. **Key naming conventions**: It is recommended to use English for key names and avoid special characters
- `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
## Troubleshooting ## Troubleshooting
### Common Issues ### Common Issues
1. **Missing Texts**: If some translatable texts are not extracted, check if they match the supported patterns **Q: The number of extracted texts does not match expectations?**
2. **Path Issues**: Ensure the source and translation directory paths are correct A: Check whether all translatable texts use the `Translation.tr()` format and ensure there are no dynamically constructed strings.
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
### 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: **Q: The cleaning operation deleted needed keys?**
- Use `--help` option with any tool A: Restore from the automatically created backup file and check whether `Translation.tr()` is used correctly in the source code.
- Check the console output for error messages
- Verify file paths and permissions
## Advanced Usage ### Restore Backup
### 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:
```bash ```bash
# Process multiple directories # Restore a single file
for dir in project1 project2 project3; do cp .config/quickshell/translations/zh_CN.json.backup .config/quickshell/translations/zh_CN.json
./manage-translations.sh -s "$dir" -t "$dir/translations" update
done # 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