From 49f5b9c4399015a02001bc6397085d9d74760453 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dario=20Vladovi=C4=87?= Date: Thu, 15 Apr 2021 08:46:29 +0200 Subject: [PATCH] refactor(lua): parse version w/o regex (#2575) --- src/modules/lua.rs | 46 +++++++++++++++++++++------------------------- 1 file changed, 21 insertions(+), 25 deletions(-) diff --git a/src/modules/lua.rs b/src/modules/lua.rs index 66219e9d..022cae7e 100644 --- a/src/modules/lua.rs +++ b/src/modules/lua.rs @@ -3,9 +3,6 @@ use super::{Context, Module, RootModuleConfig}; use crate::configs::lua::LuaConfig; use crate::formatter::StringFormatter; -use regex::Regex; -const LUA_VERSION_PATERN: &str = "(?P[\\d\\.]+[a-z\\-]*[1-9]*)[^\\s]*"; - /// Creates a module with the current Lua version pub fn module<'a>(context: &'a Context) -> Option> { let mut module = context.new_module("lua"); @@ -33,11 +30,7 @@ pub fn module<'a>(context: &'a Context) -> Option> { _ => None, }) .map(|variable| match variable { - "version" => { - let lua_version = - format_lua_version(&get_lua_version(context, &config.lua_binary)?)?; - Some(Ok(lua_version)) - } + "version" => get_lua_version(context, &config.lua_binary).map(Ok), _ => None, }) .parse(None) @@ -55,27 +48,30 @@ pub fn module<'a>(context: &'a Context) -> Option> { } fn get_lua_version(context: &Context, lua_binary: &str) -> Option { - match context.exec_cmd(lua_binary, &["-v"]) { - Some(output) => { - if output.stdout.is_empty() { - Some(output.stderr) - } else { - Some(output.stdout) - } - } - None => None, - } + let output = context.exec_cmd(lua_binary, &["-v"])?; + let lua_version = if output.stdout.is_empty() { + output.stderr + } else { + output.stdout + }; + + parse_lua_version(&lua_version) } -fn format_lua_version(lua_stdout: &str) -> Option { +fn parse_lua_version(lua_version: &str) -> Option { // lua -v output looks like this: // Lua 5.4.0 Copyright (C) 1994-2020 Lua.org, PUC-Rio // luajit -v output looks like this: // LuaJIT 2.0.5 -- Copyright (C) 2005-2017 Mike Pall. http://luajit.org/ - let re = Regex::new(LUA_VERSION_PATERN).ok()?; - let captures = re.captures(lua_stdout)?; - let version = &captures["version"]; + let version = lua_version + // Lua: split into ["Lua", "5.4.0", "Copyright", ...] + // LuaJIT: split into ["LuaJIT", "2.0.5", "--", ...] + .split_whitespace() + // Lua: take "5.4.0" + // LuaJIT: take "2.0.5" + .nth(1)?; + Some(format!("v{}", version)) } @@ -150,14 +146,14 @@ mod tests { } #[test] - fn test_format_lua_version() { + fn test_parse_lua_version() { let lua_input = "Lua 5.4.0 Copyright (C) 1994-2020 Lua.org, PUC-Rio"; - assert_eq!(format_lua_version(lua_input), Some("v5.4.0".to_string())); + assert_eq!(parse_lua_version(lua_input), Some("v5.4.0".to_string())); let luajit_input = "LuaJIT 2.1.0-beta3 -- Copyright (C) 2005-2017 Mike Pall. http://luajit.org/"; assert_eq!( - format_lua_version(luajit_input), + parse_lua_version(luajit_input), Some("v2.1.0-beta3".to_string()) ); }