Skip to main content

verctl_core/workspace/
lockfile.rs

1//! The lockfiles a Version PR may change, read to prove it moved only
2//! workspace versions.
3//!
4//! verctl never writes a lockfile: each moves through its owner
5//! ([`crate::detect::owner`]). `check` parses the merge-base and HEAD copies
6//! and compares them entry by entry with [`Lockfile::compare`].
7//!
8//! A registry entry and a workspace member can share a name, so they differ
9//! by source:
10//!
11//! - `Cargo.lock`: a member has no `source`.
12//! - `bun.lock`: a member sits under a `workspaces` key.
13//! - `package-lock.json`: a member is a path outside `node_modules/`.
14//! - `uv.lock`: a member has an `editable` or `virtual` source.
15
16use std::collections::{BTreeMap, BTreeSet};
17use std::path::{Path, PathBuf};
18use std::{fmt, fs};
19
20use anyhow::{Context, Result, bail};
21use serde_json::{Map, Value};
22
23/// How `check` treats a lockfile on a Version PR.
24///
25/// Not `#[non_exhaustive]`: `verctl-release` matches every variant
26/// exhaustively.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum Kind {
29    /// verctl parses it, and only workspace versions may move.
30    Parsed(Format),
31    /// It records no workspace version, so a Version PR leaves it unchanged:
32    /// `pnpm-lock.yaml`, `poetry.lock`, and `pdm.lock`.
33    Unchanged,
34    /// verctl does not read it, so a Version PR that changes it fails:
35    /// `yarn.lock` and the binary `bun.lockb`.
36    Unreadable,
37}
38
39/// A lockfile format verctl parses.
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41#[non_exhaustive]
42pub enum Format {
43    /// `Cargo.lock`.
44    Cargo,
45    /// The text `bun.lock`, which is JSON with trailing commas.
46    Bun,
47    /// `package-lock.json` or `npm-shrinkwrap.json`, version 2 or 3.
48    Npm,
49    /// `uv.lock`.
50    Uv,
51}
52
53/// How `check` treats the file at `path`, or `None` when it is no lockfile.
54#[must_use]
55pub fn kind(path: &Path) -> Option<Kind> {
56    match path.file_name()?.to_str()? {
57        "Cargo.lock" => Some(Kind::Parsed(Format::Cargo)),
58        "bun.lock" => Some(Kind::Parsed(Format::Bun)),
59        "package-lock.json" | "npm-shrinkwrap.json" => Some(Kind::Parsed(Format::Npm)),
60        "uv.lock" => Some(Kind::Parsed(Format::Uv)),
61        "pnpm-lock.yaml" | "poetry.lock" | "pdm.lock" => Some(Kind::Unchanged),
62        "yarn.lock" | "bun.lockb" => Some(Kind::Unreadable),
63        _ => None,
64    }
65}
66
67/// One locked package.
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct Entry {
70    /// What an error names: the package name, or the path of a JavaScript
71    /// workspace member (`.` for the root) or of a `node_modules` entry.
72    pub label: String,
73    /// The package name, as its manifest writes it.
74    pub name: String,
75    /// The locked version, when the entry records one.
76    pub version: Option<String>,
77    /// Whether the entry is a workspace member.
78    pub member: bool,
79    /// Every other field, written with sorted keys. A reference to a member
80    /// carries no version, so a member's bump leaves its dependents' entries
81    /// unchanged.
82    rest: String,
83}
84
85/// A parsed lockfile.
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct Lockfile {
88    /// Every top-level field but the entries, written with sorted keys.
89    header: String,
90    /// Entries by a key unique within the file.
91    entries: BTreeMap<String, Entry>,
92}
93
94impl Entry {
95    /// Whether a bump of the member this entry records changes the entry.
96    ///
97    /// The root workspace of a `bun.lock` records no `version` key, so a
98    /// bump leaves it as it is. Every other member entry follows its
99    /// manifest's version, even one that records none, because the lockfile
100    /// cannot say it never will.
101    #[must_use]
102    pub fn follows_version(&self, format: Format) -> bool {
103        !(format == Format::Bun && self.member && self.label == "." && self.version.is_none())
104    }
105}
106
107/// A workspace member whose version a bump moves.
108///
109/// One rule decides which lockfile entry records it, for `check` when it
110/// explains a lockfile change and for the version step when it decides whether
111/// a lockfile owner has anything to do.
112#[derive(Debug, Clone, PartialEq, Eq)]
113pub struct Member {
114    /// The member's manifest. It and the lockfile directory passed to
115    /// [`Member::records`] are relative to one root, or absolute under it.
116    manifest: PathBuf,
117    /// The names a lockfile may record it under: the configured name and the
118    /// name its manifest declares.
119    names: BTreeSet<String>,
120}
121
122impl Member {
123    /// The member whose manifest is `manifest`, recorded under any of
124    /// `names`.
125    #[must_use]
126    pub fn new(manifest: impl Into<PathBuf>, names: BTreeSet<String>) -> Self {
127        Self {
128            manifest: manifest.into(),
129            names,
130        }
131    }
132
133    /// The member's manifest.
134    #[must_use]
135    pub fn manifest(&self) -> &Path {
136        &self.manifest
137    }
138
139    /// The directory a JavaScript lockfile at `lock_dir` names this member
140    /// by: `.` for the lockfile's own directory.
141    fn label(&self, lock_dir: &Path) -> Option<String> {
142        let dir = self.manifest.parent()?;
143        let label = dir.strip_prefix(lock_dir).ok()?;
144        Some(if label.as_os_str().is_empty() {
145            ".".to_owned()
146        } else {
147            label.display().to_string()
148        })
149    }
150
151    /// Whether the entry called `name`, labelled `label`, in the `format`
152    /// lockfile at `lock_dir` records this member.
153    ///
154    /// `Cargo.lock` and `uv.lock` name a member, `uv.lock` by its [PEP 503]
155    /// normalised name. `bun.lock` and `package-lock.json` name it by its
156    /// directory.
157    ///
158    /// [PEP 503]: https://peps.python.org/pep-0503/#normalized-names
159    #[must_use]
160    pub fn records(&self, format: Format, lock_dir: &Path, name: &str, label: &str) -> bool {
161        match format {
162            Format::Cargo => self.names.contains(name),
163            Format::Uv => {
164                let name = pep503(name);
165                self.names.iter().any(|known| pep503(known) == name)
166            }
167            Format::Bun | Format::Npm => self.label(lock_dir).as_deref() == Some(label),
168        }
169    }
170}
171
172/// A Python project name as uv writes it in `uv.lock`: lowercase, with each
173/// run of `-`, `_`, and `.` as one `-` ([PEP 503]).
174///
175/// [PEP 503]: https://peps.python.org/pep-0503/#normalized-names
176fn pep503(name: &str) -> String {
177    let mut normalized = String::with_capacity(name.len());
178    for character in name.chars() {
179        if matches!(character, '-' | '_' | '.') {
180            if !normalized.ends_with('-') {
181                normalized.push('-');
182            }
183        } else {
184            normalized.extend(character.to_lowercase());
185        }
186    }
187    normalized
188}
189
190/// The package name a manifest declares, when its format has one verctl
191/// reads: `package.name` in `Cargo.toml`, `project.name` in
192/// `pyproject.toml`, and `name` in `package.json`.
193#[must_use]
194pub fn declared_name(manifest: &Path) -> Option<String> {
195    let text = fs::read_to_string(manifest).ok()?;
196    match manifest.file_name()?.to_str()? {
197        "Cargo.toml" => toml_name(&text, "package"),
198        "pyproject.toml" => toml_name(&text, "project"),
199        "package.json" => serde_json::from_str::<Value>(&text)
200            .ok()?
201            .get("name")?
202            .as_str()
203            .map(str::to_owned),
204        _ => None,
205    }
206}
207
208fn toml_name(text: &str, table: &str) -> Option<String> {
209    let document = text.parse::<toml_edit::DocumentMut>().ok()?;
210    document
211        .get(table)?
212        .get("name")?
213        .as_str()
214        .map(str::to_owned)
215}
216
217/// One difference between two copies of a lockfile.
218#[derive(Debug, Clone, PartialEq, Eq)]
219#[non_exhaustive]
220pub enum Change {
221    /// A top-level field changed, such as the format version.
222    Header,
223    /// An entry exists only in the newer copy.
224    Added(String),
225    /// An entry exists only in the older copy.
226    Removed(String),
227    /// An entry changed in a field other than a member's version, or a
228    /// registry entry changed its version.
229    Changed(String),
230    /// A workspace member's version moved and nothing else in its entry did.
231    Member {
232        /// The entry's label.
233        label: String,
234        /// The member's package name.
235        name: String,
236        /// The version in the older copy.
237        from: Option<String>,
238        /// The version in the newer copy.
239        to: Option<String>,
240    },
241}
242
243impl Change {
244    /// Whether the change is a member's version alone, the only change a
245    /// lockfile owner makes for a bump.
246    #[must_use]
247    pub fn is_member_version(&self) -> bool {
248        matches!(
249            self,
250            Self::Member {
251                label: _,
252                name: _,
253                from: _,
254                to: _
255            }
256        )
257    }
258}
259
260impl fmt::Display for Change {
261    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
262        match self {
263            Self::Header => write!(f, "its header changed"),
264            Self::Added(label) => write!(f, "`{label}` was added"),
265            Self::Removed(label) => write!(f, "`{label}` was removed"),
266            Self::Changed(label) => write!(f, "`{label}` changed"),
267            Self::Member {
268                label,
269                from,
270                to,
271                name: _,
272            } => write!(
273                f,
274                "`{label}` moved from {} to {}",
275                from.as_deref().unwrap_or("no version"),
276                to.as_deref().unwrap_or("no version")
277            ),
278        }
279    }
280}
281
282impl Lockfile {
283    /// Parse `text` as `format`.
284    ///
285    /// # Errors
286    ///
287    /// Returns an error when the text does not parse, or an entry lacks the
288    /// fields its format requires, such as a `Cargo.lock` package without a
289    /// name.
290    pub fn parse(format: Format, text: &str) -> Result<Self> {
291        match format {
292            Format::Cargo => parse_cargo(text),
293            Format::Bun => parse_bun(text),
294            Format::Npm => parse_npm(text),
295            Format::Uv => parse_uv(text),
296        }
297    }
298
299    /// Every entry, in key order.
300    pub fn entries(&self) -> impl Iterator<Item = &Entry> {
301        self.entries.values()
302    }
303
304    /// The workspace members.
305    pub fn members(&self) -> impl Iterator<Item = &Entry> {
306        self.entries().filter(|entry| entry.member)
307    }
308
309    /// Whether a bump of `member` cannot change this `format` lockfile at
310    /// `lock_dir`, so its owner has nothing to do.
311    ///
312    /// That applies only when the lockfile has an entry for the member and no
313    /// such entry follows the member's version. A member with no entry stays
314    /// uncertain in every format, so the owner runs. A `Cargo.lock` or
315    /// `uv.lock` may name it by a name this check does not know. That happens
316    /// when a virtual workspace's bump moves members that inherit its version.
317    /// In a `bun.lock` or `package-lock.json`, a directory that fails to
318    /// match must not skip a needed refresh either.
319    #[must_use]
320    pub fn is_idle_for(&self, format: Format, lock_dir: &Path, member: &Member) -> bool {
321        let mut recorded = self
322            .members()
323            .filter(|entry| member.records(format, lock_dir, &entry.name, &entry.label))
324            .peekable();
325        let found = recorded.peek().is_some();
326        found && recorded.all(|entry| !entry.follows_version(format))
327    }
328
329    /// What changed from `self` to `newer`, in key order. An entry whose key
330    /// carries its version, a registry package's, shows a version move as
331    /// one [`Change::Changed`] instead of a removal and an addition.
332    #[must_use]
333    pub fn compare(&self, newer: &Self) -> Vec<Change> {
334        let mut changes = Vec::new();
335        if self.header != newer.header {
336            changes.push(Change::Header);
337        }
338        let mut removed = BTreeSet::new();
339        let mut added = BTreeSet::new();
340        for (key, old) in &self.entries {
341            match newer.entries.get(key) {
342                None => {
343                    removed.insert(old.label.clone());
344                }
345                Some(new) if new == old => {}
346                Some(new)
347                    if new.member && old.member && new.name == old.name && new.rest == old.rest =>
348                {
349                    changes.push(Change::Member {
350                        label: new.label.clone(),
351                        name: new.name.clone(),
352                        from: old.version.clone(),
353                        to: new.version.clone(),
354                    });
355                }
356                Some(new) => changes.push(Change::Changed(new.label.clone())),
357            }
358        }
359        for (key, new) in &newer.entries {
360            if !self.entries.contains_key(key) {
361                added.insert(new.label.clone());
362            }
363        }
364        for label in removed.intersection(&added) {
365            changes.push(Change::Changed(label.clone()));
366        }
367        changes.extend(removed.difference(&added).cloned().map(Change::Removed));
368        changes.extend(added.difference(&removed).cloned().map(Change::Added));
369        changes
370    }
371
372    fn insert(&mut self, key: String, entry: Entry) -> Result<()> {
373        let label = entry.label.clone();
374        if self.entries.insert(key, entry).is_some() {
375            bail!("`{label}` is locked twice");
376        }
377        Ok(())
378    }
379}
380
381/// Shared TOML `[[package]]` lockfile parser used by `Cargo.lock` and
382/// `uv.lock`.
383fn parse_toml_lock(
384    text: &str,
385    label: &str,
386    is_member: impl Fn(&Value) -> bool,
387    scrub_deps: impl Fn(&mut Map<String, Value>, &BTreeSet<String>),
388) -> Result<Lockfile> {
389    let doc: toml_edit::DocumentMut = text.parse().with_context(|| format!("parse {label}"))?;
390    let mut top = to_json_table(doc.as_table());
391    let packages = take_array(&mut top, "package");
392    let members: BTreeSet<String> = packages
393        .iter()
394        .filter(|package| is_member(package))
395        .filter_map(|package| package.get("name").and_then(Value::as_str))
396        .map(str::to_owned)
397        .collect();
398    let mut lock = Lockfile {
399        header: canonical(&Value::Object(top)),
400        entries: BTreeMap::new(),
401    };
402    for package in packages {
403        let member = is_member(&package);
404        let Value::Object(mut fields) = package else {
405            bail!("{label}: a [[package]] is not a table");
406        };
407        let name = take_string(&mut fields, "name")
408            .with_context(|| format!("{label}: a package has no name"))?;
409        let version = take_string(&mut fields, "version");
410        scrub_deps(&mut fields, &members);
411        let key = if member {
412            format!("member {name}")
413        } else {
414            format!(
415                "{name} {} {}",
416                version.as_deref().unwrap_or_default(),
417                fields.get("source").map_or_default(canonical)
418            )
419        };
420        let entry = Entry {
421            label: name.clone(),
422            name,
423            version,
424            member,
425            rest: canonical(&Value::Object(fields)),
426        };
427        lock.insert(key, entry)?;
428    }
429    Ok(lock)
430}
431
432/// `Cargo.lock`: `[[package]]` tables. A member has no `source`, and neither
433/// has a path dependency outside the workspace, so both read as members here.
434/// The content check explains a member's move only by a version the plan
435/// moves, so a path dependency that moves still fails there. A
436/// dependency reference is `name`, `name version`, or `name version
437/// (source)`; a reference to a member drops its version.
438fn parse_cargo(text: &str) -> Result<Lockfile> {
439    parse_toml_lock(
440        text,
441        "Cargo.lock",
442        |package| package.get("source").is_none(),
443        |fields, members| {
444            if let Some(Value::Array(dependencies)) = fields.get_mut("dependencies") {
445                for dependency in dependencies.iter_mut() {
446                    if let Value::String(reference) = dependency
447                        && !reference.contains('(')
448                        && let Some(target) = reference.split_whitespace().next()
449                        && members.contains(target)
450                    {
451                        *reference = target.to_owned();
452                    }
453                }
454            }
455        },
456    )
457}
458
459/// `uv.lock`: `[[package]]` tables. A member's `source` is `editable` or
460/// `virtual`. A dependency is an inline table; a reference to a member drops
461/// its `version`.
462fn parse_uv(text: &str) -> Result<Lockfile> {
463    parse_toml_lock(
464        text,
465        "uv.lock",
466        |package| {
467            package.get("source").is_some_and(|source| {
468                source.get("editable").is_some() || source.get("virtual").is_some()
469            })
470        },
471        |fields, members| {
472            for list in ["dependencies", "dev-dependencies", "optional-dependencies"] {
473                if let Some(value) = fields.get_mut(list) {
474                    drop_member_versions(value, members);
475                }
476            }
477        },
478    )
479}
480
481/// Drop `version` from each `{ name = ... }` reference to a member, at any
482/// depth: `optional-dependencies` and `dev-dependencies` nest the lists in a
483/// table of groups.
484fn drop_member_versions(value: &mut Value, members: &BTreeSet<String>) {
485    match value {
486        Value::Array(items) => {
487            for item in items {
488                drop_member_versions(item, members);
489            }
490        }
491        Value::Object(fields) => {
492            let names_member = fields
493                .get("name")
494                .and_then(Value::as_str)
495                .is_some_and(|name| members.contains(name));
496            if names_member {
497                fields.remove("version");
498            } else {
499                for nested in fields.values_mut() {
500                    drop_member_versions(nested, members);
501                }
502            }
503        }
504        Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => {}
505    }
506}
507
508/// `bun.lock`: each `workspaces` entry is a member, keyed by its path; each
509/// `packages` entry is a resolved package, whose first element is
510/// `name@version` or `name@workspace:path`.
511fn parse_bun(text: &str) -> Result<Lockfile> {
512    let value = jsonc_parser::parse_to_value(text, &jsonc_parser::ParseOptions::default())
513        .context("parse bun.lock")?
514        .context("bun.lock is empty")?;
515    let Value::Object(mut top) = from_jsonc(value) else {
516        bail!("bun.lock is not an object");
517    };
518    let workspaces = take_object(&mut top, "workspaces");
519    let packages = take_object(&mut top, "packages");
520    let mut lock = Lockfile {
521        header: canonical(&Value::Object(top)),
522        entries: BTreeMap::new(),
523    };
524    for (path, workspace) in workspaces {
525        let Value::Object(mut fields) = workspace else {
526            bail!("bun.lock: workspace `{path}` is not an object");
527        };
528        let name = take_string(&mut fields, "name").unwrap_or_default();
529        let version = take_string(&mut fields, "version");
530        let label = if path.is_empty() {
531            ".".to_owned()
532        } else {
533            path.clone()
534        };
535        let entry = Entry {
536            label,
537            name,
538            version,
539            member: true,
540            rest: canonical(&Value::Object(fields)),
541        };
542        lock.insert(format!("workspace {path}"), entry)?;
543    }
544    for (key, package) in packages {
545        let ident = package
546            .get(0)
547            .and_then(Value::as_str)
548            .with_context(|| format!("bun.lock: package `{key}` has no name@version"))?;
549        let (name, resolved) = ident
550            .rsplit_once('@')
551            .filter(|(name, _)| !name.is_empty())
552            .with_context(|| format!("bun.lock: package `{key}` is `{ident}`, not name@version"))?;
553        let version = (!resolved.starts_with("workspace:")).then(|| resolved.to_owned());
554        let entry = Entry {
555            label: key.clone(),
556            name: name.to_owned(),
557            version,
558            member: false,
559            rest: canonical(&package),
560        };
561        lock.insert(format!("package {key}"), entry)?;
562    }
563    Ok(lock)
564}
565
566/// `package-lock.json`, lockfile version 2 or 3: `packages` keyed by path.
567/// `""` is the root, and a path outside `node_modules/` is a workspace member.
568/// A `node_modules/` path is an installed package or a link to a member, and a
569/// link records no version. The top-level `version` is the root's.
570fn parse_npm(text: &str) -> Result<Lockfile> {
571    let Value::Object(mut top) =
572        serde_json::from_str::<Value>(text).context("parse package-lock.json")?
573    else {
574        bail!("package-lock.json is not an object");
575    };
576    let packages = take_object(&mut top, "packages");
577    let root_version = take_string(&mut top, "version");
578    let mut lock = Lockfile {
579        header: canonical(&Value::Object(top)),
580        entries: BTreeMap::new(),
581    };
582    for (path, package) in packages {
583        let Value::Object(mut fields) = package else {
584            bail!("package-lock.json: `{path}` is not an object");
585        };
586        let member = path.is_empty() || !path.contains("node_modules/");
587        let version = take_string(&mut fields, "version");
588        if path.is_empty() && version != root_version {
589            bail!("package-lock.json: the top-level version differs from the root package's");
590        }
591        let name = fields
592            .get("name")
593            .and_then(Value::as_str)
594            .map(str::to_owned)
595            .or_else(|| {
596                path.rsplit_once("node_modules/")
597                    .map(|(_, name)| name.to_owned())
598            })
599            .unwrap_or_else(|| path.rsplit('/').next().unwrap_or_default().to_owned());
600        let label = if path.is_empty() {
601            ".".to_owned()
602        } else {
603            path.clone()
604        };
605        let rest = if member {
606            canonical(&Value::Object(fields))
607        } else {
608            let mut whole = fields;
609            if let Some(version) = &version {
610                whole.insert("version".to_owned(), Value::String(version.clone()));
611            }
612            canonical(&Value::Object(whole))
613        };
614        let entry = Entry {
615            label,
616            name,
617            version,
618            member,
619            rest,
620        };
621        lock.insert(format!("path {path}"), entry)?;
622    }
623    Ok(lock)
624}
625
626fn take_string(fields: &mut Map<String, Value>, key: &str) -> Option<String> {
627    match fields.remove(key) {
628        Some(Value::String(text)) => Some(text),
629        Some(other) => {
630            fields.insert(key.to_owned(), other);
631            None
632        }
633        None => None,
634    }
635}
636
637fn take_array(fields: &mut Map<String, Value>, key: &str) -> Vec<Value> {
638    match fields.remove(key) {
639        Some(Value::Array(items)) => items,
640        Some(other) => {
641            fields.insert(key.to_owned(), other);
642            Vec::new()
643        }
644        None => Vec::new(),
645    }
646}
647
648fn take_object(fields: &mut Map<String, Value>, key: &str) -> Map<String, Value> {
649    match fields.remove(key) {
650        Some(Value::Object(object)) => object,
651        Some(other) => {
652            fields.insert(key.to_owned(), other);
653            Map::new()
654        }
655        None => Map::new(),
656    }
657}
658
659/// `value` as JSON with object keys sorted at every depth, so two copies
660/// that differ only in key order or formatting compare equal.
661fn canonical(value: &Value) -> String {
662    match value {
663        Value::Object(fields) => {
664            let sorted: BTreeMap<&String, String> = fields
665                .iter()
666                .map(|(key, value)| (key, canonical(value)))
667                .collect();
668            let body: Vec<String> = sorted
669                .into_iter()
670                .map(|(key, value)| format!("{}:{value}", Value::String(key.clone())))
671                .collect();
672            format!("{{{}}}", body.join(","))
673        }
674        Value::Array(items) => {
675            let body: Vec<String> = items.iter().map(canonical).collect();
676            format!("[{}]", body.join(","))
677        }
678        Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => value.to_string(),
679    }
680}
681
682fn from_jsonc(value: jsonc_parser::JsonValue<'_>) -> Value {
683    use jsonc_parser::JsonValue;
684    match value {
685        JsonValue::String(text) => Value::String(text.into_owned()),
686        JsonValue::Number(raw) => {
687            serde_json::from_str(raw).unwrap_or_else(|_| Value::String(raw.to_owned()))
688        }
689        JsonValue::Boolean(flag) => Value::Bool(flag),
690        JsonValue::Object(object) => Value::Object(
691            object
692                .into_iter()
693                .map(|(key, value)| (key.into_owned(), from_jsonc(value)))
694                .collect(),
695        ),
696        JsonValue::Array(items) => Value::Array(items.into_iter().map(from_jsonc).collect()),
697        JsonValue::Null => Value::Null,
698    }
699}
700
701fn to_json_table(table: &toml_edit::Table) -> Map<String, Value> {
702    table
703        .iter()
704        .filter_map(|(key, item)| item_as_json(item).map(|value| (key.to_owned(), value)))
705        .collect()
706}
707
708fn item_as_json(item: &toml_edit::Item) -> Option<Value> {
709    match item {
710        toml_edit::Item::None => None,
711        toml_edit::Item::Value(value) => Some(scalar_as_json(value)),
712        toml_edit::Item::Table(table) => Some(Value::Object(to_json_table(table))),
713        toml_edit::Item::ArrayOfTables(tables) => Some(Value::Array(
714            tables
715                .iter()
716                .map(|table| Value::Object(to_json_table(table)))
717                .collect(),
718        )),
719    }
720}
721
722fn scalar_as_json(value: &toml_edit::Value) -> Value {
723    match value {
724        toml_edit::Value::String(text) => Value::String(text.value().clone()),
725        toml_edit::Value::Integer(number) => Value::from(*number.value()),
726        toml_edit::Value::Float(number) => Value::from(*number.value()),
727        toml_edit::Value::Boolean(flag) => Value::Bool(*flag.value()),
728        toml_edit::Value::Datetime(when) => Value::String(when.value().to_string()),
729        toml_edit::Value::Array(items) => Value::Array(items.iter().map(scalar_as_json).collect()),
730        toml_edit::Value::InlineTable(table) => Value::Object(
731            table
732                .iter()
733                .map(|(key, value)| (key.to_owned(), scalar_as_json(value)))
734                .collect(),
735        ),
736    }
737}