Skip to content

Runtime library

Terminal window
go get locale.dev/localizer

The root package depends on Cobra (v1.8 or later), pflag, golang.org/x/text and golang.org/x/sys; the kongx and urfave subpackages add kong and urfave/cli v3 respectively (see the kong and urfave/cli guides). The library makes no network calls, and it has no telemetry or credentials. The full API is on pkg.go.dev. Until v0.6 the module path was github.com/DABH/localizer; from v0.7.0 it is locale.dev/localizer, so a CLI that upgrades changes its imports.

Function Description
Localize(root *cobra.Command, catalogs fs.FS, opts ...Option) Translates a Cobra command tree in place: descriptions, flags, group titles, templates, the built-in help and completion commands, and Cobra’s errors. Call it right before root.Execute(). It never panics: a failure leaves the tree, or the part of it not yet translated, in English.
Init(catalogs fs.FS, opts ...Option) string Detects the language and loads the matching catalog for the helpers below. Returns the language, or "" for English. Localize calls it for you. Calling it again switches catalogs for the helpers and the hooks; it never panics.
T(s string) string The translation of s, or s unchanged. A format string (one with verbs) is looked up exactly, so call T before formatting; other text is translated like output.
Sprintf(format string, args ...any) string fmt.Sprintf with a translated format.
Errorf(format string, args ...any) error fmt.Errorf with a translated format. %w still wraps.
Error(err error) string An error message translated for display. CLI-authored parts of a wrapped chain are translated, and server text is left as it is. "" for a nil error.
Translate(s string, mode Mode) string Already formatted text translated in the given mode: ModeOutput for general output (it never splits label: rest, which could be data), ModeHelp for help text, ModeError for error messages, including wrapped-error chains. It is what Writer and Error use.
Writer(w io.Writer) io.Writer A writer that translates CLI strings written to w, one Write at a time, in output mode. It returns w itself when output isn’t localized, exposes w’s Fd method for terminal detection, and writes the original bytes if the translation fails.
WriterMode(w io.Writer, mode Mode) io.Writer Writer with an explicit mode: ModeHelp for a stream that carries help text, ModeError for one that carries error messages. The adapters for frameworks other than Cobra use it on the framework’s help and error writers.
Lang() string The active language tag ("qps" for pseudo-localization), or "" for English.
Reset() Undoes Init, for tests: the helpers become identity functions and the next Localize detects the language afresh. Command trees already localized keep their translated strings.
Option Description
WithEnvVar(name) An application-specific override variable, such as YOURCLI_LANG, checked before LOCALIZER_LANG.
WithLanguage(tag) Force a language, for example from a --lang flag. "en" or "off" disables localization.
WithoutErrWriter() Don’t wrap the root command’s error writer or translate its error prefix. Cobra’s own error messages then stay in English; help is still translated, and Error still works.

By default Localize translates the root command’s error prefix (Error:) in place when the catalog has it, and replaces the root’s error writer — the one set with SetErr, or os.Stderr — with a wrapper that translates Cobra’s error messages in error mode. The wrapper exposes the underlying writer’s Fd method, so terminal detection keeps working, but it isn’t an *os.File: an application that type-asserts cmd.ErrOrStderr() to *os.File needs WithoutErrWriter. Set your own error writer before calling Localize; one set afterwards replaces the wrapper, and Cobra’s messages then print in English behind the already translated prefix.

The same in both runtimes:

Variable Effect
LOCALIZER_LANG=ja Force a language. A list such as ja:en is allowed.
LOCALIZER_LANG=en or off Disable localization.
LOCALIZER_LANG=qps Pseudo-localization: every known string is shown as ⟦Ŝţŕîñĝ⟧, so strings that don’t go through Localizer stand out.
LOCALIZER_DEBUG=1 Report on stderr each help string that has no translation, as it renders (localizer: untranslated (ja): "Add a task."), and internal failures that were swallowed, such as a catalog that fails to load or a hook that failed. Misses in output and error messages aren’t reported.
LOCALIZER_DUMP=<file> Write every help string in the command tree as JSON, with hit or miss (see Testing). Both runtimes create the file new (an existing file is never overwritten) and ignore the variable in a root or setuid process.

Localizer uses the first of these that is set:

  1. the language passed with WithLanguage / language=;
  2. your application’s override variable (WithEnvVar / env_var=), then LOCALIZER_LANG. Besides a language or a list (ja:en), the value can be off (also none, 0, false, no, disable, disabled) or qps (also qps-ploc, pseudo);
  3. LC_ALL, LC_MESSAGES or LANG, in that order: the first one with a value decides. A C or POSIX locale means English. Otherwise GNU LANGUAGE, if set, lists preferred languages ahead of that locale;
  4. LANGUAGE alone, when none of those three has a value;
  5. the OS setting. On macOS the preferred languages (AppleLanguages), read straight from ~/Library/Preferences/.GlobalPreferences.plist — a file of at most 8 MiB, parsed without running defaults; on Windows the display languages; nothing on other systems;
  6. English.

C and POSIX locales mean English, so scripts that set LC_ALL=C get stable output. Locale names are normalized to BCP 47 (pt_BR.UTF-8 becomes pt-BR; zh_TW becomes zh-TW, which matches a zh-Hant catalog but never zh-Hans) and matched to your catalogs. Only confident matches are used. Both runtimes implement the same detection and matching rules and are tested against the same cases.

Before a language is used, the Python runtime checks that sys.stdout and sys.stderr can encode the catalog’s text. When one of them can’t, output stays in English, and LOCALIZER_DEBUG=1 says why (localizer: stdout (cp1252) cannot encode the ja catalog; output stays in English). This is the situation on Windows when output goes to a file or a pipe: Python then encodes with the ANSI code page (cp1252, cp932, …), and a translated help screen would otherwise end in UnicodeEncodeError, or in \uXXXX escapes where the stream’s error handler allows it. Output to the console itself, including Windows Terminal, is UTF-8 and unaffected. To get translations through pipes and files as well, run Python in UTF-8 mode: set PYTHONUTF8=1 (or PYTHONIOENCODING=utf-8) in the environment. UTF-8 and UTF-16/32 streams skip the check; for any other encoding the catalog is encoded once, a fraction of a millisecond.