Debian Codegraph @

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