diff --git a/src/config/config_type.rs b/src/config/config_type.rs index 7fc4486ddcd..2ffd618fa01 100644 --- a/src/config/config_type.rs +++ b/src/config/config_type.rs @@ -64,6 +64,8 @@ macro_rules! create_config { // if a license_template_path has been specified, successfully read, parsed and compiled // into a regex, it will be stored here pub license_template: Option, + // The location from which to resolve relative dirs. + root_dir: Option, // For each config item, we store a bool indicating whether it has // been accessed and the value, and a bool whether the option was // manually initialised, or taken from the default, @@ -166,6 +168,7 @@ macro_rules! create_config { self.set_license_template(); self.set_ignore(dir); self.set_merge_imports(); + self.set_root_dir(dir); self } @@ -390,7 +393,7 @@ macro_rules! create_config { if self.was_set().license_template_path() { let lt_path = self.license_template_path(); if lt_path.len() > 0 { - match license::load_and_compile_template(<_path) { + match license::load_and_compile_template(&self.root_dir, <_path) { Ok(re) => self.license_template = Some(re), Err(msg) => eprintln!("Warning for license template file {:?}: {}", lt_path, msg), @@ -405,6 +408,10 @@ macro_rules! create_config { self.ignore.2.add_prefix(dir); } + fn set_root_dir(&mut self, dir: &Path) { + self.root_dir = Some(dir.to_path_buf()); + } + fn set_merge_imports(&mut self) { if self.was_set().merge_imports() { eprintln!( @@ -438,6 +445,7 @@ macro_rules! create_config { fn default() -> Config { Config { license_template: None, + root_dir: None, $( $i: (Cell::new(false), false, $def, $stb), )+ diff --git a/src/config/license.rs b/src/config/license.rs index c7feb502ea9..d163ac312ad 100644 --- a/src/config/license.rs +++ b/src/config/license.rs @@ -211,7 +211,23 @@ impl TemplateParser { } } -pub(crate) fn load_and_compile_template(path: &str) -> Result { +pub(crate) fn load_and_compile_template( + root_dir: &Option, + path: &str, +) -> Result { + let mut path = std::path::PathBuf::from(path); + if path.is_relative() { + if let Some(root_dir) = root_dir { + // The tempate path needs to be resolved relative to the .rustfmt config file + // rather than whatever dir cargo fmt was run from. + let current = std::env::current_dir().expect("pwd"); + std::env::set_current_dir(root_dir).expect("alter pwd"); + if let Ok(abs_path) = path.canonicalize() { + path = abs_path; + } + std::env::set_current_dir(current).expect("change pwd"); + } + } let mut lt_file = File::open(&path)?; let mut lt_str = String::new(); lt_file.read_to_string(&mut lt_str)?;