Skip to content

Commit 163e31b

Browse files
committed
Added t!() macro
1 parent a8fd021 commit 163e31b

File tree

9 files changed

+154
-31
lines changed

9 files changed

+154
-31
lines changed

.github/README.md

Lines changed: 3 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -39,59 +39,47 @@ To use localizer-rs, you need a directory (eg. `translations`) with your transla
3939
1. Import the localizer-rs crate:
4040

4141
```rust,ignore
42-
4342
use localizer_rs;
44-
4543
```
4644
4745
2. Create a new config object:
4846
4947
```rust,ignore
50-
51-
let config = localizer_rs::Config::new("DIRECTORY NAME", "LANGUAGE NAME");
52-
48+
let config = localizer_rs::Config::new("translations", "en");
5349
```
5450
5551
3. Translate your text:
5652
5753
```rust,ignore
58-
59-
config.t("key", vec!["placeholder", "value"]);
60-
54+
localizer_rs::t!(config, "key", "placeholder" ="value");
6155
```
6256
6357
## Example
6458
6559
With the following `en.json` file.
6660
6761
```json
68-
6962
{
7063
"error": "{{color.red}}{{bold}}Error:{{end}} Something went wrong: {{details}}."
7164
}
72-
7365
```
7466

7567
And the following rust code.
7668

7769
```rust,ignore
78-
7970
use localizer_rs;
8071
8172
fn main() {
8273
let config: localizer_rs::Config = localizer_rs::Config::new("translations", "en");
8374
84-
println!("{:}", config.t("error", vec![("details", "Path not found")]));
75+
println!("{:}", localizer_rs::t!(config, "error", "details" = "Path not found"));
8576
}
86-
8777
```
8878

8979
You will get the following output:
9080

9181
```bash
92-
9382
Error: Something went wrong: Path not found.
94-
9583
```
9684

9785
Where `Error:` is red and bold.

.github/SECURITY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
| `v1.0.0` | :white_check_mark: |
88
| `v1.1.0` | :white_check_mark: |
99
| `v1.1.1` | :white_check_mark: |
10+
| `v1.2.0` | :white_check_mark: |
1011

1112
## Reporting a Vulnerability
1213

.github/errors.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# errors module
2+
3+
Module for dealing with errors.

.github/workflows/codecov_workflow.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ on:
66

77
jobs:
88
build:
9+
runs-on: ubuntu-latest
910
steps:
1011
- name: Upload coverage reports to Codecov
1112
uses: codecov/codecov-action@v3

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
[package]
22
name = "localizer-rs"
33
description = "Localizer helps localize (translate) your rust applications using json files."
4-
version = "1.1.1"
4+
version = "1.2.0"
55
authors = [
66
"ElBe-Plaq <[email protected]>"
77
]

examples/main.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,16 @@ fn main() {
55

66
println!(
77
"{:}",
8-
config.t(
8+
localizer_rs::t!(
9+
config,
910
"error",
10-
vec![("details", "Something went wrong when trying to do stuff")]
11+
"details" = "Something went wrong when trying to do stuff"
1112
)
1213
);
1314
println!(
1415
"{:}",
15-
config.t("success", vec![("balance", "$10"), ("user", "John Doe")])
16+
localizer_rs::t!(config, "success", "balance" = "$10", "user" = "John Doe")
1617
);
1718

18-
println!("{:}", config.t("all", vec![]));
19+
println!("{:}", localizer_rs::t!(config, "all"));
1920
}

src/errors.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
#![doc = include_str!("../.github/errors.md")]
12
// localizer-rs errors
23
// Version: 1.1.1
34

@@ -66,7 +67,31 @@ pub struct Error {
6667
pub exit_code: i32,
6768
}
6869

70+
/// Display implementation for the error object.
6971
impl fmt::Display for Error {
72+
/// Format implementation for the error object.
73+
///
74+
/// # Parameters
75+
///
76+
/// - `self`: The error object.
77+
/// - `f`: The [`fmt::Formatter`] to use.
78+
///
79+
/// # Returns
80+
///
81+
/// A [`fmt::Result`] containing the formatted error message.
82+
///
83+
/// # Examples
84+
///
85+
/// ```rust
86+
/// # use localizer_rs;
87+
/// # let error = localizer_rs::errors::Error::new("name", "description", 1);
88+
/// println!("{}", error);
89+
/// ```
90+
///
91+
/// # See also
92+
///
93+
/// - [`fmt::Display`]
94+
/// - [`Error`]
7095
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7196
write!(f, "\x1b[31;1m{}\x1b[0m: {}", self.name, self.description)
7297
}

src/lib.rs

Lines changed: 90 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
#![doc = include_str!("../.github/README.md")]
22
// localizer-rs
3-
// Version: 1.1.1
3+
// Version: 1.2.0
44

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

@@ -159,8 +159,7 @@ impl Config {
159159
}
160160
}
161161
Err(_error) => {
162-
let error: errors::Error =
163-
errors::Error::new("OS Error", "Could not open path", 2);
162+
let error: errors::Error = errors::Error::new("OS Error", "Could not open path", 2);
164163
error.raise(format!("Path: {:?}\nDetails: {}", str_path, _error).as_str());
165164
}
166165
}
@@ -226,15 +225,49 @@ impl Config {
226225
///
227226
/// # See also
228227
///
228+
/// - [`t!()`]
229229
/// - [`Config`]
230230
pub fn t(&self, key: &str, arguments: Vec<(&str, &str)>) -> String {
231-
return self.translate::<serde_json::Value>(key, arguments);
231+
return self.translate(key, arguments);
232232
}
233233

234-
fn translate<T>(&self, key: &str, mut arguments: Vec<(&str, &str)>) -> String
235-
where
236-
T: serde::Serialize + for<'de> serde::Deserialize<'de>,
237-
{
234+
/// Translates the specified key in the language specified in the config.
235+
///
236+
/// # Parameters
237+
///
238+
/// - `self`: The config object.
239+
/// - `key`: The key to translate to.
240+
/// - `arguments`: The arguments to replace.
241+
///
242+
/// # Returns
243+
///
244+
/// A `String` containing the translated value.
245+
///
246+
/// # Raises
247+
///
248+
/// This method throws an exception and exits if
249+
///
250+
/// - The translation file could not be found
251+
/// - The translation file could not be opened
252+
/// - The translation file could not be parsed
253+
/// - The parsed json could not be converted to a json value
254+
/// - The converted json could not be indexed
255+
///
256+
/// # Examples
257+
///
258+
/// ```rust
259+
/// # use localizer_rs;
260+
/// # let config: localizer_rs::Config = localizer_rs::Config::new("examples/translations", "en");
261+
/// config.translate("test", vec![]);
262+
/// ```
263+
///
264+
/// # See also
265+
///
266+
/// - [`t!()`]
267+
/// - [`Config`]
268+
/// - [`Config::t()`]
269+
/// - [`serde_json`]
270+
pub fn translate(&self, key: &str, mut arguments: Vec<(&str, &str)>) -> String {
238271
let mut colors: Vec<(&str, &str)> = vec![
239272
// Formatting codes
240273
("end", "\x1b[0m"),
@@ -305,8 +338,8 @@ impl Config {
305338
};
306339
let reader: BufReader<File> = BufReader::new(file);
307340

308-
let json: serde_json::Value = match serde_json::to_value::<T>(
309-
match serde_json::from_reader::<BufReader<File>, T>(reader) {
341+
let json: serde_json::Value = match serde_json::to_value::<serde_json::Value>(
342+
match serde_json::from_reader::<BufReader<File>, serde_json::Value>(reader) {
310343
Ok(value) => value,
311344
Err(_error) => {
312345
let error: errors::Error = errors::Error::new(
@@ -366,3 +399,50 @@ impl Config {
366399
return result;
367400
}
368401
}
402+
403+
404+
/// Translates the specified key in the language specified in the config.
405+
///
406+
/// # Parameters
407+
///
408+
/// - `config`: The config object.
409+
/// - `key`: The key to translate to.
410+
/// - `arguments`: Optional parameter. The arguments to replace. Has to be of type `"name" = "value"`.
411+
///
412+
/// # Returns
413+
///
414+
/// A `String` containing the translated value.
415+
///
416+
/// # Examples
417+
///
418+
/// ```rust
419+
/// # use localizer_rs;
420+
/// # let config: localizer_rs::Config = localizer_rs::Config::new("examples/translations", "en");
421+
/// localizer_rs::t!(config, "test");
422+
/// localizer_rs::t!(config, "test", "variable" = "content");
423+
/// ```
424+
///
425+
/// # See also
426+
///
427+
/// - [`Config`]
428+
/// - [`Config::t()`]
429+
#[macro_export]
430+
macro_rules! t {
431+
($config:expr, $key:expr) => {
432+
{
433+
$config.t($key, vec![])
434+
}
435+
};
436+
437+
($config:expr, $key:expr, $($argument_name:literal = $argument_value:literal),* $(,)?) => {
438+
{
439+
let mut arguments: Vec<(&str, &str)> = vec![];
440+
441+
$(
442+
arguments.push(($argument_name, $argument_value));
443+
)*
444+
445+
$config.t($key, arguments)
446+
}
447+
};
448+
}

tests/lib.rs

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// localizer-rs tests
2-
// Version: 1.1.1
2+
// Version: 1.2.0
33

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

@@ -80,6 +80,18 @@ mod tests {
8080

8181
#[test]
8282
fn test_translate() {
83+
let config: localizer_rs::Config = localizer_rs::Config::new("examples/translations", "en");
84+
let translation: String =
85+
config.translate("error", vec![("details", "Something went wrong")]);
86+
87+
assert_eq!(
88+
translation.as_str(),
89+
"\x1b[31m\x1b[1mError:\x1b[0m Something went wrong"
90+
);
91+
}
92+
93+
#[test]
94+
fn test_translate_t() {
8395
let config: localizer_rs::Config = localizer_rs::Config::new("examples/translations", "en");
8496
let translation: String = config.t("error", vec![("details", "Something went wrong")]);
8597

@@ -88,4 +100,16 @@ mod tests {
88100
"\x1b[31m\x1b[1mError:\x1b[0m Something went wrong"
89101
);
90102
}
103+
104+
#[test]
105+
fn test_translate_macro() {
106+
let config: localizer_rs::Config = localizer_rs::Config::new("examples/translations", "en");
107+
let translation: String =
108+
localizer_rs::t!(config, "error", "details" = "Something went wrong");
109+
110+
assert_eq!(
111+
translation.as_str(),
112+
"\x1b[31m\x1b[1mError:\x1b[0m Something went wrong"
113+
);
114+
}
91115
}

0 commit comments

Comments
 (0)