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