Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(nats): Add NATS Context #5900

Merged
merged 9 commits into from
May 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
44 changes: 35 additions & 9 deletions .github/config-schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -1022,6 +1022,19 @@
}
]
},
"nats": {
"default": {
"disabled": true,
"format": "[$symbol($name )]($style)",
"style": "bold purple",
"symbol": "✉️ "
},
"allOf": [
{
"$ref": "#/definitions/NatsConfig"
}
]
},
"nim": {
"default": {
"detect_extensions": [
Expand Down Expand Up @@ -2040,14 +2053,12 @@
"type": "string"
},
"charging_symbol": {
"default": null,
"type": [
"string",
"null"
]
},
"discharging_symbol": {
"default": null,
"type": [
"string",
"null"
Expand Down Expand Up @@ -2718,14 +2729,12 @@
"type": "string"
},
"repo_root_style": {
"default": null,
"type": [
"string",
"null"
]
},
"before_repo_root_style": {
"default": null,
"type": [
"string",
"null"
Expand Down Expand Up @@ -4182,35 +4191,30 @@
"type": "string"
},
"user_pattern": {
"default": null,
"type": [
"string",
"null"
]
},
"symbol": {
"default": null,
"type": [
"string",
"null"
]
},
"style": {
"default": null,
"type": [
"string",
"null"
]
},
"context_alias": {
"default": null,
"type": [
"string",
"null"
]
},
"user_alias": {
"default": null,
"type": [
"string",
"null"
Expand Down Expand Up @@ -4367,6 +4371,28 @@
},
"additionalProperties": false
},
"NatsConfig": {
"type": "object",
"properties": {
"format": {
"default": "[$symbol($name )]($style)",
"type": "string"
},
"symbol": {
"default": "✉️ ",
"type": "string"
},
"style": {
"default": "bold purple",
"type": "string"
},
"disabled": {
"default": true,
"type": "boolean"
}
},
"additionalProperties": false
},
"NimConfig": {
"type": "object",
"properties": {
Expand Down
30 changes: 30 additions & 0 deletions docs/config/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,7 @@ $aws\
$gcloud\
$openstack\
$azure\
$nats\
$direnv\
$env_var\
$crystal\
Expand Down Expand Up @@ -2895,6 +2896,35 @@ truncation_length = 4
truncation_symbol = ''
```

## NATS

The `nats` module shows the name of the current [NATS](https://nats.io) context.

### Options

| Option | Default | Description |
| ---------- | -------------------------- | ------------------------------------------------------------ |
| `symbol` | `'✉️ '` | The symbol used before the NATS context (defaults to empty). |
| `style` | `'bold purple'` | The style for the module. |
| `format` | `'[$symbol$name]($style)'` | The format for the module. |
| `disabled` | `false` | Disables the `nats` module. |

### Variables

| Variable | Example | Description |
| -------- | ----------- | ------------------------------------ |
| name | `localhost` | The name of the NATS context |
| symbol | | Mirrors the value of option `symbol` |
| style\* | | Mirrors the value of option `style` |

### Example

```toml
[nats]
format = '[$symbol]($style)'
style = 'bold purple'
```

## Nim

The `nim` module shows the currently installed version of [Nim](https://nim-lang.org/).
Expand Down
3 changes: 3 additions & 0 deletions docs/public/presets/toml/plain-text-symbols.toml
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,9 @@ symbol = "memory "
[meson]
symbol = "meson "

[nats]
symbol = "nats "

[nim]
symbol = "nim "

Expand Down
3 changes: 3 additions & 0 deletions src/configs/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ pub mod localip;
pub mod lua;
pub mod memory_usage;
pub mod meson;
pub mod nats;
pub mod nim;
pub mod nix_shell;
pub mod nodejs;
Expand Down Expand Up @@ -214,6 +215,8 @@ pub struct FullConfig<'a> {
#[serde(borrow)]
meson: meson::MesonConfig<'a>,
#[serde(borrow)]
nats: nats::NatsConfig<'a>,
#[serde(borrow)]
nim: nim::NimConfig<'a>,
#[serde(borrow)]
nix_shell: nix_shell::NixShellConfig<'a>,
Expand Down
26 changes: 26 additions & 0 deletions src/configs/nats.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
use serde::{Deserialize, Serialize};

#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct NatsConfig<'a> {
pub format: &'a str,
pub symbol: &'a str,
pub style: &'a str,
pub disabled: bool,
}

impl<'a> Default for NatsConfig<'a> {
fn default() -> Self {
NatsConfig {
format: "[$symbol($name )]($style)",
symbol: "✉️ ",
style: "bold purple",
disabled: true,
}
}
}
1 change: 1 addition & 0 deletions src/configs/starship_root.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ pub const PROMPT_ORDER: &[&str] = &[
"shlvl",
"singularity",
"kubernetes",
"nats",
"directory",
"vcsh",
"fossil_branch",
Expand Down
1 change: 1 addition & 0 deletions src/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ pub const ALL_MODULES: &[&str] = &[
"lua",
"memory_usage",
"meson",
"nats",
"nim",
"nix_shell",
"nodejs",
Expand Down
3 changes: 3 additions & 0 deletions src/modules/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ mod localip;
mod lua;
mod memory_usage;
mod meson;
mod nats;
mod nim;
mod nix_shell;
mod nodejs;
Expand Down Expand Up @@ -159,6 +160,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),
"nats" => nats::module(context),
"nim" => nim::module(context),
"nix_shell" => nix_shell::module(context),
"nodejs" => nodejs::module(context),
Expand Down Expand Up @@ -280,6 +282,7 @@ pub fn description(module: &str) -> &'static str {
"meson" => {
"The current Meson environment, if $MESON_DEVENV and $MESON_PROJECT_NAME are set"
}
"nats" => "The current NATS context",
"nim" => "The currently installed version of Nim",
"nix_shell" => "The nix-shell environment",
"nodejs" => "The currently installed version of NodeJS",
Expand Down
89 changes: 89 additions & 0 deletions src/modules/nats.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
use super::{Context, Module, ModuleConfig};
use serde_json as json;

use crate::configs::nats::NatsConfig;
use crate::formatter::StringFormatter;

pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("nats");
let config = NatsConfig::try_load(module.config);

if config.disabled {
return None;
};

let ctx_str = context
.exec_cmd("nats", &["context", "info", "--json"])?
.stdout;
let nats_context: json::Value = json::from_str(&ctx_str)
.map_err(|e| {
log::warn!("Error parsing nats context JSON: {}\n", e);
drop(e);

Check warning on line 21 in src/modules/nats.rs

View check run for this annotation

Codecov / codecov/patch

src/modules/nats.rs#L20-L21

Added lines #L20 - L21 were not covered by tests
})
.ok()?;

let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|var, _| match var {
"symbol" => Some(config.symbol),
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,

Check warning on line 33 in src/modules/nats.rs

View check run for this annotation

Codecov / codecov/patch

src/modules/nats.rs#L32-L33

Added lines #L32 - L33 were not covered by tests
})
.map(|variable| match variable {
"name" => Some(Ok(nats_context.get("name")?.as_str()?)),
_ => None,

Check warning on line 37 in src/modules/nats.rs

View check run for this annotation

Codecov / codecov/patch

src/modules/nats.rs#L37

Added line #L37 was not covered by tests
})
.parse(None, Some(context))
});

module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `nats`:\n{}", error);
return None;

Check warning on line 46 in src/modules/nats.rs

View check run for this annotation

Codecov / codecov/patch

src/modules/nats.rs#L44-L46

Added lines #L44 - L46 were not covered by tests
}
});

Some(module)
}

#[cfg(test)]
mod tests {
use nu_ansi_term::Color;
use std::io;

use crate::test::ModuleRenderer;

#[test]
fn show_context() -> io::Result<()> {
let actual = ModuleRenderer::new("nats")
.config(toml::toml! {
[nats]
format = "[$symbol$name](bold purple)"
symbol = ""
disabled = false
})
.collect();
let expected = Some(format!("{}", Color::Purple.bold().paint("localhost")));
assert_eq!(expected, actual);
Ok(())
}

#[test]
fn test_with_symbol() -> io::Result<()> {
let actual = ModuleRenderer::new("nats")
.config(toml::toml! {
[nats]
format = "[$symbol$name](bold red)"
symbol = "✉️ "
disabled = false
})
.collect();
let expected = Some(format!("{}", Color::Red.bold().paint("✉️ localhost")));
assert_eq!(expected, actual);
Ok(())
}
}
4 changes: 4 additions & 0 deletions src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,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(),
}),
"nats context info --json" => Some(CommandOutput{
stdout: String::from("{\"name\":\"localhost\",\"url\":\"nats://localhost:4222\"}"),
stderr: String::default(),
}),
"nim --version" => Some(CommandOutput {
stdout: String::from(
"\
Expand Down