1
0
mirror of https://github.com/Llewellynvdm/starship.git synced 2024-11-28 15:56:28 +00:00

refactor(lua): parse version w/o regex (#2575)

This commit is contained in:
Dario Vladović 2021-04-15 08:46:29 +02:00 committed by GitHub
parent 98b5807dd2
commit 49f5b9c439
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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<version>[\\d\\.]+[a-z\\-]*[1-9]*)[^\\s]*";
/// Creates a module with the current Lua version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("lua");
@ -33,11 +30,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
_ => 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<Module<'a>> {
}
fn get_lua_version(context: &Context, lua_binary: &str) -> Option<String> {
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<String> {
fn parse_lua_version(lua_version: &str) -> Option<String> {
// 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())
);
}