vrl/stdlib/
get_timezone_name.rs1use crate::compiler::prelude::*;
2use chrono::Local;
3use std::borrow::Cow;
4
5#[must_use]
6pub fn get_name_for_timezone(tz: &TimeZone) -> Cow<'_, str> {
7 match tz {
8 TimeZone::Named(tz) => tz.name().into(),
9 TimeZone::Local => iana_time_zone::get_timezone()
10 .unwrap_or_else(|_| Local::now().offset().to_string())
11 .into(),
12 }
13}
14
15#[allow(clippy::unnecessary_wraps)]
16fn get_timezone_name(ctx: &mut Context) -> Resolved {
17 Ok(get_name_for_timezone(ctx.timezone()).into())
18}
19
20#[derive(Clone, Copy, Debug)]
21pub struct GetTimezoneName;
22
23impl Function for GetTimezoneName {
24 fn identifier(&self) -> &'static str {
25 "get_timezone_name"
26 }
27
28 fn usage(&self) -> &'static str {
29 indoc! {r#"
30 Returns the name of the timezone in the Vector configuration (see
31 [global configuration options](/docs/reference/configuration/global-options)).
32 If the configuration is set to `local`, then it attempts to
33 determine the name of the timezone from the host OS. If this
34 is not possible, then it returns the fixed offset of the
35 local timezone for the current time in the format `"[+-]HH:MM"`,
36 for example, `"+02:00"`.
37 "#}
38 }
39
40 fn category(&self) -> &'static str {
41 Category::System.as_ref()
42 }
43
44 fn internal_failure_reasons(&self) -> &'static [&'static str] {
45 &["Retrieval of local timezone information failed."]
46 }
47
48 fn return_kind(&self) -> u16 {
49 kind::BYTES
50 }
51
52 fn examples(&self) -> &'static [Example] {
53 &[example! {
54 title: "Get the IANA name of Vector's timezone",
55 source: "get_timezone_name!()",
56 result: Ok("UTC"),
57 deterministic: false,
58 }]
59 }
60
61 fn compile(
62 &self,
63 _state: &TypeState,
64 _ctx: &mut FunctionCompileContext,
65 _: ArgumentList,
66 ) -> Compiled {
67 Ok(GetTimezoneNameFn.as_expr())
68 }
69}
70
71#[derive(Debug, Clone)]
72struct GetTimezoneNameFn;
73
74impl FunctionExpression for GetTimezoneNameFn {
75 fn resolve(&self, ctx: &mut Context) -> Resolved {
76 get_timezone_name(ctx)
77 }
78
79 fn type_def(&self, _: &TypeState) -> TypeDef {
80 TypeDef::bytes().fallible()
81 }
82}
83
84#[cfg(test)]
85mod tests {
86 use super::*;
87 use crate::value;
88
89 test_function![
90 get_hostname => GetTimezoneName;
91
92 utc {
94 args: func_args![],
95 want: Ok(value!(get_name_for_timezone(&TimeZone::Named(chrono_tz::Tz::UTC)))),
96 tdef: TypeDef::bytes().fallible(),
97 }
98 ];
99}