Skip to content

Commit

Permalink
Added hostname.detect_env_vars
Browse files Browse the repository at this point in the history
based on the newly added context::detect_env_vars

- extended context::detect_env_vars to check for negated environment
  variables as well, analogous to the other detect modules
- made hostname.detect_env_vars only active if ssh_only is set to false
  for backwards compatibility

Co-authored-by: Dominik Sander <dsander@users.noreply.github.com>
  • Loading branch information
mickimnet and dsander committed May 21, 2023
1 parent 1987f0a commit 56c4a45
Show file tree
Hide file tree
Showing 4 changed files with 142 additions and 12 deletions.
37 changes: 28 additions & 9 deletions docs/config/README.md
Expand Up @@ -2189,16 +2189,22 @@ format = 'via [⎈ $version](bold white) '

The `hostname` module shows the system hostname.

::: warning

The `detect_env_vars` is only recognized, if `ssh_only` is set to `false`.
You can still check for a ssh connection, add `SSH_CONNECTION` to `detect_env_vars`.

### Options

| Option | Default | Description |
| ------------ | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| `ssh_only` | `true` | Only show hostname when connected to an SSH session. |
| `ssh_symbol` | `'🌐 '` | A format string representing the symbol when connected to SSH session. |
| `trim_at` | `'.'` | String that the hostname is cut off at, after the first match. `'.'` will stop after the first dot. `''` will disable any truncation |
| `format` | `'[$ssh_symbol$hostname]($style) in '` | The format for the module. |
| `style` | `'bold dimmed green'` | The style for the module. |
| `disabled` | `false` | Disables the `hostname` module. |
| Option | Default | Description |
| ----------------- | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `ssh_only` | `true` | Only show hostname when connected to an SSH session. |
| `ssh_symbol` | `'🌐 '` | A format string representing the symbol when connected to SSH session. |
| `trim_at` | `'.'` | String that the hostname is cut off at, after the first match. `'.'` will stop after the first dot. `''` will disable any truncation. |
| `detect_env_vars` | `[]` | Which environment variable(s) should trigger this module. |
| `format` | `'[$ssh_symbol$hostname]($style) in '` | The format for the module. |
| `style` | `'bold dimmed green'` | The style for the module. |
| `disabled` | `false` | Disables the `hostname` module. |

### Variables

Expand All @@ -2210,7 +2216,9 @@ The `hostname` module shows the system hostname.

*: This variable can only be used as a part of a style string

### Example
### Examples

#### Always show the hostname

```toml
# ~/.config/starship.toml
Expand All @@ -2222,6 +2230,17 @@ trim_at = '.companyname.com'
disabled = false
```

#### Hide the hostname in remote tmux sessions

```toml
# ~/.config/starship.toml

[hostname]
ssh_only = false
detect_env_vars = ['!tmux', 'SSH_CONNECTION']
disabled = false
```

## Java

The `java` module shows the currently installed version of [Java](https://www.oracle.com/java/).
Expand Down
2 changes: 2 additions & 0 deletions src/configs/hostname.rs
Expand Up @@ -11,6 +11,7 @@ pub struct HostnameConfig<'a> {
pub ssh_only: bool,
pub ssh_symbol: &'a str,
pub trim_at: &'a str,
pub detect_env_vars: Vec<&'a str>,
pub format: &'a str,
pub style: &'a str,
pub disabled: bool,
Expand All @@ -22,6 +23,7 @@ impl<'a> Default for HostnameConfig<'a> {
ssh_only: true,
ssh_symbol: "🌐 ",
trim_at: ".",
detect_env_vars: vec![],
format: "[$ssh_symbol$hostname]($style) in ",
style: "green dimmed bold",
disabled: false,
Expand Down
17 changes: 16 additions & 1 deletion src/context.rs
Expand Up @@ -235,8 +235,23 @@ impl<'a> Context<'a> {
disabled == Some(true)
}

/// Returns true when no negated environment variable is defined in `env_vars`
/// or none of the negated variables is set in the environment.
pub fn has_no_negative_env_vars(&self, env_vars: &'a [&'a str]) -> bool {
!env_vars
.iter()
.any(|env_var| env_var.starts_with('!') && self.get_env(&env_var[1..]).is_some())
}

/// Returns true if 'detect_env_vars' is empty,
/// or if at least one environment variable is set and no negated environment variable is set
pub fn detect_env_vars(&'a self, env_vars: &'a [&'a str]) -> bool {
env_vars.is_empty() || (env_vars.iter().any(|e| self.get_env(e).is_some()))
// old
// env_vars.is_empty() || (env_vars.iter().any(|e| self.get_env(e).is_some()))
// new
env_vars.is_empty()
|| ((env_vars.iter().any(|e| self.get_env(e).is_some()))
&& self.has_no_negative_env_vars(env_vars))
}

// returns a new ScanDir struct with reference to current dir_files of context
Expand Down
98 changes: 96 additions & 2 deletions src/modules/hostname.rs
Expand Up @@ -8,14 +8,20 @@ use crate::formatter::StringFormatter;
/// Creates a module with the system hostname
///
/// Will display the hostname if all of the following criteria are met:
/// - hostname.disabled is absent or false
/// - `hostname.disabled` is absent or false
/// - `hostname.ssh_only` is false OR the user is currently connected as an SSH session (`$SSH_CONNECTION`)
/// - `hostname.ssh_only` is false AND `hostname.detect_env_vars` is either empty or contains a defined environment variable
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("hostname");
let config: HostnameConfig = HostnameConfig::try_load(module.config);

let ssh_connection = context.get_env("SSH_CONNECTION");
if config.ssh_only && ssh_connection.is_none() {
if config.ssh_only {
if ssh_connection.is_none() {
return None;
}
// check for environment variables
} else if !(context.detect_env_vars(&config.detect_env_vars)) {
return None;
}

Expand Down Expand Up @@ -95,6 +101,92 @@ mod tests {
};
}

#[test]
fn ssh_only_false_with_matching_env_var() {
let hostname = get_hostname!();
let actual = ModuleRenderer::new("hostname")
.config(toml::toml! {
[hostname]
ssh_only = false
trim_at = ""
detect_env_vars = ["FORCE_HOSTNAME"]
})
.env("FORCE_HOSTNAME", "true")
.collect();

let expected = Some(format!("{} in ", style().paint(hostname)));
assert_eq!(expected, actual);
}

#[test]
fn ssh_only_false_without_matching_env_var() {
let actual = ModuleRenderer::new("hostname")
.config(toml::toml! {
[hostname]
ssh_only = false
trim_at = ""
detect_env_vars = ["FORCE_HOSTNAME"]
})
.collect();
let expected = None;

assert_eq!(expected, actual);
}

#[test]
fn ssh_only_false_and_in_ssh_connection_with_matching_negated_env() {
let actual = ModuleRenderer::new("hostname")
.config(toml::toml! {
[hostname]
ssh_only = false
trim_at = ""
detect_env_vars = ["SSH_CONNECTION", "!TMUX"]
})
.env("SSH_CONNECTION", "something")
.env("TMUX", "true")
.collect();
let expected = None;

assert_eq!(expected, actual);
}

#[test]
fn ssh_only_false_without_matching_negated_env() {
let hostname = get_hostname!();
let actual = ModuleRenderer::new("hostname")
.config(toml::toml! {
[hostname]
ssh_only = false
trim_at = ""
detect_env_vars = ["FORCE_HOSTNAME", "!TMUX"]
})
.env("FORCE_HOSTNAME", "something")
.collect();
let expected = Some(format!("{} in ", style().paint(hostname)));

assert_eq!(expected, actual);
}

#[test]
fn ssh_only_false_and_in_ssh_connection_without_matching_negated_env() {
let hostname = get_hostname!();
let actual = ModuleRenderer::new("hostname")
.config(toml::toml! {
[hostname]
ssh_only = false
trim_at = ""
detect_env_vars = ["SSH_CONNECTION", "!TMUX"]
})
.env("SSH_CONNECTION", "something")
.collect();
let expected = Some(format!(
"{} in ",
style().paint("🌐 ".to_owned() + hostname.as_str())
));

assert_eq!(expected, actual);
}

#[test]
fn ssh_only_false_no_ssh() {
let hostname = get_hostname!();
Expand All @@ -107,6 +199,7 @@ mod tests {
.collect();
let expected = Some(format!("{} in ", style().paint(hostname)));
println!("{}", expected.as_ref().unwrap());

assert_eq!(expected, actual);
}

Expand All @@ -121,6 +214,7 @@ mod tests {
})
.collect();
let expected = Some(format!("{} in ", style().paint(hostname)));

assert_eq!(expected, actual);
}

Expand Down

0 comments on commit 56c4a45

Please sign in to comment.