Skip to content

Commit

Permalink
help users to use new configuration style
Browse files Browse the repository at this point in the history
using glob patterns
  • Loading branch information
marcmo committed Apr 11, 2017
1 parent ab16e73 commit 3cd90e5
Show file tree
Hide file tree
Showing 8 changed files with 163 additions and 20 deletions.
81 changes: 80 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "enforcer"
version = "0.11.2"
version = "0.12.0"
authors = ["Oliver Mueller <[email protected]>"]

[dependencies]
Expand All @@ -16,3 +16,4 @@ term-painter = "0.2"
ansi_term = "0.7"
glob = "0.2"
num_cpus = "1"
regex = "0.2"
13 changes: 13 additions & 0 deletions samples/.enforcer_old
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
ignore = [
".git",
".rim",
".bake",
"build_*",
"*.o",
"*.s",
"cal",
".cproject",
".project",
"securitySoftware",
"diabCompiler*"]
endings = [".h", ".cpp", ".c", ".meta"]
4 changes: 2 additions & 2 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,9 @@ pub fn app() -> App<'static, 'static> {
.takes_value(true))
.arg(Arg::with_name("status")
.short("s")
.long("status")
.long("config-status")
.value_name("FILE")
.help("show configuration that is used")
.help("check the configuration that is used")
.takes_value(false))
.arg(Arg::with_name("quiet")
.short("q")
Expand Down
6 changes: 3 additions & 3 deletions src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,10 +122,10 @@ impl<'a> ArgMatches<'a> {
endings: endings,
clean: self.is_present("clean"),
config_file: config,
line_length: try!(self.usize_of("L")),
line_length: self.usize_of("L")?,
color: self.is_present("color"),
quiet: quiet,
threads: try!(self.threads()),
threads: self.threads()?,
status: self.is_present("status"),
tabs: self.is_present("tabs"),
};
Expand Down Expand Up @@ -164,7 +164,7 @@ impl<'a> ArgMatches<'a> {

/// Returns the approximate number of threads that enforcer should use.
fn threads(&self) -> Result<usize, num::ParseIntError> {
let threads = try!(self.usize_of("N")).unwrap_or(0);
let threads = self.usize_of("N")?.unwrap_or(0);
Ok(if threads == 0 {
cmp::min(12, num_cpus::get())
} else {
Expand Down
18 changes: 9 additions & 9 deletions src/check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ pub fn is_dir(path: &Path) -> bool {
fn report_offending_line(path: &Path, logger: SyncSender<Option<String>>) -> std::io::Result<()> {
use std::io::BufReader;
let mut i: u32 = 1;
let f = try!(File::open(path));
let f = File::open(path)?;
let file = BufReader::new(f);
for line in file.lines() {
match line.ok() {
Expand Down Expand Up @@ -107,12 +107,12 @@ pub fn check_path(path: &Path,
}
Ok(buffer) => {
if check == 0 {
check = try!(check_content(&buffer,
path.to_str().expect("not available"),
verbose,
max_line_length,
s,
logger.clone()));
check = check_content(&buffer,
path.to_str().expect("not available"),
verbose,
max_line_length,
s,
logger.clone())?;
}
let no_trailing_ws = if (check & TRAILING_SPACES) > 0 && clean {
if verbose {
Expand All @@ -134,8 +134,8 @@ pub fn check_path(path: &Path,
no_trailing_ws
};
if clean {
let mut file = try!(File::create(path));
try!(file.write_all(res_string.as_bytes()));
let mut file = File::create(path)?;
file.write_all(res_string.as_bytes())?;
}
}
};
Expand Down
57 changes: 53 additions & 4 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use std::fs;
use std::io::Read;
use std::path::PathBuf;
use std::io::{Error, ErrorKind};
use regex::Regex;

const DEFAULT_CFG_FILE: &'static str = "./.enforcer";

Expand Down Expand Up @@ -36,12 +37,12 @@ pub fn get_cfg(config_file: &Option<PathBuf>) -> EnforcerCfg {
if !p.as_path().exists() {
println!("provided file {:?} does not exist!", p);
}
try!(fs::File::open(p))
fs::File::open(p)?
}
None => try!(load_default_cfg_file()),
None => load_default_cfg_file()?,
};
let mut buffer = String::new();
try!(cfg_file.read_to_string(&mut buffer));
cfg_file.read_to_string(&mut buffer)?;
parse_config(&buffer[..])
};
match read_enforcer_config(config_file) {
Expand All @@ -60,6 +61,32 @@ fn default_cfg() -> EnforcerCfg {
}
}

fn fix_config(cfg: &EnforcerCfg) -> EnforcerCfg {
EnforcerCfg {
ignore: cfg.ignore.iter().map(|i| suggestion(i)).collect::<Vec<String>>(),
endings: cfg.endings.clone(),
}
}

fn full_match(r: &Regex, s: &str) -> bool {
if let Some(mat) = r.find(s) {
mat.start() == 0 && mat.end() == s.len()
} else {
false
}
}
fn suggestion(s: &str) -> String {
let full_component = Regex::new(r"([a-zA-Z_\-]+\*?)").expect("valid regex");
let ending = Regex::new(r"(\*?\.[a-zA-Z_\-]+\*?)").expect("valid regex");
if full_match(&full_component, s) {
String::from("**/") + s + "/**"
} else if full_match(&ending, s) {
String::from("**/") + s
} else {
s.to_string()
}
}

pub fn parse_config<'a>(input: &'a str) -> io::Result<EnforcerCfg> {
use std::io::{Error, ErrorKind};
debug!("parse_config");
Expand All @@ -78,7 +105,17 @@ pub fn parse_config<'a>(input: &'a str) -> io::Result<EnforcerCfg> {
let mut decoder = toml::Decoder::new(toml::Value::Table(toml));
EnforcerCfg::decode(&mut decoder)
.ok()
.map_or(Err(default_err()), |config| Ok(config))
.map_or(Err(default_err()), |config| {
let suggested = fix_config(&config);
if suggested.ignore != config.ignore {
println!("old style config found. we will assume this:\n{:?}\nconsider \
changing it! (see http://www.globtester.com/ for reference)",
suggested);
Ok(suggested)
} else {
Ok(config)
}
})
})
}

Expand All @@ -87,6 +124,7 @@ mod tests {
use super::s;
use super::EnforcerCfg;
use super::parse_config;
use super::suggestion;

#[test]
fn test_load_simple_config() {
Expand All @@ -106,4 +144,15 @@ mod tests {
let c = include_str!("../samples/.enforcer_broken");
parse_config(c).unwrap();
}

#[test]
fn test_matches() {
assert_eq!("**/abc/**".to_string(), suggestion("abc"));
assert_eq!("**/.repo".to_string(), suggestion(".repo"));
assert_eq!("**/build_*/**".to_string(), suggestion("build_*"));
assert_eq!("**/*.o".to_string(), suggestion("*.o"));
assert_eq!("**/*.dld".to_string(), suggestion("*.dld"));
assert_eq!("**/*.s".to_string(), suggestion("*.s"));
assert_eq!("**/autosarOs/**".to_string(), suggestion("autosarOs"));
}
}
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ extern crate ansi_term;
extern crate term_painter;
extern crate glob;
extern crate walkdir;
extern crate regex;
#[macro_use]
extern crate log;

Expand Down

0 comments on commit 3cd90e5

Please sign in to comment.