use std::{collections::BTreeMap, path::Path};
use crate::{
WorkspaceIndex, domain,
markdown::{Table, code, link},
};
#[derive(Debug)]
struct Entry {
rel_path: String,
description: String,
kind: String,
}
#[must_use]
pub(crate) fn build(
workspace: &WorkspaceIndex,
current_dir: &Path,
file: &str,
patterns: &[String],
show_kind: bool,
) -> String {
let entries = collect(workspace, file, patterns, show_kind);
if entries.is_empty() {
return String::new();
}
render_table(workspace, current_dir, &entries, file, show_kind)
}
fn collect(
workspace: &WorkspaceIndex,
file: &str,
patterns: &[String],
show_kind: bool,
) -> Vec<Entry> {
let mut entries = BTreeMap::new();
for pattern in patterns {
for entry in collect_pattern(workspace, file, pattern, show_kind) {
entries.entry(entry.rel_path.clone()).or_insert(entry);
}
}
entries.into_values().collect()
}
fn collect_pattern(
workspace: &WorkspaceIndex,
file: &str,
pattern: &str,
show_kind: bool,
) -> Vec<Entry> {
if pattern.contains('*') {
collect_glob(workspace, file, pattern, show_kind)
} else {
collect_dir_children(workspace, file, pattern, show_kind)
}
}
fn resolve_kind(workspace: &WorkspaceIndex, dir: &Path, show_kind: bool) -> String {
if show_kind {
domain::load(workspace, dir).kind.to_string()
} else {
String::new()
}
}
fn collect_dir_children(
workspace: &WorkspaceIndex,
file: &str,
dir_path: &str,
show_kind: bool,
) -> Vec<Entry> {
let root = workspace.root();
let abs = root.join(dir_path);
if !workspace.is_dir(&abs) {
if has_file(workspace, &abs, file) {
let meta = domain::load(workspace, &abs);
let kind = resolve_kind(workspace, &abs, show_kind);
return vec![Entry {
rel_path: dir_path.to_string(),
description: meta.description.clone().unwrap_or_default(),
kind,
}];
}
return Vec::new();
}
let mut children: Vec<Entry> = workspace
.child_dirs(&abs)
.filter_map(|path| {
let name = path.file_name()?.to_string_lossy().to_string();
if !has_file(workspace, path, file) {
return None;
}
let meta = domain::load(workspace, path);
let kind = resolve_kind(workspace, path, show_kind);
Some(Entry {
rel_path: format!("{dir_path}/{name}"),
description: meta.description.clone().unwrap_or_default(),
kind,
})
})
.collect();
if children.is_empty() {
if has_file(workspace, &abs, file) {
let meta = domain::load(workspace, &abs);
let kind = resolve_kind(workspace, &abs, show_kind);
return vec![Entry {
rel_path: dir_path.to_string(),
description: meta.description.clone().unwrap_or_default(),
kind,
}];
}
return Vec::new();
}
children.sort_by(|a, b| a.rel_path.cmp(&b.rel_path));
children
}
fn collect_glob(
workspace: &WorkspaceIndex,
file: &str,
pattern: &str,
show_kind: bool,
) -> Vec<Entry> {
let root = workspace.root();
let (parent_str, glob_part) = pattern.rsplit_once('/').unwrap_or(("", pattern));
let parent_abs = if parent_str.is_empty() {
root.to_path_buf()
} else {
root.join(parent_str)
};
if !workspace.is_dir(&parent_abs) {
return Vec::new();
}
let mut entries: Vec<Entry> = workspace
.child_dirs(&parent_abs)
.filter_map(|path| {
let name = path.file_name()?.to_string_lossy().to_string();
if !glob_match(glob_part, &name) {
return None;
}
if !has_file(workspace, path, file) {
return None;
}
let meta = domain::load(workspace, path);
let kind = resolve_kind(workspace, path, show_kind);
let rel_path = if parent_str.is_empty() {
name
} else {
format!("{parent_str}/{name}")
};
Some(Entry {
rel_path,
description: meta.description.clone().unwrap_or_default(),
kind,
})
})
.collect();
entries.sort_by(|a, b| a.rel_path.cmp(&b.rel_path));
entries
}
fn glob_match(pattern: &str, name: &str) -> bool {
glob_match::glob_match(pattern, name)
}
fn has_file(workspace: &WorkspaceIndex, path: &Path, file: &str) -> bool {
workspace.has_document(path, file)
}
fn render_table(
workspace: &WorkspaceIndex,
current_dir: &Path,
entries: &[Entry],
file: &str,
show_kind: bool,
) -> String {
if show_kind {
Table::new()
.headers(["Path", "What it is", "Kind"])
.rows(entries.iter().map(|e| {
[
link(
code(&e.rel_path),
relative_link(workspace, current_dir, e, file),
),
e.description.clone(),
e.kind.clone(),
]
}))
.build_markdown()
} else {
Table::new()
.headers(["Path", "What it is"])
.rows(entries.iter().map(|e| {
[
link(
code(&e.rel_path),
relative_link(workspace, current_dir, e, file),
),
e.description.clone(),
]
}))
.build_markdown()
}
}
fn relative_link(
workspace: &WorkspaceIndex,
current_dir: &Path,
entry: &Entry,
file: &str,
) -> String {
let target = workspace.root().join(&entry.rel_path).join(file);
crate::workspace::relative_path(current_dir, &target)
}
#[cfg(test)]
mod tests {
use googletest::prelude::*;
use super::*;
use crate::WorkspaceFile;
fn workspace(files: &[(&str, &str)]) -> WorkspaceIndex {
let root = Path::new("/ws");
let files = files
.iter()
.map(|(path, contents)| WorkspaceFile {
path: root.join(path),
contents: Some(Box::from(*contents)),
})
.collect();
WorkspaceIndex::new(root.to_path_buf(), files)
}
fn resolve_kind(
files: &[(&str, &str)],
domain: Option<(&str, toml::Value)>,
show_kind: bool,
) -> String {
let root = Path::new("/ws");
let workspace = match domain {
Some((name, config)) => WorkspaceIndex::new_domain(
root.to_path_buf(),
files
.iter()
.map(|(path, contents)| WorkspaceFile {
path: root.join(path),
contents: Some(Box::from(*contents)),
})
.collect(),
name,
config,
),
None => workspace(files),
};
super::resolve_kind(&workspace, root, show_kind)
}
#[gtest]
fn glob_match_patterns() -> Result<()> {
verify_that!(glob_match("engine-*", "engine-world"), eq(true))?;
verify_that!(glob_match("engine-*", "engine"), eq(false))?;
verify_that!(glob_match("engine", "engine"), eq(true))?;
verify_that!(glob_match("engine", "engine-world"), eq(false))?;
Ok(())
}
#[gtest]
fn render_table_format() -> Result<()> {
let root = Path::new("/ws");
let workspace = workspace(&[]);
let entries = vec![
Entry {
rel_path: "apps/portal".to_string(),
description: "The website".to_string(),
kind: String::new(),
},
Entry {
rel_path: "apps/addon".to_string(),
description: "In-game addon".to_string(),
kind: String::new(),
},
];
let table = render_table(&workspace, root, &entries, "README.md", false);
verify_that!(table, contains_substring("Path"))?;
verify_that!(table, contains_substring("What it is"))?;
verify_that!(
table,
contains_substring("[`apps/portal`](apps/portal/README.md)")
)?;
verify_that!(table, contains_substring("The website"))?;
verify_that!(
table,
contains_substring("[`apps/addon`](apps/addon/README.md)")
)?;
verify_that!(table, contains_substring("In-game addon"))?;
verify_that!(table, not(contains_substring("Kind")))?;
Ok(())
}
#[gtest]
fn render_table_with_kind() -> Result<()> {
let root = Path::new("/ws");
let workspace = workspace(&[]);
let entries = vec![
Entry {
rel_path: "crates/engine".to_string(),
description: "Core engine".to_string(),
kind: "crate".to_string(),
},
Entry {
rel_path: "apps/portal".to_string(),
description: "The website".to_string(),
kind: "package".to_string(),
},
Entry {
rel_path: "lua/tracker".to_string(),
description: "Lua package".to_string(),
kind: "lua".to_string(),
},
];
let table = render_table(&workspace, root, &entries, "README.md", true);
verify_that!(table, contains_substring("Path"))?;
verify_that!(table, contains_substring("What it is"))?;
verify_that!(table, contains_substring("Kind"))?;
verify_that!(
table,
contains_substring("[`crates/engine`](crates/engine/README.md)")
)?;
verify_that!(table, contains_substring("crate"))?;
verify_that!(table, contains_substring("package"))?;
verify_that!(table, contains_substring("lua"))?;
Ok(())
}
#[gtest]
fn render_table_links_from_current_document_directory() -> Result<()> {
let root = Path::new("/ws");
let workspace = workspace(&[]);
let entries = vec![Entry {
rel_path: "crates/engine-domain".to_string(),
description: "Core domain types".to_string(),
kind: String::new(),
}];
let table = render_table(
&workspace,
&root.join("crates/engine"),
&entries,
"README.md",
false,
);
verify_that!(
table,
contains_substring("[`crates/engine-domain`](../engine-domain/README.md)")
)?;
Ok(())
}
#[gtest]
fn resolve_kind_crate() -> Result<()> {
verify_that!(
resolve_kind(
&[(
"Cargo.toml",
"[package]\nname = \"test\"\ndescription = \"\"",
)],
Some((
"cargo",
toml::Value::Table(toml::toml! {
manifests = ["Cargo.toml"]
workspace = "Cargo.toml"
}),
)),
true,
),
eq("crate")
)
}
#[gtest]
fn resolve_kind_package() -> Result<()> {
verify_that!(
resolve_kind(
&[("package.json", "{}")],
Some((
"node",
toml::Value::Table(toml::toml! { manifests = ["package.json"] }),
)),
true
),
eq("package")
)
}
#[gtest]
fn resolve_kind_directory() -> Result<()> {
verify_that!(resolve_kind(&[], None, true), eq("directory"))
}
#[gtest]
fn resolve_kind_skipped_when_false() -> Result<()> {
verify_that!(
resolve_kind(
&[(
"Cargo.toml",
"[package]\nname = \"test\"\ndescription = \"\"",
)],
Some((
"cargo",
toml::Value::Table(toml::toml! {
manifests = ["Cargo.toml"]
workspace = "Cargo.toml"
}),
)),
false,
),
eq("")
)
}
}