use std::future::Future;
use std::pin::Pin;
use laravel::console::{Console, clap};
use laravel::container::{Inject, Registrar};
use laravel::db::IntoExpr;
use laravel::foundation::ServiceProvider;
use crate::node::NestedSet;
type Boxed<T> = Pin<Box<dyn Future<Output = laravel::Result<T>> + Send>>;
type Findings = Vec<(&'static str, Vec<String>)>;
#[derive(Clone, Copy)]
struct Entry {
table: &'static str,
check: fn() -> Boxed<Findings>,
fix: fn() -> Boxed<u64>,
}
fn check<M: NestedSet>() -> Boxed<Findings> {
Box::pin(async {
let report = M::check_tree().await?;
let keys = |keys: Vec<M::Key>| keys.iter().map(ToString::to_string).collect::<Vec<_>>();
Ok(vec![
("bad bounds", keys(report.oddness)),
("shared bounds", keys(report.duplicates)),
("parent_id doesn't match the bounds", keys(report.wrong_parent)),
("parent_id points to no node", keys(report.missing_parent)),
])
})
}
fn fix<M: NestedSet>() -> Boxed<u64>
where
Option<M::Key>: IntoExpr,
{
Box::pin(M::fix_tree())
}
struct NestedSetModels(Vec<Entry>);
impl NestedSetModels {
fn select(&self, table: Option<&str>) -> Vec<Entry> {
self.0
.iter()
.filter(|entry| table.is_none_or(|table| entry.table == table))
.copied()
.collect()
}
}
#[derive(Clone, Default)]
pub struct NestedSetServiceProvider {
models: Vec<Entry>,
}
impl NestedSetServiceProvider {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn model<M: NestedSet>(mut self) -> Self
where
Option<M::Key>: IntoExpr,
{
self.models.push(Entry {
table: M::META.table,
check: check::<M>,
fix: fix::<M>,
});
self
}
}
impl ServiceProvider for NestedSetServiceProvider {
fn register(&self, app: &mut Registrar) {
app.instance(NestedSetModels(self.models.clone()));
let commands = app.commands();
commands.add::<CheckCommand>();
commands.add::<FixCommand>();
}
}
#[derive(clap::Parser)]
#[command(name = "nestedset:check")]
struct CheckCommand {
table: Option<String>,
}
#[laravel::console::command]
impl CheckCommand {
async fn handle(self, console: &mut Console, models: Inject<NestedSetModels>) -> laravel::Result<u8> {
let Some(entries) = selected(&models, self.table.as_deref(), console) else {
return Ok(2);
};
let mut broken = false;
for entry in entries {
let findings = (entry.check)().await?;
if findings.iter().all(|(_, keys)| keys.is_empty()) {
console.success(format!("`{}` is valid.", entry.table));
continue;
}
broken = true;
console.error(format!("`{}` is broken.", entry.table));
for (kind, keys) in findings.into_iter().filter(|(_, keys)| !keys.is_empty()) {
console.line(format!(" {kind}: {}", shorten(&keys)));
}
}
if broken {
console.info("Run `nestedset:fix` to rebuild the bounds from parent_id.");
}
Ok(u8::from(broken))
}
}
#[derive(clap::Parser)]
#[command(name = "nestedset:fix")]
struct FixCommand {
table: Option<String>,
}
#[laravel::console::command]
impl FixCommand {
async fn handle(self, console: &mut Console, models: Inject<NestedSetModels>) -> laravel::Result<u8> {
let Some(entries) = selected(&models, self.table.as_deref(), console) else {
return Ok(2);
};
for entry in entries {
match (entry.fix)().await? {
0 => console.success(format!("`{}` needed no changes.", entry.table)),
changed => console.success(format!("`{}`: fixed {changed} rows.", entry.table)),
}
}
Ok(0)
}
}
fn selected(models: &NestedSetModels, table: Option<&str>, console: &mut Console) -> Option<Vec<Entry>> {
let entries = models.select(table);
if !entries.is_empty() {
return Some(entries);
}
match table {
Some(table) => console.error(format!(
"No nested set model uses the table `{table}`. Add it with `NestedSetServiceProvider::model`."
)),
None => console.error("No nested set models are registered. Add them with `NestedSetServiceProvider::model`."),
}
None
}
fn shorten(keys: &[String]) -> String {
const SHOWN: usize = 20;
let shown = keys.iter().take(SHOWN).cloned().collect::<Vec<_>>().join(", ");
match keys.len().saturating_sub(SHOWN) {
0 => shown,
more => format!("{shown} and {more} more"),
}
}