diff options
author | Matan Kushner <hello@matchai.me> | 2019-10-04 22:30:46 +0900 |
---|---|---|
committer | GitHub <noreply@github.com> | 2019-10-04 22:30:46 +0900 |
commit | 05210b9510b797f7738d5b2d51e8a6877f2d5283 (patch) | |
tree | 7399401dba9373f61035dbbd055f4137cd20f705 /src/modules/ruby.rs | |
parent | e90a3768da7882db092b38d141cf8e19fabbee56 (diff) |
refactor: Go from Rust workspaces to a package with nested packages (#480)
Diffstat (limited to 'src/modules/ruby.rs')
-rw-r--r-- | src/modules/ruby.rs | 61 |
1 files changed, 61 insertions, 0 deletions
diff --git a/src/modules/ruby.rs b/src/modules/ruby.rs new file mode 100644 index 000000000..0faa2ccf8 --- /dev/null +++ b/src/modules/ruby.rs @@ -0,0 +1,61 @@ +use ansi_term::Color; +use std::process::Command; + +use super::{Context, Module}; + +/// Creates a module with the current Ruby version +/// +/// Will display the Ruby version if any of the following criteria are met: +/// - Current directory contains a `.rb` file +/// - Current directory contains a `Gemfile` file +pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> { + let is_rb_project = context + .try_begin_scan()? + .set_files(&["Gemfile"]) + .set_extensions(&["rb"]) + .is_match(); + + if !is_rb_project { + return None; + } + + match get_ruby_version() { + Some(ruby_version) => { + const RUBY_CHAR: &str = "💎 "; + + let mut module = context.new_module("ruby"); + let module_style = module + .config_value_style("style") + .unwrap_or_else(|| Color::Red.bold()); + module.set_style(module_style); + + let formatted_version = format_ruby_version(&ruby_version)?; + module.new_segment("symbol", RUBY_CHAR); + module.new_segment("version", &formatted_version); + + Some(module) + } + None => None, + } +} + +fn get_ruby_version() -> Option<String> { + match Command::new("ruby").arg("-v").output() { + Ok(output) => Some(String::from_utf8(output.stdout).unwrap()), + Err(_) => None, + } +} + +fn format_ruby_version(ruby_version: &str) -> Option<String> { + let version = ruby_version + // split into ["ruby", "2.6.0p0", "linux/amd64"] + .split_whitespace() + // return "2.6.0p0" + .nth(1)? + .get(0..5)?; + + let mut formatted_version = String::with_capacity(version.len() + 1); + formatted_version.push('v'); + formatted_version.push_str(version); + Some(formatted_version) +} |