Debian Codegraph @

.cargo/vendor/built/src/util.rs

raw
1 //! Various convenience functions for `built` at runtime.
2
3 use std::fmt;
4 use std::fmt::Write;
5
6 #[cfg(feature = "git2")]
7 pub use crate::git::{get_repo_description, get_repo_head};
8
9 #[cfg(feature = "chrono")]
10 pub use crate::krono::strptime;
11
12 /// Parses version-strings with `semver::Version::parse()`.
13 ///
14 /// This function is only available if `built` was compiled with the
15 /// `semver` feature.
16 ///
17 /// The function takes a reference to an array of names and version numbers as
18 /// serialized by `built` and returns an iterator over the unchanged names
19 /// and parsed version numbers.
20 ///
21 /// ```
22 /// pub mod build_info {
23 /// pub static DEPENDENCIES: [(&'static str, &'static str); 1] = [("built", "0.1.0")];
24 /// }
25 ///
26 /// let deps = build_info::DEPENDENCIES;
27 /// assert!(built::util::parse_versions(&deps)
28 /// .any(|(name, ver)| name == "built" &&
29 /// ver >= semver::Version::parse("0.1.0").unwrap()));
30 /// ```
31 ///
32 /// # Panics
33 /// If a version can't be parsed by `semver::Version::parse()`. This should never
34 /// happen with version strings provided by Cargo and `built`.
35 #[cfg(feature = "semver")]
36 pub fn parse_versions<'a, T>(
37 name_and_versions: T,
38 ) -> impl Iterator<Item = (&'a str, semver::Version)>
39 where
40 T: IntoIterator<Item = &'a (&'a str, &'a str)>,
41 {
42 fn parse_version<'a>(t: &'a (&'a str, &'a str)) -> (&'a str, semver::Version) {
43 (t.0, t.1.parse().unwrap())
44 }
45 name_and_versions.into_iter().map(parse_version)
46 }
47
48 /// Detect execution on various Continuous Integration platforms.
49 ///
50 /// CI-platforms are detected by the presence of known environment variables.
51 /// This allows to detect specific CI-platform (like `GitLab`); various
52 /// generic environment variables are also checked, which may result in
53 /// `CIPlatform::Generic`.
54 ///
55 /// Since some platforms have fairly generic environment variables to begin with
56 /// (e.g. `TASK_ID`), this function may have false positives.
57 #[must_use]
58 pub fn detect_ci() -> Option<super::CIPlatform> {
59 crate::environment::EnvironmentMap::new().detect_ci()
60 }
61
62 pub(crate) trait ParseFromEnv<'a>
63 where
64 Self: Sized,
65 {
66 type Err: std::fmt::Debug;
67
68 fn parse_from_env(s: &'a str) -> Result<Self, Self::Err>;
69 }
70
71 impl<'a> ParseFromEnv<'a> for &'a str {
72 type Err = std::convert::Infallible;
73
74 fn parse_from_env(s: &'a str) -> Result<Self, Self::Err> {
75 Ok(s)
76 }
77 }
78
79 macro_rules! parsefromenv_impl {
80 ($tie:ty) => {
81 impl ParseFromEnv<'_> for $tie {
82 type Err = <Self as std::str::FromStr>::Err;
83
84 fn parse_from_env(s: &str) -> Result<Self, Self::Err> {
85 s.parse()
86 }
87 }
88 };
89 ($($tie:ty),+) => {
90 $(
91 parsefromenv_impl!($tie);
92 )+
93 };
94 }
95 parsefromenv_impl!(i64, i32, i16, i8, u64, u32, u16, u8, bool, String);
96
97 impl<'a, T> ParseFromEnv<'a> for Vec<T>
98 where
99 T: ParseFromEnv<'a>,
100 {
101 type Err = <T as ParseFromEnv<'a>>::Err;
102
103 fn parse_from_env(s: &'a str) -> Result<Self, Self::Err> {
104 s.split(',')
105 .map(|chunk| T::parse_from_env(chunk.trim()))
106 .collect()
107 }
108 }
109
110 impl<'a, T> ParseFromEnv<'a> for Option<T>
111 where
112 T: ParseFromEnv<'a>,
113 {
114 type Err = <T as ParseFromEnv<'a>>::Err;
115
116 fn parse_from_env(s: &'a str) -> Result<Self, Self::Err> {
117 if s == "BUILT_OVERRIDE_NONE" {
118 Ok(None)
119 } else {
120 Ok(Some(T::parse_from_env(s)?))
121 }
122 }
123 }
124
125 pub(crate) struct ArrayDisplay<'a, T, F>(pub &'a [T], pub F)
126 where
127 F: Fn(&T, &mut fmt::Formatter<'_>) -> fmt::Result;
128
129 impl<T, F> fmt::Display for ArrayDisplay<'_, T, F>
130 where
131 F: Fn(&T, &mut fmt::Formatter<'_>) -> fmt::Result,
132 {
133 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134 f.write_char('[')?;
135 for (i, v) in self.0.iter().enumerate() {
136 if i != 0 {
137 f.write_str(", ")?;
138 }
139 (self.1)(v, f)?;
140 }
141 f.write_char(']')
142 }
143 }
144
145 #[cfg(feature = "cargo-lock")]
146 pub(crate) struct TupleArrayDisplay<'a, T>(pub &'a [(T, T)]);
147
148 #[cfg(feature = "cargo-lock")]
149 impl<T> fmt::Display for TupleArrayDisplay<'_, T>
150 where
151 T: AsRef<str>,
152 {
153 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
154 write!(
155 f,
156 "{}",
157 ArrayDisplay(self.0, |(a, b), fmt| write!(
158 fmt,
159 r#"("{}", "{}")"#,
160 a.as_ref().escape_default(),
161 b.as_ref().escape_default()
162 ))
163 )
164 }
165 }
166
167 #[cfg(test)]
168 mod tests {
169 use super::*;
170
171 #[test]
172 fn test_parse_env() {
173 assert_eq!(String::parse_from_env("foo"), Ok("foo".to_owned()));
174 assert_eq!(<&str>::parse_from_env("foo"), Ok("foo"));
175
176 assert_eq!(i64::parse_from_env("123"), Ok(123));
177 assert_eq!(i32::parse_from_env("123"), Ok(123));
178 assert_eq!(i16::parse_from_env("123"), Ok(123));
179 assert_eq!(i8::parse_from_env("123"), Ok(123));
180 assert_eq!(u64::parse_from_env("123"), Ok(123));
181 assert_eq!(u32::parse_from_env("123"), Ok(123));
182 assert_eq!(u16::parse_from_env("123"), Ok(123));
183 assert_eq!(u8::parse_from_env("123"), Ok(123));
184
185 assert_eq!(i8::parse_from_env("-123"), Ok(-123));
186 assert!(u8::parse_from_env("-123").is_err());
187 assert!(i32::parse_from_env("foo").is_err());
188 assert!(i32::parse_from_env("").is_err());
189
190 assert_eq!(bool::parse_from_env("true"), Ok(true));
191 assert_eq!(bool::parse_from_env("false"), Ok(false));
192 assert!(bool::parse_from_env("").is_err());
193 assert!(bool::parse_from_env("foo").is_err());
194
195 assert!(Option::<i32>::parse_from_env("").is_err());
196 assert_eq!(Option::<&str>::parse_from_env(""), Ok(Some("")));
197 assert_eq!(
198 Option::parse_from_env("BUILT_OVERRIDE_NONE"),
199 Ok(Option::<i32>::None)
200 );
201 assert_eq!(Option::parse_from_env("123"), Ok(Some(123u8)));
202 assert_eq!(Option::<bool>::parse_from_env("true"), Ok(Some(true)));
203 assert!(Option::<bool>::parse_from_env("123").is_err());
204
205 assert_eq!(
206 Vec::<&str>::parse_from_env("foo, b a r , foo"),
207 Ok(vec!["foo", "b a r", "foo"])
208 );
209 assert_eq!(
210 Vec::<i32>::parse_from_env("123,456,789"),
211 Ok(vec![123, 456, 789])
212 );
213
214 assert_eq!(
215 Option::parse_from_env("123,456"),
216 Ok(Some(vec![123u32, 456u32]))
217 );
218 }
219 }