use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use crate::file::paths::FileProvider;
use crate::include::config::{CompileCommands, parse_compile_commands};
pub const COMPILE_DATABASE_FILE: &str = "compile_commands.json";
pub const MAX_DEPTH: usize = 3;
pub const MAX_DIRECTORIES: usize = 2000;
const NEVER_SEARCHED: &[&str] = &[".git", crate::CACHE_DIRECTORY, "node_modules"];
#[derive(Debug, Clone)]
pub struct Database {
pub path: PathBuf,
pub commands: CompileCommands,
pub origin: DatabaseOrigin,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DatabaseOrigin {
Configured,
Root,
BuildDirectory,
}
impl DatabaseOrigin {
pub fn words(self) -> &'static str {
match self {
DatabaseOrigin::Configured => "named by compile.database in .cppls.toml",
DatabaseOrigin::Root => "in the project root",
DatabaseOrigin::BuildDirectory => "found in a build directory",
}
}
}
pub fn find_database(
files: &impl FileProvider,
root: &Path,
configured: Option<&Path>,
) -> (Option<Database>, Vec<String>) {
let mut problems = Vec::new();
if let Some(named) = configured {
let path = if named.is_absolute() {
named.to_path_buf()
} else {
root.join(named)
};
return match read_database(files, &path) {
Some(commands) => (
Some(Database {
path,
commands,
origin: DatabaseOrigin::Configured,
}),
problems,
),
None => {
problems.push(format!(
"compile.database names {}, which could not be read as a compile database",
path.display()
));
(None, problems)
}
};
}
let conventional = root.join(COMPILE_DATABASE_FILE);
if let Some(commands) = read_database(files, &conventional) {
return (
Some(Database {
path: conventional,
commands,
origin: DatabaseOrigin::Root,
}),
problems,
);
}
let (found, truncated) = search_for_database(root);
if truncated {
problems.push(format!(
"the search for {COMPILE_DATABASE_FILE} stopped after {MAX_DIRECTORIES} directories; \
compile.database in .cppls.toml can name one directly"
));
}
for path in found {
if let Some(commands) = read_database(files, &path) {
return (
Some(Database {
path,
commands,
origin: DatabaseOrigin::BuildDirectory,
}),
problems,
);
}
}
(None, problems)
}
fn read_database(files: &impl FileProvider, path: &Path) -> Option<CompileCommands> {
let json = files.read(path)?;
let mut database = parse_compile_commands(&json);
for command in &mut database.commands {
let directory = command.directory.clone();
command.arguments = crate::include::config::expand_response_files(
&command.arguments,
directory.as_deref(),
&mut |named| files.read(named),
);
}
(!database.is_empty()).then_some(database)
}
fn search_for_database(root: &Path) -> (Vec<PathBuf>, bool) {
let mut found = Vec::new();
let mut visited = 0usize;
let mut frontier = vec![(root.to_path_buf(), 0usize)];
let mut truncated = false;
while let Some((directory, depth)) = frontier.pop() {
if visited >= MAX_DIRECTORIES {
truncated = true;
break;
}
visited += 1;
let Ok(entries) = std::fs::read_dir(&directory) else {
continue;
};
let mut children: BTreeSet<PathBuf> = BTreeSet::new();
let mut here: Option<PathBuf> = None;
for entry in entries.flatten() {
let path = entry.path();
let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
continue;
};
let Ok(kind) = entry.file_type() else {
continue;
};
if kind.is_symlink() {
continue;
}
if kind.is_file() {
if name == COMPILE_DATABASE_FILE {
here = Some(path);
}
continue;
}
if kind.is_dir()
&& depth < MAX_DEPTH
&& !NEVER_SEARCHED
.iter()
.any(|skip| skip.eq_ignore_ascii_case(name))
{
children.insert(path);
}
}
if let Some(path) = here {
found.push(path);
}
for child in children.into_iter().rev() {
frontier.push((child, depth + 1));
}
}
found.sort_by_key(|path| {
(
path.components().count(),
path.to_string_lossy().to_lowercase(),
)
});
(found, truncated)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::MemoryFiles;
#[test]
fn a_database_in_a_build_directory_is_found_and_the_root_wins_when_it_has_one() {
let root = std::env::temp_dir().join("cppls-build-search");
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(root.join("build/deep")).expect("the fixture directories");
std::fs::create_dir_all(root.join("cmake-build-debug")).expect("the fixture directories");
let entry = |file: &str| {
format!(
"[\n {{\"directory\": \"/p\", \"file\": \"{file}\", \
\"arguments\": [\"g++\", \"-c\", \"{file}\"]}}\n]\n"
)
};
std::fs::write(
root.join("build/deep/compile_commands.json"),
entry("/p/deep.cpp"),
)
.expect("the fixture writes");
std::fs::write(
root.join("cmake-build-debug/compile_commands.json"),
entry("/p/cmake.cpp"),
)
.expect("the fixture writes");
let (found, problems) = find_database(&crate::DiskFiles, &root, None);
assert!(problems.is_empty(), "{problems:?}");
let found = found.expect("a database is found");
assert_eq!(found.origin, DatabaseOrigin::BuildDirectory);
assert_eq!(found.commands.len(), 1);
assert!(
crate::file::paths::normalize_path(&found.path, cfg!(windows))
.ends_with("cmake-build-debug/compile_commands.json"),
"the shallower of the two, and the lexicographically first: {}",
found.path.display()
);
std::fs::write(root.join("compile_commands.json"), entry("/p/root.cpp"))
.expect("the fixture writes");
let (found, _) = find_database(&crate::DiskFiles, &root, None);
let found = found.expect("a database is found");
assert_eq!(found.origin, DatabaseOrigin::Root);
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn a_configured_database_is_the_only_one_read() {
let files = MemoryFiles::new().with_file(
"/p/build/compile_commands.json",
"[\n {\"directory\": \"/p\", \"file\": \"/p/a.cpp\", \"arguments\": [\"g++\", \"-c\", \"/p/a.cpp\"]}\n]\n",
);
let (found, problems) = find_database(
&files,
Path::new("/p"),
Some(Path::new("build/compile_commands.json")),
);
let found = found.expect("the named database is read");
assert_eq!(found.origin, DatabaseOrigin::Configured);
assert!(problems.is_empty());
let (none, problems) =
find_database(&files, Path::new("/p"), Some(Path::new("elsewhere.json")));
assert!(none.is_none());
assert_eq!(problems.len(), 1);
assert!(problems[0].contains("elsewhere.json"));
}
}