use crate::scaffold::{HtlPin, dep_value, t_mise};
use anyhow::{Context, Result};
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode};
use toml_edit::{DocumentMut, Value};
const PATCH_BLOCK: &str = "[patch.crates-io]\n\
htl = { path = \"/path/to/htl/crates/htl\" }\n\
htl-core = { path = \"/path/to/htl/crates/htl-core\" }\n\
htl-macros = { path = \"/path/to/htl/crates/htl-macros\" }\n";
pub(crate) fn cmd_pin(htl: &str, dir: Option<PathBuf>, no_update: bool) -> Result<ExitCode> {
let pin = HtlPin::parse(Some(htl))?;
let pin = match pin {
HtlPin::Path(p) => match canonical_checkout(&p)? {
Some(checkout) => HtlPin::Path(checkout),
None => {
eprintln!(
"htl pin: path:{} is not an htl checkout (no crates/htl/Cargo.toml there)",
p.display()
);
return Ok(ExitCode::from(2));
}
},
other => other,
};
let start = dir.unwrap_or_else(|| PathBuf::from("."));
let Some(root) = htl::dts::find_cargo_package_root(&start) else {
eprintln!(
"htl pin: no Cargo.toml with a [package] at or above {}",
start.display()
);
return Ok(ExitCode::from(2));
};
let manifest_path = root.join("Cargo.toml");
let mut cargo_doc = fs::read_to_string(&manifest_path)
.with_context(|| format!("reading {}", manifest_path.display()))?
.parse::<DocumentMut>()
.with_context(|| format!("parsing {}", manifest_path.display()))?;
let htl_item = cargo_doc
.get("dependencies")
.and_then(|i| i.as_table_like())
.and_then(|d| d.get("htl"));
if htl_item.is_none() {
eprintln!(
"htl pin: Cargo.toml has no htl dependency; this is not a project htl new \
wrote (nothing to move)"
);
return Ok(ExitCode::from(2));
}
let Some(htl_features) = recognised_features(htl_item) else {
return Ok(refuse_unrecognised(htl_item, "htl"));
};
let old_htl = value_text(htl_item.expect("checked is_none() above"));
let new_htl = dep_value(&pin.keys_for("htl"), &refs(&htl_features));
let has_mq = cargo_doc
.get("dependencies")
.and_then(|i| i.as_table_like())
.map(|d| d.contains_key("htl-mq"))
.unwrap_or(false);
let mq_item = if has_mq {
cargo_doc
.get("dependencies")
.and_then(|i| i.as_table_like())
.and_then(|d| d.get("htl-mq"))
} else {
None
};
let mq_features = if has_mq {
match recognised_features(mq_item) {
Some(f) => Some(f),
None => return Ok(refuse_unrecognised(mq_item, "htl-mq")),
}
} else {
None
};
let old_mq = mq_item.map(value_text);
let new_mq = mq_features
.as_ref()
.map(|f| dep_value(&pin.keys_for("htl-mq"), &refs(f)));
let mise_path = root.join("mise.toml");
if mise_path.exists() && !mise_path.is_file() {
eprintln!(
"htl pin: {} exists but is not a regular file; nothing was changed",
mise_path.display()
);
return Ok(ExitCode::from(2));
}
let mise_existed = mise_path.is_file();
let mise_new_body = match &pin {
HtlPin::Release(_) => {
Some(t_mise(&pin).expect("a Release pin always has a mise.toml body"))
}
HtlPin::Main | HtlPin::Path(_) => None,
};
let mise_before = read_if_present(&mise_path)?;
let mise_unchanged = match &mise_new_body {
Some(body) => mise_before.as_deref() == Some(body.as_str()),
None => !mise_existed,
};
let htl_toml_path = root.join("htl.toml");
let htl_toml_before = read_if_present(&htl_toml_path)?;
let mut htl_toml_doc = htl_toml_before
.as_deref()
.map(|t| {
t.parse::<DocumentMut>()
.with_context(|| format!("parsing {}", htl_toml_path.display()))
})
.transpose()?;
let had_toolchain_key = htl_toml_doc
.as_ref()
.and_then(|d| d.get("toolchain"))
.and_then(|i| i.as_table_like())
.map(|t| t.contains_key("htl"))
.unwrap_or(false);
let mut toolchain_report = "unchanged".to_string();
if had_toolchain_key {
let doc = htl_toml_doc
.as_mut()
.expect("had_toolchain_key implies a parsed doc");
let tc = doc
.get_mut("toolchain")
.and_then(|i| i.as_table_like_mut())
.expect("had_toolchain_key just confirmed [toolchain] is a table");
match &pin {
HtlPin::Release(v) => {
set_value_keeping_decor(tc, "htl", Value::from(v.clone())).with_context(|| {
format!(
"{}'s [toolchain] htl is not a plain value",
htl_toml_path.display()
)
})?;
toolchain_report = format!("[toolchain] htl = \"{v}\"");
}
HtlPin::Main | HtlPin::Path(_) => {
tc.remove("htl");
if tc.is_empty() {
doc.as_table_mut().remove("toolchain");
}
toolchain_report = "key removed".to_string();
}
}
if doc.to_string()
== *htl_toml_before
.as_ref()
.expect("had_toolchain_key implies text")
{
toolchain_report = "unchanged".to_string();
}
}
let mut cargo_changed = false;
if new_htl != old_htl {
let deps = cargo_doc
.get_mut("dependencies")
.and_then(|i| i.as_table_like_mut())
.context("no [dependencies] table in Cargo.toml")?;
set_value_keeping_decor(
deps,
"htl",
new_htl.parse().with_context(|| {
format!("parsing the value htl pin computed for htl: {new_htl}")
})?,
)?;
cargo_changed = true;
}
if let (Some(old), Some(new)) = (&old_mq, &new_mq)
&& old != new
{
let deps = cargo_doc
.get_mut("dependencies")
.and_then(|i| i.as_table_like_mut())
.context("no [dependencies] table in Cargo.toml")?;
set_value_keeping_decor(
deps,
"htl-mq",
new.parse()
.with_context(|| format!("parsing the value htl pin computed for htl-mq: {new}"))?,
)?;
cargo_changed = true;
}
if cargo_changed {
fs::write(&manifest_path, cargo_doc.to_string())
.with_context(|| format!("writing {}", manifest_path.display()))?;
}
let mut cargo_line = format!("htl pin: Cargo.toml htl: {old_htl} -> {new_htl}");
if let Some(new_mq) = &new_mq {
cargo_line.push_str(&format!(
" htl-mq: {} -> {new_mq}",
old_mq.as_deref().unwrap_or("")
));
}
eprintln!("{cargo_line}");
let mise_report = if mise_unchanged {
"unchanged"
} else {
match &mise_new_body {
Some(body) => {
fs::write(&mise_path, body)
.with_context(|| format!("writing {}", mise_path.display()))?;
"written"
}
None => {
fs::remove_file(&mise_path)
.with_context(|| format!("removing {}", mise_path.display()))?;
"removed"
}
}
};
eprintln!("htl pin: mise.toml: {mise_report}");
if toolchain_report != "unchanged" {
let after = htl_toml_doc
.as_ref()
.expect("toolchain_report changed implies a parsed doc")
.to_string();
fs::write(&htl_toml_path, &after)
.with_context(|| format!("writing {}", htl_toml_path.display()))?;
}
eprintln!("htl pin: htl.toml: {toolchain_report}");
let mut names = vec!["htl", "htl-core", "htl-macros"];
if has_mq {
names.push("htl-mq");
}
if no_update {
let flags = names
.iter()
.map(|p| format!("-p {p}"))
.collect::<Vec<_>>()
.join(" ");
eprintln!("htl pin: --no-update; run `cargo update {flags}` to update Cargo.lock");
return Ok(ExitCode::SUCCESS);
}
let mut cmd = Command::new(cargo());
cmd.arg("update");
for p in &names {
cmd.args(["-p", p]);
}
cmd.current_dir(&root);
let status = cmd
.status()
.with_context(|| format!("running `cargo update` in {}", root.display()))?;
if !status.success() {
eprintln!(
"htl pin: cargo update failed (exit {}); the files above are rewritten — fix \
the cause and run the command again",
status.code().unwrap_or(-1)
);
return Ok(ExitCode::from(2));
}
Ok(ExitCode::SUCCESS)
}
fn canonical_checkout(p: &Path) -> Result<Option<PathBuf>> {
let cwd = std::env::current_dir().context("reading the current directory")?;
let absolute = if p.is_absolute() {
p.to_path_buf()
} else {
cwd.join(p)
};
let Ok(canonical) = fs::canonicalize(&absolute) else {
return Ok(None);
};
if canonical
.join("crates")
.join("htl")
.join("Cargo.toml")
.is_file()
{
Ok(Some(canonical))
} else {
Ok(None)
}
}
fn read_if_present(path: &Path) -> Result<Option<String>> {
match fs::read_to_string(path) {
Ok(s) => Ok(Some(s)),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e).with_context(|| format!("reading {}", path.display())),
}
}
fn set_value_keeping_decor(
table: &mut dyn toml_edit::TableLike,
key: &str,
new: Value,
) -> Result<()> {
let slot = table
.get_mut(key)
.and_then(|i| i.as_value_mut())
.with_context(|| format!("{key} is not a plain value"))?;
let decor = slot.decor().clone();
let mut new = new;
*new.decor_mut() = decor;
*slot = new;
Ok(())
}
fn cargo() -> std::ffi::OsString {
std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into())
}
fn recognised_features(item: Option<&toml_edit::Item>) -> Option<Vec<String>> {
match item?.as_value()? {
Value::String(_) => Some(Vec::new()),
Value::InlineTable(t) => {
let mut keys: Vec<&str> = t
.iter()
.map(|(k, _)| k)
.filter(|k| *k != "features")
.collect();
keys.sort_unstable();
if !matches!(keys.as_slice(), ["version"] | ["branch", "git"] | ["path"]) {
return None;
}
match t.get("features") {
None => Some(Vec::new()),
Some(Value::Array(arr)) => {
let mut feats = Vec::with_capacity(arr.len());
for v in arr.iter() {
feats.push(v.as_str()?.to_string());
}
Some(feats)
}
Some(_) => None,
}
}
_ => None,
}
}
fn value_text(item: &toml_edit::Item) -> String {
let mut v = item
.as_value()
.expect("recognised_features(Some(_)) returned Some only for a Value")
.clone();
v.decor_mut().clear();
v.to_string()
}
fn refuse_unrecognised(item: Option<&toml_edit::Item>, name: &str) -> ExitCode {
let found = match item {
None => format!("no {name} dependency in [dependencies]"),
Some(toml_edit::Item::Value(v)) => {
let mut v = v.clone();
v.decor_mut().clear();
format!("{name} = {v}")
}
Some(_) => format!("[dependencies.{name}]"),
};
eprintln!(
"htl pin: Cargo.toml's {name} line is not one the scaffold wrote ({found}); write the \
patch by hand:\n\n{PATCH_BLOCK}\n\
All three, not one; then `cargo update -p htl -p htl-core -p htl-macros` once, and \
the same command again with the block deleted to go back."
);
ExitCode::from(2)
}
fn refs(features: &[String]) -> Vec<&str> {
features.iter().map(String::as_str).collect()
}