Skip to main content

verctl_core/
driver.rs

1use std::fs;
2use std::io::ErrorKind;
3use std::path::Path;
4
5use anyhow::{Context, Result, anyhow, bail};
6use jsonc_parser::ParseOptions;
7use jsonc_parser::cst::{CstInputValue, CstObject, CstRootNode};
8use toml_edit::{DocumentMut, Item, value};
9
10use crate::{config, gomod, marker, process};
11
12/// The file format a path driver edits.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14#[non_exhaustive]
15pub enum Format {
16    /// A TOML file, edited with its comments and layout kept.
17    Toml,
18    /// A JSON file; comments are accepted (JSONC).
19    Json,
20}
21
22/// A file whose version sits in its text. A key path cannot state the rule for
23/// each file.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25#[non_exhaustive]
26pub enum Text {
27    /// A `go.mod` whose `module` line ends in `// vX.Y.Z`.
28    GoMod,
29    /// A `VERSION` file that contains one version and nothing else.
30    Version,
31    /// Any file, with the version on its one `version:` marker line.
32    Marker,
33}
34
35impl Text {
36    fn read(self, raw: &str) -> Result<String> {
37        match self {
38            Self::GoMod => gomod::read(raw),
39            Self::Version => read_version_file(raw),
40            Self::Marker => marker::read(raw),
41        }
42    }
43
44    fn write(self, raw: &str, new_version: &str) -> Result<String> {
45        match self {
46            Self::GoMod => gomod::write(raw, new_version),
47            Self::Marker => marker::write(raw, new_version),
48            Self::Version => {
49                read_version_file(raw)?;
50                Ok(format!("{new_version}\n"))
51            }
52        }
53    }
54
55    fn accepts(self, raw: &str, new_version: &str) -> Result<()> {
56        match self {
57            Self::GoMod => gomod::accepts(raw, new_version),
58            Self::Version | Self::Marker => Ok(()),
59        }
60    }
61}
62
63/// The version a `VERSION` file contains: one version and an optional final
64/// newline. Empty text, such as a file that does not exist yet
65/// ([`Driver::source`]), reads as a new package's `0.0.0`.
66fn read_version_file(raw: &str) -> Result<String> {
67    let line = raw
68        .strip_suffix('\n')
69        .map_or(raw, |line| line.strip_suffix('\r').unwrap_or(line));
70    if line.is_empty() {
71        return Ok("0.0.0".to_owned());
72    }
73    if semver::Version::parse(line).is_ok() {
74        return Ok(line.to_owned());
75    }
76    bail!("contains {raw:?}, not one version and a newline")
77}
78
79/// How a package's version is read and written.
80#[derive(Debug, Clone, PartialEq, Eq)]
81#[non_exhaustive]
82pub enum Driver {
83    /// The version is in the file's text, in a place its format fixes.
84    Text {
85        /// Which format.
86        text: Text,
87        /// Follow-up command to run after the bump, such as a lockfile refresh.
88        after: Option<String>,
89    },
90    /// The version is a string at a key path in a TOML or JSON file.
91    Path {
92        /// The file format.
93        format: Format,
94        /// Dotted key paths tried in order; the first that contains a string
95        /// wins.
96        keys: Vec<String>,
97        /// Follow-up command to run after the bump, such as a lockfile refresh.
98        after: Option<String>,
99    },
100    /// An external filter reads and writes the version.
101    Command {
102        /// Prints the version from the file on stdin.
103        read: CommandSpec,
104        /// Prints the new file from the file on stdin and `VERCTL_VERSION`.
105        write: CommandSpec,
106        /// Follow-up command to run after the bump, such as a lockfile refresh.
107        after: Option<String>,
108    },
109}
110
111/// How a command driver's filter is invoked.
112#[derive(Debug, Clone, PartialEq, Eq)]
113#[non_exhaustive]
114pub enum CommandSpec {
115    /// `mise run <task>`: stdin is the file, stdout is the version or new
116    /// file.
117    Mise(String),
118    /// Execvp. No shell.
119    Argv(Vec<String>),
120}
121
122impl Driver {
123    /// The stock driver for `Cargo.toml`.
124    ///
125    /// # Errors
126    ///
127    /// Returns an error only if the built-in definition fails validation,
128    /// which a test guards against.
129    pub fn cargo() -> Result<Self> {
130        config::stock_driver("cargo")
131    }
132
133    /// The stock driver for `package.json`.
134    ///
135    /// # Errors
136    ///
137    /// Returns an error only if the built-in definition fails validation,
138    /// which a test guards against.
139    pub fn npm() -> Result<Self> {
140        config::stock_driver("npm")
141    }
142
143    /// The text of `path`, the file this driver reads and writes.
144    ///
145    /// A `VERSION` file that does not exist yet is empty text.
146    /// Empty text reads as `0.0.0`, so a new package needs no file before its
147    /// first release. `version` creates the file, and `check` leaves the tree
148    /// as it was.
149    ///
150    /// The file's directory must exist. A package whose directory is missing
151    /// has a wrong `path`, and `version` would otherwise fail halfway through
152    /// its writes.
153    ///
154    /// # Errors
155    ///
156    /// Returns an error naming `path` when it cannot be read. A missing file
157    /// is an error unless the driver is a `VERSION` file whose directory
158    /// exists.
159    pub fn source(&self, path: &Path) -> Result<String> {
160        match fs::read_to_string(path) {
161            Ok(raw) => Ok(raw),
162            Err(error)
163                if error.kind() == ErrorKind::NotFound
164                    && path.parent().is_some_and(Path::is_dir)
165                    && matches!(
166                        self,
167                        Self::Text {
168                            text: Text::Version,
169                            after: _
170                        }
171                    ) =>
172            {
173                Ok(String::new())
174            }
175            Err(error) => Err(error).with_context(|| path.display().to_string()),
176        }
177    }
178
179    /// The follow-up command to run after the bump, if any.
180    #[must_use]
181    pub fn after(&self) -> Option<&str> {
182        match self {
183            Self::Text { after, text: _ }
184            | Self::Path {
185                after,
186                format: _,
187                keys: _,
188            }
189            | Self::Command {
190                after,
191                read: _,
192                write: _,
193            } => after.as_deref(),
194        }
195    }
196
197    /// Refuse `new_version` when the file's own format forbids it, before
198    /// anything is written, so `version --dry-run` refuses it too.
199    ///
200    /// # Errors
201    ///
202    /// For a `go.mod`, returns an error when the new major version and the
203    /// module path's `/vN` suffix conflict. Other drivers accept any version.
204    pub fn accepts(&self, raw: &str, new_version: &str) -> Result<()> {
205        match self {
206            Self::Text { text, after: _ } => text.accepts(raw, new_version),
207            Self::Path {
208                format: _,
209                keys: _,
210                after: _,
211            }
212            | Self::Command {
213                read: _,
214                write: _,
215                after: _,
216            } => Ok(()),
217        }
218    }
219
220    /// The current version in `raw`.
221    ///
222    /// # Errors
223    ///
224    /// For a path driver, returns an error when `raw` is not valid TOML or
225    /// JSON, or when none of the configured keys contains a string. For a
226    /// command driver, returns an error when the filter cannot be run, times
227    /// out, exits unsuccessfully, or prints non-UTF-8 or oversized output.
228    pub fn read(&self, raw: &str) -> Result<String> {
229        match self {
230            Self::Text { text, after: _ } => text.read(raw),
231            Self::Path {
232                format,
233                keys,
234                after: _,
235            } => match format {
236                Format::Toml => read_toml(raw, keys),
237                Format::Json => read_json(raw, keys),
238            },
239            Self::Command {
240                read,
241                write: _,
242                after: _,
243            } => run_filter(read, raw, None),
244        }
245    }
246
247    /// `raw` with the version replaced by `new_version`.
248    ///
249    /// # Errors
250    ///
251    /// Fails on the same conditions as [`Driver::read`]: unparsable input, no
252    /// configured key containing a string, or a command filter that fails.
253    pub fn write(&self, raw: &str, new_version: &str) -> Result<String> {
254        match self {
255            Self::Text { text, after: _ } => text.write(raw, new_version),
256            Self::Path {
257                format,
258                keys,
259                after: _,
260            } => match format {
261                Format::Toml => write_toml(raw, keys, new_version),
262                Format::Json => write_json(raw, keys, new_version),
263            },
264            Self::Command {
265                write,
266                read: _,
267                after: _,
268            } => run_filter(write, raw, Some(new_version)),
269        }
270    }
271}
272
273fn read_toml(raw: &str, keys: &[String]) -> Result<String> {
274    let doc: DocumentMut = raw.parse().context("parse TOML")?;
275    for key in keys {
276        if let Some(item) = toml_get(&doc, key)
277            && let Some(version) = item.as_str()
278        {
279            return Ok(version.to_owned());
280        }
281    }
282    Err(missing_toml_keys(&doc, keys))
283}
284
285fn write_toml(raw: &str, keys: &[String], new_version: &str) -> Result<String> {
286    let mut doc: DocumentMut = raw.parse().context("parse TOML")?;
287    for key in keys {
288        if toml_get(&doc, key).and_then(Item::as_str).is_some() {
289            let item = toml_get_mut(&mut doc, key).context(key.clone())?;
290            let decor = item.as_value().map(|old| old.decor().clone());
291            *item = value(new_version);
292            if let (Some(decor), Some(new)) = (decor, item.as_value_mut()) {
293                *new.decor_mut() = decor;
294            }
295            return Ok(doc.to_string());
296        }
297    }
298    Err(missing_toml_keys(&doc, keys))
299}
300
301/// Why no key contained a version.
302///
303/// A `pyproject.toml` that lists `version` in `project.dynamic` has no
304/// static `project.version`: the build backend computes it, and the
305/// [pyproject.toml specification] lets nothing else change it. verctl cannot
306/// bump a version it does not own, so the error names what can.
307///
308/// [pyproject.toml specification]: https://packaging.python.org/en/latest/specifications/pyproject-toml/#dynamic
309fn missing_toml_keys(doc: &DocumentMut, keys: &[String]) -> anyhow::Error {
310    let dynamic_version = toml_get(doc, "project.dynamic")
311        .and_then(Item::as_array)
312        .is_some_and(|fields| fields.iter().any(|field| field.as_str() == Some("version")));
313    if dynamic_version {
314        return anyhow!(
315            "project.dynamic lists version, so the build backend sets it and verctl cannot; write a static project.version, keep the version in a VERSION file, or declare a driver"
316        );
317    }
318    anyhow!("none of these TOML keys exist: {}", keys.join(", "))
319}
320
321fn toml_get<'a>(doc: &'a DocumentMut, path: &str) -> Option<&'a Item> {
322    let mut item: Option<&Item> = None;
323    for (index, part) in path.split('.').enumerate() {
324        item = if index == 0 {
325            doc.get(part)
326        } else {
327            item.and_then(|item| item.get(part))
328        };
329    }
330    item
331}
332
333fn toml_get_mut<'a>(doc: &'a mut DocumentMut, path: &str) -> Option<&'a mut Item> {
334    let mut parts = path.split('.');
335    let first = parts.next()?;
336    let mut item = doc.get_mut(first)?;
337    for part in parts {
338        item = item.get_mut(part)?;
339    }
340    Some(item)
341}
342
343fn read_json(raw: &str, keys: &[String]) -> Result<String> {
344    let root = parse_json(raw)?;
345    for key in keys {
346        if let Some(version) = json_string_at(&root, key) {
347            return Ok(version);
348        }
349    }
350    bail!("none of these JSON keys exist: {}", keys.join(", "))
351}
352
353fn write_json(raw: &str, keys: &[String], new_version: &str) -> Result<String> {
354    let root = parse_json(raw)?;
355    for key in keys {
356        if json_set_string(&root, key, new_version) {
357            return Ok(root.to_string());
358        }
359    }
360    bail!("none of these JSON keys exist: {}", keys.join(", "))
361}
362
363fn parse_json(raw: &str) -> Result<CstRootNode> {
364    CstRootNode::parse(raw, &ParseOptions::default()).context("parse JSON")
365}
366
367fn json_object_at(object: &CstObject, path: &str) -> Option<CstObject> {
368    let mut current = object.clone();
369    for part in path.split('.') {
370        current = current.object_value(part)?;
371    }
372    Some(current)
373}
374
375fn json_string_at(root: &CstRootNode, path: &str) -> Option<String> {
376    let object = root.object_value()?;
377    let (parent_path, field) = split_json_path(path);
378    let parent = match parent_path {
379        Some(parent) => json_object_at(&object, parent)?,
380        None => object,
381    };
382    parent
383        .get(field)?
384        .value()?
385        .as_string_lit()?
386        .decoded_value()
387        .ok()
388}
389
390fn json_set_string(root: &CstRootNode, path: &str, new_version: &str) -> bool {
391    let Some(object) = root.object_value() else {
392        return false;
393    };
394    let (parent_path, field) = split_json_path(path);
395    let parent = match parent_path {
396        Some(parent) => match json_object_at(&object, parent) {
397            Some(parent) => parent,
398            None => return false,
399        },
400        None => object,
401    };
402    let Some(prop) = parent.get(field) else {
403        return false;
404    };
405    if prop
406        .value()
407        .and_then(|value| value.as_string_lit())
408        .is_none()
409    {
410        return false;
411    }
412    prop.set_value(CstInputValue::String(new_version.to_owned()));
413    true
414}
415
416fn split_json_path(path: &str) -> (Option<&str>, &str) {
417    match path.rsplit_once('.') {
418        Some((parent, field)) => (Some(parent), field),
419        None => (None, path),
420    }
421}
422
423fn run_filter(spec: &CommandSpec, stdin: &str, new_version: Option<&str>) -> Result<String> {
424    let argv = match spec {
425        CommandSpec::Mise(task) => vec!["mise".into(), "run".into(), task.clone()],
426        CommandSpec::Argv(argv) => argv.clone(),
427    };
428    let env = new_version.map_or_else(Vec::new, |version| vec![("VERCTL_VERSION", version)]);
429    let stdout = process::filter(&argv, stdin, &env)?;
430    if new_version.is_some() {
431        Ok(stdout)
432    } else {
433        Ok(stdout.trim().to_owned())
434    }
435}