use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
use crate::app::AppSnapshot;
use crate::modules::kind::{Kinds, TESTS};
use crate::modules::layout::Layout;
use crate::modules::module::{artisan_command, command_of, files_of, is_php};
use crate::php::{DeclaredKind, analyze};
const EVENTS: &str = "Events";
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AcceptedSurface {
#[serde(default)]
pub classes: Vec<String>,
#[serde(default)]
pub routes: Vec<String>,
#[serde(default)]
pub commands: Vec<String>,
}
impl AcceptedSurface {
pub(crate) fn of_manifest(manifest: &serde_json::Value) -> Option<Self> {
let surface = manifest
.get("surface")
.filter(|surface| surface.is_object())?;
let surface: Self = serde_json::from_value(surface.clone()).ok()?;
let stored =
|list: &[String], valid: fn(&str) -> bool| list.iter().all(|entry| valid(entry));
(stored(&surface.classes, is_class_name)
&& stored(&surface.routes, |route| {
stored_route(route).as_deref() == Some(route)
})
&& stored(&surface.commands, is_command_name))
.then_some(surface)
}
pub fn of_file(path: &std::path::Path) -> Option<Self> {
let text = std::fs::read(path).ok()?;
Self::of_manifest(&serde_json::from_slice(&text).ok()?)
}
pub fn normalized(mut self) -> Self {
let mut seen = BTreeSet::new();
self.classes = self
.classes
.into_iter()
.map(|class| class.trim_start_matches('\\').to_owned())
.filter(|class| seen.insert(class.to_lowercase()))
.collect();
self.routes = self
.routes
.into_iter()
.map(|route| stored_route(&route).unwrap_or(route))
.collect();
for list in [&mut self.classes, &mut self.routes, &mut self.commands] {
list.sort();
list.dedup();
}
self
}
fn list_of(&mut self, kind: SurfaceKind) -> &mut Vec<String> {
match kind {
SurfaceKind::Contract | SurfaceKind::Event | SurfaceKind::OtherClass => {
&mut self.classes
}
SurfaceKind::Route => &mut self.routes,
SurfaceKind::Command => &mut self.commands,
}
}
pub fn entries(&self) -> usize {
self.classes.len() + self.routes.len() + self.commands.len()
}
pub fn has_class(&self, class: &str) -> bool {
self.classes.iter().any(|listed| same_class(listed, class))
}
fn covers(&self, uri: &str) -> bool {
self.routes.iter().any(|route| pattern_matches(route, uri))
}
pub fn has(&self, entry: &SurfaceEntry) -> bool {
match entry.kind {
SurfaceKind::Contract | SurfaceKind::Event | SurfaceKind::OtherClass => {
self.has_class(&entry.name)
}
SurfaceKind::Route => self.routes.contains(&entry.name),
SurfaceKind::Command => self.commands.contains(&entry.name),
}
}
pub fn with_differences(&self, differences: &[Difference]) -> Self {
let mut surface = self.clone();
for difference in differences.iter().filter(|difference| difference.taken) {
let entry = &difference.entry;
let list = surface.list_of(entry.kind);
if difference.new {
list.push(entry.name.clone());
} else {
let class = !matches!(entry.kind, SurfaceKind::Route | SurfaceKind::Command);
list.retain(|listed| {
if class {
!same_class(listed, &entry.name)
} else {
listed != &entry.name
}
});
}
}
surface.normalized()
}
pub fn to_stdin(&self) -> String {
serde_json::to_string(self).expect("a surface is plain data")
}
}
pub fn surface_args(module: &str) -> Vec<String> {
["module:surface", module, "--set", "--stdin", "--json"]
.map(str::to_owned)
.to_vec()
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct SurfaceAnswer {
pub module: String,
#[serde(default)]
pub surface: Option<AcceptedSurface>,
#[serde(default)]
pub changed: bool,
#[serde(default)]
pub errors: Vec<SurfaceProblem>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct SurfaceProblem {
pub message: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Difference {
pub entry: SurfaceEntry,
pub new: bool,
pub taken: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum SurfaceKind {
Contract,
Event,
OtherClass,
Route,
Command,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SurfaceEntry {
pub kind: SurfaceKind,
pub name: String,
pub folder: String,
pub used_by: Vec<(String, usize)>,
pub routes: usize,
pub schedule: Option<String>,
pub proposed: bool,
pub by_hand: bool,
}
impl SurfaceEntry {
fn new(kind: SurfaceKind, name: String) -> Self {
Self {
kind,
name,
folder: String::new(),
used_by: Vec::new(),
routes: 0,
schedule: None,
proposed: true,
by_hand: false,
}
}
pub fn used_files(&self) -> usize {
self.used_by.iter().map(|(_, files)| files).sum()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Typed {
Class { folder: String },
Command,
Route { routes: usize },
Listed,
Unknown,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Proposal {
pub module: String,
pub entries: Vec<SurfaceEntry>,
pub routes_read: bool,
declared: BTreeMap<String, String>,
commands: BTreeSet<String>,
uris: Vec<String>,
}
impl Proposal {
pub fn found(&self) -> usize {
self.entries.len()
}
pub fn proposed(&self) -> usize {
self.entries.iter().filter(|entry| entry.proposed).count()
}
pub fn of(&self, kind: SurfaceKind) -> impl Iterator<Item = (usize, &SurfaceEntry)> {
self.entries
.iter()
.enumerate()
.filter(move |(_, entry)| entry.kind == kind)
}
pub fn check(&self, typed: &str) -> Typed {
let typed = typed.trim().trim_start_matches('\\');
if typed.is_empty() {
return Typed::Unknown;
}
if self.entries.iter().any(|entry| entry.name == typed) {
return Typed::Listed;
}
if let Some(folder) = self.declared.get(typed) {
return Typed::Class {
folder: folder.clone(),
};
}
if self.commands.contains(typed) {
return Typed::Command;
}
let routes = self
.uris
.iter()
.filter(|uri| pattern_matches(typed, uri))
.count();
if routes > 0 {
Typed::Route { routes }
} else {
Typed::Unknown
}
}
pub fn add(&mut self, typed: &str) -> bool {
let name = typed.trim().trim_start_matches('\\').to_owned();
let mut entry = match self.check(&name) {
Typed::Class { folder } => {
let mut entry = SurfaceEntry::new(SurfaceKind::OtherClass, name);
entry.folder = folder;
entry
}
Typed::Command => SurfaceEntry::new(SurfaceKind::Command, name),
Typed::Route { routes } => {
let mut entry = SurfaceEntry::new(SurfaceKind::Route, name);
entry.routes = routes;
entry
}
Typed::Listed | Typed::Unknown => return false,
};
entry.by_hand = true;
self.insert(entry);
true
}
fn insert(&mut self, entry: SurfaceEntry) {
let at = self
.entries
.iter()
.rposition(|other| other.kind <= entry.kind)
.map_or(0, |last| last + 1);
self.entries.insert(at, entry);
}
pub fn keep_choices_of(&mut self, earlier: &Proposal) {
for entry in &earlier.entries {
let same = self
.entries
.iter_mut()
.find(|other| other.kind == entry.kind && other.name == entry.name);
match same {
Some(same) => same.proposed = entry.proposed,
None if entry.by_hand => {
if self.add(&entry.name)
&& let Some(added) = self
.entries
.iter_mut()
.find(|other| other.name == entry.name)
{
added.proposed = entry.proposed;
}
}
None => {}
}
}
}
pub fn surface(&self) -> AcceptedSurface {
let mut surface = AcceptedSurface::default();
for entry in self.entries.iter().filter(|entry| entry.proposed) {
let list = surface.list_of(entry.kind);
list.push(entry.name.clone());
}
surface.normalized()
}
pub fn take_choices_of(&mut self, accepted: &AcceptedSurface) {
for entry in &mut self.entries {
entry.proposed = accepted.has(entry);
}
let names = accepted
.classes
.iter()
.chain(&accepted.routes)
.chain(&accepted.commands);
for name in names {
if self.add(name)
&& let Some(added) = self.entries.iter_mut().find(|entry| &entry.name == name)
{
added.by_hand = false;
}
}
if !self.routes_read {
for route in &accepted.routes {
if !self
.entries
.iter()
.any(|entry| entry.kind == SurfaceKind::Route && &entry.name == route)
{
self.insert(SurfaceEntry::new(SurfaceKind::Route, route.clone()));
}
}
}
}
pub fn differences(&self, accepted: &AcceptedSurface) -> Vec<Difference> {
let lacks = |entry: &SurfaceEntry| match entry.kind {
SurfaceKind::Route => self
.uris
.iter()
.any(|uri| pattern_matches(&entry.name, uri) && !accepted.covers(uri)),
_ => !accepted.has(entry),
};
let mut differences: Vec<Difference> = self
.entries
.iter()
.filter(|entry| entry.proposed && lacks(entry))
.map(|entry| Difference {
entry: entry.clone(),
new: true,
taken: true,
})
.collect();
let gone = |kind: SurfaceKind, name: &String| Difference {
entry: SurfaceEntry::new(kind, name.clone()),
new: false,
taken: true,
};
for class in &accepted.classes {
if !self
.declared
.keys()
.any(|declared| same_class(declared, class))
{
differences.push(gone(SurfaceKind::OtherClass, class));
}
}
if self.routes_read {
for route in &accepted.routes {
if !self.uris.iter().any(|uri| pattern_matches(route, uri)) {
differences.push(gone(SurfaceKind::Route, route));
}
}
}
for command in &accepted.commands {
if !self.commands.contains(command) {
differences.push(gone(SurfaceKind::Command, command));
}
}
differences
}
pub fn as_text(&self) -> String {
let mut text = format!("Public surface of {}, proposed by Mortise\n", self.module);
let groups = [
(SurfaceKind::Contract, "Contracts"),
(SurfaceKind::Event, "Events"),
(SurfaceKind::OtherClass, "Other classes"),
(SurfaceKind::Route, "Routes"),
(SurfaceKind::Command, "Console commands"),
];
for (kind, title) in groups {
let names: Vec<&str> = self
.of(kind)
.filter(|(_, entry)| entry.proposed)
.map(|(_, entry)| entry.name.as_str())
.collect();
if names.is_empty() {
continue;
}
text.push_str(&format!("\n{title}\n"));
for name in names {
text.push_str(&format!(" {name}\n"));
}
}
text
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct ScanCounts {
pub used_classes: usize,
pub used_files: usize,
pub contracts: usize,
pub events: usize,
pub commands: usize,
}
struct Found {
class: String,
interface: bool,
folder: String,
command: Option<String>,
}
pub struct SurfaceScan {
module: String,
kinds: Kinds,
files: Vec<(PathBuf, String)>,
next: usize,
found: Vec<Found>,
used: BTreeMap<String, BTreeMap<String, BTreeSet<String>>>,
}
impl SurfaceScan {
pub fn start(app: &AppSnapshot, module: &str) -> Option<Self> {
let found = app.module(module)?;
let (layout, config) = Layout::read(&app.root);
let kinds = Kinds::new(config.as_ref(), &layout.app_folder);
let files = files_of(&found.dir)
.into_iter()
.filter(|(_, relative)| is_php(relative) && kinds.of(relative) != TESTS)
.collect();
let mut used: BTreeMap<String, BTreeMap<String, BTreeSet<String>>> = BTreeMap::new();
for link in app.links.iter().filter(|link| link.to == module) {
for reference in &link.refs {
used.entry(reference.class.clone())
.or_default()
.entry(link.from.clone())
.or_default()
.insert(reference.file.clone());
}
}
Some(Self {
module: module.to_owned(),
kinds,
files,
next: 0,
found: Vec::new(),
used,
})
}
pub fn total(&self) -> usize {
self.files.len()
}
pub fn read(&self) -> usize {
self.next
}
pub fn module(&self) -> &str {
&self.module
}
pub fn step(&mut self, files: usize) -> bool {
let end = (self.next + files).min(self.files.len());
for (path, relative) in &self.files[self.next..end] {
let folder = self.kinds.of(relative);
let analysis = analyze(&std::fs::read(path).unwrap_or_default());
for declared in analysis.declares {
self.found.push(Found {
command: command_of(&declared, &folder),
class: declared.class,
interface: declared.kind == DeclaredKind::Interface,
folder: folder.clone(),
});
}
}
self.next = end;
self.next == self.files.len()
}
pub fn counts(&self) -> ScanCounts {
let files: BTreeSet<&String> = self
.used
.values()
.flat_map(|users| users.values().flatten())
.collect();
ScanCounts {
used_classes: self.used.len(),
used_files: files.len(),
contracts: self.found.iter().filter(|found| found.interface).count(),
events: self.found.iter().filter(|found| is_event(found)).count(),
commands: self
.found
.iter()
.filter(|found| found.command.is_some())
.count(),
}
}
pub fn finish(self, routes: Option<&[String]>, scheduled: &[(String, String)]) -> Proposal {
let users = |class: &str| -> Vec<(String, usize)> {
let mut users: Vec<(String, usize)> = self
.used
.get(class)
.map(|users| {
users
.iter()
.map(|(module, files)| (module.clone(), files.len()))
.collect()
})
.unwrap_or_default();
users.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
users
};
let class_entry = |kind: SurfaceKind, found: &Found| {
let mut entry = SurfaceEntry::new(kind, found.class.clone());
entry.folder = found.folder.clone();
entry.used_by = users(&found.class);
entry
};
let sorted = |mut entries: Vec<SurfaceEntry>| {
entries.sort_by(|a, b| {
b.used_files()
.cmp(&a.used_files())
.then_with(|| a.name.cmp(&b.name))
});
entries
};
let contracts: Vec<SurfaceEntry> = self
.found
.iter()
.filter(|found| found.interface)
.map(|found| class_entry(SurfaceKind::Contract, found))
.collect();
let events: Vec<SurfaceEntry> = self
.found
.iter()
.filter(|found| is_event(found))
.map(|found| class_entry(SurfaceKind::Event, found))
.collect();
let listed: BTreeSet<&str> = contracts
.iter()
.chain(&events)
.map(|entry| entry.name.as_str())
.collect();
let others: Vec<SurfaceEntry> = self
.used
.keys()
.filter(|class| !listed.contains(class.as_str()))
.map(|class| {
let mut entry = SurfaceEntry::new(SurfaceKind::OtherClass, class.clone());
entry.folder = self
.found
.iter()
.find(|found| &found.class == class)
.map(|found| found.folder.clone())
.unwrap_or_default();
entry.used_by = users(class);
entry.proposed = false;
entry
})
.collect();
let mut patterns: BTreeMap<String, usize> = BTreeMap::new();
for uri in routes.unwrap_or_default() {
*patterns.entry(pattern_of(uri)).or_default() += 1;
}
let mut route_entries: Vec<SurfaceEntry> = patterns
.into_iter()
.map(|(pattern, count)| {
let mut entry = SurfaceEntry::new(SurfaceKind::Route, pattern);
entry.routes = count;
entry
})
.collect();
route_entries.sort_by(|a, b| b.routes.cmp(&a.routes).then_with(|| a.name.cmp(&b.name)));
let mut commands: Vec<SurfaceEntry> = self
.found
.iter()
.filter_map(|found| found.command.as_ref())
.map(|name| {
let mut entry = SurfaceEntry::new(SurfaceKind::Command, name.clone());
entry.schedule = scheduled
.iter()
.find(|(target, _)| artisan_command(target) == Some(name.as_str()))
.map(|(_, schedule)| schedule.clone());
entry
})
.collect();
commands.sort_by(|a, b| {
b.schedule
.is_some()
.cmp(&a.schedule.is_some())
.then_with(|| a.name.cmp(&b.name))
});
let mut entries = sorted(contracts);
entries.extend(sorted(events));
entries.extend(sorted(others));
entries.extend(route_entries);
entries.extend(commands);
Proposal {
module: self.module,
entries,
routes_read: routes.is_some(),
declared: self
.found
.iter()
.map(|found| (found.class.clone(), found.folder.clone()))
.collect(),
commands: self
.found
.iter()
.filter_map(|found| found.command.clone())
.collect(),
uris: routes.unwrap_or_default().to_vec(),
}
}
}
fn same_class(a: &str, b: &str) -> bool {
a.trim_start_matches('\\')
.eq_ignore_ascii_case(b.trim_start_matches('\\'))
}
fn is_class_name(class: &str) -> bool {
class.split('\\').all(|part| {
let mut bytes = part.bytes();
let word = |byte: u8| byte == b'_' || byte >= 0x80 || byte.is_ascii_alphanumeric();
bytes
.next()
.is_some_and(|first| word(first) && !first.is_ascii_digit())
&& bytes.all(word)
})
}
fn is_command_name(command: &str) -> bool {
command
.split(':')
.all(|part| !part.is_empty() && !part.chars().any(char::is_whitespace))
}
fn stored_route(route: &str) -> Option<String> {
if route.is_empty() || route.chars().any(char::is_whitespace) {
return None;
}
let route = route.trim_matches('/');
Some(if route.is_empty() { "/" } else { route }.to_owned())
}
fn is_event(found: &Found) -> bool {
!found.interface && found.folder == EVENTS
}
fn pattern_of(uri: &str) -> String {
if uri.trim_matches('/').is_empty() {
return "/".to_owned();
}
let parts: Vec<&str> = uri.trim_matches('/').split('/').collect();
let take = if parts.first() == Some(&"api") { 2 } else { 1 };
let prefix: Vec<&str> = parts
.iter()
.copied()
.take(take)
.take_while(|part| !part.is_empty() && !part.starts_with('{'))
.collect();
if prefix.len() < take || prefix.is_empty() {
return uri.trim_matches('/').to_owned();
}
format!("{}/*", prefix.join("/"))
}
fn pattern_matches(pattern: &str, uri: &str) -> bool {
let (pattern, uri) = (pattern.trim_matches('/'), uri.trim_matches('/'));
match pattern.strip_suffix("/*") {
Some(prefix) => {
uri == prefix
|| uri
.strip_prefix(prefix)
.is_some_and(|rest| rest.starts_with('/'))
}
None => pattern == uri,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_route_is_proposed_under_its_prefix() {
assert_eq!(
pattern_of("api/billing/invoices/{invoice}"),
"api/billing/*"
);
assert_eq!(pattern_of("billing/invoices"), "billing/*");
assert_eq!(pattern_of("checkout"), "checkout/*");
assert_eq!(pattern_of("/api/billing"), "api/billing/*");
assert_eq!(pattern_of("{tenant}/invoices"), "{tenant}/invoices");
assert_eq!(
pattern_of("api/{version}/invoices"),
"api/{version}/invoices"
);
assert_eq!(pattern_of("api"), "api");
assert_eq!(pattern_of("/"), "/");
assert_eq!(pattern_of(""), "/");
assert!(pattern_matches("/", "/"));
assert!(pattern_matches("billing/*", "billing"));
assert!(pattern_matches("billing/*", "billing/invoices/{invoice}"));
assert!(!pattern_matches("billing/*", "billings/list"));
assert!(pattern_matches("checkout/confirm", "checkout/confirm"));
assert!(!pattern_matches("checkout/confirm", "checkout/confirm/now"));
}
}