use crate::model::slugify;
use crate::store::{self, Store};
use anyhow::{Context, Result, bail};
use std::fmt::Write;
use std::fs;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
macro_rules! description_scope {
() => {
"what the app is, its services and how they connect, conventions they share: the big picture, in at most \
five lines, without tables, columns, function signatures, files or dependencies, which the code \
already says"
};
}
pub(crate) use description_scope;
pub const REGISTRY_FILE: &str = "projects.md";
pub const PROJECT_FILE: &str = "project.md";
const CARDS_DIR: &str = "projects";
pub const CENTRAL: &str = "central";
const DESCRIPTION_TEMPLATE: &str = "What the application is, its services and how they connect, and the \
conventions they share: what an agent should know before touching any of its repositories.";
const OLD_DESCRIPTION_TEMPLATE: &str = "What this project is for, its stack and its conventions: \
what an agent should know before touching any of its repositories.";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Repo {
pub project: String,
pub dir: PathBuf,
}
impl Repo {
pub fn name(&self) -> String {
self.dir
.parent()
.and_then(Path::file_name)
.map_or_else(|| self.project.clone(), |n| n.to_string_lossy().into_owned())
}
pub fn label(&self, repos: &[Repo]) -> String {
if repos.iter().filter(|r| r.project == self.project).count() > 1 {
format!("{}/{}", self.project, self.name())
} else {
self.project.clone()
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectInfo {
pub name: String,
pub description: String,
pub repo: String,
pub notes: String,
pub siblings: Vec<(String, PathBuf)>,
}
pub fn central_dir() -> Result<PathBuf> {
if let Some(dir) = std::env::var_os("KANBRAIN_DIR") {
return Ok(dir.into());
}
Ok(dirs::data_dir().context("could not determine the data directory; set KANBRAIN_DIR")?.join("kanbrain"))
}
pub fn load(central: &Path) -> Result<Vec<Repo>> {
let path = central.join(REGISTRY_FILE);
let text = match fs::read_to_string(&path) {
Ok(text) => text,
Err(e) if e.kind() == ErrorKind::NotFound => return Ok(Vec::new()),
Err(e) => return Err(e).with_context(|| format!("reading {}", path.display())),
};
Ok(text
.lines()
.filter_map(|line| line.strip_prefix("- ")?.split_once(": "))
.map(|(project, dir)| Repo { project: project.trim().to_string(), dir: PathBuf::from(dir.trim()) })
.collect())
}
pub fn find(central: &Path, label: &str) -> Result<Repo> {
let repos = load(central)?;
if let Some(repo) = repos.iter().find(|r| r.label(&repos) == label) {
return Ok(repo.clone());
}
if repos.is_empty() {
bail!("no project `{label}`: none is registered yet (see `kb init`)");
}
let labels: Vec<String> = repos.iter().map(|r| r.label(&repos)).collect();
let hint = if repos.iter().any(|r| r.project == label) { " (it has several repositories: name one)" } else { "" };
bail!("no project `{label}`{hint}; there are {}, and `{CENTRAL}`", labels.join(", "))
}
pub fn register(central: &Path, project: &str, dir: &Path) -> Result<()> {
check_name(project)?;
let mut repos = load(central)?;
let new = Repo { project: project.to_string(), dir: dir.to_path_buf() };
if repos.contains(&new) {
return Ok(());
}
repos.retain(|r| r.dir != dir);
if let Some(twin) = repos.iter().find(|r| r.project == project && r.name() == new.name() && r.dir.is_dir()) {
bail!(
"project `{project}` already has a repository named `{}`, at {}; rename one of the folders",
new.name(),
twin.dir.display()
);
}
repos.retain(|r| !(r.project == project && r.name() == new.name()));
repos.push(new);
save(central, &repos)
}
pub fn unregister(central: &Path, dir: &Path) -> Result<Option<Repo>> {
let mut repos = load(central)?;
let Some(at) = repos.iter().position(|r| same_dir(&r.dir, dir)) else { return Ok(None) };
let repo = repos.remove(at);
save(central, &repos)?;
Ok(Some(repo))
}
fn check_name(name: &str) -> Result<()> {
if name.trim().is_empty() || name.contains([':', '/', '\n']) || name.trim() != name {
bail!("`{name}` can't be a project name: it needs to be one line, without `:`, `/` or surrounding spaces");
}
if name == CENTRAL {
bail!("`{CENTRAL}` is the name of the central brain; pick another: `kb init NAME`");
}
Ok(())
}
fn save(central: &Path, repos: &[Repo]) -> Result<()> {
Store::at(central)?;
let mut text = String::from(
"# Projects\n\nRepositories with their own `.brain/`, registered by `kb init`; several lines \
with the same name are one project's repositories. The kanban app shows them all.\n\n",
);
for r in repos {
writeln!(text, "- {}: {}", r.project, r.dir.display()).expect("writing to a String cannot fail");
}
store::write_file(¢ral.join(REGISTRY_FILE), &text)
}
pub fn read_repo_card(dir: &Path) -> Option<(String, String)> {
let text = fs::read_to_string(dir.join(PROJECT_FILE)).ok()?;
let mut lines = text.lines();
let name = lines.by_ref().find_map(|l| l.strip_prefix("# "))?.trim().to_string();
Some((name, lines.collect::<Vec<_>>().join("\n").trim().to_string()))
}
pub fn write_repo_card(dir: &Path, project: &str, notes: &str) -> Result<()> {
let notes = notes.trim();
let text = if notes.is_empty() { format!("# {project}\n") } else { format!("# {project}\n\n{notes}\n") };
store::write_file(&dir.join(PROJECT_FILE), &text)
}
fn card_path(central: &Path, project: &str) -> PathBuf {
central.join(CARDS_DIR).join(format!("{}.md", slugify(project)))
}
pub fn read_description(central: &Path, project: &str) -> String {
let text = fs::read_to_string(card_path(central, project)).unwrap_or_default();
let body = text.lines().skip_while(|l| !l.starts_with("# ")).skip(1).collect::<Vec<_>>().join("\n");
match body.trim() {
DESCRIPTION_TEMPLATE | OLD_DESCRIPTION_TEMPLATE => String::new(),
described => described.to_string(),
}
}
pub fn write_description(central: &Path, project: &str, description: &str) -> Result<()> {
store::write_file(&card_path(central, project), &format!("# {project}\n\n{}\n", description.trim()))
}
pub fn ensure_description(central: &Path, project: &str) -> Result<bool> {
if card_path(central, project).is_file() {
return Ok(false);
}
write_description(central, project, DESCRIPTION_TEMPLATE)?;
Ok(true)
}
pub fn remove_description(central: &Path, project: &str) -> Result<bool> {
let path = card_path(central, project);
match fs::remove_file(&path) {
Ok(()) => Ok(true),
Err(e) if e.kind() == ErrorKind::NotFound => Ok(false),
Err(e) => Err(e).with_context(|| format!("removing {}", path.display())),
}
}
pub fn info(dir: &Path, central: Option<&Path>) -> Option<ProjectInfo> {
let (name, notes) = read_repo_card(dir)?;
let repo = Repo { project: name.clone(), dir: dir.to_path_buf() }.name();
let (description, siblings) = match central {
Some(central) => {
let siblings = load(central)
.unwrap_or_default()
.into_iter()
.filter(|r| r.project == name && !same_dir(&r.dir, dir))
.map(|r| (r.name(), r.dir))
.collect();
(read_description(central, &name), siblings)
}
None => (String::new(), Vec::new()),
};
Some(ProjectInfo { name, description, repo, notes, siblings })
}
pub fn same_dir(a: &Path, b: &Path) -> bool {
a == b || fs::canonicalize(a).is_ok_and(|a| fs::canonicalize(b).ok() == Some(a))
}
#[cfg(test)]
#[path = "../tests/projects.rs"]
mod tests;