link-cli 3.5.2

A CLI tool and reusable library for links manipulation backed by a LiNo-notation doublet storage engine.
Documentation
use anyhow::{ensure, Result};
use std::fs::{self, File, FileTimes};
use std::path::Path;
use std::process::{Command, Output};
use std::time::{Duration, SystemTime};
use tempfile::tempdir;

#[test]
fn plain_export_preserves_the_input_stores() -> Result<()> {
    let directory = tempdir()?;
    let state = directory.path().join("state");
    fs::create_dir(&state)?;
    let db = state.join("bot.links");
    let names = state.join("bot.names.links");
    let input = directory.path().join("input.lino");
    let expected = "(root: root root)\n";
    fs::write(&input, expected)?;
    ensure_success(
        &Command::new(env!("CARGO_BIN_EXE_clink"))
            .arg("--db")
            .arg(&db)
            .arg("--in")
            .arg(input)
            .output()?,
    )?;
    let old = SystemTime::UNIX_EPOCH + Duration::from_secs(1_600_000_000);
    let snapshot = [&db, &names].map(|path| -> Result<_> {
        File::options()
            .write(true)
            .open(path)?
            .set_times(FileTimes::new().set_modified(old))?;
        Ok((fs::read(path)?, fs::metadata(path)?.modified()?))
    });
    let [data, names_data] = snapshot;
    let export = |name: &str| -> Result<()> {
        let output = directory.path().join(name);
        ensure_success(
            &Command::new(env!("CARGO_BIN_EXE_clink"))
                .arg("--db")
                .arg(&db)
                .arg("--out")
                .arg(&output)
                .output()?,
        )?;
        assert_eq!(fs::read_to_string(output)?, expected);
        Ok(())
    };

    export("writable.lino")?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        for path in [&db, &names, &link_cli::lock_file_path(&db)] {
            fs::set_permissions(path, fs::Permissions::from_mode(0o400))?;
        }
        fs::set_permissions(&state, fs::Permissions::from_mode(0o500))?;
        let result = export("read-only.lino");
        fs::set_permissions(&state, fs::Permissions::from_mode(0o700))?;
        result?;
    }
    for (path, snapshot) in [(&db, data?), (&names, names_data?)] {
        assert_eq!(fs::read(path)?, snapshot.0, "{}", path.display());
        assert_eq!(
            fs::metadata(path)?.modified()?,
            snapshot.1,
            "{}",
            path.display()
        );
    }
    Ok(())
}

#[test]
fn export_alias_writes_numbered_references() -> Result<()> {
    let temp_dir = tempdir()?;
    let db_path = temp_dir.path().join("numbered.links");
    let output_path = temp_dir.path().join("numbered.lino");

    let output = run_clink(&db_path, "() ((1 1) (2 2))", false, &output_path)?;

    ensure_success(&output)?;
    assert_eq!(
        std::fs::read_to_string(&output_path)?,
        "(1: 1 1)\n(2: 2 2)\n"
    );

    Ok(())
}

#[test]
fn export_alias_writes_named_references() -> Result<()> {
    let temp_dir = tempdir()?;
    let db_path = temp_dir.path().join("named.links");
    let output_path = temp_dir.path().join("named.lino");

    let output = run_clink(&db_path, "() ((child: father mother))", true, &output_path)?;

    ensure_success(&output)?;
    assert_eq!(
        std::fs::read_to_string(&output_path)?,
        "(father: father father)\n(mother: mother mother)\n(child: father mother)\n"
    );

    Ok(())
}

#[test]
fn quoted_query_names_round_trip_through_export_and_query() -> Result<()> {
    let directory = tempdir()?;
    let source = directory.path().join("source.links");
    let text = directory.path().join("export.lino");
    let replay = directory.path().join("replay.lino");
    ensure_success(&run_query(&source, "() ((a: a a) (b: b b))")?)?;
    ensure_success(&run_clink(
        &source,
        "() ((zero: x \"0\") (one: x \"1\") (two: x '2') (large: x '99') (address: x 1))",
        true,
        &text,
    )?)?;
    let exported = std::fs::read_to_string(text)?;
    for expected in [
        "(zero: x '0')",
        "(one: x '1')",
        "(two: x '2')",
        "(large: x '99')",
        "(address: x a)",
    ] {
        assert!(
            exported.contains(expected),
            "missing {expected}: {exported}"
        );
    }
    ensure_success(&run_clink(
        &directory.path().join("destination.links"),
        &format!("() ({exported})"),
        false,
        &replay,
    )?)?;
    assert_eq!(exported, std::fs::read_to_string(replay)?);
    Ok(())
}

#[test]
fn structure_option_renders_left_branch_with_indexes() -> Result<()> {
    let temp_dir = tempdir()?;
    let db_path = temp_dir.path().join("structure.links");

    ensure_success(&run_query(&db_path, "() ((1: 1 1))")?)?;
    ensure_success(&run_query(&db_path, "() ((2: 1 2))")?)?;
    ensure_success(&run_query(&db_path, "() ((3: 2 1))")?)?;
    ensure_success(&run_query(&db_path, "() ((4: 3 2))")?)?;

    let output = run_structure(&db_path, 4)?;

    ensure_success(&output)?;
    assert_eq!(
        String::from_utf8_lossy(&output.stdout),
        "(4: (3: (2: (1: 1 1) 2) 1) 2)\n"
    );

    Ok(())
}

fn run_clink(
    db_path: &Path,
    query: &str,
    auto_create_missing_references: bool,
    output_path: &Path,
) -> Result<Output> {
    let mut command = Command::new(env!("CARGO_BIN_EXE_clink"));
    command.arg("--db").arg(db_path);
    if auto_create_missing_references {
        command.arg("--auto-create-missing-references");
    }

    Ok(command
        .arg(query)
        .arg("--export")
        .arg(output_path)
        .output()?)
}

fn run_query(db_path: &Path, query: &str) -> Result<Output> {
    Ok(Command::new(env!("CARGO_BIN_EXE_clink"))
        .arg("--db")
        .arg(db_path)
        .arg(query)
        .output()?)
}

fn run_structure(db_path: &Path, structure: u32) -> Result<Output> {
    Ok(Command::new(env!("CARGO_BIN_EXE_clink"))
        .arg("--db")
        .arg(db_path)
        .arg("--structure")
        .arg(structure.to_string())
        .output()?)
}

fn ensure_success(output: &Output) -> Result<()> {
    ensure!(
        output.status.success(),
        "clink failed with status {:?}\nstdout:\n{}\nstderr:\n{}",
        output.status.code(),
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    Ok(())
}