use nadi_plugin::nadi_internal_plugin;
#[nadi_internal_plugin]
mod files {
use crate::prelude::*;
use nadi_core::nadi_plugin::{env_func, node_func};
use std::io::Write;
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
fn file_exists(path: &Path, min_lines: Option<usize>) -> bool {
if let Some(ml) = min_lines {
match std::fs::File::open(path) {
Ok(f) => BufReader::new(f).lines().nth(ml).is_some(),
_ => false,
}
} else {
path.exists()
}
}
#[env_func]
fn line(
path: PathBuf,
line: usize,
) -> std::io::Result<Option<String>> {
let f = std::fs::File::open(path)?;
BufReader::new(f)
.lines()
.nth(line - 1)
.map_or(Ok(None), |v| v.map(Some))
}
#[env_func]
fn exists(
path: PathBuf,
min_lines: Option<usize>,
) -> bool {
file_exists(&path, min_lines)
}
#[node_func]
fn exists(
node: &NodeInner,
path: Template,
min_lines: Option<usize>,
) -> anyhow::Result<bool> {
let p = path.render(node)?;
Ok(file_exists(p.as_ref(), min_lines))
}
#[env_func]
fn from_file(
path: PathBuf,
default: Option<String>,
) -> anyhow::Result<String> {
let contents = if let Some(val) = default {
std::fs::read_to_string(path).unwrap_or(val)
} else {
std::fs::read_to_string(path)?
};
Ok(contents)
}
#[env_func(append = false, terminate = "\n")]
fn to_file(
contents: String,
path: PathBuf,
append: bool,
terminate: String,
) -> anyhow::Result<()> {
let mut file = std::fs::OpenOptions::new()
.write(true)
.create(true)
.append(append)
.truncate(!append)
.open(path)?;
write!(file, "{}{}", contents, terminate)?;
Ok(())
}
}