Crowdin CLI uses a configuration file that contains a description of the resources to manage: files to be uploaded into Crowdin and the locations of the corresponding translations.
Щоб використовувати Crowdin CLI, ви повинні спочатку згенерувати файл конфігурації, а потім запустити інструмент. By default, Crowdin CLI looks for a configuration file named crowdin.yml (so you don’t have to specify the file name unless it’s different from crowdin.yml).
Для створення файлу конфігурації виконайте наступну команду:
$ crowdin init
A valid Crowdin CLI configuration file has the following structure, so please make sure that you fill out all the needed information:
A typical configuration file looks similar to the following:
"project_id": "projectId" #open project and go to Resources > Integrations & API > Integration tool
"api_token": "personal-access-token" #open project and go to Resources > Integrations & API > Integration tool
"base_path": "/project-base-path"
"base_url": "https://{organization-name}.crowdin.com"
"files": [
{
"source": "/locale/en/folder1/[0-2].txt", #source files filter
"translation": "/locale/%two_letters_code%/folder1/%original_file_name%" #where translations are stored
},
{
"source": "/locale/en/folder2/[0-2].txt",
"translation": "/locale/%two_letters_code%/folder2/%original_file_name%"
}
]
To run the above configuration file and upload source files to Crowdin Enterprise:
$ crowdin upload sources
Get translations from Crowdin Enterprise and put them in the right locations:
$ crowdin download
Ви можете завантажити облікові дані API зі змінної оточення, наприклад:
"project_id_env": "CROWDIN_PROJECT_ID"
"api_token_env": "CROWDIN_PERSONAL_TOKEN"
"base_path_env": "CROWDIN_BASE_PATH"
"base_url_env": "CROWDIN_BASE_URL"
При змішуванні api_token і project_id мають перевагу:
"project_id_env": "CROWDIN_PROJECT_ID" # Low priority
"api_token_env": "CROWDIN_PERSONAL_TOKEN" # Low priority
"base_path_env": "CROWDIN_BASE_PATH" # Low priority
"base_url_env": "CROWDIN_BASE_PATH" # Low priority
"project_id": "projectId" # High priority
"api_token": "personal-access-token" # High priority
"base_path": "/project-base-path" # High priority
"base_url": "https://{organization-name}.crowdin.com" # High priority
The crowdin.yml file contains a description of the resources to manage and API credentials (project_id, api_token, base_path, base_url). Це означає, що небезпечно, поміщати цей файл в репозиторій коду, так як ключ API буде доступний іншим користувачам. Crowdin CLI підтримує 2 типи конфігурації файлів:
Якщо вам потрібно запустити команду до призначених для користувача обліковими даними (наприклад, upload sources
) то виконайте наступну команду:
$ crowdin upload sources --identity 'path-to-user-credentials-file'
Але якщо файл призначених для користувача облікових даних знаходиться в $HOME/.crowdin.yml, ви можете просто запустити:
$ crowdin upload sources
Наведений вище приклад конфігурації має атрибути ‘source’ і ‘translation’, які містять стандартні постановочні знаки (також відомі як універсальні шаблони) для спрощення роботи з декількома файлами.
Ось шаблони, які ви можете використовувати:
* (зірочка)
Являє собою всякий символ в імені файлу або каталогу. Якщо ви виберете “*.json”, він буде включати всі файли, такі як “messages.json”, “about_us.json”, і все, що закінчується на “.json”.
*** (подвійна зірочка)
Збігається з будь-яким рядком рекурсивно (включаючи підпапки). Зверніть увагу, що ви можете використовувати ** і в шаблонах source і translation. При використанні ** в шаблоні translation, він завжди буде містити підшлях з source для конкретного файлу. Наприклад, ви можете використовувати source: ‘/en/**/*.po’, щоб завантажити в Crowdin все рекурсивні файли *.po. Шаблон перекладу буде ‘/%two_letters_code%/**/%original_file_name%’.
? (знак питання)
Відповідає будь-якому одному символу.
[set]
Відповідає будь-якому одному символу в наборі. Behaves exactly like character sets in Regexp, including set negation ([^a-z]).
\ (зворотний слеш)
Пропускає такий метасимвол.
У Crowdin CLI можна використовувати наступні наповнювачі для внесення відповідних змінних в результуюче ім’я файлу:
Ім'я | Опис |
---|---|
%language% | Language name (e.g., Ukrainian) |
%two_letters_code% | Language code ISO 639-1 (e.g., uk) |
%three_letters_code% | Language code ISO 639-2/T (e.g., ukr) |
%locale% | Locale (e.g., uk-UA) |
%locale_with_underscore% | Locale (e.g., uk_UA) |
%original_file_name% | Початкову назва файлу |
%android_code% | Ідентифікатор мови в Android використаний в назвах «values-» директорій |
%osx_code% | Локаль OS X, яка використовується для назв ".lproj" директорій |
%original_path% | Використовуйте імена батьківських папок в проекті Crowdin для створення шляху до файлу в отриманому пакеті |
%file_extension% | Початкове розширення файлу |
%file_name% | Файл без розширення |
Ви також можете вказати повний шлях до файлів в архіві, поставивши косу риску (/) на початку шаблону.
Шаблон translation
може виглядати наступним чином: “/locale/%two_letters_code%/LC_MESSAGES/%original_file_name%”.
Структура файлів і папок на локальному комп’ютері:
- base_path | |-- folder | | | |-- 1.xml | |-- 1.txt | |-- 123.txt | |-- 123_test.txt | |-- a.txt | |-- a1.txt | |-- crowdin?test.txt | |-- crowdin_test.txt | |-- 1.xml |-- 1.txt |-- 123.txt |-- 123_test.txt |-- a.txt |-- a1.txt |-- crowdin?test.txt |-- crowdin_test.txt |-- 3.txt
Приклад 1. Використання підстановних знаків у вихідному шляхуі:
#........конфігурація вашого проекту........
"files": [
{
"source": "/**/?[0-9].txt", #upload a1.txt, folder/a1.txt
"translation": "/**/%two_letters_code%_%original_file_name%"
},
{
"source": "/**/*\\?*.txt", #upload crowdin?test.txt, folder/crowdin?test.txt
"translation": "/**/%two_letters_code%_%original_file_name%"
},
{
"source": "/**/[^0-2].txt", #upload 3.txt, folder/3.txt, a.txt, folder/a.txt (ignore 1.txt, folder/1.txt)
"translation": "/**/%two_letters_code%_%original_file_name%"
}
]
Приклад 2. Використання підстановних знаків для ігнорування файлів:
#........конфігурація вашого проекту........
"files": [
{
"source": "/**/*.*", #завантажити всі файли, які містять base_path
"translation": "/**/%two_letters_code%_%original_file_name%",
"ignore": [
"/**/%two_letters_code%_%original_file_name%", #ігнорувати перекладені файли
"/**/?.txt", #ignore 1.txt, a.txt, folder/1.txt, folder/a.txt
"/**/[0-9].txt", #ignore 1.txt, folder/1.txt
"/**/*\\?*.txt", #ignore crowdin?test.txt, folder/crowdin?test.txt
"/**/[0-9][0-9][0-9].txt", #ignore 123.txt , folder/123.txt
"/**/[0-9]*_*.txt" #ignore 123_test.txt, folder/123_test.txt
]
}
]
Часто програмні проекти мають власні імена для каталогів локалі. Crowdin Enterprise дозволяє відображати власні мови, щоб вони стали відомими у ваших проектах.
Припустимо, папки з вашими Локаль називаються ‘en’, ‘uk’, ‘fr’, ‘de’. Всі вони можуть бути представлені заповнювачем %two_letters_code%. У той же час у вас є папка ‘zh_CH’. To make it work with Crowdin without changes in your project, you can set up Language Mapping. Також ви можете перевизначити коди мов для інших наповнювачів, таких як%android_code%, %locale% і т.д.
You can set up Language Mapping either via the user interface (UI) or by adding a languages_mapping
section to your file set. We recommend setting up a language mapping via UI since it eliminates the need for duplicating the languages_mapping
parameter for each file filter, but of course, you can choose the option that works best for you.
To set up Language Mapping via UI, follow these steps:
To set up Language Mapping in your configuration file, add the languages_mapping
section to your file set as shown below.
Приклад конфігурації:
"files": [
{
"source" : "/locale/en/**/*.po",
"translation" : "/locale/%two_letters_code%/**/%original_file_name%",
"languages_mapping" : {
"two_letters_code" : {
"uk" : "ukr",
"pl" : "pol"
}
}
}
]
Mapping format is the following: “crowdin_language_code” : “code_you_use”. Check the full list of Crowdin Enterprise language codes that can be used for mapping.
Якщо вам потрібно перейменувати файл з перекладами після експорту, це легко зробити за допомогою параметра ` translation_replace`.
Наприклад, якщо файл має ім’я “en_strings.po”, його можна перейменувати в “strings.po”. Для цього додайте новий параметр (на тому ж рівні, що і параметр перекладу) в файл конфігурації (crowdin.yml):
"files": [
{
"source": "/locale/**/en_*.po",
"translation": "/locale/**/%two_letters_code%_%original_file_name%",
"translation_replace": {
"en_": ""
}
}
]
У цьому випадку «_en» буде просто видалений з імені файлу.
Час від часу в Crowdin є файли і каталоги, які не вимагають перекладу. In such cases, local per-file rules can be added to the config file in your project.
"files": [
{
"source": "/**/*.properties",
"translation": "/**/%file_name%_%two_letters_code%.%file_extension%",
"ignore": [
"/test/file.properties",
"/example.properties"
]
},
{
"source": "/locale/en/**/*.po",
"translation": "/locale/%two_letters_code%/**/%original_file_name%",
"ignore": [
"/locale/en/templates",
"/locale/en/workflow"
]
}
]
If a CSV or XLS/XLSX file contains the translations for all target languages, you should specify appropriate language codes in the scheme.
Приклад файлу CSV:
identifier,source_phrase,context,Ukrainian,Russian,French ident1,Source 1,Context 1,,, ident2,Source 2,Context 2,,, ident3,Source 3,Context 3,,,
Приклад файлу конфігурації:
"files": [
{
"source": "multicolumn.csv",
"translation": "multicolumn.csv",
"first_line_contains_header": true,
"scheme": "identifier,source_phrase,context,uk,ru,fr"
}
]
If your CSV or XLS/XLSX file contains columns that should be skipped on import, use none
for such columns in the scheme, for example:
"scheme" : "identifier,source_phrase,context,uk,none,ru,none,fr"
To form the scheme for your CSV or XLS/XLSX file, use the following constants:
identifier
– Column contains string identifiers.
source_phrase
– Column contains source strings.
source_or_translation
– Column contains source strings, but the same column will be filled with translations when the file is exported. When uploading existing translations, the values from this column will be used as translations.
translation
– Column contains translations.
context
– Column contains comments or context information for the source strings.
max_length
– Column contains max.length limit values for the translations of the strings.
labels
– Column contains labels for the source strings.
none
– Column that will be skipped on import.
"preserve_hierarchy": true
Example of the configuration file using the preserve_hierarchy
option:
"project_id": "projectId" #open project and go to Resources > Integrations & API > Integration tool
"api_token": "personal-access-token" #open project and go to Resources > Integrations & API > Integration tool
"base_path": "/project-base-path"
"base_url": "https://{organization-name}.crowdin.com"
"preserve_hierarchy": true
"files": [
{
"source": "/locale/en/**/*.po",
"translation": "/locale/%two_letters_code%/**/%original_file_name%"
}
]
За замовчуванням каталоги, які містять файлів для перекладу, не будуть створені в Crowdin. Наприклад:
- locale | |-- en | |-- foo.po |-- bar.po
За замовчуванням файли проекту будуть представлені в Crowdin наступним чином:
- foo.po
- bar.po
З використанням параметра preserve_hierarchy
структура файлів в Crowdin буде наступною:
- en | |-- foo.po |-- bar.po
This feature adds support for 2 optional parameters in the yml file section: dest
and type
. Це як правило корисно для деяких проектів, де завантажені імена повинні відрізнятися від Crowdin, але він міг визначити тип правильно. Параметр Dest
дозволяє задати ім’я файлу в Crowdin.
dest
працює тільки для окремих файлів, і якщо ви використовуєте його, файл конфігурації також містить точок serve_hierarchy
в значенні true.Приклад конфігураційного файлу з обома параметрами:
"project_id": "projectId" #open project and go to Resources > Integrations & API > Integration tool
"api_token": "personal-access-token" #open project and go to Resources > Integrations & API > Integration tool
"base_path": "/project-base-path"
"base_url": "https://{organization-name}.crowdin.com"
"preserve_hierarchy": true
"files": [
{
"source": "/conf/messages",
"dest": "/messages.properties",
"translation": "/conf/messages.%two_letters_code%",
"type": "properties"
},
{
"source": "/app/strings.xml",
"dest": "/strings.xml",
"translation": "/res/values-%android_code%/%original_file_name%",
"type": "properties"
}
]
Параметр update_option
— необов’язковий. Якщо він не заданий, переклади для змінених рядків будуть втрачені. Корисно для виправлення помилок і незначних змін у вихідних рядках.
Залежно від значення update_option
використовується для збереження перекладів і збереження/видалення затверджень перекладів і змінених рядків під час оновлення файлу.
Використовуйте наступні значення:
Приклад конфігураційного файлу з використанням параметра update_option:</p>
"project_id": "projectId" #open project and go to Resources > Integrations & API > Integration tool
"api_token": "personal-access-token" #open project and go to Resources > Integrations & API > Integration tool
"base_path": "/project-base-path"
"base_url": "https://{organization-name}.crowdin.com"
"files": [
{
"source": "/*.csv",
"translation": "/%three_letters_code%/%file_name%.csv",
"first_line_contains_header": true,
"scheme": "identifier,source_phrase,translation,context",
"update_option": "update_as_unapproved"
},
{
"source": "/**/*.xlsx",
"translation": "/%three_letters_code%/folder/%file_name%.xlsx",
"update_option": "update_without_changes"
}
]
The command upload translations uploads existing translations to Crowdin. If no options specified, the uploaded translations will not be imported even if they are equal with the source strings and will not be approved.
Використовуйте наступні значення:
To configure the preferred export behavior for each file group, you may use the following export options:
skip_untranslated_strings
– Only translated strings will be included in the exported translation files.
skip_untranslated_files
– Only translated files will be included in the exported translation archive.
export_only_approved
– Only texts that are both translated and approved will be included in the exported translation files.
Example of the configuration file with the export options:
"project_id": "projectId" #open project and go to Resources > Integrations & API > Integration tool
"api_token": "personal-access-token" #open project and go to Resources > Integrations & API > Integration tool
"base_path": "/project-base-path"
"base_url": "https://{organization-name}.crowdin.com"
"preserve_hierarchy": true
"files": [
{
"source": "/locale/en/**/*.po",
"translation": "/locale/%two_letters_code%/**/%original_file_name%",
"skip_untranslated_strings": true
},
{
"source": "/locale/en/**/*.json",
"translation": "/locale/%two_letters_code%/**/%original_file_name%",
"skip_untranslated_files": true
},
{
"source": "/locale/en/**/*.yml",
"translation": "/locale/%two_letters_code%/**/%original_file_name%",
"export_only_approved": true
}
]
translate_content необов'язковий | bool | Defines whether to translate texts placed inside the tags. Acceptable values are: 0 or 1. Значення за замовчуванням 1. |
translate_attributes необов'язковий | bool | Defines whether to translate tags' attributes. Acceptable values are: 0 or 1. Значення за замовчуванням 1. |
content_segmentation необов'язковий | bool | Defines whether to split long texts into smaller text segments. Acceptable values are: 0 or 1. Значення за замовчуванням 1. Важливо! Ця опція вимикає можливість завантажувати існуючі переклади для файлів XML, коли увімкнена. |
translatable_elements необов'язковий | масив | Це масив рядків, де кожен елемент є елементом XPath для DOM, який повинен бути імпортований. Приклад шляху: /path/to/node or /path/to/attribute[@attr] Увага! Якщо задані, параметри translate_content і translate_attributes не враховуються при імпорті. |
Приклад конфігураційного файлу з додатковими параметрами:
"project_id": "projectId" #open project and go to Resources > Integrations & API > Integration tool
"api_token": "personal-access-token" #open project and go to Resources > Integrations & API > Integration tool
"base_path": "/project-base-path"
"base_url": "https://{organization-name}.crowdin.com"
"files": [
{
"source": "/app/sample1.xml",
"translation": "/app/%locale%/%original_file_name%",
"translate_attributes": 1,
"translate_content": 0
},
{
"source": "/app/sample2.xml",
"translation": "/app/%locale%/%original_file_name%",
"translatable_elements": [
"/content/text", # translatable texts are stored in 'text' nodes of parent node 'content'
"/content/text[@value]" # translatable texts are stored in 'value' attribute of 'text' nodes
]
}
]
Визначає, чи буде одинарна лапка екранована інший одинарною лапкою або зворотнім слешем в експортованих перекладах. Ви можете додати параметр escape_quotes
. Допустимі значення: 0, 1, 2, 3. Значення за замовчуванням 3.
Використовуйте наступні значення:
Escape special characters
Defines whether any special characters (=, :, ! і #) зворотною косою скобкою в експортованих перекладах. Ви можете додати параметр escape_special_characters
для кожного файлу.
Acceptable values are: 0, 1. Значення за замовчуванням 1.
Приклад конфігураційного файлу:
"project_id": "projectId" #open project and go to Resources > Integrations & API > Integration tool
"api_token": "personal-access-token" #open project and go to Resources > Integrations & API > Integration tool
"base_path": "/project-base-path"
"base_url": "https://{organization-name}.crowdin.com"
"files": [
{
"source": "/en/strings.properties",
"translation": "/%two_letters_code%/%original_file_name%",
"escape_quotes": 1,
"translate_content": 0,
"escape_special_characters": 0
}
]
"project_id": "projectId" #open project and go to Resources > Integrations & API > Integration tool
"api_token": "personal-access-token" #open project and go to Resources > Integrations & API > Integration tool
"base_path": "/project-base-path"
"base_url": "https://{organization-name}.crowdin.com"
"files": [
{
"source": "/*.csv",
"translation": "/%two_letters_code%/%original_file_name%",
# Specifies whether first line should be imported or it contains columns headers
"first_line_contains_header": true,
# used only when uploading CSV file to define data columns mapping
"scheme": "identifier,source_phrase,translation,context,max_length"
}
]
"project_id": "projectId" #open project and go to Resources > Integrations & API > Integration tool
"api_token": "personal-access-token" #open project and go to Resources > Integrations & API > Integration tool
"base_path": "/project-base-path"
"base_url": "https://{organization-name}.crowdin.com"
"files" : [
{
"source" : "/locale/en/**/*.po",
"translation" : "/locale/%two_letters_code%/LC_MESSAGES/%original_file_name%",
"languages_mapping" : {
"two_letters_code" : {
"zh-CN" : "zh_CH",
"fr-QC": "fr"
}
}
}
]
"project_id": "projectId" #open project and go to Resources > Integrations & API > Integration tool
"api_token": "personal-access-token" #open project and go to Resources > Integrations & API > Integration tool
"base_path": "/project-base-path"
"base_url": "https://{organization-name}.crowdin.com"
"files" : [
{
"source" : "/res/values/*.xml",
"translation" : "/res/values-%android_code%/%original_file_name%",
"languages_mapping" : {
"android_code" : {
"de" : "de",
"ru" : "ru"
}
}
}
]
Інтеграція VCS вимагає того ж файлу конфігурації, що і інструмент CLI, тобто підтримується та ж структура. Єдина відмінність полягає в тому, що облікові дані проекту не повинні зберігатися в заголовку файлу з міркувань безпеки. Також можна використовувати два додаткові параметри.
Кожен раз, коли переклади відправляються на злиття, за замовчуванням відображається повідомлення «Нові переклади {fileName} ({languageName})». Ви можете використовувати параметр commit_message
для додавання тегів Git (наприклад, для пропуску збірок).
Приклад:
"base_path": "/project-base-path"
"commit_message": "[ci skip]"
"files": [
{
"source" : "/resources/en/*.json",
"translation" : "/resources/%two_letters_code%/%original_file_name%"
}
]
To replace the default commit message, use append_commit_message
parameter with the value false. Ви також можете додати два необов’язкових заповнювача: %original_file_name% і %language% щоб використовувати змінні ім’я файлу і мову відповідно.
Приклад:
"commit_message": "Fix: New translations %original_file_name% from Crowdin"
"append_commit_message": false
"files": [
{
"source" : "/resources/en/*.json",
"translation" : "/resources/%two_letters_code%/%original_file_name%"
}
]
За замовчуванням всі мови експортуються. Якщо вам потрібно експортувати будь-які конкретні мови, використовуйте параметр export_languages
, щоб позначити їх.
Приклад:
"base_path": "/project-base-path"
"export_languages": [
"ru",
"uk",
"ja"
]
"files": [
{
"source" : "/resources/en/*.json",
"translation" : "/resources/%two_letters_code%/%original_file_name%"
}
]
To add existing or new labels to the source strings, use the labels
parameter. Labels will be added to the source strings only during the initial upload to the Crowdin Enterprise project.
The strings uploaded to the Crowdin Enterprise project before the use of the labels
parameter won’t be labeled. If you remove the label added during the initial upload directly in Crowdin Enterprise, it won’t be re-added on the next syncs.
The label names can contain any characters except “,
”.
Приклад:
"base_path": "/project-base-path"
"files": [
{
"source" : "/resources/en/*.json",
"translation" : "/resources/%two_letters_code%/%original_file_name%",
"labels" : [
"android",
"emails"
]
}
]
Read more about Labels.
Бувають випадки, коли для одного проекту необхідно використовувати інтеграцію VCS та CLI. В основному в такій ситуації потрібно мати два окремі файли конфігурації: один - для інтеграції в VCS, інший - для CLI. Однак можна використовувати один файл конфігурації в обох випадках.
Оскільки файл конфігурації інтеграції VCS не містить облікових даних project_id
і api_token
, необхідні для CLI, ви можете передати їх безпосередньо команді, використовуючи такі параметри: -i/--project-id
, -T/-token
. Alternatively, you may use environment variables for this purpose.
Як результат, ваша команда для завантаження перекладів через CLI буде виглядати наступним чином:
$ crowdin download -i {your-project-id} -T {your-token}
Вам потрібна допомога з API Crowdin або у вас є питання? Зв’язатись з командою підтримки.