Find user configuration even if there’s no project directory (#216)

This commit is contained in:
Anders Kaseorg 2022-09-16 20:47:15 -07:00 committed by GitHub
parent 9bdb922c75
commit b8f878df5e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 23 additions and 21 deletions

View File

@ -10,24 +10,22 @@ use crate::checks::CheckCode;
use crate::fs; use crate::fs;
pub fn load_config(paths: &[PathBuf]) -> Config { pub fn load_config(paths: &[PathBuf]) -> Config {
match find_project_root(paths) { let project_root = find_project_root(paths);
Some(project_root) => match find_pyproject_toml(&project_root) { match find_pyproject_toml(project_root.as_deref()) {
Some(path) => { Some(path) => {
debug!("Found pyproject.toml at: {:?}", path); debug!("Found pyproject.toml at: {:?}", path);
match parse_pyproject_toml(&path) { match parse_pyproject_toml(&path) {
Ok(pyproject) => pyproject Ok(pyproject) => pyproject
.tool .tool
.and_then(|tool| tool.ruff) .and_then(|tool| tool.ruff)
.unwrap_or_default(), .unwrap_or_default(),
Err(e) => { Err(e) => {
println!("Failed to load pyproject.toml: {:?}", e); println!("Failed to load pyproject.toml: {:?}", e);
println!("Falling back to default configuration..."); println!("Falling back to default configuration...");
Default::default() Default::default()
}
} }
} }
None => Default::default(), }
},
None => Default::default(), None => Default::default(),
} }
} }
@ -57,11 +55,14 @@ fn parse_pyproject_toml(path: &Path) -> Result<PyProject> {
toml::from_str(&contents).map_err(|e| e.into()) toml::from_str(&contents).map_err(|e| e.into())
} }
fn find_pyproject_toml(path: &Path) -> Option<PathBuf> { fn find_pyproject_toml(path: Option<&Path>) -> Option<PathBuf> {
let path_pyproject_toml = path.join("pyproject.toml"); if let Some(path) = path {
if path_pyproject_toml.is_file() { let path_pyproject_toml = path.join("pyproject.toml");
return Some(path_pyproject_toml); if path_pyproject_toml.is_file() {
return Some(path_pyproject_toml);
}
} }
find_user_pyproject_toml() find_user_pyproject_toml()
} }
@ -252,7 +253,8 @@ other-attribute = 1
.expect("Unable to find project root."); .expect("Unable to find project root.");
assert_eq!(project_root, cwd.join("resources/test/fixtures")); assert_eq!(project_root, cwd.join("resources/test/fixtures"));
let path = find_pyproject_toml(&project_root).expect("Unable to find pyproject.toml."); let path =
find_pyproject_toml(Some(&project_root)).expect("Unable to find pyproject.toml.");
assert_eq!(path, cwd.join("resources/test/fixtures/pyproject.toml")); assert_eq!(path, cwd.join("resources/test/fixtures/pyproject.toml"));
let pyproject = parse_pyproject_toml(&path)?; let pyproject = parse_pyproject_toml(&path)?;