├── .travis.yml ├── .gitignore ├── examples ├── extract.rs └── macrogen.rs ├── README.tpl ├── data └── localize_macros.rs ├── Cargo.toml ├── src ├── error.rs ├── message.rs ├── localizer.rs ├── common.rs ├── macrogen.rs ├── lib.rs ├── extractor.rs └── lang.rs ├── ChangeLog.md ├── README.md └── LICENSE /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | rust: 3 | - 1.13.0 4 | - stable 5 | - beta 6 | - nightly 7 | matrix: 8 | allow_failures: 9 | - rust: nightly 10 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock 7 | Cargo.lock 8 | -------------------------------------------------------------------------------- /examples/extract.rs: -------------------------------------------------------------------------------- 1 | extern crate crowbook_intl; 2 | 3 | use crowbook_intl::Extractor; 4 | 5 | fn main() { 6 | let mut extractor = Extractor::new(); 7 | extractor.add_messages_from_dir("src/").unwrap(); 8 | println!("{}", extractor.generate_pot_file()); 9 | } 10 | -------------------------------------------------------------------------------- /README.tpl: -------------------------------------------------------------------------------- 1 | {{readme}} 2 | 3 | ## Documentation ## 4 | 5 | See the 6 | [documentation on docs.rs](https://docs.rs/crowbook-intl). 7 | 8 | ## ChangeLog ## 9 | 10 | See [the ChangeLog file](ChangeLog.md). 11 | 12 | ## Author ## 13 | 14 | [Élisabeth Henry](http://lise-henry.github.io/) . 15 | 16 | 17 | -------------------------------------------------------------------------------- /data/localize_macros.rs: -------------------------------------------------------------------------------- 1 | // This file was generated automatically by crowbook-localize. 2 | // It is probably not a good idea to edit it manually. 3 | // 4 | // # Usage: 5 | // 6 | // ```rust, no_run 7 | // extern crate crowbook_intl_runtime; 8 | // #[macro_use] mod localize_macros; 9 | // crowbook_intl_runtime::set_lang("en"); 10 | // lformat!("Hello, {}", name); 11 | // set_lang("fr"); 12 | // lformat!("Hello, {}", name); 13 | // ``` 14 | 15 | 16 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "crowbook-intl" 3 | version = "0.2.1" 4 | authors = ["Elisabeth Henry "] 5 | description = "An internationalization library to localize strings, translating them according to runtime option, using macros." 6 | readme = "README.md" 7 | keywords = ["localization", "internationalization"] 8 | repository = "https://github.com/lise-henry/crowbook-intl/" 9 | documentation = "https://docs.rs/crowbook-intl" 10 | license = "MPL-2.0" 11 | publish = true 12 | 13 | [dependencies] 14 | lazy_static = "0.2" 15 | regex = "0.2" 16 | walkdir = "1" 17 | -------------------------------------------------------------------------------- /examples/macrogen.rs: -------------------------------------------------------------------------------- 1 | extern crate crowbook_intl; 2 | 3 | use crowbook_intl::{Localizer, Extractor}; 4 | 5 | fn main() { 6 | let str_fr = r#" 7 | msgid "hello, {}" 8 | msgstr "bonjour, {}" 9 | 10 | msgid "Shit: \"{}\" went wrong;" 11 | msgstr "Chiotte: \"{}\" est parti en live;" 12 | 13 | msgid "kwak!" 14 | msgstr "coin !" 15 | "#; 16 | 17 | let str_es = r#" 18 | msgid "hello, {}" 19 | msgstr "hola, {}" 20 | 21 | msgid "Oi!" 22 | msgstr "¡Oi!" 23 | "#; 24 | let extractor = Extractor::new(); 25 | let mut localizer = Localizer::new(&extractor); 26 | localizer.add_lang("fr", str_fr).unwrap(); 27 | localizer.add_lang("es", str_es).unwrap(); 28 | println!("{}", localizer.generate_macro_file()); 29 | } 30 | -------------------------------------------------------------------------------- /src/error.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with 3 | // this file, You can obtain one at https://mozilla.org/MPL/2.0/. 4 | 5 | use std::error; 6 | use std::result; 7 | use std::fmt; 8 | 9 | /// Internal ErrorType 10 | #[derive(Debug, PartialEq)] 11 | enum ErrorType { 12 | Default, 13 | Parse, 14 | } 15 | 16 | /// Result type (returned by most methods of this library) 17 | pub type Result = result::Result; 18 | 19 | #[derive(Debug, PartialEq)] 20 | /// Error type returned by methods of this library 21 | pub struct Error { 22 | msg: String, 23 | variant: ErrorType 24 | } 25 | 26 | impl Error { 27 | /// Creates a new default error 28 | pub fn new>(msg: S) -> Error { 29 | Error { 30 | msg: msg.into(), 31 | variant: ErrorType::Default, 32 | } 33 | } 34 | 35 | /// Creates a new parse error 36 | pub fn parse>(msg: S) -> Error { 37 | Error { 38 | msg: msg.into(), 39 | variant: ErrorType::Parse, 40 | } 41 | } 42 | } 43 | 44 | impl error::Error for Error { 45 | fn description(&self) -> &str { 46 | &self.msg 47 | } 48 | } 49 | 50 | impl fmt::Display for Error { 51 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 52 | match self.variant { 53 | ErrorType::Parse => write!(f, "Error parsing localization file: {}", self.msg), 54 | _ => write!(f, "{}", self.msg), 55 | } 56 | } 57 | } 58 | 59 | -------------------------------------------------------------------------------- /src/message.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with 3 | // this file, You can obtain one at https://mozilla.org/MPL/2.0/. 4 | 5 | use std::fmt; 6 | use common::escape_string; 7 | 8 | /// Represents a comment concerning the location/translation of a message 9 | #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)] 10 | pub enum Comment { 11 | /// File and line 12 | Source(String, usize) 13 | } 14 | 15 | 16 | /// Represents a message, with a string and a list of comments 17 | /// corresponding to position in source file 18 | #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)] 19 | pub struct Message { 20 | pub comments: Vec, 21 | pub msg: String, 22 | } 23 | 24 | 25 | impl Message { 26 | /// Creates a new message 27 | pub fn new>(msg: S) -> Message { 28 | Message { 29 | msg: msg.into(), 30 | comments: vec!(), 31 | } 32 | } 33 | 34 | /// Add a source location to a comment 35 | pub fn add_source>(&mut self, file: S, line: usize) -> &mut Self { 36 | self.comments.push(Comment::Source(file.into(), line)); 37 | self 38 | } 39 | } 40 | 41 | 42 | impl fmt::Display for Message { 43 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 44 | write!(f, "#:")?; 45 | for comment in &self.comments { 46 | match *comment { 47 | Comment::Source(ref file, line) => write!(f, " {}:{}", file, line)?, 48 | } 49 | } 50 | writeln!(f, " 51 | msgid \"{}\" 52 | msgstr \"\"\n", 53 | escape_string(self.msg.as_str())) 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /ChangeLog.md: -------------------------------------------------------------------------------- 1 | # ChangeLog # 2 | 3 | ## 0.2.1 (2017-03-04) ## 4 | * Update *regex* dependency to 0.2 5 | 6 | ## 0.2.0 (2016-12-23) ## 7 | * Fix use of `crowbook-intl-runtime` in macro generation. This might 8 | be a breaking change in some cases. 9 | * Structs now derive `Debug` and `Clone`. 10 | 11 | ## 0.1.0 (2016-11-18) ## 12 | * Renamed library `crowbook-localize` to `crowbook-intl`. 13 | * Requires `rustc` >= 1.13.0. 14 | * Split library between `crowbook-intl` and 15 | `crowbook-intl-runtime`. The latter defines some runtime functions 16 | used by the generated macros. This split (should) allow to have 17 | multiple libraries using `crowbook-intl` in the same program. 18 | * `Localizer::write_macro_file` now takes an `AsRef` instead of 19 | an `&str`. 20 | 21 | ## 0.0.9 (2016-10-26) ## 22 | * Make it possible to `include!` the generated macro files from 23 | `OUT_DIR`, and document this way of doing. 24 | 25 | ## 0.0.8 (2016-10-14) ## 26 | * In order to correctly handle multiline strings, and to make it 27 | possible to use the same translation for two strings that are 28 | identical but don't use backslash the same way, the API had to be 29 | modified a bit. It should now work correctly-ish. 30 | * Messages are now sorted (by file of apparition) before being written 31 | to `.pot` file. 32 | 33 | ## 0.0.7 (2016-10-13) ## 34 | * `Extractor` now uses `escape_string` for its keys, allowing to use 35 | `lformat!` with multiline strings using the `\` escape at end of line. 36 | 37 | ## 0.0.6 (2016-10-13) ## 38 | * '\' followed by a newline is now escaped (well, suppressed along 39 | leading whitespace on next line) when generating pot file. 40 | * Now uses Travis for continuous integration. 41 | 42 | ## 0.0.5 (2016-10-10) ## 43 | * Newlines characters are escaped when generating pot file so 44 | `msgmerge` doesn't complain 45 | 46 | ## 0.0.4 (2016-10-09) ## 47 | `crowbook-localize` should now be able to generate `.pot` files that 48 | are compatible with `msgmerge` and be able to read `.po` files that 49 | have been updated with `msgmerge`. 50 | * Fix printing and reading of strings which caused problems with 51 | escape characters. 52 | * Add support for multiline strings ala gettext in translation files. 53 | 54 | ## 0.0.3 (2016-10-08) ## 55 | * Added the `Extractor` struct, that generates a pot-like file looking 56 | at `lformat!` invocations in your source code. 57 | 58 | ## 0.0.2 (2016-10-07) ## 59 | * Only export `Localizer` as public API. 60 | * Rewrote `lformat!` macro generation. 61 | 62 | ## 0.0.1 (2016-10-07) ## 63 | * Initial (pre-)release 64 | -------------------------------------------------------------------------------- /src/localizer.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with 3 | // this file, You can obtain one at https://mozilla.org/MPL/2.0/. 4 | 5 | use lang::Lang; 6 | use error::{Result, Error}; 7 | use macrogen; 8 | use extractor::Extractor; 9 | 10 | use std::fs::File; 11 | use std::path::Path; 12 | use std::io::Write; 13 | 14 | /// Main struct for initiating localization for a project. 15 | /// 16 | /// # Example 17 | /// 18 | /// ```rust 19 | /// use crowbook_intl::{Localizer, Extractor}; 20 | /// let fr = r#" 21 | /// msgid "Hello, {}" 22 | /// msgstr "Bonjour, {}" 23 | /// "#; 24 | /// let es = r#" 25 | /// msgid "Hello, {}" 26 | /// msgstr "Hola, {}" 27 | /// "#; 28 | /// let extractor = Extractor::new(); 29 | /// let mut localizer = Localizer::new(&extractor); 30 | /// localizer.add_lang("fr", fr).unwrap(); 31 | /// localizer.add_lang("es", es).unwrap(); 32 | /// println!("{}", localizer.generate_macro_file()); 33 | /// ``` 34 | #[derive(Debug, Clone)] 35 | pub struct Localizer<'a> { 36 | langs: Vec, 37 | extractor: &'a Extractor, 38 | } 39 | 40 | impl<'a> Localizer<'a> { 41 | /// Create a new, empty Localizer 42 | pub fn new(extractor: &'a Extractor) -> Localizer<'a> { 43 | Localizer { 44 | langs: vec!(), 45 | extractor: extractor, 46 | } 47 | } 48 | 49 | /// Add a lang to the localizer 50 | /// 51 | /// # Arguments 52 | /// 53 | /// * `lang`: the code of the language (e.g. "fr", "en", ...); 54 | /// * `s`: a string containing localization information. It should be foramtted 55 | /// similarly to gettext `mo` files. 56 | pub fn add_lang>(&mut self, lang: S, s: &str) -> Result<()> { 57 | let lang = Lang::new_from_str(lang, s)?; 58 | self.langs.push(lang); 59 | Ok(()) 60 | } 61 | 62 | /// Generate the `localization_macros.rs` file. 63 | pub fn generate_macro_file(mut self) -> String { 64 | macrogen::generate_macro_file(&mut self.langs, self.extractor) 65 | } 66 | 67 | /// Write the `localization_macros.rs` file to a file. 68 | pub fn write_macro_file>(self, file: P) -> Result<()> { 69 | let mut f = File::create(file.as_ref()) 70 | .map_err(|e| Error::new(format!("Could not create file {file}: {error}", 71 | file = file.as_ref().display(), 72 | error = e)))?; 73 | let content = self.generate_macro_file(); 74 | f.write_all(content.as_bytes()) 75 | .map_err(|e| Error::new(format!("Could not write to file {file}: {error}", 76 | file = file.as_ref().display(), 77 | error = e)))?; 78 | Ok(()) 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/common.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with 3 | // this file, You can obtain one at https://mozilla.org/MPL/2.0/. 4 | 5 | use error::{Error, Result}; 6 | 7 | use std::borrow::Cow; 8 | 9 | use regex::Regex; 10 | 11 | /// Escape some special characters that would cause trouble 12 | /// 13 | /// The newline character 14 | /// '\' followed by a newline 15 | pub fn escape_string<'a, S:Into>>(s: S) -> Cow<'a, str> { 16 | lazy_static! { 17 | static ref REGEX:Regex = Regex::new(r#"\\\n\s*"#).unwrap(); 18 | } 19 | 20 | let s = s.into(); 21 | if s.contains('\n') || REGEX.is_match(&s) { 22 | let mut res = REGEX.replace_all(&s, "").into_owned(); 23 | res = res.replace('\n', r"\n"); 24 | Cow::Owned(res) 25 | } else { 26 | s 27 | } 28 | } 29 | 30 | /// Find the next string, delimited by quotes `"` (which are not returned), 31 | /// and not stopping at escape quotes `\"` 32 | pub fn find_string(bytes: &[u8]) -> Result { 33 | let mut begin = None; 34 | let mut i = 0; 35 | while i < bytes.len() { 36 | match bytes[i] { 37 | b'"' => if begin.is_some() { 38 | if bytes[i-1] != b'\\' { 39 | break 40 | } 41 | } else { 42 | if i + 1 >= bytes.len() { 43 | return Err(Error::new("")); 44 | } 45 | begin = Some(i + 1); 46 | }, 47 | _ => (), 48 | } 49 | i += 1; 50 | } 51 | let begin = if let Some(begin) = begin { 52 | begin 53 | } else { 54 | return Err(Error::new("")); 55 | }; 56 | Ok(String::from_utf8(bytes[begin..i].to_vec()).unwrap()) 57 | } 58 | 59 | 60 | #[test] 61 | fn find_string_1() { 62 | let s = r#" 63 | "Test" 64 | "#; 65 | let expected = "Test"; 66 | assert_eq!(&find_string(s.as_bytes()).unwrap(), expected); 67 | } 68 | 69 | #[test] 70 | fn find_string_2() { 71 | let s = r#" 72 | "A \"test\"..." 73 | "#; 74 | let expected = r#"A \"test\"..."#; 75 | assert_eq!(&find_string(s.as_bytes()).unwrap(), expected); 76 | } 77 | 78 | #[test] 79 | fn escape_string_1() { 80 | let s = r#"foo 81 | bar"#; 82 | let expected = "foo\\nbar"; 83 | assert_eq!(&escape_string(s), expected); 84 | } 85 | 86 | #[test] 87 | fn escape_string_2() { 88 | let s = "foo\ 89 | bar"; 90 | let expected = "foobar"; 91 | assert_eq!(&escape_string(s), expected); 92 | } 93 | 94 | #[test] 95 | fn escape_string_3() { 96 | let s = r#"foo\ 97 | bar"#; 98 | let expected = "foobar"; 99 | assert_eq!(&escape_string(s), expected); 100 | } 101 | 102 | 103 | #[test] 104 | fn escape_string_4() { 105 | let s = r#"foo\ 106 | bar 107 | baz"#; 108 | let expected = "foobar\\nbaz"; 109 | assert_eq!(&escape_string(s), expected); 110 | } 111 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # crowbook-intl 2 | 3 | A library to localize strings, translating them according to runtime options. 4 | 5 | Basically, this library allows your project to generate a `lformat!` macro, that behaves 6 | similarly to `format!`, except the message string (the first argument) might get translated 7 | (if you can find the appropriate string for the language). 8 | 9 | ## Usage 10 | 11 | First, you'll need to add the following to your `Cargo.toml` file: 12 | 13 | ```toml 14 | build = "build.rs" 15 | 16 | [build-dependencies] 17 | crowbook-intl = "0.1.0" 18 | 19 | [dependencies] 20 | crowbook-intl-runtime = "0.1.0" 21 | ``` 22 | 23 | You'll then need to create the `build.rs` file, which can look like this: 24 | 25 | ```rust,ignore 26 | extern crate crowbook_intl; 27 | use crowbook_intl::{Localizer, Extractor}; 28 | 29 | fn main() { 30 | // Generate a `lang/default.pot` containing strings used to call `lformat!` 31 | let mut extractor = Extractor::new(); 32 | extractor.add_messages_from_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/src")).unwrap(); 33 | extractor.write_pot_file(concat!(env!("CARGO_MANIFEST_DIR"), "/lang/default.pot")).unwrap(); 34 | 35 | // Generate the `localize_macros.rs` file 36 | let mut localizer = Localizer::new(&extractor); 37 | // Use env::var instead of env! to avoid problems when cross-compiling 38 | let dest_path = Path::new(&env::var("OUT_DIR").unwrap()) 39 | .join("localize_macros.rs"); 40 | localizer.write_macro_file(dest_path).unwrap(); 41 | } 42 | ``` 43 | 44 | This will create a `localize_macros.rs` at build time somewhere in `OUT_DIR`, containing the `lformat!` macro. 45 | To actually use this macro, you have to create a `src/localize_macros.rs` file that includes it: 46 | 47 | ```rust,ignore 48 | include!(concat!(env!("OUT_DIR"), "/localize_macros.rs")); 49 | ``` 50 | 51 | To use it, the last step is to modify your `src/lib/lib.rs` file: 52 | 53 | ```rust,ignore 54 | extern crate crowbook_intl_runtime; 55 | #[macro_use] mod localize_macros; 56 | ``` 57 | 58 | Once this is done, you can start replacing your calls to `format!` with calls to `lformat!`. 59 | 60 | In order to get translation, you'll need to actually translate the strings in separate 61 | files, and set your `build.rs` to load them. 62 | 63 | E.g., if you have the following code: 64 | 65 | ```rust,ignore 66 | println!("{}", lformat!("Hello, world!")); 67 | ``` 68 | 69 | and you want it translated in french, you'll have to create a `lang/fr.po` file 70 | from the `lang/default.pot` file containing: 71 | 72 | ```text 73 | msgid "Hello, world!"; 74 | msgstr "Bonjour le monde !"; 75 | ``` 76 | 77 | And load it in your `build.rs` file: 78 | 79 | ```rust,ignore 80 | let mut localizer = Localizer::new(); 81 | localizer.add_lang("fr", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/lang/fr.mp"))).unwrap(); 82 | (...) 83 | ``` 84 | 85 | Once *this* is done, you can use the `localize_macros::set_lang` function 86 | to switch the language at runtime: 87 | 88 | ```rust,ignore 89 | use crowbook_intl_runtime::set_lang; 90 | set_lang("en"); 91 | println!("{}", lformat!("Hello, world!")); // prints "Hello, world!" 92 | set_lang("fr"); 93 | println!("{}", lformat!("Hello, world!")); // prints "Bonjour le monde !" 94 | ``` 95 | 96 | ## Updating your translation 97 | 98 | When you add new strings that need to be translated (by more calls to `lformat!`), 99 | or when you change the content of existing strings, you can use [Gettext's `msgmerge` and `msgcmp`](https://www.gnu.org/software/gettext/manual/html_node/msgmerge-Invocation.html) 100 | commands to update your translation. While it is not guaranteed that the formats are 101 | strictly identical, it should work. (That is, it is a bug if it doesn't; but at this 102 | stage, this library is absolutely not guaranteed to be bug-free.) 103 | 104 | ## Known limitations and bugs 105 | 106 | * Currently, `crowbook-intl` doesn't handle correctly raw string literals in `lformat!` 107 | (they won't be translated correctly). 108 | * Multiple calls to the same string, but formatted differently (e.g. using a backslash 109 | before a newline to separate a string on multiple lines) will also cause problems. 110 | 111 | ## Warning 112 | 113 | In case the complexity of the operation didn't discourage you, I should warn you 114 | that this library is highly experimental at this time. 115 | 116 | ## License 117 | 118 | This is free software, published under the [Mozilla Public License, 119 | version 2.0](https://www.mozilla.org/en-US/MPL/2.0/). 120 | 121 | ## Documentation ## 122 | 123 | See the 124 | [documentation on docs.rs](https://docs.rs/crowbook-intl). 125 | 126 | ## ChangeLog ## 127 | 128 | See [the ChangeLog file](ChangeLog.md). 129 | 130 | ## Author ## 131 | 132 | [Élisabeth Henry](http://lise-henry.github.io/) . 133 | -------------------------------------------------------------------------------- /src/macrogen.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with 3 | // this file, You can obtain one at https://mozilla.org/MPL/2.0/. 4 | 5 | use lang::Lang; 6 | use extractor::Extractor; 7 | 8 | /// Generate the `lformat!` macro 9 | pub fn generate_lformat(langs: &mut [Lang], extractor: &Extractor) -> String { 10 | let mut arg_variant = String::new(); 11 | let mut noarg_variant = String::new(); 12 | 13 | for i in 0..langs.len() { 14 | let (curr, rest) = langs.split_at_mut(i + 1); 15 | let ref mut hash = curr[i].content; 16 | 17 | // Write keys and translations from the po files 18 | for (key, value) in hash { 19 | let b = has_arguments(key); 20 | let mut inner = String::new(); 21 | if b { 22 | inner.push_str(&format!(" \"{}\" => format!(\"{}\", $($arg)*),\n", 23 | curr[i].lang, 24 | value)); 25 | } else { 26 | inner.push_str(&format!(" \"{}\" => format!(\"{}\"),\n", 27 | curr[i].lang, 28 | value)); 29 | } 30 | 31 | for other_lang in rest.iter_mut() { 32 | let ref mut hash = other_lang.content; 33 | if let Some(value) = hash.remove(key) { 34 | if b { 35 | inner.push_str(&format!(" \"{}\" => format!(\"{}\", $($arg)*),\n", 36 | other_lang.lang, 37 | value)); 38 | } else { 39 | inner.push_str(&format!(" \"{}\" => format!(\"{}\"),\n", 40 | other_lang.lang, 41 | value)); 42 | } 43 | } 44 | } 45 | 46 | 47 | if b { 48 | inner.push_str(&format!(" _ => format!(\"{}\", $($arg)*),\n", 49 | key)); 50 | } else { 51 | inner.push_str(&format!(" _ => format!(\"{}\"),\n", 52 | key)); 53 | } 54 | 55 | let this_variant = format!(" let __guard = ::crowbook_intl_runtime::__get_lang(); 56 | match __guard.as_str() {{ 57 | {} }}", 58 | inner); 59 | 60 | if b { 61 | arg_variant.push_str(&format!(" (\"{}\", $($arg:tt)*) => ({{ 62 | {} 63 | }});\n", 64 | key, this_variant)); 65 | } else { 66 | noarg_variant.push_str(&format!(" (\"{}\") => ({{ 67 | {} 68 | }});\n", 69 | key, this_variant)); 70 | } 71 | } 72 | 73 | // Add translations from exact msg formats used in lformat! to the ones 74 | // Used in .po files (e.g. might not have the same escape codes) 75 | for (key, value) in extractor.original_strings() { 76 | if has_arguments(key) { 77 | arg_variant.push_str(&format!(" (\"{}\", $($arg:tt)*) => (lformat!(\"{}\", $($arg)*));\n", 78 | key, value)); 79 | } else { 80 | noarg_variant.push_str(&format!(" (\"{}\") => (lformat!(\"{}\"));\n", 81 | key, value)); 82 | } 83 | } 84 | } 85 | 86 | format!("/// Localized format macro (or `lformat!` in short) 87 | /// 88 | /// Should be similar to `format!`, except strings are localized. 89 | /// Generated automatically, you should not edit it. 90 | macro_rules! lformat {{ 91 | {}{} ($($arg:tt)*) => (format!($($arg)*)); 92 | }}", 93 | &arg_variant, 94 | &noarg_variant) 95 | } 96 | 97 | 98 | /// Generate the file containing the localization macros 99 | pub fn generate_macro_file(langs: &mut [Lang], extractor: &Extractor) -> String { 100 | let mut output = String::from(include_str!("../data/localize_macros.rs")); 101 | output.push_str(&generate_lformat(langs, extractor)); 102 | output 103 | } 104 | 105 | 106 | /// Returns true if s contains arguments, false else 107 | fn has_arguments(s: &str) -> bool { 108 | let chars:Vec<_> = s.chars().collect(); 109 | for i in 0..chars.len() { 110 | let c = chars[i]; 111 | if c == '{' || c == '}' { 112 | if i >= chars.len() - 1 { 113 | return true; 114 | } else { 115 | let next_c = chars[i+1]; 116 | return !(c == next_c); 117 | } 118 | } 119 | } 120 | false 121 | } 122 | 123 | #[test] 124 | fn test_arguments() { 125 | assert_eq!(has_arguments("foo bar"), false); 126 | assert_eq!(has_arguments("foo {}"), true); 127 | assert_eq!(has_arguments("foo {{bar}}"), false); 128 | } 129 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with 3 | // this file, You can obtain one at https://mozilla.org/MPL/2.0/. 4 | 5 | //! A library to localize strings, translating them according to runtime options. 6 | //! 7 | //! Basically, this library allows your project to generate a `lformat!` macro, that behaves 8 | //! similarly to `format!`, except the message string (the first argument) might get translated 9 | //! (if you can find the appropriate string for the language). 10 | //! 11 | //! # Usage 12 | //! 13 | //! First, you'll need to add the following to your `Cargo.toml` file: 14 | //! 15 | //! ```toml 16 | //! build = "build.rs" 17 | //! 18 | //! [build-dependencies] 19 | //! crowbook-intl = "0.1.0" 20 | //! 21 | //! [dependencies] 22 | //! crowbook-intl-runtime = "0.1.0" 23 | //! ``` 24 | //! 25 | //! You'll then need to create the `build.rs` file, which can look like this: 26 | //! 27 | //! ```rust,ignore 28 | //! extern crate crowbook_intl; 29 | //! use crowbook_intl::{Localizer, Extractor}; 30 | //! 31 | //! fn main() { 32 | //! // Generate a `lang/default.pot` containing strings used to call `lformat!` 33 | //! let mut extractor = Extractor::new(); 34 | //! extractor.add_messages_from_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/src")).unwrap(); 35 | //! extractor.write_pot_file(concat!(env!("CARGO_MANIFEST_DIR"), "/lang/default.pot")).unwrap(); 36 | //! 37 | //! // Generate the `localize_macros.rs` file 38 | //! let mut localizer = Localizer::new(&extractor); 39 | //! // Use env::var instead of env! to avoid problems when cross-compiling 40 | //! let dest_path = Path::new(&env::var("OUT_DIR").unwrap()) 41 | //! .join("localize_macros.rs"); 42 | //! localizer.write_macro_file(dest_path).unwrap(); 43 | //! } 44 | //! ``` 45 | //! 46 | //! This will create a `localize_macros.rs` at build time somewhere in `OUT_DIR`, containing the `lformat!` macro. 47 | //! To actually use this macro, you have to create a `src/localize_macros.rs` file that includes it: 48 | //! 49 | //! ```rust,ignore 50 | //! include!(concat!(env!("OUT_DIR"), "/localize_macros.rs")); 51 | //! ``` 52 | //! 53 | //! To use it, the last step is to modify your `src/lib/lib.rs` file: 54 | //! 55 | //! ```rust,ignore 56 | //! extern crate crowbook_intl_runtime; 57 | //! #[macro_use] mod localize_macros; 58 | //! ``` 59 | //! 60 | //! Once this is done, you can start replacing your calls to `format!` with calls to `lformat!`. 61 | //! 62 | //! In order to get translation, you'll need to actually translate the strings in separate 63 | //! files, and set your `build.rs` to load them. 64 | //! 65 | //! E.g., if you have the following code: 66 | //! 67 | //! ```rust,ignore 68 | //! println!("{}", lformat!("Hello, world!")); 69 | //! ``` 70 | //! 71 | //! and you want it translated in french, you'll have to create a `lang/fr.po` file 72 | //! from the `lang/default.pot` file containing: 73 | //! 74 | //! ```text 75 | //! msgid "Hello, world!"; 76 | //! msgstr "Bonjour le monde !"; 77 | //! ``` 78 | //! 79 | //! And load it in your `build.rs` file: 80 | //! 81 | //! ```rust,ignore 82 | //! let mut localizer = Localizer::new(); 83 | //! localizer.add_lang("fr", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/lang/fr.mp"))).unwrap(); 84 | //! (...) 85 | //! ``` 86 | //! 87 | //! Once *this* is done, you can use the `localize_macros::set_lang` function 88 | //! to switch the language at runtime: 89 | //! 90 | //! ```rust,ignore 91 | //! use crowbook_intl_runtime::set_lang; 92 | //! set_lang("en"); 93 | //! println!("{}", lformat!("Hello, world!")); // prints "Hello, world!" 94 | //! set_lang("fr"); 95 | //! println!("{}", lformat!("Hello, world!")); // prints "Bonjour le monde !" 96 | //! ``` 97 | //! 98 | //! # Updating your translation 99 | //! 100 | //! When you add new strings that need to be translated (by more calls to `lformat!`), 101 | //! or when you change the content of existing strings, you can use [Gettext's `msgmerge` and `msgcmp`](https://www.gnu.org/software/gettext/manual/html_node/msgmerge-Invocation.html) 102 | //! commands to update your translation. While it is not guaranteed that the formats are 103 | //! strictly identical, it should work. (That is, it is a bug if it doesn't; but at this 104 | //! stage, this library is absolutely not guaranteed to be bug-free.) 105 | //! 106 | //! # Known limitations and bugs 107 | //! 108 | //! * Currently, `crowbook-intl` doesn't handle correctly raw string literals in `lformat!` 109 | //! (they won't be translated correctly). 110 | //! * Multiple calls to the same string, but formatted differently (e.g. using a backslash 111 | //! before a newline to separate a string on multiple lines) will also cause problems. 112 | //! 113 | //! # Warning 114 | //! 115 | //! In case the complexity of the operation didn't discourage you, I should warn you 116 | //! that this library is highly experimental at this time. 117 | //! 118 | //! # License 119 | //! 120 | //! This is free software, published under the [Mozilla Public License, 121 | //! version 2.0](https://www.mozilla.org/en-US/MPL/2.0/). 122 | 123 | 124 | extern crate regex; 125 | #[macro_use] extern crate lazy_static; 126 | extern crate walkdir; 127 | 128 | mod common; 129 | mod macrogen; 130 | mod lang; 131 | mod error; 132 | mod localizer; 133 | mod message; 134 | mod extractor; 135 | 136 | pub use error::{Result, Error}; 137 | pub use localizer::Localizer; 138 | pub use extractor::Extractor; 139 | -------------------------------------------------------------------------------- /src/extractor.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with 3 | // this file, You can obtain one at https://mozilla.org/MPL/2.0/. 4 | 5 | use message::Message; 6 | use error::{Error, Result}; 7 | use common::{find_string, escape_string}; 8 | 9 | use std::collections::HashMap; 10 | use std::path::Path; 11 | use std::fs::File; 12 | use std::io::Read; 13 | use std::io::Write; 14 | 15 | use regex::Regex; 16 | use walkdir::WalkDir; 17 | 18 | /// Struct that extracts all messages from source code and can print them 19 | /// to a `.pot` file. 20 | /// 21 | /// This file can then be used as a starting point to begin translation. 22 | /// It should be relatively similar to `gettext` generated files. 23 | /// 24 | /// # Example 25 | /// 26 | /// ``` 27 | /// use crowbook_intl::Extractor; 28 | /// let mut extractor = Extractor::new(); 29 | /// extractor.add_messages_from_dir("src/").unwrap(); 30 | /// println!("{}", extractor.generate_pot_file()); 31 | /// ``` 32 | /// 33 | /// # Note 34 | /// 35 | /// This struct only add messages that are considered as needing localization, 36 | /// that is, the first argument of calls so `lformat!` macro. 37 | #[derive(Debug, Clone)] 38 | pub struct Extractor { 39 | messages: HashMap, 40 | // Matches the format string (as used by `lformat!` and the actual escaped string 41 | // given to potfile 42 | orig_strings: HashMap, 43 | } 44 | 45 | impl Extractor { 46 | /// Create a new, empty extractor 47 | pub fn new() -> Extractor { 48 | Extractor { 49 | messages: HashMap::new(), 50 | orig_strings: HashMap::new(), 51 | } 52 | } 53 | 54 | /// Returns a hashmap mapping the original strings (as used by `lformat!`) 55 | /// to escaped strings. Only contains strings that are different and 56 | /// must thus be handled. 57 | pub fn original_strings<'a>(&'a self) -> &'a HashMap { 58 | &self.orig_strings 59 | } 60 | 61 | /// Add all the messages contained in a source file 62 | pub fn add_messages_from_file>(&mut self, file: P) -> Result<()> { 63 | lazy_static! { 64 | static ref REMOVE_COMMS: Regex = Regex::new(r#"//[^\n]*"#).unwrap(); 65 | static ref FIND_MSGS: Regex = Regex::new(r#"lformat!\("#).unwrap(); 66 | } 67 | 68 | let filename = format!("{}", file.as_ref().display()); 69 | let mut f = try!(File::open(file) 70 | .map_err(|e| Error::parse(format!("could not open file {}: {}", 71 | &filename, 72 | e)))); 73 | let mut content = String::new(); 74 | try!(f.read_to_string(&mut content) 75 | .map_err(|e| Error::parse(format!("could not read file {}: {}", 76 | &filename, 77 | e)))); 78 | content = REMOVE_COMMS.replace_all(&content, "").into_owned(); 79 | 80 | for caps in FIND_MSGS.captures_iter(&content) { 81 | let pos = caps.get(0).unwrap().end(); 82 | let line = 1 + &content[..pos].bytes().filter(|b| b == &b'\n').count(); 83 | 84 | let bytes = content[pos..].as_bytes(); 85 | let orig_msg: String = try!(find_string(bytes) 86 | .map_err(|_| Error::parse(format!("{}:{}: could not parse as string", 87 | &filename, 88 | line)))); 89 | let msg = escape_string(orig_msg.as_str()).into_owned(); 90 | if msg != orig_msg { 91 | self.orig_strings.insert(orig_msg, msg.clone()); 92 | } 93 | 94 | if self.messages.contains_key(msg.as_str()) { 95 | self.messages.get_mut(&msg).unwrap().add_source(filename.as_str(), line); 96 | } else { 97 | let mut message = Message::new(msg.as_str()); 98 | message.add_source(filename.as_str(), line); 99 | self.messages.insert(msg, message); 100 | } 101 | } 102 | 103 | Ok(()) 104 | } 105 | 106 | /// Add messages from all `.rs` files contained in a directory 107 | /// (walks through subdirectories) 108 | pub fn add_messages_from_dir>(&mut self, dir: P) -> Result<()> { 109 | let filtered = WalkDir::new(dir) 110 | .into_iter() 111 | .filter_map(|e| e.ok()) 112 | .map(|e| e.path() 113 | .to_string_lossy() 114 | .into_owned()) 115 | .filter(|s| s.ends_with(".rs")); 116 | for filename in filtered { 117 | try!(self.add_messages_from_file(&filename)); 118 | } 119 | 120 | Ok(()) 121 | } 122 | 123 | /// Generate a pot-like file from the strings extracted from all files (if any) 124 | pub fn generate_pot_file(&self) -> String { 125 | let mut output = String::from(POT_HEADER); 126 | let mut values = self.messages 127 | .values() 128 | .collect::>(); 129 | values.sort(); 130 | for value in values { 131 | output.push_str(&format!("{}", value)); 132 | } 133 | output 134 | } 135 | 136 | /// Write a pot-like file to specified location 137 | pub fn write_pot_file(&mut self, file: &str) -> Result<()> { 138 | let mut f = try!(File::create(file).map_err(|e| Error::new(format!("Could not create file {}: {}", 139 | file, e)))); 140 | let content = self.generate_pot_file(); 141 | try!(f.write_all(content.as_bytes()) 142 | .map_err(|e| Error::new(format!("Could not write to file {}: {}", 143 | file, e)))); 144 | Ok(()) 145 | } 146 | } 147 | 148 | const POT_HEADER: &'static str = r#"# SOME DESCRIPTIVE TITLE 149 | # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER 150 | # LICENSE 151 | # AUTHOR , YEAR. 152 | # 153 | #, fuzzy 154 | msgid "" 155 | msgstr "" 156 | "Content-Type: text/plain; charset=UTF-8\n" 157 | 158 | "#; 159 | -------------------------------------------------------------------------------- /src/lang.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with 3 | // this file, You can obtain one at https://mozilla.org/MPL/2.0/. 4 | 5 | use error::{Error,Result}; 6 | use common::find_string; 7 | 8 | use std::collections::HashMap; 9 | 10 | /// Struct used to store localization information for a language. 11 | #[derive(Debug, Clone)] 12 | pub struct Lang { 13 | /// The lang code 14 | pub lang: String, 15 | /// The content of localization 16 | pub content: HashMap, 17 | } 18 | 19 | impl Lang { 20 | /// Create a new empty Lang with no content 21 | pub fn new(lang: S) -> Lang 22 | where S: Into { 23 | Lang { 24 | lang: lang.into(), 25 | content: HashMap::new(), 26 | } 27 | } 28 | 29 | /// Create a new Lang from a string 30 | /// 31 | /// This string should vaguely follow .po/.mo files: it can contain 32 | /// comments starting by a `#`, and an entry should be of the form: 33 | /// 34 | /// ```text, no_run 35 | /// msgid "Initial string" 36 | /// msgstr "Translated string" 37 | /// ``` 38 | pub fn new_from_str(lang: S, s: &str) -> Result 39 | where S: Into { 40 | let mut lang = Self::new(lang); 41 | let lines:Vec<_> = s.lines() 42 | .map(|s| s.trim()) 43 | .collect(); 44 | let mut i = 0; 45 | while i < lines.len() { 46 | if lines[i].is_empty() || lines[i].starts_with("#") { 47 | // empty line or comment, ignore 48 | i += 1; 49 | continue; 50 | } 51 | if let Some(begin) = lines[i].find("msgid") { 52 | let end = begin + "msgid".len(); 53 | let mut s = &lines[i][end..]; 54 | let mut key = String::new(); 55 | loop { 56 | key.push_str(&try!(find_string(s.as_bytes()).map_err(|e| { 57 | Error::parse(format!("initializing lang '{}' at line {}, could not parse {} as a String: {}", 58 | &lang.lang, i, s, e)) 59 | }))); 60 | if i >= lines.len() - 1 || lines[i+1].starts_with("msgstr") { 61 | break; 62 | } else if lines[i+1].starts_with('"') { 63 | i = i + 1; 64 | s = lines[i]; 65 | } else { 66 | return Err(Error::parse(format!("initializing lang '{}' at line {}, found 'msgid' without matching 'msgstr on next line", 67 | &lang.lang, 68 | i))); 69 | } 70 | } 71 | i += 1; 72 | if let Some(begin) = lines[i].find("msgstr") { 73 | let end = begin + "msgstr".len(); 74 | let mut s = &lines[i][end..]; 75 | let mut value = String::new(); 76 | loop { 77 | value.push_str(&try!(find_string(s.as_bytes()).map_err(|e| { 78 | Error::parse(format!("initializing lang '{}' at line {}, could not parse {} as a String: {}", 79 | &lang.lang, 80 | i, 81 | s, 82 | e)) 83 | }))); 84 | if i >= lines.len() - 1 || lines[i+1].is_empty() { 85 | break; 86 | } else { 87 | i = i + 1; 88 | s = lines[i]; 89 | } 90 | } 91 | if !key.is_empty() && !value.is_empty() { 92 | lang.insert(key, value); 93 | } 94 | } else { 95 | unreachable!() 96 | } 97 | i += 1; 98 | } else { 99 | return Err(Error::parse(format!("initializing lang '{}' at line {}, unexected input: '{}'", 100 | &lang.lang, i, lines[i]))); 101 | } 102 | } 103 | Ok(lang) 104 | } 105 | 106 | /// Insert a (key, value) pair in the HashMap containing localization strings 107 | /// 108 | /// # Arguments: 109 | /// * `key`: the string in default language 110 | /// * `value`: the translation in this language 111 | pub fn insert(&mut self, key: S1, value: S2) 112 | where S1: Into, 113 | S2: Into { 114 | self.content.insert(key.into(), value.into()); 115 | } 116 | } 117 | 118 | 119 | 120 | #[test] 121 | fn lang_new_valid_1() { 122 | let s = r#" 123 | # Some comment 124 | msgid "Some string" 125 | msgstr "Une chaîne" 126 | 127 | # Other comment 128 | msgid "Other string" 129 | msgstr "Autre chaîne" 130 | "#; 131 | Lang::new_from_str("fr", s).unwrap(); 132 | } 133 | 134 | 135 | #[test] 136 | fn lang_new_invalid_1() { 137 | let s = r#" 138 | msgstr "Msgstr first" 139 | msgid "Some string" 140 | msgstr "Une chaîne" 141 | 142 | # Other comment 143 | msgid "Other string" 144 | msgstr "Autre chaîne" 145 | "#; 146 | let lang = Lang::new_from_str("fr", s); 147 | assert!(lang.is_err()); 148 | } 149 | 150 | #[test] 151 | fn lang_new_invalid_2() { 152 | let s = r#" 153 | msgid "Some string" 154 | msgid "Two consecutive msgid without msgstr" 155 | 156 | # Other comment 157 | msgid "Other string" 158 | msgstr "Autre chaîne" 159 | "#; 160 | let lang = Lang::new_from_str("fr", s); 161 | assert!(lang.is_err()); 162 | } 163 | 164 | #[test] 165 | fn lang_multiline_1() { 166 | let s = r#" 167 | msgid "foo" 168 | msgstr "" 169 | "foo" 170 | "bar" 171 | "#; 172 | let lang = Lang::new_from_str("fr", s).unwrap(); 173 | assert_eq!(lang.content.get("foo").unwrap(), "foobar"); 174 | } 175 | 176 | #[test] 177 | fn lang_multiline_2() { 178 | let s = r#" 179 | msgid "foo" 180 | "bar" 181 | msgstr "" 182 | "foo" 183 | "bar" 184 | "#; 185 | let lang = Lang::new_from_str("fr", s).unwrap(); 186 | assert_eq!(lang.content.get("foobar").unwrap(), "foobar"); 187 | } 188 | 189 | #[test] 190 | fn lang_empty() { 191 | let s = r#" 192 | msgid "foo" 193 | msgstr "" 194 | 195 | msgid "" 196 | msgstr "bar" 197 | "#; 198 | let lang = Lang::new_from_str("fr", s).unwrap(); 199 | assert_eq!(lang.content.len(), 0); 200 | } 201 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | --------------------------------------------------------------------------------