use std::path::{Path, PathBuf};
use crate::file::paths::FileProvider;
use super::build::{self, Database};
use super::config::{ConfigReport, load_config};
#[derive(Debug, Clone)]
pub struct ProjectDiscovery {
pub root: PathBuf,
pub config: ConfigReport,
pub database: Option<Database>,
pub problems: Vec<DiscoveryProblem>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiscoveryProblem {
pub severity: super::Severity,
pub message: String,
}
impl DiscoveryProblem {
fn warning(message: impl Into<String>) -> Self {
DiscoveryProblem {
severity: super::Severity::Warning,
message: message.into(),
}
}
}
impl ProjectDiscovery {
pub fn flags(&self) -> Vec<String> {
if let Some(args) = &self.config.config.compile.args {
return args.clone();
}
if let Some(database) = &self.database
&& let Some(command) = database.commands.commands.first()
{
return command.arguments.clone();
}
Vec::new()
}
pub fn working_directory(&self) -> Option<PathBuf> {
self.database
.as_ref()
.and_then(|database| database.commands.commands.first())
.and_then(|command| command.directory.clone())
}
pub fn standard(&self) -> Option<String> {
let command = self
.database
.as_ref()?
.commands
.commands
.first()?
.arguments
.clone();
standard_in(&command)
}
pub fn named_compilers(&self) -> Vec<(PathBuf, crate::ToolchainSource)> {
let mut named = Vec::new();
if let Some(compiler) = self.config.config.compile.named_compiler() {
named.push((
PathBuf::from(compiler),
crate::ToolchainSource::Configuration,
));
}
if let Some(database) = &self.database
&& let Some(program) = database
.commands
.commands
.first()
.and_then(|command| command.arguments.first())
{
named.push((
PathBuf::from(program),
crate::ToolchainSource::CompileDatabase,
));
}
named
}
pub fn errors(&self) -> impl Iterator<Item = &str> {
self.config
.errors()
.map(|problem| problem.message.as_str())
.chain(
self.problems
.iter()
.filter(|problem| problem.severity == super::Severity::Error)
.map(|problem| problem.message.as_str()),
)
}
}
fn standard_in(arguments: &[String]) -> Option<String> {
const JOINED: &[&str] = &["-std=", "-std:", "/std:", "/std="];
const SEPARATED: &[&str] = &["-std", "/std"];
for (at, argument) in arguments.iter().enumerate() {
for spelling in JOINED {
if let Some(value) = argument.strip_prefix(spelling) {
return non_empty(value);
}
}
if SEPARATED.contains(&argument.as_str())
&& let Some(value) = arguments.get(at + 1)
{
return non_empty(value);
}
}
None
}
fn non_empty(value: &str) -> Option<String> {
let value = value.trim();
(!value.is_empty()).then(|| value.to_string())
}
pub fn discover(
files: &impl FileProvider,
root: &Path,
config_file: Option<&Path>,
) -> ProjectDiscovery {
let config = load_config(files, root, config_file);
let mut problems: Vec<DiscoveryProblem> = Vec::new();
let (database, database_problems) =
build::find_database(files, root, config.config.compile.database.as_deref());
problems.extend(database_problems.into_iter().map(DiscoveryProblem::warning));
if database.is_none() && config.config.compile.args.is_none() {
problems.push(DiscoveryProblem::warning(
"no compile database was found, so this project is analysed with the compiler's own defaults: export \
one (`compile_commands.json`, which every build system can produce), or write [compile].args in \
.cppls.toml",
));
}
if let Some(database) = &database
&& database.origin == build::DatabaseOrigin::BuildDirectory
{
problems.push(DiscoveryProblem::warning(format!(
"the compile database was found in a build directory: {}",
database.path.display()
)));
}
ProjectDiscovery {
root: root.to_path_buf(),
config,
database,
problems,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::MemoryFiles;
#[test]
fn the_files_flags_win_and_nothing_else_is_consulted() {
let files = MemoryFiles::new()
.with_file("/p/.cppls.toml", "[compile]\nargs = [\"-DFROM_CONFIG\"]\n");
let found = discover(&files, Path::new("/p"), None);
assert_eq!(found.flags(), ["-DFROM_CONFIG"]);
assert!(
found.database.is_none(),
"a file that says how it is built needs no build to be found"
);
assert!(
found
.problems
.iter()
.all(|problem| !problem.message.contains("no compile database")),
"and is not told to export one: {:?}",
found.problems
);
}
#[test]
fn a_project_with_neither_a_database_nor_its_own_flags_is_told_what_to_do() {
let files = MemoryFiles::new();
let found = discover(&files, Path::new("/p"), None);
assert!(
found
.problems
.iter()
.any(|problem| problem.message.contains("no compile database")),
"{:?}",
found.problems
);
}
#[test]
fn the_standard_is_read_out_of_the_builds_own_command_line() {
assert_eq!(
standard_in(&["g++".into(), "-std=c++20".into()]),
Some("c++20".into())
);
assert_eq!(
standard_in(&["clang++".into(), "-std".into(), "c++17".into()]),
Some("c++17".into())
);
assert_eq!(
standard_in(&["cl.exe".into(), "/std:c++latest".into()]),
Some("c++latest".into())
);
assert_eq!(standard_in(&["g++".into(), "-O2".into()]), None);
}
#[test]
fn a_project_that_names_everything_names_it_in_one_order() {
let files = MemoryFiles::new()
.with_file(
"/p/.cppls.toml",
"[compile]\ncompiler = \"/opt/gcc/bin/g++\"\n",
)
.with_file(
"/p/compile_commands.json",
"[\n {\"directory\": \"/p\", \"file\": \"/p/a.cpp\", \"arguments\": [\"clang++\", \"-std=c++20\", \"-c\", \"/p/a.cpp\"]}\n]\n",
);
let found = discover(&files, Path::new("/p"), None);
let sources: Vec<crate::ToolchainSource> = found
.named_compilers()
.into_iter()
.map(|(_, source)| source)
.collect();
assert_eq!(
sources,
[
crate::ToolchainSource::Configuration,
crate::ToolchainSource::CompileDatabase,
],
"the order the discovery follows, and the labels it reports"
);
assert_eq!(found.standard(), Some("c++20".to_string()));
}
#[test]
fn a_database_in_a_build_directory_is_said_out_loud() {
let root = std::env::temp_dir().join("cppls-discovery-build-dir");
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(root.join("build")).expect("the fixture directory");
std::fs::write(
root.join("build/compile_commands.json"),
"[\n {\"directory\": \"/p\", \"file\": \"/p/a.cpp\", \"arguments\": [\"g++\", \"-c\", \"/p/a.cpp\"]}\n]\n",
)
.expect("the fixture writes");
let found = discover(&crate::DiskFiles, &root, None);
assert_eq!(
found.database.as_ref().map(|database| database.origin),
Some(build::DatabaseOrigin::BuildDirectory)
);
assert!(
found
.problems
.iter()
.any(|problem| problem.message.contains("build directory")),
"{:?}",
found.problems
);
let _ = std::fs::remove_dir_all(&root);
}
}