Files
ianitor/crates/core/src/routes.rs
T

106 lines
3.2 KiB
Rust

// SPDX-License-Identifier: CPAL-1.0
// Copyright (c) 2026 Marek Novák. Part of Ianitor, under the Common Public Attribution
// License 1.0: see LICENSE (its Exhibit A is this file's notice).
//! The shape of the routes repository: exactly `ianitor.toml` and `hosts/<hostname>.toml`,
//! regular files only. Anything else (other names, folders inside `hosts/`, symbolic links,
//! submodules, executables) is refused, so the repository can never hold something the
//! compilers do not read.
use crate::error::{ValidationError, reason};
use crate::validate::check_hostname;
/// The site file at the root of the repository.
pub const SITE_FILE: &str = "ianitor.toml";
/// The folder holding one file per host.
pub const HOSTS_DIR: &str = "hosts";
/// Most host files one repository may hold.
pub const MAX_HOST_FILES: usize = 1000;
/// What a tree entry is, as git reports it (`git ls-tree` modes).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EntryKind {
/// Mode 100644.
File,
/// Mode 100755.
Executable,
/// Mode 120000.
Symlink,
/// Mode 160000.
Submodule,
}
/// A path the repository may hold.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RoutePath {
Site,
Host { hostname: String },
}
/// The path of the file for `hostname`.
pub fn host_path(hostname: &str) -> String {
format!("{HOSTS_DIR}/{hostname}.toml")
}
/// Check one path of the repository tree (as listed recursively, `/`-separated).
pub fn check_path(path: &str, kind: EntryKind) -> Result<RoutePath, ValidationError> {
let bad = |reason| ValidationError::UnexpectedFile {
file: path.to_owned(),
reason,
};
if kind != EntryKind::File {
return Err(bad(reason::PATH_KIND));
}
if path == SITE_FILE {
return Ok(RoutePath::Site);
}
let Some(rest) = path.strip_prefix("hosts/") else {
return Err(bad(reason::PATH_LAYOUT));
};
if rest.contains(['/', '\\']) {
return Err(bad(reason::PATH_SUBDIR));
}
let Some(hostname) = rest.strip_suffix(".toml") else {
return Err(bad(reason::PATH_NAME));
};
if check_hostname(hostname).is_err() {
return Err(bad(reason::PATH_NAME));
}
Ok(RoutePath::Host {
hostname: hostname.to_owned(),
})
}
/// Check a whole tree listing. Returns every problem; at most [`MAX_HOST_FILES`] host files.
pub fn check_tree<'a>(
entries: impl IntoIterator<Item = (&'a str, EntryKind)>,
) -> Result<(), Vec<ValidationError>> {
let mut errors = Vec::new();
let mut hosts = 0usize;
let mut site = false;
for (path, kind) in entries {
match check_path(path, kind) {
Ok(RoutePath::Site) => site = true,
Ok(RoutePath::Host { .. }) => hosts += 1,
Err(e) => errors.push(e),
}
}
if !site {
errors.push(ValidationError::MissingField {
file: SITE_FILE.into(),
field: "(the file itself)".into(),
});
}
if hosts > MAX_HOST_FILES {
errors.push(ValidationError::UnexpectedFile {
file: HOSTS_DIR.into(),
reason: "more than 1000 host files",
});
}
if errors.is_empty() {
Ok(())
} else {
Err(errors)
}
}