Translation file discovery library used by Weblate to identify translation files and their configuration in source repositories.
Discovery can operate on file listings alone or inspect the filesystem when more accurate detection is needed, such as determining file encoding or distinguishing formats with similar syntax.
Maintained by Weblate — a privacy-respecting localization platform built on open-source foundations.
It can be used from Python:
>>> from translation_finder import discover
>>> from pprint import pprint
>>> results = discover("translation_finder/test_data/")
>>> len(results)
40
>>> pprint(results[0].match)
{'file_format': 'aresource',
'filemask': 'app/src/res/main/values-*/strings.xml',
'name': 'android',
'template': 'app/src/res/main/values/strings.xml'}
>>> pprint(results[1].match)
{'file_format': 'po',
'filemask': 'locales/*.po',
'name': 'translation',
'new_base': 'locales/messages.pot'}Additional information about discovery can be obtained from meta attribute:
>>> pprint(results[0].meta)
{'discovery': 'TransifexDiscovery', 'origin': 'Transifex', 'priority': 500}
>>> pprint(results[22].meta)
{'discovery': 'GettextDiscovery', 'origin': None, 'priority': 1000}Or command line:
$ weblate-discovery translation_finder/test_data/
== Match 1 (Transifex) ==
file_format : aresource
filemask : app/src/res/main/values-*/strings.xml
name : android
template : app/src/res/main/values/strings.xml
...
== Match 7 ==
file_format : po
filemask : locales/*.po
new_base : locales/messages.potNon-printable characters in command-line results are displayed as visible
escapes (for example, \n and \x1b). The Python API returns the original
values unchanged.
Each result describes a suggested configuration. Paths are relative to the
discovery root, and filemask identifies the translation files belonging to
that configuration. File masks, including discovery hints, use * as their
only wildcard. Question marks and brackets match literal characters, so paths
such as src/[locale]/*.json preserve their bracketed directory names.
Custom discovery selectors needing multiple alternatives should provide a tuple
of masks, for example ("resources.resx", "resources.resw").
Two optional fields describe files with different roles:
template- The source file containing string definitions for a monolingual configuration. This maps to Weblate's Monolingual base language file. Translations are interpreted using the string definitions in this file.
new_base- The file used to create translation files for additional languages. This
maps to Weblate's Template for new translations. It can be an untranslated
source file, a Gettext POT file, or an existing bilingual translation whose
translations will be cleared when creating the new language file.
Setting
new_basealone does not make a configuration monolingual.
For example, the Gettext result in the usage example has only new_base:
locales/messages.pot supplies the messages for new languages, while existing
PO files contain their own source strings. Similarly, Qt's translation
repository can produce this bilingual configuration, using an existing Arabic
translation to create new languages:
{
"file_format": "ts",
"filemask": "translations/designer_*.ts",
"new_base": "translations/designer_ar.ts",
}Both fields can refer to the same file. For example, the PHP and Laravel fixtures use their English source files both to define strings and to create new language files:
>>> pprint(sorted(
... (r["file_format"], r["template"], r["new_base"])
... for r in results if r["file_format"] in {"php", "laravel"}
... ))
[('laravel', 'laravel/en.php', 'laravel/en.php'),
('php', 'php/en.php', 'php/en.php')]Either field can appear independently, both can appear, or both can be absent. An absent field means discovery did not provide that setting; it does not necessarily mean the format does not support it. Discovery backends may also read settings from repository configuration, such as Transifex configuration.
Filename-based discovery first looks for an exact name derived from the
filemask for new_base. Otherwise, it prefers a discovered template when
that file is eligible for creating translations. Formats using the same file
extension for sources and translations then prefer a translation from the same
discovered filemask. If those checks do not identify a file, discovery retains
a deterministic fallback from the nearest directory containing an eligible
file. These are heuristics: review suggestions when a directory contains
unrelated catalogs or several possible templates.
The threat model describes which inputs discovery treats as untrusted and which resource limits are the caller's responsibility.
The high-level discover() API accepts a hint and a source language of at most
400 characters each. These limits bound the cost of compiling wildcard patterns
and constructing candidate template paths. Longer values raise ValueError
before discovery scans the repository. The CLI applies the same limits to
--hint and --source-language and exits with status 2 for an overlong
value. Both limits apply even with unlimited discovery budgets.
The CLI accepts nonnegative integer limits. Each value applies to the operation described below, including when you set it to zero.
--max-candidates: 4096 generated candidates across all backends. Transifex discovery also processes at most this many resource-section occurrences across its configuration files, including empty, repeated, and non-discoverable sections.[main]and[DEFAULT]do not count as resources. Section processing has separate accounting, so useful resources are not charged twice. Exceeding either allowance reportscandidatestruncation.--max-results: 4096 returned matches.--max-new-base-checks: 65536 probes in the shared new-base resolver. Gettext can also check up to five fallback filenames per candidate, even when this budget is zero.--max-wildcard-checks: 1000000 language-code probes in the generic wildcard generator across the run. The Apple.stringsand RESX backends also check locales in files selected under Finder's match budget. Those locale checks use a separate code path and can still run at zero.--max-masks-per-path: 32 alternative masks during one pass of the generic generator over the language-like components of a path. Masks derived from a hint, an eager filename, or a format-specific rule can still be returned at zero.--sniff-max-bytes: 67108864 bytes (64 MiB) sampled across the run.--sniff-max-files: 512 content-sniffing file attempts across the run.--max-files: 100000 indexed files.--max-dirs: 20000 indexed directories.--max-depth: 64 directory levels below the root.--max-entries: 150000 directory entries examined, including excluded entries and symlinks.--max-path-length: 4096 characters in an indexed relative path.--max-path-bytes: 67108864 bytes (64 MiB) across all collected file and directory paths. Each entry counts once, using its full path relative to the discovery root, encoded as UTF-8 withsurrogatepassfor undecodable names. For example, collectingpoandpo/fr.pouses 10 bytes (2 + 8). Collection stops before adding a path that would exceed the budget and reportspath-bytestruncation. Process memory can exceed the budget because Python objects and lookup indexes also use memory.--max-match-checks: 65536 regular expression and wildcard candidate evaluations.
For example, weblate-discover --max-results 10000 translations/ raises
only the result limit. weblate-discover --unlimited translations/ disables
all configurable discovery limits. Use it without individual limit options.
Internal parser safeguards and per-result format and encoding sampling limits
remain active.
Transifex configuration discovery follows the Transifex client's INI syntax,
including comments, quoted values, backslash continuations, repeated-section
merging, dotted parent sections, and %(name)s value references. It does not
inherit Python ConfigParser behavior such as indentation-only continuations
or implicit [DEFAULT] option inheritance. Malformed headers and their
following options are skipped until the next valid header, preserving preceding
resource sections. Malformed assignments invalidate only their own section.
Discovery attempts up to 16 Transifex configuration files per run, samples up
to 1 MiB per file, and admits up to 1 MiB in total for parsing. It skips a
file if its sample is incomplete or its contents exceed the remaining parsing
allowance. A later, smaller file can still fit. A physical line longer than
4096 UTF-8 bytes (excluding the line ending) skips the entire file. A resolved
discovery value longer than 4096 UTF-8 bytes skips its section. These fixed
safeguards apply even with --unlimited and can omit resources without
setting a truncation flag.
Across all Transifex configuration files, each run also has 8,388,608 work
units for resolving options. Each scan costs 64 units
plus the character count of the current value. Substitution also charges for
the replacement text and the expanded output. If the next operation exceeds
the allowance, discovery keeps completed resources, stops processing Transifex
configuration, and reports transifex-interpolation. This safeguard applies
even with --unlimited.
The CLI prints collected matches to stdout, including partial results. Exit status 0 means discovery finished with no reported limit reason. Content sampling is best effort, so exhausting a sniff budget can affect detection without setting a truncation flag. When discovery reports truncation, the CLI prints one warning listing the reasons to stderr and exits with status 3. Invalid arguments produce exit status 2.
Python callers can import DiscoveryLimits from translation_finder.api
and pass it as the keyword-only limits argument to discover(). Defaults
match the CLI. Setting a field to None disables that limit.
DiscoveryLimits.unlimited() disables all configurable discovery limits.
Fixed safeguards such as the Transifex interpolation allowance still apply.
Negative values raise ValueError. High-level discovery reports truncation
through results.truncated and results.limit_reasons without emitting a
Python warning for truncation. Format detection can issue its own warnings,
for example when a JSON template cannot be parsed.
max_results=0 returns before scanning the tree and conservatively reports
truncation. Direct Finder use has the same scan and matching defaults and
exposes limit_reasons; pass None for a limit to disable it.
Direct backend discover() calls also use the default run-wide sniff limits.
Finder.filter_masks() accepts basename patterns such as *.po, using
only * as a wildcard, and matches them against lowercased filenames in every
directory. Question marks and brackets match literal characters. To select
multiple alternatives, pass a tuple such as ("resources.resx", "resources.resw").
Patterns containing / raise ValueError when the generator is iterated,
before any matches are yielded.
To restrict directories, pass a separate directory regular expression as
dirglob, for example finder.filter_masks("*.po", dirglob="po").
Finder.filter_files() accepts regular expressions for both the basename
and the optional directory filter. Both expressions are fullmatched against
lowercased names. Supply application-controlled regular expressions that are
safe to evaluate on repository-controlled names. The match budget counts
evaluations and cannot interrupt a single expensive expression. For a
user-supplied discovery hint, use the high-level discover(..., hint=...) API.
Finder.mask_matches() matches relative paths, for example po/*.po.
Its * wildcard can span directory separators; ? and brackets are
literal characters. It preserves case according to platform fnmatch rules,
rather than lowercasing paths as the filtering methods do.
Custom BaseDiscovery implementations return DiscoveryCandidate objects
from get_masks(). Each candidate associates the result with the paths which
actually generated it, allowing content detection to inspect the group without
expanding its wildcard mask again.
Backend filter_files() and candidate paths use read-only path references.
These can be compact file records or PurePath objects supplied through mock
listings. Use their name, parent, parts, and as_posix() interfaces;
do not require concrete Path instances or access filesystem methods on the
references. Read file content through self.finder.open(path). If additional
path operations are necessary, explicitly construct Path(path.as_posix()).
The public Finder.mask_matches(), filter_masks(), filter_files(), and
get_lc_candidates() methods continue to return relative PurePath objects,
including the original path objects for mock listings. Filesystem paths are
materialized on demand, so callers should not depend on object identity across
calls. Finder's lookup indexes are private implementation details.
Direct calls to a backend's get_masks() use Finder's configured limits and
any safeguards specific to that backend. The generic language-mask generator
also applies its per-path allowance. Use the high-level discover() to share
budgets across backends and receive a list-compatible DiscoveryResults
with run-wide truncated and limit_reasons attributes.
from translation_finder.discovery.base import BaseDiscovery
from translation_finder.discovery.result import DiscoveryCandidate
class CustomDiscovery(BaseDiscovery):
def get_masks(self, *, eager=False, hint=None):
for path in self.filter_files():
yield DiscoveryCandidate({"filemask": "locale/*.json"}, [path])