use std::path::{Component, Path, PathBuf};
use globset::{Glob, GlobSet, GlobSetBuilder};
use crate::Engine;
use crate::pipeline::{MediumType, PatternMode, Source};
pub fn normalize_lexical(path: &Path) -> PathBuf {
let mut out: Vec<Component> = Vec::new();
for comp in path.components() {
match comp {
Component::CurDir => {}
Component::ParentDir => match out.last() {
Some(Component::Normal(_)) => {
out.pop();
}
Some(Component::RootDir | Component::Prefix(_)) => {}
_ => out.push(comp),
},
other => out.push(other),
}
}
out.iter().collect()
}
pub fn relative_path(from: &Path, to: &Path) -> PathBuf {
let from = normalize_lexical(from);
let to = normalize_lexical(to);
let from_comps: Vec<Component> = from.components().collect();
let to_comps: Vec<Component> = to.components().collect();
let mut common = 0;
while common < from_comps.len()
&& common < to_comps.len()
&& from_comps[common] == to_comps[common]
{
common += 1;
}
let mut result = PathBuf::new();
for _ in common..from_comps.len() {
result.push("..");
}
for comp in &to_comps[common..] {
result.push(comp.as_os_str());
}
result
}
pub fn medium_base(pointer: &str, workspace_root: &Path) -> PathBuf {
if pointer.is_empty() {
workspace_root.to_path_buf()
} else {
normalize_lexical(&workspace_root.join(pointer))
}
}
pub fn engine_state_denies(workspace_root: &Path) -> Vec<String> {
use crate::workspace_store::{FileWorkspaceStore, WorkspaceStoreAdapter};
let mut denies: Vec<String> = vec![
".memstead/**".to_string(),
".memstead.cache/**".to_string(),
"**/.memstead/**".to_string(),
"**/.memstead.cache/**".to_string(),
];
if let Ok(ws) = FileWorkspaceStore.load(workspace_root) {
for mount in &ws.mounts {
let dir: Option<PathBuf> = match &mount.storage {
crate::workspace::MountStorage::GitBranch { gitdir, .. } => {
gitdir.parent().map(Path::to_path_buf)
}
crate::workspace::MountStorage::Folder { path } => Some(path.clone()),
crate::workspace::MountStorage::Archive { path, .. } => {
let rel = relative_path(workspace_root, &normalize_lexical(path));
denies.push(rel.to_string_lossy().to_string());
None
}
crate::workspace::MountStorage::InMemory => None,
};
if let Some(dir) = dir {
let rel = relative_path(workspace_root, &normalize_lexical(&dir));
if !rel.as_os_str().is_empty() {
denies.push(format!("{}/**", rel.to_string_lossy()));
}
}
}
}
denies
}
pub fn build_glob_set(patterns: &[&str]) -> Option<GlobSet> {
build_glob_set_reporting(patterns).0
}
pub fn build_glob_set_reporting(patterns: &[&str]) -> (Option<GlobSet>, Vec<String>) {
let mut builder = GlobSetBuilder::new();
let mut malformed = Vec::new();
let mut any = false;
for pattern in patterns {
match Glob::new(pattern) {
Ok(g) => {
builder.add(g);
any = true;
}
Err(_) => malformed.push((*pattern).to_string()),
}
}
let set = if any { builder.build().ok() } else { None };
(set, malformed)
}
pub fn enumerate_facet_files(
source: &Source,
deny_paths: &[String],
workspace_root: &Path,
) -> Vec<String> {
enumerate_facet_files_reported(source, deny_paths, workspace_root).files
}
pub fn enumerate_facet_files_reported(
source: &Source,
deny_paths: &[String],
workspace_root: &Path,
) -> ScopeEnumeration {
if !matches!(
source.medium_type,
MediumType::Codebase | MediumType::Filesystem | MediumType::Git
) {
return ScopeEnumeration::default();
}
let legacy_dialect = scope_migration_notes(source);
let mut allows: Vec<&str> = Vec::new();
let mut scope_denies: Vec<&str> = Vec::new();
for rule in &source.scope {
match rule.mode {
PatternMode::Allow => allows.push(&rule.path),
PatternMode::Deny => scope_denies.push(&rule.path),
}
}
let mut ws_denies: Vec<&str> = deny_paths.iter().map(String::as_str).collect();
let forced = engine_state_denies(workspace_root);
for f in &forced {
ws_denies.push(f);
}
if allows.is_empty() {
return ScopeEnumeration {
legacy_dialect,
..Default::default()
};
}
let (allow_set, mut malformed) = build_glob_set_reporting(&allows);
let (scope_deny_set, deny_malformed) = build_glob_set_reporting(&scope_denies);
malformed.extend(deny_malformed);
let ws_oracle = crate::check_path::DenyOracle::new(
&ws_denies
.iter()
.map(|d| (*d).to_string())
.collect::<Vec<_>>(),
);
let Some(allow_set) = allow_set else {
return ScopeEnumeration {
malformed,
legacy_dialect,
..Default::default()
};
};
let base = medium_base(&source.pointer, workspace_root);
let allow_prefixes: Vec<Vec<String>> = allows.iter().map(|p| glob_literal_prefix(p)).collect();
let mut out: Vec<String> = Vec::new();
let mut stack = vec![base.clone()];
while let Some(dir) = stack.pop() {
let Ok(entries) = std::fs::read_dir(&dir) else {
continue;
};
for entry in entries.flatten() {
let Ok(file_type) = entry.file_type() else {
continue;
};
let path = entry.path();
if file_type.is_dir() {
let skip = path.file_name().and_then(|n| n.to_str()).is_some_and(|n| {
VCS_INTERNAL_DIRS.contains(&n) || n == ".memstead" || n == ".memstead.cache"
});
if !skip {
let dir_src_rel = relative_path(&base, &normalize_lexical(&path))
.to_string_lossy()
.to_string();
if allow_could_match_under(&allow_prefixes, &dir_src_rel) {
stack.push(path);
}
}
} else if file_type.is_file() {
let normalized = normalize_lexical(&path);
let rel = relative_path(workspace_root, &normalized)
.to_string_lossy()
.to_string();
let src_rel = relative_path(&base, &normalized)
.to_string_lossy()
.to_string();
let denied = scope_deny_set
.as_ref()
.is_some_and(|d| d.is_match(&src_rel))
|| ws_oracle.is_denied(&rel);
if allow_set.is_match(&src_rel) && !denied {
out.push(rel);
}
}
}
}
out.sort();
out.dedup();
ScopeEnumeration {
files: out,
malformed,
legacy_dialect,
}
}
pub fn glob_literal_prefix(pattern: &str) -> Vec<String> {
pattern
.split('/')
.take_while(|seg| {
!seg.chars()
.any(|c| matches!(c, '*' | '?' | '[' | ']' | '{' | '}'))
})
.map(str::to_string)
.collect()
}
pub fn allow_could_match_under(prefixes: &[Vec<String>], dir_rel: &str) -> bool {
let dir_segs: Vec<&str> = dir_rel.split('/').filter(|s| !s.is_empty()).collect();
prefixes.iter().any(|prefix| {
let n = dir_segs.len().min(prefix.len());
dir_segs[..n]
.iter()
.zip(prefix[..n].iter())
.all(|(d, p)| *d == p.as_str())
})
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ScopeEnumeration {
pub files: Vec<String>,
pub malformed: Vec<String>,
pub legacy_dialect: Vec<ScopePatternNote>,
}
impl ScopeEnumeration {
pub fn is_partial(&self) -> bool {
!self.malformed.is_empty() || !self.legacy_dialect.is_empty()
}
pub fn partiality_reason(&self) -> Option<String> {
let mut causes = Vec::new();
if !self.malformed.is_empty() {
causes.push(format!(
"scope pattern(s) that would not compile were skipped: {}",
self.malformed.join(", ")
));
}
if !self.legacy_dialect.is_empty() {
causes.push(format!(
"scope pattern(s) are still written against the workspace root rather than the \
source pointer, so they select nothing under the pointer join: {}",
self.legacy_dialect
.iter()
.map(|n| n.pattern.as_str())
.collect::<Vec<_>>()
.join(", ")
));
}
(!causes.is_empty()).then(|| causes.join("; "))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScopePatternNote {
pub pattern: String,
pub deny: bool,
pub suggested: Option<String>,
}
pub fn scope_migration_notes(source: &Source) -> Vec<ScopePatternNote> {
let pointer = source.pointer.trim_end_matches('/');
if pointer.is_empty() {
return Vec::new();
}
let prefix = format!("{pointer}/");
source
.scope
.iter()
.filter(|r| !r.path.starts_with("**"))
.filter_map(|rule| {
let stripped = rule.path.strip_prefix(&prefix)?;
Some(ScopePatternNote {
pattern: rule.path.clone(),
deny: rule.mode == PatternMode::Deny,
suggested: (!stripped.is_empty()).then(|| stripped.to_string()),
})
})
.collect()
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EntitySelector {
All,
Type(String),
Id(String),
}
pub fn parse_entity_selector(pattern: &str) -> Option<EntitySelector> {
let pattern = pattern.trim();
if pattern == "*" {
return Some(EntitySelector::All);
}
if let Some(rest) = pattern.strip_prefix("type:") {
let rest = rest.trim();
if rest.is_empty() {
return None;
}
return Some(EntitySelector::Type(rest.to_string()));
}
if let Some(rest) = pattern.strip_prefix("id:") {
let rest = rest.trim();
if rest.is_empty() {
return None;
}
Glob::new(rest).ok()?;
return Some(EntitySelector::Id(rest.to_string()));
}
None
}
pub fn selector_matches(selector: &EntitySelector, id: &str, entity_type: &str) -> bool {
match selector {
EntitySelector::All => true,
EntitySelector::Type(t) => entity_type == t,
EntitySelector::Id(g) => Glob::new(g)
.ok()
.map(|glob| glob.compile_matcher().is_match(id))
.unwrap_or(false),
}
}
pub fn enumerate_graph_entities(engine: &Engine, source: &Source) -> Vec<String> {
if source.medium_type != MediumType::Graph {
return Vec::new();
}
let mut allows: Vec<EntitySelector> = Vec::new();
let mut denies: Vec<EntitySelector> = Vec::new();
for rule in &source.scope {
let Some(sel) = parse_entity_selector(&rule.path) else {
continue;
};
match rule.mode {
PatternMode::Allow => allows.push(sel),
PatternMode::Deny => denies.push(sel),
}
}
if allows.is_empty() {
return Vec::new();
}
let mem = source.pointer.as_str();
let mut out: Vec<String> = Vec::new();
for entity in engine.store().all_entities() {
if entity.mem != mem || entity.stub {
continue;
}
let id = entity.id.0.as_str();
let ty = entity.entity_type.as_str();
if !allows.iter().any(|s| selector_matches(s, id, ty)) {
continue;
}
if denies.iter().any(|s| selector_matches(s, id, ty)) {
continue;
}
out.push(id.to_string());
}
out.sort();
out.dedup();
out
}
pub fn enumerate_source_artifacts(
engine: &Engine,
source: &Source,
deny_paths: &[String],
workspace_root: &Path,
) -> Vec<String> {
enumerate_source_artifacts_reported(engine, source, deny_paths, workspace_root).files
}
pub fn enumerate_source_artifacts_reported(
engine: &Engine,
source: &Source,
deny_paths: &[String],
workspace_root: &Path,
) -> ScopeEnumeration {
match source.medium_type {
MediumType::Codebase | MediumType::Filesystem | MediumType::Git => {
enumerate_facet_files_reported(source, deny_paths, workspace_root)
}
MediumType::Graph => ScopeEnumeration {
files: enumerate_graph_entities(engine, source),
..Default::default()
},
MediumType::Web => ScopeEnumeration::default(),
}
}
pub const VCS_INTERNAL_DIRS: &[&str] = &[".git", ".svn", ".hg"];