xtask_kit/latest_json/
mod.rs1use 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#[derive(Clone, Debug)]
10pub struct UpdateOptions {
11 pub version: String,
13 pub channel: String,
15 pub output: PathBuf,
17 pub existing: Option<PathBuf>,
19}
20
21pub 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
41pub 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}