feat: Add the ability to configure per-module color styles (#285)

Add parsing logic, config support, docs, and integration with other modules 
for custom styling of each module.
This commit is contained in:
Kevin Song 2019-09-07 19:33:06 -05:00 committed by GitHub
parent 3e5cac9852
commit 9721666d33
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
21 changed files with 485 additions and 184 deletions

View File

@ -72,3 +72,30 @@ precmd_functions+=(set_win_title)
If you like the result, add these lines to your shell configuration file
(`~/.bashrc` or `~/.zsrhc`) to make it permanent.
## Style Strings
Style strings are a list of words, separated by whitespace. The words are not case sensitive (i.e. `bold` and `BoLd` are considered the same string). Each word can be one of the following:
- `bold`
- `underline`
- `dimmed`
- `bg:<color>`
- `fg:<color>`
- `<color>`
- `none`
where `<color>` is a color specifier (discussed below). `fg:<color>` and `<color>` currently do the same thing , though this may change in the future. The order of words in the string does not matter.
The `none` token overrides all other tokens in a string, so that e.g. `fg:red none fg:blue` will still create a string with no styling. It may become an error to use `none` in conjunction with other tokens in the future.
A color specifier can be one of the following:
- One of the standard terminal colors: `black`, `red`, `green`, `blue`,
`yellow`, `purple`, `cyan`, `white`. You can optionally prefix these
with `bright-` to get the bright version (e.g. `bright-white`).
- A `#` followed by a six-digit hexadecimal number. This specifies an
[RGB color hex code](https://www.w3schools.com/colors/colors_hexadecimal.asp).
- A number between 0-255. This specifies an [8-bit ANSI Color Code](https://i.stack.imgur.com/KTSQa.png).
If multiple colors are specified for foreground/background, the last one in the string will take priority.

View File

@ -40,6 +40,18 @@ are segments within it. Every module also has a prefix and suffix that are the d
"via " "⬢" "v10.4.1" ""
```
### Style Strings
Most modules in starship allow you to configure their display styles. This is done with an entry (usually called `style`) which is a string specifying the configuration. Here are some examples of style strings along with what they do. For details on the full syntax, consult the [advanced config guide](/advanced-config/).
- `"fg:green bg:blue"` sets green text on a blue background
- `"bg:blue fg:bright-green"` sets bright green text on a blue background
- `"bold fg:27"` sets bold text with [ANSI color](https://i.stack.imgur.com/KTSQa.png) 27
- `"underline bg:#bf5700"` sets underlined text on a burnt orange background
- `""` explicitly disables all styling
Note that what styling looks like will be controlled by your terminal emulator. For example, some terminal emulators will brighten the colors instead of bolding text, and some color themes use the same values for the normal and bright colors.
## Prompt
This is the list of prompt-wide configuration options.
@ -96,12 +108,13 @@ The module is only visible when the device's battery is below 10%.
### Options
| Variable | Default | Description |
| -------------------- | ------- | ------------------------------------------------- |
| `full_symbol` | `"•"` | The symbol shown when the battery is full. |
| `charging_symbol` | `"⇡"` | The symbol shown when the battery is charging. |
| `discharging_symbol` | `"⇣"` | The symbol shown when the battery is discharging. |
| `disabled` | `false` | Disables the `battery` module. |
| Variable | Default | Description |
| -------------------- | ------------ | ------------------------------------------------- |
| `full_symbol` | `"•"` | The symbol shown when the battery is full. |
| `charging_symbol` | `"⇡"` | The symbol shown when the battery is charging. |
| `discharging_symbol` | `"⇣"` | The symbol shown when the battery is discharging. |
| `style` | `"bold red"` | The style for the module. |
| `disabled` | `false` | Disables the `battery` module. |
### Example
@ -125,13 +138,15 @@ can do this in two ways: by changing color (red/green) or by changing its shape
### Options
| Variable | Default | Description |
| ----------------------- | ------- | ----------------------------------------------------------------------------------- |
| `symbol` | `""` | The symbol used before the text input in the prompt. |
| `error_symbol` | `"✖"` | The symbol used before text input if the previous command failed. |
| `use_symbol_for_status` | `false` | Indicate error status by changing the symbol. |
| `vicmd_symbol` | `""` | The symbol used before the text input in the prompt if shell is in vim normal mode. |
| `disabled` | `false` | Disables the `character` module. |
| Variable | Default | Description |
| ----------------------- | -------------- | ----------------------------------------------------------------------------------- |
| `symbol` | `""` | The symbol used before the text input in the prompt. |
| `error_symbol` | `"✖"` | The symbol used before text input if the previous command failed. |
| `use_symbol_for_status` | `false` | Indicate error status by changing the symbol. |
| `vicmd_symbol` | `""` | The symbol used before the text input in the prompt if shell is in vim normal mode. |
| `style_success` | `"bold green"` | The style used if the last command was successful. |
| `style_failure` | `"bold red"` | The style used if the last command failed. |
| `disabled` | `false` | Disables the `character` module. |
### Example
@ -162,10 +177,11 @@ running `eval $(starship init $0)`, and then proceed as normal.
### Options
| Variable | Default | Description |
| ---------- | ------- | ----------------------------------- |
| `min_time` | `2` | Shortest duration to show time for. |
| `disabled` | `false` | Disables the `cmd_duration` module. |
| Variable | Default | Description |
| ---------- | --------------- | ----------------------------------- |
| `min_time` | `2` | Shortest duration to show time for. |
| `style` | `"bold yellow"` | The style for the module. |
| `disabled` | `false` | Disables the `cmd_duration` module. |
### Example
@ -192,12 +208,13 @@ it would have been `nixpkgs/pkgs`.
### Options
| Variable | Default | Description |
| --------------------------- | ------- | -------------------------------------------------------------------------------- |
| `truncation_length` | `3` | The number of parent folders that the current directory should be truncated to. |
| `truncate_to_repo` | `true` | Whether or not to truncate to the root of the git repo that you're currently in. |
| `disabled` | `false` | Disables the `directory` module. |
| `fish_style_pwd_dir_length` | `0` | The number of characters to use when applying fish shell pwd path logic. |
| Variable | Default | Description |
| --------------------------- | ------------- | -------------------------------------------------------------------------------- |
| `truncation_length` | `3` | The number of parent folders that the current directory should be truncated to. |
| `truncate_to_repo` | `true` | Whether or not to truncate to the root of the git repo that you're currently in. |
| `fish_style_pwd_dir_length` | `0` | The number of characters to use when applying fish shell pwd path logic. |
| `style` | `"bold cyan"` | The style for the module. |
| `disabled` | `false` | Disables the `directory` module. |
### Example
@ -214,12 +231,13 @@ The `git_branch` module shows the active branch of the repo in your current dire
### Options
| Variable | Default | Description |
| ------------------- | ---------- | ------------------------------------------------------------------------------------- |
| `symbol` | `" "` | The symbol used before the branch name of the repo in your current directory. |
| `disabled` | `false` | Disables the `git_branch` module. |
| `truncation_length` | `2^63 - 1` | Truncates a git branch to X graphemes |
| `truncation_symbol` | `"…"` | The symbol used to indicate a branch name was truncated. You can use "" for no symbol |
| Variable | Default | Description |
| ------------------- | --------------- | ------------------------------------------------------------------------------------- |
| `symbol` | `" "` | The symbol used before the branch name of the repo in your current directory. |
| `truncation_length` | `2^63 - 1` | Truncates a git branch to X graphemes |
| `truncation_symbol` | `"…"` | The symbol used to indicate a branch name was truncated. You can use "" for no symbol |
| `style` | `"bold purple"` | The style for the module. |
| `disabled` | `false` | Disables the `git_branch` module. |
### Example
@ -251,6 +269,7 @@ that information will be shown too.
| `am` | `"AM"` | The text displayed when an `apply-mailbox` (`git am`) is in progress. |
| `am_or_rebase` | `"AM/REBASE"` | The text displayed when an ambiguous `apply-mailbox` or `rebase` is in progress. |
| `progress_divider` | `"/"` | The symbol or text which will separate the current and total progress amounts. (e.g., `" of "`, for `"3 of 10"`) |
| `style` | `"bold yellow"` | The style for the module. |
| `disabled` | `false` | Disables the `git_state` module. |
### Example
@ -270,20 +289,21 @@ current directory.
### Options
| Variable | Default | Description |
| ----------------- | ------- | ------------------------------------------------------- |
| `conflicted` | `"="` | This branch has merge conflicts. |
| `ahead` | `"⇡"` | This branch is ahead of the branch being tracked. |
| `behind` | `"⇣"` | This branch is behind of the branch being tracked. |
| `diverged` | `"⇕"` | This branch has diverged from the branch being tracked. |
| `untracked` | `"?"` | There are untracked files in the working directory. |
| `stashed` | `"$"` | A stash exists for the local repository. |
| `modified` | `"!"` | There are file modifications in the working directory. |
| `staged` | `"+"` | A new file has been added to the staging area. |
| `renamed` | `"»"` | A renamed file has been added to the staging area. |
| `deleted` | `"✘"` | A file's deletion has been added to the staging area. |
| `show_sync_count` | `false` | Show ahead/behind count of the branch being tracked. |
| `disabled` | `false` | Disables the `git_status` module. |
| Variable | Default | Description |
| ----------------- | ------------ | ------------------------------------------------------- |
| `conflicted` | `"="` | This branch has merge conflicts. |
| `ahead` | `"⇡"` | This branch is ahead of the branch being tracked. |
| `behind` | `"⇣"` | This branch is behind of the branch being tracked. |
| `diverged` | `"⇕"` | This branch has diverged from the branch being tracked. |
| `untracked` | `"?"` | There are untracked files in the working directory. |
| `stashed` | `"$"` | A stash exists for the local repository. |
| `modified` | `"!"` | There are file modifications in the working directory. |
| `staged` | `"+"` | A new file has been added to the staging area. |
| `renamed` | `"»"` | A renamed file has been added to the staging area. |
| `deleted` | `"✘"` | A file's deletion has been added to the staging area. |
| `show_sync_count` | `false` | Show ahead/behind count of the branch being tracked. |
| `style` | `"bold red"` | The style for the module. |
| `disabled` | `false` | Disables the `git_status` module. |
### Example
@ -303,31 +323,6 @@ 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 = "⟪"
suffix = "⟫"
disabled = false
```
## Golang
The `golang` module shows the currently installed version of Golang.
@ -343,10 +338,11 @@ The module will be shown if any of the following conditions are met:
### Options
| Variable | Default | Description |
| ---------- | ------- | -------------------------------------------------------- |
| `symbol` | `"🐹 "` | The symbol used before displaying the version of Golang. |
| `disabled` | `false` | Disables the `golang` module. |
| Variable | Default | Description |
| ---------- | ------------- | -------------------------------------------------------- |
| `symbol` | `"🐹 "` | The symbol used before displaying the version of Golang. |
| `style` | `"bold cyan"` | The style for the module. |
| `disabled` | `false` | Disables the `golang` module. |
### Example
@ -357,6 +353,34 @@ The module will be shown if any of the following conditions are met:
symbol = "🏎💨 "
```
## 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. |
| `style` | `"bold dimmed green"` | The style for the module. |
| `disabled` | `false` | Disables the `hostname` module. |
### Example
```toml
# ~/.config/starship.toml
[hostname]
ssh_only = false
prefix = "⟪"
suffix = "⟫"
disabled = false
```
## Jobs
The `jobs` module shows the current number of jobs running.
@ -366,11 +390,12 @@ more than the `threshold` config value, if it exists.
### Options
| Variable | Default | Description |
| ----------- | ------- | ----------------------------------------------------- |
| `symbol` | `"✦ "` | The symbol used before displaying the number of jobs. |
| `threshold` | `1` | Show number of jobs if exceeded. |
| `disabled` | `false` | Disables the `jobs` module. |
| Variable | Default | Description |
| ----------- | ------------- | ----------------------------------------------------- |
| `symbol` | `"✦ "` | The symbol used before displaying the number of jobs. |
| `threshold` | `1` | Show number of jobs if exceeded. |
| `style` | `"bold blue"` | The style for the module. |
| `disabled` | `false` | Disables the `jobs` module. |
### Example
@ -401,20 +426,6 @@ The `line_break` module separates the prompt into two lines.
disabled = true
```
## Ruby
The `ruby` module shows the currently installed version of Ruby.
The module will be shown if any of the following conditions are met:
- The current directory contains a `Gemfile` file
- The current directory contains a `.rb` file
### Options
| Variable | Default | Description |
| ---------- | ------- | ------------------------------------------------------ |
| `symbol` | `"💎 "` | The symbol used before displaying the version of Ruby. |
| `disabled` | `false` | Disables the `ruby` module. |
### Example
@ -425,6 +436,34 @@ The module will be shown if any of the following conditions are met:
symbol = "🔺 "
```
## Nix-shell
The `nix_shell` module shows the nix-shell environment.
The module will be shown when inside a nix-shell environment.
### Options
| Variable | Default | Description |
| ------------ | ------------ | ---------------------------------- |
| `use_name` | `false` | Display the name of the nix-shell. |
| `impure_msg` | `impure` | Customize the "impure" msg. |
| `pure_msg` | `pure` | Customize the "pure" msg. |
| `style` | `"bold red"` | The style for the module. |
| `disabled` | `false` | Disables the `nix_shell` module. |
### Example
```toml
# ~/.config/starship.toml
[nix_shell]
disabled = true
use_name = true
impure_msg = "impure shell"
pure_msg = "pure shell"
```
## NodeJS
The `nodejs` module shows the currently installed version of NodeJS.
@ -436,10 +475,11 @@ The module will be shown if any of the following conditions are met:
### Options
| Variable | Default | Description |
| ---------- | ------- | -------------------------------------------------------- |
| `symbol` | `"⬢ "` | The symbol used before displaying the version of NodeJS. |
| `disabled` | `false` | Disables the `nodejs` module. |
| Variable | Default | Description |
| ---------- | -------------- | -------------------------------------------------------- |
| `symbol` | `"⬢ "` | The symbol used before displaying the version of NodeJS. |
| `style` | `"bold green"` | The style for the module. |
| `disabled` | `false` | Disables the `nodejs` module. |
### Example
@ -468,10 +508,11 @@ and `poetry` packages.
### Options
| Variable | Default | Description |
| ---------- | ------- | ---------------------------------------------------------- |
| `symbol` | `"📦 "` | The symbol used before displaying the version the package. |
| `disabled` | `false` | Disables the `package` module. |
| Variable | Default | Description |
| ---------- | ------------ | ---------------------------------------------------------- |
| `symbol` | `"📦 "` | The symbol used before displaying the version the package. |
| `style` | `"bold red"` | The style for the module. |
| `disabled` | `false` | Disables the `package` module. |
### Example
@ -502,12 +543,13 @@ The module will be shown if any of the following conditions are met:
### Options
| Variable | Default | Description |
| -------------------- | ---------- | --------------------------------------------------------------------------- |
| `symbol` | `"🐍 "` | The symbol used before displaying the version of Python. |
| `disabled` | `false` | Disables the `python` module. |
| `pyenv_version_name` | `false` | Use pyenv to get Python version |
| `pyenv_prefix` | `"pyenv "` | Prefix before pyenv version display (default display is `pyenv MY_VERSION`) |
| Variable | Default | Description |
| -------------------- | --------------- | --------------------------------------------------------------------------- |
| `symbol` | `"🐍 "` | The symbol used before displaying the version of Python. |
| `pyenv_version_name` | `false` | Use pyenv to get Python version |
| `pyenv_prefix` | `"pyenv "` | Prefix before pyenv version display (default display is `pyenv MY_VERSION`) |
| `style` | `"bold yellow"` | The style for the module. |
| `disabled` | `false` | Disables the `python` module. |
### Example
@ -520,6 +562,22 @@ pyenv_version_name = true
pyenv_prefix = "foo "
```
## Ruby
The `ruby` module shows the currently installed version of Ruby.
The module will be shown if any of the following conditions are met:
- The current directory contains a `Gemfile` file
- The current directory contains a `.rb` file
### Options
| Variable | Default | Description |
| ---------- | ------------ | ------------------------------------------------------ |
| `symbol` | `"💎 "` | The symbol used before displaying the version of Ruby. |
| `style` | `"bold red"` | The style for the module. |
| `disabled` | `false` | Disables the `ruby` module. |
## Rust
The `rust` module shows the currently installed version of Rust.
@ -530,10 +588,11 @@ The module will be shown if any of the following conditions are met:
### Options
| Variable | Default | Description |
| ---------- | ------- | ------------------------------------------------------ |
| `symbol` | `"🦀 "` | The symbol used before displaying the version of Rust. |
| `disabled` | `false` | Disables the `rust` module. |
| Variable | Default | Description |
| ---------- | ------------ | ------------------------------------------------------ |
| `symbol` | `"🦀 "` | The symbol used before displaying the version of Rust. |
| `style` | `"bold red"` | The style for the module. |
| `disabled` | `false` | Disables the `rust` module. |
### Example
@ -555,9 +614,11 @@ The module will be shown if any of the following conditions are met:
### Options
| Variable | Default | Description |
| ---------- | ------- | ------------------------------- |
| `disabled` | `false` | Disables the `username` module. |
| Variable | Default | Description |
| ------------ | --------------- | ------------------------------------- |
| `style_root` | `"bold red"` | The style used when the user is root. |
| `style_user` | `"bold yellow"` | The style used for non-root users. |
| `disabled` | `false` | Disables the `username` module. |
### Example
@ -567,29 +628,3 @@ The module will be shown if any of the following conditions are met:
[username]
disabled = true
```
## Nix-shell
The `nix_shell` module shows the nix-shell environment.
The module will be shown when inside a nix-shell environment.
### Options
| Variable | Default | Description |
| ------------ | -------- | ---------------------------------- |
| `disabled` | `false` | Disables the `nix_shell` module. |
| `use_name` | `false` | Display the name of the nix-shell. |
| `impure_msg` | `impure` | Customize the "impure" msg. |
| `pure_msg` | `pure` | Customize the "pure" msg. |
### Example
```toml
# ~/.config/starship.toml
[nix_shell]
disabled = true
use_name = true
impure_msg = "impure shell"
pure_msg = "pure shell"
```

View File

@ -4,6 +4,8 @@ use std::env;
use dirs::home_dir;
use toml::value::Table;
use ansi_term::Color;
pub trait Config {
fn initialize() -> Table;
fn config_from_file() -> Option<Table>;
@ -14,6 +16,7 @@ pub trait Config {
fn get_as_str(&self, key: &str) -> Option<&str>;
fn get_as_i64(&self, key: &str) -> Option<i64>;
fn get_as_array(&self, key: &str) -> Option<&Vec<toml::value::Value>>;
fn get_as_ansi_style(&self, key: &str) -> Option<ansi_term::Style>;
// Internal implementation for accessors
fn get_config(&self, key: &str) -> Option<&toml::value::Value>;
@ -157,11 +160,132 @@ impl Config for Table {
}
array_value
}
/// Get a text key and attempt to interpret it into an ANSI style.
fn get_as_ansi_style(&self, key: &str) -> Option<ansi_term::Style> {
let style_string = self.get_as_str(key)?;
parse_style_string(style_string)
}
}
/** Parse a style string which represents an ansi style. Valid tokens in the style
string include the following:
- 'fg:<color>' (specifies that the color read should be a foreground color)
- 'bg:<color>' (specifies that the color read should be a background color)
- 'underline'
- 'bold'
- '<color>' (see the parse_color_string doc for valid color strings)
*/
fn parse_style_string(style_string: &str) -> Option<ansi_term::Style> {
let tokens = style_string.split_whitespace();
let mut style = ansi_term::Style::new();
// If col_fg is true, color the foreground. If it's false, color the background.
let mut col_fg: bool;
for token in tokens {
let token = token.to_lowercase();
// Check for FG/BG identifiers and strip them off if appropriate
let token = if token.as_str().starts_with("fg:") {
col_fg = true;
token.trim_start_matches("fg:").to_owned()
} else if token.as_str().starts_with("bg:") {
col_fg = false;
token.trim_start_matches("bg:").to_owned()
} else {
col_fg = true; // Bare colors are assumed to color the foreground
token
};
match token.as_str() {
"underline" => style = style.underline(),
"bold" => style = style.bold(),
"dimmed" => style = style.dimmed(),
"none" => return Some(ansi_term::Style::new()), // Overrides other toks
// Try to see if this token parses as a valid color string
color_string => {
// Match found: set either fg or bg color
if let Some(ansi_color) = parse_color_string(color_string) {
if col_fg {
style = style.fg(ansi_color);
} else {
style = style.on(ansi_color);
}
} else {
// Match failed: skip this token and log it
log::debug!("Could not parse token in color string: {}", token)
}
}
}
}
Some(style)
}
/** Parse a string that represents a color setting, returning None if this fails
There are three valid color formats:
- #RRGGBB (a hash followed by an RGB hex)
- u8 (a number from 0-255, representing an ANSI color)
- colstring (one of the 16 predefined color strings)
*/
fn parse_color_string(color_string: &str) -> Option<ansi_term::Color> {
// Parse RGB hex values
log::trace!("Parsing color_string: {}", color_string);
if color_string.starts_with('#') {
log::trace!(
"Attempting to read hexadecimal color string: {}",
color_string
);
let r: u8 = u8::from_str_radix(&color_string[1..3], 16).ok()?;
let g: u8 = u8::from_str_radix(&color_string[3..5], 16).ok()?;
let b: u8 = u8::from_str_radix(&color_string[5..7], 16).ok()?;
log::trace!("Read RGB color string: {},{},{}", r, g, b);
return Some(Color::RGB(r, g, b));
}
// Parse a u8 (ansi color)
if let Result::Ok(ansi_color_num) = color_string.parse::<u8>() {
log::trace!("Read ANSI color string: {}", ansi_color_num);
return Some(Color::Fixed(ansi_color_num));
}
// Check for any predefined color strings
// There are no predefined enums for bright colors, so we use Color::Fixed
let predefined_color = match color_string.to_lowercase().as_str() {
"black" => Some(Color::Black),
"red" => Some(Color::Red),
"green" => Some(Color::Green),
"yellow" => Some(Color::Yellow),
"blue" => Some(Color::Blue),
"purple" => Some(Color::Purple),
"cyan" => Some(Color::Cyan),
"white" => Some(Color::White),
"bright-black" => Some(Color::Fixed(8)), // "bright-black" is dark grey
"bright-red" => Some(Color::Fixed(9)),
"bright-green" => Some(Color::Fixed(10)),
"bright-yellow" => Some(Color::Fixed(11)),
"bright-blue" => Some(Color::Fixed(12)),
"bright-purple" => Some(Color::Fixed(13)),
"bright-cyan" => Some(Color::Fixed(14)),
"bright-white" => Some(Color::Fixed(15)),
_ => None,
};
if predefined_color.is_some() {
log::trace!("Read predefined color: {}", color_string);
return predefined_color;
}
// All attempts to parse have failed
None
}
#[cfg(test)]
mod tests {
use super::*;
use ansi_term::Style;
#[test]
fn table_get_as_bool() {
@ -210,4 +334,79 @@ mod tests {
);
assert_eq!(table.get_as_bool("string"), None);
}
#[test]
fn table_get_styles_simple() {
let mut table = toml::value::Table::new();
// Test for a bold underline green module (with SiLlY cApS)
table.insert(
String::from("mystyle"),
toml::value::Value::String(String::from("bOlD uNdErLiNe GrEeN")),
);
assert!(table.get_as_ansi_style("mystyle").unwrap().is_bold);
assert!(table.get_as_ansi_style("mystyle").unwrap().is_underline);
assert_eq!(
table.get_as_ansi_style("mystyle").unwrap(),
ansi_term::Style::new().bold().underline().fg(Color::Green)
);
// Test a "plain" style with no formatting
table.insert(
String::from("plainstyle"),
toml::value::Value::String(String::from("")),
);
assert_eq!(
table.get_as_ansi_style("plainstyle").unwrap(),
ansi_term::Style::new()
);
// Test a string that's clearly broken
table.insert(
String::from("broken"),
toml::value::Value::String(String::from("djklgfhjkldhlhk;j")),
);
assert_eq!(
table.get_as_ansi_style("broken").unwrap(),
ansi_term::Style::new()
);
// Test a string that's nullified by `none`
table.insert(
String::from("nullified"),
toml::value::Value::String(String::from("fg:red bg:green bold none")),
);
assert_eq!(
table.get_as_ansi_style("nullified").unwrap(),
ansi_term::Style::new()
);
}
#[test]
fn table_get_styles_ordered() {
let mut table = toml::value::Table::new();
// Test a background style with inverted order (also test hex + ANSI)
table.insert(
String::from("flipstyle"),
toml::value::Value::String(String::from("bg:#050505 underline fg:120")),
);
assert_eq!(
table.get_as_ansi_style("flipstyle").unwrap(),
Style::new()
.underline()
.fg(Color::Fixed(120))
.on(Color::RGB(5, 5, 5))
);
// Test that the last color style is always the one used
table.insert(
String::from("multistyle"),
toml::value::Value::String(String::from("bg:120 bg:125 bg:127 fg:127 122 125")),
);
assert_eq!(
table.get_as_ansi_style("multistyle").unwrap(),
Style::new().fg(Color::Fixed(125)).on(Color::Fixed(127))
);
}
}

View File

@ -139,6 +139,11 @@ impl<'a> Module<'a> {
pub fn config_value_bool(&self, key: &str) -> Option<bool> {
self.config.and_then(|config| config.get_as_bool(key))
}
/// Get a module's config value as a style
pub fn config_value_style(&self, key: &str) -> Option<Style> {
self.config.and_then(|config| config.get_as_ansi_style(key))
}
}
impl<'a> fmt::Display for Module<'a> {

View File

@ -30,7 +30,10 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
// TODO: Set style based on percentage when threshold is modifiable
let mut module = context.new_module("battery")?;
module.set_style(Color::Red.bold());
let module_style = module
.config_value_style("style")
.unwrap_or_else(|| Color::Red.bold());
module.set_style(module_style);
module.get_prefix().set_value("");
match state {

View File

@ -5,10 +5,10 @@ use ansi_term::Color;
///
/// The character segment prints an arrow character in a color dependant on the exit-
/// code of the last executed command:
/// - If the exit-code was "0", the arrow will be formatted with `COLOR_SUCCESS`
/// - If the exit-code was "0", the arrow will be formatted with `style_success`
/// (green by default)
/// - If the exit-code was anything else, the arrow will be formatted with
/// `COLOR_FAILURE` (red by default)
/// `style_failure` (red by default)
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
const SUCCESS_CHAR: &str = "";
const FAILURE_CHAR: &str = "";
@ -20,12 +20,16 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
const ASSUMED_MODE: ShellEditMode = ShellEditMode::Insert;
// TODO: extend config to more modes
let color_success = Color::Green.bold();
let color_failure = Color::Red.bold();
let mut module = context.new_module("character")?;
module.get_prefix().set_value("");
let style_success = module
.config_value_style("style_success")
.unwrap_or_else(|| Color::Green.bold());
let style_failure = module
.config_value_style("style_failure")
.unwrap_or_else(|| Color::Red.bold());
let arguments = &context.arguments;
let use_symbol = module
.config_value_bool("use_symbol_for_status")
@ -56,9 +60,9 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
};
if exit_success {
symbol.set_style(color_success.bold());
symbol.set_style(style_success);
} else {
symbol.set_style(color_failure.bold());
symbol.set_style(style_failure);
};
Some(module)

View File

@ -32,7 +32,9 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let module_color = match elapsed {
time if time < config_min => return None,
_ => Color::Yellow.bold(),
_ => module
.config_value_style("style")
.unwrap_or_else(|| Color::Yellow.bold()),
};
module.set_style(module_color);

View File

@ -17,9 +17,11 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
const HOME_SYMBOL: &str = "~";
const DIR_TRUNCATION_LENGTH: i64 = 3;
const FISH_STYLE_PWD_DIR_LENGTH: i64 = 0;
let module_color = Color::Cyan.bold();
let mut module = context.new_module("directory")?;
let module_color = module
.config_value_style("style")
.unwrap_or_else(|| Color::Cyan.bold());
module.set_style(module_color);
let truncation_length = module

View File

@ -9,9 +9,11 @@ use super::{Context, Module};
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
const GIT_BRANCH_CHAR: &str = "";
let segment_color = Color::Purple.bold();
let mut module = context.new_module("git_branch")?;
let segment_color = module
.config_value_style("style")
.unwrap_or_else(|| Color::Purple.bold());
module.set_style(segment_color);
module.get_prefix().set_value("on ");

View File

@ -19,9 +19,12 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
return None;
}
let module_style = module
.config_value_style("style")
.unwrap_or_else(|| Color::Yellow.bold());
module.set_style(module_style);
module.get_prefix().set_value("(");
module.get_suffix().set_value(") ");
module.set_style(Color::Yellow.bold());
let label = match state_description {
StateDescription::Label(label) => label,

View File

@ -34,10 +34,11 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let repo_root = context.repo_root.as_ref()?;
let repository = Repository::open(repo_root).ok()?;
let module_style = Color::Red.bold();
let mut module = context.new_module("git_status")?;
let show_sync_count = module.config_value_bool("show_sync_count").unwrap_or(false);
let module_style = module
.config_value_style("style")
.unwrap_or_else(|| Color::Red.bold());
module.get_prefix().set_value("[").set_style(module_style);
module.get_suffix().set_value("] ").set_style(module_style);

View File

@ -28,10 +28,12 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
match get_go_version() {
Some(go_version) => {
const GO_CHAR: &str = "🐹 ";
let module_color = Color::Cyan.bold();
let mut module = context.new_module("golang")?;
module.set_style(module_color);
let module_style = module
.config_value_style("style")
.unwrap_or_else(|| Color::Cyan.bold());
module.set_style(module_style);
let formatted_version = format_go_version(&go_version)?;
module.new_segment("symbol", GO_CHAR);

View File

@ -1,6 +1,5 @@
use ansi_term::{Color, Style};
use ansi_term::Color;
use std::env;
use std::process::Command;
use super::{Context, Module};
use std::ffi::OsString;
@ -12,6 +11,9 @@ use std::ffi::OsString;
/// - 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 module_style = module
.config_value_style("style")
.unwrap_or_else(|| Color::Green.bold().dimmed());
let ssh_connection = env::var("SSH_CONNECTION").ok();
if module.config_value_bool("ssh_only").unwrap_or(true) && ssh_connection.is_none() {
@ -31,7 +33,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
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.set_style(module_style);
module.new_segment("hostname", &format!("{}{}{}", prefix, host, suffix));
module.get_prefix().set_value("on ");

View File

@ -9,9 +9,10 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let threshold = module.config_value_i64("threshold").unwrap_or(1);
const JOB_CHAR: &str = "";
let module_color = Color::Blue.bold();
module.set_style(module_color);
let module_style = module
.config_value_style("style")
.unwrap_or_else(|| Color::Blue.bold());
module.set_style(module_style);
let arguments = &context.arguments;
let num_of_jobs = arguments

View File

@ -46,8 +46,10 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
}
})
.map(|segment| {
let module_color = Color::Red.bold();
module.set_style(module_color);
let module_style = module
.config_value_style("style")
.unwrap_or_else(|| Color::Red.bold());
module.set_style(module_style);
module.new_segment("nix_shell", &segment);
module
})

View File

@ -24,10 +24,12 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
match get_node_version() {
Some(node_version) => {
const NODE_CHAR: &str = "";
let module_color = Color::Green.bold();
let mut module = context.new_module("nodejs")?;
module.set_style(module_color);
let module_style = module
.config_value_style("style")
.unwrap_or_else(|| Color::Green.bold());
module.set_style(module_style);
let formatted_version = node_version.trim();
module.new_segment("symbol", NODE_CHAR);

View File

@ -12,10 +12,12 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
match get_package_version() {
Some(package_version) => {
const PACKAGE_CHAR: &str = "📦 ";
let module_color = Color::Red.bold();
let mut module = context.new_module("package")?;
module.set_style(module_color);
let module_style = module
.config_value_style("style")
.unwrap_or_else(|| Color::Red.bold());
module.set_style(module_style);
module.get_prefix().set_value("is ");
module.new_segment("symbol", PACKAGE_CHAR);

View File

@ -36,7 +36,9 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
.unwrap_or(false);
const PYTHON_CHAR: &str = "🐍 ";
let module_color = Color::Yellow.bold();
let module_color = module
.config_value_style("style")
.unwrap_or_else(|| Color::Yellow.bold());
module.set_style(module_color);
module.new_segment("symbol", PYTHON_CHAR);

View File

@ -22,10 +22,12 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
match get_ruby_version() {
Some(ruby_version) => {
const RUBY_CHAR: &str = "💎 ";
let module_color = Color::Red.bold();
let mut module = context.new_module("ruby")?;
module.set_style(module_color);
let module_style = module
.config_value_style("style")
.unwrap_or_else(|| Color::Red.bold());
module.set_style(module_style);
let formatted_version = format_ruby_version(&ruby_version)?;
module.new_segment("symbol", RUBY_CHAR);

View File

@ -22,10 +22,12 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
match get_rust_version() {
Some(rust_version) => {
const RUST_CHAR: &str = "🦀 ";
let module_color = Color::Red.bold();
let mut module = context.new_module("rust")?;
module.set_style(module_color);
let module_style = module
.config_value_style("style")
.unwrap_or_else(|| Color::Red.bold());
module.set_style(module_style);
let formatted_version = format_rustc_version(rust_version);
module.new_segment("symbol", RUST_CHAR);

View File

@ -15,11 +15,12 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let logname = env::var("LOGNAME").ok();
let ssh_connection = env::var("SSH_CONNECTION").ok();
let mut module_color = Color::Yellow.bold();
if user != logname || ssh_connection.is_some() || is_root(&mut module_color) {
const ROOT_UID: Option<u32> = Some(0);
let user_uid = get_uid();
if user != logname || ssh_connection.is_some() || user_uid == ROOT_UID {
let mut module = context.new_module("username")?;
module.set_style(module_color);
let module_style = get_mod_style(user_uid, &module);
module.set_style(module_style);
module.new_segment("username", &user?);
return Some(module);
@ -37,13 +38,13 @@ fn get_uid() -> Option<u32> {
}
}
fn is_root(style: &mut Style) -> bool {
match get_uid() {
Some(uid) if uid == 0 => {
style.clone_from(&Color::Red.bold());
true
}
_ => false,
fn get_mod_style(user_uid: Option<u32>, module: &Module) -> Style {
match user_uid {
Some(0) => module
.config_value_style("style_root")
.unwrap_or_else(|| Color::Red.bold()),
_ => module
.config_value_style("style_user")
.unwrap_or_else(|| Color::Yellow.bold()),
}
}