Cliente Weblate

Instalação

The Weblate Client is shipped separately and includes the Python module. The source code is maintained in the WeblateOrg/wlc repository. To use the commands below, you need to install wlc using pip:

pip install wlc

Também pode executá-lo diretamente usando uvx:

uvx wlc --help

Dica

Também pode utilizar este wlc como um módulo Python, consulte wlc.

Uso do Docker

O Weblate Client também está disponível como uma imagem Docker.

Images are published on Docker Hub and the GitHub Container Registry. The examples below use the Docker Hub image name.

Instalar:

docker pull weblate/wlc

The following tags are available:

latest

Latest stable release.

Full version, for example 2.2.0

A specific stable release.

Major version, for example 2

Latest stable release in that major series.

edge

Current development version from the main branch.

edge-YYYY-MM-DD-COMMIT

A specific development snapshot.

To build an image from the source checkout:

docker build -t weblate/wlc .

O contentor Docker usa as predefinições do Weblate Client e conecta a API implementada no localhost. Configure a URL da API e chave da API usando os argumentos wlc normais ou variáveis de ambiente, por exemplo --url, --key, WLC_URL, e WLC_KEY. Chaves de API são rejeitadas em relação a URLs http:// não locais; utilize HTTPS, loopback HTTP para desenvolvimento local, ou escolha explicitamente usar HTTP inseguro.

O comando para iniciar o contentor usa a seguinte sintaxe:

docker run --rm weblate/wlc [WLC_ARGS]

Exemplo:

docker run --rm weblate/wlc --url https://hosted.weblate.org/api/ list-projects

Quereria passar o seu Ficheiros de configuração para o contentor Docker. Quando o seu repositório contém uma configuração de projeto como por exemplo .weblate, a abordagem mais fácil é adicionar o seu diretório atual como o volume /home/weblate:

docker run --volume $PWD:/home/weblate --rm weblate/wlc show

When the mounted repository provides the API URL in project configuration and you pass an unscoped API key to the container, also pin the URL explicitly: WLC_KEY requires WLC_URL, and --key requires --url. The same pairing is required for the --allow-insecure-http and --allow-insecure-ssl overrides.

If the configured API URL uses non-local http:// and an API key is provided, the container refuses to send the key unless insecure HTTP is explicitly enabled. Prefer HTTPS; for legacy deployments, pass --allow-insecure-http or set WLC_ALLOW_INSECURE_HTTP. TLS certificates are always verified by default, including for loopback URLs. Use --allow-insecure-ssl or WLC_ALLOW_INSECURE_SSL only when certificate verification can not be enabled.

Primeiros Passos

A forma mais fácil de iniciar é criar um wlc configuration in ~/.config/weblate pessoal (veja Ficheiros de configuração para as regras de descoberta completas e outras localizações):

[weblate]
url = https://hosted.weblate.org/api/

[keys]
https://hosted.weblate.org/api/ = APIKEY

Depois pode invocar comandos no servidor predefinido:

wlc ls
wlc commit sandbox/hello-world

Configuração de legado

Alterado na versão 1.17: A configuração de legado usando uma key sem âmbito já não é suportado.

Alterado na versão 2.2.0: Global allow_insecure_http configuration is no longer supported. Configure an origin in the [insecure_http] section instead.

Migrar configuração de legado:

[weblate]
url = https://hosted.weblate.org/api/
key = YOUR_KEY_HERE

Para uma configuração com uma chave com âmbito para um URL de API:

[weblate]
url = https://hosted.weblate.org/api/

[keys]
https://hosted.weblate.org/api/ = YOUR_KEY_HERE

Sinopse

wlc [arguments] <command> [options]

Os comandos indicam, na verdade, qual operação deve ser realizada.

Descrição

Weblate Client is a Python library and command-line utility to manage Weblate remotely using API REST do Weblate. Invoke the command-line utility as wlc; see wlc for the Python API.

Argumentos

O programa aceita os seguintes argumentos que definem o formato de saída ou qual a instância do Weblate a utilizar. Estes devem ser inseridos antes de qualquer comando.

--format {csv,json,text,html}

Specify the output format. The default is text.

--version

Print the program version and exit. The version command supports output formatting and can print only the version number.

--debug

Print verbose HTTP communication. Authorization header values are redacted and request bodies are not logged, but query parameters are; do not put secrets in query parameters.

--url URL

Especifica a URL da API. Substitui qualquer valor encontrado no ficheiro de configuração, consulte Ficheiros de configuração. A URL deve terminar com /api/, por exemplo, https://hosted.weblate.org/api/.

--key KEY

Especifica a chave do utilizador de API a ser usada. Substitui qualquer valor encontrado no ficheiro de configuração, consulte Ficheiros de configuração. Pode encontrar a sua chave no seu perfil no Weblate. Quando o URL da API é carregado através da configuração de projeto automaticamente descoberta, a opção --key tem que ser utilizada com a --url. Chaves de API são rejeitadas em relação a URLs http:// não locais por predefinição.

--allow-insecure-http

Allow sending API keys over non-local http:// URLs. Prefer HTTPS or loopback HTTP instead; this option is intended only for legacy deployments where HTTPS is not available. This option only enables insecure HTTP for the current run. When the API URL comes from automatically discovered project configuration, this option requires --url.

--allow-insecure-ssl

Disable TLS certificate verification for the current run. Certificates are verified by default for every HTTPS URL, including loopback URLs. When the API URL comes from automatically discovered project configuration, this option requires --url.

--config PATH

Carregar configuração a partir de apenas PATH em vez da global descoberta e ficheiros de configuração de projeto, veja Ficheiros de configuração.

--config-section SECTION

Selects the configuration file section to use instead of [weblate], see Ficheiros de configuração.

Object paths

Commands that operate on an object accept one of these paths:

PROJECT

Project slug.

PROJECT/COMPONENT

Component slug, including its project.

PROJECT/COMPONENT/LANGUAGE

Translation language, including its project and component.

UNIT_ID

Numeric translation unit ID. Only commands that explicitly support units accept this form.

Commands that require an object use the translation setting from Ficheiros de configuração when the path is omitted. The ls and download commands also use this setting before falling back to their no-object behavior. For list-components and list-translations, an omitted object always requests an instance-wide list.

Comandos

Os comandos seguintes estão disponíveis:

version

Imprime a versão atual.

--bare

Prints only the version number.

list-languages

Lists all languages in Weblate.

list-projects

Lists all projects in Weblate.

list-components

Lists all components in Weblate, or components in the specified project.

list-translations

Lists all translations in Weblate, or translations in the specified component.

list-units

Lists units in the specified translation.

--query QUERY

Filters units using the search query syntax.

show

Shows a project, component, translation, or unit.

delete

Deletes a project, component, translation, or unit without a confirmation prompt.

ls

Lists all projects when no object is specified, components in a project, or translations in a component.

commit

Faz um commit das alterações feitas num objeto Weblate (tradução, componente ou projeto).

pull

Faz um pull das alterações remotas do repositório no objeto Weblate (tradução, componente ou projeto).

push

Faz um push das alterações do objeto Weblate ao repositório remoto (tradução, componente ou projeto).

reset

Redefine as alterações no objeto Weblate para corresponder ao repositório remoto (tradução, componente ou projeto).

cleanup

Remove todas as alterações não rastreadas num objeto Weblate para corresponder ao repositório remoto (tradução, componente ou projeto).

repo

Exibe o estado do repositório para um determinado objeto do Weblate (tradução, componente ou projeto).

stats

Exibe estatísticas detalhadas para um determinado objeto Weblate (tradução, componente ou projeto).

lock-status

Displays the lock status of a component.

lock

Bloqueia o componente de tradução posterior no Weblate.

unlock

Desbloqueia a tradução do componente Weblate.

changes

Displays changes for a project, component, or translation.

download

Downloads translation files. For a translation, wlc writes the file to --output or to redirected standard output. It refuses to write raw file content to an interactive terminal.

For a component or project, --output is required and is treated as a directory. wlc writes one ZIP archive per component. With no object, it downloads every component in the Weblate instance in the same way.

--convert FORMAT

Requests conversion to FORMAT on the server. If unspecified, no conversion happens.

--output PATH

Specifies the output file for a translation or output directory for a component, project, or instance-wide download. Use - to write a translation to standard output.

--no-glossary

Excludes glossary components from component, project, and instance-wide downloads.

upload

Descarrega um ficheiro de tradução.

--overwrite

Overwrites existing translated strings. This is equivalent to --conflicts replace-translated.

--conflicts {ignore,replace-translated,replace-approved}

Selects how conflicts with existing translations are handled.

--input PATH

Reads content from PATH. If unspecified or -, content is read from standard input.

--method {translate,approve,suggest,fuzzy,replace,source,add}

Upload method to use, see Métodos de importação. The default is translate.

--fuzzy {process,approve}

Selects processing of fuzzy strings (marked for edit).

--author-name NAME

Nome do autor, para substituir o utilizador atualmente autenticado

--author-email EMAIL

Email do autor, para substituir o utilizador atualmente autenticado

edit-unit

Updates a translation unit. At least one update option is required.

--target TARGET [TARGET ...]

Sets one or more translated strings.

--state STATE

Sets the unit state: 0 for empty, 10 for fuzzy, 20 for translated, or 30 for approved.

--explanation EXPLANATION

Sets the string explanation.

--extra-flags FLAGS

Sets additional string flags.

Dica

Pode obter informações mais detalhadas sobre como invocar comandos individuais a passar --help, por exemplo: wlc ls --help.

Ficheiros de configuração

Quando --config é fornecido, wlc carrega apenas aquele ficheiro.

Sem --config, wlc carrega primeiro o ficheiro de configuração local descoberta a partir das localizações específicas a uma plataforma:

C:\Users\NAME\AppData\Roaming\weblate.ini

Ficheiro de configuração global do utilizador no Windows no perfil roaming.

C:\Users\NAME\AppData\Local\weblate.ini

Ficheiro de configuração do utilizador global no Windows no perfil local.

~/.config/weblate

Ficheiro de configuração global em sistemas tipo Unix.

~/.config/weblate.ini

Alternative global configuration filename on Unix-like systems.

/etc/xdg/weblate

Ficheiro de configuração de alternativa no sistema inteiro.

/etc/xdg/weblate.ini

Alternative system-wide fallback filename.

O programa segue a especificação XDG, para que possa ajustar o posicionamento de ficheiros de configuração por variáveis de ambiente XDG_CONFIG_HOME ou XDG_CONFIG_DIRS.

No Windows, os diretórios APPDATA e LOCALAPPDATA são os locais preferidos para o ficheiro de configuração.

Após carregar a configuração global, wlc carrega o ficheiro de configuração mais próximo a partir do diretório atual ou os seus parentes:

.weblate, .weblate.ini, weblate.ini

Ficheiro de configuração do projeto colocado no repositório.

Project configuration is loaded after global configuration and overrides matching settings. It can select the API URL, default object, request settings, and a matching URL-scoped API key, allowing a cloned repository to automatically select its Weblate server and translation.

Apenas o ficheiro de configuração de projeto mais próximo é carregado. Ficheiros de configuração em diretórios parentes mais distantes são ignorados.

As configurações seguintes podem ser configuradas na secção [weblate] (pode personalizar-lo por --config-section):

key

Removed in version 1.17: Utilize a secção {keys} para especificar chaves com âmbito para URLs de API individuais, veja Configuração de legado.

url

URL de API do servidor, a predefinição é http://127.0.0.1:8000/api/.

translation

Default object path for commands that accept one: a project, component, translation, or numeric unit ID.

retries, timeout, allowed_methods, backoff_factor, status_forcelist

HTTP request retry and timeout settings. retries defaults to 0 and backoff_factor to 0. status_forcelist is a comma-separated list of HTTP status codes that trigger retries and is empty by default.

allowed_methods lists methods that may be retried, separated by commas or whitespace. It defaults to HEAD, DELETE, OPTIONS, PUT, and GET. These retry settings are passed to urllib3.util.Retry.

timeout is the request timeout in seconds and defaults to 300. Current wlc releases use allowed_methods in place of the older method_whitelist option.

O ficheiro de configuração é um ficheiro INI, por exemplo:

[weblate]
url = https://hosted.weblate.org/api/
translation = weblate/application
retries = 3
allowed_methods = PUT,POST,GET
backoff_factor = 0.2
status_forcelist = 429,500,502,503,504
timeout = 30

As chaves de API são armazenadas na secção [keys]:

[keys]
https://hosted.weblate.org/api/ = APIKEY

This allows you to store keys in your personal settings, while using the .weblate configuration in the VCS repository so that wlc knows which server it should talk to. The [keys] lookup is scoped to the complete configured API URL, not merely its network origin.

Project configuration can also supply or replace a matching entry in [keys]. Do not commit valuable API keys to version control; normally keep keys in personal configuration and only the API URL and default object in project configuration.

Insecure transport exceptions are stored in origin-scoped sections in trusted user configuration:

[insecure_http]
http://legacy.example.com:80 = true

[insecure_ssl]
https://legacy.example.com:443 = true

An origin consists of the scheme, normalized hostname, and effective port. The API path is ignored, while different schemes and ports remain isolated. The [insecure_http] section allows API keys over non-local HTTP for matching origins. The [insecure_ssl] section disables TLS certificate verification for matching origins.

Alterado na versão 2.2.0: TLS certificates are verified for all hosts by default. Insecure HTTP and TLS configuration is scoped to origins. Automatically discovered project configuration can neither add entries to these sections nor enable the removed global settings. User configuration and explicitly selected --config files are trusted.

Na CI, chaves sem âmbito devem afixar o URL de API explicitamente: define ambas WLC_URL e WLC_KEY, ou utilize --url em conjunto com --key.

Variáveis de ambiente

Added in version 1.18.0.

Alterado na versão 2.0.1: Chaves de API sem âmbito requerem um URL de API quando a configuração de projeto é descoberta automaticamente. Chaves de API são rejeitadas sob URLs http:// não locais, a não ser que HTTP inseguro seja explicitamente ativado.

Alterado na versão 2.2.0: Insecure HTTP and TLS environment overrides require WLC_URL when the API URL would otherwise come from automatically discovered project configuration.

O URL de API e chave também podem ser configurados usando variáveis de ambiente. Isto é especialmente útil para fluxos de trabalho CI onde WLC_URL afixa o destino e WLC_KEY é injetado enquanto segredo:

WLC_URL

URL da API

WLC_KEY

Chave API. Quando o URL de API seria de outra forma originado a partir de configuração de projeto automaticamente descoberto, WLC_KEY é aceitado apenas em conjunto com WLC_URL. Chaves de API são rejeitadas sobre URLs http:// não locais por predefinição.

WLC_ALLOW_INSECURE_HTTP

Set to 1, true, yes, or on to allow API keys over non-local http:// URLs. Prefer HTTPS or loopback HTTP instead. Other values, such as 0 or false, are treated as unset. When the API URL would otherwise come from automatically discovered project configuration, this variable is accepted only together with WLC_URL.

WLC_ALLOW_INSECURE_SSL

Set to 1, true, yes, or on to disable TLS certificate verification. Other values, such as 0 or false, are treated as unset. When the API URL would otherwise come from automatically discovered project configuration, this variable is accepted only together with WLC_URL.

The same protection applies to command-line arguments: --key, --allow-insecure-http, and --allow-insecure-ssl are accepted with automatically discovered project configuration only when --url is provided.

Precedência de API URL e configuração de chave (mais alto para mais baixo) é:

  1. Argumentos de linha de comandos (--url, --key).

  2. Variáveis de ambiente (WLC_URL, WLC_KEY).

  3. Configuração carregada a partir de --config, ou a partir da configuração global descoberta mais a configuração de projeto mais próxima quando --config não é usada.

The insecure transport opt-ins are enable-only rather than normal precedence settings. They are enabled by a command-line or environment override, or by a matching origin in the trusted [insecure_http] or [insecure_ssl] section. Automatically discovered project configuration cannot add trusted origins.

Security model

Project configuration is part of the repository workflow and is intentionally trusted to select the API endpoint, default object, request settings, and a matching URL-scoped API key. Running wlc inside a repository authorizes its nearest project configuration to select the server that receives commands and uploads and supplies displayed or downloaded content. Use an explicit trusted --config file when this is not desired.

The command-line client accepts API keys from --key, WLC_KEY, or the [keys] section. It does not load HTTP authentication from .netrc or the file named by NETRC. Credentials embedded in API URLs are rejected; use an API key instead. Other Requests environment integration, including proxy and CA-bundle variables, remains enabled.

The wlc threat model documents the complete trust boundaries, security properties, non-goals, and downstream responsibilities. A version-matched copy is included in source and wheel distributions. Report security issues using the Weblate vulnerability reporting process.

Exemplos

Imprimir a versão atual do programa:

$ wlc version

Listar todos os projetos:

$ wlc list-projects
name: Hello
slug: hello
url: http://example.com/api/projects/hello/
web: https://weblate.org/
web_url: http://example.com/projects/hello/

Enviar ficheiro de tradução:

$ wlc upload project/component/language --input /tmp/hello.po

Também pode designar em qual projeto o wlc deve trabalhar:

$ cat .weblate
[weblate]
url = https://hosted.weblate.org/api/
translation = weblate/application

$ wlc show
branch: main
file_format: po
source_language: en
filemask: weblate/locale/*/LC_MESSAGES/django.po
git_export: https://hosted.weblate.org/git/weblate/application/
license: GPL-3.0+
license_url: https://spdx.org/licenses/GPL-3.0+
name: Application
new_base: weblate/locale/django.pot
project: weblate
repo: git://github.com/WeblateOrg/weblate.git
slug: application
template:
url: https://hosted.weblate.org/api/components/weblate/application/
vcs: git
web_url: https://hosted.weblate.org/projects/weblate/application/

Com esta configuração é fácil fazer um commit de alterações pendentes no projeto atual:

$ wlc commit