├── .github └── workflows │ └── rust.yml ├── .gitignore ├── .travis.yml ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── build.rs ├── locales └── test.json └── src └── lib.rs /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rust 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v2 19 | - name: Build 20 | run: cargo build --verbose 21 | - name: Run tests 22 | run: cargo test --verbose 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | Cargo.lock 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | sudo: required 3 | cache: cargo 4 | rust: 5 | - stable 6 | - beta 7 | - nightly 8 | matrix: 9 | include: 10 | - rust: nightly 11 | before_script: 12 | - export PATH=$HOME/.cargo/bin:$PATH 13 | - cargo install cargo-update || echo "cargo-update already installed" 14 | - cargo install cargo-travis || echo "cargo-travis already installed" 15 | - cargo install-update -a 16 | - mkdir -p target/kcov-master 17 | script: cargo coveralls --verbose --all-features 18 | allow_failures: 19 | - rust: nightly 20 | fast_finish: true 21 | addons: 22 | apt: 23 | packages: 24 | - libcurl4-openssl-dev 25 | - libelf-dev 26 | - libdw-dev 27 | - binutils-dev 28 | - cmake 29 | sources: 30 | - kalakris-cmake 31 | 32 | cache: 33 | directories: 34 | - /home/travis/.cargo 35 | 36 | before_cache: 37 | - rm -rf /home/travis/.cargo/registry 38 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "locales" 3 | version = "0.1.0" 4 | authors = ["Terry Raimondo "] 5 | edition = "2018" 6 | description = "Easy to use I18n" 7 | keywords = ["i18n", "internationalization", "locales", "localization"] 8 | license = "MIT/Apache-2.0" 9 | repository = "https://github.com/terry90/internationalization-rs" 10 | homepage = "https://github.com/terry90/internationalization-rs" 11 | build = "build.rs" 12 | 13 | [build-dependencies] 14 | glob = "0.3.0" 15 | quote = "1.0.2" 16 | serde_json = "1.0.41" 17 | proc-macro2 = "1.0" 18 | regex = "1.3.1" 19 | lazy_static = "1.4.0" 20 | 21 | [badges] 22 | travis-ci = { repository = "terry90/internationalization-rs" } 23 | coveralls = { repository = "terry90/internationalization-rs", branch = "master", service = "github" } 24 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2019 Terry Raimondo 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | Copyright (c) 2019 Terry Raimondo 3 | 4 | Permission is hereby granted, free of charge, to any person obtaining a copy of 5 | this software and associated documentation files (the "Software"), to deal in 6 | the Software without restriction, including without limitation the rights to 7 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 8 | the Software, and to permit persons to whom the Software is furnished to do so, 9 | subject to the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be included in all 12 | copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 16 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 17 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 18 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 19 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Locales 2 | 3 | [![Crates.io Version](https://img.shields.io/crates/v/locales.svg)](https://crates.io/crates/locales) 4 | ![LICENSE](https://img.shields.io/crates/l/locales) 5 | [![Coverage Status](https://coveralls.io/repos/github/terry90/internationalization-rs/badge.svg?branch=master)](https://coveralls.io/github/terry90/internationalization-rs?branch=master) 6 | [![Build Status](https://travis-ci.org/terry90/internationalization-rs.svg?branch=master)](https://travis-ci.org/terry90/internationalization-rs) 7 | 8 | A simple compile time i18n implementation in Rust. 9 | It throws a compilation error if the translation key is not present, but since the `lang` argument is dynamic it will panic if the language has not been added for the matching key. 10 | 11 | > API documentation [https://crates.io/crates/locales](https://crates.io/crates/locales) 12 | 13 | ### Usage 14 | 15 | Have a `locales/` folder somewhere in your app, root, src, anywhere. with `.json` files, nested in folders or not. 16 | It uses a glob pattern: `**/locales/**/*.json` to match your translation files. 17 | the files must look like this: 18 | 19 | ```json 20 | { 21 | "err.user.not_found": { 22 | "fr": "Utilisateur introuvable: $email, $id", 23 | "en": "User not found: $email, $id" 24 | }, 25 | "err.answer.all": { 26 | "fr": "Échec lors de la récupération des réponses", 27 | "en": "Failed to retrieve answers" 28 | }, 29 | "err.answer.delete.failed": { 30 | "fr": "Échec lors de la suppression de la réponse", 31 | "en": "Failed to delete answer" 32 | } 33 | } 34 | ``` 35 | 36 | Any number of languages can be added, but you should provide them for everything since it will panic if a language is not found when queried for a key. 37 | In your app, just call the `t!` macro 38 | 39 | ```rust 40 | use locales::t; 41 | 42 | fn main() { 43 | let lang = "en"; 44 | let res = t!("err.not_allowed", lang); 45 | assert_eq!("You are not allowed to do this", res); 46 | } 47 | ``` 48 | 49 | If the key is missing, your code will not compile 50 | 51 | ```rust,compile_fail 52 | use locales::t; 53 | 54 | fn main() { 55 | let lang = "en"; 56 | let res = t!("missing key", lang); 57 | // Code will not compile 58 | } 59 | 60 | ``` 61 | 62 | You can use interpolation, any number of argument is OK but you should note that they have to be sorted alphabetically. 63 | To use variables, call the `t!` macro like this: 64 | 65 | ```rust 66 | use locales::t; 67 | 68 | fn main() { 69 | let lang = "en"; 70 | let res = t!("err.user.not_found", email: "me@localhost", id: "1", lang); 71 | 72 | assert_eq!("User not found: me@localhost, ID: 1", res); 73 | } 74 | ``` 75 | 76 | ### Installation 77 | 78 | Locales is available on [crates.io](https://crates.io/crates/locales), include it in your `Cargo.toml`: 79 | 80 | ```toml 81 | [dependencies] 82 | locales = "0.1.0" 83 | ``` 84 | 85 | Then include it in your code like this: 86 | 87 | ```rust 88 | #[macro_use] 89 | extern crate locales; 90 | ``` 91 | 92 | Or use the macro where you want to use it: 93 | 94 | ```rust 95 | use locales::t; 96 | ``` 97 | 98 | ### Note 99 | 100 | Locales will not work if no `PWD` env var is set at compile time. 101 | It should work out of the box though 102 | 103 | License: MIT/Apache-2.0 104 | -------------------------------------------------------------------------------- /build.rs: -------------------------------------------------------------------------------- 1 | use glob::glob; 2 | use lazy_static::lazy_static; 3 | use proc_macro2::{Ident, Span, TokenStream}; 4 | use quote::quote; 5 | use regex::Regex; 6 | use std::collections::HashMap; 7 | use std::fs::File; 8 | use std::io::prelude::*; 9 | 10 | type Key = String; 11 | type Locale = String; 12 | type Value = String; 13 | type Translations = HashMap>; 14 | 15 | fn read_locales() -> Translations { 16 | let mut translations: Translations = HashMap::new(); 17 | 18 | let build_directory = std::env::var("PWD").unwrap(); 19 | let locales = format!("{}/**/locales/**/*.json", build_directory); 20 | println!("Reading {}", &locales); 21 | 22 | for entry in glob(&locales).expect("Failed to read glob pattern") { 23 | let entry = entry.unwrap(); 24 | println!("cargo:rerun-if-changed={}", entry.display()); 25 | let file = File::open(entry).expect("Failed to open the file"); 26 | let mut reader = std::io::BufReader::new(file); 27 | let mut content = String::new(); 28 | reader 29 | .read_to_string(&mut content) 30 | .expect("Failed to read the file"); 31 | let res: HashMap> = 32 | serde_json::from_str(&content).expect("Cannot parse locale file"); 33 | translations.extend(res); 34 | } 35 | translations 36 | } 37 | 38 | fn extract_vars(tr: &str) -> Vec { 39 | lazy_static! { 40 | static ref RE: Regex = Regex::new("\\$[a-zA-Z0-9_-]+").unwrap(); 41 | } 42 | 43 | let mut a = RE 44 | .find_iter(tr) 45 | .map(|mat| mat.as_str().to_owned()) 46 | .collect::>(); 47 | a.sort(); 48 | 49 | println!("-----\n{:?}\n-----", &a); 50 | a 51 | } 52 | 53 | fn convert_vars_to_idents(vars: &[String]) -> Vec { 54 | vars.iter() 55 | .map(|var| Ident::new(&var[1..], Span::call_site())) 56 | .collect() 57 | } 58 | 59 | fn generate_code(translations: Translations) -> proc_macro2::TokenStream { 60 | let mut branches = Vec::::new(); 61 | 62 | for (key, trs) in translations { 63 | let mut langs = Vec::::new(); 64 | let mut needs_interpolation = false; 65 | let mut vars = Vec::new(); 66 | for (lang, tr) in trs { 67 | let lang_vars = extract_vars(&tr); 68 | needs_interpolation = !lang_vars.is_empty(); 69 | 70 | if needs_interpolation { 71 | let idents = convert_vars_to_idents(&lang_vars); 72 | vars.extend(lang_vars.clone()); 73 | 74 | langs.push(quote! { 75 | #lang => #tr#(.replace(#lang_vars, $#idents))*, 76 | }); 77 | } else { 78 | langs.push(quote! { 79 | #lang => #tr.to_owned(), 80 | }); 81 | } 82 | } 83 | 84 | vars.sort(); 85 | vars.dedup(); 86 | let vars_ident = convert_vars_to_idents(&vars); 87 | if needs_interpolation { 88 | branches.push(quote! { 89 | (#key, #(#vars_ident: $#vars_ident:expr, )*$lang:expr) => { 90 | match $lang.as_ref() { 91 | #(#langs)* 92 | e => panic!("Missing language: {}", e) 93 | } 94 | }; 95 | }); 96 | branches.push(quote! { 97 | (#key, $($e:tt)*) => { 98 | compile_error!(stringify!(Please provide: #(#vars_ident),* >> The order matters!)); 99 | }; 100 | }); 101 | } else { 102 | branches.push(quote! { 103 | (#key, $lang:expr) => { 104 | match $lang.as_ref() { 105 | #(#langs)* 106 | e => panic!("Missing language: {}", e) 107 | } 108 | }; 109 | }); 110 | } 111 | } 112 | 113 | quote! { 114 | #[macro_export] 115 | macro_rules! t { 116 | #(#branches)* 117 | ($key:expr, $lang:expr) => { 118 | compile_error!("Missing translation"); 119 | } 120 | } 121 | } 122 | } 123 | 124 | fn write_code(code: TokenStream) { 125 | let dest = std::env::var("OUT_DIR").unwrap(); 126 | let mut output = File::create(std::path::Path::new(&dest).join("i18n.rs")).unwrap(); 127 | output 128 | .write_all(code.to_string().as_bytes()) 129 | .expect("Cannot write generated i18n code"); 130 | } 131 | 132 | fn main() { 133 | let translations = read_locales(); 134 | let code = generate_code(translations); 135 | println!("{}", &code); 136 | write_code(code); 137 | } 138 | -------------------------------------------------------------------------------- /locales/test.json: -------------------------------------------------------------------------------- 1 | { 2 | "hello": { 3 | "en": "Hello $name!", 4 | "fr": "Salut $name !" 5 | }, 6 | "multiple.vars": { 7 | "fr": "Nom: $name, Truc: $thing, bingo: $bingo" 8 | }, 9 | "inconsistent.vars": { 10 | "en": "Name: $thing, ok: $ok", 11 | "fr": "Salut $name !" 12 | }, 13 | "key.test": { 14 | "en": "This is a test", 15 | "fr": "C'est un test" 16 | }, 17 | "err.not_allowed": { 18 | "en": "You are not allowed to do this", 19 | "fr": "Vous n'êtes pas autorisé à faire cela" 20 | }, 21 | "err.user.not_found": { 22 | "en": "User not found: $email, ID: $id" 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! [![Crates.io Version](https://img.shields.io/crates/v/locales.svg)](https://crates.io/crates/locales) 2 | //! ![LICENSE](https://img.shields.io/crates/l/locales) 3 | //! [![Coverage Status](https://coveralls.io/repos/github/terry90/internationalization-rs/badge.svg?branch=master)](https://coveralls.io/github/terry90/internationalization-rs?branch=master) 4 | //! [![Build Status](https://travis-ci.org/terry90/internationalization-rs.svg?branch=master)](https://travis-ci.org/terry90/internationalization-rs) 5 | //! 6 | //! A simple compile time i18n implementation in Rust. 7 | //! It throws a compilation error if the translation key is not present, but since the `lang` argument is dynamic it will panic if the language has not been added for the matching key. 8 | 9 | //! > API documentation [https://crates.io/crates/locales](https://crates.io/crates/locales) 10 | 11 | //! ## Usage 12 | 13 | //! Have a `locales/` folder somewhere in your app, root, src, anywhere. with `.json` files, nested in folders or not. 14 | //! It uses a glob pattern: `**/locales/**/*.json` to match your translation files. 15 | 16 | //! the files must look like this: 17 | 18 | //! ```json 19 | //! { 20 | //! "err.user.not_found": { 21 | //! "fr": "Utilisateur introuvable: $email, $id", 22 | //! "en": "User not found: $email, $id" 23 | //! }, 24 | //! "err.answer.all": { 25 | //! "fr": "Échec lors de la récupération des réponses", 26 | //! "en": "Failed to retrieve answers" 27 | //! }, 28 | //! "err.answer.delete.failed": { 29 | //! "fr": "Échec lors de la suppression de la réponse", 30 | //! "en": "Failed to delete answer" 31 | //! } 32 | //! } 33 | //! ``` 34 | 35 | //! Any number of languages can be added, but you should provide them for everything since it will panic if a language is not found when queried for a key. 36 | 37 | //! In your app, just call the `t!` macro 38 | 39 | //! ```rust 40 | //! use locales::t; 41 | //! 42 | //! fn main() { 43 | //! let lang = "en"; 44 | //! let res = t!("err.not_allowed", lang); 45 | 46 | //! assert_eq!("You are not allowed to do this", res); 47 | //! } 48 | //! ``` 49 | //! 50 | //! If the key is missing, your code will not compile 51 | 52 | //! ```rust,compile_fail 53 | //! use locales::t; 54 | //! 55 | //! fn main() { 56 | //! let lang = "en"; 57 | //! let res = t!("missing key", lang); 58 | 59 | //! // Code will not compile 60 | //! } 61 | //! 62 | //! ``` 63 | //! You can use interpolation, any number of argument is OK but you should note that they have to be sorted alphabetically. 64 | //! To use variables, call the `t!` macro like this: 65 | //! 66 | //! ```rust 67 | //! use locales::t; 68 | //! 69 | //! fn main() { 70 | //! let lang = "en"; 71 | //! let res = t!("err.user.not_found", email: "me@localhost", id: "1", lang); 72 | //! 73 | //! assert_eq!("User not found: me@localhost, ID: 1", res); 74 | //! } 75 | //! ``` 76 | //! 77 | //! ## Installation 78 | 79 | //! Locales is available on [crates.io](https://crates.io/crates/locales), include it in your `Cargo.toml`: 80 | 81 | //! ```toml 82 | //! [dependencies] 83 | //! locales = "0.1.0" 84 | //! ``` 85 | 86 | //! Then include it in your code like this: 87 | 88 | //! ```rust,ignore 89 | //! #[macro_use] 90 | //! extern crate locales; 91 | //! ``` 92 | 93 | //! Or use the macro where you want to use it: 94 | 95 | //! ```rust 96 | //! use locales::t; 97 | //! ``` 98 | 99 | //! ## Note 100 | 101 | //! Locales will not work if no `PWD` env var is set at compile time. 102 | //! It should work out of the box though 103 | 104 | include!(concat!(env!("OUT_DIR"), "/i18n.rs")); 105 | 106 | #[cfg(test)] 107 | mod tests { 108 | use super::*; 109 | 110 | #[test] 111 | fn it_translates() { 112 | assert_eq!(t!("key.test", "en"), "This is a test"); 113 | assert_eq!(t!("key.test", "fr"), "C'est un test"); 114 | assert_eq!( 115 | t!("err.not_allowed", "fr"), 116 | "Vous n'êtes pas autorisé à faire cela" 117 | ); 118 | assert_eq!( 119 | t!("err.not_allowed", "en"), 120 | "You are not allowed to do this" 121 | ); 122 | } 123 | 124 | #[test] 125 | fn it_interpolates() { 126 | assert_eq!(t!("hello", name: "Fred", "fr"), "Salut Fred !"); 127 | assert_eq!(t!("hello", name: "Fred", "en"), "Hello Fred!"); 128 | } 129 | 130 | #[test] 131 | fn it_interpolates_multiple_vars() { 132 | assert_eq!( 133 | t!("multiple.vars", bingo: "bingo", name: "Fred", thing: "thing", "fr"), 134 | "Nom: Fred, Truc: thing, bingo: bingo" 135 | ); 136 | } 137 | 138 | #[test] 139 | fn it_interpolates_inconsistent_vars() { 140 | assert_eq!( 141 | t!("inconsistent.vars", name: "Fred", ok: "top", thing: "thing", "fr"), 142 | "Salut Fred !" 143 | ); 144 | assert_eq!( 145 | t!("inconsistent.vars", name: "Fred", ok: "top", thing: "thing", "en"), 146 | "Name: thing, ok: top" 147 | ); 148 | } 149 | 150 | #[test] 151 | #[should_panic] 152 | fn it_fails_to_translate() { 153 | assert_eq!(t!("key.test", "es"), "Hola"); 154 | } 155 | } 156 | --------------------------------------------------------------------------------