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

fix(rust): add missing branding replacements in ockam_command #8785

Merged
merged 1 commit into from
Feb 5, 2025
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 92 additions & 0 deletions implementations/rust/ockam/ockam_api/src/ui/command.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
use std::fmt::{Debug, Formatter};

#[derive(Clone, Debug)]
pub struct Commands {
pub(crate) commands: Vec<Command>,
}

#[derive(Clone)]
pub(crate) struct Command {
pub(crate) name: &'static str,
pub(crate) custom_name: &'static str,
}

impl Debug for Command {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Command")
.field("name", &self.name)
.field("custom_name", &self.custom_name)
.finish()
}
}

impl Commands {
pub fn new(commands: &'static str) -> Self {
let commands = commands
.split(',')
.filter_map(|c| {
if c.is_empty() {
return None;
}
let mut parts = c.split('=');
let name = match parts.next() {
Some(name) => name,
None => return None,
};
let custom_name = parts.next().unwrap_or(name);
Some(Command { name, custom_name })
})
.collect();
Self { commands }
}

pub fn hide(&self, command_name: &'static str) -> bool {
// No restrictions
if self.commands.is_empty() {
return false;
}
// Check if the command is in the list of hidden commands
!self.commands.iter().any(|c| c.name == command_name)
}

pub fn name(&self, command_name: &'static str) -> &'static str {
// No restrictions
if self.commands.is_empty() {
return command_name;
}
// Check the custom name in the list of renamed commands
self.commands
.iter()
.find(|c| c.name == command_name)
.map_or(command_name, |c| c.custom_name)
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_hide() {
let commands = Commands::new("node=host,project,enroll");
assert!(!commands.hide("node"));
assert!(!commands.hide("project"));
assert!(!commands.hide("enroll"));
assert!(commands.hide("command4"));

let commands = Commands::new("");
assert!(!commands.hide("command1"));
}

#[test]
fn test_commands() {
let commands = Commands::new("node=host,project,enroll");
assert_eq!(commands.name("node"), "host");
assert_eq!(commands.name("project"), "project");
assert_eq!(commands.name("enroll"), "enroll");
assert_eq!(commands.name("command4"), "command4");

let commands = Commands::new("");
assert_eq!(commands.name("command1"), "command1");
}
}
1 change: 1 addition & 0 deletions implementations/rust/ockam/ockam_api/src/ui/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod colors;
pub mod command;
pub mod output;
pub mod terminal;
51 changes: 51 additions & 0 deletions implementations/rust/ockam/ockam_api/src/ui/output/branding.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
use crate::command::Commands;

#[derive(Clone, Debug)]
pub struct OutputBranding {
pub brand_name: String,
pub bin_name: String,
pub commands: Commands,
}

impl OutputBranding {
pub fn new(brand_name: String, bin_name: String, commands: Commands) -> Self {
Self {
brand_name,
bin_name,
commands,
}
}

pub fn replace(&self, text: &str) -> String {
// brand name
let mut text = if self.brand_name != "Ockam" {
text.replace("Ockam", &self.brand_name)
} else {
text.to_string()
};
// command names
for command in &self.commands.commands {
text = text.replace(
&format!("ockam {}", command.name),
&format!("ockam {}", command.custom_name),
);
}
// bin name
text = if self.bin_name != "ockam" {
text.replace("ockam", &self.bin_name)
} else {
text
};
text
}
}

impl Default for OutputBranding {
fn default() -> Self {
Self {
brand_name: "Ockam".to_string(),
bin_name: "ockam".to_string(),
commands: Commands::new(""),
}
}
}
2 changes: 2 additions & 0 deletions implementations/rust/ockam/ockam_api/src/ui/output/mod.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
mod branding;
mod encode_format;
mod ockam_abac;
mod output_format;
mod utils;

pub use branding::OutputBranding;
pub use encode_format::EncodeFormat;
pub use output_format::OutputFormat;
pub use utils::*;
Expand Down
32 changes: 9 additions & 23 deletions implementations/rust/ockam/ockam_api/src/ui/terminal/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ pub mod term;
pub use fmt::{get_separator_width, ICON_PADDING, INDENTATION, PADDING};
pub use highlighting::TextHighlighter;

use crate::output::OutputBranding;
use crate::ui::output::OutputFormat;
use crate::{Result, UiError};
use colorful::Colorful;
Expand Down Expand Up @@ -69,24 +70,13 @@ impl<T: TerminalWriter + Debug, W> Terminal<T, W> {
pub struct TerminalStream<T: Write + Debug + Clone> {
pub writer: T,
pub no_color: bool,
bin_name: String,
brand_name: String,
branding: OutputBranding,
}

impl<T: Write + Debug + Clone> TerminalStream<T> {
pub fn prepare_msg(&self, msg: impl AsRef<str>) -> Result<String> {
let msg = msg.as_ref().to_string();
let mut msg = if self.brand_name != "Ockam" {
msg.replace("Ockam", &self.brand_name)
} else {
msg
};
msg = if self.bin_name != "ockam" {
msg.replace("ockam", &self.bin_name)
} else {
msg
};

let msg = self.branding.replace(&msg);
if self.no_color {
Ok(strip_ansi_escapes::strip_str(&msg))
} else {
Expand All @@ -97,8 +87,8 @@ impl<T: Write + Debug + Clone> TerminalStream<T> {

/// Trait defining the main methods to write messages to a terminal stream.
pub trait TerminalWriter: Clone {
fn stdout(no_color: bool, bin_name: impl Into<String>, brand_name: impl Into<String>) -> Self;
fn stderr(no_color: bool, bin_name: impl Into<String>, brand_name: impl Into<String>) -> Self;
fn stdout(no_color: bool, branding: OutputBranding) -> Self;
fn stderr(no_color: bool, branding: OutputBranding) -> Self;
fn is_tty(&self) -> bool;
fn color(&self) -> bool;

Expand All @@ -117,15 +107,12 @@ impl<W: TerminalWriter + Debug> Terminal<W> {
no_color: bool,
no_input: bool,
output_format: OutputFormat,
bin_name: impl Into<String>,
brand_name: impl Into<String>,
branding: OutputBranding,
) -> Self {
let bin_name = bin_name.into();
let brand_name = brand_name.into();
let no_color = Self::should_disable_color(no_color);
let no_input = Self::should_disable_user_input(no_input);
let stdout = W::stdout(no_color, &bin_name, &brand_name);
let stderr = W::stderr(no_color, bin_name, brand_name);
let stdout = W::stdout(no_color, branding.clone());
let stderr = W::stderr(no_color, branding);
let max_width_col_count = get_size().map(|it| it.col_count).unwrap_or(ch!(80)).into();
Self {
stdout,
Expand All @@ -149,8 +136,7 @@ impl<W: TerminalWriter + Debug> Terminal<W> {
false,
false,
OutputFormat::Plain,
"ockam",
"Ockam",
OutputBranding::default(),
)
}

Expand Down
21 changes: 9 additions & 12 deletions implementations/rust/ockam/ockam_api/src/ui/terminal/term.rs
Original file line number Diff line number Diff line change
@@ -1,31 +1,29 @@
//! Implementation of the `TerminalWriter` using the `Term` crate

use dialoguer::console::Term;
use std::io::Write;

use crate::output::OutputBranding;
use crate::terminal::{TerminalStream, TerminalWriter};
use crate::Result;
use dialoguer::console::Term;
use std::io::Write;

impl TerminalWriter for TerminalStream<Term> {
fn stdout(no_color: bool, bin_name: impl Into<String>, brand_name: impl Into<String>) -> Self {
fn stdout(no_color: bool, branding: OutputBranding) -> Self {
let writer = Term::stdout();
let no_color = no_color || !writer.features().colors_supported();
Self {
writer,
no_color,
bin_name: bin_name.into(),
brand_name: brand_name.into(),
branding,
}
}

fn stderr(no_color: bool, bin_name: impl Into<String>, brand_name: impl Into<String>) -> Self {
fn stderr(no_color: bool, branding: OutputBranding) -> Self {
let writer = Term::stderr();
let no_color = no_color || !writer.features().colors_supported();
Self {
writer,
no_color,
bin_name: bin_name.into(),
brand_name: brand_name.into(),
branding,
}
}

Expand Down Expand Up @@ -62,7 +60,7 @@ mod tests {
use colorful::Colorful;
use dialoguer::console::Term;

use crate::output::OutputFormat;
use crate::output::{OutputBranding, OutputFormat};
use crate::terminal::{Terminal, TerminalStream};

#[test]
Expand All @@ -74,8 +72,7 @@ mod tests {
false,
false,
OutputFormat::Plain,
"",
"",
OutputBranding::default(),
);
sut.write("1").unwrap();
sut.rewrite("1-r\n").unwrap();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use crate::node::node_callback::NodeCallback;
use crate::node::util::run_ockam;
use crate::util::foreground_args::{wait_for_exit_signal, ForegroundArgs};
use crate::util::parsers::internet_address_parser;
use crate::{docs, CommandGlobalOpts, Result};
use crate::{branding, docs, CommandGlobalOpts, Result};

const LONG_ABOUT: &str = include_str!("./static/create/long_about.txt");
const PREVIEW_TAG: &str = include_str!("../static/preview_tag.txt");
Expand Down Expand Up @@ -144,7 +144,7 @@ impl CreateCommand {
0 => "-vv".to_string(),
v => format!("-{}", "v".repeat(v as usize)),
},
"authority".to_string(),
branding::command::name("authority").to_string(),
"create".to_string(),
"--foreground".to_string(),
"--child-process".to_string(),
Expand Down
Loading
Loading