Skip to content

Commit

Permalink
fix format date based on users locale (#11908)
Browse files Browse the repository at this point in the history
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->
# Description
Hi, 

Fixes #10838, where before the `date` would be formatted incorrectly,
and was not picking `LC_TIME` for time formatting, but it picked the
first locale returned by the `sys-locale` crate instead. Now it will
format time based on `LC_TIME`. For example,

```
// my locale `nl_NL.UTF-8`
❯ date now | format date '%x %X'
20-02-24 17:17:12

$env.LC_TIME = "en_US.UTF-8"

❯ date now | format date '%x %X'
02/20/2024 05:16:28 PM
```
Note that I also changed the `default_env.nu` as otherwise the Time will
show AM/PM twice. Also reason for the `chrono` update is because this
relies on a fix to upstream repo, which i initially submitted an
[issue](chronotope/chrono#1349 (comment))

<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.

Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->

# Tests + Formatting

Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- [X] `cargo fmt --all -- --check` to check standard code formatting
(`cargo fmt --all` applies these changes)
- [X] `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used`
to check that you're using the standard code style
- [X] `cargo test --workspace` to check that all tests pass (on Windows
make sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- [X] `cargo run -- -c "use std testing; testing run-tests --path
crates/nu-std"` to run the tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```


# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->
  • Loading branch information
dmatos2012 committed Feb 20, 2024
1 parent 7c1eb6b commit 123bf2d
Show file tree
Hide file tree
Showing 7 changed files with 51 additions and 24 deletions.
8 changes: 4 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion crates/nu-command/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ base64 = "0.21"
byteorder = "1.5"
bytesize = "1.3"
calamine = "0.24.0"
chrono = { version = "0.4", features = ["std", "unstable-locales"], default-features = false }
chrono = { version = "0.4.34", features = ["std", "unstable-locales"], default-features = false }
chrono-humanize = "0.2.3"
chrono-tz = "0.8"
crossterm = "0.27"
Expand Down
20 changes: 11 additions & 9 deletions crates/nu-command/src/strings/format/date.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use nu_protocol::{
Category, Example, PipelineData, ShellError, Signature, Span, Spanned, SyntaxShape, Type,
Value,
};
use nu_utils::locale::get_system_locale_string;
use nu_utils::locale::{get_system_locale_string, LOCALE_OVERRIDE_ENV_VAR};
use std::fmt::{Display, Write};

use crate::{generate_strftime_list, parse_date_from_string};
Expand Down Expand Up @@ -118,21 +118,23 @@ where
Tz::Offset: Display,
{
let mut formatter_buf = String::new();
// These are already in locale format, so we don't need to localize them
let format = if ["%x", "%X", "%r"]
.iter()
.any(|item| formatter.contains(item))
// Format using locale LC_TIME
let locale = if let Ok(l) =
std::env::var(LOCALE_OVERRIDE_ENV_VAR).or_else(|_| std::env::var("LC_TIME"))
{
date_time.format(formatter)
let locale_str = l.split('.').next().unwrap_or("en_US");
locale_str.try_into().unwrap_or(Locale::en_US)
} else {
let locale: Locale = get_system_locale_string()
// LC_ALL > LC_CTYPE > LANG
// Not locale present, default to en_US
get_system_locale_string()
.map(|l| l.replace('-', "_")) // `chrono::Locale` needs something like `xx_xx`, rather than `xx-xx`
.unwrap_or_else(|| String::from("en_US"))
.as_str()
.try_into()
.unwrap_or(Locale::en_US);
date_time.format_localized(formatter, locale)
.unwrap_or(Locale::en_US)
};
let format = date_time.format_localized(formatter, locale);

match formatter_buf.write_fmt(format_args!("{format}")) {
Ok(_) => Value::string(formatter_buf, span),
Expand Down
23 changes: 23 additions & 0 deletions crates/nu-command/tests/commands/date/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,26 @@ fn locale_format_respect_different_locale() {
);
assert!(actual.out.contains("ven. 22 oct. 2021 20:00:12 +01:00"));
}

#[test]
fn locale_with_different_format_specifiers() {
let actual = nu!(
locale: "en_US",
pipeline(
r#"
"Thu, 26 Oct 2023 22:52:14 +0200" | format date "%x %X"
"#
)
);
assert!(actual.out.contains("10/26/2023 10:52:14 PM"));

let actual = nu!(
locale: "nl_NL",
pipeline(
r#"
"Thu, 26 Oct 2023 22:52:14 +0200" | format date "%x %X"
"#
)
);
assert!(actual.out.contains("26-10-23 22:52:14"));
}
2 changes: 1 addition & 1 deletion crates/nu-protocol/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ nu-path = { path = "../nu-path", version = "0.90.2" }
nu-system = { path = "../nu-system", version = "0.90.2" }

byte-unit = { version = "5.1", features = [ "serde" ] }
chrono = { version = "0.4", features = [ "serde", "std", "unstable-locales" ], default-features = false }
chrono = { version = "0.4.34", features = [ "serde", "std", "unstable-locales" ], default-features = false }
chrono-humanize = "0.2"
fancy-regex = "0.13"
indexmap = "2.2"
Expand Down
18 changes: 10 additions & 8 deletions crates/nu-protocol/src/value/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ pub use custom_value::CustomValue;
use fancy_regex::Regex;
pub use from_value::FromValue;
pub use lazy_record::LazyRecord;
use nu_utils::locale::LOCALE_OVERRIDE_ENV_VAR;
use nu_utils::{
contains_emoji, get_system_locale, locale::get_system_locale_string, IgnoreCaseExt,
};
Expand All @@ -29,6 +30,7 @@ pub use range::*;
pub use record::Record;
use serde::{Deserialize, Serialize};
use std::fmt::Write;

use std::{
borrow::Cow,
fmt::{Display, Formatter, Result as FmtResult},
Expand Down Expand Up @@ -844,21 +846,21 @@ impl Value {
Tz::Offset: Display,
{
let mut formatter_buf = String::new();
// These are already in locale format, so we don't need to localize them
let format = if ["%x", "%X", "%r"]
.iter()
.any(|item| formatter.contains(item))
let locale = if let Ok(l) =
std::env::var(LOCALE_OVERRIDE_ENV_VAR).or_else(|_| std::env::var("LC_TIME"))
{
date_time.format(formatter)
let locale_str = l.split('.').next().unwrap_or("en_US");
locale_str.try_into().unwrap_or(Locale::en_US)
} else {
let locale: Locale = get_system_locale_string()
// LC_ALL > LC_CTYPE > LANG else en_US
get_system_locale_string()
.map(|l| l.replace('-', "_")) // `chrono::Locale` needs something like `xx_xx`, rather than `xx-xx`
.unwrap_or_else(|| String::from("en_US"))
.as_str()
.try_into()
.unwrap_or(Locale::en_US);
date_time.format_localized(formatter, locale)
.unwrap_or(Locale::en_US)
};
let format = date_time.format_localized(formatter, locale);

match formatter_buf.write_fmt(format_args!("{format}")) {
Ok(_) => (),
Expand Down
2 changes: 1 addition & 1 deletion crates/nu-utils/src/sample_config/default_env.nu
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def create_right_prompt [] {
let time_segment = ([
(ansi reset)
(ansi magenta)
(date now | format date '%x %X %p') # try to respect user's locale
(date now | format date '%x %X') # try to respect user's locale
] | str join | str replace --regex --all "([/:])" $"(ansi green)${1}(ansi magenta)" |
str replace --regex --all "([AP]M)" $"(ansi magenta_underline)${1}")

Expand Down

0 comments on commit 123bf2d

Please sign in to comment.