Overview

Rosetta is an easy-to-use Rust internationalization library powered by code generation. Unlike other libraries, translation files are parsed and embedded into the resulting binary at build-time. This provide a better developer experience and reduce runtime overheat.

Using your translation files in your project is (almost) as easy as that:


#![allow(unused)]
fn main() {
rosetta_i18n::include_translations!();

println!("{}", Lang::En.hello("world"));  // Hello, world!
}

The following documentation aims to provide an exhaustive guide about using Rosetta in your project. See Getting started to get an usage overview.

Here are all the links related to the project:

Please give a ⭐ to the GitHub repository if you use Rosetta.

Support

If you encounter bugs or need help using Rosetta, here's what to do:

Please do not open issues for help request, this is not the right place for it. Use discussions instead.

Contributing

Rosetta is free and open-source. You can find the source code on GitHub and open a new issue to report bug or request features. If you want to improve the code or the documentation, consider opening a pull request.

Any contribution is welcome, even the smallest! 🙌

Getting started

The following guide explains how to use rosetta-i18 and rosetta-build to manage your translations. Please refer to other sections in this documentation or to the API documentation for in depth explanations.

Installation

Rosetta is separated into two crates: rosetta-i18n and rosetta-build. To install both, add the following to your Cargo.toml:

[dependencies]
rosetta-i18n = "0.1"

[build-dependencies]
rosetta-build = "0.1"

rosetta-build is used inside a build script and must be a build dependency.

Writing translations files

Rosetta use JSON translation files, which is similar to the one used by many other translation libraries and this widely supported. We need to put these files somewhere, for example in a /locales directory.

locales/en.json

{
    "hello": "Hello world!",
    "hello_name": "Hello {name}!"
}

In this example, we defined two keys, hello and hello_name. The first is a static string, whereas the second contains the name variable which will be replaced at runtime by the value of your choice.

Create a file for each language you want to be supported by your application. It is not required that all files contain all keys: we will define the fallback language later.

Generating code from translation files

It is now that the magic happens. Rosetta lets you generate a Rust type from your translation files. For that, it use a build script which will be run each time you edit a translation file.

We need to create a build.rs file at the root folder of the crate (same folder as the Cargo.toml file).

build.rs

fn main() -> Result<(), Box<dyn std::error::Error>> {
    rosetta_build::config()
        .source("en", "locales/en.json")
        .source("fr", "locales/fr.json")
        .fallback("en")
        .generate()?;

    Ok(())
}

This script use the rosetta_build crate. In this example, we define two languages with ISO 639-1 language identifiers: en and fr. The en language is defined as fallback and will be used if a key is not defined in other languages.

The .generate() method is responsible for code generation. By default, the output file will be generated in a folder inside the target directory (OUT_DIR env variable).

Using the generated type

The generated type (named Lang except if you defined another name - see the previous section) must be included in your code with the include_translations macro. A good practice is to isolate it in a dedicated module.

Each translation key is transformed into a method, and each language into an enum variant. Parameters are sorted alphabetically to avoid silent breaking changes when reordering.

src/main.rs

mod translations {
    rosetta_i18n::include_translations!();
}

fn main() {
    use translations::Lang;

    println!("{}", Lang::En.hello());  // Hello world!
    println!("{}", Lang::En.hello_name("Rust"));  // Hello Rust!
}

Optional features

The rosetta-i18n and rosetta-build crates allow to turn on some additional features with Cargo features. Most of these requires additional dependencies and are not enabled by default.

To enable a feature, you need to add a feature key in the Cargo.toml file like the following example:

rosetta-i18n = { version = "0.1", features = ["serde"] }

rosetta-i18n

  • serde: enable Serde support, providing Serialize and Deserialize implementation for some types. Utility functions to serialize and deserialize generated types are also provided.

rosetta-build

  • rustfmt (enabled by default): format generated code with rustfmt. Disable this feature if rustfmt is not installed in your computer.

Build options

The following is an exhaustive reference of all configurable build options.

These options are provided as methods of the RosettaBuilder type.

Required options :

  • .fallback(): register the fallback language with a given language identifier and path
  • .source(): register an additional translation source with a given language identifier and path

Additional options :

  • .name(): use a custom name for the generate type (Lang by default)
  • .output(): export the type in another output location (OUT_DIR by default)

More information in the RosettaBuilder API documentation.

JSON file format

The following is an exhaustive reference of the JSON file format used for translations.

Note: nested keys are not yet available.

Simple key

A simple translation key is a static string key without any variable interpolation. The { and } characters are not allowed.

{
    "simple": "Hello world!"
}

String formatting

You can add variables inside keys to insert dynamic content at runtime. Variable name should be in snake_case surrounded by { and } characters.

{
    "formatted": "I like three things: {first}, {second} and Rust."
}

You can add as many parameters as you want. The same parameter can be inserted several times. Languages that are not fallback languages must have the same parameters as the fallback language.

Useful extensions

If you are using Visual Studio Code, here is some useful extensions you can use.

Using with Rust Analyzer

rust-analyzer is a popular extension providing completion and more for Rust files. If the generated code is not correctly loaded, add the following line to the .vscode/settings.json file:

"rust-analyzer.cargo.loadOutDirsFromCheck": true

Using with i18n ally

i18n ally is an all-in-one i18n extension for VS Code that provide inline annotation of translated strings in your code.

i18n ally example usage

i18n ally supports custom translations frameworks by adding a simple config file. Because code generated by Rosetta looks like any Rust method, the following configuration will consider that any method of a variable named lang or an enum named Lang is a translation key. It's not perfect as trait methods are also considered by the extension as translations keys, but it work well in most case.

Create a .vscode/i18n-ally-custom-framework.yml file with the following content to enable Rosetta support. Edit this configuration if you are not using lang as variable name.

# .vscode/i18n-ally-custom-framework.yml
languageIds:
  - rust

usageMatchRegex:
  - "[^\\w\\d]Lang::[A-z]+\\.([a-z_]+)\\(.*\\)"
  - "[^\\w\\d]lang\\.([a-z_]+)\\(.*\\)"

# If set to true, only enables this custom framework (will disable all built-in frameworks)
monopoly: true