use std::path::{Path, PathBuf};
use std::process::Command;
pub const DIR: &str = "mnemo";
pub const FILE: &str = "project.mnemo";
pub fn start_dir(moved: bool) -> Result<(PathBuf, bool), String> {
if !moved {
if let Some(d) = std::env::var_os("CLAUDE_PROJECT_DIR").map(PathBuf::from) {
if d.is_absolute() {
return Ok((d, true));
}
}
}
std::env::current_dir()
.map(|d| (d, false))
.map_err(|e| format!("can't read the working directory: {e}"))
}
pub fn find(moved: bool, quiet: bool) -> Result<PathBuf, String> {
let (start, from_env) = start_dir(moved)?;
let common = common_dir(&start)?;
if from_env && !quiet {
if let Ok(cwd) = std::env::current_dir() {
let here = std::fs::canonicalize(&cwd).unwrap_or(cwd);
let there = std::fs::canonicalize(&start).unwrap_or_else(|_| start.clone());
if here != there {
if let Ok(other) = common_dir(&here) {
if other != common {
eprintln!(
"mnemo: using the project brain of $CLAUDE_PROJECT_DIR ({}); \
-C . uses this directory's",
common.join(DIR).join(FILE).display()
);
}
}
}
}
}
let brain = common.join(DIR).join(FILE);
refuse_link(&brain)?;
Ok(brain)
}
pub fn refuse_link(brain: &Path) -> Result<(), String> {
let dir = brain.parent().unwrap_or(brain);
for p in [dir, brain] {
if std::fs::symlink_metadata(p).is_ok_and(|m| m.file_type().is_symlink()) {
return Err(format!(
"{} is a symbolic link; a project brain found without a path must be a real \
file in a real directory (give the brain's path to use it)",
p.display()
));
}
}
Ok(())
}
pub fn common_dir_fast(start: &Path) -> Option<PathBuf> {
for v in [
"GIT_DIR",
"GIT_COMMON_DIR",
"GIT_WORK_TREE",
"GIT_CEILING_DIRECTORIES",
"GIT_DISCOVERY_ACROSS_FILESYSTEM",
] {
if std::env::var_os(v).is_some() {
return None;
}
}
let mut d = Some(start);
while let Some(dir) = d {
if dir.join("HEAD").is_file() && dir.join("objects").is_dir() && dir.join("refs").is_dir() {
return None;
}
let dot = dir.join(".git");
match std::fs::symlink_metadata(&dot) {
Ok(m) if m.is_dir() => return Some(dot),
Ok(m) if m.is_file() => {
let text = std::fs::read_to_string(&dot).ok()?;
let gitdir = text.trim_end().strip_prefix("gitdir: ")?;
let gitdir = dir.join(gitdir);
return match std::fs::read_to_string(gitdir.join("commondir")) {
Ok(c) => Some(gitdir.join(c.trim_end())),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Some(gitdir),
Err(_) => None,
};
}
Ok(_) => return None,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => d = dir.parent(),
Err(_) => return None,
}
}
None
}
pub fn common_dir(start: &Path) -> Result<PathBuf, String> {
let out = Command::new("git")
.args(["rev-parse", "--git-common-dir"])
.current_dir(start)
.stdin(std::process::Stdio::null())
.output()
.map_err(|e| {
if e.kind() == std::io::ErrorKind::NotFound {
format!(
"no project brain here: finding it needs git, which isn't on the PATH; \
give the brain's path ({e})"
)
} else {
format!(
"no project brain here: git didn't run in {}: {e}",
start.display()
)
}
})?;
if !out.status.success() {
return Err(format!(
"no project brain here: {} isn't in a git repository; run this in one, or give \
the brain's path",
start.display()
));
}
let text = String::from_utf8(out.stdout)
.map_err(|_| "no project brain here: git printed a path that isn't UTF-8".to_string())?;
let line = text.trim_end_matches(['\n', '\r']);
if line.is_empty() {
return Err("no project brain here: git printed no common dir".into());
}
let dir = start.join(line);
std::fs::canonicalize(&dir)
.map(plain)
.map_err(|e| format!("no project brain here: {}: {e}", dir.display()))
}
pub fn plain(p: PathBuf) -> PathBuf {
let s = p.to_string_lossy();
if let Some(rest) = s.strip_prefix(r"\\?\UNC\") {
return PathBuf::from(format!(r"\\{rest}"));
}
match s.strip_prefix(r"\\?\") {
Some(rest) if rest.len() < 260 && rest.as_bytes().get(1) == Some(&b':') => {
PathBuf::from(rest)
}
_ => p,
}
}
pub fn create_dir(brain: &Path) -> Result<(), String> {
let dir = brain
.parent()
.ok_or_else(|| format!("{}: no parent directory", brain.display()))?;
match std::fs::symlink_metadata(dir) {
Ok(m) if m.file_type().is_symlink() => {
return Err(format!(
"{} is a symbolic link; the project brain's directory must be a real one",
dir.display()
))
}
Ok(m) if m.is_dir() => return Ok(()),
Ok(_) => return Err(format!("{} exists and isn't a directory", dir.display())),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(format!("{}: {e}", dir.display())),
}
#[cfg_attr(not(unix), allow(unused_mut))]
let mut b = std::fs::DirBuilder::new();
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt;
b.mode(0o700);
}
match b.create(dir) {
Ok(()) => Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
match std::fs::symlink_metadata(dir) {
Ok(m) if m.is_dir() => Ok(()),
_ => Err(format!(
"{} appeared while it was being created, and isn't a directory",
dir.display()
)),
}
}
Err(e) => Err(format!("can't create {}: {e}", dir.display())),
}
}
pub const EXCLUDE_OPEN: &str =
"# >>> mnemo onboard: files it wrote for this user (mnemo onboard --undo removes this block)";
pub const EXCLUDE_CLOSE: &str = "# <<< mnemo onboard";
pub fn exclude_path(common: &Path) -> PathBuf {
common.join("info").join("exclude")
}
pub fn with_excluded(text: &str, lines: &[String]) -> String {
let mut before = Vec::new();
let mut after = Vec::new();
let mut inside: Vec<String> = Vec::new();
let mut state = 0; for l in text.lines() {
match state {
0 if l == EXCLUDE_OPEN => state = 1,
1 if l == EXCLUDE_CLOSE => state = 2,
1 if !l.starts_with('/') => {
state = 2;
after.push(l.to_string());
}
0 => before.push(l.to_string()),
1 => inside.push(l.to_string()),
_ => after.push(l.to_string()),
}
}
let mut keep: Vec<String> = Vec::new();
if !lines.is_empty() {
for l in inside.iter().chain(lines) {
if !keep.contains(l) {
keep.push(l.clone());
}
}
}
let mut out: Vec<String> = before;
if !keep.is_empty() {
out.push(EXCLUDE_OPEN.to_string());
out.extend(keep);
out.push(EXCLUDE_CLOSE.to_string());
}
out.extend(after);
let mut s = out.join("\n");
if !s.is_empty() {
s.push('\n');
}
s
}
pub fn exclude_line(root: &Path, file: &Path) -> Option<String> {
let rel = file.strip_prefix(root).ok()?;
let parts: Vec<String> = rel
.components()
.map(|c| c.as_os_str().to_string_lossy().into_owned())
.collect();
Some(format!("/{}", parts.join("/")))
}
pub fn toplevel(start: &Path) -> Result<PathBuf, String> {
let out = Command::new("git")
.args(["rev-parse", "--show-toplevel"])
.current_dir(start)
.stdin(std::process::Stdio::null())
.output()
.map_err(|e| format!("git didn't run: {e}"))?;
if !out.status.success() {
return Err(format!(
"{} isn't in a git work tree; run this in one",
start.display()
));
}
let p = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim().to_string());
std::fs::canonicalize(&p)
.map(plain)
.map_err(|e| format!("{}: {e}", p.display()))
}
pub fn tracked(root: &Path, file: &Path) -> bool {
Command::new("git")
.args(["ls-files", "--error-unmatch", "--"])
.arg(file)
.current_dir(root)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.is_ok_and(|s| s.success())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn plain_drops_the_verbatim_prefix() {
assert_eq!(
plain(PathBuf::from(r"\\?\C:\x\mnemo.exe")),
PathBuf::from(r"C:\x\mnemo.exe")
);
assert_eq!(
plain(PathBuf::from(r"\\?\UNC\srv\share\a")),
PathBuf::from(r"\\srv\share\a")
);
assert_eq!(
plain(PathBuf::from("/usr/bin/mnemo")),
PathBuf::from("/usr/bin/mnemo")
);
}
#[test]
fn the_exclude_block_is_added_once_and_removed_whole() {
let base = "# git's own\n*.log\n";
let a = with_excluded(base, &["/.cursor/mcp.json".into()]);
assert!(a.starts_with(base), "{a}");
assert_eq!(a.matches(EXCLUDE_OPEN).count(), 1);
let b = with_excluded(&a, &["/.cursor/mcp.json".into(), "/.mcp.json".into()]);
assert_eq!(b.matches("/.cursor/mcp.json").count(), 1, "{b}");
assert!(b.contains("/.mcp.json"));
assert_eq!(with_excluded(&b, &[]), base);
assert_eq!(with_excluded("", &[]), "");
let open = format!("{base}{EXCLUDE_OPEN}\n/.mcp.json\n\n# mine\n*.tmp\n");
assert_eq!(
with_excluded(&open, &[]),
format!("{base}\n# mine\n*.tmp\n")
);
}
}