use std::collections::HashSet;
use std::fmt;
use std::fs::{self, OpenOptions};
use std::io::{self, Write};
use std::path::Path;
use crate::BoxError;
use crate::graph::Graph;
use crate::plugin::{PublishTag, destination};
use crate::plugin_graph::shipped;
pub fn is_safe_relative_path(path: &str) -> bool {
!path.is_empty()
&& path.len() <= 255
&& !path.chars().any(is_refused_char)
&& path.split('/').all(is_safe_segment)
}
fn is_refused_char(c: char) -> bool {
c.is_control() || matches!(c, '\\' | ':' | '<' | '>' | '"' | '|' | '?' | '*')
}
fn is_safe_segment(segment: &str) -> bool {
!segment.is_empty()
&& segment.len() <= 128
&& segment != "."
&& segment != ".."
&& !segment.ends_with('.')
&& !segment.ends_with(' ')
&& !is_device_name(segment)
}
fn is_device_name(segment: &str) -> bool {
let stem = segment
.split_once('.')
.map_or(segment, |(stem, _)| stem)
.trim_end_matches(' ')
.to_ascii_uppercase();
match stem.as_bytes() {
b"CON" | b"PRN" | b"AUX" | b"NUL" | b"CONIN$" | b"CONOUT$" => true,
[b'C', b'O', b'M', digit] | [b'L', b'P', b'T', digit] => digit.is_ascii_digit(),
[b'C', b'O', b'M', 0xC2, last] | [b'L', b'P', b'T', 0xC2, last] => {
matches!(*last, 0xB9 | 0xB2 | 0xB3)
}
_ => false,
}
}
pub(crate) fn is_locale_path(path: &str) -> bool {
let Some((locale, _)) = path.split_once('/') else {
return false;
};
let mut parts = locale.split('-');
parts.next().is_some_and(|language| {
(2..=8).contains(&language.len()) && language.bytes().all(|b| b.is_ascii_alphabetic())
}) && parts.all(|part| {
(1..=8).contains(&part.len()) && part.bytes().all(|b| b.is_ascii_alphanumeric())
})
}
pub(crate) fn first_case_collision<'a>(
paths: impl IntoIterator<Item = &'a str>,
) -> Option<&'a str> {
let mut lower = HashSet::new();
let mut upper = HashSet::new();
paths.into_iter().find(|path| {
let seen_lower = !lower.insert(path.to_lowercase());
let seen_upper = !upper.insert(path.to_uppercase());
seen_lower || seen_upper
})
}
pub(crate) fn first_file_and_folder<'a>(paths: &[&'a str]) -> Option<(&'a str, &'a str)> {
let folded: Vec<(String, String)> = paths
.iter()
.map(|path| {
(
format!("{}/", path.to_lowercase()),
format!("{}/", path.to_uppercase()),
)
})
.collect();
paths
.iter()
.zip(&folded)
.find_map(|(&file, (lower, upper))| {
paths.iter().find_map(|&inside| {
(inside.to_lowercase().starts_with(lower.as_str())
|| inside.to_uppercase().starts_with(upper.as_str()))
.then_some((file, inside))
})
})
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Published {
Written,
Kept,
WouldBeWritten,
WouldBeKept,
WouldBeReplaced,
}
impl Published {
pub fn line(&self, path: &str) -> String {
let outcome = match self {
Published::Written => "written",
Published::Kept => "exists, kept (use --force to replace it)",
Published::WouldBeWritten => "would be written",
Published::WouldBeKept => "exists, would be kept (use --force to replace it)",
Published::WouldBeReplaced => "exists, would be replaced",
};
format!("{path}: {outcome}")
}
}
#[derive(Debug)]
pub struct PublishRefused(String);
impl fmt::Display for PublishRefused {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for PublishRefused {}
pub fn publish_files(
root: &Path,
files: &[(&str, &[u8])],
force: bool,
dry_run: bool,
) -> Result<Vec<(String, Published)>, PublishRefused> {
let mut files = files.to_vec();
files.sort_by_key(|&(path, _)| path);
if let Some(&(path, _)) = files
.iter()
.find(|&&(path, _)| !is_safe_relative_path(path))
{
return Err(PublishRefused(format!(
"{path} is not a safe relative path; nothing was written"
)));
}
let paths: Vec<&str> = files.iter().map(|&(path, _)| path).collect();
if let Some(path) = first_case_collision(paths.iter().copied()) {
return Err(PublishRefused(format!(
"{path} is the same file as another one on a disk that ignores case; nothing was written"
)));
}
if let Some((file, inside)) = first_file_and_folder(&paths) {
return Err(PublishRefused(format!(
"{file} would be both a file and the folder of {inside}; nothing was written"
)));
}
let mut outcomes = Vec::with_capacity(files.len());
for &(path, _) in &files {
let published = match (file_exists(root, path)?, force, dry_run) {
(false, _, false) | (true, true, false) => Published::Written,
(false, _, true) => Published::WouldBeWritten,
(true, false, false) => Published::Kept,
(true, false, true) => Published::WouldBeKept,
(true, true, true) => Published::WouldBeReplaced,
};
outcomes.push((path.to_owned(), published));
}
if dry_run {
return Ok(outcomes);
}
let to_write: Vec<(&str, &[u8])> = files
.iter()
.zip(&outcomes)
.filter(|(_, (_, published))| *published == Published::Written)
.map(|(&file, _)| file)
.collect();
let Some(&(first, _)) = to_write.first() else {
return Ok(outcomes);
};
let real_root = fs::canonicalize(root).map_err(|error| cannot_write(first, &error))?;
for (path, bytes) in to_write {
write_file(root, &real_root, path, bytes)?;
}
Ok(outcomes)
}
fn file_exists(root: &Path, path: &str) -> Result<bool, PublishRefused> {
for (end, _) in path.match_indices('/') {
let folder = &path[..end];
match fs::symlink_metadata(root.join(folder)) {
Ok(metadata) => {
if let Some(problem) = folder_problem(folder, &metadata) {
return Err(PublishRefused(format!("{problem}; nothing was written")));
}
}
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(false),
Err(error) => return Err(cannot_write(path, &error)),
}
}
match fs::symlink_metadata(root.join(path)) {
Ok(metadata) if metadata.file_type().is_symlink() => Err(inside_a_link(path)),
Ok(metadata) if metadata.is_dir() => Err(PublishRefused(format!(
"{path} is a folder where a file would be written; nothing was written"
))),
Ok(_) => Ok(true),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
Err(error) => Err(cannot_write(path, &error)),
}
}
fn folder_problem(folder: &str, metadata: &fs::Metadata) -> Option<String> {
if metadata.file_type().is_symlink() {
Some(format!("{folder} is a symbolic link or inside one"))
} else if metadata.is_dir() {
None
} else {
Some(format!("{folder} is a file where a folder is needed"))
}
}
fn changed_while_writing(problem: &str, path: &str) -> PublishRefused {
PublishRefused(format!(
"{problem}; it changed while publishing, and the files before {path} were written"
))
}
fn write_file(
root: &Path,
real_root: &Path,
path: &str,
bytes: &[u8],
) -> Result<(), PublishRefused> {
for (end, _) in path.match_indices('/') {
let folder = &path[..end];
match fs::create_dir(root.join(folder)) {
Ok(()) => {}
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
let metadata = fs::symlink_metadata(root.join(folder))
.map_err(|error| cannot_write(path, &error))?;
if let Some(problem) = folder_problem(folder, &metadata) {
return Err(changed_while_writing(&problem, path));
}
}
Err(error) => return Err(cannot_write(path, &error)),
}
}
let destination = root.join(path);
let name = path.rsplit_once('/').map_or(path, |(_, name)| name);
let temporary =
destination.with_file_name(format!(".{name}.navree-publish-{}.tmp", std::process::id()));
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.open(&temporary)
.map_err(|error| cannot_write(path, &error))?;
let written = file.write_all(bytes);
drop(file);
let folder = temporary.parent().unwrap_or(root);
let refused = match written.and_then(|()| fs::canonicalize(folder)) {
Err(error) => Some(cannot_write(path, &error)),
Ok(real_folder) if !real_folder.starts_with(real_root) => Some(changed_while_writing(
&format!("the folder of {path} is a symbolic link or inside one"),
path,
)),
Ok(_) => rename(&temporary, &destination)
.err()
.map(|error| cannot_write(path, &error)),
};
if let Some(refused) = refused {
let _ = fs::remove_file(&temporary);
return Err(refused);
}
Ok(())
}
#[cfg(windows)]
fn rename(from: &Path, to: &Path) -> io::Result<()> {
for wait in [10, 40, 160, 640] {
match fs::rename(from, to) {
Err(error) if matches!(error.raw_os_error(), Some(5 | 32)) => {
std::thread::sleep(std::time::Duration::from_millis(wait));
}
other => return other,
}
}
fs::rename(from, to)
}
#[cfg(not(windows))]
fn rename(from: &Path, to: &Path) -> io::Result<()> {
fs::rename(from, to)
}
fn inside_a_link(path: &str) -> PublishRefused {
PublishRefused(format!(
"{path} is a symbolic link or inside one; nothing was written"
))
}
fn cannot_write(path: &str, error: &io::Error) -> PublishRefused {
PublishRefused(format!("cannot write {path}: {error}"))
}
const USAGE: &str =
"usage: plugin:publish <plugin> [--tag views|locales|config|files] [--force] [--dry-run]";
const TAGS: &str = "tags: views, locales, config, files";
pub(crate) struct PublishRun {
pub(crate) config_args: Option<Vec<String>>,
pub(crate) dry_run: bool,
force: bool,
files: Vec<(String, &'static [u8])>,
checked: Vec<String>,
notes: Vec<String>,
}
pub(crate) fn run(graph: &Graph, args: &[String], root: &Path) -> Result<PublishRun, BoxError> {
let mut plugin: Option<&str> = None;
let mut tag: Option<&str> = None;
let (mut force, mut dry_run) = (false, false);
let mut words = args.iter();
while let Some(arg) = words.next() {
match arg.as_str() {
"--tag" if tag.is_none() => match words.next() {
Some(word) => tag = Some(word.as_str()),
None => return Err(format!("plugin:publish: --tag needs a tag ({TAGS})").into()),
},
"--force" => force = true,
"--dry-run" => dry_run = true,
word if plugin.is_none() && !word.starts_with('-') => plugin = Some(word),
other => {
return Err(
format!("plugin:publish: unexpected argument `{other}`; {USAGE}").into(),
);
}
}
}
let Some(word) = plugin else {
return Err(format!("plugin:publish: name the plugin to publish; {USAGE}").into());
};
let (tags, config): (Vec<PublishTag>, bool) = match tag {
None => (PublishTag::ALL.to_vec(), true),
Some("config") => (Vec::new(), true),
Some(name) => match PublishTag::from_name(name) {
Some(tag) => (vec![tag], false),
None => {
return Err(format!("plugin:publish: unknown tag `{name}` ({TAGS})").into());
}
},
};
let report = graph.plugins_report();
let found = report
.plugins
.iter()
.find(|plugin| plugin.info.namespace == word)
.or_else(|| {
report
.plugins
.iter()
.find(|plugin| plugin.info.name == word)
});
let Some(found) = found else {
let namespaces: Vec<&str> = report
.plugins
.iter()
.map(|plugin| plugin.info.namespace)
.collect();
let known = if namespaces.is_empty() {
"none".to_owned()
} else {
namespaces.join(", ")
};
return Err(
format!("plugin:publish: no plugin is named `{word}` (plugins: {known})").into(),
);
};
let (name, namespace) = (found.info.name, found.info.namespace);
let mut files: Vec<(String, &'static [u8])> = Vec::new();
for &m in &graph.order {
let module = &graph.modules[m];
if module.plugin.as_ref().map(|info| info.name) != Some(name) {
continue;
}
for publishable in shipped(module) {
let tag = publishable.tag();
if tags.contains(&tag) {
files.extend(
publishable
.files()
.map(|(path, bytes)| (destination(tag, namespace, path), bytes)),
);
}
}
}
let has_config = graph.has_command("config:publish");
let mut notes = Vec::new();
let checked = if files.is_empty() {
match tag {
Some(asked) if asked != "config" => {
notes.push(format!(
"{asked}: plugin `{namespace}` has nothing to publish"
));
}
None if !has_config => {
notes.push(format!(
"{namespace}: plugin `{namespace}` has nothing to publish"
));
}
_ => {}
}
Vec::new()
} else {
publish_lines(root, &files, force, true)?
};
let mut config_args = None;
if config {
if !has_config {
notes
.push("config: the app has no ConfigModule, so no section is published".to_owned());
} else if dry_run {
notes.push(format!(
"config: would run config:publish --plugin {namespace}"
));
} else {
let mut forwarded = vec!["--plugin".to_owned(), namespace.to_owned()];
if force {
forwarded.push("--force".to_owned());
}
config_args = Some(forwarded);
}
}
Ok(PublishRun {
config_args,
dry_run,
force,
files,
checked,
notes,
})
}
fn publish_lines(
root: &Path,
files: &[(String, &'static [u8])],
force: bool,
dry_run: bool,
) -> Result<Vec<String>, BoxError> {
let listed: Vec<(&str, &[u8])> = files
.iter()
.map(|(path, bytes)| (path.as_str(), *bytes))
.collect();
let published = publish_files(root, &listed, force, dry_run)
.map_err(|refused| format!("plugin:publish: {refused}"))?;
Ok(published
.iter()
.map(|(path, outcome)| outcome.line(path))
.collect())
}
pub(crate) fn write(root: &Path, planned: &PublishRun) -> Result<Vec<String>, BoxError> {
let mut lines = if planned.dry_run || planned.files.is_empty() {
planned.checked.clone()
} else {
publish_lines(root, &planned.files, planned.force, false)?
};
lines.extend(planned.notes.iter().cloned());
Ok(lines)
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use super::*;
struct TempFolder(PathBuf);
impl TempFolder {
fn new(name: &str) -> TempFolder {
let path =
std::env::temp_dir().join(format!("navree-kernel-{name}-{}", std::process::id()));
let _ = fs::remove_dir_all(&path);
fs::create_dir_all(&path).expect("a temporary folder");
TempFolder(path)
}
}
impl Drop for TempFolder {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
fn lines(out: &[(String, Published)]) -> Vec<String> {
out.iter()
.map(|(path, published)| published.line(path))
.collect()
}
fn accepted_paths() -> Vec<String> {
let mut paths: Vec<String> = [
"list.html",
"admin/list.html",
".gitkeep",
"a.b.c",
"console.html",
"con-list.html",
"com10.css",
"lpt.txt",
"ਸੂਚਨਾ.html",
"conin.html",
"com⁴.css",
]
.map(String::from)
.to_vec();
paths.push("a".repeat(128));
paths.push(format!("{}/{}", "a".repeat(127), "b".repeat(127)));
paths
}
fn refused_paths() -> Vec<String> {
let mut paths: Vec<String> = [
"",
"/",
"/etc/navree.css",
"../x",
"a/../x",
"./x",
"a/./x",
"a//b",
"a/",
"a\\b",
"c:/x",
"C:x",
"banner.css:hidden",
"a\u{1}b",
"a\tb",
"a\u{7f}b",
"a<b",
"a>b",
"a\"b",
"a|b",
"a?b",
"a*b",
"list.html.",
"list.html ",
"...",
". ",
"a/.../b",
"con",
"CON",
"con.html",
"Con.tar.gz",
"nul",
"aux.txt",
"prn",
"com0",
"com1.css",
"COM9",
"lpt0",
"lpt9",
"Lpt5.log",
"con .txt",
"conin$",
"CONIN$.log",
"conout$",
"CONOUT$.txt",
"com¹",
"emails/COM¹",
"Com².css",
"com³",
"lpt¹",
"lpt².html",
"LPT³.txt",
]
.map(String::from)
.to_vec();
paths.push("a".repeat(129));
paths.push(format!("{}/{}", "a".repeat(128), "b".repeat(127)));
paths
}
#[test]
fn the_publish_path_rule_accepts_plain_paths_and_refuses_every_unsafe_shape() {
for good in accepted_paths() {
assert!(is_safe_relative_path(&good), "{good:?}");
}
for bad in refused_paths() {
assert!(!is_safe_relative_path(&bad), "{bad:?}");
}
for good in [
"en/announcements.ftl",
"pa-IN/admin/announcements.ftl",
"zh-Hant-TW/x.ftl",
] {
assert!(is_locale_path(good), "{good}");
}
for bad in [
"announcements.ftl",
"e/x.ftl",
"en_GB/x.ftl",
"123/x.ftl",
"en-/x.ftl",
] {
assert!(!is_locale_path(bad), "{bad}");
}
assert_eq!(
first_case_collision(["list.html", "show.html", "List.html"]),
Some("List.html")
);
assert_eq!(
first_case_collision(["list.html", "list.html"]),
Some("list.html")
);
assert_eq!(first_case_collision(["a/list.html", "b/list.html"]), None);
assert_eq!(
first_case_collision(["straße.html", "STRASSE.html"]),
Some("STRASSE.html")
);
assert_eq!(
first_case_collision(["k.html", "\u{212A}.html"]),
Some("\u{212A}.html")
);
}
#[test]
fn the_writer_writes_new_files_and_keeps_existing_ones_without_force() {
let root = TempFolder::new("writer-keep");
let banner = root.0.join("resources/announcements/banner.css");
fs::create_dir_all(banner.parent().unwrap()).unwrap();
fs::write(&banner, "/* Simran Kaur */").unwrap();
let files = [
("resources/announcements/banner.css", &b"body{}"[..]),
("resources/announcements/print.css", &b"@media print{}"[..]),
];
let out = publish_files(&root.0, &files, false, false).expect("published");
assert_eq!(
lines(&out),
[
"resources/announcements/banner.css: exists, kept (use --force to replace it)",
"resources/announcements/print.css: written",
]
);
assert_eq!(fs::read_to_string(&banner).unwrap(), "/* Simran Kaur */");
let out = publish_files(&root.0, &files, true, true).expect("dry run");
assert_eq!(
lines(&out),
[
"resources/announcements/banner.css: exists, would be replaced",
"resources/announcements/print.css: exists, would be replaced",
]
);
assert_eq!(
fs::read_to_string(&banner).unwrap(),
"/* Simran Kaur */",
"a dry run writes nothing"
);
fs::remove_file(root.0.join("resources/announcements/print.css")).unwrap();
let out = publish_files(&root.0, &files, false, true).expect("dry run");
assert_eq!(
lines(&out),
[
"resources/announcements/banner.css: exists, would be kept (use --force to replace it)",
"resources/announcements/print.css: would be written",
]
);
assert!(!root.0.join("resources/announcements/print.css").exists());
let out = publish_files(&root.0, &files, true, false).expect("forced");
assert_eq!(
lines(&out)[0],
"resources/announcements/banner.css: written"
);
assert_eq!(fs::read_to_string(&banner).unwrap(), "body{}");
}
#[test]
fn the_writer_checks_every_file_before_the_first_write() {
let root = TempFolder::new("writer-check");
let unsafe_late = [
("resources/a/one.css", &b"x"[..]),
("resources/a/../two.css", &b"y"[..]),
];
let refused = publish_files(&root.0, &unsafe_late, false, false).expect_err("refused");
assert_eq!(
refused.to_string(),
"resources/a/../two.css is not a safe relative path; nothing was written"
);
assert!(!root.0.join("resources").exists(), "nothing was written");
fs::create_dir_all(root.0.join("resources")).unwrap();
fs::write(root.0.join("resources/a"), "a file").unwrap();
let refused = publish_files(&root.0, &unsafe_late[..1], false, false).expect_err("refused");
assert_eq!(
refused.to_string(),
"resources/a is a file where a folder is needed; nothing was written"
);
fs::remove_file(root.0.join("resources/a")).unwrap();
fs::create_dir_all(root.0.join("resources/a/one.css")).unwrap();
let refused = publish_files(&root.0, &unsafe_late[..1], true, false).expect_err("refused");
assert_eq!(
refused.to_string(),
"resources/a/one.css is a folder where a file would be written; nothing was written"
);
}
#[test]
fn the_writer_refuses_two_paths_that_would_be_one_file_or_a_file_and_its_folder() {
let root = TempFolder::new("writer-conflicts");
for (paths, refusal) in [
(
[
"resources/views/announcements/list.html",
"resources/views/announcements/List.html",
],
"resources/views/announcements/list.html is the same file as another one on a disk that ignores case; nothing was written",
),
(
["config/announcements.toml", "config/announcements.toml"],
"config/announcements.toml is the same file as another one on a disk that ignores case; nothing was written",
),
(
[
"resources/views/announcements/admin",
"resources/views/announcements/admin/edit.html",
],
"resources/views/announcements/admin would be both a file and the folder of resources/views/announcements/admin/edit.html; nothing was written",
),
(
[
"resources/views/announcements/Admin",
"resources/views/announcements/admin/edit.html",
],
"resources/views/announcements/Admin would be both a file and the folder of resources/views/announcements/admin/edit.html; nothing was written",
),
] {
let files = [
(paths[0], &b"<ul></ul>"[..]),
(paths[1], &b"<form></form>"[..]),
];
for (force, dry_run) in [(false, false), (true, false), (false, true)] {
let refused = publish_files(&root.0, &files, force, dry_run).expect_err(refusal);
assert_eq!(refused.to_string(), refusal);
}
assert_eq!(
fs::read_dir(&root.0).unwrap().count(),
0,
"nothing was written for {paths:?}"
);
}
assert_eq!(
first_file_and_folder(&["a/b", "a/b/c.html", "a"]),
Some(("a/b", "a/b/c.html"))
);
assert_eq!(
first_file_and_folder(&["admin.html", "admin/edit.html"]),
None
);
}
#[test]
fn a_folder_that_changed_while_writing_is_refused_without_saying_nothing_was_written() {
let root = TempFolder::new("writer-changed");
fs::create_dir(root.0.join("resources")).unwrap();
fs::write(root.0.join("resources/a"), "a file").unwrap();
let real_root = fs::canonicalize(&root.0).unwrap();
let refused =
write_file(&root.0, &real_root, "resources/a/one.css", b"x").expect_err("a file");
assert_eq!(
refused.to_string(),
"resources/a is a file where a folder is needed; it changed while publishing, and the files before resources/a/one.css were written"
);
}
#[test]
fn a_file_whose_folder_left_the_app_while_writing_is_not_put_in_place() {
let root = TempFolder::new("writer-swapped");
fs::create_dir(root.0.join("app")).unwrap();
fs::create_dir(root.0.join("elsewhere")).unwrap();
let elsewhere = fs::canonicalize(root.0.join("elsewhere")).unwrap();
let refused = write_file(
&root.0.join("app"),
&elsewhere,
"resources/banner.css",
b"body{}",
)
.expect_err("outside the app");
assert_eq!(
refused.to_string(),
"the folder of resources/banner.css is a symbolic link or inside one; it changed while publishing, and the files before resources/banner.css were written"
);
assert_eq!(
fs::read_dir(root.0.join("app/resources")).unwrap().count(),
0,
"neither the file nor the new file beside it is left"
);
}
#[test]
fn the_writer_refuses_every_unsafe_shape_itself() {
let root = TempFolder::new("writer-shapes");
for path in refused_paths() {
for force in [false, true] {
let refused = publish_files(&root.0, &[(path.as_str(), b"x")], force, false)
.expect_err(&path);
assert_eq!(
refused.to_string(),
format!("{path} is not a safe relative path; nothing was written")
);
}
assert_eq!(
fs::read_dir(&root.0).unwrap().count(),
0,
"nothing was written for {path:?}"
);
}
}
#[cfg(unix)]
#[test]
fn plugin_publish_works_in_an_app_inside_a_linked_folder() {
let root = TempFolder::new("writer-linked-app");
fs::create_dir(root.0.join("real")).unwrap();
std::os::unix::fs::symlink(root.0.join("real"), root.0.join("app")).unwrap();
publish_files(
&root.0.join("app"),
&[("resources/announcements/banner.css", b"body{}")],
false,
false,
)
.expect("an app inside a linked folder publishes");
assert!(
root.0
.join("real/resources/announcements/banner.css")
.is_file()
);
}
mod navree_plugin_announcements {
use crate::{Module, ModuleBuilder, PluginInfo, PublishTag, Publishable};
const ANNOUNCEMENTS: PluginInfo = PluginInfo::new(
"navree-plugin-announcements",
module_path!(),
"announcements",
"1.0.0",
);
pub struct Notices;
impl Module for Notices {
fn register(&self, m: &mut ModuleBuilder) {
m.plugin(ANNOUNCEMENTS).contribute(
Publishable::new(PublishTag::Views).file("list.html", b"<ul></ul>"),
);
}
}
pub struct Empty;
impl Module for Empty {
fn register(&self, m: &mut ModuleBuilder) {
m.plugin(ANNOUNCEMENTS);
}
}
}
use navree_plugin_announcements::{Empty, Notices};
struct ConfigCommand;
impl crate::Module for ConfigCommand {
fn register(&self, m: &mut crate::ModuleBuilder) {
m.command(
crate::CommandSpec::new("config:publish", "Write a section's file", |_, _| async {
Ok(())
})
.offline(),
);
}
}
fn graph(roots: Vec<Box<dyn crate::Module>>) -> Graph {
Graph::build(&roots, &[]).expect("a valid graph")
}
#[test]
fn the_publish_lines_say_what_was_done_and_what_was_left() {
let root = TempFolder::new("publish-lines");
let args = |list: &[&str]| list.iter().map(|a| (*a).to_owned()).collect::<Vec<_>>();
let no_config = "config: the app has no ConfigModule, so no section is published";
let notices = graph(vec![Box::new(Notices)]);
let planned = run(¬ices, &args(&["announcements"]), &root.0).expect("checked");
assert!(
!root.0.join("resources").exists(),
"run checks every file and writes none"
);
assert_eq!(
(planned.config_args.clone(), planned.dry_run),
(None, false)
);
assert_eq!(
write(&root.0, &planned).expect("published"),
[
"resources/views/announcements/list.html: written",
no_config
]
);
let planned = run(
¬ices,
&args(&["announcements", "--tag", "files"]),
&root.0,
)
.expect("nothing");
assert_eq!(
write(&root.0, &planned).expect("nothing"),
["files: plugin `announcements` has nothing to publish"]
);
let planned = run(
¬ices,
&args(&["announcements", "--dry-run", "--force"]),
&root.0,
)
.expect("dry run");
assert!(planned.dry_run);
assert_eq!(
write(&root.0, &planned).expect("dry run"),
[
"resources/views/announcements/list.html: exists, would be replaced",
no_config,
]
);
let empty = graph(vec![Box::new(Empty)]);
let planned = run(&empty, &args(&["announcements"]), &root.0).expect("nothing at all");
assert_eq!(
write(&root.0, &planned).expect("nothing at all"),
[
"announcements: plugin `announcements` has nothing to publish",
no_config,
]
);
let configured = graph(vec![Box::new(Empty), Box::new(ConfigCommand)]);
let planned =
run(&configured, &args(&["announcements", "--force"]), &root.0).expect("config");
assert_eq!(
planned.config_args,
Some(args(&["--plugin", "announcements", "--force"]))
);
assert!(
write(&root.0, &planned).expect("config").is_empty(),
"config:publish says itself whether a section was written"
);
let planned =
run(&configured, &args(&["announcements", "--dry-run"]), &root.0).expect("dry run");
assert_eq!(planned.config_args, None);
assert_eq!(
write(&root.0, &planned).expect("dry run"),
["config: would run config:publish --plugin announcements"]
);
}
}