feat(mojo): add module for Mojo language (#6108)

* feat: add support to mojo lang

* docs: fix mojo formatting

* Update src/modules/mojo.rs

Co-authored-by: David Knaack <davidkna@users.noreply.github.com>

* feat(mojo): parse hash as an independent variable

* chore(mojo): fix formatting

* chore(mojo): update schema and docs

* feat(mojo): use lazy cmd evaluation

---------

Co-authored-by: David Knaack <davidkna@users.noreply.github.com>
This commit is contained in:
Daniel Kneipp
2024-08-18 18:12:39 +02:00
committed by GitHub
parent c9ed921b66
commit 171746a584
9 changed files with 317 additions and 0 deletions
+3
View File
@@ -55,6 +55,7 @@ pub mod localip;
pub mod lua;
pub mod memory_usage;
pub mod meson;
pub mod mojo;
pub mod nats;
pub mod nim;
pub mod nix_shell;
@@ -219,6 +220,8 @@ pub struct FullConfig<'a> {
#[serde(borrow)]
meson: meson::MesonConfig<'a>,
#[serde(borrow)]
mojo: mojo::MojoConfig<'a>,
#[serde(borrow)]
nats: nats::NatsConfig<'a>,
#[serde(borrow)]
nim: nim::NimConfig<'a>,
+35
View File
@@ -0,0 +1,35 @@
use nu_ansi_term::Color;
use serde::{Deserialize, Serialize};
pub const MOJO_DEFAULT_COLOR: Color = Color::Fixed(208);
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct MojoConfig<'a> {
pub format: &'a str,
pub symbol: &'a str,
pub style: &'a str,
pub disabled: bool,
pub detect_extensions: Vec<&'a str>,
pub detect_files: Vec<&'a str>,
pub detect_folders: Vec<&'a str>,
}
impl<'a> Default for MojoConfig<'a> {
fn default() -> Self {
MojoConfig {
format: "with [$symbol($version )]($style)",
symbol: "🔥 ",
style: "bold 208",
disabled: false,
detect_extensions: vec!["mojo", "🔥"],
detect_files: vec![],
detect_folders: vec![],
}
}
}
+1
View File
@@ -75,6 +75,7 @@ pub const PROMPT_ORDER: &[&str] = &[
"julia",
"kotlin",
"lua",
"mojo",
"nim",
"nodejs",
"ocaml",
+1
View File
@@ -60,6 +60,7 @@ pub const ALL_MODULES: &[&str] = &[
"lua",
"memory_usage",
"meson",
"mojo",
"nats",
"nim",
"nix_shell",
+3
View File
@@ -52,6 +52,7 @@ mod localip;
mod lua;
mod memory_usage;
mod meson;
mod mojo;
mod nats;
mod nim;
mod nix_shell;
@@ -163,6 +164,7 @@ pub fn handle<'a>(module: &str, context: &'a Context) -> Option<Module<'a>> {
"lua" => lua::module(context),
"memory_usage" => memory_usage::module(context),
"meson" => meson::module(context),
"mojo" => mojo::module(context),
"nats" => nats::module(context),
"nim" => nim::module(context),
"nix_shell" => nix_shell::module(context),
@@ -287,6 +289,7 @@ pub fn description(module: &str) -> &'static str {
"meson" => {
"The current Meson environment, if $MESON_DEVENV and $MESON_PROJECT_NAME are set"
}
"mojo" => "The currently installed version of Mojo",
"nats" => "The current NATS context",
"nim" => "The currently installed version of Nim",
"nix_shell" => "The nix-shell environment",
+170
View File
@@ -0,0 +1,170 @@
use super::{Context, Module, ModuleConfig};
use crate::configs::mojo::MojoConfig;
use crate::formatter::StringFormatter;
use once_cell::sync::Lazy;
use std::ops::Deref;
/// Creates a module with the current Mojo version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("mojo");
let config = MojoConfig::try_load(module.config);
let is_mojo_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_mojo_project {
return None;
}
let version_hash = Lazy::new(|| get_mojo_version(context));
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|variable, _| match variable {
"symbol" => Some(config.symbol),
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map(|variable| match variable {
"version" => match version_hash.deref() {
Some((version, _)) => Some(Ok(version)),
_ => None,
},
"hash" => match version_hash.deref() {
Some((_, Some(hash))) => Some(Ok(hash)),
_ => None,
},
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `mojo`:\n{}", error);
return None;
}
});
Some(module)
}
fn get_mojo_version(context: &Context) -> Option<(String, Option<String>)> {
let mojo_version_output = context.exec_cmd("mojo", &["--version"])?.stdout;
let version_items = mojo_version_output
.split_ascii_whitespace()
.collect::<Vec<&str>>();
let (version, hash) = match version_items[..] {
[_, version] => (version.trim().to_string(), None),
[_, version, hash, ..] => (version.trim().to_string(), Some(hash.trim().to_string())),
_ => {
log::debug!("Unexpected `mojo --version` output: {mojo_version_output}");
return None;
}
};
Some((version, hash))
}
#[cfg(test)]
mod tests {
use crate::configs::mojo::MOJO_DEFAULT_COLOR;
use crate::test::ModuleRenderer;
use crate::utils::CommandOutput;
use std::fs::File;
use std::io;
#[test]
fn folder_without_mojo() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("mojo.txt"))?.sync_all()?;
let actual = ModuleRenderer::new("mojo").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_mojo_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("main.mojo"))?.sync_all()?;
let actual = ModuleRenderer::new("mojo")
.path(dir.path())
.collect()
.unwrap();
let expected = format!("with {}", MOJO_DEFAULT_COLOR.bold().paint("🔥 24.4.0 "));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_mojo_file_emoji() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("main.🔥"))?.sync_all()?;
let actual = ModuleRenderer::new("mojo")
.path(dir.path())
.collect()
.unwrap();
let expected = format!("with {}", MOJO_DEFAULT_COLOR.bold().paint("🔥 24.4.0 "));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_mojo_file_with_commit() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("main.mojo"))?.sync_all()?;
let actual = ModuleRenderer::new("mojo")
.config(toml::toml! {
[mojo]
format = "with [$symbol($version )($hash )]($style)"
})
.path(dir.path())
.collect()
.unwrap();
let expected = format!(
"with {}",
MOJO_DEFAULT_COLOR.bold().paint("🔥 24.4.0 (2cb57382) ")
);
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_mojo_file_with_no_commit_available() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("main.mojo"))?.sync_all()?;
let actual = ModuleRenderer::new("mojo")
.config(toml::toml! {
[mojo]
show_commit = true
})
.cmd(
"mojo --version",
Some(CommandOutput {
stdout: String::from("mojo 24.4.0\n"),
stderr: String::default(),
}),
)
.path(dir.path())
.collect();
let expected = Some(format!(
"with {}",
MOJO_DEFAULT_COLOR.bold().paint("🔥 24.4.0 ")
));
assert_eq!(expected, actual);
dir.close()
}
}
+4
View File
@@ -315,6 +315,10 @@ Elixir 1.10 (compiled with Erlang/OTP 22)\n",
stdout: String::from("LuaJIT 2.0.5 -- Copyright (C) 2005-2017 Mike Pall. http://luajit.org/\n"),
stderr: String::default(),
}),
"mojo --version" => Some(CommandOutput {
stdout: String::from("mojo 24.4.0 (2cb57382)\n"),
stderr: String::default(),
}),
"nats context info --json" => Some(CommandOutput{
stdout: String::from("{\"name\":\"localhost\",\"url\":\"nats://localhost:4222\"}"),
stderr: String::default(),