use std::{
collections::BTreeSet,
fs,
path::{Path, PathBuf},
};
use super::IdTemplate;
use crate::{
RepoPath, RepoRoot, Source,
git::{self, Git, MIN_GIT, NO_LAZY_FETCH, Partial},
model::core_fields,
source::split,
yaml,
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Place {
Branch(String),
Worktree(PathBuf),
}
impl std::fmt::Display for Place {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Place::Branch(name) => write!(f, "on the branch `{name}`"),
Place::Worktree(dir) => write!(f, "in the worktree {}", dir.display()),
}
}
}
#[derive(Debug, Clone)]
pub struct Elsewhere {
pub place: Place,
pub path: RepoPath,
pub id: String,
pub seq: u64,
}
pub struct Scope<'a> {
pub dir: &'a RepoPath,
pub nested: &'a [RepoPath],
}
impl Scope<'_> {
fn holds(&self, path: &RepoPath) -> bool {
path.starts_with(self.dir) && !self.nested.iter().any(|n| path.starts_with(n))
}
fn pathspec(&self) -> &str {
match self.dir.relative() {
"" => ".",
dir => dir,
}
}
}
type Blob = (Place, RepoPath, Option<String>);
pub fn numbers(
root: &RepoRoot,
scope: &Scope<'_>,
type_name: &str,
template: &IdTemplate,
) -> Vec<Elsewhere> {
let git = Git::new(root.as_path());
if git::version().is_none_or(|v| v < MIN_GIT) || !git.is_top() {
return Vec::new();
}
let head = git.head();
let partial = git.partial();
let treeless = partial == Some(Partial::Treeless);
let mut files = worktree_files(&git, head.as_deref(), scope, treeless);
let blobs = if treeless {
Vec::new()
} else {
branch_blobs(&git, head.as_deref(), scope)
};
if partial.is_some() && git::version().is_none_or(|v| v < NO_LAZY_FETCH) {
files.extend(
blobs
.into_iter()
.map(|(_, place, path)| (place, path, None)),
);
} else {
files.extend(read_blobs(&git, &blobs));
}
files
.into_iter()
.filter_map(|(place, path, text)| {
let (id, seq) = match &text {
Some(text) => numbered(&path, text, type_name, template)?,
None => named(&path, template)?,
};
Some(Elsewhere {
place,
path,
id,
seq,
})
})
.collect()
}
fn numbered(
path: &RepoPath,
text: &str,
type_name: &str,
template: &IdTemplate,
) -> Option<(String, u64)> {
let source = Source::from_text(path.clone(), text);
let (front, line) = split(&source).frontmatter?;
let parsed = yaml::parse(front, line);
let core = core_fields(Some(parsed.as_ref()), path);
if core.type_.as_deref() != Some(type_name) {
return None;
}
let id = core.id?;
let seq = template.seq_of(&id)?;
Some((id, seq))
}
fn named(path: &RepoPath, template: &IdTemplate) -> Option<(String, u64)> {
let id = path.file_name().strip_suffix(".md")?;
let seq = template.seq_of(id)?;
Some((id.to_string(), seq))
}
fn changed(git: &Git, base: &str, scope: &Scope<'_>) -> Option<Vec<RepoPath>> {
let out = git.run(&[
"diff-index",
"--raw",
"-z",
"--no-renames",
"--diff-filter=AMT",
base,
"--",
scope.pathspec(),
])?;
Some(
raw(&out)
.filter_map(|(_, path)| md_path(&path, scope))
.collect(),
)
}
fn tracked(git: &Git, scope: &Scope<'_>, others: bool) -> Vec<RepoPath> {
let mut args = vec!["ls-files", "-z"];
if others {
args.extend(["--others", "--exclude-standard"]);
}
args.extend(["--", scope.pathspec()]);
git.run(&args)
.map(|out| {
out.split(|b| *b == 0)
.filter_map(|p| md_path(&String::from_utf8_lossy(p), scope))
.collect()
})
.unwrap_or_default()
}
fn read_blobs(git: &Git, blobs: &[(String, Place, RepoPath)]) -> Vec<Blob> {
let texts = git.blobs(blobs.iter().map(|(oid, _, _)| oid.as_str()));
blobs
.iter()
.map(|(oid, place, path)| {
let text = texts.get(oid.as_str()).cloned().flatten();
(place.clone(), path.clone(), text)
})
.collect()
}
fn raw(out: &[u8]) -> impl Iterator<Item = (String, String)> {
git::raw(out)
.into_iter()
.filter_map(|r| Some((r.after.unwrap_or_default(), r.paths.last()?.clone())))
}
fn md_path(path: &str, scope: &Scope<'_>) -> Option<RepoPath> {
if Path::new(path).extension().is_none_or(|e| e != "md") {
return None;
}
let path = RepoPath::parse(&format!("/{path}"))?;
scope.holds(&path).then_some(path)
}
fn worktree_files(git: &Git, head: Option<&str>, scope: &Scope<'_>, treeless: bool) -> Vec<Blob> {
let own = fs::canonicalize(&git.dir).ok();
let list = git
.run(&["worktree", "list", "--porcelain"])
.unwrap_or_default();
let others: Vec<PathBuf> = String::from_utf8_lossy(&list)
.lines()
.filter_map(|line| line.strip_prefix("worktree "))
.map(PathBuf::from)
.filter(|p| p.is_dir() && fs::canonicalize(p).ok() != own)
.collect();
let mut files = Vec::new();
for wt in others {
let there = Git::new(&wt);
let base = (!treeless)
.then(|| there.head())
.flatten()
.and_then(|commit| git.merge_base(head, &commit));
let mut paths = base
.and_then(|base| changed(&there, &base, scope))
.unwrap_or_else(|| tracked(&there, scope, false));
paths.extend(tracked(&there, scope, true));
let wt_root = RepoRoot::new(wt.clone());
for path in paths {
if let Ok(bytes) = fs::read(path.to_fs(&wt_root)) {
let text = String::from_utf8(bytes).ok();
files.push((Place::Worktree(wt.clone()), path, text));
}
}
}
files
}
fn branch_blobs(
git: &Git,
head: Option<&str>,
scope: &Scope<'_>,
) -> Vec<(String, Place, RepoPath)> {
let mut args = vec![
"for-each-ref",
"--format=%(objectname)%00%(symref)%00%(refname:short)",
];
if let Some(head) = head {
args.extend(["--no-merged", head]);
}
args.extend(["refs/heads", "refs/remotes"]);
let refs = git.run(&args).unwrap_or_default();
let mut commits = BTreeSet::new();
let mut seen = BTreeSet::new();
let mut blobs = Vec::new();
for line in String::from_utf8_lossy(&refs).lines() {
let mut parts = line.split('\0');
let (Some(commit), Some(""), Some(name)) = (parts.next(), parts.next(), parts.next())
else {
continue;
};
if !commits.insert(commit.to_string()) {
continue;
}
let diff = git.merge_base(head, commit).and_then(|base| {
git.run(&[
"diff-tree",
"-r",
"--raw",
"-z",
"--no-renames",
"--no-abbrev",
"--diff-filter=AMT",
&base,
commit,
"--",
scope.pathspec(),
])
});
let entries: Vec<(String, String)> = match diff {
Some(out) => raw(&out).collect(),
None => tree(git, commit, scope),
};
for (oid, path) in entries {
if let Some(path) = md_path(&path, scope)
&& seen.insert((oid.clone(), path.clone()))
{
blobs.push((oid, Place::Branch(name.to_string()), path));
}
}
}
blobs
}
fn tree(git: &Git, commit: &str, scope: &Scope<'_>) -> Vec<(String, String)> {
let Some(out) = git.run(&["ls-tree", "-r", "-z", commit, "--", scope.pathspec()]) else {
return Vec::new();
};
out.split(|b| *b == 0)
.filter_map(|entry| {
let entry = String::from_utf8_lossy(entry);
let (meta, path) = entry.split_once('\t')?;
let mut meta = meta.split(' ');
match (meta.next(), meta.next(), meta.next()) {
(Some(_), Some("blob"), Some(oid)) => Some((oid.to_string(), path.to_string())),
_ => None,
}
})
.collect()
}