verctl-core 0.9.4

Core configuration, manifest, fragment, changelog, and version domain logic for verctl
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
use std::fs;
use std::io::ErrorKind;
use std::path::Path;

use anyhow::{Context, Result, anyhow, bail};
use jsonc_parser::ParseOptions;
use jsonc_parser::cst::{CstInputValue, CstObject, CstRootNode};
use toml_edit::{DocumentMut, Item, value};

use crate::{config, gomod, marker, process};

/// The file format a path driver edits.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Format {
    /// A TOML file, edited with its comments and layout kept.
    Toml,
    /// A JSON file; comments are accepted (JSONC).
    Json,
}

/// A file whose version sits in its text. A key path cannot state the rule for
/// each file.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Text {
    /// A `go.mod` whose `module` line ends in `// vX.Y.Z`.
    GoMod,
    /// A `VERSION` file that contains one version and nothing else.
    Version,
    /// Any file, with the version on its one `version:` marker line.
    Marker,
}

impl Text {
    fn read(self, raw: &str) -> Result<String> {
        match self {
            Self::GoMod => gomod::read(raw),
            Self::Version => read_version_file(raw),
            Self::Marker => marker::read(raw),
        }
    }

    fn write(self, raw: &str, new_version: &str) -> Result<String> {
        match self {
            Self::GoMod => gomod::write(raw, new_version),
            Self::Marker => marker::write(raw, new_version),
            Self::Version => {
                read_version_file(raw)?;
                Ok(format!("{new_version}\n"))
            }
        }
    }

    fn accepts(self, raw: &str, new_version: &str) -> Result<()> {
        match self {
            Self::GoMod => gomod::accepts(raw, new_version),
            Self::Version | Self::Marker => Ok(()),
        }
    }
}

/// The version a `VERSION` file contains: one version and an optional final
/// newline. Empty text, such as a file that does not exist yet
/// ([`Driver::source`]), reads as a new package's `0.0.0`.
fn read_version_file(raw: &str) -> Result<String> {
    let line = raw
        .strip_suffix('\n')
        .map_or(raw, |line| line.strip_suffix('\r').unwrap_or(line));
    if line.is_empty() {
        return Ok("0.0.0".to_owned());
    }
    if semver::Version::parse(line).is_ok() {
        return Ok(line.to_owned());
    }
    bail!("contains {raw:?}, not one version and a newline")
}

/// How a package's version is read and written.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Driver {
    /// The version is in the file's text, in a place its format fixes.
    Text {
        /// Which format.
        text: Text,
        /// Follow-up command to run after the bump, such as a lockfile refresh.
        after: Option<String>,
    },
    /// The version is a string at a key path in a TOML or JSON file.
    Path {
        /// The file format.
        format: Format,
        /// Dotted key paths tried in order; the first that contains a string
        /// wins.
        keys: Vec<String>,
        /// Follow-up command to run after the bump, such as a lockfile refresh.
        after: Option<String>,
    },
    /// An external filter reads and writes the version.
    Command {
        /// Prints the version from the file on stdin.
        read: CommandSpec,
        /// Prints the new file from the file on stdin and `VERCTL_VERSION`.
        write: CommandSpec,
        /// Follow-up command to run after the bump, such as a lockfile refresh.
        after: Option<String>,
    },
}

/// How a command driver's filter is invoked.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum CommandSpec {
    /// `mise run <task>`: stdin is the file, stdout is the version or new
    /// file.
    Mise(String),
    /// Execvp. No shell.
    Argv(Vec<String>),
}

impl Driver {
    /// The stock driver for `Cargo.toml`.
    ///
    /// # Errors
    ///
    /// Returns an error only if the built-in definition fails validation,
    /// which a test guards against.
    pub fn cargo() -> Result<Self> {
        config::stock_driver("cargo")
    }

    /// The stock driver for `package.json`.
    ///
    /// # Errors
    ///
    /// Returns an error only if the built-in definition fails validation,
    /// which a test guards against.
    pub fn npm() -> Result<Self> {
        config::stock_driver("npm")
    }

    /// The text of `path`, the file this driver reads and writes.
    ///
    /// A `VERSION` file that does not exist yet is empty text.
    /// Empty text reads as `0.0.0`, so a new package needs no file before its
    /// first release. `version` creates the file, and `check` leaves the tree
    /// as it was.
    ///
    /// The file's directory must exist. A package whose directory is missing
    /// has a wrong `path`, and `version` would otherwise fail halfway through
    /// its writes.
    ///
    /// # Errors
    ///
    /// Returns an error naming `path` when it cannot be read. A missing file
    /// is an error unless the driver is a `VERSION` file whose directory
    /// exists.
    pub fn source(&self, path: &Path) -> Result<String> {
        match fs::read_to_string(path) {
            Ok(raw) => Ok(raw),
            Err(error)
                if error.kind() == ErrorKind::NotFound
                    && path.parent().is_some_and(Path::is_dir)
                    && matches!(
                        self,
                        Self::Text {
                            text: Text::Version,
                            after: _
                        }
                    ) =>
            {
                Ok(String::new())
            }
            Err(error) => Err(error).with_context(|| path.display().to_string()),
        }
    }

    /// The follow-up command to run after the bump, if any.
    #[must_use]
    pub fn after(&self) -> Option<&str> {
        match self {
            Self::Text { after, text: _ }
            | Self::Path {
                after,
                format: _,
                keys: _,
            }
            | Self::Command {
                after,
                read: _,
                write: _,
            } => after.as_deref(),
        }
    }

    /// Refuse `new_version` when the file's own format forbids it, before
    /// anything is written, so `version --dry-run` refuses it too.
    ///
    /// # Errors
    ///
    /// For a `go.mod`, returns an error when the new major version and the
    /// module path's `/vN` suffix conflict. Other drivers accept any version.
    pub fn accepts(&self, raw: &str, new_version: &str) -> Result<()> {
        match self {
            Self::Text { text, after: _ } => text.accepts(raw, new_version),
            Self::Path {
                format: _,
                keys: _,
                after: _,
            }
            | Self::Command {
                read: _,
                write: _,
                after: _,
            } => Ok(()),
        }
    }

    /// The current version in `raw`.
    ///
    /// # Errors
    ///
    /// For a path driver, returns an error when `raw` is not valid TOML or
    /// JSON, or when none of the configured keys contains a string. For a
    /// command driver, returns an error when the filter cannot be run, times
    /// out, exits unsuccessfully, or prints non-UTF-8 or oversized output.
    pub fn read(&self, raw: &str) -> Result<String> {
        match self {
            Self::Text { text, after: _ } => text.read(raw),
            Self::Path {
                format,
                keys,
                after: _,
            } => match format {
                Format::Toml => read_toml(raw, keys),
                Format::Json => read_json(raw, keys),
            },
            Self::Command {
                read,
                write: _,
                after: _,
            } => run_filter(read, raw, None),
        }
    }

    /// `raw` with the version replaced by `new_version`.
    ///
    /// # Errors
    ///
    /// Fails on the same conditions as [`Driver::read`]: unparsable input, no
    /// configured key containing a string, or a command filter that fails.
    pub fn write(&self, raw: &str, new_version: &str) -> Result<String> {
        match self {
            Self::Text { text, after: _ } => text.write(raw, new_version),
            Self::Path {
                format,
                keys,
                after: _,
            } => match format {
                Format::Toml => write_toml(raw, keys, new_version),
                Format::Json => write_json(raw, keys, new_version),
            },
            Self::Command {
                write,
                read: _,
                after: _,
            } => run_filter(write, raw, Some(new_version)),
        }
    }
}

fn read_toml(raw: &str, keys: &[String]) -> Result<String> {
    let doc: DocumentMut = raw.parse().context("parse TOML")?;
    for key in keys {
        if let Some(item) = toml_get(&doc, key)
            && let Some(version) = item.as_str()
        {
            return Ok(version.to_owned());
        }
    }
    Err(missing_toml_keys(&doc, keys))
}

fn write_toml(raw: &str, keys: &[String], new_version: &str) -> Result<String> {
    let mut doc: DocumentMut = raw.parse().context("parse TOML")?;
    for key in keys {
        if toml_get(&doc, key).and_then(Item::as_str).is_some() {
            let item = toml_get_mut(&mut doc, key).context(key.clone())?;
            let decor = item.as_value().map(|old| old.decor().clone());
            *item = value(new_version);
            if let (Some(decor), Some(new)) = (decor, item.as_value_mut()) {
                *new.decor_mut() = decor;
            }
            return Ok(doc.to_string());
        }
    }
    Err(missing_toml_keys(&doc, keys))
}

/// Why no key contained a version.
///
/// A `pyproject.toml` that lists `version` in `project.dynamic` has no
/// static `project.version`: the build backend computes it, and the
/// [pyproject.toml specification] lets nothing else change it. verctl cannot
/// bump a version it does not own, so the error names what can.
///
/// [pyproject.toml specification]: https://packaging.python.org/en/latest/specifications/pyproject-toml/#dynamic
fn missing_toml_keys(doc: &DocumentMut, keys: &[String]) -> anyhow::Error {
    let dynamic_version = toml_get(doc, "project.dynamic")
        .and_then(Item::as_array)
        .is_some_and(|fields| fields.iter().any(|field| field.as_str() == Some("version")));
    if dynamic_version {
        return anyhow!(
            "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"
        );
    }
    anyhow!("none of these TOML keys exist: {}", keys.join(", "))
}

fn toml_get<'a>(doc: &'a DocumentMut, path: &str) -> Option<&'a Item> {
    let mut item: Option<&Item> = None;
    for (index, part) in path.split('.').enumerate() {
        item = if index == 0 {
            doc.get(part)
        } else {
            item.and_then(|item| item.get(part))
        };
    }
    item
}

fn toml_get_mut<'a>(doc: &'a mut DocumentMut, path: &str) -> Option<&'a mut Item> {
    let mut parts = path.split('.');
    let first = parts.next()?;
    let mut item = doc.get_mut(first)?;
    for part in parts {
        item = item.get_mut(part)?;
    }
    Some(item)
}

fn read_json(raw: &str, keys: &[String]) -> Result<String> {
    let root = parse_json(raw)?;
    for key in keys {
        if let Some(version) = json_string_at(&root, key) {
            return Ok(version);
        }
    }
    bail!("none of these JSON keys exist: {}", keys.join(", "))
}

fn write_json(raw: &str, keys: &[String], new_version: &str) -> Result<String> {
    let root = parse_json(raw)?;
    for key in keys {
        if json_set_string(&root, key, new_version) {
            return Ok(root.to_string());
        }
    }
    bail!("none of these JSON keys exist: {}", keys.join(", "))
}

fn parse_json(raw: &str) -> Result<CstRootNode> {
    CstRootNode::parse(raw, &ParseOptions::default()).context("parse JSON")
}

fn json_object_at(object: &CstObject, path: &str) -> Option<CstObject> {
    let mut current = object.clone();
    for part in path.split('.') {
        current = current.object_value(part)?;
    }
    Some(current)
}

fn json_string_at(root: &CstRootNode, path: &str) -> Option<String> {
    let object = root.object_value()?;
    let (parent_path, field) = split_json_path(path);
    let parent = match parent_path {
        Some(parent) => json_object_at(&object, parent)?,
        None => object,
    };
    parent
        .get(field)?
        .value()?
        .as_string_lit()?
        .decoded_value()
        .ok()
}

fn json_set_string(root: &CstRootNode, path: &str, new_version: &str) -> bool {
    let Some(object) = root.object_value() else {
        return false;
    };
    let (parent_path, field) = split_json_path(path);
    let parent = match parent_path {
        Some(parent) => match json_object_at(&object, parent) {
            Some(parent) => parent,
            None => return false,
        },
        None => object,
    };
    let Some(prop) = parent.get(field) else {
        return false;
    };
    if prop
        .value()
        .and_then(|value| value.as_string_lit())
        .is_none()
    {
        return false;
    }
    prop.set_value(CstInputValue::String(new_version.to_owned()));
    true
}

fn split_json_path(path: &str) -> (Option<&str>, &str) {
    match path.rsplit_once('.') {
        Some((parent, field)) => (Some(parent), field),
        None => (None, path),
    }
}

fn run_filter(spec: &CommandSpec, stdin: &str, new_version: Option<&str>) -> Result<String> {
    let argv = match spec {
        CommandSpec::Mise(task) => vec!["mise".into(), "run".into(), task.clone()],
        CommandSpec::Argv(argv) => argv.clone(),
    };
    let env = new_version.map_or_else(Vec::new, |version| vec![("VERCTL_VERSION", version)]);
    let stdout = process::filter(&argv, stdin, &env)?;
    if new_version.is_some() {
        Ok(stdout)
    } else {
        Ok(stdout.trim().to_owned())
    }
}