Skip to main content

xtask_kit/latest_json/
mod.rs

1use std::path::{Path, PathBuf};
2
3use anyhow::{Context, Result};
4use serde_json::{Map, Value, json};
5use time::OffsetDateTime;
6use time::macros::format_description;
7
8/// Options for updating a channel-based `latest.json` file.
9#[derive(Clone, Debug)]
10pub struct UpdateOptions {
11    /// Release version, with or without a leading `v`.
12    pub version: String,
13    /// Update channel, for example `stable` or `beta`.
14    pub channel: String,
15    /// Output manifest path.
16    pub output: PathBuf,
17    /// Existing manifest to merge into.
18    pub existing: Option<PathBuf>,
19}
20
21/// Update or create a channel-based `latest.json` manifest.
22pub fn update(options: &UpdateOptions) -> Result<()> {
23    let mut data = load_existing(options.existing.as_deref())?;
24    let display_version = options.version.trim_start_matches('v');
25    data.insert(
26        options.channel.clone(),
27        json!({
28            "version": display_version,
29            "date": OffsetDateTime::now_utc()
30                .format(format_description!(
31                    "[year]-[month]-[day]T[hour]:[minute]:[second]Z"
32                ))
33                .context("format latest.json timestamp")?,
34        }),
35    );
36
37    let content = serde_json::to_string_pretty(&Value::Object(data))? + "\n";
38    crate::fs::write_string(&options.output, content)
39}
40
41/// Load an existing `latest.json` object, returning an empty map if the path is absent.
42pub fn load_existing(existing: Option<&Path>) -> Result<Map<String, Value>> {
43    let Some(existing) = existing.filter(|path| path.is_file()) else {
44        return Ok(Map::new());
45    };
46    let content = std::fs::read_to_string(existing)
47        .with_context(|| format!("read existing latest.json {}", existing.display()))?;
48    let value: Value = serde_json::from_str(&content)
49        .with_context(|| format!("parse existing latest.json {}", existing.display()))?;
50    Ok(value.as_object().cloned().unwrap_or_default())
51}