forked from uutils/coreutils
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlocale.rs
More file actions
260 lines (226 loc) · 9.18 KB
/
Copy pathlocale.rs
File metadata and controls
260 lines (226 loc) · 9.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
// This file is part of the uutils coreutils package.
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
//! Locale detection for time format preferences
// nl_langinfo is available on glibc (Linux), Apple platforms, and BSDs
// but not on Android, Redox or other minimal Unix systems
// Macro to reduce cfg duplication across the module
macro_rules! cfg_langinfo {
($($item:item)*) => {
$(
#[cfg(all(unix, not(target_os = "android"), not(target_os = "cygwin"), not(target_os = "redox")))]
$item
)*
}
}
cfg_langinfo! {
use std::ffi::CStr;
use std::sync::OnceLock;
#[cfg(test)]
use std::sync::Mutex;
/// glibc's `_DATE_FMT` has been stable for the last 12 years
/// being added upstream to libc TODO: update to libc
#[cfg(any(target_os = "linux", target_os = "cygwin"))]
const DATE_FMT: libc::nl_item = 0x2006c;
#[cfg(not(any(target_os = "linux", target_os = "cygwin")))]
const DATE_FMT: libc::nl_item = libc::D_T_FMT;
}
cfg_langinfo! {
/// Cached locale date/time format string
static DEFAULT_FORMAT_CACHE: OnceLock<&'static str> = OnceLock::new();
/// Mutex to serialize setlocale() calls during tests.
///
/// setlocale() is process-global, so parallel tests that call it can
/// interfere with each other. This mutex ensures only one test accesses
/// locale functions at a time.
#[cfg(test)]
static LOCALE_MUTEX: Mutex<()> = Mutex::new(());
/// Returns the default date format string for the current locale.
///
/// The format respects locale preferences for time display (12-hour vs 24-hour),
/// component ordering, and numeric formatting conventions. Ensures timezone
/// information is included in the output.
pub fn get_locale_default_format() -> &'static str {
DEFAULT_FORMAT_CACHE.get_or_init(|| {
// Try to get locale format string
if let Some(format) = get_locale_format_string() {
let format_with_tz = ensure_timezone_in_format(&format);
return Box::leak(format_with_tz.into_boxed_str());
}
// Fallback: use 24-hour format as safe default
"%a %b %e %X %Z %Y"
})
}
/// Retrieves the date/time format string from the system locale
fn get_locale_format_string() -> Option<String> {
// In tests, acquire mutex to prevent race conditions with setlocale()
// which is process-global and not thread-safe
#[cfg(test)]
let _lock = LOCALE_MUTEX.lock().unwrap();
unsafe {
// Set locale from environment variables
libc::setlocale(libc::LC_TIME, c"".as_ptr());
// Get the date/time format string
let d_t_fmt_ptr = libc::nl_langinfo(DATE_FMT);
if d_t_fmt_ptr.is_null() {
return None;
}
let format = CStr::from_ptr(d_t_fmt_ptr).to_str().ok()?;
if format.is_empty() {
return None;
}
Some(format.to_string())
}
}
/// Ensures the format string includes timezone (%Z)
fn ensure_timezone_in_format(format: &str) -> String {
if format.contains("%Z") {
return format.to_string();
}
// Try to insert %Z before year specifier (%Y or %y)
if let Some(pos) = format.find("%Y").or_else(|| format.find("%y")) {
let mut result = String::with_capacity(format.len() + 3);
result.push_str(&format[..pos]);
result.push_str("%Z ");
result.push_str(&format[pos..]);
result
} else {
// No year found, append %Z at the end
format.to_string() + " %Z"
}
}
}
/// On platforms without nl_langinfo support, use 24-hour format by default
#[cfg(any(
not(unix),
target_os = "android",
target_os = "cygwin",
target_os = "redox"
))]
pub fn get_locale_default_format() -> &'static str {
"%a %b %e %X %Z %Y"
}
#[cfg(test)]
mod tests {
cfg_langinfo! {
use super::*;
#[test]
fn test_locale_detection() {
// Just verify the function doesn't panic
let _ = get_locale_default_format();
}
#[test]
fn test_default_format_contains_valid_codes() {
let format = get_locale_default_format();
assert!(format.contains("%a")); // abbreviated weekday
assert!(format.contains("%b")); // abbreviated month
assert!(format.contains("%Y") || format.contains("%y")); // year (4-digit or 2-digit)
assert!(format.contains("%Z")); // timezone
}
#[test]
fn test_locale_format_structure() {
// Verify we're using actual locale format strings, not hardcoded ones
let format = get_locale_default_format();
// The format should not be empty
assert!(!format.is_empty(), "Locale format should not be empty");
// Should contain date/time components
let has_date_component = format.contains("%a")
|| format.contains("%A")
|| format.contains("%b")
|| format.contains("%B")
|| format.contains("%d")
|| format.contains("%e");
assert!(has_date_component, "Format should contain date components");
// Should contain time component (hour)
let has_time_component = format.contains("%H")
|| format.contains("%I")
|| format.contains("%k")
|| format.contains("%l")
|| format.contains("%r")
|| format.contains("%R")
|| format.contains("%T")
|| format.contains("%X");
assert!(has_time_component, "Format should contain time components");
}
#[test]
fn test_c_locale_format() {
// Acquire mutex to prevent interference with other tests
let _lock = LOCALE_MUTEX.lock().unwrap();
// Save original locale (both environment and process locale)
let original_lc_all = std::env::var_os("LC_ALL");
let original_lc_time = std::env::var_os("LC_TIME");
let original_lang = std::env::var_os("LANG");
// Save current process locale
let original_process_locale = unsafe {
let ptr = libc::setlocale(libc::LC_TIME, std::ptr::null());
if ptr.is_null() {
None
} else {
CStr::from_ptr(ptr).to_str().ok().map(ToString::to_string)
}
};
unsafe {
// Set C locale
std::env::set_var("LC_ALL", "C");
std::env::remove_var("LC_TIME");
std::env::remove_var("LANG");
}
// Get the locale format
let format = unsafe {
libc::setlocale(libc::LC_TIME, c"C".as_ptr());
let d_t_fmt_ptr = libc::nl_langinfo(libc::D_T_FMT);
if d_t_fmt_ptr.is_null() {
None
} else {
CStr::from_ptr(d_t_fmt_ptr).to_str().ok()
}
};
if let Some(locale_format) = format {
// C locale typically uses 24-hour format
// Common patterns: %H (24-hour with leading zero) or %T (HH:MM:SS)
let uses_24_hour = locale_format.contains("%H")
|| locale_format.contains("%T")
|| locale_format.contains("%R");
assert!(uses_24_hour, "C locale should use 24-hour format, got: {locale_format}");
}
// Restore original environment variables
unsafe {
if let Some(val) = original_lc_all {
std::env::set_var("LC_ALL", val);
} else {
std::env::remove_var("LC_ALL");
}
if let Some(val) = original_lc_time {
std::env::set_var("LC_TIME", val);
} else {
std::env::remove_var("LC_TIME");
}
if let Some(val) = original_lang {
std::env::set_var("LANG", val);
} else {
std::env::remove_var("LANG");
}
}
// Restore original process locale
unsafe {
if let Some(locale) = original_process_locale {
let c_locale = std::ffi::CString::new(locale).unwrap();
libc::setlocale(libc::LC_TIME, c_locale.as_ptr());
} else {
// Restore from environment
libc::setlocale(libc::LC_TIME, c"".as_ptr());
}
}
}
#[test]
fn test_timezone_included_in_format() {
// The implementation should ensure %Z is present
let format = get_locale_default_format();
assert!(
format.contains("%Z") || format.contains("%z"),
"Format should contain timezone indicator: {format}"
);
}
}
}