Configuração do Ficheiro

Note: This configuration file can work only with new CLI (v3).

Introdução

O Crowdin CLI usas um ficheiro de configuração YAML, que contém uma descrição dos recursos para gerir: os ficheiros para serem enviados para o Crowdin e os locais das traduções correspondentes.

Para usar o Crowdin CLI, deves primeiro gerar o teu ficheiro de configuração e depois, executar a ferramenta. By default, Crowdin CLI looks for a configuration file named crowdin.yaml (so you don’t have to specify the file name unless it’s different from crowdin.yaml).

Para criar o ficheiro de configuração, executa o seguinte comando:

$ crowdin init

Estrutura do Ficheiro de Configuração

Um ficheiro de configuração YAML do Crowdin CLI, tem a seguinte estrutura, por isso, certifica-te de preencher todas as informações necessárias:

  • O cabeçalho do ficheiro com as credenciais do projeto, preferências, e informações de acesso
  • Um elemento de array de ficheiros que descreve um conjunto de ficheiros de origem e de tradução que gerirás
  • Required fields in the files array: Source that defines filters for the source files and Translation with instructions on where to store the translated files or where to look for translations you already have if you want to upload them while setting up the CLI

Escrever um Simples Ficheiro de Configuração

Um típico ficheiro de configuração de YAML semelhante, ao seguinte:

"project_id": "projectId"                     #open project settings and go to API section 
"api_token": "personal-access-token"          #open profile settings and go to API & SSO > New Token > create Token
"base_path": "/project-base-path"
"base_url": "https://crowdin.com"
"preserve_hierarchy": true

"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%"
  }
]

Para executar o ficheiro de configuração acima, e enviar os ficheiros de origem para o Crowdin:

$ crowdin upload sources

Obter as traduções do Crowdin e colocá-las nos lugares certos:

$ crowdin download

Credenciais API das Variáveis de Ambiente

Podes carregar as Credenciais API duma variável ambiente, por exemplo:

"project_id_env": "CROWDIN_PROJECT_ID"
"api_token_env": "CROWDIN_PERSONAL_TOKEN"
"base_path_env": "CROWDIN_BASE_PATH"
"base_url_env": "CROWDIN_BASE_URL"

If mixed, api_token and project_id are prioritized:

"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://crowdin.com"           # High priority

Dividir Configuração de Projeto e Credenciais API

The crowdin.yaml file contains a description of the resources to manage and API credentials (project_id, api_token, base_path, base_url). Isto significa que, não é seguro enviar (commit) este ficheiro no repositório do código, porque a chave API pode ser acessada por outros utilizadores. Crowdin CLI supports 2 types of configuration files:

  • a description of the resources to manage, residing in the project directory
  • API credentials, probably residing in $HOME/.crowdin.yaml
Note: API credentials from .crowdin.yaml configuration file are of higher priority than credentials from project directory(crowdin.yaml).

Se precisas de executar um comando com as credenciais específicas do utilizador (por exemplo, upload sources), então executa o seguinte comando:

$ crowdin upload sources --identity 'caminho-para-o-ficheiro-das-credenciais-do-utilizador'

Mas se o ficheiro de credenciais específicas do utilizador, residir em $HOME/.crowdin.yaml, podes simplesmente executar:

$ crowdin upload sources

Configuração Geral

O exemplo de configuração fornecido acima, possui atributos de origem e tradução, ao conter caracteres especiais (wildcards) padrão(também conhecidos como globalizar padrões) para facilitar o trabalho com vários ficheiros.

Aqui estão os padrões que podes usar:

* (asterisk)

Represents any character in file or directory name. If you specify a “*.json” it will include all files like “messages.json”, “about_us.json” and anything that ends with “.json”.

** (doubled asterisk)

Corresponde a qualquer frase recursiva (incluindo subdiretórios). Note that you can use ** in both source and translation patterns. When using ** in the translation pattern, it will always contain sub-path from source for a certain file. For example, you can use source: ‘/en/**/*.po’ to upload all *.po files to Crowdin recursively. The translation pattern will be ‘/%two_letters_code%/**/%original_file_name%’.

? (ponto de interrogação)

Corresponde a qualquer caractere único.

[set]

Matches any single character in a set. Behaves exactly like character sets in Regexp, including set negation ([^a-z]).

\ (barra invertida)

Escapa o próximo metacaractere.

Espaços reservados

O Crowdin CLI permite usar os seguintes espaços reservados para colocar as variáveis apropriadas no nome do ficheiro resultante:

Nome Descrição
%language% Nome do idioma (exemplo, Ukrainian)
%two_letters_code% Código do idioma ISO 639-1 (exemplo uk)
%three_letters_code% Código do idioma ISO 639-2/T (exemplo ukr)
%locale% Localidade (como uk-UA)
%locale_with_underscore% Região (exemplo, uk_UA)
%original_file_name% Nome do ficheiro original
%android_code% Identificador de localidade do Android usado para nomear diretórios "values-"
%osx_code% Identificador de localidade do OS X usado para nomear diretórios ".lproj"
%original_path% Use nomes das pastas pai no projeto do Crowdin para criar um caminho de ficheiro no pacote resultante
%file_extension% Extensão do ficheiro original
%file_name% Nome do ficheiro sem extensão

Também podes definir o caminho para os ficheiros no arquivamento resultante, ao colocar uma barra (/) no início do padrão.

A tua opção translation pode se parecer como: “/locale/%two_letters_code%/LC_MESSAGES/%original_file_name%”.

Uso de Caracteres Especiais

Estrutura de ficheiros e diretórios na máquina local:

- 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

Example 1. Usage of wildcards in the source path:

#........your project configuration........
"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%"
  }
]

Example 2. Usage of wildcards for ignoring files:

#........your project configuration........
"files": [
  {
    "source": "/**/*.*",                             #upload all files that  the base_path contains
    "translation": "/**/%two_letters_code%_%original_file_name%",
    "ignore": [
      "/**/%two_letters_code%_%original_file_name%", #ignore the translated files
      "/**/?.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
    ]
  }
]

Mapeamento do Idioma

Muitas vezes, os projetos de software têm nomes personalizados para diretórios de localidade. Crowdin allows you to map your own languages to be recognizable in your projects.

Digamos que os teus diretórios locais são denominados ‘en’, ‘uk’, ‘fr’, ‘de’. Todos eles podem ser representados pelo espaço reservado %two_letters_code%. Ainda assim, tens um diretório chamado ‘zh_CH’. You can also override language codes for other placeholders like %android_code%, %locale%, etc.

To make it work with Crowdin without changes in your project, you can set up Language Mapping via UI.

To set up Language Mapping, follow these steps:

  1. Open the Project settings > General tab and scroll down to the Export section.
  2. Click Language Mapping to add custom language codes to the target languages of your project.

Renomear Ficheiro de Traduções

If you need to rename a file with translations after the export, you can easily do this with the help of the parameter translation_replace.

For example, if the file is named “en_strings.po” it can be renamed to “strings.po”. For this, add a new parameter (at the same level as the translation parameter) to the configuration file (crowdin.yaml):

"files": [
  {
    "source": "/locale/**/en_*.po",
    "translation": "/locale/**/%two_letters_code%_%original_file_name%",
    "translation_replace": {
      "en_": ""
    }
  }
]

In this case, “_en” will simply be erased from the file name.

Ignorar Ficheiros e Diretórios

From time to time there are files and directories you don’t need to translate in 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"
    ]
  }
]

CSV com Multicolunas

If a CSV file contains the translations for all target languages, you should specify appropriate language codes in the scheme.

CSV file example:

identifier,source_phrase,context,Ukrainian,Russian,French ident1,Source 1,Context 1,,, ident2,Source 2,Context 2,,, ident3,Source 3,Context 3,,,

Exemplo de ficheiro de configuração:

"files": [
  {
    "source": "multicolumn.csv",
    "translation": "multicolumn.csv",
    "first_line_contains_header": true,
    "scheme": "identifier,source_phrase,context,uk,ru,fr"
  }
]

If your CSV 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"

Guarda a Estrutura de Diretórios no Servidor

"preserve_hierarchy": true

Example of file configuration using the preserve_hierarchy option:

"project_id": "projectId"                     #open project settings and go to API section
"api_token": "personal-access-token"          #open profile settings and go to API & SSO > New Token > create Token
"base_path": "/project-base-path"
"base_url": "https://crowdin.com"
"preserve_hierarchy": true

"files": [
  {
    "source": "/locale/en/**/*.po",
    "translation": "/locale/%two_letters_code%/**/%original_file_name%"
  }
]

By default, directories that do not contain any files for translation will not be created in Crowdin. For example:

- locale | |-- en | |-- foo.po |-- bar.po

By default, project files will be represented in Crowdin as following:

- foo.po
- bar.po

Using the option preserve_hierarchy, file structure in Crowdin will be the following:

- en | |-- foo.po |-- bar.po

Enviar Ficheiros para o Caminho Especificado com o Tipo Especificado

This feature adds support for 2 optional parameters in the yaml file section: dest and type. This is typically used for projects, where the uploaded name must be different, so Crowdin can detect the type correctly. The dest parameter allows you to specify a file name in Crowdin.

Note! The dest parameter only works for single files, and if you use it, the configuration file should also include the preserve_hierarchy parameter with true value.

Example of the configuration file with both parameters:

"project_id": "projectId"                     #open project settings and go to API section
"api_token": "personal-access-token"          #open profile settings and go to API & SSO > New Token > create Token
"base_path": "/project-base-path"
"base_url": "https://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"
  }
]

Atualização de Frases Alteradas

The parameter update_option is optional. If it is not set, translations for changed strings will be lost. Useful for typo fixes and minor changes in source strings.

Depending on the value, update_option is used to preserve translations and preserve/remove validations of changed strings during file update.

Os valores são:

  • update_as_unapproved - preserve translations of changed strings and remove validations of those translations if they exist
  • update_without_changes - preserve translations and validations of changed strings

Example of the configuration file with update_option parameter:

"project_id": "projectId"                     #open project settings and go to API section
"api_token": "personal-access-token"          #open profile settings and go to API & SSO > New Token > create Token
"base_path": "/project-base-path"
"base_url": "https://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"
  }
]

Envio de Traduções

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.

Os valores são:

  • -l, --language=language_code - defines the language translations that should be uploaded to Crowdin. Por padrão, as traduções são enviadas para todos os idiomas de destino do projeto. (Códigos de Idioma do Crowdin)
  • --[no-]import-eq-suggestions - defines whether to add translation if it is equal to source string in Crowdin project
  • --[no-]auto-approve-imported - automatically approves uploaded translations

Opções Adicionais para Ficheiros XML

translate_content
opcional
bool Defines whether to translate texts placed inside the tags.
Acceptable values are: 0 or 1. O padrão é 1.
translate_attributes
opcional
bool Defines whether to translate tags' attributes.
Acceptable values are: 0 or 1. O padrão é 1.
content_segmentation
opcional
bool Defines whether to split long texts into smaller text segments.
Acceptable values are: 0 or 1. O padrão é 1.
Importante! Esta opção desativa a possibilidade de enviar traduções existentes para ficheiros XML quando ativada.
translatable_elements
opcional
array Este é um array de frases, onde cada item é o XPaths para elemento DOM que deve ser importado.
Exemplo de caminho: /path/to/node or /path/to/attribute[@attr]
Nota! se definido. os parâmetros translate_content e translate_attributes não são considerados durante a importação.

Example of the configuration file with additional parameters:

"project_id": "projectId"                   #open project settings and go to API section
"api_token": "personal-access-token"        #open profile settings and go to API & SSO > New Token > create Token
"base_path": "/project-base-path"
"base_url": "https://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
    ]
  }
]

Opções de Cotas de Escape para Formato de Ficheiro .properties

Defines whether a single quote should be escaped by another single quote or backslash in exported translations. You can add escape_quotes per-file option. Os valores aceitáveis são: 0, 1, 2, 3. O padrão é 3.

Os valores são:

  • 0 - não escapar da citação simples
  • 1 - escapar duma citação simples por uma outra
  • 2 - escapar de aspas simples por uma barra invertida
  • 3 - escapar de aspas simples por outra apenas em frases que contenham variáveis ( {0} )

Escape special characters
Defines whether any special characters (=, :, ! and #) should be escaped by backslash in exported translations. You can add escape_special_characters per-file option.

Acceptable values are: 0, 1. O padrão é 1.

  • 0 - não escapar dde caracteres especiais
  • 1 - escapar de caracteres especiais por uma barra invertida

Example of the configuration file:

"project_id": "projectId"                   #open project settings and go to API section
"api_token": "personal-access-token"        #open profile settings and go to API & SSO > New Token > create Token
"base_path": "/project-base-path"
"base_url": "https://crowdin.com"

"files": [
  {
    "source": "/en/strings.properties",
    "translation": "/%two_letters_code%/%original_file_name%",
    "escape_quotes": 1,
    "translate_content": 0,
    "escape_special_characters": 0
  }
]

Exemplo de Configurações

Enviar ficheiros CSV através de API

"project_id": "projectId"                   #open project settings and go to API section
"api_token": "personal-access-token"        #open profile settings and go to API & SSO > New Token > create Token
"base_path": "/project-base-path"
"base_url": "https://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"
  }
]

Projeto GetText

"project_id": "projectId"                   #open project settings and go to API section
"api_token": "personal-access-token"        #open profile settings and go to API & SSO > New Token > create Token
"base_path": "/project-base-path"
"base_url": "https://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"
      }
    }
  }
]

Projeto Android

"project_id": "projectId"                   #open project settings and go to API section
"api_token": "personal-access-token"        #open profile settings and go to API & SSO > New Token > create Token
"base_path": "/project-base-path"
"base_url": "https://crowdin.com"

"files" : [
  {
    "source" : "/res/values/*.xml",
    "translation" : "/res/values-%android_code%/%original_file_name%",
    "languages_mapping" : {
      "android_code" : {
        "de" : "de",
        "ru" : "ru"
      }
    }
  }
]

Ficheiro de Configuração para Integrações de VCS

VCS integrations require the same configuration file as the CLI tool, meaning the same structure is supported. The only difference, is that the project credentials should not be stored in the file header for security reasons. Also, two additional parameters can be used.

Enviar Parâmetro de mensagem para Integrações VCS

Each time translations are committed the default message is shown “New translations {fileName} ({languageName})”. You can use commit_message parameter to add Git tags (e.g. to skip builds).

Exemplo:

"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. You can also add two optional placeholders: %original_file_name% and %language% to use the appropriate file name and language variables accordingly.

Exemplo:

"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%"
  }
]

Exportar Parâmetro de Idiomas para Integrações VCS

By default, all the languages are exported. If you need to export some specific languages, use export_languages parameter to specify them.

Exemplo:

"base_path": "/project-base-path"
"export_languages": [                                   
    "ru", 
    "uk", 
    "ja"
  ]
"files": [
  {
    "source" : "/resources/en/*.json",
    "translation" : "/resources/%two_letters_code%/%original_file_name%"
  }
]

Using One Configuration File for VCS Integrations and CLI

There are cases when it’s necessary to use VCS integration and CLI for one project. Mostly, in this kind of situation, you’d need to have two separate configuration files, one for VCS integration and another for CLI. However, there is a possibility to use a single configuration file for both cases.

Since the VCS integration configuration file doesn’t contain project_id and api_token credentials that are required for CLI, you can pass them directly in the command using the following parameters: -i/--project-id, -T/--token. Alternatively, you may use environment variables for this purpose.

As a result, your command for downloading translations via CLI will look like the following:

$ crowdin download -i {your-project-id} -T {your-token}

Procurar por Ajuda

Need help working with Crowdin CLI or have any questions? Contact Support Team.

Ver Também

Este artigo foi útil?