Debian Codegraph @

src/cli/types/version.rs

raw
1 use std::borrow::Borrow;
2 use std::fmt;
3 use std::str::FromStr;
4
5 use anyhow::anyhow;
6
7 use serde::Serialize;
8
9 use crate::Result;
10
11 /// A value parser for the version string.
12 ///
13 /// This parser always emits an error that the argument is at the
14 /// wrong place.
15 #[derive(Clone, Debug, Default)]
16 pub struct VersionInvalidPositionValueParser {}
17
18 impl clap::builder::TypedValueParser for VersionInvalidPositionValueParser {
19 type Value = Version;
20
21 fn parse_ref(
22 &self,
23 cmd: &clap::Command,
24 arg: Option<&clap::Arg>,
25 value: &std::ffi::OsStr,
26 ) -> std::result::Result<Self::Value, clap::error::Error> {
27 let mut err = clap::Error::new(clap::error::ErrorKind::UnknownArgument)
28 .with_cmd(cmd);
29 if let Some(arg) = arg {
30 err.insert(
31 clap::error::ContextKind::InvalidArg,
32 clap::error::ContextValue::String(arg.to_string()));
33 }
34 err.insert(
35 clap::error::ContextKind::InvalidValue,
36 clap::error::ContextValue::String(
37 String::from_utf8_lossy(value.as_encoded_bytes()).to_string()));
38 err.insert(
39 clap::error::ContextKind::Suggested,
40 clap::error::ContextValue::StyledStrs(vec![
41 "--cli-version must be the very first argument".to_string().into()
42 ]));
43
44 Err(err)
45 }
46 }
47
48 /// A semver version string.
49 ///
50 /// As `sq` evolves, the machine-readable output format may need to
51 /// change. Consumers should be able to know what version of the output
52 /// format has been produced. This is expressed using a three-part
53 /// version number, which is always included in the output, similar to
54 /// [Semantic Versions][]. The parts are known as "major", "minor",
55 /// and "patch", and have the following semantics:
56 ///
57 /// * patch: incremented if there are no semantic changes
58 /// * minor: one or more fields were added
59 /// * major: one or more fields were dropped
60 ///
61 /// [Semantic Version]: https://semver.org/
62 #[derive(Debug, Copy, Clone, Eq, PartialEq, Serialize)]
63 pub struct Version {
64 major: usize,
65 minor: usize,
66 patch: usize,
67 }
68
69 impl Version {
70 /// Create a new version number from constituent parts.
71 pub const fn new(major: usize, minor: usize, patch: usize) -> Self {
72 Self {
73 major,
74 minor,
75 patch,
76 }
77 }
78
79 /// Does this version fulfill the needs of the version that is requested?
80 pub fn is_acceptable_for<V>(&self, wanted: V) -> bool
81 where V: Borrow<Self>
82 {
83 let wanted = wanted.borrow();
84
85 self.major == wanted.major &&
86 (self.minor > wanted.minor ||
87 (self.minor == wanted.minor && self.patch >= wanted.patch))
88 }
89 }
90
91 impl FromStr for Version {
92 type Err = anyhow::Error;
93
94 fn from_str(v: &str) -> Result<Self> {
95 let ints = parse_ints(v)?;
96 match ints.len() {
97 0 => Err(anyhow!("doesn't look like a version: {}", v)),
98 1 => Ok(Self::new(ints[0], 0, 0)),
99 2 => Ok(Self::new(ints[0], ints[1], 0)),
100 3 => Ok(Self::new(ints[0], ints[1], ints[2])),
101 _ => Err(anyhow!("too many components in version (at most three allowed): {}", v)),
102 }
103 }
104 }
105
106 impl fmt::Display for Version {
107 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108 write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
109 }
110 }
111
112 impl PartialEq<Version> for &Version {
113 fn eq(&self, other: &Version) -> bool {
114 self.major == other.major &&
115 self.minor == other.minor &&
116 self.patch == other.patch
117 }
118 }
119
120 fn parse_ints(s: &str) -> Result<Vec<usize>> {
121 let mut ints = vec![];
122 let mut v = s;
123 while !v.is_empty() {
124 if let Some(i) = v.find('.') {
125 ints.push(parse_component(&v[..i])?);
126 v = &v[i+1..];
127 if v.is_empty() {
128 return Err(anyhow!("trailing dot in version: {}", s));
129 }
130 } else {
131 ints.push(parse_component(v)?);
132 v = "";
133 }
134 }
135 Ok(ints)
136 }
137
138 fn parse_component(s: &str) -> Result<usize> {
139 Ok(FromStr::from_str(s)?)
140 }
141
142 #[cfg(test)]
143 mod test {
144 use std::str::FromStr;
145 use super::Version;
146
147 #[test]
148 fn empty_string() {
149 assert!(Version::from_str("").is_err());
150 }
151
152 #[test]
153 fn not_int() {
154 assert!(Version::from_str("foo").is_err());
155 }
156
157 #[test]
158 fn not_int2() {
159 assert!(Version::from_str("1.foo").is_err());
160 }
161
162 #[test]
163 fn leading_dot() {
164 assert!(Version::from_str(".1").is_err());
165 }
166
167 #[test]
168 fn trailing_dot() {
169 assert!(Version::from_str("1.").is_err());
170 }
171
172 #[test]
173 fn one_int() {
174 assert_eq!(Version::from_str("1").unwrap(), Version::new(1, 0, 0));
175 }
176
177 #[test]
178 fn two_ints() {
179 assert_eq!(Version::from_str("1.2").unwrap(), Version::new(1, 2, 0));
180 }
181
182 #[test]
183 fn three_ints() {
184 assert_eq!(Version::from_str("1.2.3").unwrap(), Version::new(1, 2, 3));
185 }
186
187 #[test]
188 fn four_ints() {
189 assert!(Version::from_str("1.2.3.4").is_err());
190 }
191
192 #[test]
193 fn acceptable_if_same() {
194 let a = Version::new(0, 0, 0);
195 assert!(a.is_acceptable_for(a));
196 }
197
198 #[test]
199 fn acceptable_if_newer_patch() {
200 let wanted = Version::new(0, 0, 0);
201 let actual = Version::new(0, 0, 1);
202 assert!(actual.is_acceptable_for(wanted));
203 }
204
205 #[test]
206 fn not_acceptable_if_older_patch() {
207 let wanted = Version::new(0, 0, 1);
208 let actual = Version::new(0, 0, 0);
209 assert!(!actual.is_acceptable_for(wanted));
210 }
211
212 #[test]
213 fn acceptable_if_newer_minor() {
214 let wanted = Version::new(0, 0, 0);
215 let actual = Version::new(0, 1, 0);
216 assert!(actual.is_acceptable_for(wanted));
217 }
218
219 #[test]
220 fn not_acceptable_if_older_minor() {
221 let wanted = Version::new(0, 1, 0);
222 let actual = Version::new(0, 0, 0);
223 assert!(!actual.is_acceptable_for(wanted));
224 }
225
226 #[test]
227 fn not_acceptable_if_newer_major() {
228 let wanted = Version::new(0, 0, 0);
229 let actual = Version::new(1, 0, 0);
230 assert!(!actual.is_acceptable_for(wanted));
231 }
232
233 #[test]
234 fn not_acceptable_if_older_major() {
235 let wanted = Version::new(1, 0, 0);
236 let actual = Version::new(0, 0, 0);
237 assert!(!actual.is_acceptable_for(wanted));
238 }
239 }