use crate::fsutil;
use crate::{LovelyError, Result};
use std::collections::BTreeMap;
use std::fs;
use std::io::Read;
use std::path::{Path, PathBuf};
pub const DEFAULT_CHANNEL: &str = "love-11-plus";
pub const MANIFEST_FILE: &str = "runtime.txt";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RuntimeManifest {
pub target: String,
pub channel: String,
pub kind: RuntimeKind,
pub source: String,
pub sha256: String,
pub path: PathBuf,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RuntimeKind {
File,
Directory,
}
impl RuntimeManifest {
pub fn parse(text: &str) -> Result<Self> {
let mut values = BTreeMap::new();
for (index, raw_line) in text.lines().enumerate() {
let line = raw_line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let Some((key, value)) = line.split_once('=') else {
return Err(LovelyError::Config(format!(
"runtime manifest line {} is not a key/value pair",
index + 1
)));
};
values.insert(key.trim().to_string(), unquote(value.trim()));
}
let kind = match take(&values, "kind")?.as_str() {
"file" => RuntimeKind::File,
"directory" => RuntimeKind::Directory,
other => {
return Err(LovelyError::Config(format!(
"unsupported runtime kind {other:?}"
)));
}
};
Ok(Self {
target: take(&values, "target")?,
channel: take(&values, "channel")?,
kind,
source: take(&values, "source")?,
sha256: take(&values, "sha256")?,
path: PathBuf::from(take(&values, "path")?),
})
}
pub fn to_text(&self) -> String {
format!(
r#"# Generated by Lovely. Describes one cached runtime artifact.
target = "{target}"
channel = "{channel}"
kind = "{kind}"
source = "{source}"
sha256 = "{sha256}"
path = "{path}"
"#,
target = escape(&self.target),
channel = escape(&self.channel),
kind = match self.kind {
RuntimeKind::File => "file",
RuntimeKind::Directory => "directory",
},
source = escape(&self.source),
sha256 = escape(&self.sha256),
path = escape(&fsutil::normalize_slashes(&self.path)),
)
}
}
#[derive(Debug, Clone)]
pub struct RuntimeRegistry {
root: PathBuf,
}
impl RuntimeRegistry {
pub fn new() -> Self {
Self {
root: cache_dir().join("runtimes"),
}
}
#[cfg(test)]
pub fn at(root: PathBuf) -> Self {
Self { root }
}
pub fn root(&self) -> &Path {
&self.root
}
pub fn install_local(
&self,
target: &str,
channel: &str,
source: &Path,
expected_sha256: Option<&str>,
) -> Result<RuntimeManifest> {
validate_target(target)?;
if source.to_string_lossy().starts_with("http://")
|| source.to_string_lossy().starts_with("https://")
{
return Err(LovelyError::Command(
"URL runtime fetching is not implemented yet; download the upstream artifact and pass a local path".to_string(),
));
}
if !source.exists() {
return Err(LovelyError::Command(format!(
"runtime source does not exist: {}",
source.display()
)));
}
let kind = if source.is_dir() {
RuntimeKind::Directory
} else {
RuntimeKind::File
};
let sha256 = hash_path(source)?;
if let Some(expected) = expected_sha256 {
if !expected.eq_ignore_ascii_case(&sha256) {
return Err(LovelyError::Command(format!(
"runtime checksum mismatch for {}: expected {}, got {}",
source.display(),
expected,
sha256
)));
}
}
let target_dir = self.target_dir(channel, target);
if target_dir.exists() {
fs::remove_dir_all(&target_dir).map_err(|err| LovelyError::io(&target_dir, err))?;
}
fsutil::ensure_dir(&target_dir)?;
let relative_path = match kind {
RuntimeKind::File => {
let file_name = source
.file_name()
.ok_or_else(|| LovelyError::Command("runtime file has no name".to_string()))?;
let destination = target_dir.join(file_name);
fsutil::copy_file(source, &destination)?;
PathBuf::from(file_name)
}
RuntimeKind::Directory => {
let destination = target_dir.join("files");
fsutil::copy_dir_contents(source, &destination)?;
PathBuf::from("files")
}
};
let manifest = RuntimeManifest {
target: target.to_string(),
channel: channel.to_string(),
kind,
source: source.display().to_string(),
sha256,
path: relative_path,
};
fsutil::write_string(&target_dir.join(MANIFEST_FILE), &manifest.to_text())?;
Ok(manifest)
}
pub fn find(&self, target: &str, channel: &str) -> Result<Option<CachedRuntime>> {
let manifest_path = self.target_dir(channel, target).join(MANIFEST_FILE);
if !manifest_path.is_file() {
return Ok(None);
}
let manifest = RuntimeManifest::parse(&fsutil::read_to_string(&manifest_path)?)?;
let path = self.target_dir(channel, target).join(&manifest.path);
Ok(Some(CachedRuntime { manifest, path }))
}
pub fn list(&self) -> Result<Vec<CachedRuntime>> {
let mut out = Vec::new();
if !self.root.exists() {
return Ok(out);
}
for channel in fs::read_dir(&self.root).map_err(|err| LovelyError::io(&self.root, err))? {
let channel = channel.map_err(LovelyError::plain_io)?;
if !channel.file_type().map_err(LovelyError::plain_io)?.is_dir() {
continue;
}
for target in fs::read_dir(channel.path()).map_err(LovelyError::plain_io)? {
let target = target.map_err(LovelyError::plain_io)?;
if !target.file_type().map_err(LovelyError::plain_io)?.is_dir() {
continue;
}
let manifest_path = target.path().join(MANIFEST_FILE);
if manifest_path.is_file() {
let manifest =
RuntimeManifest::parse(&fsutil::read_to_string(&manifest_path)?)?;
let path = target.path().join(&manifest.path);
out.push(CachedRuntime { manifest, path });
}
}
}
out.sort_by(|a, b| {
(&a.manifest.channel, &a.manifest.target)
.cmp(&(&b.manifest.channel, &b.manifest.target))
});
Ok(out)
}
fn target_dir(&self, channel: &str, target: &str) -> PathBuf {
self.root.join(channel).join(target)
}
}
impl Default for RuntimeRegistry {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CachedRuntime {
pub manifest: RuntimeManifest,
pub path: PathBuf,
}
pub fn cache_dir() -> PathBuf {
if let Some(path) = std::env::var_os("LOVELY_CACHE_DIR") {
return PathBuf::from(path);
}
if let Some(home) = std::env::var_os("HOME") {
return PathBuf::from(home).join(".cache/lovely");
}
PathBuf::from(".lovely/cache")
}
pub fn validate_target(target: &str) -> Result<()> {
match target {
"web" | "windows" | "macos" | "linux" => Ok(()),
_ => Err(LovelyError::Command(format!(
"unknown runtime target {target:?}; expected web, windows, macos, or linux"
))),
}
}
pub fn hash_path(path: &Path) -> Result<String> {
if path.is_dir() {
hash_directory(path)
} else {
hash_file(path)
}
}
pub fn hash_file(path: &Path) -> Result<String> {
let mut file = fs::File::open(path).map_err(|err| LovelyError::io(path, err))?;
let mut sha = Sha256::new();
let mut buffer = [0u8; 64 * 1024];
loop {
let read = file.read(&mut buffer).map_err(LovelyError::plain_io)?;
if read == 0 {
break;
}
sha.update(&buffer[..read]);
}
Ok(sha.finish_hex())
}
fn hash_directory(path: &Path) -> Result<String> {
let mut sha = Sha256::new();
sha.update(b"lovely-directory-runtime-v1\0");
for file in fsutil::collect_files(path)? {
let rel = fsutil::relative_path(path, &file)?;
let name = fsutil::normalize_slashes(&rel);
sha.update(name.as_bytes());
sha.update(b"\0");
let mut bytes = fs::File::open(&file).map_err(|err| LovelyError::io(&file, err))?;
let mut buffer = [0u8; 64 * 1024];
loop {
let read = bytes.read(&mut buffer).map_err(LovelyError::plain_io)?;
if read == 0 {
break;
}
sha.update(&buffer[..read]);
}
sha.update(b"\0");
}
Ok(sha.finish_hex())
}
fn take(values: &BTreeMap<String, String>, key: &str) -> Result<String> {
values
.get(key)
.cloned()
.ok_or_else(|| LovelyError::Config(format!("runtime manifest missing {key}")))
}
fn unquote(value: &str) -> String {
if value.starts_with('"') && value.ends_with('"') && value.len() >= 2 {
value[1..value.len() - 1].replace("\\\"", "\"")
} else {
value.to_string()
}
}
fn escape(input: &str) -> String {
input.replace('\\', "\\\\").replace('"', "\\\"")
}
struct Sha256 {
state: [u32; 8],
length_bits: u64,
buffer: Vec<u8>,
}
impl Sha256 {
fn new() -> Self {
Self {
state: [
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab,
0x5be0cd19,
],
length_bits: 0,
buffer: Vec::with_capacity(64),
}
}
fn update(&mut self, input: &[u8]) {
self.length_bits = self.length_bits.wrapping_add((input.len() as u64) * 8);
self.buffer.extend_from_slice(input);
while self.buffer.len() >= 64 {
let mut block = [0u8; 64];
block.copy_from_slice(&self.buffer[..64]);
self.compress(&block);
self.buffer.drain(..64);
}
}
fn finish_hex(mut self) -> String {
self.buffer.push(0x80);
while self.buffer.len() % 64 != 56 {
self.buffer.push(0);
}
self.buffer
.extend_from_slice(&self.length_bits.to_be_bytes());
let blocks = self.buffer.clone();
for block in blocks.chunks(64) {
let mut fixed = [0u8; 64];
fixed.copy_from_slice(block);
self.compress(&fixed);
}
self.state
.iter()
.map(|word| format!("{word:08x}"))
.collect::<Vec<_>>()
.join("")
}
fn compress(&mut self, block: &[u8; 64]) {
const K: [u32; 64] = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4,
0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe,
0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f,
0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116,
0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
0xc67178f2,
];
let mut w = [0u32; 64];
for (i, chunk) in block.chunks_exact(4).take(16).enumerate() {
w[i] = u32::from_be_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
}
for i in 16..64 {
let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
w[i] = w[i - 16]
.wrapping_add(s0)
.wrapping_add(w[i - 7])
.wrapping_add(s1);
}
let mut a = self.state[0];
let mut b = self.state[1];
let mut c = self.state[2];
let mut d = self.state[3];
let mut e = self.state[4];
let mut f = self.state[5];
let mut g = self.state[6];
let mut h = self.state[7];
for i in 0..64 {
let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
let ch = (e & f) ^ ((!e) & g);
let temp1 = h
.wrapping_add(s1)
.wrapping_add(ch)
.wrapping_add(K[i])
.wrapping_add(w[i]);
let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
let maj = (a & b) ^ (a & c) ^ (b & c);
let temp2 = s0.wrapping_add(maj);
h = g;
g = f;
f = e;
e = d.wrapping_add(temp1);
d = c;
c = b;
b = a;
a = temp1.wrapping_add(temp2);
}
self.state[0] = self.state[0].wrapping_add(a);
self.state[1] = self.state[1].wrapping_add(b);
self.state[2] = self.state[2].wrapping_add(c);
self.state[3] = self.state[3].wrapping_add(d);
self.state[4] = self.state[4].wrapping_add(e);
self.state[5] = self.state[5].wrapping_add(f);
self.state[6] = self.state[6].wrapping_add(g);
self.state[7] = self.state[7].wrapping_add(h);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sha256_known_value() {
let mut sha = Sha256::new();
sha.update(b"abc");
assert_eq!(
sha.finish_hex(),
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
);
}
#[test]
fn manifest_round_trips() {
let manifest = RuntimeManifest {
target: "web".to_string(),
channel: DEFAULT_CHANNEL.to_string(),
kind: RuntimeKind::Directory,
source: "/tmp/runtime".to_string(),
sha256: "abc".to_string(),
path: PathBuf::from("files"),
};
assert_eq!(
RuntimeManifest::parse(&manifest.to_text()).unwrap(),
manifest
);
}
}