#[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, HashSet};
use std::path::Path;
struct Row {
line: String,
key: String,
outcome: Option<bool>,
casebook: 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"),
casebook: false,
});
}
Ok(Row {
line: line.to_string(),
key: format!("l\t{line}"),
outcome: None,
casebook: kind == "casebook",
})
}
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], dest: &Path) -> Result<Plan, String> {
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,
};
let mut adds_cases = false;
let mut conflicting_outcomes = HashSet::new();
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;
conflicting_outcomes.insert(r.key.as_str());
}
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());
adds_cases |= r.casebook;
}
if adds_cases {
if super::is_team_bank(dest) {
return Err("cannot sync personal casebooks into a team bank".into());
}
if !conflicting_outcomes.is_empty() {
for line in &plan.missing {
check_case_verdicts(line, &conflicting_outcomes)?;
}
}
let prospective = dst
.iter()
.map(|r| r.line.as_str())
.chain(plan.missing.iter().map(String::as_str))
.collect::<Vec<_>>()
.join("\n");
super::fold_text(&prospective, &dest.display().to_string(), |_, _, _, _| {})?;
}
Ok(plan)
}
fn check_case_verdicts(line: &str, conflicting: &HashSet<&str>) -> Result<(), String> {
let v = parse_json(line)?;
if v.get("kind").and_then(Json::as_str) != Some("casebook") {
return Ok(());
}
let id = v.get("id").and_then(Json::as_str).unwrap_or("");
let Some(Json::Arr(examples)) = v.get("casebook").and_then(|b| b.get("examples")) else {
return Err("invalid casebook examples".into());
};
for reference in examples
.iter()
.filter_map(|row| row.get("ref").and_then(Json::as_str))
{
if conflicting.contains(format!("o\t{id}\t{reference}").as_str()) {
return Err(format!(
"conflicting verdict for case {reference}; nothing copied"
));
}
}
Ok(())
}
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, dest)?;
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, a)?, plan(&ra, &rb, b)?);
Ok((from_b.missing.len(), from_a.missing.len(), from_b.conflicts))
}