#!/usr/bin/env -S cargo +nightly -Zscript
---cargo
[package]
edition = "2021"
---
use std::{env, fs};
const README: &str = "README.md";
const FILE_TO_INSERT: &str = "examples/example-json.rs";
const START_PATTERN: &str = "<!-- START_INSERT: examples/example-json.rs -->\n";
const END_PATTERN: &str = "<!-- END_INSERT: examples/example-json.rs -->\n";
fn main() -> Result<(), ()> {
let only_check = match env::args().nth(1).as_deref() {
Some("--check") => true,
Some(_) => panic!("invalid first CLI argument"),
None => false,
};
let mut file_to_insert = fs::read_to_string(FILE_TO_INSERT)
.expect("could not read file to insert");
let crate_manifest = fs::read_to_string("Cargo.toml").unwrap();
let version_line = crate_manifest
.lines()
.find(|l| l.starts_with("version = "))
.unwrap();
file_to_insert = file_to_insert.replace(r#"path = "..""#, &version_line);
let readme_file = fs::read_to_string(README).expect("could not read the README.md file");
let mut output = readme_file.clone();
let start_bytes = output.find(START_PATTERN).unwrap();
let end_bytes = output.find(END_PATTERN).unwrap();
output.replace_range(
start_bytes..end_bytes,
&format!("{START_PATTERN}```rust\n{file_to_insert}```\n"),
);
if only_check {
if output == readme_file {
Ok(())
} else {
panic!("README.md is not up to date");
}
} else {
fs::write(README, output).map_err(|_| ())
}
}