#[cfg(windows)]
#[allow(dead_code)]
const SYS_CURL: &str = "C:\\Windows\\System32\\curl.exe";
#[cfg(not(windows))]
#[allow(dead_code)]
const SYS_CURL: &str = "curl";
#[allow(dead_code)]
fn _helix_allowed(var: &str, what: &str) -> bool {
let ok = std::env::var(var).map(|v| v == "1").unwrap_or(false);
if !ok {
eprintln!("helix: BLOCKED {} -- permission denied (set {}=1 to allow; `hxc run` allows by default, a `hxc build`/`export-rust` binary does not)", what, var);
}
ok
}
#[cfg(windows)]
#[allow(dead_code)]
fn _nw_exec(mut c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_RUN", "process execution") {
std::process::exit(13);
}
use std::os::windows::process::CommandExt;
c.creation_flags(0x08000000);
c
}
#[cfg(not(windows))]
#[allow(dead_code)]
fn _nw_exec(c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_RUN", "process execution") {
std::process::exit(13);
}
c
}
#[cfg(windows)]
#[allow(dead_code)]
fn _nw_net(mut c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_NET", "network access") {
std::process::exit(13);
}
use std::os::windows::process::CommandExt;
c.creation_flags(0x08000000);
c
}
#[cfg(not(windows))]
#[allow(dead_code)]
fn _nw_net(c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_NET", "network access") {
std::process::exit(13);
}
c
}
use super::{journal, parse_json, Json};
use std::collections::HashMap;
use std::path::Path;
struct Row {
line: String,
key: String,
outcome: Option<bool>,
}
pub struct Report {
pub source: usize,
pub added: usize,
pub had: usize,
pub conflicts: usize,
}
pub struct Plan {
pub missing: Vec<String>,
pub had: usize,
pub conflicts: usize,
}
fn row(line: &str, label: &str, n: usize) -> Result<Row, String> {
let line = line.trim();
let v = parse_json(line).map_err(|e| format!("{label}:{n}: {e}"))?;
let kind = v
.get("kind")
.and_then(Json::as_str)
.ok_or_else(|| format!("{label}:{n}: event has no string kind"))?;
let s = |k: &str| v.get(k).and_then(Json::as_str).unwrap_or("");
if matches!(kind, "hit" | "miss") && !s("outcome_id").is_empty() {
return Ok(Row {
line: line.to_string(),
key: format!("o\t{}\t{}", s("id"), s("outcome_id")),
outcome: Some(kind == "hit"),
});
}
Ok(Row {
line: line.to_string(),
key: format!("l\t{line}"),
outcome: None,
})
}
fn read_rows(path: &Path) -> Result<Vec<Row>, String> {
let text = journal::read(path)?;
let label = path.display().to_string();
let mut rows = Vec::new();
for (n, line) in text
.lines()
.enumerate()
.filter(|(_, l)| !l.trim().is_empty())
{
rows.push(row(line, &label, n + 1)?);
}
Ok(rows)
}
fn plan(src: &[Row], dst: &[Row]) -> Plan {
let mut verdicts: HashMap<&str, Option<bool>> = HashMap::new();
let mut copies: HashMap<&str, usize> = HashMap::new();
for r in dst {
if r.outcome.is_some() {
verdicts.entry(&r.key).or_insert(r.outcome);
} else {
*copies.entry(&r.key).or_insert(0) += 1;
}
}
let mut plan = Plan {
missing: Vec::new(),
had: 0,
conflicts: 0,
};
for r in src {
if r.outcome.is_some() {
if let Some(held) = verdicts.get(r.key.as_str()) {
if *held == r.outcome {
plan.had += 1;
} else {
plan.conflicts += 1;
}
continue;
}
verdicts.insert(&r.key, r.outcome);
} else {
if let Some(n) = copies.get_mut(r.key.as_str()).filter(|n| **n > 0) {
*n -= 1;
plan.had += 1;
continue;
}
}
plan.missing.push(r.line.clone());
}
plan
}
fn same_file(a: &Path, b: &Path) -> bool {
match (a.canonicalize(), b.canonicalize()) {
(Ok(x), Ok(y)) => x == y,
_ => a == b,
}
}
pub fn pull(dest: &Path, source: &Path) -> Result<Report, String> {
if !source.try_exists().map_err(|e| e.to_string())? {
return Err(format!("source bank {} does not exist", source.display()));
}
if same_file(dest, source) {
return Err("source and destination are the same bank".into());
}
let _lock = journal::identity_lock(dest)?;
let src = read_rows(source)?;
let dst = read_rows(dest)?;
let plan = plan(&src, &dst);
journal::append_many(
dest,
&plan.missing.iter().map(String::as_str).collect::<Vec<_>>(),
)?;
Ok(Report {
source: src.len(),
added: plan.missing.len(),
had: plan.had,
conflicts: plan.conflicts,
})
}
pub fn status(a: &Path, b: &Path) -> Result<(usize, usize, usize), String> {
if !b.try_exists().map_err(|e| e.to_string())? {
return Err(format!("bank {} does not exist", b.display()));
}
let (ra, rb) = (read_rows(a)?, read_rows(b)?);
let (from_b, from_a) = (plan(&rb, &ra), plan(&ra, &rb));
Ok((from_b.missing.len(), from_a.missing.len(), from_b.conflicts))
}