Use rustfmt to fix outstanding style issues

This commit is contained in:
Matt Green 2016-10-23 20:12:48 -04:00
parent 6a812d31b4
commit d10b790c35
6 changed files with 110 additions and 103 deletions

View File

@ -33,48 +33,48 @@ pub fn get_args() -> Args {
.multiple(true)
.required(true))
.arg(Arg::with_name("extensions")
.help("Comma-separated list of file extensions to watch (js,css,html)")
.short("e")
.long("exts")
.takes_value(true))
.help("Comma-separated list of file extensions to watch (js,css,html)")
.short("e")
.long("exts")
.takes_value(true))
.arg(Arg::with_name("clear")
.help("Clear screen before executing command")
.short("c")
.long("clear"))
.arg(Arg::with_name("restart")
.help("Restart the process if it's still running")
.short("r")
.long("restart"))
.help("Restart the process if it's still running")
.short("r")
.long("restart"))
.arg(Arg::with_name("debug")
.help("Print debugging messages to stderr")
.short("d")
.long("debug"))
.help("Print debugging messages to stderr")
.short("d")
.long("debug"))
.arg(Arg::with_name("filter")
.help("Ignore all modifications except those matching the pattern")
.short("f")
.long("filter")
.number_of_values(1)
.multiple(true)
.takes_value(true)
.value_name("pattern"))
.help("Ignore all modifications except those matching the pattern")
.short("f")
.long("filter")
.number_of_values(1)
.multiple(true)
.takes_value(true)
.value_name("pattern"))
.arg(Arg::with_name("ignore")
.help("Ignore modifications to paths matching the pattern")
.short("i")
.long("ignore")
.number_of_values(1)
.multiple(true)
.takes_value(true)
.value_name("pattern"))
.help("Ignore modifications to paths matching the pattern")
.short("i")
.long("ignore")
.number_of_values(1)
.multiple(true)
.takes_value(true)
.value_name("pattern"))
.arg(Arg::with_name("no-vcs-ignore")
.help("Skip auto-loading of .gitignore files for filtering")
.long("no-vcs-ignore"))
.help("Skip auto-loading of .gitignore files for filtering")
.long("no-vcs-ignore"))
.arg(Arg::with_name("run-initially")
.help("Run command initially, before first file change")
.long("run-initially"))
.help("Run command initially, before first file change")
.long("run-initially"))
.arg(Arg::with_name("poll")
.help("Forces polling mode")
.long("force-poll")
.value_name("interval"))
.help("Forces polling mode")
.long("force-poll")
.value_name("interval"))
.get_matches();
let cmd = values_t!(args.values_of("command"), String).unwrap().join(" ");
@ -83,10 +83,9 @@ pub fn get_args() -> Args {
if let Some(extensions) = args.values_of("extensions") {
for exts in extensions {
filters.extend(exts
.split(",")
.filter(|ext| !ext.is_empty())
.map(|ext| format!("*.{}", ext.replace(".", ""))));
filters.extend(exts.split(",")
.filter(|ext| !ext.is_empty())
.map(|ext| format!("*.{}", ext.replace(".", ""))));
}
}
@ -102,7 +101,9 @@ pub fn get_args() -> Args {
ignores.extend(values_t!(args.values_of("ignore"), String).unwrap_or(vec![]));
let poll_interval = if args.occurrences_of("poll") > 0 {
value_t!(args.value_of("poll"), u32).unwrap_or_else(|e| e.exit())
} else { 1000 };
} else {
1000
};
Args {
cmd: cmd,
@ -115,6 +116,6 @@ pub fn get_args() -> Args {
run_initially: args.is_present("run-initially"),
no_vcs_ignore: args.is_present("no-vcs-ignore"),
poll: args.occurrences_of("poll") > 0,
poll_interval: poll_interval
poll_interval: poll_interval,
}
}

View File

@ -8,7 +8,7 @@ use std::path::{Path, PathBuf};
// Immutable, ordered set of Patterns
// Used to implement whitelisting
pub struct PatternSet {
patterns: Vec<Pattern>
patterns: Vec<Pattern>,
}
// Represents a single gitignore rule
@ -23,7 +23,7 @@ struct Pattern {
whitelist: bool,
#[allow(dead_code)]
directory: bool,
anchored: bool
anchored: bool,
}
#[derive(Debug)]
@ -39,8 +39,7 @@ pub fn parse(path: &Path) -> Result<PatternSet, Error> {
// If we've opened the file, we'll have at least one other path component
let root = path.parent().unwrap();
let patterns = try!(contents
.lines()
let patterns = try!(contents.lines()
.filter(|l| !l.is_empty())
.filter(|l| !l.starts_with("#"))
.map(|l| Pattern::new(l, root))
@ -51,9 +50,7 @@ pub fn parse(path: &Path) -> Result<PatternSet, Error> {
impl PatternSet {
fn new(patterns: Vec<Pattern>) -> PatternSet {
PatternSet {
patterns: patterns
}
PatternSet { patterns: patterns }
}
// Apply the patterns to the path one-by-one
@ -70,8 +67,7 @@ impl PatternSet {
if matched {
if pattern.whitelist {
excluded = false;
}
else {
} else {
excluded = true;
// We can stop running rules in this case
@ -93,17 +89,23 @@ impl Pattern {
let whitelisted = if normalized.starts_with('!') {
normalized.remove(0);
true
} else { false };
} else {
false
};
let anchored = if normalized.starts_with('/') {
normalized.remove(0);
true
} else { false };
} else {
false
};
let directory = if normalized.ends_with('/') {
normalized.pop();
true
} else { false };
} else {
false
};
if normalized.starts_with("\\#") || normalized.starts_with("\\!") {
normalized.remove(0);
@ -117,7 +119,7 @@ impl Pattern {
root: root.to_path_buf(),
whitelist: whitelisted,
directory: directory,
anchored: anchored
anchored: anchored,
})
}
@ -125,12 +127,12 @@ impl Pattern {
let options = glob::MatchOptions {
case_sensitive: false,
require_literal_separator: true,
require_literal_leading_dot: false
require_literal_leading_dot: false,
};
let stripped_path = match path.strip_prefix(&self.root) {
Ok(p) => p,
Err(_) => return false
Ok(p) => p,
Err(_) => return false,
};
let mut result = false;
@ -138,16 +140,13 @@ impl Pattern {
if self.anchored {
let first_component = stripped_path.iter().next();
result = match first_component {
Some(s) => self.pattern.matches_path_with(Path::new(&s), &options),
None => false
Some(s) => self.pattern.matches_path_with(Path::new(&s), &options),
None => false,
}
}
else if !self.str.contains('/') {
result = stripped_path.iter().any(|c| {
self.pattern.matches_path_with(Path::new(c), &options)
});
}
else if self.pattern.matches_path_with(stripped_path, &options) {
} else if !self.str.contains('/') {
result = stripped_path.iter()
.any(|c| self.pattern.matches_path_with(Path::new(c), &options));
} else if self.pattern.matches_path_with(stripped_path, &options) {
result = true;
}
@ -167,17 +166,17 @@ impl From<io::Error> for Error {
}
}
//fn main() {
//let cwd = env::current_dir().unwrap();
//let gitignore_file = cwd.join(".gitignore");
//let file = File::new(&gitignore_file).unwrap();
// fn main() {
// let cwd = env::current_dir().unwrap();
// let gitignore_file = cwd.join(".gitignore");
// let file = File::new(&gitignore_file).unwrap();
//for arg in env::args().skip(1) {
//let path = cwd.join(&arg);
//let matches = file.is_excluded(&path);
//println!("File: {}, Excluded: {}", arg, matches);
//}
//}
// for arg in env::args().skip(1) {
// let path = cwd.join(&arg);
// let matches = file.is_excluded(&path);
// println!("File: {}, Excluded: {}", arg, matches);
// }
// }
#[cfg(test)]
mod tests {
@ -290,4 +289,3 @@ mod tests {
assert!(!set.is_excluded(&base_dir().join("target").join("foo.txt")));
}
}

View File

@ -1,15 +1,21 @@
#![feature(process_exec)]
#[macro_use] extern crate clap;
#[macro_use]
extern crate clap;
extern crate env_logger;
extern crate libc;
#[macro_use] extern crate log;
#[macro_use] extern crate lazy_static;
#[macro_use]
extern crate log;
#[macro_use]
extern crate lazy_static;
extern crate notify;
#[cfg(unix)] extern crate nix;
#[cfg(windows)] extern crate winapi;
#[cfg(windows)] extern crate kernel32;
#[cfg(unix)]
extern crate nix;
#[cfg(windows)]
extern crate winapi;
#[cfg(windows)]
extern crate kernel32;
mod args;
mod gitignore;
@ -51,11 +57,10 @@ fn init_logger(debug: bool) {
let level = if debug {
log::LogLevelFilter::Debug
} else {
log::LogLevelFilter::Warn
log::LogLevelFilter::Warn
};
log_builder
.format(|r| format!("*** {}", r.args()))
log_builder.format(|r| format!("*** {}", r.args()))
.filter(None, level);
log_builder.init().expect("unable to initialize logger");
}
@ -79,7 +84,8 @@ fn main() {
}
}
let mut filter = NotificationFilter::new(&cwd, gitignore_file).expect("unable to create notification filter");
let mut filter = NotificationFilter::new(&cwd, gitignore_file)
.expect("unable to create notification filter");
for f in args.filters {
filter.add_filter(&f).expect("bad filter");
@ -99,8 +105,8 @@ fn main() {
for path in args.paths {
match Path::new(&path).canonicalize() {
Ok(canonicalized) => watcher.watch(canonicalized).expect("unable to watch path"),
Err(_) => {
Ok(canonicalized) => watcher.watch(canonicalized).expect("unable to watch path"),
Err(_) => {
println!("invalid path: {}", path);
return;
}
@ -144,7 +150,7 @@ fn wait(rx: &Receiver<Event>, filter: &NotificationFilter) -> Result<Event, Recv
// Drain rx buffer and drop them
while let Ok(_) = rx.try_recv() {
// nothing to do here
// nothing to do here
}
return Ok(e);

View File

@ -2,32 +2,34 @@ extern crate glob;
use gitignore;
use std::io;
use std::path::{Path,PathBuf};
use std::path::{Path, PathBuf};
use self::glob::{Pattern,PatternError};
use self::glob::{Pattern, PatternError};
pub struct NotificationFilter {
cwd: PathBuf,
filters: Vec<Pattern>,
ignores: Vec<Pattern>,
ignore_file: Option<gitignore::PatternSet>
ignore_file: Option<gitignore::PatternSet>,
}
#[derive(Debug)]
pub enum NotificationError {
BadPattern(PatternError),
Io(io::Error)
Io(io::Error),
}
impl NotificationFilter {
pub fn new(current_dir: &Path, ignore_file: Option<gitignore::PatternSet>) -> Result<NotificationFilter, io::Error> {
pub fn new(current_dir: &Path,
ignore_file: Option<gitignore::PatternSet>)
-> Result<NotificationFilter, io::Error> {
let canonicalized = try!(current_dir.canonicalize());
Ok(NotificationFilter {
cwd: canonicalized,
filters: vec![],
ignores: vec![],
ignore_file: ignore_file
ignore_file: ignore_file,
})
}

View File

@ -11,7 +11,7 @@ impl Runner {
Runner {
process: None,
restart: restart,
cls: clear
cls: clear,
}
}
@ -38,7 +38,7 @@ impl Runner {
fn kill(&mut self) {
use libc;
extern {
extern "C" {
fn killpg(pgrp: libc::pid_t, sig: libc::c_int) -> libc::c_int;
}
@ -79,8 +79,10 @@ impl Runner {
debug!("Executing: {}", cmd);
command
.before_exec(|| unsafe { libc::setpgid(0, 0); Ok(()) })
command.before_exec(|| unsafe {
libc::setpgid(0, 0);
Ok(())
})
.spawn()
.ok()
}
@ -109,7 +111,7 @@ impl Runner {
#[cfg(target_family = "unix")]
fn wait(&mut self) {
use nix::sys::wait::{waitpid};
use nix::sys::wait::waitpid;
if let Some(ref mut child) = self.process {
debug!("Waiting for child process (pid: {})", child.id());

View File

@ -10,7 +10,7 @@ use notify::{PollWatcher, RecommendedWatcher};
/// (e.g. polymorphically). This has the nice side effect of separating out
/// all coupling to the notify crate into this module.
pub struct Watcher {
watcher_impl: WatcherImpl
watcher_impl: WatcherImpl,
}
pub use notify::Event;
@ -18,7 +18,7 @@ pub use notify::Error;
enum WatcherImpl {
Recommended(RecommendedWatcher),
Poll(PollWatcher)
Poll(PollWatcher),
}
impl Watcher {
@ -31,9 +31,7 @@ impl Watcher {
WatcherImpl::Recommended(try!(RecommendedWatcher::new(tx)))
};
Ok(self::Watcher {
watcher_impl: imp
})
Ok(self::Watcher { watcher_impl: imp })
}
pub fn is_polling(&self) -> bool {
@ -49,7 +47,7 @@ impl Watcher {
match self.watcher_impl {
WatcherImpl::Recommended(ref mut w) => w.watch(path),
WatcherImpl::Poll(ref mut w) => w.watch(path)
WatcherImpl::Poll(ref mut w) => w.watch(path),
}
}
}