resticview/src/envfile.rs

228 lines
7.6 KiB
Rust

//! Scanning and parsing of restic credential env files.
//!
//! Env files are plain `KEY=VALUE` files (optionally with an `export ` prefix,
//! quotes and `#` comments). They are parsed literally — no shell evaluation.
use std::collections::HashMap;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
/// A single env file discovered in the env directory, with parsed variables.
#[derive(Debug, Clone)]
pub struct EnvFile {
/// Path relative to the env dir, e.g. `.env` or `.work/.env`. Used for display.
pub rel_path: String,
/// Parsed KEY=VALUE pairs.
pub vars: HashMap<String, String>,
}
impl EnvFile {
pub fn get(&self, key: &str) -> Option<&str> {
self.vars.get(key).map(String::as_str)
}
/// Value of RESTIC_REPOSITORY, for display in the picker and repo panel.
pub fn repository(&self) -> &str {
self.get("RESTIC_REPOSITORY")
.unwrap_or("(no RESTIC_REPOSITORY)")
}
}
/// Parse env file content: `KEY=VALUE` lines with an optional `export ` prefix,
/// single/double quotes, `#` comments and empty lines. No shell evaluation.
pub fn parse(content: &str) -> HashMap<String, String> {
let mut vars = HashMap::new();
for line in content.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let line = line
.strip_prefix("export ")
.map(str::trim_start)
.unwrap_or(line);
let Some((key, value)) = line.split_once('=') else {
continue;
};
let key = key.trim();
if key.is_empty() {
continue;
}
vars.insert(key.to_string(), parse_value(value.trim()));
}
vars
}
/// Strip surrounding quotes; for unquoted values strip a trailing ` # comment`.
fn parse_value(raw: &str) -> String {
let bytes = raw.as_bytes();
if raw.len() >= 2 {
let (first, last) = (bytes[0], bytes[bytes.len() - 1]);
if (first == b'"' && last == b'"') || (first == b'\'' && last == b'\'') {
return raw[1..raw.len() - 1].to_string();
}
}
match raw.find(" #") {
Some(i) => raw[..i].trim_end().to_string(),
None => raw.to_string(),
}
}
fn is_hidden(name: &str) -> bool {
name.starts_with('.')
}
/// Scan `dir` for env files: every hidden file (`.*`) directly in `dir`, plus
/// hidden files one level deep inside hidden subdirectories (`.*/`). Results
/// are sorted by relative path.
pub fn scan(dir: &Path) -> io::Result<Vec<EnvFile>> {
let mut paths: Vec<PathBuf> = Vec::new();
for entry in fs::read_dir(dir)? {
let entry = entry?;
let name = entry.file_name();
let Some(name) = name.to_str() else { continue };
let file_type = entry.file_type()?;
if file_type.is_file() && is_hidden(name) {
paths.push(entry.path());
} else if file_type.is_dir() && is_hidden(name) {
let Ok(sub_entries) = fs::read_dir(entry.path()) else {
continue;
};
for sub in sub_entries {
let Ok(sub) = sub else { continue };
let sub_name = sub.file_name();
let Some(sub_name) = sub_name.to_str() else { continue };
if let Ok(ft) = sub.file_type()
&& ft.is_file()
&& is_hidden(sub_name)
{
paths.push(sub.path());
}
}
}
}
let mut files: Vec<EnvFile> = paths
.into_iter()
.filter_map(|path| {
let content = fs::read_to_string(&path).ok()?;
let rel_path = path
.strip_prefix(dir)
.unwrap_or(&path)
.to_string_lossy()
.into_owned();
Some(EnvFile {
rel_path,
vars: parse(&content),
})
})
.collect();
files.sort_by(|a, b| a.rel_path.cmp(&b.rel_path));
Ok(files)
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
#[test]
fn parse_simple_pairs() {
let vars = parse("RESTIC_REPOSITORY=s3:example/repo\nRESTIC_PASSWORD=secret\n");
assert_eq!(vars["RESTIC_REPOSITORY"], "s3:example/repo");
assert_eq!(vars["RESTIC_PASSWORD"], "secret");
}
#[test]
fn parse_export_prefix() {
let vars = parse("export RESTIC_PASSWORD=secret\nexport SPACED=value\n");
assert_eq!(vars["RESTIC_PASSWORD"], "secret");
assert_eq!(vars["SPACED"], "value");
}
#[test]
fn parse_quoted_values() {
let vars = parse(
"DOUBLE=\"with spaces # not a comment\"\nSINGLE='also # kept'\nEMPTY=\"\"\n",
);
assert_eq!(vars["DOUBLE"], "with spaces # not a comment");
assert_eq!(vars["SINGLE"], "also # kept");
assert_eq!(vars["EMPTY"], "");
}
#[test]
fn parse_comments_and_empty_lines() {
let vars = parse("# a comment\n\n \nKEY=value # trailing comment\n");
assert_eq!(vars.len(), 1);
assert_eq!(vars["KEY"], "value");
}
#[test]
fn parse_hash_inside_unquoted_value_is_kept() {
let vars = parse("PASS=abc#def\n");
assert_eq!(vars["PASS"], "abc#def");
}
#[test]
fn parse_value_containing_equals() {
let vars = parse("AWS_TOKEN=abc=def==\n");
assert_eq!(vars["AWS_TOKEN"], "abc=def==");
}
#[test]
fn parse_ignores_garbage_lines() {
let vars = parse("no equals sign\n=emptykey\nOK=yes\n");
assert_eq!(vars.len(), 1);
assert_eq!(vars["OK"], "yes");
}
#[test]
fn scan_finds_hidden_files_flat_and_in_hidden_subdirs() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
fs::write(root.join(".env"), "A=1").unwrap();
fs::write(root.join(".ble"), "A=2").unwrap();
fs::write(root.join(".hetzner"), "A=3").unwrap();
fs::write(root.join("backup.sh"), "A=4").unwrap(); // non-hidden: excluded
fs::write(root.join("backup.log"), "A=5").unwrap(); // non-hidden: excluded
fs::write(root.join("excludes.txt"), "A=6").unwrap(); // non-hidden: excluded
// hidden subdir, one level deep: included
let work = root.join(".work");
fs::create_dir(&work).unwrap();
fs::write(work.join(".env"), "B=1").unwrap();
fs::write(work.join(".token"), "B=2").unwrap();
fs::write(work.join("notes.txt"), "B=3").unwrap(); // non-hidden: excluded
// visible subdir: excluded
let visible = root.join("sub");
fs::create_dir(&visible).unwrap();
fs::write(visible.join(".env"), "C=1").unwrap();
// two levels deep: excluded
let deep = work.join(".deep");
fs::create_dir(&deep).unwrap();
fs::write(deep.join(".env"), "D=1").unwrap();
let files = scan(root).unwrap();
let rels: Vec<&str> = files.iter().map(|f| f.rel_path.as_str()).collect();
assert_eq!(
rels,
vec![".ble", ".env", ".hetzner", ".work/.env", ".work/.token"]
);
assert_eq!(files[1].vars["A"], "1");
assert_eq!(files[3].vars["B"], "1");
}
#[test]
fn repository_helper() {
let tmp = tempfile::tempdir().unwrap();
fs::write(tmp.path().join(".env"), "RESTIC_REPOSITORY=/backup\n").unwrap();
let files = scan(tmp.path()).unwrap();
assert_eq!(files[0].repository(), "/backup");
fs::write(tmp.path().join(".env"), "OTHER=1\n").unwrap();
let files = scan(tmp.path()).unwrap();
assert_eq!(files[0].repository(), "(no RESTIC_REPOSITORY)");
}
}