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: add host module #286

Merged
merged 7 commits into from Sep 4, 2019
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
11 changes: 11 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Expand Up @@ -40,6 +40,7 @@ battery = { version = "0.7.4", optional = true }
lazy_static = "1.4.0"
path-slash = "0.1.1"
unicode-segmentation = "1.3.0"
gethostname = "0.2.0"

[dev-dependencies]
tempfile = "3.1.0"
26 changes: 26 additions & 0 deletions docs/config/README.md
Expand Up @@ -69,6 +69,7 @@ The `default_prompt_order` configuration option is used to define the order in w
```
default_prompt_order = [
"username",
"hostname",
"directory",
"git_branch",
"git_status",
Expand Down Expand Up @@ -268,6 +269,31 @@ renamed = "👅"
deleted = "🗑"
```

## Hostname

The `hostname` module shows the system hostname.

### Options

| Variable | Default | Description |
| ------------ | ------- | ------------------------------------------------------- |
| `ssh_only` | `true` | Only show hostname when connected to an SSH session. |
| `prefix` | `""` | Prefix to display immediately before the hostname. |
| `suffix` | `""` | Suffix to display immediately after the hostname. |
| `disabled` | `false` | Disables the `hostname` module. |

### Example

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

[hostname]
ssh_only = false
prefix = "⟪"
ahouts marked this conversation as resolved.
Show resolved Hide resolved
suffix = "⟫"
disabled = false
```

## Golang

The `golang` module shows the currently installed version of Golang.
Expand Down
39 changes: 39 additions & 0 deletions src/modules/hostname.rs
@@ -0,0 +1,39 @@
use ansi_term::{Color, Style};
use std::env;
use std::process::Command;

use super::{Context, Module};
use std::ffi::OsString;

/// Creates a module with the system hostname
///
/// Will display the hostname if all of the following criteria are met:
ahouts marked this conversation as resolved.
Show resolved Hide resolved
/// - hostname.disabled is absent or false
/// - hostname.ssh_only is false OR the user is currently connected as an SSH session (`$SSH_CONNECTION`)
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("hostname")?;

let ssh_connection = env::var("SSH_CONNECTION").ok();
if module.config_value_bool("ssh_only").unwrap_or(true) && ssh_connection.is_none() {
return None;
}

let os_hostname: OsString = gethostname::gethostname();

let host = match os_hostname.into_string() {
Ok(host) => host,
Err(bad) => {
log::debug!("hostname is not valid UTF!\n{:?}", bad);
return None;
}
};

let prefix = module.config_value_str("prefix").unwrap_or("").to_owned();
let suffix = module.config_value_str("suffix").unwrap_or("").to_owned();

module.set_style(Color::Green.bold().dimmed());
module.new_segment("hostname", &format!("{}{}{}", prefix, host, suffix));
module.get_prefix().set_value("on ");

Some(module)
}
2 changes: 2 additions & 0 deletions src/modules/mod.rs
Expand Up @@ -5,6 +5,7 @@ mod directory;
mod git_branch;
mod git_status;
mod golang;
mod hostname;
mod jobs;
mod line_break;
mod nix_shell;
Expand Down Expand Up @@ -40,6 +41,7 @@ pub fn handle<'a>(module: &str, context: &'a Context) -> Option<Module<'a>> {
"cmd_duration" => cmd_duration::module(context),
"jobs" => jobs::module(context),
"nix_shell" => nix_shell::module(context),
"hostname" => hostname::module(context),

_ => {
eprintln!("Error: Unknown module {}. Use starship module --list to list out all supported modules.", module);
Expand Down
1 change: 1 addition & 0 deletions src/print.rs
Expand Up @@ -13,6 +13,7 @@ use crate::modules;
// prompt heading of config docs needs to be updated according to changes made here.
const DEFAULT_PROMPT_ORDER: &[&str] = &[
"username",
"hostname",
"directory",
"git_branch",
"git_status",
Expand Down
117 changes: 117 additions & 0 deletions tests/testsuite/hostname.rs
@@ -0,0 +1,117 @@
use ansi_term::{Color, Style};
use std::io;

use crate::common;
use crate::common::TestCommand;

#[test]
fn ssh_only_false() -> io::Result<()> {
let hostname = match get_hostname() {
Some(h) => h,
None => return hostname_not_tested(),
};
let output = common::render_module("hostname")
.env_clear()
.use_config(toml::toml! {
[hostname]
ssh_only = false
})
.output()?;
let actual = String::from_utf8(output.stdout).unwrap();
let expected = format!("on {} ", style().paint(hostname));
assert_eq!(expected, actual);
Ok(())
}

#[test]
fn no_ssh() -> io::Result<()> {
let output = common::render_module("hostname")
.env_clear()
.use_config(toml::toml! {
[hostname]
ssh_only = true
})
.output()?;
let actual = String::from_utf8(output.stdout).unwrap();
assert_eq!("", actual);
Ok(())
}

#[test]
fn ssh() -> io::Result<()> {
let hostname = match get_hostname() {
Some(h) => h,
None => return hostname_not_tested(),
};
let output = common::render_module("hostname")
.env_clear()
.use_config(toml::toml! {
[hostname]
ssh_only = true
})
.env("SSH_CONNECTION", "something")
.output()?;
let actual = String::from_utf8(output.stdout).unwrap();
let expected = format!("on {} ", style().paint(hostname));
assert_eq!(expected, actual);
Ok(())
}

#[test]
fn prefix() -> io::Result<()> {
let hostname = match get_hostname() {
Some(h) => h,
None => return hostname_not_tested(),
};
let output = common::render_module("hostname")
.env_clear()
.use_config(toml::toml! {
[hostname]
ssh_only = false
prefix = "<"
})
.output()?;
let actual = String::from_utf8(output.stdout).unwrap();
let expected = format!("on {} ", style().paint(format!("<{}", hostname)));
assert_eq!(actual, expected);
Ok(())
}

#[test]
fn suffix() -> io::Result<()> {
let hostname = match get_hostname() {
Some(h) => h,
None => return hostname_not_tested(),
};
let output = common::render_module("hostname")
.env_clear()
.use_config(toml::toml! {
[hostname]
ssh_only = false
suffix = ">"
})
.output()?;
let actual = String::from_utf8(output.stdout).unwrap();
let expected = format!("on {} ", style().paint(format!("{}>", hostname)));
assert_eq!(actual, expected);
Ok(())
}

fn get_hostname() -> Option<String> {
match gethostname::gethostname().into_string() {
Ok(hostname) => Some(hostname),
Err(_) => None,
}
}

fn style() -> Style {
Color::Green.bold().dimmed()
}

fn hostname_not_tested() -> io::Result<()> {
println!(
"hostname was not tested because gethostname failed! \
This could be caused by your hostname containing invalid UTF."
);
Ok(())
}
1 change: 1 addition & 0 deletions tests/testsuite/main.rs
Expand Up @@ -6,6 +6,7 @@ mod directory;
mod git_branch;
mod git_status;
mod golang;
mod hostname;
mod jobs;
mod line_break;
mod modules;
Expand Down