Skip to content

Commit

Permalink
Added t!() macro
Browse files Browse the repository at this point in the history
  • Loading branch information
ElBe-Plaq committed Oct 6, 2023
1 parent a8fd021 commit 163e31b
Show file tree
Hide file tree
Showing 9 changed files with 154 additions and 31 deletions.
18 changes: 3 additions & 15 deletions .github/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,59 +39,47 @@ To use localizer-rs, you need a directory (eg. `translations`) with your transla
1. Import the localizer-rs crate:

```rust,ignore
use localizer_rs;
```
2. Create a new config object:
```rust,ignore
let config = localizer_rs::Config::new("DIRECTORY NAME", "LANGUAGE NAME");
let config = localizer_rs::Config::new("translations", "en");
```
3. Translate your text:
```rust,ignore
config.t("key", vec!["placeholder", "value"]);
localizer_rs::t!(config, "key", "placeholder" ="value");
```
## Example
With the following `en.json` file.
```json
{
"error": "{{color.red}}{{bold}}Error:{{end}} Something went wrong: {{details}}."
}
```

And the following rust code.

```rust,ignore
use localizer_rs;
fn main() {
let config: localizer_rs::Config = localizer_rs::Config::new("translations", "en");
println!("{:}", config.t("error", vec![("details", "Path not found")]));
println!("{:}", localizer_rs::t!(config, "error", "details" = "Path not found"));
}
```

You will get the following output:

```bash

Error: Something went wrong: Path not found.

```

Where `Error:` is red and bold.
Expand Down
1 change: 1 addition & 0 deletions .github/SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
| `v1.0.0` | :white_check_mark: |
| `v1.1.0` | :white_check_mark: |
| `v1.1.1` | :white_check_mark: |
| `v1.2.0` | :white_check_mark: |

## Reporting a Vulnerability

Expand Down
3 changes: 3 additions & 0 deletions .github/errors.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# errors module

Module for dealing with errors.
1 change: 1 addition & 0 deletions .github/workflows/codecov_workflow.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ on:

jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Upload coverage reports to Codecov
uses: codecov/codecov-action@v3
Expand Down
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
name = "localizer-rs"
description = "Localizer helps localize (translate) your rust applications using json files."
version = "1.1.1"
version = "1.2.0"
authors = [
"ElBe-Plaq <elbe.dev.plaq@gmail.com>"
]
Expand Down
9 changes: 5 additions & 4 deletions examples/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,16 @@ fn main() {

println!(
"{:}",
config.t(
localizer_rs::t!(
config,
"error",
vec![("details", "Something went wrong when trying to do stuff")]
"details" = "Something went wrong when trying to do stuff"
)
);
println!(
"{:}",
config.t("success", vec![("balance", "$10"), ("user", "John Doe")])
localizer_rs::t!(config, "success", "balance" = "$10", "user" = "John Doe")
);

println!("{:}", config.t("all", vec![]));
println!("{:}", localizer_rs::t!(config, "all"));
}
25 changes: 25 additions & 0 deletions src/errors.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#![doc = include_str!("../.github/errors.md")]
// localizer-rs errors
// Version: 1.1.1

Expand Down Expand Up @@ -66,7 +67,31 @@ pub struct Error {
pub exit_code: i32,
}

/// Display implementation for the error object.
impl fmt::Display for Error {
/// Format implementation for the error object.
///
/// # Parameters
///
/// - `self`: The error object.
/// - `f`: The [`fmt::Formatter`] to use.
///
/// # Returns
///
/// A [`fmt::Result`] containing the formatted error message.
///
/// # Examples
///
/// ```rust
/// # use localizer_rs;
/// # let error = localizer_rs::errors::Error::new("name", "description", 1);
/// println!("{}", error);
/// ```
///
/// # See also
///
/// - [`fmt::Display`]
/// - [`Error`]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "\x1b[31;1m{}\x1b[0m: {}", self.name, self.description)
}
Expand Down
100 changes: 90 additions & 10 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#![doc = include_str!("../.github/README.md")]
// localizer-rs
// Version: 1.1.1
// Version: 1.2.0

// Copyright (c) 2023-present ElBe Development.

Expand Down Expand Up @@ -159,8 +159,7 @@ impl Config {
}
}
Err(_error) => {
let error: errors::Error =
errors::Error::new("OS Error", "Could not open path", 2);
let error: errors::Error = errors::Error::new("OS Error", "Could not open path", 2);
error.raise(format!("Path: {:?}\nDetails: {}", str_path, _error).as_str());
}
}
Expand Down Expand Up @@ -226,15 +225,49 @@ impl Config {
///
/// # See also
///
/// - [`t!()`]
/// - [`Config`]
pub fn t(&self, key: &str, arguments: Vec<(&str, &str)>) -> String {
return self.translate::<serde_json::Value>(key, arguments);
return self.translate(key, arguments);
}

fn translate<T>(&self, key: &str, mut arguments: Vec<(&str, &str)>) -> String
where
T: serde::Serialize + for<'de> serde::Deserialize<'de>,
{
/// Translates the specified key in the language specified in the config.
///
/// # Parameters
///
/// - `self`: The config object.
/// - `key`: The key to translate to.
/// - `arguments`: The arguments to replace.
///
/// # Returns
///
/// A `String` containing the translated value.
///
/// # Raises
///
/// This method throws an exception and exits if
///
/// - The translation file could not be found
/// - The translation file could not be opened
/// - The translation file could not be parsed
/// - The parsed json could not be converted to a json value
/// - The converted json could not be indexed
///
/// # Examples
///
/// ```rust
/// # use localizer_rs;
/// # let config: localizer_rs::Config = localizer_rs::Config::new("examples/translations", "en");
/// config.translate("test", vec![]);
/// ```
///
/// # See also
///
/// - [`t!()`]
/// - [`Config`]
/// - [`Config::t()`]
/// - [`serde_json`]
pub fn translate(&self, key: &str, mut arguments: Vec<(&str, &str)>) -> String {
let mut colors: Vec<(&str, &str)> = vec![
// Formatting codes
("end", "\x1b[0m"),
Expand Down Expand Up @@ -305,8 +338,8 @@ impl Config {
};
let reader: BufReader<File> = BufReader::new(file);

let json: serde_json::Value = match serde_json::to_value::<T>(
match serde_json::from_reader::<BufReader<File>, T>(reader) {
let json: serde_json::Value = match serde_json::to_value::<serde_json::Value>(
match serde_json::from_reader::<BufReader<File>, serde_json::Value>(reader) {
Ok(value) => value,
Err(_error) => {
let error: errors::Error = errors::Error::new(
Expand Down Expand Up @@ -366,3 +399,50 @@ impl Config {
return result;
}
}


/// Translates the specified key in the language specified in the config.
///
/// # Parameters
///
/// - `config`: The config object.
/// - `key`: The key to translate to.
/// - `arguments`: Optional parameter. The arguments to replace. Has to be of type `"name" = "value"`.
///
/// # Returns
///
/// A `String` containing the translated value.
///
/// # Examples
///
/// ```rust
/// # use localizer_rs;
/// # let config: localizer_rs::Config = localizer_rs::Config::new("examples/translations", "en");
/// localizer_rs::t!(config, "test");
/// localizer_rs::t!(config, "test", "variable" = "content");
/// ```
///
/// # See also
///
/// - [`Config`]
/// - [`Config::t()`]
#[macro_export]
macro_rules! t {
($config:expr, $key:expr) => {
{
$config.t($key, vec![])
}
};

($config:expr, $key:expr, $($argument_name:literal = $argument_value:literal),* $(,)?) => {
{
let mut arguments: Vec<(&str, &str)> = vec![];

$(
arguments.push(($argument_name, $argument_value));
)*

$config.t($key, arguments)
}
};
}
26 changes: 25 additions & 1 deletion tests/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// localizer-rs tests
// Version: 1.1.1
// Version: 1.2.0

// Copyright (c) 2023-present ElBe Development.

Expand Down Expand Up @@ -80,6 +80,18 @@ mod tests {

#[test]
fn test_translate() {
let config: localizer_rs::Config = localizer_rs::Config::new("examples/translations", "en");
let translation: String =
config.translate("error", vec![("details", "Something went wrong")]);

assert_eq!(
translation.as_str(),
"\x1b[31m\x1b[1mError:\x1b[0m Something went wrong"
);
}

#[test]
fn test_translate_t() {
let config: localizer_rs::Config = localizer_rs::Config::new("examples/translations", "en");
let translation: String = config.t("error", vec![("details", "Something went wrong")]);

Expand All @@ -88,4 +100,16 @@ mod tests {
"\x1b[31m\x1b[1mError:\x1b[0m Something went wrong"
);
}

#[test]
fn test_translate_macro() {
let config: localizer_rs::Config = localizer_rs::Config::new("examples/translations", "en");
let translation: String =
localizer_rs::t!(config, "error", "details" = "Something went wrong");

assert_eq!(
translation.as_str(),
"\x1b[31m\x1b[1mError:\x1b[0m Something went wrong"
);
}
}

0 comments on commit 163e31b

Please sign in to comment.