rust setup

This commit is contained in:
zipfriis
2026-10-24 09:56:57 +02:00
parent cb50869808
commit 4a4a2685ca
4 changed files with 130 additions and 0 deletions
+117
View File
@@ -0,0 +1,117 @@
use std::collections::HashMap;
use std::env;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, Copy, PartialEq)]
enum NoteKind {
Txt,
Md,
Typ,
}
impl NoteKind {
fn from_ext(ext: &str) -> Option<Self> {
match ext {
"txt" => Some(Self::Txt),
"md" => Some(Self::Md),
"typ" => Some(Self::Typ),
_ => None,
}
}
}
#[derive(Debug)]
struct Note {
path: PathBuf,
kind: NoteKind,
tags: Vec<String>, // folder names above this note
}
#[derive(Debug, Default)]
struct Vault {
notes: Vec<Note>, // nodes
tags: HashMap<String, Vec<usize>>, // tag -> indices into `notes` (the edges)
images: Vec<PathBuf>, // files found in ".images" folders
}
fn scan_dir(root: &Path) -> io::Result<Vault> {
let mut vault = Vault::default();
walk(root, root, &mut vault)?;
Ok(vault)
}
fn walk(root: &Path, dir: &Path, vault: &mut Vault) -> io::Result<()> {
let in_images = dir.file_name().and_then(|n| n.to_str()) == Some(".images");
for entry in fs::read_dir(dir)? {
let path = entry?.path();
if path.is_dir() {
// skip hidden folders, except ".images"
let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
if name.starts_with('.') && name != ".images" {
continue;
}
walk(root, &path, vault)?;
continue;
}
let ext = path
.extension()
.and_then(|e| e.to_str())
.unwrap_or("")
.to_lowercase();
if in_images {
if matches!(ext.as_str(), "svg" | "webp") {
vault.images.push(path);
}
continue;
}
if let Some(kind) = NoteKind::from_ext(&ext) {
// folders between root and the file become tags
let tags: Vec<String> = path
.strip_prefix(root)
.ok()
.and_then(|rel| rel.parent())
.map(|p| {
p.components()
.map(|c| c.as_os_str().to_string_lossy().into_owned())
.collect()
})
.unwrap_or_default();
let idx = vault.notes.len();
for tag in &tags {
vault.tags.entry(tag.clone()).or_default().push(idx);
}
vault.notes.push(Note { path, kind, tags });
}
}
Ok(())
}
fn main() -> io::Result<()> {
let dir = env::args().nth(1).unwrap_or_else(|| ".".to_string());
let root = Path::new(&dir);
if !root.is_dir() {
eprintln!("'{}' is not a directory", root.display());
std::process::exit(1);
}
let vault = scan_dir(root)?;
for (tag, ids) in &vault.tags {
println!("#{tag}");
for &i in ids {
println!(" {}", vault.notes[i].path.display());
}
}
println!("{} notes, {} images", vault.notes.len(), vault.images.len());
Ok(())
}