about summary refs log tree commit diff
path: root/shovel/src/main.rs
blob: 68a4a5043329b5217809fda0f3a686ee845bfcb2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
use std::fmt;

use camino::{Utf8Path, Utf8PathBuf};
use confindent::Confindent;
use scurvy::{Argument, Scurvy, arg, formula::Utf8PathFormula};

fn main() {
	let args = vec![
		arg!(["conf", "c"] = "path"),
		arg!(["webroot", "r"] = "path"),
	];
	let scurvy = Scurvy::make(args);

	let webroot: Utf8PathBuf = match scurvy.parse("webroot", Utf8PathFormula::new()) {
		Some(path) => path,
		None => {
			let conf_path = scurvy.parse_req("conf", Utf8PathFormula::new());
			let conf = Confindent::from_file(conf_path).unwrap();
			conf.child_parse("Webroot").unwrap()
		}
	};

	let rootdir = map_directory(webroot.clone(), &webroot);
	println!("{rootdir}")
}

fn map_directory(root: Utf8PathBuf, path: &Utf8Path) -> Directory {
	let name = path.file_name().unwrap();

	let mut files = vec![];
	let mut children = vec![];
	let mut has_dirfile = false;

	for res_entry in path.read_dir_utf8().unwrap() {
		let entry = res_entry.unwrap();
		let entry_path = entry.path().to_owned();
		let entry_name = entry.file_name();
		let entry_stem = entry_path.file_stem().unwrap();

		let entry_meta = entry.metadata().unwrap();
		if entry_meta.is_file() {
			if let Some("html") = entry_path.extension() {
				if name == entry_stem {
					has_dirfile = true;
					continue;
				}

				files.push(Page {
					name: entry_name.to_owned(),
					path: entry_path,
				});
			}
		} else if entry_meta.is_dir() {
			let entry_dir = map_directory(root.clone(), &entry_path);
			if entry_dir.files.len() > 0 {
				children.push(entry_dir);
			}
		}
	}

	Directory {
		name: name.to_owned(),
		path: path.to_owned(),
		has_dirfile,
		files,
		children,
		root,
	}
}

struct Directory {
	name: String,
	path: Utf8PathBuf,
	has_dirfile: bool,

	files: Vec<Page>,
	children: Vec<Directory>,

	root: Utf8PathBuf,
}

impl fmt::Display for Directory {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		let root = &self.root;

		writeln!(f, "# {}", rel_or_abs(root, &self.path))?;

		for page in &self.files {
			writeln!(f, "{}", rel_or_abs(root, &page.path))?;
		}

		for subdir in &self.children {
			write!(f, "\n{subdir}")?;
		}

		Ok(())
	}
}

fn rel_or_abs<'r, 'p>(root: &'r Utf8Path, path: &'p Utf8Path) -> &'p Utf8Path {
	path.strip_prefix(root).unwrap_or(path)
}

struct Page {
	name: String,
	path: Utf8PathBuf,
}