From 756019b0a87dbda3d94a450dd115c07506f1b2c5 Mon Sep 17 00:00:00 2001 From: Jesse Luehrs Date: Sat, 24 Feb 2018 04:21:57 -0500 Subject: rustfmt --- .rustfmt.toml | 5 ++ src/colors.rs | 84 +++++++++++++---------- src/power.rs | 54 +++++++-------- src/prompt.rs | 190 ++++++++++++++++++++++++++--------------------------- src/system_info.rs | 8 +-- src/vcs/git.rs | 89 ++++++++++++++----------- src/vcs/mod.rs | 13 ++-- 7 files changed, 234 insertions(+), 209 deletions(-) create mode 100644 .rustfmt.toml diff --git a/.rustfmt.toml b/.rustfmt.toml new file mode 100644 index 0000000..6735a78 --- /dev/null +++ b/.rustfmt.toml @@ -0,0 +1,5 @@ +max_width = 78 +control_brace_style = "ClosingNextLine" +use_small_heuristics = false +combine_control_expr = false +struct_lit_single_line = false diff --git a/src/colors.rs b/src/colors.rs index 199f4f9..86815e4 100644 --- a/src/colors.rs +++ b/src/colors.rs @@ -1,7 +1,7 @@ use std; use term; -#[derive(Debug,Clone)] +#[derive(Debug, Clone)] pub enum ShellType { Unknown, Bash, @@ -21,7 +21,7 @@ impl ShellType { match shell { "bash" => ShellType::Bash, "zsh" => ShellType::Zsh, - _ => panic!("unknown shell {}", shell) + _ => panic!("unknown shell {}", shell), } } } @@ -32,16 +32,19 @@ impl Colors { color_map.insert(String::from("user_root"), term::color::BRIGHT_RED); - color_map.insert(String::from("path_not_writable"), term::color::YELLOW); + color_map + .insert(String::from("path_not_writable"), term::color::YELLOW); color_map.insert(String::from("path_not_exist"), term::color::RED); color_map.insert(String::from("vcs_dirty"), term::color::RED); color_map.insert(String::from("vcs_error"), term::color::BRIGHT_RED); color_map.insert(String::from("battery_warn"), term::color::YELLOW); color_map.insert(String::from("battery_crit"), term::color::RED); - color_map.insert(String::from("battery_emerg"), term::color::BRIGHT_RED); + color_map + .insert(String::from("battery_emerg"), term::color::BRIGHT_RED); color_map.insert(String::from("battery_full"), term::color::GREEN); - color_map.insert(String::from("battery_charging"), term::color::GREEN); + color_map + .insert(String::from("battery_charging"), term::color::GREEN); color_map.insert(String::from("default"), term::color::BRIGHT_BLACK); color_map.insert(String::from("error"), term::color::RED); @@ -64,7 +67,7 @@ impl Colors { let (name, color) = (parts[0], parts[1]); color_map.insert( String::from(name), - Self::color_from_string(color) + Self::color_from_string(color), ); } } @@ -108,24 +111,24 @@ impl Colors { } pub fn print_host(&self, host: &Option, text: &str) { - let color = host - .clone() - .and_then(|hostname| { - self.color_map.get(&format!("host_{}", hostname)) - }); + let color = host.clone().and_then(|hostname| { + self.color_map.get(&format!("host_{}", hostname)) + }); self.print_with_color(color, text); } pub fn print_user(&self, user: &Option, text: &str) { - let color = user - .clone() - .and_then(|username| { - self.color_map.get(&format!("user_{}", username)) - }); + let color = user.clone().and_then(|username| { + self.color_map.get(&format!("user_{}", username)) + }); self.print_with_color(color, text); } - fn print_with_color(&self, color: Option<&term::color::Color>, text: &str) { + fn print_with_color( + &self, + color: Option<&term::color::Color>, + text: &str, + ) { let mut t = term::stdout().unwrap(); self.print_color(&mut *t, color); write!(t, "{}", text).unwrap(); @@ -134,41 +137,54 @@ impl Colors { }) } - fn print_color(&self, t: &mut term::StdoutTerminal, color: Option<&term::color::Color>) { + fn print_color( + &self, + t: &mut term::StdoutTerminal, + color: Option<&term::color::Color>, + ) { self.print_wrapped(|| { let real_color = *color.unwrap_or(&self.unknown_color); t.fg(real_color).unwrap(); match real_color { term::color::BRIGHT_BLACK - | term::color::BRIGHT_BLUE - | term::color::BRIGHT_CYAN - | term::color::BRIGHT_GREEN - | term::color::BRIGHT_MAGENTA - | term::color::BRIGHT_RED - | term::color::BRIGHT_WHITE - | term::color::BRIGHT_YELLOW => { + | term::color::BRIGHT_BLUE + | term::color::BRIGHT_CYAN + | term::color::BRIGHT_GREEN + | term::color::BRIGHT_MAGENTA + | term::color::BRIGHT_RED + | term::color::BRIGHT_WHITE + | term::color::BRIGHT_YELLOW => { t.attr(term::Attr::Bold).unwrap() - }, - _ => {}, + } + _ => {} } }) } fn print_wrapped(&self, printer: T) - where T: FnOnce() + where + T: FnOnce(), { match self.shell_type { - ShellType::Bash => { print!("{}", "\\["); }, - ShellType::Zsh => { print!("{}", "%{"); }, - _ => {}, + ShellType::Bash => { + print!("{}", "\\["); + } + ShellType::Zsh => { + print!("{}", "%{"); + } + _ => {} } printer(); match self.shell_type { - ShellType::Bash => { print!("{}", "\\]"); }, - ShellType::Zsh => { print!("{}", "%}"); }, - _ => {}, + ShellType::Bash => { + print!("{}", "\\]"); + } + ShellType::Zsh => { + print!("{}", "%}"); + } + _ => {} } } } diff --git a/src/power.rs b/src/power.rs index 2a9dd31..4bc5c0b 100644 --- a/src/power.rs +++ b/src/power.rs @@ -5,7 +5,7 @@ use std::io::Read; // XXX maybe extract this out into a separate crate? -#[derive(PartialEq,Eq,Debug,Clone)] +#[derive(PartialEq, Eq, Debug, Clone)] enum PowerSupplyType { AC, Battery, @@ -16,7 +16,7 @@ pub struct PowerInfo { power_supplies: Vec, } -#[derive(Debug,Clone)] +#[derive(Debug, Clone)] struct PowerSupplyInfo { name: String, ty: PowerSupplyType, @@ -28,10 +28,15 @@ struct PowerSupplyInfo { impl PowerInfo { pub fn new() -> PowerInfo { let mut power_supplies = vec![]; - for entry in walkdir::WalkDir::new("/sys/class/power_supply/").min_depth(1).max_depth(1).follow_links(true) { + for entry in walkdir::WalkDir::new("/sys/class/power_supply/") + .min_depth(1) + .max_depth(1) + .follow_links(true) + { let entry = entry.unwrap(); - let name = entry.path() + let name = entry + .path() .file_name() .unwrap() .to_string_lossy() @@ -41,18 +46,16 @@ impl PowerInfo { .expect("couldn't find power supply type"); let full = slurp(entry.path().join("energy_full")); let now = slurp(entry.path().join("energy_now")); - let online = slurp(entry.path().join("online")) - .map(|n: u8| n != 0); - - power_supplies.push( - PowerSupplyInfo { - name: name, - ty: ty, - energy_now: now, - energy_full: full, - online: online, - } - ) + let online = + slurp(entry.path().join("online")).map(|n: u8| n != 0); + + power_supplies.push(PowerSupplyInfo { + name: name, + ty: ty, + energy_now: now, + energy_full: full, + online: online, + }) } PowerInfo { @@ -117,21 +120,20 @@ impl PowerSupplyType { match ty { "Mains" => PowerSupplyType::AC, "Battery" => PowerSupplyType::Battery, - _ => panic!("unknown power supply type {}", ty) + _ => panic!("unknown power supply type {}", ty), } } } fn slurp(path: U) -> Option - where T: std::str::FromStr, - U: AsRef +where + T: std::str::FromStr, + U: AsRef, { let mut contents = String::new(); - std::fs::File::open(path) - .ok() - .and_then(|mut fh| { - fh.read_to_string(&mut contents) - .ok() - .and_then(|_| contents.trim().parse().ok()) - }) + std::fs::File::open(path).ok().and_then(|mut fh| { + fh.read_to_string(&mut contents) + .ok() + .and_then(|_| contents.trim().parse().ok()) + }) } diff --git a/src/prompt.rs b/src/prompt.rs index 2a8a12a..781287e 100644 --- a/src/prompt.rs +++ b/src/prompt.rs @@ -39,18 +39,14 @@ impl Prompt { } pub fn display(&self) { - let user = self.data.user - .clone() - .unwrap_or_else(|| String::from("???")); - let host = self.data.hostname - .clone() - .unwrap_or_else(|| String::from("???")); + let user = + self.data.user.clone().unwrap_or_else(|| String::from("???")); + let host = + self.data.hostname.clone().unwrap_or_else(|| String::from("???")); let max_vcs_len = 20; // "g*+?:mybr...nch:+1-1" let vcs = self.format_vcs(); - let vcs = vcs.map(|vcs| { - compress_vcs(&vcs, max_vcs_len) - }); + let vcs = vcs.map(|vcs| compress_vcs(&vcs, max_vcs_len)); let battery_len = 10; let cols = self.data.terminal_cols.unwrap_or(80); @@ -79,11 +75,8 @@ impl Prompt { ); } - let path = compress_path( - &self.data.pwd, - &self.data.home, - max_path_len - ); + let path = + compress_path(&self.data.pwd, &self.data.home, max_path_len); self.colors.pad(1); self.display_path( @@ -120,7 +113,7 @@ impl Prompt { path: &str, path_color: &str, vcs: &Option, - vcs_color: &str + vcs_color: &str, ) { self.colors.print_host(&self.data.hostname, "("); self.colors.print(path_color, path); @@ -152,7 +145,8 @@ impl Prompt { self.colors.print(color, ">"); } if filled > 1 { - self.colors.print("battery_charging", &"=".repeat(filled - 1)); + self.colors + .print("battery_charging", &"=".repeat(filled - 1)); } } else { @@ -171,7 +165,7 @@ impl Prompt { self.colors.print_host(&self.data.hostname, "["); self.colors.print( "default", - &format!("{}", self.data.time.format("%H:%M:%S")) + &format!("{}", self.data.time.format("%H:%M:%S")), ); self.colors.print_host(&self.data.hostname, "]"); } @@ -183,14 +177,17 @@ impl Prompt { else { "error" }; - self.colors.print( - error_code_color, - &format!("{:03}", self.data.error_code) - ); + self.colors + .print(error_code_color, &format!("{:03}", self.data.error_code)); } fn display_prompt(&self) { - let prompt = if self.data.is_root { "#" } else { "$" }; + let prompt = if self.data.is_root { + "#" + } + else { + "$" + }; self.colors.print_user(&self.data.user, prompt); } @@ -225,35 +222,39 @@ fn battery_discharge_color(usage: f64, charging: bool) -> &'static str { } fn path_color(path: &Option) -> String - where T: AsRef +where + T: AsRef, { - path.as_ref().and_then(|path| { - std::fs::metadata(path) - .map(|stat| { - // XXX there really has to be a better option here - let euid = users::get_effective_uid(); - let egid = users::get_effective_gid(); - let file_uid = stat.st_uid(); - let file_gid = stat.st_gid(); - let file_mode = stat.permissions().mode(); - - if euid == 0 { - String::from("default") - } - else if (file_uid == euid) && (file_mode & 0o200 != 0) { - String::from("default") - } - else if (file_gid == egid) && (file_mode & 0o020 != 0) { - String::from("default") - } - else if file_mode & 0o002 != 0 { - String::from("default") - } - else { - String::from("path_not_writable") - } - }).ok() - }).unwrap_or_else(|| String::from("path_not_exist")) + path.as_ref() + .and_then(|path| { + std::fs::metadata(path) + .map(|stat| { + // XXX there really has to be a better option here + let euid = users::get_effective_uid(); + let egid = users::get_effective_gid(); + let file_uid = stat.st_uid(); + let file_gid = stat.st_gid(); + let file_mode = stat.permissions().mode(); + + if euid == 0 { + String::from("default") + } + else if (file_uid == euid) && (file_mode & 0o200 != 0) { + String::from("default") + } + else if (file_gid == egid) && (file_mode & 0o020 != 0) { + String::from("default") + } + else if file_mode & 0o002 != 0 { + String::from("default") + } + else { + String::from("path_not_writable") + } + }) + .ok() + }) + .unwrap_or_else(|| String::from("path_not_exist")) } fn format_vcs(vcs_info: &Option>) -> Option { @@ -276,14 +277,17 @@ fn format_vcs(vcs_info: &Option>) -> Option { return vcs; } - let branch = vcs_info.branch().map(|branch| { - if branch == "master" { - String::new() - } - else { - branch - } - }).unwrap_or_else(|| String::from("???")); + let branch = vcs_info + .branch() + .map(|branch| { + if branch == "master" { + String::new() + } + else { + branch + } + }) + .unwrap_or_else(|| String::from("???")); if branch != "" { write!(vcs, ":").unwrap(); } @@ -305,7 +309,7 @@ fn format_vcs(vcs_info: &Option>) -> Option { } match vcs_info.active_operation() { - vcs::ActiveOperation::None => {}, + vcs::ActiveOperation::None => {} op => { write!(vcs, "({})", active_operation_id(op)).unwrap(); } @@ -316,26 +320,30 @@ fn format_vcs(vcs_info: &Option>) -> Option { } fn vcs_color(vcs_info: &Option>) -> String { - vcs_info.as_ref().map(|vcs_info| { - if vcs_info.is_error() { - String::from("vcs_error") - } - else if vcs_info.is_dirty() { - String::from("vcs_dirty") - } - else { - String::from("default") - } - }).unwrap_or_else(|| String::from("vcs_error")) + vcs_info + .as_ref() + .map(|vcs_info| { + if vcs_info.is_error() { + String::from("vcs_error") + } + else if vcs_info.is_dirty() { + String::from("vcs_dirty") + } + else { + String::from("default") + } + }) + .unwrap_or_else(|| String::from("vcs_error")) } fn compress_path( path: &Option, home: &Option, - len: usize + len: usize, ) -> String - where T: AsRef, - U: AsRef +where + T: AsRef, + U: AsRef, { if let Some(ref path) = *path { let mut path_str = path.as_ref().to_string_lossy().into_owned(); @@ -343,27 +351,25 @@ fn compress_path( if let Some(ref home) = *home { let home_str = home.as_ref().to_string_lossy().into_owned(); let home_re = regex::Regex::new( - &(String::from(r"^") + ®ex::escape(&home_str)) + &(String::from(r"^") + ®ex::escape(&home_str)), ).unwrap(); path_str = home_re.replace(&path_str, "~").into_owned(); } - let path_compress_re = regex::Regex::new( - r"/([^/])[^/]+/" - ).unwrap(); + let path_compress_re = regex::Regex::new(r"/([^/])[^/]+/").unwrap(); while path_str.len() > len { let prev_len = path_str.len(); - path_str = path_compress_re.replace(&path_str, "/$1/").into_owned(); + path_str = + path_compress_re.replace(&path_str, "/$1/").into_owned(); if prev_len == path_str.len() { break; } } if path_str.len() > len { - path_str = String::from(&path_str[..len - 6]) - + "..." + path_str = String::from(&path_str[..len - 6]) + "..." + &path_str[path_str.len() - 3..] } @@ -376,9 +382,8 @@ fn compress_path( fn compress_vcs(vcs: &str, len: usize) -> String { if vcs.len() > len { - let vcs_parts_re = regex::Regex::new( - r"^([^:]+):.*?(?::([^:]+))?$" - ).unwrap(); + let vcs_parts_re = + regex::Regex::new(r"^([^:]+):.*?(?::([^:]+))?$").unwrap(); vcs_parts_re .captures(vcs) .map(|cap| { @@ -389,12 +394,10 @@ fn compress_vcs(vcs: &str, len: usize) -> String { .map(|mat| mat.end() - mat.start() + 1) .unwrap_or(0); let branch_len = len - prefix_len - suffix_len; - let branch_re = regex::Regex::new( - &format!( - r"(:[^:]{{{}}})[^:]*([^:]{{3}}:?)", - (branch_len - 6).to_string() - ) - ).unwrap(); + let branch_re = regex::Regex::new(&format!( + r"(:[^:]{{{}}})[^:]*([^:]{{3}}:?)", + (branch_len - 6).to_string() + )).unwrap(); branch_re.replace(vcs, "$1...$2").into_owned() }) .unwrap_or_else(|| vcs.to_string()) @@ -475,12 +478,12 @@ mod test { "~/coding/fancy-prompt", "~/coding/fancy-prompt", "~/coding/fancy-prompt", - "~/c/fancy-prompt", // 20 + "~/c/fancy-prompt", // 20 "~/c/fancy-prompt", "~/c/fancy-prompt", "~/c/fancy-prompt", "~/c/fancy-prompt", - "~/c/fancy...mpt", // 15 + "~/c/fancy...mpt", // 15 "~/c/fanc...mpt", "~/c/fan...mpt", "~/c/fa...mpt", @@ -572,10 +575,7 @@ mod test { #[test] fn test_format_vcs() { { - assert_eq!( - format_vcs(&None), - None - ) + assert_eq!(format_vcs(&None), None) } { let test_vcs = TestVcs { diff --git a/src/system_info.rs b/src/system_info.rs index a4c4122..25b5a67 100644 --- a/src/system_info.rs +++ b/src/system_info.rs @@ -21,15 +21,11 @@ pub fn terminal_cols() -> Option { } pub fn pwd() -> Option { - std::env::var("PWD") - .map(std::path::PathBuf::from) - .ok() + std::env::var("PWD").map(std::path::PathBuf::from).ok() } pub fn home() -> Option { - std::env::var("HOME") - .map(std::path::PathBuf::from) - .ok() + std::env::var("HOME").map(std::path::PathBuf::from).ok() } pub fn user() -> Option { diff --git a/src/vcs/git.rs b/src/vcs/git.rs index 5b351a7..05558af 100644 --- a/src/vcs/git.rs +++ b/src/vcs/git.rs @@ -33,7 +33,8 @@ impl GitInfo { let mut status_options = git2::StatusOptions::new(); status_options.include_untracked(true); - if true { // XXX + if true { + // XXX status_options.update_index(true); } else { @@ -60,48 +61,54 @@ impl GitInfo { let head = git.head(); let commits = head.is_ok(); - let branch = head.ok() - .and_then(|head| { - if head.is_branch() { - head.shorthand().map(|s| s.to_string()) - } - else { - head.resolve().ok() - .and_then(|head| head.target()) - .map(|oid| { - let mut sha = String::new(); - for b in oid.as_bytes().iter() { - write!(sha, "{:02x}", b).unwrap(); - } - sha.truncate(7); - sha - }) - } - }); + let branch = head.ok().and_then(|head| { + if head.is_branch() { + head.shorthand().map(|s| s.to_string()) + } + else { + head.resolve().ok().and_then(|head| head.target()).map( + |oid| { + let mut sha = String::new(); + for b in oid.as_bytes().iter() { + write!(sha, "{:02x}", b).unwrap(); + } + sha.truncate(7); + sha + }, + ) + } + }); let active_operation = match git.state() { - git2::RepositoryState::Merge - => super::ActiveOperation::Merge, + git2::RepositoryState::Merge => super::ActiveOperation::Merge, git2::RepositoryState::Revert - | git2::RepositoryState::RevertSequence - => super::ActiveOperation::Revert, + | git2::RepositoryState::RevertSequence => { + super::ActiveOperation::Revert + } git2::RepositoryState::CherryPick - | git2::RepositoryState::CherryPickSequence - => super::ActiveOperation::CherryPick, - git2::RepositoryState::Bisect - => super::ActiveOperation::Bisect, + | git2::RepositoryState::CherryPickSequence => { + super::ActiveOperation::CherryPick + } + git2::RepositoryState::Bisect => super::ActiveOperation::Bisect, git2::RepositoryState::Rebase - | git2::RepositoryState::RebaseInteractive - | git2::RepositoryState::RebaseMerge - => super::ActiveOperation::Rebase, + | git2::RepositoryState::RebaseInteractive + | git2::RepositoryState::RebaseMerge => { + super::ActiveOperation::Rebase + } _ => super::ActiveOperation::None, }; - let remote_branch_diff = git.head().ok() - .and_then(|head| if head.is_branch() { Some(head) } else { None }) + let remote_branch_diff = git.head() + .ok() .and_then(|head| { - head.resolve().ok() + if head.is_branch() { + Some(head) + } + else { + None + } }) + .and_then(|head| head.resolve().ok()) .map(|head| { (head.target(), head.shorthand().map(|s| s.to_string())) }) @@ -109,10 +116,12 @@ impl GitInfo { head_id.and_then(|head_id| { name.and_then(|name| { git.refname_to_id( - &(String::from("refs/remotes/origin/") + &name) - ).ok().and_then(|remote_id| { - git.graph_ahead_behind(head_id, remote_id).ok() - }) + &(String::from("refs/remotes/origin/") + &name), + ).ok() + .and_then(|remote_id| { + git.graph_ahead_behind(head_id, remote_id) + .ok() + }) }) }) }); @@ -164,9 +173,9 @@ impl super::VcsInfo for GitInfo { } pub fn detect() -> Option> { - let git = std::env::current_dir().ok().and_then(|pwd| { - git2::Repository::discover(pwd).ok() - }); + let git = std::env::current_dir() + .ok() + .and_then(|pwd| git2::Repository::discover(pwd).ok()); if let Some(git) = git { Some(Box::new(GitInfo::new(&git))) diff --git a/src/vcs/mod.rs b/src/vcs/mod.rs index f68e4ef..b7a9fc7 100644 --- a/src/vcs/mod.rs +++ b/src/vcs/mod.rs @@ -1,11 +1,11 @@ mod git; -#[derive(Debug,Copy,Clone)] +#[derive(Debug, Copy, Clone)] pub enum VcsType { Git, } -#[derive(Debug,Copy,Clone)] +#[derive(Debug, Copy, Clone)] pub enum ActiveOperation { None, Merge, @@ -27,12 +27,9 @@ pub trait VcsInfo { fn is_dirty(&self) -> bool { let diff = self.remote_branch_diff(); - self.has_modified_files() - || self.has_staged_files() - || self.has_new_files() - || !diff.is_some() - || diff - .map(|(local, remote)| local > 0 || remote > 0) + self.has_modified_files() || self.has_staged_files() + || self.has_new_files() || !diff.is_some() + || diff.map(|(local, remote)| local > 0 || remote > 0) .unwrap_or(false) } -- cgit v1.2.3-54-g00ecf