repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/deno.rs | src/modules/deno.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::deno::DenoConfig;
use crate::formatter::StringFormatter;
use crate::formatter::VersionFormatter;
/// Creates a module with the current Deno version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("deno");
let config = DenoConfig::try_load(module.config);
let is_deno_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_deno_project {
return None;
}
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,
})
.map(|variable| match variable {
"version" => {
let deno_version =
parse_deno_version(&context.exec_cmd("deno", &["-V"])?.stdout)?;
VersionFormatter::format_module_version(
module.get_name(),
&deno_version,
config.version_format,
)
.map(Ok)
}
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `deno`:\n{error}");
return None;
}
});
Some(module)
}
fn parse_deno_version(deno_version: &str) -> Option<String> {
Some(
deno_version
// split into ["deno", "1.8.3"]
.split_whitespace()
// return "1.8.3"
.nth(1)?
.to_string(),
)
}
#[cfg(test)]
mod tests {
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
use std::fs::File;
use std::io;
#[test]
fn folder_without_deno_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("deno").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_deno_json() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("deno.json"))?.sync_all()?;
let actual = ModuleRenderer::new("deno").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Green.bold().paint("🦕 v1.8.3 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_deno_jsonc() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("deno.jsonc"))?.sync_all()?;
let actual = ModuleRenderer::new("deno").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Green.bold().paint("🦕 v1.8.3 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_deno_lock() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("deno.lock"))?.sync_all()?;
let actual = ModuleRenderer::new("deno").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Green.bold().paint("🦕 v1.8.3 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_mod_ts() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("mod.ts"))?.sync_all()?;
let actual = ModuleRenderer::new("deno").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Green.bold().paint("🦕 v1.8.3 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_mod_js() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("mod.js"))?.sync_all()?;
let actual = ModuleRenderer::new("deno").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Green.bold().paint("🦕 v1.8.3 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_deps_ts() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("deps.ts"))?.sync_all()?;
let actual = ModuleRenderer::new("deno").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Green.bold().paint("🦕 v1.8.3 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_deps_js() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("deps.js"))?.sync_all()?;
let actual = ModuleRenderer::new("deno").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Green.bold().paint("🦕 v1.8.3 ")));
assert_eq!(expected, actual);
dir.close()
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/git_commit.rs | src/modules/git_commit.rs | use super::{Context, Module, ModuleConfig};
use gix::commit::describe::SelectRef::AllTags;
use crate::configs::git_commit::GitCommitConfig;
use crate::context::Repo;
use crate::formatter::StringFormatter;
/// Creates a module with the Git commit in the current directory
///
/// Will display the commit hash if the current directory is a git repo
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("git_commit");
let config: GitCommitConfig = GitCommitConfig::try_load(module.config);
let repo = context.get_repo().ok()?;
let git_repo = repo.open();
let git_head = git_repo.head().ok()?;
let is_detached = git_head.is_detached();
if config.only_detached && !is_detached {
return None;
}
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map(|variable| match variable {
"hash" => Some(Ok(git_hash(context.get_repo().ok()?, &config)?)),
"tag" if !config.tag_disabled => Some(Ok(format!(
"{}{}",
config.tag_symbol,
git_tag(context.get_repo().ok()?, &config)?
))),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `git_commit`:\n{error}");
return None;
}
});
Some(module)
}
fn git_tag(repo: &Repo, config: &GitCommitConfig) -> Option<String> {
let mut git_repo = repo.open();
// Increase the default object cache size to speed up operation for some repos
git_repo.object_cache_size_if_unset(4 * 1024 * 1024);
let head_commit = git_repo.head_commit().ok()?;
let describe_platform = head_commit
.describe()
.names(AllTags)
.max_candidates(config.tag_max_candidates)
.traverse_first_parent(true);
let formatter = describe_platform.try_format().ok()??;
Some(formatter.name?.to_string())
}
fn git_hash(repo: &Repo, config: &GitCommitConfig) -> Option<String> {
let git_repo = repo.open();
let head_id = git_repo.head_id().ok()?;
Some(format!(
"{}",
head_id.to_hex_with_len(config.commit_hash_length)
))
}
#[cfg(test)]
mod tests {
use nu_ansi_term::Color;
use std::{io, str};
use crate::test::{FixtureProvider, ModuleRenderer, fixture_repo};
use crate::utils::create_command;
#[test]
fn show_nothing_on_empty_dir() -> io::Result<()> {
let repo_dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("git_commit")
.path(repo_dir.path())
.collect();
let expected = None;
assert_eq!(expected, actual);
repo_dir.close()
}
#[test]
fn test_render_commit_hash() -> io::Result<()> {
let repo_dir = fixture_repo(FixtureProvider::Git)?;
let mut git_output = create_command("git")?
.args(["rev-parse", "HEAD"])
.current_dir(repo_dir.path())
.output()?
.stdout;
git_output.truncate(7);
let expected_hash = str::from_utf8(&git_output).unwrap();
let actual = ModuleRenderer::new("git_commit")
.config(toml::toml! {
[git_commit]
only_detached = false
})
.path(repo_dir.path())
.collect();
let expected = Some(format!(
"{} ",
Color::Green.bold().paint(format!("({expected_hash})"))
));
assert_eq!(expected, actual);
repo_dir.close()
}
#[test]
fn test_render_commit_hash_len_override() -> io::Result<()> {
let repo_dir = fixture_repo(FixtureProvider::Git)?;
let mut git_output = create_command("git")?
.args(["rev-parse", "HEAD"])
.current_dir(repo_dir.path())
.output()?
.stdout;
git_output.truncate(14);
let expected_hash = str::from_utf8(&git_output).unwrap();
let actual = ModuleRenderer::new("git_commit")
.config(toml::toml! {
[git_commit]
only_detached = false
commit_hash_length = 14
})
.path(repo_dir.path())
.collect();
let expected = Some(format!(
"{} ",
Color::Green.bold().paint(format!("({expected_hash})"))
));
assert_eq!(expected, actual);
repo_dir.close()
}
#[test]
fn test_render_commit_hash_only_detached_on_branch() -> io::Result<()> {
let repo_dir = fixture_repo(FixtureProvider::Git)?;
let actual = ModuleRenderer::new("git_commit")
.path(repo_dir.path())
.collect();
let expected = None;
assert_eq!(expected, actual);
repo_dir.close()
}
#[test]
fn test_render_commit_hash_only_detached_on_detached() -> io::Result<()> {
let repo_dir = fixture_repo(FixtureProvider::Git)?;
create_command("git")?
.args(["checkout", "@~1"])
.current_dir(repo_dir.path())
.output()?;
let mut git_output = create_command("git")?
.args(["rev-parse", "HEAD"])
.current_dir(repo_dir.path())
.output()?
.stdout;
git_output.truncate(7);
let expected_hash = str::from_utf8(&git_output).unwrap();
let actual = ModuleRenderer::new("git_commit")
.path(repo_dir.path())
.collect();
let expected = Some(format!(
"{} ",
Color::Green.bold().paint(format!("({expected_hash})"))
));
assert_eq!(expected, actual);
repo_dir.close()
}
#[test]
fn test_render_commit_hash_with_tag_disabled() -> io::Result<()> {
let repo_dir = fixture_repo(FixtureProvider::Git)?;
create_command("git")?
.args(["tag", "v1", "-m", "Testing tags"])
.current_dir(repo_dir.path())
.output()?;
let mut git_commit = create_command("git")?
.args(["rev-parse", "HEAD"])
.current_dir(repo_dir.path())
.output()?
.stdout;
git_commit.truncate(7);
let commit_output = str::from_utf8(&git_commit).unwrap().trim();
let actual = ModuleRenderer::new("git_commit")
.config(toml::toml! {
[git_commit]
only_detached = false
})
.path(repo_dir.path())
.collect();
let expected = Some(format!(
"{} ",
Color::Green
.bold()
.paint(format!("({})", commit_output.trim()))
));
assert_eq!(expected, actual);
Ok(())
}
#[test]
fn test_render_commit_hash_with_tag_enabled() -> io::Result<()> {
let repo_dir = fixture_repo(FixtureProvider::Git)?;
create_command("git")?
.args(["tag", "v1", "-m", "Testing tags"])
.current_dir(repo_dir.path())
.output()?;
let mut git_commit = create_command("git")?
.args(["rev-parse", "HEAD"])
.current_dir(repo_dir.path())
.output()?
.stdout;
git_commit.truncate(7);
let commit_output = str::from_utf8(&git_commit).unwrap().trim();
let git_tag = create_command("git")?
.args(["describe", "--tags", "--exact-match", "HEAD"])
.current_dir(repo_dir.path())
.output()?
.stdout;
let tag_output = str::from_utf8(&git_tag).unwrap().trim();
let expected_output = format!("{commit_output} {tag_output}");
let actual = ModuleRenderer::new("git_commit")
.config(toml::toml! {
[git_commit]
only_detached = false
tag_disabled = false
tag_symbol = " "
})
.path(repo_dir.path())
.collect();
let expected = Some(format!(
"{} ",
Color::Green
.bold()
.paint(format!("({})", expected_output.trim()))
));
assert_eq!(expected, actual);
Ok(())
}
#[test]
fn test_render_commit_hash_only_detached_on_detached_with_tag_enabled() -> io::Result<()> {
let repo_dir = fixture_repo(FixtureProvider::Git)?;
create_command("git")?
.args(["checkout", "@~1"])
.current_dir(repo_dir.path())
.output()?;
create_command("git")?
.args(["tag", "tagOnDetached", "-m", "Testing tags on detached"])
.current_dir(repo_dir.path())
.output()?;
let mut git_commit = create_command("git")?
.args(["rev-parse", "HEAD"])
.current_dir(repo_dir.path())
.output()?
.stdout;
git_commit.truncate(7);
let commit_output = str::from_utf8(&git_commit).unwrap().trim();
let git_tag = create_command("git")?
.args(["describe", "--tags", "--exact-match", "HEAD"])
.current_dir(repo_dir.path())
.output()?
.stdout;
let tag_output = str::from_utf8(&git_tag).unwrap().trim();
let expected_output = format!("{commit_output} {tag_output}");
let actual = ModuleRenderer::new("git_commit")
.config(toml::toml! {
[git_commit]
tag_disabled = false
tag_symbol = " "
})
.path(repo_dir.path())
.collect();
let expected = Some(format!(
"{} ",
Color::Green
.bold()
.paint(format!("({})", expected_output.trim()))
));
assert_eq!(expected, actual);
Ok(())
}
#[test]
fn test_latest_tag_shown_with_tag_enabled() -> io::Result<()> {
let repo_dir = fixture_repo(FixtureProvider::Git)?;
let mut git_commit = create_command("git")?
.args(["rev-parse", "HEAD"])
.current_dir(repo_dir.path())
.output()?
.stdout;
git_commit.truncate(7);
let commit_output = str::from_utf8(&git_commit).unwrap().trim();
create_command("git")?
.args(["tag", "--no-sign", "v2", "-m", "Testing tags v2"])
.env("GIT_COMMITTER_DATE", "2022-01-01 00:00:00 +0000")
.current_dir(repo_dir.path())
.output()?;
create_command("git")?
.args(["tag", "--no-sign", "v0", "-m", "Testing tags v0", "HEAD~1"])
.env("GIT_COMMITTER_DATE", "2022-01-01 00:00:01 +0000")
.current_dir(repo_dir.path())
.output()?;
create_command("git")?
.args(["tag", "--no-sign", "v1", "-m", "Testing tags v1"])
.env("GIT_COMMITTER_DATE", "2022-01-01 00:00:01 +0000")
.current_dir(repo_dir.path())
.output()?;
// Annotated tags are preferred over lightweight tags
create_command("git")?
.args(["tag", "--no-sign", "l0"])
.env("GIT_COMMITTER_DATE", "2022-01-01 00:00:02 +0000")
.current_dir(repo_dir.path())
.output()?;
let git_tag = create_command("git")?
.args(["describe", "--tags"])
.current_dir(repo_dir.path())
.output()?
.stdout;
let tag_output = str::from_utf8(&git_tag).unwrap().trim();
let expected_output = format!("{commit_output} {tag_output}");
let actual = ModuleRenderer::new("git_commit")
.config(toml::toml! {
[git_commit]
only_detached = false
tag_disabled = false
tag_symbol = " "
})
.path(repo_dir.path())
.collect();
let expected = Some(format!(
"{} ",
Color::Green
.bold()
.paint(format!("({})", expected_output.trim()))
));
assert_eq!(expected, actual);
Ok(())
}
#[test]
fn test_latest_tag_shown_with_tag_enabled_lightweight() -> io::Result<()> {
let repo_dir = fixture_repo(FixtureProvider::Git)?;
let mut git_commit = create_command("git")?
.args(["rev-parse", "HEAD"])
.current_dir(repo_dir.path())
.output()?
.stdout;
git_commit.truncate(7);
let commit_output = str::from_utf8(&git_commit).unwrap().trim();
// Lightweight tags are chosen lexicographically
create_command("git")?
.args(["tag", "--no-sign", "v1"])
.env("GIT_COMMITTER_DATE", "2022-01-01 00:00:00 +0000")
.current_dir(repo_dir.path())
.output()?;
create_command("git")?
.args(["tag", "--no-sign", "v0", "HEAD~1"])
.env("GIT_COMMITTER_DATE", "2022-01-01 00:00:01 +0000")
.current_dir(repo_dir.path())
.output()?;
create_command("git")?
.args(["tag", "--no-sign", "v2"])
.env("GIT_COMMITTER_DATE", "2022-01-01 00:00:01 +0000")
.current_dir(repo_dir.path())
.output()?;
let git_tag = create_command("git")?
.args(["describe", "--tags"])
.current_dir(repo_dir.path())
.output()?
.stdout;
let tag_output = str::from_utf8(&git_tag).unwrap().trim();
let expected_output = format!("{commit_output} {tag_output}");
let actual = ModuleRenderer::new("git_commit")
.config(toml::toml! {
[git_commit]
only_detached = false
tag_disabled = false
tag_symbol = " "
})
.path(repo_dir.path())
.collect();
let expected = Some(format!(
"{} ",
Color::Green
.bold()
.paint(format!("({})", expected_output.trim()))
));
assert_eq!(expected, actual);
Ok(())
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/shell.rs | src/modules/shell.rs | use super::{Context, Module, ModuleConfig, Shell};
use crate::configs::shell::ShellConfig;
use crate::formatter::StringFormatter;
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("shell");
let config: ShellConfig = ShellConfig::try_load(module.config);
if config.disabled {
return None;
}
let shell = &context.shell;
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|variable, _| match variable {
"indicator" => match shell {
Shell::Bash => Some(config.bash_indicator),
Shell::Fish => Some(config.fish_indicator),
Shell::Zsh => Some(config.zsh_indicator),
Shell::Pwsh => config.pwsh_indicator.or(Some(config.powershell_indicator)),
Shell::PowerShell => Some(config.powershell_indicator),
Shell::Ion => Some(config.ion_indicator),
Shell::Elvish => Some(config.elvish_indicator),
Shell::Tcsh => Some(config.tcsh_indicator),
Shell::Nu => Some(config.nu_indicator),
Shell::Xonsh => Some(config.xonsh_indicator),
Shell::Cmd => Some(config.cmd_indicator),
Shell::Unknown => Some(config.unknown_indicator),
},
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map(|var| match var {
"bash_indicator" => Some(Ok(config.bash_indicator)),
"fish_indicator" => Some(Ok(config.fish_indicator)),
"zsh_indicator" => Some(Ok(config.zsh_indicator)),
"powershell_indicator" => Some(Ok(config.powershell_indicator)),
"pwsh_indicator" => config.pwsh_indicator.map(Ok),
"ion_indicator" => Some(Ok(config.ion_indicator)),
"elvish_indicator" => Some(Ok(config.elvish_indicator)),
"tcsh_indicator" => Some(Ok(config.tcsh_indicator)),
"xonsh_indicator" => Some(Ok(config.xonsh_indicator)),
"cmd_indicator" => Some(Ok(config.cmd_indicator)),
"unknown_indicator" => Some(Ok(config.unknown_indicator)),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `shell`: \n{error}");
return None;
}
});
Some(module)
}
#[cfg(test)]
mod tests {
use crate::context::Shell;
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
#[test]
fn test_none_if_disabled() {
let expected = None;
let actual = ModuleRenderer::new("shell").shell(Shell::Bash).collect();
assert_eq!(expected, actual);
}
#[test]
fn test_none_if_unknown_shell() {
let expected = None;
let actual = ModuleRenderer::new("shell").shell(Shell::Unknown).collect();
assert_eq!(expected, actual);
}
#[test]
fn test_bash_default_format() {
let expected = Some(format!("{} ", Color::White.bold().paint("bsh")));
let actual = ModuleRenderer::new("shell")
.shell(Shell::Bash)
.config(toml::toml! {
[shell]
disabled = false
})
.collect();
assert_eq!(expected, actual);
}
#[test]
fn test_bash_custom_format() {
let expected = Some(format!("{} ", Color::Cyan.bold().paint("bash")));
let actual = ModuleRenderer::new("shell")
.shell(Shell::Bash)
.config(toml::toml! {
[shell]
bash_indicator = "[bash](bold cyan)"
disabled = false
})
.collect();
assert_eq!(expected, actual);
}
#[test]
fn test_fish_default_format() {
let expected = Some(format!("{} ", Color::White.bold().paint("fsh")));
let actual = ModuleRenderer::new("shell")
.shell(Shell::Fish)
.config(toml::toml! {
[shell]
disabled = false
})
.collect();
assert_eq!(expected, actual);
}
#[test]
fn test_fish_custom_format() {
let expected = Some(format!("{} ", Color::Cyan.bold().paint("fish")));
let actual = ModuleRenderer::new("shell")
.shell(Shell::Fish)
.config(toml::toml! {
[shell]
fish_indicator = "[fish](cyan bold)"
disabled = false
})
.collect();
assert_eq!(expected, actual);
}
#[test]
fn test_zsh_default_format() {
let expected = Some(format!("{} ", Color::White.bold().paint("zsh")));
let actual = ModuleRenderer::new("shell")
.shell(Shell::Zsh)
.config(toml::toml! {
[shell]
disabled = false
})
.collect();
assert_eq!(expected, actual);
}
#[test]
fn test_zsh_custom_format() {
let expected = Some(format!("{} ", Color::Cyan.bold().paint("zsh")));
let actual = ModuleRenderer::new("shell")
.shell(Shell::Bash)
.config(toml::toml! {
[shell]
bash_indicator = "[zsh](bold cyan)"
disabled = false
})
.collect();
assert_eq!(expected, actual);
}
#[test]
fn test_powershell_default_format() {
let expected = Some(format!("{} ", Color::White.bold().paint("psh")));
let actual = ModuleRenderer::new("shell")
.shell(Shell::PowerShell)
.config(toml::toml! {
[shell]
disabled = false
})
.collect();
assert_eq!(expected, actual);
}
#[test]
fn test_powershell_custom_format() {
let expected = Some(format!("{} ", Color::Cyan.bold().paint("powershell")));
let actual = ModuleRenderer::new("shell")
.shell(Shell::PowerShell)
.config(toml::toml! {
[shell]
powershell_indicator = "[powershell](bold cyan)"
disabled = false
})
.collect();
assert_eq!(expected, actual);
}
#[test]
fn test_pwsh_default_format() {
let expected = Some(format!("{} ", Color::White.bold().paint("psh")));
let actual = ModuleRenderer::new("shell")
.shell(Shell::Pwsh)
.config(toml::toml! {
[shell]
disabled = false
})
.collect();
assert_eq!(expected, actual);
}
#[test]
fn test_pwsh_custom_format() {
let expected = Some(format!("{} ", Color::Cyan.bold().paint("pwsh")));
let actual = ModuleRenderer::new("shell")
.shell(Shell::Pwsh)
.config(toml::toml! {
[shell]
pwsh_indicator = "[pwsh](bold cyan)"
disabled = false
})
.collect();
assert_eq!(expected, actual);
}
#[test]
fn test_pwsh_custom_format_fallback() {
let expected = Some(format!("{} ", Color::Cyan.bold().paint("pwsh")));
let actual = ModuleRenderer::new("shell")
.shell(Shell::Pwsh)
.config(toml::toml! {
[shell]
powershell_indicator = "[pwsh](bold cyan)"
disabled = false
})
.collect();
assert_eq!(expected, actual);
}
#[test]
fn test_ion_default_format() {
let expected = Some(format!("{} ", Color::White.bold().paint("ion")));
let actual = ModuleRenderer::new("shell")
.shell(Shell::Ion)
.config(toml::toml! {
[shell]
disabled = false
})
.collect();
assert_eq!(expected, actual);
}
#[test]
fn test_ion_custom_format() {
let expected = Some(format!("{} ", Color::Cyan.bold().paint("ion")));
let actual = ModuleRenderer::new("shell")
.shell(Shell::Ion)
.config(toml::toml! {
[shell]
ion_indicator = "[ion](bold cyan)"
disabled = false
})
.collect();
assert_eq!(expected, actual);
}
#[test]
fn test_elvish_default_format() {
let expected = Some(format!("{} ", Color::White.bold().paint("esh")));
let actual = ModuleRenderer::new("shell")
.shell(Shell::Elvish)
.config(toml::toml! {
[shell]
disabled = false
})
.collect();
assert_eq!(expected, actual);
}
#[test]
fn test_elvish_custom_format() {
let expected = Some(format!("{} ", Color::Cyan.bold().paint("elvish")));
let actual = ModuleRenderer::new("shell")
.shell(Shell::Elvish)
.config(toml::toml! {
[shell]
elvish_indicator = "[elvish](bold cyan)"
disabled = false
})
.collect();
assert_eq!(expected, actual);
}
#[test]
fn test_nu_default_format() {
let expected = Some(format!("{} ", Color::White.bold().paint("nu")));
let actual = ModuleRenderer::new("shell")
.shell(Shell::Nu)
.config(toml::toml! {
[shell]
disabled = false
})
.collect();
assert_eq!(expected, actual);
}
#[test]
fn test_nu_custom_format() {
let expected = Some(format!("{} ", Color::Cyan.bold().paint("nu")));
let actual = ModuleRenderer::new("shell")
.shell(Shell::Nu)
.config(toml::toml! {
[shell]
nu_indicator = "[nu](bold cyan)"
disabled = false
})
.collect();
assert_eq!(expected, actual);
}
#[test]
fn test_xonsh_default_format() {
let expected = Some(format!("{} ", Color::White.bold().paint("xsh")));
let actual = ModuleRenderer::new("shell")
.shell(Shell::Xonsh)
.config(toml::toml! {
[shell]
disabled = false
})
.collect();
assert_eq!(expected, actual);
}
#[test]
fn test_xonsh_custom_format() {
let expected = Some(format!("{} ", Color::Cyan.bold().paint("xonsh")));
let actual = ModuleRenderer::new("shell")
.shell(Shell::Xonsh)
.config(toml::toml! {
[shell]
xonsh_indicator = "[xonsh](bold cyan)"
disabled = false
})
.collect();
assert_eq!(expected, actual);
}
#[test]
fn test_cmd_default_format() {
let expected = Some(format!("{} ", Color::White.bold().paint("cmd")));
let actual = ModuleRenderer::new("shell")
.shell(Shell::Cmd)
.config(toml::toml! {
[shell]
disabled = false
})
.collect();
assert_eq!(expected, actual);
}
#[test]
fn test_cmd_custom_format() {
let expected = Some(format!("{} ", Color::Cyan.bold().paint("cmd")));
let actual = ModuleRenderer::new("shell")
.shell(Shell::Cmd)
.config(toml::toml! {
[shell]
cmd_indicator = "[cmd](bold cyan)"
disabled = false
})
.collect();
assert_eq!(expected, actual);
}
#[test]
fn test_custom_format_conditional_indicator_match() {
let expected = Some(format!("{} ", "B"));
let actual = ModuleRenderer::new("shell")
.shell(Shell::Bash)
.config(toml::toml! {
[shell]
bash_indicator = "B"
format = "($bash_indicator )"
disabled = false
})
.collect();
assert_eq!(expected, actual);
}
// Known issue #3409,
// #[test]
// fn test_custom_format_conditional_indicator_no_match() {
// let expected = None;
// let actual = ModuleRenderer::new("shell")
// .shell(Shell::Fish)
// .config(toml::toml! {
// [shell]
// fish_indicator = ""
// format = "($indicator )"
// disabled = false
// })
// .collect();
// assert_eq!(expected, actual);
// }
#[test]
fn test_default_style() {
let expected = Some(format!("{}", Color::White.bold().paint("fish")));
let actual = ModuleRenderer::new("shell")
.shell(Shell::Fish)
.config(toml::toml! {
[shell]
format = "[fish]($style)"
disabled = false
})
.collect();
assert_eq!(expected, actual);
}
#[test]
fn test_custom_style() {
let expected = Some(format!("{}", Color::Cyan.bold().paint("fish")));
let actual = ModuleRenderer::new("shell")
.shell(Shell::Fish)
.config(toml::toml! {
[shell]
format = "[fish]($style)"
style = "cyan bold"
disabled = false
})
.collect();
assert_eq!(expected, actual);
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/python.rs | src/modules/python.rs | use ini::Ini;
use std::path::Path;
use super::{Context, Module, ModuleConfig};
use crate::configs::python::PythonConfig;
use crate::formatter::StringFormatter;
use crate::formatter::VersionFormatter;
use crate::utils::get_command_string_output;
/// Creates a module with the current Python version and, if active, virtual environment.
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("python");
let config: PythonConfig = PythonConfig::try_load(module.config);
let is_py_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
let has_env_vars =
!config.detect_env_vars.is_empty() && context.detect_env_vars(&config.detect_env_vars);
if !is_py_project && !has_env_vars {
return None;
}
let pyenv_prefix = if config.pyenv_version_name {
config.pyenv_prefix
} else {
""
};
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,
})
.map(|variable| match variable {
"version" => {
if config.pyenv_version_name {
return get_pyenv_version(context).map(Ok);
}
let python_version = get_python_version(context, &config)?;
VersionFormatter::format_module_version(
module.get_name(),
&python_version,
config.version_format,
)
.map(Ok)
}
"virtualenv" => {
let virtual_env = get_python_virtual_env(context);
virtual_env.as_ref().map(|e| Ok(e.trim().to_string()))
}
"pyenv_prefix" => Some(Ok(pyenv_prefix.to_string())),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `python`:\n{error}");
return None;
}
});
Some(module)
}
fn get_pyenv_version(context: &Context) -> Option<String> {
let mut version_name = context.get_env("PYENV_VERSION");
if version_name.is_none() {
version_name = Some(
context
.exec_cmd("pyenv", &["version-name"])?
.stdout
.trim()
.to_string(),
);
}
version_name
}
fn get_python_version(context: &Context, config: &PythonConfig) -> Option<String> {
config
.python_binary
.0
.iter()
.find_map(|binary| {
let command = binary.0.first()?;
let args: Vec<_> = binary
.0
.iter()
.skip(1)
.copied()
.chain(std::iter::once("--version"))
.collect();
context.exec_cmd(command, &args)
})
.map(get_command_string_output)
.map(|output| parse_python_version(&output))?
}
fn parse_python_version(python_version_string: &str) -> Option<String> {
let version = python_version_string
// split into ["Python", "3.8.6", ...]
.split_whitespace()
// get down to "3.8.6"
.nth(1)?;
Some(version.to_string())
}
fn get_python_virtual_env(context: &Context) -> Option<String> {
context.get_env("VIRTUAL_ENV").and_then(|venv| {
get_prompt_from_venv(Path::new(&venv)).or_else(|| {
Path::new(&venv)
.file_name()
.map(|filename| String::from(filename.to_str().unwrap_or("")))
})
})
}
fn get_prompt_from_venv(venv_path: &Path) -> Option<String> {
Ini::load_from_file_noescape(venv_path.join("pyvenv.cfg"))
.ok()?
.general_section()
.get("prompt")
.map(|prompt| String::from(prompt.trim_matches(&['(', ')'] as &[_])))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
use std::fs::{File, create_dir_all};
use std::io;
use std::io::Write;
#[test]
fn test_parse_python_version() {
assert_eq!(
parse_python_version("Python 3.7.2"),
Some("3.7.2".to_string())
);
}
#[test]
fn test_parse_python_version_is_malformed() {
assert_eq!(parse_python_version("Python 3.7"), Some("3.7".to_string()));
}
#[test]
fn test_parse_python_version_anaconda() {
assert_eq!(
parse_python_version("Python 3.6.10 :: Anaconda, Inc.",),
Some("3.6.10".to_string())
);
}
#[test]
fn test_parse_python_version_pypy() {
assert_eq!(
parse_python_version(
"\
Python 3.7.9 (7e6e2bb30ac5fbdbd443619cae28c51d5c162a02, Nov 24 2020, 10:03:59)
[PyPy 7.3.3-beta0 with GCC 10.2.0]",
),
Some("3.7.9".to_string())
);
}
#[test]
fn folder_without_python_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("python").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_python_version() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join(".python-version"))?.sync_all()?;
check_python2_renders(&dir, None);
check_python3_renders(&dir, None);
check_pyenv_renders(&dir, None);
check_multiple_binaries_renders(&dir, None);
dir.close()
}
#[test]
fn folder_with_requirements_txt() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("requirements.txt"))?.sync_all()?;
check_python2_renders(&dir, None);
check_python3_renders(&dir, None);
check_pyenv_renders(&dir, None);
check_multiple_binaries_renders(&dir, None);
dir.close()
}
#[test]
fn folder_with_pyproject_toml() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("pyproject.toml"))?.sync_all()?;
check_python2_renders(&dir, None);
check_python3_renders(&dir, None);
check_pyenv_renders(&dir, None);
check_multiple_binaries_renders(&dir, None);
dir.close()
}
#[test]
fn folder_with_pipfile() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("Pipfile"))?.sync_all()?;
check_python2_renders(&dir, None);
check_python3_renders(&dir, None);
check_pyenv_renders(&dir, None);
check_multiple_binaries_renders(&dir, None);
dir.close()
}
#[test]
fn folder_with_tox() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("tox.ini"))?.sync_all()?;
check_python2_renders(&dir, None);
check_python3_renders(&dir, None);
check_pyenv_renders(&dir, None);
check_multiple_binaries_renders(&dir, None);
dir.close()
}
#[test]
fn folder_with_setup_py() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("setup.py"))?.sync_all()?;
check_python2_renders(&dir, None);
check_python3_renders(&dir, None);
check_pyenv_renders(&dir, None);
check_multiple_binaries_renders(&dir, None);
dir.close()
}
#[test]
fn folder_with_init_py() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("__init__.py"))?.sync_all()?;
check_python2_renders(&dir, None);
check_python3_renders(&dir, None);
check_pyenv_renders(&dir, None);
check_multiple_binaries_renders(&dir, None);
dir.close()
}
#[test]
fn folder_with_py_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("main.py"))?.sync_all()?;
check_python2_renders(&dir, None);
check_python3_renders(&dir, None);
check_pyenv_renders(&dir, None);
check_multiple_binaries_renders(&dir, None);
dir.close()
}
#[test]
fn folder_with_ipynb_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("notebook.ipynb"))?.sync_all()?;
check_python2_renders(&dir, None);
check_python3_renders(&dir, None);
check_pyenv_renders(&dir, None);
check_multiple_binaries_renders(&dir, None);
dir.close()
}
#[test]
fn disabled_scan_for_pyfiles_and_folder_with_ignored_py_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("foo.py"))?.sync_all()?;
let expected = None;
let config = toml::toml! {
[python]
detect_extensions = []
};
let actual = ModuleRenderer::new("python")
.path(dir.path())
.config(config)
.collect();
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn disabled_scan_for_pyfiles_and_folder_with_setup_py() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("setup.py"))?.sync_all()?;
let config = toml::toml! {
[python]
python_binary = "python2"
detect_extensions = []
};
check_python2_renders(&dir, Some(config));
let config_python3 = toml::toml! {
[python]
python_binary = "python3"
detect_extensions = []
};
check_python3_renders(&dir, Some(config_python3));
let config_pyenv = toml::toml! {
[python]
pyenv_version_name = true
pyenv_prefix = "test_pyenv "
detect_extensions = []
};
check_pyenv_renders(&dir, Some(config_pyenv));
let config_multi = toml::toml! {
[python]
python_binary = ["python", "python3"]
detect_extensions = []
};
check_multiple_binaries_renders(&dir, Some(config_multi));
dir.close()
}
#[test]
fn with_virtual_env() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("main.py"))?.sync_all()?;
let actual = ModuleRenderer::new("python")
.path(dir.path())
.env("VIRTUAL_ENV", "/foo/bar/my_venv")
.collect();
let expected = Some(format!(
"via {}",
Color::Yellow.bold().paint("🐍 v3.8.0 (my_venv) ")
));
assert_eq!(actual, expected);
dir.close()
}
#[test]
fn with_active_venv() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("python")
.path(dir.path())
.env("VIRTUAL_ENV", "/foo/bar/my_venv")
.collect();
let expected = Some(format!(
"via {}",
Color::Yellow.bold().paint("🐍 v3.8.0 (my_venv) ")
));
assert_eq!(actual, expected);
dir.close()
}
#[test]
fn with_different_env_var() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("python")
.path(dir.path())
.env("MY_ENV_VAR", "my_env_var")
.config(toml::toml! {
[python]
detect_env_vars = ["MY_ENV_VAR"]
})
.collect();
let expected = Some(format!("via {}", Color::Yellow.bold().paint("🐍 v3.8.0 ")));
assert_eq!(actual, expected);
dir.close()
}
#[test]
fn with_no_env_var() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("python")
.path(dir.path())
.env("VIRTUAL_ENV", "env_var")
.config(toml::toml! {
[python]
detect_env_vars = []
})
.collect();
assert_eq!(actual, None);
dir.close()
}
#[test]
fn with_active_venv_and_prompt() -> io::Result<()> {
let dir = tempfile::tempdir()?;
create_dir_all(dir.path().join("my_venv"))?;
let mut venv_cfg = File::create(dir.path().join("my_venv").join("pyvenv.cfg"))?;
venv_cfg.write_all(
br"
home = something
prompt = 'foo'
",
)?;
venv_cfg.sync_all()?;
let actual = ModuleRenderer::new("python")
.path(dir.path())
.env("VIRTUAL_ENV", dir.path().join("my_venv").to_str().unwrap())
.collect();
let expected = Some(format!(
"via {}",
Color::Yellow.bold().paint("🐍 v3.8.0 (foo) ")
));
assert_eq!(actual, expected);
dir.close()
}
#[test]
fn with_active_venv_and_dirty_prompt() -> io::Result<()> {
let dir = tempfile::tempdir()?;
create_dir_all(dir.path().join("my_venv"))?;
let mut venv_cfg = File::create(dir.path().join("my_venv").join("pyvenv.cfg"))?;
venv_cfg.write_all(
br"
home = something
prompt = '(foo)'
",
)?;
venv_cfg.sync_all()?;
let actual = ModuleRenderer::new("python")
.path(dir.path())
.env("VIRTUAL_ENV", dir.path().join("my_venv").to_str().unwrap())
.collect();
let expected = Some(format!(
"via {}",
Color::Yellow.bold().paint("🐍 v3.8.0 (foo) ")
));
assert_eq!(actual, expected);
dir.close()
}
#[test]
fn with_active_venv_and_line_break_like_prompt() -> io::Result<()> {
let dir = tempfile::tempdir()?;
create_dir_all(dir.path().join("my_venv"))?;
let mut venv_cfg = File::create(dir.path().join("my_venv").join("pyvenv.cfg"))?;
venv_cfg.write_all(
br"
home = something
prompt = foo\nbar
",
)?;
venv_cfg.sync_all()?;
let actual = ModuleRenderer::new("python")
.path(dir.path())
.env("VIRTUAL_ENV", dir.path().join("my_venv").to_str().unwrap())
.collect();
let expected = Some(format!(
"via {}",
Color::Yellow.bold().paint(r"🐍 v3.8.0 (foo\nbar) ")
));
assert_eq!(actual, expected);
dir.close()
}
fn check_python2_renders(dir: &tempfile::TempDir, starship_config: Option<toml::Table>) {
let config = starship_config.unwrap_or(toml::toml! {
[python]
python_binary = "python2"
});
let actual = ModuleRenderer::new("python")
.path(dir.path())
.config(config)
.collect();
let expected = Some(format!("via {}", Color::Yellow.bold().paint("🐍 v2.7.17 ")));
assert_eq!(expected, actual);
}
fn check_python3_renders(dir: &tempfile::TempDir, starship_config: Option<toml::Table>) {
let config = starship_config.unwrap_or(toml::toml! {
[python]
python_binary = "python3"
});
let actual = ModuleRenderer::new("python")
.path(dir.path())
.config(config)
.collect();
let expected = Some(format!("via {}", Color::Yellow.bold().paint("🐍 v3.8.0 ")));
assert_eq!(expected, actual);
}
fn check_multiple_binaries_renders(
dir: &tempfile::TempDir,
starship_config: Option<toml::Table>,
) {
let config = starship_config.unwrap_or(toml::toml! {
[python]
python_binary = ["python", "python3"]
});
let actual = ModuleRenderer::new("python")
.path(dir.path())
.config(config)
.collect();
let expected = Some(format!("via {}", Color::Yellow.bold().paint("🐍 v3.8.0 ")));
assert_eq!(expected, actual);
}
fn check_pyenv_renders(dir: &tempfile::TempDir, starship_config: Option<toml::Table>) {
let config = starship_config.unwrap_or(toml::toml! {
[python]
pyenv_version_name = true
pyenv_prefix = "test_pyenv "
});
let actual = ModuleRenderer::new("python")
.path(dir.path())
.config(config)
.collect();
let expected = Some(format!(
"via {}",
Color::Yellow.bold().paint("🐍 test_pyenv system ")
));
assert_eq!(expected, actual);
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/pijul_channel.rs | src/modules/pijul_channel.rs | use super::utils::truncate::truncate_text;
use super::{Context, Module, ModuleConfig};
use crate::configs::pijul_channel::PijulConfig;
use crate::formatter::StringFormatter;
/// Creates a module with the Pijul channel in the current directory
///
/// Will display the channel lame if the current directory is a pijul repo
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let is_repo = context
.try_begin_scan()?
.set_folders(&[".pijul"])
.is_match();
if !is_repo {
return None;
}
let mut module = context.new_module("pijul_channel");
let config: PijulConfig = PijulConfig::try_load(module.config);
// We default to disabled=true, so we have to check after loading our config module.
if config.disabled {
return None;
}
let channel_name = get_pijul_current_channel(context)?;
let truncated_text = truncate_text(
&channel_name,
config.truncation_length as usize,
config.truncation_symbol,
);
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|variable, _| match variable {
"symbol" => Some(config.symbol),
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map(|variable| match variable {
"channel" => Some(Ok(&truncated_text)),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `pijul_channel`:\n{error}");
return None;
}
});
Some(module)
}
fn get_pijul_current_channel(ctx: &Context) -> Option<String> {
let output = ctx.exec_cmd("pijul", &["channel"])?.stdout;
output
.lines()
.find_map(|l| l.strip_prefix("* "))
.map(str::to_owned)
}
#[cfg(test)]
mod tests {
use nu_ansi_term::{Color, Style};
use std::io;
use std::path::Path;
use crate::test::{FixtureProvider, ModuleRenderer, fixture_repo};
enum Expect<'a> {
ChannelName(&'a str),
Empty,
NoTruncation,
Symbol(&'a str),
Style(Style),
TruncationSymbol(&'a str),
}
#[test]
fn show_nothing_on_empty_dir() -> io::Result<()> {
let repo_dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("pijul_channel")
.path(repo_dir.path())
.collect();
let expected = None;
assert_eq!(expected, actual);
repo_dir.close()
}
#[test]
fn test_pijul_disabled_per_default() -> io::Result<()> {
let tempdir = fixture_repo(FixtureProvider::Pijul)?;
let repo_dir = tempdir.path();
expect_pijul_with_config(
repo_dir,
Some(toml::toml! {
[pijul_channel]
truncation_length = 14
}),
&[Expect::Empty],
);
tempdir.close()
}
#[test]
fn test_pijul_autodisabled() -> io::Result<()> {
let tempdir = tempfile::tempdir()?;
expect_pijul_with_config(tempdir.path(), None, &[Expect::Empty]);
tempdir.close()
}
#[test]
fn test_pijul_channel() -> io::Result<()> {
let tempdir = fixture_repo(FixtureProvider::Pijul)?;
let repo_dir = tempdir.path();
run_pijul(&["channel", "new", "tributary-48198"], repo_dir)?;
run_pijul(&["channel", "switch", "tributary-48198"], repo_dir)?;
expect_pijul_with_config(
repo_dir,
None,
&[Expect::ChannelName("tributary-48198"), Expect::NoTruncation],
);
tempdir.close()
}
#[test]
fn test_pijul_configured() -> io::Result<()> {
let tempdir = fixture_repo(FixtureProvider::Pijul)?;
let repo_dir = tempdir.path();
run_pijul(&["channel", "new", "tributary-48198"], repo_dir)?;
run_pijul(&["channel", "switch", "tributary-48198"], repo_dir)?;
expect_pijul_with_config(
repo_dir,
Some(toml::toml! {
[pijul_channel]
style = "underline blue"
symbol = "P "
truncation_length = 14
truncation_symbol = "%"
disabled = false
}),
&[
Expect::ChannelName("tributary-4819"),
Expect::Style(Color::Blue.underline()),
Expect::Symbol("P"),
Expect::TruncationSymbol("%"),
],
);
tempdir.close()
}
fn expect_pijul_with_config(
repo_dir: &Path,
config: Option<toml::Table>,
expectations: &[Expect],
) {
let actual = ModuleRenderer::new("pijul_channel")
.path(repo_dir.to_str().unwrap())
.config(config.unwrap_or_else(|| {
toml::toml! {
[pijul_channel]
disabled = false
}
}))
.collect();
let mut expect_channel_name = "main";
let mut expect_style = Color::Purple.bold();
let mut expect_symbol = "\u{e0a0}";
let mut expect_truncation_symbol = "…";
for expect in expectations {
match expect {
Expect::Empty => {
assert_eq!(None, actual);
return;
}
Expect::Symbol(symbol) => {
expect_symbol = symbol;
}
Expect::TruncationSymbol(truncation_symbol) => {
expect_truncation_symbol = truncation_symbol;
}
Expect::NoTruncation => {
expect_truncation_symbol = "";
}
Expect::ChannelName(channel_name) => {
expect_channel_name = channel_name;
}
Expect::Style(style) => expect_style = *style,
}
}
let expected = Some(format!(
"on {} ",
expect_style.paint(format!(
"{expect_symbol} {expect_channel_name}{expect_truncation_symbol}"
)),
));
assert_eq!(expected, actual);
}
fn run_pijul(args: &[&str], _repo_dir: &Path) -> io::Result<()> {
crate::utils::mock_cmd("pijul", args).ok_or(io::ErrorKind::Unsupported)?;
Ok(())
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/spack.rs | src/modules/spack.rs | use super::{Context, Module, ModuleConfig};
use super::utils::directory::truncate;
use crate::configs::spack::SpackConfig;
use crate::formatter::StringFormatter;
/// Creates a module with the current Spack environment
///
/// Will display the Spack environment if `$SPACK_ENV` is set.
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let spack_env = context.get_env("SPACK_ENV").unwrap_or_default();
if spack_env.trim().is_empty() {
return None;
}
let mut module = context.new_module("spack");
let config: SpackConfig = SpackConfig::try_load(module.config);
let spack_env = truncate(&spack_env, config.truncation_length).unwrap_or(spack_env);
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|variable, _| match variable {
"symbol" => Some(config.symbol),
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map(|variable| match variable {
"environment" => Some(Ok(spack_env.as_str())),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `spack`:\n{error}");
return None;
}
});
Some(module)
}
#[cfg(test)]
mod tests {
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
#[test]
fn not_in_env() {
let actual = ModuleRenderer::new("spack").collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn env_set() {
let actual = ModuleRenderer::new("spack")
.env("SPACK_ENV", "astronauts")
.collect();
let expected = Some(format!("via {} ", Color::Blue.bold().paint("🅢 astronauts")));
assert_eq!(expected, actual);
}
#[test]
fn truncate() {
let actual = ModuleRenderer::new("spack")
.env("SPACK_ENV", "/some/really/long/and/really/annoying/path/that/shouldnt/be/displayed/fully/spack/my_env")
.collect();
let expected = Some(format!("via {} ", Color::Blue.bold().paint("🅢 my_env")));
assert_eq!(expected, actual);
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/ocaml.rs | src/modules/ocaml.rs | use super::{Context, Module, ModuleConfig};
use std::ops::Deref;
use std::path::Path;
use std::sync::LazyLock;
use crate::configs::ocaml::OCamlConfig;
use crate::formatter::StringFormatter;
use crate::formatter::VersionFormatter;
#[derive(Debug, PartialEq)]
enum SwitchType {
Global,
Local,
}
type OpamSwitch = (SwitchType, String);
/// Creates a module with the current OCaml version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("ocaml");
let config: OCamlConfig = OCamlConfig::try_load(module.config);
let is_ocaml_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_folders(&config.detect_folders)
.set_extensions(&config.detect_extensions)
.is_match();
if !is_ocaml_project {
return None;
}
let opam_switch: LazyLock<Option<OpamSwitch>, _> = LazyLock::new(|| get_opam_switch(context));
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|variable, _| match variable {
"symbol" => Some(config.symbol),
"switch_indicator" => {
let (switch_type, _) = &opam_switch.deref().as_ref()?;
match switch_type {
SwitchType::Global => Some(config.global_switch_indicator),
SwitchType::Local => Some(config.local_switch_indicator),
}
}
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map(|variable| match variable {
"switch_name" => {
let (_, name) = opam_switch.deref().as_ref()?;
Some(Ok(name.to_string()))
}
"version" => {
let is_esy_project = context
.try_begin_scan()?
.set_folders(&["esy.lock"])
.is_match();
let ocaml_version = if is_esy_project {
context.exec_cmd("esy", &["ocaml", "-vnum"])?.stdout
} else {
context.exec_cmd("ocaml", &["-vnum"])?.stdout
};
VersionFormatter::format_module_version(
module.get_name(),
ocaml_version.trim(),
config.version_format,
)
.map(Ok)
}
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `ocaml`: \n{error}");
return None;
}
});
Some(module)
}
fn get_opam_switch(context: &Context) -> Option<OpamSwitch> {
let opam_switch = context
.exec_cmd("opam", &["switch", "show", "--safe"])?
.stdout;
parse_opam_switch(opam_switch.trim())
}
fn parse_opam_switch(opam_switch: &str) -> Option<OpamSwitch> {
if opam_switch.is_empty() {
return None;
}
let path = Path::new(opam_switch);
if path.has_root() {
Some((SwitchType::Local, path.file_name()?.to_str()?.to_string()))
} else {
Some((SwitchType::Global, opam_switch.to_string()))
}
}
#[cfg(test)]
mod tests {
use super::{SwitchType, parse_opam_switch};
use crate::{test::ModuleRenderer, utils::CommandOutput};
use nu_ansi_term::Color;
use std::fs::{self, File};
use std::io;
#[test]
fn test_parse_opam_switch() {
let global_switch = "ocaml-base-compiler.4.10.0";
let local_switch = "/path/to/my-project";
assert_eq!(
parse_opam_switch(global_switch),
Some((SwitchType::Global, "ocaml-base-compiler.4.10.0".to_string()))
);
assert_eq!(
parse_opam_switch(local_switch),
Some((SwitchType::Local, "my-project".to_string()))
);
}
#[test]
fn folder_without_ocaml_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("ocaml").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_opam_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("any.opam"))?.sync_all()?;
let actual = ModuleRenderer::new("ocaml").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Yellow.bold().paint("🐫 v4.10.0 (default) ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_opam_directory() -> io::Result<()> {
let dir = tempfile::tempdir()?;
fs::create_dir_all(dir.path().join("_opam"))?;
let actual = ModuleRenderer::new("ocaml").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Yellow.bold().paint("🐫 v4.10.0 (default) ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_esy_lock_directory() -> io::Result<()> {
let dir = tempfile::tempdir()?;
fs::create_dir_all(dir.path().join("esy.lock"))?;
File::create(dir.path().join("package.json"))?.sync_all()?;
fs::write(
dir.path().join("package.lock"),
r#"{"dependencies": {"ocaml": "4.8.1000"}}"#,
)?;
let actual = ModuleRenderer::new("ocaml").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Yellow.bold().paint("🐫 v4.08.1 (default) ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_dune() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("dune"))?.sync_all()?;
let actual = ModuleRenderer::new("ocaml").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Yellow.bold().paint("🐫 v4.10.0 (default) ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_dune_project() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("dune-project"))?.sync_all()?;
let actual = ModuleRenderer::new("ocaml").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Yellow.bold().paint("🐫 v4.10.0 (default) ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_jbuild() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("jbuild"))?.sync_all()?;
let actual = ModuleRenderer::new("ocaml").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Yellow.bold().paint("🐫 v4.10.0 (default) ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_jbuild_ignore() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("jbuild-ignore"))?.sync_all()?;
let actual = ModuleRenderer::new("ocaml").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Yellow.bold().paint("🐫 v4.10.0 (default) ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_merlin_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join(".merlin"))?.sync_all()?;
let actual = ModuleRenderer::new("ocaml").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Yellow.bold().paint("🐫 v4.10.0 (default) ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_ml_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("any.ml"))?.sync_all()?;
let actual = ModuleRenderer::new("ocaml").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Yellow.bold().paint("🐫 v4.10.0 (default) ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_mli_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("any.mli"))?.sync_all()?;
let actual = ModuleRenderer::new("ocaml").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Yellow.bold().paint("🐫 v4.10.0 (default) ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_re_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("any.re"))?.sync_all()?;
let actual = ModuleRenderer::new("ocaml").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Yellow.bold().paint("🐫 v4.10.0 (default) ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_rei_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("any.rei"))?.sync_all()?;
let actual = ModuleRenderer::new("ocaml").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Yellow.bold().paint("🐫 v4.10.0 (default) ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn without_opam_switch() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("any.ml"))?.sync_all()?;
let actual = ModuleRenderer::new("ocaml")
.cmd(
"opam switch show --safe",
Some(CommandOutput {
stdout: String::default(),
stderr: String::default(),
}),
)
.path(dir.path())
.collect();
let expected = Some(format!("via {}", Color::Yellow.bold().paint("🐫 v4.10.0 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn with_global_opam_switch() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("any.ml"))?.sync_all()?;
let actual = ModuleRenderer::new("ocaml")
.cmd(
"opam switch show --safe",
Some(CommandOutput {
stdout: String::from("ocaml-base-compiler.4.10.0\n"),
stderr: String::default(),
}),
)
.path(dir.path())
.collect();
let expected = Some(format!(
"via {}",
Color::Yellow
.bold()
.paint("🐫 v4.10.0 (ocaml-base-compiler.4.10.0) ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn with_global_opam_switch_custom_indicator() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("any.ml"))?.sync_all()?;
let actual = ModuleRenderer::new("ocaml")
.config(toml::toml! {
[ocaml]
global_switch_indicator = "g/"
})
.cmd(
"opam switch show --safe",
Some(CommandOutput {
stdout: String::from("ocaml-base-compiler.4.10.0\n"),
stderr: String::default(),
}),
)
.path(dir.path())
.collect();
let expected = Some(format!(
"via {}",
Color::Yellow
.bold()
.paint("🐫 v4.10.0 (g/ocaml-base-compiler.4.10.0) ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn with_local_opam_switch() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("any.ml"))?.sync_all()?;
let actual = ModuleRenderer::new("ocaml")
.cmd(
"opam switch show --safe",
Some(CommandOutput {
stdout: String::from("/path/to/my-project\n"),
stderr: String::default(),
}),
)
.path(dir.path())
.collect();
let expected = Some(format!(
"via {}",
Color::Yellow.bold().paint("🐫 v4.10.0 (*my-project) ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn with_local_opam_switch_custom_indicator() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("any.ml"))?.sync_all()?;
let actual = ModuleRenderer::new("ocaml")
.config(toml::toml! {
[ocaml]
local_switch_indicator = "^"
})
.cmd(
"opam switch show --safe",
Some(CommandOutput {
stdout: String::from("/path/to/my-project\n"),
stderr: String::default(),
}),
)
.path(dir.path())
.collect();
let expected = Some(format!(
"via {}",
Color::Yellow.bold().paint("🐫 v4.10.0 (^my-project) ")
));
assert_eq!(expected, actual);
dir.close()
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/mise.rs | src/modules/mise.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::mise::MiseConfig;
use crate::formatter::StringFormatter;
/// Creates a module with the current mise config
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("mise");
let config = MiseConfig::try_load(module.config);
let mise_applies = !config.disabled
&& context
.try_begin_scan()?
.set_extensions(&config.detect_extensions)
.set_files(&config.detect_files)
.set_folders(&config.detect_folders)
.is_match();
if !mise_applies {
return None;
}
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map(|variable| match variable {
"symbol" => Some(Ok(config.symbol)),
"health" => match context.exec_cmd("mise", &["doctor"]) {
Some(_) => Some(Ok(config.healthy_symbol)),
None => Some(Ok(config.unhealthy_symbol)),
},
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(e) => {
log::warn!("{e}");
return None;
}
});
Some(module)
}
#[cfg(test)]
mod tests {
use crate::test::ModuleRenderer;
use crate::utils::CommandOutput;
use nu_ansi_term::Color;
use std::io;
#[test]
fn folder_without_mise_config() {
let renderer = ModuleRenderer::new("mise").config(toml::toml! {
[mise]
disabled = false
});
assert_eq!(None, renderer.collect());
}
#[test]
fn folder_with_mise_config_file_healthy() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let config_path = dir.path().join(".mise.toml");
std::fs::File::create(config_path)?.sync_all()?;
let renderer = ModuleRenderer::new("mise")
.path(dir.path())
.config(toml::toml! {
[mise]
disabled = false
})
.cmd(
"mise doctor",
Some(CommandOutput {
stdout: String::default(),
stderr: String::default(),
}),
);
let expected = Some(format!(
"on {} ",
Color::Purple.bold().paint("mise healthy")
));
assert_eq!(expected, renderer.collect());
dir.close()
}
#[test]
fn folder_with_mise_config_folder_healthy() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let config_dir = dir.path().join(".mise");
std::fs::create_dir_all(config_dir)?;
let renderer = ModuleRenderer::new("mise")
.path(dir.path())
.config(toml::toml! {
[mise]
disabled = false
})
.cmd(
"mise doctor",
Some(CommandOutput {
stdout: String::default(),
stderr: String::default(),
}),
);
let expected = Some(format!(
"on {} ",
Color::Purple.bold().paint("mise healthy")
));
assert_eq!(expected, renderer.collect());
dir.close()
}
#[test]
fn folder_with_mise_config_file_unhealthy() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let config_path = dir.path().join(".mise.toml");
std::fs::File::create(config_path)?.sync_all()?;
let renderer = ModuleRenderer::new("mise")
.path(dir.path())
.config(toml::toml! {
[mise]
disabled = false
})
.cmd("mise doctor", None);
let expected = Some(format!(
"on {} ",
Color::Purple.bold().paint("mise unhealthy")
));
assert_eq!(expected, renderer.collect());
dir.close()
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/singularity.rs | src/modules/singularity.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::singularity::SingularityConfig;
use crate::formatter::StringFormatter;
/// Creates a module with the current Singularity image
///
/// Will display the Singularity image if `$SINGULARITY_NAME` is set.
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let singularity_env = context.get_env("SINGULARITY_NAME")?;
let mut module = context.new_module("singularity");
let config: SingularityConfig = SingularityConfig::try_load(module.config);
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|variable, _| match variable {
"symbol" => Some(config.symbol),
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map(|variable| match variable {
"env" => Some(Ok(&singularity_env)),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `singularity`: \n{error}");
return None;
}
});
Some(module)
}
#[cfg(test)]
mod tests {
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
#[test]
fn no_env_set() {
let actual = ModuleRenderer::new("singularity").collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn env_set() {
let actual = ModuleRenderer::new("singularity")
.env("SINGULARITY_NAME", "centos.img")
.collect();
let expected = Some(format!(
"{} ",
Color::Blue.bold().dimmed().paint("[centos.img]")
));
assert_eq!(expected, actual);
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/raku.rs | src/modules/raku.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::raku::RakuConfig;
use crate::formatter::StringFormatter;
use crate::formatter::VersionFormatter;
use std::ops::Deref;
use std::sync::LazyLock;
/// Creates a module with the current raku version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("raku");
let config: RakuConfig = RakuConfig::try_load(module.config);
let is_raku_project = context
.try_begin_scan()?
.set_extensions(&config.detect_extensions)
.set_files(&config.detect_files)
.set_folders(&config.detect_folders)
.is_match();
if !is_raku_project {
return None;
}
let versions = LazyLock::new(|| get_raku_version(context));
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,
})
.map(|variable| match variable {
"version" => versions
.deref()
.as_ref()
.map(|(raku_version, _)| raku_version)
.map(|raku_version| {
VersionFormatter::format_module_version(
module.get_name(),
raku_version,
config.version_format,
)
})?
.map(Ok),
"vm_version" => versions
.deref()
.as_ref()
.map(|(_, vm_version)| vm_version.to_string())
.map(Ok),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `raku`:\n{error}");
return None;
}
});
Some(module)
}
fn get_raku_version(context: &Context) -> Option<(String, String)> {
let output = context.exec_cmd("raku", &["--version"])?.stdout;
parse_raku_version(&output)
}
fn parse_raku_version(version: &str) -> Option<(String, String)> {
let mut lines = version.lines();
// skip 1st line
let _ = lines.next()?;
// split 2nd line into ["Implement", "the", "Raku®", ..., "v6.d."], take "v6.d."
// get rid of the trailing "."
let raku_version = lines
.next()?
.split_whitespace()
.nth(5)?
.strip_suffix('.')?
.to_string();
// split line into ["Built", "on", "MoarVM", ...], take "MoarVM"
// and change MoarVM to Moar (community's preference), leave other VMs as they are
let vm_version = lines
.next()?
.split_whitespace()
.nth(2)?
.replace("MoarVM", "Moar");
Some((raku_version.to_lowercase(), vm_version.to_lowercase()))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
use std::fs::File;
use std::io;
#[test]
fn test_parse_raku_version() {
let moar_input = "\
Welcome to Rakudo™ v2021.12.
Implementing the Raku® Programming Language v6.d.
Built on MoarVM version 2021.12.
";
let jvm_input = "\
Welcome to Rakudo™ v2021.12.
Implementing the Raku® Programming Language v6.d.
Built on JVM version 2021.12.
";
assert_eq!(
parse_raku_version(moar_input),
Some(("v6.d".to_string(), "moar".to_string()))
);
assert_eq!(
parse_raku_version(jvm_input),
Some(("v6.d".to_string(), "jvm".to_string()))
);
}
#[test]
fn folder_without_raku_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("raku").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_meta6_json_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("META6.json"))?.sync_all()?;
let actual = ModuleRenderer::new("raku").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Fixed(149).bold().paint("🦋 v6.d-moar ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_raku_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("any.raku"))?.sync_all()?;
let actual = ModuleRenderer::new("raku").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Fixed(149).bold().paint("🦋 v6.d-moar ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_raku_module_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("any.rakumod"))?.sync_all()?;
let actual = ModuleRenderer::new("raku").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Fixed(149).bold().paint("🦋 v6.d-moar ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_rakudoc_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("any.pod6"))?.sync_all()?;
let actual = ModuleRenderer::new("raku").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Fixed(149).bold().paint("🦋 v6.d-moar ")
));
assert_eq!(expected, actual);
dir.close()
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/nix_shell.rs | src/modules/nix_shell.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::nix_shell::NixShellConfig;
use crate::formatter::StringFormatter;
enum NixShellType {
Pure,
Impure,
/// We're in a Nix shell, but we don't know which type.
/// This can only happen in a `nix shell` shell (not a `nix-shell` one).
Unknown,
}
impl NixShellType {
fn detect_shell_type(use_heuristic: bool, context: &Context) -> Option<Self> {
use NixShellType::{Impure, Pure, Unknown};
let shell_type = context.get_env("IN_NIX_SHELL");
match shell_type.as_deref() {
Some("pure") => return Some(Pure),
Some("impure") => return Some(Impure),
_ => {}
}
if use_heuristic {
Self::in_new_nix_shell(context).map(|()| Unknown)
} else {
None
}
}
// Hack to detect if we're in a `nix shell` (in contrast to a `nix-shell`).
// A better way to do this will be enabled by https://github.com/NixOS/nix/issues/6677.
fn in_new_nix_shell(context: &Context) -> Option<()> {
let path = context.get_env("PATH")?;
std::env::split_paths(&path)
.any(|path| path.starts_with("/nix/store"))
.then_some(())
}
}
/// Creates a module showing if inside a nix-shell
///
/// The module will use the `$IN_NIX_SHELL` and `$name` environment variable to
/// determine if it's inside a nix-shell and the name of it.
///
/// The following options are available:
/// - `impure_msg` (string) // change the impure msg
/// - `pure_msg` (string) // change the pure msg
/// - `unknown_msg` (string) // change the unknown message
///
/// Will display the following:
/// - pure (name) // $name == "name" in a pure nix-shell
/// - impure (name) // $name == "name" in an impure nix-shell
/// - pure // $name == "" in a pure nix-shell
/// - impure // $name == "" in an impure nix-shell
/// - unknown (name) // $name == "name" in an unknown nix-shell
/// - unknown // $name == "" in an unknown nix-shell
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("nix_shell");
let config: NixShellConfig = NixShellConfig::try_load(module.config);
let shell_name = context.get_env("name");
let shell_type = NixShellType::detect_shell_type(config.heuristic, context)?;
let shell_type_format = match shell_type {
NixShellType::Pure => config.pure_msg,
NixShellType::Impure => config.impure_msg,
NixShellType::Unknown => config.unknown_msg,
};
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|variable, _| match variable {
"symbol" => Some(config.symbol),
"state" => Some(shell_type_format),
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map(|variable| match variable {
"name" => shell_name.as_ref().map(Ok),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `nix_shell`:\n{error}");
return None;
}
});
Some(module)
}
#[cfg(test)]
mod tests {
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
#[test]
fn no_env_variables() {
let actual = ModuleRenderer::new("nix_shell").collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn invalid_env_variables() {
let actual = ModuleRenderer::new("nix_shell")
.env("IN_NIX_SHELL", "something_wrong")
.collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn pure_shell() {
let actual = ModuleRenderer::new("nix_shell")
.env("IN_NIX_SHELL", "pure")
.collect();
let expected = Some(format!("via {} ", Color::Blue.bold().paint("❄️ pure")));
assert_eq!(expected, actual);
}
#[test]
fn impure_shell() {
let actual = ModuleRenderer::new("nix_shell")
.env("IN_NIX_SHELL", "impure")
.collect();
let expected = Some(format!("via {} ", Color::Blue.bold().paint("❄️ impure")));
assert_eq!(expected, actual);
}
#[test]
fn pure_shell_name() {
let actual = ModuleRenderer::new("nix_shell")
.env("IN_NIX_SHELL", "pure")
.env("name", "starship")
.collect();
let expected = Some(format!(
"via {} ",
Color::Blue.bold().paint("❄️ pure (starship)")
));
assert_eq!(expected, actual);
}
#[test]
fn impure_shell_name() {
let actual = ModuleRenderer::new("nix_shell")
.env("IN_NIX_SHELL", "impure")
.env("name", "starship")
.collect();
let expected = Some(format!(
"via {} ",
Color::Blue.bold().paint("❄️ impure (starship)")
));
assert_eq!(expected, actual);
}
#[test]
fn new_nix_shell() {
let actual = ModuleRenderer::new("nix_shell")
.env(
"PATH",
"/nix/store/v7qvqv81jp0cajvrxr9x072jgqc01yhi-nix-info/bin:/Users/user/.cargo/bin",
)
.config(toml::toml! {
[nix_shell]
heuristic = true
})
.collect();
let expected = Some(format!("via {} ", Color::Blue.bold().paint("❄️ ")));
assert_eq!(expected, actual);
}
#[test]
fn no_new_nix_shell() {
let actual = ModuleRenderer::new("nix_shell")
.env("PATH", "/Users/user/.cargo/bin")
.config(toml::toml! {
[nix_shell]
heuristic = true
})
.collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn no_new_nix_shell_with_nix_store_subdirectory() {
let actual = ModuleRenderer::new("nix_shell")
.env("PATH", "/Users/user/some/nix/store/subdirectory")
.config(toml::toml! {
[nix_shell]
heuristic = true
})
.collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn no_new_nix_shell_when_heuristic_is_disabled() {
let actual = ModuleRenderer::new("nix_shell")
.env(
"PATH",
"/nix/store/v7qvqv81jp0cajvrxr9x072jgqc01yhi-nix-info/bin:/Users/user/.cargo/bin",
)
.collect();
let expected = None;
assert_eq!(expected, actual);
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/conda.rs | src/modules/conda.rs | use super::{Context, Module, ModuleConfig};
use super::utils::directory::truncate;
use crate::configs::conda::CondaConfig;
use crate::formatter::StringFormatter;
/// Creates a module with the current Conda environment
///
/// Will display the Conda environment iff `$CONDA_DEFAULT_ENV` is set.
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
// Reference implementation: https://github.com/denysdovhan/spaceship-prompt/blob/master/sections/conda.zsh
let conda_env = context.get_env("CONDA_DEFAULT_ENV").unwrap_or_default();
if conda_env.trim().is_empty() {
return None;
}
let mut module = context.new_module("conda");
let config: CondaConfig = CondaConfig::try_load(module.config);
if config.ignore_base && conda_env == "base" {
return None;
}
if !context.detect_env_vars(&config.detect_env_vars) {
return None;
}
let conda_env = truncate(&conda_env, config.truncation_length).unwrap_or(conda_env);
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|variable, _| match variable {
"symbol" => Some(config.symbol),
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map(|variable| match variable {
"environment" => Some(Ok(conda_env.as_str())),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `conda`:\n{error}");
return None;
}
});
Some(module)
}
#[cfg(test)]
mod tests {
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
#[test]
fn not_in_env() {
let actual = ModuleRenderer::new("conda").collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn ignore_base() {
let actual = ModuleRenderer::new("conda")
.env("CONDA_DEFAULT_ENV", "base")
.config(toml::toml! {
[conda]
ignore_base = true
})
.collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn ignore_pixi_envs() {
let actual = ModuleRenderer::new("conda")
.env("CONDA_DEFAULT_ENV", "my-env")
.env("PIXI_ENVIRONMENT_NAME", "my-env")
.collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn env_set() {
let actual = ModuleRenderer::new("conda")
.env("CONDA_DEFAULT_ENV", "astronauts")
.collect();
let expected = Some(format!(
"via {} ",
Color::Green.bold().paint("🅒 astronauts")
));
assert_eq!(expected, actual);
}
#[test]
fn truncate() {
let actual = ModuleRenderer::new("conda")
.env("CONDA_DEFAULT_ENV", "/some/really/long/and/really/annoying/path/that/shouldnt/be/displayed/fully/conda/my_env")
.collect();
let expected = Some(format!("via {} ", Color::Green.bold().paint("🅒 my_env")));
assert_eq!(expected, actual);
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/helm.rs | src/modules/helm.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::helm::HelmConfig;
use crate::formatter::StringFormatter;
use crate::formatter::VersionFormatter;
/// Creates a module with the current Helm version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("helm");
let config = HelmConfig::try_load(module.config);
let is_helm_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_helm_project {
return None;
}
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,
})
.map(|variable| match variable {
"version" => {
let helm_version = parse_helm_version(
&context.exec_cmd("helm", &["version", "--short"])?.stdout,
)?;
VersionFormatter::format_module_version(
module.get_name(),
&helm_version,
config.version_format,
)
.map(Ok)
}
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `helm`:\n{error}");
return None;
}
});
Some(module)
}
fn parse_helm_version(helm_stdout: &str) -> Option<String> {
// `helm version --short` output looks like this:
// v3.1.1+gafe7058
let version = helm_stdout
// split into ("v3.1.1","gafe7058")
.split_once('+')
// return "v3.1.1"
.map_or(helm_stdout, |x| x.0)
.trim_start_matches('v')
.trim()
.to_string();
Some(version)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
use std::fs::File;
use std::io;
#[test]
fn folder_without_helm_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("helm").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_helm_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("helmfile.yaml"))?.sync_all()?;
let actual = ModuleRenderer::new("helm").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::White.bold().paint("⎈ v3.1.1 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_chart_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("Chart.yaml"))?.sync_all()?;
let actual = ModuleRenderer::new("helm").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::White.bold().paint("⎈ v3.1.1 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn test_parse_helm_version() {
let helm_3 = "v3.1.1+ggit afe7058";
assert_eq!(parse_helm_version(helm_3), Some("3.1.1".to_string()));
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/rlang.rs | src/modules/rlang.rs | use super::{Context, Module, ModuleConfig};
use crate::formatter::VersionFormatter;
use crate::configs::rlang::RLangConfig;
use crate::formatter::StringFormatter;
use crate::utils::get_command_string_output;
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("rlang");
let config: RLangConfig = RLangConfig::try_load(module.config);
let is_r_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_r_project {
return None;
}
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,
})
.map(|variable| match variable {
"version" => {
let r_version_string =
get_command_string_output(context.exec_cmd("R", &["--version"])?);
let r_version = parse_r_version(&r_version_string)?;
VersionFormatter::format_module_version(
module.get_name(),
&r_version,
config.version_format,
)
.map(Ok)
}
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `rlang`:\n{error}");
return None;
}
});
Some(module)
}
fn parse_r_version(r_version: &str) -> Option<String> {
r_version
.lines()
// take first line
.next()?
// split into ["R", "version", "3.6.3", "(2020-02-29)", ...]
.split_whitespace()
// and pick version entry at index 2, i.e. "3.6.3".
.nth(2)
.map(ToString::to_string)
}
#[cfg(test)]
mod tests {
use super::parse_r_version;
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
use std::fs;
use std::fs::File;
use std::io;
#[test]
fn test_parse_r_version() {
let r_v3 = r#"R version 4.1.0 (2021-05-18) -- "Camp Pontanezen"
Copyright (C) 2021 The R Foundation for Statistical Computing
Platform: x86_64-w64-mingw32/x64 (64-bit)\n
R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under the terms of the
GNU General Public License versions 2 or 3.
For more information about these matters see
https://www.gnu.org/licenses/."#;
assert_eq!(parse_r_version(r_v3), Some(String::from("4.1.0")));
}
#[test]
fn folder_with_r_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("analysis.R"))?.sync_all()?;
check_r_render(&dir);
dir.close()
}
#[test]
fn folder_with_rd_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("analysis.Rd"))?.sync_all()?;
check_r_render(&dir);
dir.close()
}
#[test]
fn folder_with_rmd_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("analysis.Rmd"))?.sync_all()?;
check_r_render(&dir);
dir.close()
}
#[test]
fn folder_with_rproj_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("analysis.Rproj"))?.sync_all()?;
check_r_render(&dir);
dir.close()
}
#[test]
fn folder_with_rsx_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("analysis.Rsx"))?.sync_all()?;
check_r_render(&dir);
dir.close()
}
#[test]
fn folder_with_description_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("DESCRIPTION"))?.sync_all()?;
check_r_render(&dir);
dir.close()
}
#[test]
fn folder_with_rproj_user_folder() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let rprofile = dir.path().join(".Rproj.user");
fs::create_dir_all(rprofile)?;
check_r_render(&dir);
dir.close()
}
fn check_r_render(dir: &tempfile::TempDir) {
let actual = ModuleRenderer::new("rlang").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Blue.bold().paint("📐 v4.1.0 ")));
assert_eq!(expected, actual);
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/pulumi.rs | src/modules/pulumi.rs | #![warn(missing_docs)]
use serde::Deserialize;
use sha1::{Digest, Sha1};
use std::collections::HashMap;
use std::ffi::OsStr;
use std::fs::File;
use std::io::{BufReader, Read};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use yaml_rust2::{Yaml, YamlLoader};
use super::{Context, Module, ModuleConfig};
use crate::configs::pulumi::PulumiConfig;
use crate::formatter::{StringFormatter, VersionFormatter};
static PULUMI_HOME: &str = "PULUMI_HOME";
#[derive(Deserialize)]
struct Credentials {
current: Option<String>,
accounts: Option<HashMap<String, Account>>,
}
#[derive(Deserialize)]
struct Account {
username: Option<String>,
}
/// Creates a module with the current Pulumi version and stack name.
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("pulumi");
let config = PulumiConfig::try_load(module.config);
let project_file_in_cwd = context
.try_begin_scan()?
.set_files(&["Pulumi.yaml", "Pulumi.yml"])
.is_match();
if !project_file_in_cwd && !config.search_upwards {
return None;
}
let project_file = find_package_file(&context.logical_dir)?;
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|variable, _| match variable {
"symbol" => Some(config.symbol),
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map(|variable| match variable {
"version" => {
let stdout = context.exec_cmd("pulumi", &["version"])?.stdout;
VersionFormatter::format_module_version(
module.get_name(),
parse_version(&stdout),
config.version_format,
)
}
.map(Ok),
"username" => get_pulumi_username(context).map(Ok),
"stack" => stack_name(&project_file, context).map(Ok),
_ => None,
})
.parse(None, Some(context))
});
match parsed {
Ok(x) => {
module.set_segments(x);
Some(module)
}
Err(e) => {
log::warn!("Error in module `pulumi`:\n{e}");
None
}
}
}
/// Parse and sanitize the output of `pulumi version` into just the version string.
///
/// Normally, this just means returning it. When Pulumi is being developed, it
/// can return results like `3.12.0-alpha.1630554544+f89e9a29.dirty`, which we
/// don't want to see. Instead we display that as `3.12.0-alpha`.
fn parse_version(version: &str) -> &str {
let new_version = version.strip_prefix('v').unwrap_or(version);
let sanitized_version = new_version.trim_end();
let mut periods = 0;
for (i, c) in sanitized_version.as_bytes().iter().enumerate() {
if *c == b'.' {
if periods == 2 {
return &sanitized_version[0..i];
}
periods += 1;
}
}
// We didn't hit 3 periods, so we just return the whole string.
sanitized_version
}
/// Find a file describing a Pulumi package in the current directory (or any parent directory).
fn find_package_file(path: &Path) -> Option<PathBuf> {
for path in path.ancestors() {
log::trace!("Looking for package file in {path:?}");
let dir = std::fs::read_dir(path).ok()?;
let goal = dir.filter_map(Result::ok).find(|path| {
path.file_name() == OsStr::new("Pulumi.yaml")
|| path.file_name() == OsStr::new("Pulumi.yml")
});
if let Some(goal) = goal {
return Some(goal.path());
}
}
log::trace!("Did not find a Pulumi package file");
None
}
/// We get the name of the current stack.
///
/// Pulumi has no CLI option that is fast enough to get this for us, but finding
/// the location is simple. We get it ourselves.
fn stack_name(project_file: &Path, context: &Context) -> Option<String> {
let mut file = File::open(project_file).ok()?;
let mut contents = String::new();
file.read_to_string(&mut contents).ok()?;
let name = YamlLoader::load_from_str(&contents).ok().and_then(
|yaml| -> Option<Option<String>> {
log::trace!("Parsed {project_file:?} into yaml");
let yaml = yaml.into_iter().next()?;
yaml.into_hash().map(|mut hash| -> Option<String> {
hash.remove(&Yaml::String("name".to_string()))?
.into_string()
})
},
)??;
log::trace!("Found project name: {name:?}");
let workspace_file = get_pulumi_workspace(context, &name, project_file)
.map(File::open)?
.ok()?;
log::trace!("Trying to read workspace_file: {workspace_file:?}");
let workspace: serde_json::Value = match serde_json::from_reader(workspace_file) {
Ok(k) => k,
Err(e) => {
log::debug!("Failed to parse workspace file: {e}");
return None;
}
};
log::trace!("Read workspace_file: {workspace:?}");
workspace
.as_object()?
.get("stack")?
.as_str()
.map(ToString::to_string)
}
/// Calculates the path of the workspace settings file for a given pulumi stack.
fn get_pulumi_workspace(context: &Context, name: &str, project_file: &Path) -> Option<PathBuf> {
let project_file = if cfg!(test) {
// Because this depends on the absolute path of the file, it changes in
// each test run. We thus mock it.
"test".to_string()
} else {
let mut hasher = Sha1::new();
hasher.update(project_file.to_str()?.as_bytes());
crate::utils::encode_to_hex(&hasher.finalize())
};
let unique_file_name = format!("{name}-{project_file}-workspace.json");
let mut path = pulumi_home_dir(context)?;
path.push("workspaces");
path.push(unique_file_name);
Some(path)
}
/// Get the Pulumi home directory. We first check `PULUMI_HOME`. If that isn't
/// set, we return `$HOME/.pulumi`.
fn pulumi_home_dir(context: &Context) -> Option<PathBuf> {
if let Some(k) = context.get_env(PULUMI_HOME) {
std::path::PathBuf::from_str(&k).ok()
} else {
context.get_home().map(|p| p.join(".pulumi"))
}
}
fn get_pulumi_username(context: &Context) -> Option<String> {
let home_dir = pulumi_home_dir(context)?;
let creds_path = home_dir.join("credentials.json");
let file = File::open(creds_path).ok()?;
let reader = BufReader::new(file);
// Read the JSON contents of the file as an instance of `User`.
let creds: Credentials = serde_json::from_reader(reader).ok()?;
let current_api_provider = creds.current?;
creds.accounts?.remove(¤t_api_provider)?.username
}
#[cfg(test)]
mod tests {
use std::io;
use super::*;
use crate::context::{Properties, Target};
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
#[test]
fn pulumi_version_release() {
let expected = "3.12.0";
let inputs: [&str; 6] = [
"v3.12.0\r\n",
"v3.12.0\n",
"v3.12.0",
"3.12.0\r\n",
"3.12.0\n",
"3.12.0",
];
for input in &inputs {
assert_eq!(parse_version(input), expected);
}
}
#[test]
fn pulumi_version_prerelease() {
let expected = "3.12.0-alpha";
let inputs: [&str; 6] = [
"v3.12.0-alpha\r\n",
"v3.12.0-alpha\n",
"v3.12.0-alpha",
"3.12.0-alpha\r\n",
"3.12.0-alpha\n",
"3.12.0-alpha",
];
for input in &inputs {
assert_eq!(parse_version(input), expected);
}
}
#[test]
fn pulumi_version_dirty() {
let expected = "3.12.0-alpha";
let inputs: [&str; 6] = [
"v3.12.0-alpha.1630554544+f89e9a29.dirty\r\n",
"v3.12.0-alpha.1630554544+f89e9a29.dirty\n",
"v3.12.0-alpha.1630554544+f89e9a29.dirty",
"3.12.0-alpha.1630554544+f89e9a29.dirty\r\n",
"3.12.0-alpha.1630554544+f89e9a29.dirty\n",
"3.12.0-alpha.1630554544+f89e9a29.dirty",
];
for input in &inputs {
assert_eq!(parse_version(input), expected);
}
}
#[test]
fn get_home_dir() {
let mut context = Context::new(Properties::default(), Target::Main);
context.env.insert("HOME", "/home/sweet/home".to_string());
assert_eq!(
pulumi_home_dir(&context),
Some(PathBuf::from("/home/sweet/home/.pulumi"))
);
context.env.insert("PULUMI_HOME", "/a/dir".to_string());
assert_eq!(pulumi_home_dir(&context), Some(PathBuf::from("/a/dir")));
}
#[test]
fn test_get_pulumi_workspace() {
let mut context = Context::new(Properties::default(), Target::Main);
context.env.insert("HOME", "/home/sweet/home".to_string());
let name = "foobar";
let project_file = PathBuf::from("/hello/Pulumi.yaml");
assert_eq!(
get_pulumi_workspace(&context, name, &project_file),
Some(PathBuf::from(
"/home/sweet/home/.pulumi/workspaces/foobar-test-workspace.json"
))
);
}
#[test]
fn version_render() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let pulumi_file = File::create(dir.path().join("Pulumi.yaml"))?;
pulumi_file.sync_all()?;
let rendered = ModuleRenderer::new("pulumi")
.path(dir.path())
.config(toml::toml! {
[pulumi]
format = "with [$version]($style) "
})
.collect();
dir.close()?;
let expected = format!("with {} ", Color::Fixed(5).bold().paint("v1.2.3-ver"));
assert_eq!(expected, rendered.expect("a result"));
Ok(())
}
#[test]
/// This test confirms a full render. This means finding a Pulumi.yml file,
/// tracing back to the backing workspace settings file, and printing the
/// stack name.
fn render_valid_paths() -> io::Result<()> {
use io::Write;
let (module_renderer, dir) = ModuleRenderer::new_with_home("pulumi")?;
let root = dunce::canonicalize(dir.path())?;
let mut yaml = File::create(root.join("Pulumi.yml"))?;
yaml.write_all("name: starship\nruntime: nodejs\ndescription: A thing\n".as_bytes())?;
yaml.sync_all()?;
let workspace_path = root.join(".pulumi").join("workspaces");
std::fs::create_dir_all(&workspace_path)?;
let workspace_path = &workspace_path.join("starship-test-workspace.json");
let mut workspace = File::create(workspace_path)?;
serde_json::to_writer_pretty(
&mut workspace,
&serde_json::json!(
{
"stack": "launch"
}
),
)?;
workspace.sync_all()?;
let credential_path = root.join(".pulumi");
std::fs::create_dir_all(&credential_path)?;
let credential_path = &credential_path.join("credentials.json");
let mut credential = File::create(credential_path)?;
serde_json::to_writer_pretty(
&mut credential,
&serde_json::json!(
{
"current": "https://api.example.com",
"accessTokens": {
"https://api.example.com": "redacted",
"https://api.pulumi.com": "redacted"
},
"accounts": {
"https://api.example.com": {
"accessToken": "redacted",
"username": "test-user",
"lastValidatedAt": "2022-01-12T00:00:00.000000000-08:00"
}
}
}
),
)?;
credential.sync_all()?;
let rendered = module_renderer
.path(root.clone())
.logical_path(root)
.config(toml::toml! {
[pulumi]
format = "via [$symbol($username@)$stack]($style) "
})
.collect();
let expected = format!(
"via {} ",
Color::Fixed(5).bold().paint(" test-user@launch")
);
assert_eq!(expected, rendered.expect("a result"));
dir.close()
}
#[test]
/// This test confirms a render when the account information incomplete, i.e.: no username for
/// the current API.
fn partial_login() -> io::Result<()> {
use io::Write;
let (module_renderer, dir) = ModuleRenderer::new_with_home("pulumi")?;
let root = dunce::canonicalize(dir.path())?;
let mut yaml = File::create(root.join("Pulumi.yml"))?;
yaml.write_all("name: starship\nruntime: nodejs\ndescription: A thing\n".as_bytes())?;
yaml.sync_all()?;
let workspace_path = root.join(".pulumi").join("workspaces");
std::fs::create_dir_all(&workspace_path)?;
let workspace_path = &workspace_path.join("starship-test-workspace.json");
let mut workspace = File::create(workspace_path)?;
serde_json::to_writer_pretty(
&mut workspace,
&serde_json::json!(
{
"stack": "launch"
}
),
)?;
workspace.sync_all()?;
let credential_path = root.join(".pulumi");
std::fs::create_dir_all(&credential_path)?;
let credential_path = &credential_path.join("starship-test-credential.json");
let mut credential = File::create(credential_path)?;
serde_json::to_writer_pretty(
&mut credential,
&serde_json::json!(
{
"current": "https://api.example.com",
"accessTokens": {
"https://api.example.com": "redacted",
"https://api.pulumi.com": "redacted"
},
"accounts": {
}
}
),
)?;
credential.sync_all()?;
let rendered = module_renderer
.path(root.clone())
.logical_path(root)
.config(toml::toml! {
[pulumi]
format = "via [$symbol($username@)$stack]($style) "
})
.collect();
let expected = format!("via {} ", Color::Fixed(5).bold().paint(" launch"));
assert_eq!(expected, rendered.expect("a result"));
dir.close()
}
#[test]
fn empty_config_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let yaml = File::create(dir.path().join("Pulumi.yaml"))?;
yaml.sync_all()?;
let rendered = ModuleRenderer::new("pulumi")
.path(dir.path())
.logical_path(dir.path())
.config(toml::toml! {
[pulumi]
format = "in [$symbol($stack)]($style) "
})
.collect();
let expected = format!("in {} ", Color::Fixed(5).bold().paint(" "));
assert_eq!(expected, rendered.expect("a result"));
dir.close()?;
Ok(())
}
#[test]
fn do_not_search_upwards() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let child_dir = dir.path().join("child");
std::fs::create_dir(&child_dir)?;
let yaml = File::create(dir.path().join("Pulumi.yaml"))?;
yaml.sync_all()?;
let actual = ModuleRenderer::new("pulumi")
.path(&child_dir)
.logical_path(&child_dir)
.config(toml::toml! {
[pulumi]
format = "in [$symbol($stack)]($style) "
search_upwards = false
})
.collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn search_upwards_default() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let child_dir = dir.path().join("child");
std::fs::create_dir(&child_dir)?;
let yaml = File::create(dir.path().join("Pulumi.yaml"))?;
yaml.sync_all()?;
let actual = ModuleRenderer::new("pulumi")
.path(&child_dir)
.logical_path(&child_dir)
.config(toml::toml! {
[pulumi]
format = "in [$symbol($stack)]($style) "
})
.collect();
let expected = Some(format!("in {} ", Color::Fixed(5).bold().paint(" ")));
assert_eq!(expected, actual);
dir.close()
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/solidity.rs | src/modules/solidity.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::solidity::SolidityConfig;
use crate::formatter::{StringFormatter, VersionFormatter};
use crate::utils::get_command_string_output;
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("solidity");
let config = SolidityConfig::try_load(module.config);
let is_solidity_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_solidity_project {
return None;
}
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|variable, _| match variable {
"symbol" => Some(config.symbol),
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map(|variable| match variable {
"version" => {
let version = get_solidity_version(context, &config)?;
VersionFormatter::format_module_version(
module.get_name(),
&version,
config.version_format,
)
.map(Ok)
}
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module 'solidity'\n {error}");
return None;
}
});
Some(module)
}
fn get_solidity_version(context: &Context, config: &SolidityConfig) -> Option<String> {
let version = config
.compiler
.0
.iter()
.find_map(|compiler_name| context.exec_cmd(compiler_name, &["--version"]))
.map(get_command_string_output)?;
parse_solidity_version(&version)
}
fn parse_solidity_version(version: &str) -> Option<String> {
/*solc --version output looks like "solc, the solidity compiler commandline interface Version: 0.8.16+commit.07a7930e.Linux.g++"
solcjs --version out looks like 0.8.15+commit.e14f2714.Emscripten.clang */
let version_var = match version.split_whitespace().nth(7) {
// Will return Some(x) for solc --version and None for solcjs --version
Some(c) => c.split_terminator('+').next()?, //Isolates the versioning number e.g "0.8.16"
None => version.split_terminator('+').next()?, //Isolates the version number e.g "0.8.15"
};
Some(version_var.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
use std::fs::File;
use std::io;
#[test]
fn test_parse_solc_version() {
let input = "solc, the solidity compiler commandline interface
Version: 0.8.16+commit.07a7930e.Linux.g++";
assert_eq!(parse_solidity_version(input), Some(String::from("0.8.16")));
}
#[test]
fn test_parse_solcjs_version() {
let input = "0.8.15+commit.e14f2714.Emscripten.clang";
assert_eq!(parse_solidity_version(input), Some(String::from("0.8.15")));
}
#[test]
fn folder_without_solidity_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("solidity.txt"))?.sync_all()?;
let actual = ModuleRenderer::new("solidity").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_solidity_file() -> io::Result<()> {
let tempdir = tempfile::tempdir()?;
// Create some file needed to render the module
File::create(tempdir.path().join("main.sol"))?.sync_all()?;
// The output of the module
let actual = ModuleRenderer::new("solidity")
// For a custom path
.path(tempdir.path())
// Run the module and collect the output
.collect();
// The value that should be rendered by the module.
let expected = Some(format!("via {}", Color::Blue.bold().paint("S v0.8.16")));
// Assert that the actual and expected values are the same
assert_eq!(actual, expected);
// Close the tempdir
tempdir.close()
}
#[test]
fn testing_for_solcjs_render() -> io::Result<()> {
let tempdir = tempfile::tempdir()?;
// Create some file needed to render the module
File::create(tempdir.path().join("main.sol"))?.sync_all()?;
// The output of the module
let actual = ModuleRenderer::new("solidity")
// For a custom path
.path(tempdir.path())
// For a custom config
.config(toml::toml! {
[solidity]
compiler = "solcjs"
})
// Run the module and collect the output
.collect();
// The value that should be rendered by the module.
let expected = Some(format!("via {}", Color::Blue.bold().paint("S v0.8.15")));
// Assert that the actual and expected values are the same
assert_eq!(actual, expected);
// Close the tempdir
tempdir.close()
}
#[test]
fn testing_sol_fallback() -> io::Result<()> {
let tempdir = tempfile::tempdir()?;
// Create some file needed to render the module
File::create(tempdir.path().join("main.sol"))?.sync_all()?;
// The output of the module
let actual = ModuleRenderer::new("solidity")
// For a custom path
.path(tempdir.path())
// Make regular solc unavailable
.cmd("solc --version", None)
// Custom Config
.config(toml::toml! {
[solidity]
compiler = ["solc", "solcjs"]
})
// Run the module and collect the output
.collect();
// The value that should be rendered by the module.
let expected = Some(format!("via {}", Color::Blue.bold().paint("S v0.8.15")));
// Assert that the actual and expected values are the same
assert_eq!(actual, expected);
// Close the tempdir
tempdir.close()
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/terraform.rs | src/modules/terraform.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::terraform::TerraformConfig;
use crate::formatter::StringFormatter;
use crate::utils;
use crate::formatter::VersionFormatter;
use std::io;
use std::path::PathBuf;
/// Creates a module with the current Terraform version and workspace
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("terraform");
let config: TerraformConfig = TerraformConfig::try_load(module.config);
let is_terraform_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_folders(&config.detect_folders)
.set_extensions(&config.detect_extensions)
.is_match();
if !is_terraform_project {
return None;
}
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|variable, _| match variable {
"symbol" => Some(config.symbol),
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map(|variable| match variable {
"version" => {
let terraform_version = parse_terraform_version(
context
.exec_cmds_return_first(&config.commands)?
.stdout
.as_str(),
)?;
VersionFormatter::format_module_version(
module.get_name(),
&terraform_version,
config.version_format,
)
}
.map(Ok),
"workspace" => get_terraform_workspace(context).map(Ok),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `terraform`:\n{error}");
return None;
}
});
Some(module)
}
// Determines the currently selected workspace (see https://github.com/hashicorp/terraform/blob/master/command/meta.go for the original implementation)
fn get_terraform_workspace(context: &Context) -> Option<String> {
// Workspace can be explicitly overwritten by an env var
let workspace_override = context.get_env("TF_WORKSPACE");
if workspace_override.is_some() {
return workspace_override;
}
// Data directory containing current workspace can be overwritten by an env var
let datadir = match context.get_env("TF_DATA_DIR") {
Some(s) => PathBuf::from(s),
None => context.current_dir.join(".terraform"),
};
match utils::read_file(datadir.join("environment")) {
Err(ref e) if e.kind() == io::ErrorKind::NotFound => Some("default".to_string()),
Ok(s) => Some(s),
_ => None,
}
}
fn parse_terraform_version(version: &str) -> Option<String> {
// `terraform version` or `tofu version` output looks like this
// Terraform v0.12.14/OpenTofu v1.7.2
// with potential extra output if it detects you are not running the latest version
let version = version
.lines()
.next()?
.trim_start_matches("Terraform ")
.trim_start_matches("OpenTofu ")
.trim()
.trim_start_matches('v');
Some(version.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
use std::fs::{self, File};
use std::io::{self, Write};
#[test]
fn test_parse_terraform_version_release() {
let input = "Terraform v0.12.14";
assert_eq!(parse_terraform_version(input), Some("0.12.14".to_string()));
}
#[test]
fn test_parse_opentofu_version_release() {
let input = "OpenTofu v1.7.2";
assert_eq!(parse_terraform_version(input), Some("1.7.2".to_string()));
}
#[test]
fn test_parse_opentofu_version_multiline() {
let input = "OpenTofu v1.7.2
on darwin_arm64
+ provider registry.opentofu.org/hashicorp/helm v2.14.0
+ provider registry.opentofu.org/hashicorp/kubernetes v2.31.0
";
assert_eq!(parse_terraform_version(input), Some("1.7.2".to_string()));
}
#[test]
fn test_parse_terraform_version_prerelease() {
let input = "Terraform v0.12.14-rc1";
assert_eq!(
parse_terraform_version(input),
Some("0.12.14-rc1".to_string())
);
}
#[test]
fn test_parse_opentofu_version_prerelease() {
let input = "OpenTofu v1.8.0-alpha1";
assert_eq!(
parse_terraform_version(input),
Some("1.8.0-alpha1".to_string())
)
}
#[test]
fn test_parse_terraform_version_development() {
let input = "Terraform v0.12.14-dev (cca89f74)";
assert_eq!(
parse_terraform_version(input),
Some("0.12.14-dev (cca89f74)".to_string())
);
}
#[test]
fn test_parse_terraform_version_multiline() {
let input = "Terraform v0.12.13
Your version of Terraform is out of date! The latest version
is 0.12.14. You can update by downloading from www.terraform.io/downloads.html
";
assert_eq!(parse_terraform_version(input), Some("0.12.13".to_string()));
}
#[test]
fn folder_with_dotterraform_with_version_no_environment() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let tf_dir = dir.path().join(".terraform");
fs::create_dir(tf_dir)?;
let actual = ModuleRenderer::new("terraform")
.path(dir.path())
.config(toml::toml! {
[terraform]
format = "via [$symbol$version $workspace]($style) "
})
.collect();
let expected = Some(format!(
"via {} ",
Color::Fixed(105).bold().paint("💠 v0.12.14 default")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_dotterraform_with_version_with_environment() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let tf_dir = dir.path().join(".terraform");
fs::create_dir(&tf_dir)?;
let mut file = File::create(tf_dir.join("environment"))?;
file.write_all(b"development")?;
file.sync_all()?;
let actual = ModuleRenderer::new("terraform")
.path(dir.path())
.config(toml::toml! {
[terraform]
format = "via [$symbol$version $workspace]($style) "
})
.collect();
let expected = Some(format!(
"via {} ",
Color::Fixed(105).bold().paint("💠 v0.12.14 development")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_without_dotterraform() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("terraform").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_tf_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("main.tf"))?;
let actual = ModuleRenderer::new("terraform").path(dir.path()).collect();
let expected = Some(format!(
"via {} ",
Color::Fixed(105).bold().paint("💠 default")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_workspace_override() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("main.tf"))?;
let actual = ModuleRenderer::new("terraform")
.path(dir.path())
.env("TF_WORKSPACE", "development")
.collect();
let expected = Some(format!(
"via {} ",
Color::Fixed(105).bold().paint("💠 development")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_datadir_override() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("main.tf"))?;
let datadir = tempfile::tempdir()?;
let mut file = File::create(datadir.path().join("environment"))?;
file.write_all(b"development")?;
file.sync_all()?;
let actual = ModuleRenderer::new("terraform")
.path(dir.path())
.env("TF_DATA_DIR", datadir.path().to_str().unwrap())
.collect();
let expected = Some(format!(
"via {} ",
Color::Fixed(105).bold().paint("💠 development")
));
assert_eq!(expected, actual);
dir.close()?;
datadir.close()
}
#[test]
fn folder_with_dotterraform_no_environment() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let tf_dir = dir.path().join(".terraform");
fs::create_dir(tf_dir)?;
let actual = ModuleRenderer::new("terraform").path(dir.path()).collect();
let expected = Some(format!(
"via {} ",
Color::Fixed(105).bold().paint("💠 default")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_dotterraform_with_environment() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let tf_dir = dir.path().join(".terraform");
fs::create_dir(&tf_dir)?;
let mut file = File::create(tf_dir.join("environment"))?;
file.write_all(b"development")?;
file.sync_all()?;
let actual = ModuleRenderer::new("terraform").path(dir.path()).collect();
let expected = Some(format!(
"via {} ",
Color::Fixed(105).bold().paint("💠 development")
));
assert_eq!(expected, actual);
dir.close()
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/git_branch.rs | src/modules/git_branch.rs | use gix::bstr::ByteSlice;
use unicode_segmentation::UnicodeSegmentation;
use super::{Context, Module, ModuleConfig};
use crate::configs::git_branch::GitBranchConfig;
use crate::context::Repo;
use crate::formatter::StringFormatter;
use crate::modules::git_status::uses_reftables;
/// Creates a module with the Git branch in the current directory
///
/// Will display the branch name if the current directory is a git repo
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("git_branch");
let config = GitBranchConfig::try_load(module.config);
let truncation_symbol = get_first_grapheme(config.truncation_symbol);
let len = if config.truncation_length <= 0 {
log::warn!(
"\"truncation_length\" should be a positive value, found {}",
config.truncation_length
);
usize::MAX
} else {
config.truncation_length as usize
};
let repo = context.get_repo().ok()?;
let gix_repo = repo.open();
if config.ignore_bare_repo && gix_repo.is_bare() {
return None;
}
// Get branch and remote information
let (branch_name, remote_branch, remote_name) = if uses_reftables(&gix_repo) {
// Use git executable for branch information
match get_branch_info_from_git(context, repo) {
Some((branch, remote_branch)) => {
// Successfully got branch name, parse upstream into remote_name and remote_branch
let remote_name = remote_branch
.as_ref()
.map(|remote_branch| {
find_longest_matching_remote_name(
remote_branch.as_ref(),
&gix_repo.remote_names(),
)
})
.unwrap_or_default();
(
branch.shorten().to_string(),
remote_branch.zip(remote_name.as_deref()).map(
|(remote_branch, remote_name)| {
remote_branch
.shorten()
.to_str_lossy()
.strip_prefix(remote_name)
.expect("remote name determined by finding it as prefix before")
.trim_start_matches("/")
.to_string()
},
),
remote_name,
)
}
None => {
// get_branch_info_from_git returns None when:
// 1. HEAD is detached (git symbolic-ref fails)
// 2. git command fails for other reasons (corrupted repo, missing git, etc.)
// In both cases, if only_attached is set, we should return None
if config.only_attached {
return None;
}
// Fallback to HEAD for detached state or when branch can't be determined
("HEAD".to_string(), None, None)
}
}
} else {
if config.only_attached && gix_repo.head().ok()?.is_detached() {
return None;
}
let branch = repo.branch.clone().unwrap_or_else(|| "HEAD".to_string());
let (remote_branch, remote_name) = if let Some(remote) = repo.remote.as_ref() {
(remote.branch.clone(), remote.name.clone())
} else {
(None, None)
};
(branch, remote_branch, remote_name)
};
if config
.ignore_branches
.iter()
.any(|&ignored| branch_name.eq(ignored))
{
return None;
}
let mut graphemes: Vec<&str> = branch_name.graphemes(true).collect();
let remote_branch_string = remote_branch.unwrap_or_default();
let mut remote_branch_graphemes: Vec<&str> = remote_branch_string.graphemes(true).collect();
let remote_name_string = remote_name.unwrap_or_default();
let mut remote_name_graphemes: Vec<&str> = remote_name_string.graphemes(true).collect();
// Truncate fields if need be
for e in &mut [
&mut graphemes,
&mut remote_branch_graphemes,
&mut remote_name_graphemes,
] {
let e = &mut **e;
let trunc_len = len.min(e.len());
if trunc_len < e.len() {
// The truncation symbol should only be added if we truncate
e[trunc_len] = truncation_symbol;
e.truncate(trunc_len + 1);
}
}
let show_remote = config.always_show_remote
|| (!graphemes.eq(&remote_branch_graphemes) && !remote_branch_graphemes.is_empty());
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,
})
.map(|variable| match variable {
"branch" => Some(Ok(graphemes.concat())),
"remote_branch" => {
if show_remote && !remote_branch_graphemes.is_empty() {
Some(Ok(remote_branch_graphemes.concat()))
} else {
None
}
}
"remote_name" => {
if show_remote && !remote_name_graphemes.is_empty() {
Some(Ok(remote_name_graphemes.concat()))
} else {
None
}
}
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `git_branch`: \n{error}");
return None;
}
});
Some(module)
}
/// Given `remote_names`, find the longest matching remote name in `remote_ref_name` and return it.
fn find_longest_matching_remote_name(
remote_ref_name: &gix::refs::FullNameRef,
remote_names: &gix::remote::Names<'_>,
) -> Option<String> {
let (category, shorthand_name) = remote_ref_name.category_and_short_name()?;
if !matches!(category, gix::refs::Category::RemoteBranch) {
return None;
}
let longest_remote = remote_names
.iter()
.rfind(|reference_name| shorthand_name.starts_with(reference_name))?;
Some(longest_remote.to_string())
}
/// Get branch information using the git executable.
/// Returns `None` if not on a branch (detached HEAD) or if the git command fails.
fn get_branch_info_from_git(
context: &Context,
repo: &Repo,
) -> Option<(gix::refs::FullName, Option<gix::refs::FullName>)> {
// Get current branch name using git symbolic-ref
let branch_output = repo.exec_git(context, ["symbolic-ref", "HEAD"])?;
// Check if the command was successful (exit code 0)
// symbolic-ref returns non-zero exit code when HEAD is detached
let branch_name = branch_output.stdout.trim();
if branch_name.is_empty() {
return None;
}
let branch_name: gix::refs::FullName = branch_name.try_into().ok()?;
// Get upstream tracking branch using git for-each-ref
let upstream_output = repo.exec_git(
context,
[
"for-each-ref",
"--format=%(upstream)",
branch_name.as_bstr().to_str_lossy().as_ref(),
],
)?;
let upstream = upstream_output.stdout.trim();
let remote_info = if upstream.is_empty() {
None
} else {
upstream.try_into().ok()
};
Some((branch_name, remote_info))
}
fn get_first_grapheme(text: &str) -> &str {
UnicodeSegmentation::graphemes(text, true)
.next()
.unwrap_or("")
}
#[cfg(test)]
mod tests {
use nu_ansi_term::Color;
use std::io;
use crate::test::{FixtureProvider, ModuleRenderer, fixture_repo};
use crate::utils::create_command;
const NORMAL_AND_REFTABLE: [FixtureProvider; 2] =
[FixtureProvider::Git, FixtureProvider::GitReftable];
const BARE_AND_REFTABLE: [FixtureProvider; 2] =
[FixtureProvider::GitBare, FixtureProvider::GitBareReftable];
#[test]
fn show_nothing_on_empty_dir() -> io::Result<()> {
let repo_dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("git_branch")
.path(repo_dir.path())
.collect();
let expected = None;
assert_eq!(expected, actual);
repo_dir.close()
}
#[test]
fn test_changed_truncation_symbol() -> io::Result<()> {
test_truncate_length_with_config(
"1337_hello_world",
15,
"1337_hello_worl",
"%",
"truncation_symbol = \"%\"",
)
}
#[test]
fn test_no_truncation_symbol() -> io::Result<()> {
test_truncate_length_with_config(
"1337_hello_world",
15,
"1337_hello_worl",
"",
"truncation_symbol = \"\"",
)
}
#[test]
fn test_multi_char_truncation_symbol() -> io::Result<()> {
test_truncate_length_with_config(
"1337_hello_world",
15,
"1337_hello_worl",
"a",
"truncation_symbol = \"apple\"",
)
}
#[test]
fn test_ascii_boundary_below() -> io::Result<()> {
test_truncate_length("1337_hello_world", 15, "1337_hello_worl", "…")
}
#[test]
fn test_ascii_boundary_on() -> io::Result<()> {
test_truncate_length("1337_hello_world", 16, "1337_hello_world", "")
}
#[test]
fn test_ascii_boundary_above() -> io::Result<()> {
test_truncate_length("1337_hello_world", 17, "1337_hello_world", "")
}
#[test]
fn test_one() -> io::Result<()> {
test_truncate_length("1337_hello_world", 1, "1", "…")
}
#[test]
fn test_zero() -> io::Result<()> {
test_truncate_length("1337_hello_world", 0, "1337_hello_world", "")
}
#[test]
fn test_negative() -> io::Result<()> {
test_truncate_length("1337_hello_world", -1, "1337_hello_world", "")
}
#[test]
fn test_hindi_truncation() -> io::Result<()> {
test_truncate_length("नमस्ते", 2, "नम", "…")
}
#[test]
fn test_hindi_truncation2() -> io::Result<()> {
test_truncate_length("नमस्त", 2, "नम", "…")
}
#[test]
fn test_japanese_truncation() -> io::Result<()> {
test_truncate_length("がんばってね", 4, "がんばっ", "…")
}
#[test]
fn test_format_no_branch() -> io::Result<()> {
test_format("1337_hello_world", "no_branch", "", "no_branch")
}
#[test]
fn test_format_just_branch_name() -> io::Result<()> {
test_format("1337_hello_world", "$branch", "", "1337_hello_world")
}
#[test]
fn test_format_just_branch_name_color() -> io::Result<()> {
test_format(
"1337_hello_world",
"[$branch](bold blue)",
"",
Color::Blue.bold().paint("1337_hello_world").to_string(),
)
}
#[test]
fn test_format_mixed_colors() -> io::Result<()> {
test_format(
"1337_hello_world",
"branch: [$branch](bold blue) [THE COLORS](red) ",
"",
format!(
"branch: {} {} ",
Color::Blue.bold().paint("1337_hello_world"),
Color::Red.paint("THE COLORS")
),
)
}
#[test]
fn test_format_symbol_style() -> io::Result<()> {
test_format(
"1337_hello_world",
"$symbol[$branch]($style)",
r#"
symbol = "git: "
style = "green"
"#,
format!("git: {}", Color::Green.paint("1337_hello_world"),),
)
}
#[test]
fn test_works_with_unborn_default_branch() -> io::Result<()> {
for mode in NORMAL_AND_REFTABLE {
let repo_dir = tempfile::tempdir()?;
create_command("git")?
.arg("init")
.args(maybe_reftable_format(mode))
.current_dir(&repo_dir)
.output()?;
create_command("git")?
.args(["symbolic-ref", "HEAD", "refs/heads/main"])
.current_dir(&repo_dir)
.output()?;
let actual = ModuleRenderer::new("git_branch")
.path(repo_dir.path())
.collect();
let expected = Some(format!(
"on {} ",
Color::Purple.bold().paint(format!("\u{e0a0} {}", "main")),
));
assert_eq!(expected, actual);
repo_dir.close()?;
}
Ok(())
}
#[test]
fn test_render_branch_only_attached_on_branch() -> io::Result<()> {
for mode in NORMAL_AND_REFTABLE {
let repo_dir = fixture_repo(mode)?;
create_command("git")?
.args(["checkout", "-b", "test_branch"])
.current_dir(repo_dir.path())
.output()?;
let actual = ModuleRenderer::new("git_branch")
.config(toml::toml! {
[git_branch]
only_attached = true
})
.path(repo_dir.path())
.collect();
let expected = Some(format!(
"on {} ",
Color::Purple
.bold()
.paint(format!("\u{e0a0} {}", "test_branch")),
));
assert_eq!(expected, actual);
repo_dir.close()?;
}
Ok(())
}
#[test]
fn test_render_branch_only_attached_on_detached() -> io::Result<()> {
for mode in NORMAL_AND_REFTABLE {
let repo_dir = fixture_repo(mode)?;
create_command("git")?
.args(["checkout", "@~1"])
.current_dir(repo_dir.path())
.output()?;
let actual = ModuleRenderer::new("git_branch")
.config(toml::toml! {
[git_branch]
only_attached = true
})
.path(repo_dir.path())
.collect();
let expected = None;
assert_eq!(expected, actual);
repo_dir.close()?;
}
Ok(())
}
#[test]
fn test_works_in_bare_repo() -> io::Result<()> {
for mode in NORMAL_AND_REFTABLE {
let repo_dir = tempfile::tempdir()?;
create_command("git")?
.arg("init")
.args(maybe_reftable_format(mode))
.arg("--bare")
.current_dir(&repo_dir)
.output()?;
create_command("git")?
.args(["symbolic-ref", "HEAD", "refs/heads/main"])
.current_dir(&repo_dir)
.output()?;
let actual = ModuleRenderer::new("git_branch")
.path(repo_dir.path())
.collect();
let expected = Some(format!(
"on {} ",
Color::Purple.bold().paint(format!("\u{e0a0} {}", "main")),
));
assert_eq!(expected, actual);
repo_dir.close()?;
}
Ok(())
}
#[test]
fn test_ignore_branches() -> io::Result<()> {
for mode in NORMAL_AND_REFTABLE {
let repo_dir = fixture_repo(mode)?;
create_command("git")?
.args(["checkout", "-b", "test_branch"])
.current_dir(repo_dir.path())
.output()?;
let actual = ModuleRenderer::new("git_branch")
.config(toml::toml! {
[git_branch]
ignore_branches = ["dummy", "test_branch"]
})
.path(repo_dir.path())
.collect();
let expected = None;
assert_eq!(expected, actual);
repo_dir.close()?;
}
Ok(())
}
#[test]
fn test_ignore_bare_repo() -> io::Result<()> {
for mode in BARE_AND_REFTABLE {
let repo_dir = fixture_repo(mode)?;
let actual = ModuleRenderer::new("git_branch")
.config(toml::toml! {
[git_branch]
ignore_bare_repo = true
})
.path(repo_dir.path())
.collect();
let expected = None;
assert_eq!(expected, actual);
repo_dir.close()?;
}
Ok(())
}
#[test]
fn test_remote() -> io::Result<()> {
for mode in NORMAL_AND_REFTABLE {
let remote_dir = fixture_repo(mode)?;
let repo_dir = fixture_repo(mode)?;
create_command("git")?
.args(["checkout", "-b", "test_branch"])
.current_dir(repo_dir.path())
.output()?;
create_command("git")?
.args(["remote", "add", "--fetch", "remote_repo"])
.arg(remote_dir.path())
.current_dir(repo_dir.path())
.output()?;
create_command("git")?
.args(["branch", "--set-upstream-to", "remote_repo/master"])
.current_dir(repo_dir.path())
.output()?;
let actual = ModuleRenderer::new("git_branch")
.path(repo_dir.path())
.config(toml::toml! {
[git_branch]
format = "$branch(:$remote_name/$remote_branch)"
})
.collect();
let expected = Some("test_branch:remote_repo/master");
assert_eq!(expected, actual.as_deref());
repo_dir.close()?;
remote_dir.close()?;
}
Ok(())
}
#[test]
fn test_branch_fallback_on_detached() -> io::Result<()> {
for mode in NORMAL_AND_REFTABLE {
let repo_dir = fixture_repo(mode)?;
create_command("git")?
.args(["checkout", "@~1"])
.current_dir(repo_dir.path())
.output()?;
let actual = ModuleRenderer::new("git_branch")
.config(toml::toml! {
[git_branch]
format = "$branch"
})
.path(repo_dir.path())
.collect();
let expected = Some("HEAD".into());
assert_eq!(expected, actual);
repo_dir.close()?;
}
Ok(())
}
// This test is not possible until we switch to `git status --porcelain`
// where we can mock the env for the specific git process. This is because
// git2 does not care about our mocking and when we set the real `GIT_DIR`
// variable it will interfere with the other tests.
// #[test]
// fn test_git_dir_env_variable() -> io::Result<()> {let repo_dir =
// tempfile::tempdir()?;
// create_command("git")?
// .args(&["init"])
// .current_dir(&repo_dir)
// .output()?;
// // git2 does not care about our mocking
// std::env::set_var("GIT_DIR", repo_dir.path().join(".git"));
// let actual = ModuleRenderer::new("git_branch").collect();
// std::env::remove_var("GIT_DIR");
// let expected = Some(format!(
// "on {} ",
// Color::Purple.bold().paint(format!("\u{e0a0} {}", "master")),
// ));
// assert_eq!(expected, actual);
// repo_dir.close()
// }
fn test_truncate_length(
branch_name: &str,
truncate_length: i64,
expected_name: &str,
truncation_symbol: &str,
) -> io::Result<()> {
test_truncate_length_with_config(
branch_name,
truncate_length,
expected_name,
truncation_symbol,
"",
)
}
fn test_truncate_length_with_config(
branch_name: &str,
truncate_length: i64,
expected_name: &str,
truncation_symbol: &str,
config_options: &str,
) -> io::Result<()> {
for mode in NORMAL_AND_REFTABLE {
let repo_dir = fixture_repo(mode)?;
create_command("git")?
.args(["checkout", "-b", branch_name])
.current_dir(repo_dir.path())
.output()?;
let actual = ModuleRenderer::new("git_branch")
.config(
toml::from_str(&format!(
"
[git_branch]
truncation_length = {truncate_length}
{config_options}
"
))
.unwrap(),
)
.path(repo_dir.path())
.collect();
let expected = Some(format!(
"on {} ",
Color::Purple
.bold()
.paint(format!("\u{e0a0} {expected_name}{truncation_symbol}")),
));
assert_eq!(expected, actual);
repo_dir.close()?;
}
Ok(())
}
fn test_format<T: Into<String>>(
branch_name: &str,
format: &str,
config_options: &str,
expected: T,
) -> io::Result<()> {
let expected = expected.into();
for mode in NORMAL_AND_REFTABLE {
let repo_dir = fixture_repo(mode)?;
create_command("git")?
.args(["checkout", "-b", branch_name])
.current_dir(repo_dir.path())
.output()?;
let actual = ModuleRenderer::new("git_branch")
.config(
toml::from_str(&format!(
r#"
[git_branch]
format = "{format}"
{config_options}
"#
))
.unwrap(),
)
.path(repo_dir.path())
.collect();
assert_eq!(Some(&expected), actual.as_ref());
repo_dir.close()?;
}
Ok(())
}
fn maybe_reftable_format(provider: FixtureProvider) -> Option<&'static str> {
matches!(provider, FixtureProvider::GitReftable).then(|| "--ref-format=reftable")
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/fossil_metrics.rs | src/modules/fossil_metrics.rs | use regex::Regex;
use super::{Context, Module, ModuleConfig};
use crate::configs::fossil_metrics::FossilMetricsConfig;
use crate::formatter::StringFormatter;
/// Creates a module with currently added/deleted lines in the Fossil check-out in the current
/// directory.
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("fossil_metrics");
let config = FossilMetricsConfig::try_load(module.config);
// As we default to disabled=true, we have to check here after loading our config module,
// before it was only checking against whatever is in the config starship.toml
if config.disabled {
return None;
}
let checkout_db = if cfg!(windows) {
"_FOSSIL_"
} else {
".fslckout"
};
// See if we're in a check-out by scanning upwards for a directory containing the checkout_db file
context
.begin_ancestor_scan()
.set_files(&[checkout_db])
.scan()?;
// Read the total number of added and deleted lines from "fossil diff -i --numstat"
let output = context
.exec_cmd("fossil", &["diff", "-i", "--numstat"])?
.stdout;
let stats = FossilDiff::parse(&output, config.only_nonzero_diffs);
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_style(|variable| match variable {
"added_style" => Some(Ok(config.added_style)),
"deleted_style" => Some(Ok(config.deleted_style)),
_ => None,
})
.map(|variable| match variable {
"added" => Some(Ok(stats.added)),
"deleted" => Some(Ok(stats.deleted)),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `fossil_metrics`:\n{error}");
return None;
}
});
Some(module)
}
/// Represents the parsed output from a Fossil diff with the -i --numstat option enabled.
#[derive(Debug, PartialEq)]
struct FossilDiff<'a> {
added: &'a str,
deleted: &'a str,
}
impl<'a> FossilDiff<'a> {
/// Parses the output of `fossil diff -i --numstat` as a `FossilDiff` struct.
pub fn parse(diff_numstat: &'a str, only_nonzero_diffs: bool) -> Self {
// Fossil formats the last line of the output as "%10d %10d TOTAL over %d changed files\n"
// where the 1st and 2nd placeholders are the number of added and deleted lines respectively
let re = Regex::new(r"^\s*(\d+)\s+(\d+) TOTAL over \d+ changed files?$").unwrap();
let (added, deleted) = diff_numstat
.lines()
.last()
.and_then(|s| re.captures(s))
.and_then(|caps| {
let added = match caps.get(1)?.as_str() {
"0" if only_nonzero_diffs => "",
s => s,
};
let deleted = match caps.get(2)?.as_str() {
"0" if only_nonzero_diffs => "",
s => s,
};
Some((added, deleted))
})
.unwrap_or_default();
Self { added, deleted }
}
}
#[cfg(test)]
mod tests {
use std::io;
use std::path::Path;
use nu_ansi_term::{Color, Style};
use crate::test::{FixtureProvider, ModuleRenderer, fixture_repo};
use super::FossilDiff;
enum Expect<'a> {
Empty,
Added(Option<&'a str>),
AddedStyle(Style),
Deleted(Option<&'a str>),
DeletedStyle(Style),
}
#[test]
fn show_nothing_on_empty_dir() -> io::Result<()> {
let checkout_dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("fossil_metrics")
.path(checkout_dir.path())
.collect();
let expected = None;
assert_eq!(expected, actual);
checkout_dir.close()
}
#[test]
fn test_fossil_metrics_disabled_per_default() -> io::Result<()> {
let tempdir = fixture_repo(FixtureProvider::Fossil)?;
let checkout_dir = tempdir.path();
expect_fossil_metrics_with_config(
checkout_dir,
Some(toml::toml! {
// no "disabled=false" in config!
[fossil_metrics]
only_nonzero_diffs = false
}),
&[Expect::Empty],
);
tempdir.close()
}
#[test]
fn test_fossil_metrics_autodisabled() -> io::Result<()> {
let tempdir = tempfile::tempdir()?;
expect_fossil_metrics_with_config(tempdir.path(), None, &[Expect::Empty]);
tempdir.close()
}
#[test]
fn test_fossil_metrics() -> io::Result<()> {
let tempdir = fixture_repo(FixtureProvider::Fossil)?;
let checkout_dir = tempdir.path();
expect_fossil_metrics_with_config(
checkout_dir,
None,
&[Expect::Added(Some("3")), Expect::Deleted(Some("2"))],
);
tempdir.close()
}
#[test]
fn test_fossil_metrics_subdir() -> io::Result<()> {
let tempdir = fixture_repo(FixtureProvider::Fossil)?;
let checkout_dir = tempdir.path();
expect_fossil_metrics_with_config(
&checkout_dir.join("subdir"),
None,
&[Expect::Added(Some("3")), Expect::Deleted(Some("2"))],
);
tempdir.close()
}
#[test]
fn test_fossil_metrics_configured() -> io::Result<()> {
let tempdir = fixture_repo(FixtureProvider::Fossil)?;
let checkout_dir = tempdir.path();
expect_fossil_metrics_with_config(
checkout_dir,
Some(toml::toml! {
[fossil_metrics]
added_style = "underline blue"
deleted_style = "underline purple"
disabled = false
}),
&[
Expect::Added(Some("3")),
Expect::AddedStyle(Color::Blue.underline()),
Expect::Deleted(Some("2")),
Expect::DeletedStyle(Color::Purple.underline()),
],
);
tempdir.close()
}
#[test]
fn parse_no_changes_discard_zeros() {
let actual = FossilDiff::parse(" 0 0 TOTAL over 0 changed files\n", true);
let expected = FossilDiff {
added: "",
deleted: "",
};
assert_eq!(expected, actual);
}
#[test]
fn parse_no_changes_keep_zeros() {
let actual = FossilDiff::parse(" 0 0 TOTAL over 0 changed files\n", false);
let expected = FossilDiff {
added: "0",
deleted: "0",
};
assert_eq!(expected, actual);
}
#[test]
fn parse_with_changes() {
let actual = FossilDiff::parse(
" 3 2 README.md\n 3 2 TOTAL over 1 changed files\n",
true,
);
let expected = FossilDiff {
added: "3",
deleted: "2",
};
assert_eq!(expected, actual);
}
#[test]
fn parse_single_file() {
let actual = FossilDiff::parse(
" 3 2 README.md\n 3 2 TOTAL over 1 changed file\n",
true,
);
let expected = FossilDiff {
added: "3",
deleted: "2",
};
assert_eq!(expected, actual);
let actual = FossilDiff::parse(
" 3 2 README.md\n 3 2 TOTAL over 1 changed files\n",
true,
);
assert_eq!(expected, actual);
}
#[test]
fn parse_ignore_empty() {
let actual = FossilDiff::parse("", true);
let expected = FossilDiff {
added: "",
deleted: "",
};
assert_eq!(expected, actual);
}
/// Tests output as produced by Fossil v2.3 to v2.14, i.e. without the summary line.
#[test]
fn parse_ignore_when_missing_total_line() {
let actual = FossilDiff::parse(" 3 2 README.md\n", true);
let expected = FossilDiff {
added: "",
deleted: "",
};
assert_eq!(expected, actual);
}
fn expect_fossil_metrics_with_config(
checkout_dir: &Path,
config: Option<toml::Table>,
expectations: &[Expect],
) {
let actual = ModuleRenderer::new("fossil_metrics")
.path(checkout_dir.to_str().unwrap())
.config(config.unwrap_or_else(|| {
toml::toml! {
[fossil_metrics]
disabled = false
}
}))
.collect();
let mut expect_added = Some("3");
let mut expect_added_style = Color::Green.bold();
let mut expect_deleted = Some("2");
let mut expect_deleted_style = Color::Red.bold();
for expect in expectations {
match expect {
Expect::Empty => {
assert_eq!(None, actual);
return;
}
Expect::Added(added) => expect_added = *added,
Expect::AddedStyle(style) => expect_added_style = *style,
Expect::Deleted(deleted) => expect_deleted = *deleted,
Expect::DeletedStyle(style) => expect_deleted_style = *style,
}
}
let expected = Some(format!(
"{}{}",
expect_added
.map(|added| format!("{} ", expect_added_style.paint(format!("+{added}"))))
.unwrap_or_default(),
expect_deleted
.map(|deleted| format!("{} ", expect_deleted_style.paint(format!("-{deleted}"))))
.unwrap_or_default(),
));
assert_eq!(expected, actual);
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/xmake.rs | src/modules/xmake.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::xmake::XMakeConfig;
use crate::formatter::{StringFormatter, VersionFormatter};
/// Creates a module with the current `XMake` version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("xmake");
let config = XMakeConfig::try_load(module.config);
let is_xmake_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_xmake_project {
return None;
}
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|variable, _| match variable {
"symbol" => Some(config.symbol),
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map(|variable| match variable {
"version" => {
let xmake_version =
parse_xmake_version(&context.exec_cmd("xmake", &["--version"])?.stdout)?;
VersionFormatter::format_module_version(
module.get_name(),
&xmake_version,
config.version_format,
)
.map(Ok)
}
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `xmake`: \n{error}");
return None;
}
});
Some(module)
}
fn parse_xmake_version(xmake_version: &str) -> Option<String> {
Some(
xmake_version.
// split into ["xmake", "v3.0.0+HEAD.0db4fe6", ".."]
split_whitespace().
// get "v3.0.0+HEAD.0db4fe6"
nth(1)?.
// remove the "v" prefix
trim_start_matches('v').
// remove "+HEAD.0db4fe6" suffix
split('+').next()?.
to_string(),
)
}
#[cfg(test)]
mod tests {
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
use std::fs::File;
use std::io;
#[test]
fn folder_without_xmake_lists() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("xmake").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_xmake_lists() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("xmake.lua"))?.sync_all()?;
let actual = ModuleRenderer::new("xmake").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Green.bold().paint("△ v2.9.5 ")));
assert_eq!(expected, actual);
dir.close()
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/gcloud.rs | src/modules/gcloud.rs | use ini::Ini;
use std::borrow::Cow;
use std::path::Path;
use std::path::PathBuf;
use std::sync::{LazyLock, OnceLock};
use super::{Context, Module, ModuleConfig};
use crate::configs::gcloud::GcloudConfig;
use crate::formatter::StringFormatter;
use crate::utils;
type Account<'a> = (&'a str, Option<&'a str>);
struct GcloudContext {
config_name: String,
config_path: PathBuf,
config: OnceLock<Option<Ini>>,
}
impl<'a> GcloudContext {
pub fn new(config_name: &str, config_path: &Path) -> Self {
Self {
config_name: config_name.to_string(),
config_path: PathBuf::from(config_path),
config: OnceLock::default(),
}
}
fn get_config(&self) -> Option<&Ini> {
self.config
.get_or_init(|| Ini::load_from_file(&self.config_path).ok())
.as_ref()
}
pub fn get_account(&'a self) -> Option<Account<'a>> {
let config = self.get_config()?;
let account = config.section(Some("core"))?.get("account")?;
let mut segments = account.splitn(2, '@');
Some((segments.next()?, segments.next()))
}
pub fn get_project(&'a self) -> Option<&'a str> {
let config = self.get_config()?;
config.section(Some("core"))?.get("project")
}
pub fn get_region(&'a self) -> Option<&'a str> {
let config = self.get_config()?;
config.section(Some("compute"))?.get("region")
}
}
fn get_current_config(context: &Context) -> Option<(String, PathBuf)> {
let config_dir = get_config_dir(context)?;
let name = get_active_config(context, &config_dir)?;
let path = config_dir
.join("configurations")
.join(format!("config_{name}"));
Some((name, path))
}
fn get_config_dir(context: &Context) -> Option<PathBuf> {
context
.get_env("CLOUDSDK_CONFIG")
.map(PathBuf::from)
.or_else(|| {
let home = context.get_home()?;
Some(home.join(".config").join("gcloud"))
})
}
fn get_active_config(context: &Context, config_dir: &Path) -> Option<String> {
context.get_env("CLOUDSDK_ACTIVE_CONFIG_NAME").or_else(|| {
let path = config_dir.join("active_config");
utils::read_file(path)
.ok()?
.lines()
.next()
.map(String::from)
})
}
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("gcloud");
let config: GcloudConfig = GcloudConfig::try_load(module.config);
if !(context.detect_env_vars(&config.detect_env_vars)) {
return None;
}
let (config_name, config_path) = get_current_config(context)?;
if config_name == "NONE" {
return None;
}
let gcloud_context = GcloudContext::new(&config_name, &config_path);
let account: LazyLock<Option<Account<'_>>, _> = LazyLock::new(|| gcloud_context.get_account());
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|variable, _| match variable {
"symbol" => Some(config.symbol),
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map(|variable| match variable {
"account" => account
.map(|(account, _)| account)
.map(Cow::Borrowed)
.map(Ok),
"domain" => account
.and_then(|(_, domain)| domain)
.map(Cow::Borrowed)
.map(Ok),
"region" => gcloud_context
.get_region()
.map(|region| config.region_aliases.get(region).copied().unwrap_or(region))
.map(Cow::Borrowed)
.map(Ok),
"project" => context
.get_env("CLOUDSDK_CORE_PROJECT")
.map(Cow::Owned)
.or_else(|| gcloud_context.get_project().map(Cow::Borrowed))
.map(|project| {
config
.project_aliases
.get(project.as_ref())
.copied()
.map_or(project, Cow::Borrowed)
})
.map(Ok),
"active" => Some(Ok(Cow::Borrowed(&gcloud_context.config_name))),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::error!("Error in module `gcloud`: \n{error}");
return None;
}
});
Some(module)
}
#[cfg(test)]
mod tests {
use std::fs::{File, create_dir};
use std::io::{self, Write};
use nu_ansi_term::Color;
use crate::test::ModuleRenderer;
#[test]
fn account_set_but_not_shown_because_of_detect_env_vars() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let active_config_path = dir.path().join("active_config");
let mut active_config_file = File::create(active_config_path)?;
active_config_file.write_all(b"default")?;
// check if this config would lead to the module being rendered
assert_eq!(
ModuleRenderer::new("gcloud")
.env("CLOUDSDK_CONFIG", dir.path().to_string_lossy())
.config(toml::toml! {
[gcloud]
format = "$active"
})
.collect(),
Some("default".into())
);
// when we set `detect_env_vars` now, the module is empty
assert_eq!(
ModuleRenderer::new("gcloud")
.env("CLOUDSDK_CONFIG", dir.path().to_string_lossy())
.config(toml::toml! {
[gcloud]
format = "$active"
detect_env_vars = ["SOME_TEST_VAR"]
})
.collect(),
None
);
// and when the environment variable has a value, the module is shown
assert_eq!(
ModuleRenderer::new("gcloud")
.env("CLOUDSDK_CONFIG", dir.path().to_string_lossy())
.env("SOME_TEST_VAR", "1")
.config(toml::toml! {
[gcloud]
format = "$active"
detect_env_vars = ["SOME_TEST_VAR"]
})
.collect(),
Some("default".into())
);
dir.close()
}
#[test]
fn account_set() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let active_config_path = dir.path().join("active_config");
let mut active_config_file = File::create(active_config_path)?;
active_config_file.write_all(b"default")?;
create_dir(dir.path().join("configurations"))?;
let config_default_path = dir.path().join("configurations").join("config_default");
let mut config_default_file = File::create(config_default_path)?;
config_default_file.write_all(
b"\
[core]
account = foo@example.com
",
)?;
let actual = ModuleRenderer::new("gcloud")
.env("CLOUDSDK_CONFIG", dir.path().to_string_lossy())
.collect();
let expected = Some(format!(
"on {} ",
Color::Blue.bold().paint("☁️ foo@example.com")
));
assert_eq!(actual, expected);
dir.close()
}
#[test]
fn account_with_custom_format_set() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let active_config_path = dir.path().join("active_config");
let mut active_config_file = File::create(active_config_path)?;
active_config_file.write_all(b"default")?;
create_dir(dir.path().join("configurations"))?;
let config_default_path = dir.path().join("configurations").join("config_default");
let mut config_default_file = File::create(config_default_path)?;
config_default_file.write_all(
b"\
[core]
account = foo@example.com
",
)?;
let actual = ModuleRenderer::new("gcloud")
.env("CLOUDSDK_CONFIG", dir.path().to_string_lossy())
.config(toml::toml! {
[gcloud]
format = "on [$symbol$account(\\($region\\))]($style) "
})
.collect();
let expected = Some(format!("on {} ", Color::Blue.bold().paint("☁️ foo")));
assert_eq!(actual, expected);
dir.close()
}
#[test]
fn account_and_region_set() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let active_config_path = dir.path().join("active_config");
let mut active_config_file = File::create(active_config_path)?;
active_config_file.write_all(b"default")?;
create_dir(dir.path().join("configurations"))?;
let config_default_path = dir.path().join("configurations").join("config_default");
let mut config_default_file = File::create(config_default_path)?;
config_default_file.write_all(
b"\
[core]
account = foo@example.com
[compute]
region = us-central1
",
)?;
let actual = ModuleRenderer::new("gcloud")
.env("CLOUDSDK_CONFIG", dir.path().to_string_lossy())
.collect();
let expected = Some(format!(
"on {} ",
Color::Blue.bold().paint("☁️ foo@example.com(us-central1)")
));
assert_eq!(actual, expected);
dir.close()
}
#[test]
fn account_and_region_set_with_alias() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let active_config_path = dir.path().join("active_config");
let mut active_config_file = File::create(active_config_path)?;
active_config_file.write_all(b"default")?;
create_dir(dir.path().join("configurations"))?;
let config_default_path = dir.path().join("configurations").join("config_default");
let mut config_default_file = File::create(config_default_path)?;
config_default_file.write_all(
b"\
[core]
account = foo@example.com
[compute]
region = us-central1
",
)?;
let actual = ModuleRenderer::new("gcloud")
.env("CLOUDSDK_CONFIG", dir.path().to_string_lossy())
.config(toml::toml! {
[gcloud.region_aliases]
us-central1 = "uc1"
})
.collect();
let expected = Some(format!(
"on {} ",
Color::Blue.bold().paint("☁️ foo@example.com(uc1)")
));
assert_eq!(actual, expected);
dir.close()
}
#[test]
fn active_set() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let active_config_path = dir.path().join("active_config");
let mut active_config_file = File::create(active_config_path)?;
active_config_file.write_all(b"default1")?;
let actual = ModuleRenderer::new("gcloud")
.env("CLOUDSDK_CONFIG", dir.path().to_string_lossy())
.config(toml::toml! {
[gcloud]
format = "on [$symbol$active]($style) "
})
.collect();
let expected = Some(format!("on {} ", Color::Blue.bold().paint("☁️ default1")));
assert_eq!(actual, expected);
dir.close()
}
#[test]
fn project_set() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let active_config_path = dir.path().join("active_config");
let mut active_config_file = File::create(active_config_path)?;
active_config_file.write_all(b"default")?;
create_dir(dir.path().join("configurations"))?;
let config_default_path = dir.path().join("configurations").join("config_default");
let mut config_default_file = File::create(config_default_path)?;
config_default_file.write_all(
b"\
[core]
project = abc
",
)?;
let actual = ModuleRenderer::new("gcloud")
.env("CLOUDSDK_CONFIG", dir.path().to_string_lossy())
.config(toml::toml! {
[gcloud]
format = "on [$symbol$project]($style) "
})
.collect();
let expected = Some(format!("on {} ", Color::Blue.bold().paint("☁️ abc")));
assert_eq!(actual, expected);
dir.close()
}
#[test]
fn project_set_in_env() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let active_config_path = dir.path().join("active_config");
let mut active_config_file = File::create(active_config_path)?;
active_config_file.write_all(b"default")?;
create_dir(dir.path().join("configurations"))?;
let config_default_path = dir.path().join("configurations").join("config_default");
let mut config_default_file = File::create(config_default_path)?;
config_default_file.write_all(
b"\
[core]
project = abc
",
)?;
let actual = ModuleRenderer::new("gcloud")
.env("CLOUDSDK_CORE_PROJECT", "env_project")
.env("CLOUDSDK_CONFIG", dir.path().to_string_lossy())
.config(toml::toml! {
[gcloud]
format = "on [$symbol$project]($style) "
})
.collect();
let expected = Some(format!(
"on {} ",
Color::Blue.bold().paint("☁️ env_project")
));
assert_eq!(actual, expected);
dir.close()
}
#[test]
fn project_set_with_alias() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let active_config_path = dir.path().join("active_config");
let mut active_config_file = File::create(active_config_path)?;
active_config_file.write_all(b"default")?;
create_dir(dir.path().join("configurations"))?;
let config_default_path = dir.path().join("configurations").join("config_default");
let mut config_default_file = File::create(config_default_path)?;
config_default_file.write_all(
b"\
[core]
project = very-long-project-name
",
)?;
let actual = ModuleRenderer::new("gcloud")
.env("CLOUDSDK_CONFIG", dir.path().to_string_lossy())
.config(toml::toml! {
[gcloud]
format = "on [$symbol$project]($style) "
[gcloud.project_aliases]
very-long-project-name = "vlpn"
})
.collect();
let expected = Some(format!("on {} ", Color::Blue.bold().paint("☁️ vlpn")));
assert_eq!(actual, expected);
dir.close()
}
#[test]
fn region_not_set_with_display_region() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("gcloud")
.env("CLOUDSDK_CONFIG", dir.path().to_string_lossy())
.config(toml::toml! {
[gcloud]
format = "on [$symbol$region]($style) "
})
.collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn no_active_config() {
let actual = ModuleRenderer::new("gcloud")
.env("CLOUDSDK_ACTIVE_CONFIG_NAME", "NONE")
.collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn active_config_manually_overridden() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let active_config_path = dir.path().join("active_config");
let mut active_config_file = File::create(active_config_path)?;
active_config_file.write_all(b"default")?;
create_dir(dir.path().join("configurations"))?;
let config_default_path = dir.path().join("configurations").join("config_default");
let mut config_default_file = File::create(config_default_path)?;
config_default_file.write_all(
b"\
[core]
project = default
",
)?;
let config_overridden_path = dir.path().join("configurations").join("config_overridden");
let mut config_overridden_file = File::create(config_overridden_path)?;
config_overridden_file.write_all(
b"\
[core]
project = overridden
",
)?;
let actual = ModuleRenderer::new("gcloud")
.env("CLOUDSDK_CONFIG", dir.path().to_string_lossy())
.env("CLOUDSDK_ACTIVE_CONFIG_NAME", "overridden")
.config(toml::toml! {
[gcloud]
format = "on [$symbol$project]($style) "
})
.collect();
#[rustfmt::skip]
let expected = Some(format!(
"on {} ",
Color::Blue.bold().paint("☁️ overridden")
));
assert_eq!(actual, expected);
dir.close()
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/mod.rs | src/modules/mod.rs | // While adding out new module add out module to src/module.rs ALL_MODULES const array also.
mod aws;
mod azure;
mod buf;
mod bun;
mod c;
mod cc;
mod character;
mod cmake;
mod cmd_duration;
mod cobol;
mod conda;
mod container;
mod cpp;
mod crystal;
pub mod custom;
mod daml;
mod dart;
mod deno;
mod directory;
mod direnv;
mod docker_context;
mod dotnet;
mod elixir;
mod elm;
mod env_var;
mod erlang;
mod fennel;
mod fill;
mod fortran;
mod fossil_branch;
mod fossil_metrics;
mod gcloud;
mod git_branch;
mod git_commit;
mod git_metrics;
mod git_state;
pub(crate) mod git_status;
mod gleam;
mod golang;
mod gradle;
mod guix_shell;
mod haskell;
mod haxe;
mod helm;
mod hg_branch;
mod hg_state;
mod hostname;
mod java;
mod jobs;
mod julia;
mod kotlin;
mod kubernetes;
mod line_break;
mod localip;
mod lua;
mod memory_usage;
mod meson;
mod mise;
mod mojo;
mod nats;
mod netns;
mod nim;
mod nix_shell;
mod nodejs;
mod ocaml;
mod odin;
mod opa;
mod openstack;
mod os;
mod package;
mod perl;
mod php;
mod pijul_channel;
mod pixi;
mod pulumi;
mod purescript;
mod python;
mod quarto;
mod raku;
mod red;
mod rlang;
mod ruby;
mod rust;
mod scala;
mod shell;
mod shlvl;
mod singularity;
mod solidity;
mod spack;
mod status;
mod sudo;
mod swift;
mod terraform;
mod time;
mod username;
mod utils;
mod vagrant;
mod vcsh;
mod vlang;
mod xmake;
mod zig;
#[cfg(feature = "battery")]
mod battery;
mod typst;
#[cfg(feature = "battery")]
pub use self::battery::{BatteryInfoProvider, BatteryInfoProviderImpl};
use crate::config::ModuleConfig;
use crate::context::{Context, Detected, Shell};
use crate::module::Module;
use std::time::Instant;
pub fn handle<'a>(module: &str, context: &'a Context) -> Option<Module<'a>> {
let start: Instant = Instant::now();
let mut m: Option<Module> = {
match module {
// Keep these ordered alphabetically.
// Default ordering is handled in configs/starship_root.rs
"aws" => aws::module(context),
"azure" => azure::module(context),
#[cfg(feature = "battery")]
"battery" => battery::module(context),
"buf" => buf::module(context),
"bun" => bun::module(context),
"c" => c::module(context),
"character" => character::module(context),
"cmake" => cmake::module(context),
"cmd_duration" => cmd_duration::module(context),
"cobol" => cobol::module(context),
"conda" => conda::module(context),
"container" => container::module(context),
"cpp" => cpp::module(context),
"daml" => daml::module(context),
"dart" => dart::module(context),
"deno" => deno::module(context),
"directory" => directory::module(context),
"direnv" => direnv::module(context),
"docker_context" => docker_context::module(context),
"dotnet" => dotnet::module(context),
"elixir" => elixir::module(context),
"elm" => elm::module(context),
"erlang" => erlang::module(context),
"env_var" => env_var::module(None, context),
"fennel" => fennel::module(context),
"fill" => fill::module(context),
"fortran" => fortran::module(context),
"fossil_branch" => fossil_branch::module(context),
"fossil_metrics" => fossil_metrics::module(context),
"gcloud" => gcloud::module(context),
"git_branch" => git_branch::module(context),
"git_commit" => git_commit::module(context),
"git_metrics" => git_metrics::module(context),
"git_state" => git_state::module(context),
"git_status" => git_status::module(context),
"gleam" => gleam::module(context),
"golang" => golang::module(context),
"gradle" => gradle::module(context),
"guix_shell" => guix_shell::module(context),
"haskell" => haskell::module(context),
"haxe" => haxe::module(context),
"helm" => helm::module(context),
"hg_branch" => hg_branch::module(context),
"hg_state" => hg_state::module(context),
"hostname" => hostname::module(context),
"java" => java::module(context),
"jobs" => jobs::module(context),
"julia" => julia::module(context),
"kotlin" => kotlin::module(context),
"kubernetes" => kubernetes::module(context),
"line_break" => line_break::module(context),
"localip" => localip::module(context),
"lua" => lua::module(context),
"memory_usage" => memory_usage::module(context),
"meson" => meson::module(context),
"mise" => mise::module(context),
"mojo" => mojo::module(context),
"nats" => nats::module(context),
"netns" => netns::module(context),
"nim" => nim::module(context),
"nix_shell" => nix_shell::module(context),
"nodejs" => nodejs::module(context),
"ocaml" => ocaml::module(context),
"odin" => odin::module(context),
"opa" => opa::module(context),
"openstack" => openstack::module(context),
"os" => os::module(context),
"package" => package::module(context),
"perl" => perl::module(context),
"php" => php::module(context),
"pijul_channel" => pijul_channel::module(context),
"pixi" => pixi::module(context),
"pulumi" => pulumi::module(context),
"purescript" => purescript::module(context),
"python" => python::module(context),
"quarto" => quarto::module(context),
"raku" => raku::module(context),
"rlang" => rlang::module(context),
"red" => red::module(context),
"ruby" => ruby::module(context),
"rust" => rust::module(context),
"scala" => scala::module(context),
"shell" => shell::module(context),
"shlvl" => shlvl::module(context),
"singularity" => singularity::module(context),
"solidity" => solidity::module(context),
"spack" => spack::module(context),
"swift" => swift::module(context),
"status" => status::module(context),
"sudo" => sudo::module(context),
"terraform" => terraform::module(context),
"time" => time::module(context),
"typst" => typst::module(context),
"crystal" => crystal::module(context),
"username" => username::module(context),
"vlang" => vlang::module(context),
"vagrant" => vagrant::module(context),
"vcsh" => vcsh::module(context),
"xmake" => xmake::module(context),
"zig" => zig::module(context),
env if env.starts_with("env_var.") => {
env_var::module(env.strip_prefix("env_var."), context)
}
custom if custom.starts_with("custom.") => {
// SAFETY: We just checked that the module starts with "custom."
custom::module(custom.strip_prefix("custom.").unwrap(), context)
}
_ => {
eprintln!(
"Error: Unknown module {module}. Use starship module --list to list out all supported modules."
);
None
}
}
};
let elapsed = start.elapsed();
log::trace!("Took {elapsed:?} to compute module {module:?}");
if elapsed.as_millis() >= 1 {
// If we take less than 1ms to compute a None, then we will not return a module at all
// if we have a module: default duration is 0 so no need to change it
// if we took more than 1ms we want to report that and so--in case we have None currently--
// need to create an empty module just to hold the duration for that case
m.get_or_insert_with(|| context.new_module(module)).duration = elapsed;
}
m
}
pub fn description(module: &str) -> &'static str {
match module {
"aws" => "The current AWS region and profile",
"azure" => "The current Azure subscription",
"battery" => "The current charge of the device's battery and its current charging status",
"buf" => "The currently installed version of the Buf CLI",
"bun" => "The currently installed version of the Bun",
"c" => "Your C compiler type",
"character" => {
"A character (usually an arrow) beside where the text is entered in your terminal"
}
"cmake" => "The currently installed version of CMake",
"cmd_duration" => "How long the last command took to execute",
"cobol" => "The currently installed version of COBOL/GNUCOBOL",
"conda" => "The current conda environment, if $CONDA_DEFAULT_ENV is set",
"container" => "The container indicator, if inside a container.",
"cpp" => "your cpp compiler type",
"crystal" => "The currently installed version of Crystal",
"daml" => "The Daml SDK version of your project",
"dart" => "The currently installed version of Dart",
"deno" => "The currently installed version of Deno",
"directory" => "The current working directory",
"direnv" => "The currently applied direnv file",
"docker_context" => "The current docker context",
"dotnet" => "The relevant version of the .NET Core SDK for the current directory",
"elixir" => "The currently installed versions of Elixir and OTP",
"elm" => "The currently installed version of Elm",
"erlang" => "Current OTP version",
"fennel" => "The currently installed version of Fennel",
"fill" => "Fills the remaining space on the line with a pad string",
"fortran" => "The currently used version of Fortran",
"fossil_branch" => "The active branch of the check-out in your current directory",
"fossil_metrics" => "The currently added/deleted lines in your check-out",
"gcloud" => "The current GCP client configuration",
"git_branch" => "The active branch of the repo in your current directory",
"git_commit" => "The active commit (and tag if any) of the repo in your current directory",
"git_metrics" => "The currently added/deleted lines in your repo",
"git_state" => "The current git operation, and it's progress",
"git_status" => "Symbol representing the state of the repo",
"gleam" => "The currently installed version of Gleam",
"golang" => "The currently installed version of Golang",
"gradle" => "The currently installed version of Gradle",
"guix_shell" => "The guix-shell environment",
"haskell" => "The selected version of the Haskell toolchain",
"haxe" => "The currently installed version of Haxe",
"helm" => "The currently installed version of Helm",
"hg_branch" => "The active branch and topic of the repo in your current directory",
"hg_state" => "The current hg operation",
"hostname" => "The system hostname",
"java" => "The currently installed version of Java",
"jobs" => "The current number of jobs running",
"julia" => "The currently installed version of Julia",
"kotlin" => "The currently installed version of Kotlin",
"kubernetes" => "The current Kubernetes context name and, if set, the namespace",
"line_break" => "Separates the prompt into two lines",
"localip" => "The currently assigned ipv4 address",
"lua" => "The currently installed version of Lua",
"memory_usage" => "Current system memory and swap usage",
"meson" => {
"The current Meson environment, if $MESON_DEVENV and $MESON_PROJECT_NAME are set"
}
"mise" => "The current mise status",
"mojo" => "The currently installed version of Mojo",
"nats" => "The current NATS context",
"netns" => "The current network namespace",
"nim" => "The currently installed version of Nim",
"nix_shell" => "The nix-shell environment",
"nodejs" => "The currently installed version of NodeJS",
"ocaml" => "The currently installed version of OCaml",
"odin" => "The currently installed version of Odin",
"opa" => "The currently installed version of Open Platform Agent",
"openstack" => "The current OpenStack cloud and project",
"os" => "The current operating system",
"package" => "The package version of the current directory's project",
"perl" => "The currently installed version of Perl",
"php" => "The currently installed version of PHP",
"pijul_channel" => "The current channel of the repo in the current directory",
"pixi" => {
"The currently installed version of Pixi, and the active environment if $PIXI_ENVIRONMENT_NAME is set"
}
"pulumi" => "The current username, stack, and installed version of Pulumi",
"purescript" => "The currently installed version of PureScript",
"python" => "The currently installed version of Python",
"quarto" => "The current installed version of quarto",
"raku" => "The currently installed version of Raku",
"red" => "The currently installed version of Red",
"rlang" => "The currently installed version of R",
"ruby" => "The currently installed version of Ruby",
"rust" => "The currently installed version of Rust",
"scala" => "The currently installed version of Scala",
"shell" => "The currently used shell indicator",
"shlvl" => "The current value of SHLVL",
"singularity" => "The currently used Singularity image",
"solidity" => "The current installed version of Solidity",
"spack" => "The current spack environment, if $SPACK_ENV is set",
"status" => "The status of the last command",
"sudo" => "The sudo credentials are currently cached",
"swift" => "The currently installed version of Swift",
"terraform" => "The currently selected terraform workspace and version",
"time" => "The current local time",
"typst" => "The current installed version of typst",
"username" => "The active user's username",
"vagrant" => "The currently installed version of Vagrant",
"vcsh" => "The currently active VCSH repository",
"vlang" => "The currently installed version of V",
"xmake" => "The currently installed version of XMake",
"zig" => "The currently installed version of Zig",
_ => "<no description>",
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::module::ALL_MODULES;
#[test]
fn all_modules_have_description() {
for module in ALL_MODULES {
println!("Checking if {module:?} has a description");
assert_ne!(description(module), "<no description>");
}
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/pixi.rs | src/modules/pixi.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::pixi::PixiConfig;
use crate::formatter::{StringFormatter, VersionFormatter};
use crate::utils::get_command_string_output;
/// Creates a module with the current Pixi environment
///
/// Will display the Pixi environment iff `$PIXI_ENVIRONMENT_NAME` is set.
/// Will display the Pixi version iff pixi files are detected or `$PIXI_ENVIRONMENT_NAME` is set.
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("pixi");
let config: PixiConfig = PixiConfig::try_load(module.config);
let pixi_environment_name = context.get_env("PIXI_ENVIRONMENT_NAME");
let is_pixi_project = pixi_environment_name.is_some()
|| context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_pixi_project {
return None;
}
let pixi_environment_name = if !config.show_default_environment
&& pixi_environment_name == Some("default".to_string())
{
None
} else {
pixi_environment_name
};
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|variable, _| match variable {
"symbol" => Some(config.symbol),
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map(|variable| match variable {
"environment" => pixi_environment_name.clone().map(Ok),
"version" => {
let pixi_version = get_pixi_version(context, &config)?;
VersionFormatter::format_module_version(
module.get_name(),
&pixi_version,
config.version_format,
)
.map(Ok)
}
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `pixi`:\n{error}");
return None;
}
});
Some(module)
}
fn get_pixi_version(context: &Context, config: &PixiConfig) -> Option<String> {
let version = config
.pixi_binary
.0
.iter()
.find_map(|binary| context.exec_cmd(binary, &["--version"]))
.map(get_command_string_output)?;
Some(version.split_once(' ')?.1.trim().to_string())
}
#[cfg(test)]
mod tests {
use std::{fs::File, io};
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
#[test]
fn not_in_env() {
let actual = ModuleRenderer::new("pixi").collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn ignore_default_environment() {
let actual = ModuleRenderer::new("pixi")
.env("PIXI_ENVIRONMENT_NAME", "default")
.config(toml::toml! {
[pixi]
show_default_environment = false
})
.collect();
let expected = Some(format!("via {}", Color::Yellow.bold().paint("🧚 v0.33.0 ")));
assert_eq!(expected, actual);
}
#[test]
fn env_set() {
let actual = ModuleRenderer::new("pixi")
.env("PIXI_ENVIRONMENT_NAME", "py312")
.collect();
let expected = Some(format!(
"via {}",
Color::Yellow.bold().paint("🧚 v0.33.0 (py312) ")
));
assert_eq!(expected, actual);
}
#[test]
fn folder_with_pixi_toml() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("pixi.toml"))?.sync_all()?;
let actual = ModuleRenderer::new("pixi").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Yellow.bold().paint("🧚 v0.33.0 ")));
assert_eq!(expected, actual);
dir.close()
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/java.rs | src/modules/java.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::java::JavaConfig;
use crate::formatter::{StringFormatter, VersionFormatter};
use crate::utils::get_command_string_output;
use std::path::PathBuf;
use regex::Regex;
const JAVA_VERSION_PATTERN: &str =
"(?:JRE.*\\(|OpenJ9 )(?P<version>\\d+(?:\\.\\d+){0,2}).*, built on";
/// Creates a module with the current Java version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("java");
let config: JavaConfig = JavaConfig::try_load(module.config);
let is_java_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_java_project {
return None;
}
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,
})
.map(|variable| match variable {
"version" => {
let java_version = get_java_version(context)?;
VersionFormatter::format_module_version(
module.get_name(),
&java_version,
config.version_format,
)
.map(Ok)
}
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `java`:\n{error}");
return None;
}
});
Some(module)
}
fn get_java_version(context: &Context) -> Option<String> {
let java_command = context
.get_env("JAVA_HOME")
.map(PathBuf::from)
.and_then(|path| {
path.join("bin")
.join("java")
.into_os_string()
.into_string()
.ok()
})
.unwrap_or_else(|| String::from("java"));
let output = context.exec_cmd(java_command, &["-Xinternalversion"])?;
let java_version_string = get_command_string_output(output);
parse_java_version(&java_version_string)
}
fn parse_java_version(java_version_string: &str) -> Option<String> {
let re = Regex::new(JAVA_VERSION_PATTERN).ok()?;
let captures = re.captures(java_version_string)?;
let version = &captures["version"];
Some(version.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{test::ModuleRenderer, utils::CommandOutput};
use nu_ansi_term::Color;
use std::fs::File;
use std::io;
#[test]
fn test_parse_java_version_openjdk() {
let java_8 = "OpenJDK 64-Bit Server VM (25.222-b10) for linux-amd64 JRE (1.8.0_222-b10), built on Jul 11 2019 10:18:43 by \"openjdk\" with gcc 4.4.7 20120313 (Red Hat 4.4.7-23)";
let java_11 = "OpenJDK 64-Bit Server VM (11.0.4+11-post-Ubuntu-1ubuntu219.04) for linux-amd64 JRE (11.0.4+11-post-Ubuntu-1ubuntu219.04), built on Jul 18 2019 18:21:46 by \"build\" with gcc 8.3.0";
assert_eq!(parse_java_version(java_8), Some("1.8.0".to_string()));
assert_eq!(parse_java_version(java_11), Some("11.0.4".to_string()));
}
#[test]
fn test_parse_java_version_oracle() {
let java_8 = "Java HotSpot(TM) Client VM (25.65-b01) for linux-arm-vfp-hflt JRE (1.8.0_65-b17), built on Oct 6 2015 16:19:04 by \"java_re\" with gcc 4.7.2 20120910 (prerelease)";
assert_eq!(parse_java_version(java_8), Some("1.8.0".to_string()));
}
#[test]
fn test_parse_java_version_redhat() {
let java_8 = "OpenJDK 64-Bit Server VM (25.222-b10) for linux-amd64 JRE (1.8.0_222-b10), built on Jul 11 2019 20:48:53 by \"root\" with gcc 7.3.1 20180303 (Red Hat 7.3.1-5)";
let java_12 = "OpenJDK 64-Bit Server VM (12.0.2+10) for linux-amd64 JRE (12.0.2+10), built on Jul 18 2019 14:41:47 by \"jenkins\" with gcc 7.3.1 20180303 (Red Hat 7.3.1-5)";
assert_eq!(parse_java_version(java_8), Some("1.8.0".to_string()));
assert_eq!(parse_java_version(java_12), Some("12.0.2".to_string()));
}
#[test]
fn test_parse_java_version_zulu() {
let java_8 = "OpenJDK 64-Bit Server VM (25.222-b10) for linux-amd64 JRE (Zulu 8.40.0.25-CA-linux64) (1.8.0_222-b10), built on Jul 11 2019 11:36:39 by \"zulu_re\" with gcc 4.4.7 20120313 (Red Hat 4.4.7-3)";
let java_11 = "OpenJDK 64-Bit Server VM (11.0.4+11-LTS) for linux-amd64 JRE (Zulu11.33+15-CA) (11.0.4+11-LTS), built on Jul 11 2019 21:37:17 by \"zulu_re\" with gcc 4.9.2 20150212 (Red Hat 4.9.2-6)";
let java_17 = "OpenJDK 64-Bit Server VM (17.0.5+8-LTS) for bsd-amd64 JRE (17.0.5+8-LTS) (Zulu17.38+21-CA), built on Oct 7 2022 06:03:12 by \"zulu_re\" with clang 4.2.1 Compatible Apple LLVM 11.0.0 (clang-1100.0.33.17)";
assert_eq!(parse_java_version(java_8), Some("1.8.0".to_string()));
assert_eq!(parse_java_version(java_11), Some("11.0.4".to_string()));
assert_eq!(parse_java_version(java_17), Some("17.0.5".to_string()));
}
#[test]
fn test_parse_java_version_eclipse_openj9() {
let java_8 = "Eclipse OpenJ9 OpenJDK 64-bit Server VM (1.8.0_222-b10) from linux-amd64 JRE with Extensions for OpenJDK for Eclipse OpenJ9 8.0.222.0, built on Jul 17 2019 21:29:18 by jenkins with g++ (GCC) 7.3.1 20180303 (Red Hat 7.3.1-5)";
let java_11 = "Eclipse OpenJ9 OpenJDK 64-bit Server VM (11.0.4+11) from linux-amd64 JRE with Extensions for OpenJDK for Eclipse OpenJ9 11.0.4.0, built on Jul 17 2019 21:51:37 by jenkins with g++ (GCC) 7.3.1 20180303 (Red Hat 7.3.1-5)";
assert_eq!(parse_java_version(java_8), Some("8.0.222".to_string()));
assert_eq!(parse_java_version(java_11), Some("11.0.4".to_string()));
}
#[test]
fn test_parse_java_version_graalvm() {
let java_8 = "OpenJDK 64-Bit GraalVM CE 19.2.0.1 (25.222-b08-jvmci-19.2-b02) for linux-amd64 JRE (8u222), built on Jul 19 2019 17:37:13 by \"buildslave\" with gcc 7.3.0";
assert_eq!(parse_java_version(java_8), Some("8".to_string()));
}
#[test]
fn test_parse_java_version_amazon_corretto() {
let java_8 = "OpenJDK 64-Bit Server VM (25.222-b10) for linux-amd64 JRE (1.8.0_222-b10), built on Jul 11 2019 20:48:53 by \"root\" with gcc 7.3.1 20180303 (Red Hat 7.3.1-5)";
let java_11 = "OpenJDK 64-Bit Server VM (11.0.4+11-LTS) for linux-amd64 JRE (11.0.4+11-LTS), built on Jul 11 2019 20:06:11 by \"\" with gcc 7.3.1 20180303 (Red Hat 7.3.1-5)";
assert_eq!(parse_java_version(java_8), Some("1.8.0".to_string()));
assert_eq!(parse_java_version(java_11), Some("11.0.4".to_string()));
}
#[test]
fn test_parse_java_version_sapmachine() {
let java_11 = "OpenJDK 64-Bit Server VM (11.0.4+11-LTS-sapmachine) for linux-amd64 JRE (11.0.4+11-LTS-sapmachine), built on Jul 17 2019 08:58:43 by \"\" with gcc 7.3.0";
assert_eq!(parse_java_version(java_11), Some("11.0.4".to_string()));
}
#[test]
fn test_parse_java_version_android_studio_jdk() {
let java_11 = "OpenJDK 64-Bit Server VM (11.0.15+0-b2043.56-8887301) for linux-amd64 JRE (11.0.15+0-b2043.56-8887301), built on Jul 29 2022 22:12:21 by \"androidbuild\" with gcc Android (7284624, based on r416183b) Clang 12.0.5 (https://android.googlesource.com/toolchain/llvm-project c935d99d7cf2016289302412d708641d52d2f7ee)}";
assert_eq!(parse_java_version(java_11), Some("11.0.15".to_string()));
}
#[test]
fn test_parse_java_version_unknown() {
let unknown_jre = "Unknown JRE";
assert_eq!(parse_java_version(unknown_jre), None);
}
#[test]
fn folder_without_java_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("java").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_java_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("Main.java"))?.sync_all()?;
let actual = ModuleRenderer::new("java").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Red.dimmed().paint("☕ v13.0.2 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_java_file_preview() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("Main.java"))?.sync_all()?;
let actual = ModuleRenderer::new("java").cmd("java -Xinternalversion", Some(CommandOutput {
stdout: "OpenJDK 64-Bit Server VM (16+14) for bsd-aarch64 JRE (16+14), built on Jan 17 2021 07:19:47 by \"brew\" with clang Apple LLVM 12.0.0 (clang-1200.0.32.28)\n".to_owned(),
stderr: String::new()
})).path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Red.dimmed().paint("☕ v16 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_java_file_no_java_installed() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("Main.java"))?.sync_all()?;
let actual = ModuleRenderer::new("java")
.cmd("java -Xinternalversion", None)
.path(dir.path())
.collect();
let expected = Some(format!("via {}", Color::Red.dimmed().paint("☕ ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_class_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("Main.class"))?.sync_all()?;
let actual = ModuleRenderer::new("java").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Red.dimmed().paint("☕ v13.0.2 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_gradle_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("build.gradle"))?.sync_all()?;
let actual = ModuleRenderer::new("java").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Red.dimmed().paint("☕ v13.0.2 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_jar_archive() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("test.jar"))?.sync_all()?;
let actual = ModuleRenderer::new("java").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Red.dimmed().paint("☕ v13.0.2 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_pom_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("pom.xml"))?.sync_all()?;
let actual = ModuleRenderer::new("java").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Red.dimmed().paint("☕ v13.0.2 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_sdkman_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join(".sdkmanrc"))?.sync_all()?;
let actual = ModuleRenderer::new("java").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Red.dimmed().paint("☕ v13.0.2 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_gradle_kotlin_build_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("build.gradle.kts"))?.sync_all()?;
let actual = ModuleRenderer::new("java").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Red.dimmed().paint("☕ v13.0.2 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_sbt_build_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("build.gradle.kts"))?.sync_all()?;
let actual = ModuleRenderer::new("java").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Red.dimmed().paint("☕ v13.0.2 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_java_version_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join(".java-version"))?.sync_all()?;
let actual = ModuleRenderer::new("java").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Red.dimmed().paint("☕ v13.0.2 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn test_java_home() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("Main.java"))?.sync_all()?;
let java_home: PathBuf = ["a", "b", "c"].iter().collect();
let java_bin = java_home.join("bin").join("java");
let actual = ModuleRenderer::new("java")
.env("JAVA_HOME", java_home.to_str().unwrap())
.cmd(&format!("{} -Xinternalversion", java_bin.to_str().unwrap()),
Some(CommandOutput {
stdout: "OpenJDK 64-Bit Server VM (11.0.4+11-LTS-sapmachine) for linux-amd64 JRE (11.0.4+11-LTS-sapmachine), built on Jul 17 2019 08:58:43 by \"\" with gcc 7.3.0".to_owned(),
stderr: String::new(),
}))
.path(dir.path())
.collect();
let expected = Some(format!("via {}", Color::Red.dimmed().paint("☕ v11.0.4 ")));
assert_eq!(expected, actual);
dir.close()
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/hg_branch.rs | src/modules/hg_branch.rs | use std::io::Error;
use std::path::Path;
use super::utils::truncate::truncate_text;
use super::{Context, Module, ModuleConfig};
use crate::configs::hg_branch::HgBranchConfig;
use crate::formatter::StringFormatter;
use crate::utils::read_file;
/// Creates a module with the Hg bookmark or branch in the current directory
///
/// Will display the bookmark or branch name if the current directory is an hg repo
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("hg_branch");
let config: HgBranchConfig = HgBranchConfig::try_load(module.config);
// As we default to disabled=true, we have to check here after loading our config module,
// before it was only checking against whatever is in the config starship.toml
if config.disabled {
return None;
}
let len = if config.truncation_length <= 0 {
log::warn!(
"\"truncation_length\" should be a positive value, found {}",
config.truncation_length
);
usize::MAX
} else {
config.truncation_length as usize
};
let repo_root = context.begin_ancestor_scan().set_folders(&[".hg"]).scan()?;
let branch_name = get_hg_current_bookmark(&repo_root).unwrap_or_else(|_| {
get_hg_branch_name(&repo_root).unwrap_or_else(|_| String::from("default"))
});
let branch_graphemes = truncate_text(&branch_name, len, config.truncation_symbol);
let topic_graphemes = if let Ok(topic) = get_hg_topic_name(&repo_root) {
truncate_text(&topic, len, config.truncation_symbol)
} else {
String::new()
};
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|variable, _| match variable {
"symbol" => Some(config.symbol),
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map(|variable| match variable {
"branch" => Some(Ok(branch_graphemes.as_str())),
"topic" => Some(Ok(topic_graphemes.as_str())),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `hg_branch`:\n{error}");
return None;
}
});
Some(module)
}
fn get_hg_branch_name(hg_root: &Path) -> Result<String, Error> {
match read_file(hg_root.join(".hg").join("branch")) {
Ok(b) => Ok(b.trim().to_string()),
Err(e) => Err(e),
}
}
fn get_hg_current_bookmark(hg_root: &Path) -> Result<String, Error> {
read_file(hg_root.join(".hg").join("bookmarks.current"))
}
fn get_hg_topic_name(hg_root: &Path) -> Result<String, Error> {
match read_file(hg_root.join(".hg").join("topic")) {
Ok(b) => Ok(b.trim().to_string()),
Err(e) => Err(e),
}
}
#[cfg(test)]
mod tests {
use nu_ansi_term::{Color, Style};
use std::fs;
use std::io;
use std::path::Path;
use crate::test::{FixtureProvider, ModuleRenderer, fixture_repo};
use crate::utils::create_command;
enum Expect<'a> {
BranchName(&'a str),
Empty,
NoTruncation,
Symbol(&'a str),
Style(Style),
TruncationSymbol(&'a str),
}
#[test]
fn show_nothing_on_empty_dir() -> io::Result<()> {
let repo_dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("hg_branch")
.path(repo_dir.path())
.collect();
let expected = None;
assert_eq!(expected, actual);
repo_dir.close()
}
#[test]
#[ignore]
fn test_hg_disabled_per_default() -> io::Result<()> {
let tempdir = fixture_repo(FixtureProvider::Hg)?;
let repo_dir = tempdir.path();
run_hg(&["whatever", "blubber"], repo_dir)?;
expect_hg_branch_with_config(
repo_dir,
// no "disabled=false" in config!
Some(toml::toml! {
[hg_branch]
truncation_length = 14
}),
&[Expect::Empty],
);
tempdir.close()
}
#[test]
#[ignore]
fn test_hg_get_branch_fails() -> io::Result<()> {
let tempdir = tempfile::tempdir()?;
// Create a fake corrupted mercurial repo.
let hgdir = tempdir.path().join(".hg");
fs::create_dir(&hgdir)?;
fs::write(hgdir.join("requires"), "fake-corrupted-repo")?;
expect_hg_branch_with_config(
tempdir.path(),
None,
&[Expect::BranchName("default"), Expect::NoTruncation],
);
tempdir.close()
}
#[test]
#[ignore]
fn test_hg_get_branch_autodisabled() -> io::Result<()> {
let tempdir = tempfile::tempdir()?;
expect_hg_branch_with_config(tempdir.path(), None, &[Expect::Empty]);
tempdir.close()
}
#[test]
#[ignore]
fn test_hg_bookmark() -> io::Result<()> {
let tempdir = fixture_repo(FixtureProvider::Hg)?;
let repo_dir = tempdir.path();
run_hg(&["bookmark", "bookmark-101"], repo_dir)?;
expect_hg_branch_with_config(
repo_dir,
None,
&[Expect::BranchName("bookmark-101"), Expect::NoTruncation],
);
tempdir.close()
}
#[test]
#[ignore]
fn test_hg_topic() -> io::Result<()> {
let tempdir = fixture_repo(FixtureProvider::Hg)?;
let repo_dir = tempdir.path();
fs::write(repo_dir.join(".hg").join("topic"), "feature\n")?;
let actual = ModuleRenderer::new("hg_branch")
.path(repo_dir.to_str().unwrap())
.config(toml::toml! {
[hg_branch]
format = "$topic"
disabled = false
})
.collect();
assert_eq!(Some(String::from("feature")), actual);
tempdir.close()
}
#[test]
#[ignore]
fn test_default_truncation_symbol() -> io::Result<()> {
let tempdir = fixture_repo(FixtureProvider::Hg)?;
let repo_dir = tempdir.path();
run_hg(&["branch", "-f", "branch-name-101"], repo_dir)?;
run_hg(
&[
"commit",
"-m",
"empty commit 101",
"-u",
"fake user <fake@user>",
],
repo_dir,
)?;
expect_hg_branch_with_config(
repo_dir,
Some(toml::toml! {
[hg_branch]
truncation_length = 14
disabled = false
}),
&[Expect::BranchName("branch-name-10")],
);
tempdir.close()
}
#[test]
#[ignore]
fn test_configured_symbols() -> io::Result<()> {
let tempdir = fixture_repo(FixtureProvider::Hg)?;
let repo_dir = tempdir.path();
run_hg(&["branch", "-f", "branch-name-121"], repo_dir)?;
run_hg(
&[
"commit",
"-m",
"empty commit 121",
"-u",
"fake user <fake@user>",
],
repo_dir,
)?;
expect_hg_branch_with_config(
repo_dir,
Some(toml::toml! {
[hg_branch]
symbol = "B "
truncation_length = 14
truncation_symbol = "%"
disabled = false
}),
&[
Expect::BranchName("branch-name-12"),
Expect::Symbol("B"),
Expect::TruncationSymbol("%"),
],
);
tempdir.close()
}
#[test]
#[ignore]
fn test_configured_style() -> io::Result<()> {
let tempdir = fixture_repo(FixtureProvider::Hg)?;
let repo_dir = tempdir.path();
run_hg(&["branch", "-f", "branch-name-131"], repo_dir)?;
run_hg(
&[
"commit",
"-m",
"empty commit 131",
"-u",
"fake user <fake@user>",
],
repo_dir,
)?;
expect_hg_branch_with_config(
repo_dir,
Some(toml::toml! {
[hg_branch]
style = "underline blue"
disabled = false
}),
&[
Expect::BranchName("branch-name-131"),
Expect::Style(Color::Blue.underline()),
Expect::TruncationSymbol(""),
],
);
tempdir.close()
}
fn expect_hg_branch_with_config(
repo_dir: &Path,
config: Option<toml::Table>,
expectations: &[Expect],
) {
let actual = ModuleRenderer::new("hg_branch")
.path(repo_dir.to_str().unwrap())
.config(config.unwrap_or_else(|| {
toml::toml! {
[hg_branch]
disabled = false
}
}))
.collect();
let mut expect_branch_name = "default";
let mut expect_style = Color::Purple.bold();
let mut expect_symbol = "\u{e0a0}";
let mut expect_truncation_symbol = "…";
for expect in expectations {
match expect {
Expect::Empty => {
assert_eq!(None, actual);
return;
}
Expect::Symbol(symbol) => {
expect_symbol = symbol;
}
Expect::TruncationSymbol(truncation_symbol) => {
expect_truncation_symbol = truncation_symbol;
}
Expect::NoTruncation => {
expect_truncation_symbol = "";
}
Expect::BranchName(branch_name) => {
expect_branch_name = branch_name;
}
Expect::Style(style) => expect_style = *style,
}
}
let expected = Some(format!(
"on {} ",
expect_style.paint(format!(
"{expect_symbol} {expect_branch_name}{expect_truncation_symbol}"
)),
));
assert_eq!(expected, actual);
}
fn run_hg(args: &[&str], repo_dir: &Path) -> io::Result<()> {
create_command("hg")?
.args(args)
.current_dir(repo_dir)
.output()?;
Ok(())
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/character.rs | src/modules/character.rs | use super::{Context, Module, ModuleConfig, Shell};
use crate::configs::character::CharacterConfig;
use crate::formatter::StringFormatter;
/// Creates a module for the prompt character
///
/// The character segment prints an arrow character in a color dependent on the
/// exit-code of the last executed command:
/// - If the exit-code was "0", it will be formatted with `success_symbol`
/// (green arrow by default)
/// - If the exit-code was anything else, it will be formatted with
/// `error_symbol` (red arrow by default)
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
enum ShellEditMode {
Normal,
Visual,
Replace,
ReplaceOne,
Insert,
}
const ASSUMED_MODE: ShellEditMode = ShellEditMode::Insert;
// TODO: extend config to more modes
let mut module = context.new_module("character");
let config: CharacterConfig = CharacterConfig::try_load(module.config);
let props = &context.properties;
let exit_code = props.status_code.as_deref().unwrap_or("0");
let keymap = props.keymap.as_str();
let exit_success = exit_code == "0";
// Match shell "keymap" names to normalized vi modes
// NOTE: in vi mode, fish reports normal mode as "default".
// Unfortunately, this is also the name of the non-vi default mode.
// We do some environment detection in src/init.rs to translate.
// The result: in non-vi fish, keymap is always reported as "insert"
let mode = match (&context.shell, keymap) {
(Shell::Fish, "default")
| (Shell::Zsh, "vicmd")
| (Shell::Cmd | Shell::PowerShell | Shell::Pwsh, "vi") => ShellEditMode::Normal,
(Shell::Fish, "visual") => ShellEditMode::Visual,
(Shell::Fish, "replace") => ShellEditMode::Replace,
(Shell::Fish, "replace_one") => ShellEditMode::ReplaceOne,
_ => ASSUMED_MODE,
};
let symbol = match mode {
ShellEditMode::Normal => config.vimcmd_symbol,
ShellEditMode::Visual => config.vimcmd_visual_symbol,
ShellEditMode::Replace => config.vimcmd_replace_symbol,
ShellEditMode::ReplaceOne => config.vimcmd_replace_one_symbol,
ShellEditMode::Insert => {
if exit_success {
config.success_symbol
} else {
config.error_symbol
}
}
};
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|variable, _| match variable {
"symbol" => Some(symbol),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `character`:\n{error}");
return None;
}
});
Some(module)
}
#[cfg(test)]
mod test {
use crate::context::Shell;
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
#[test]
fn success_status() {
let expected = Some(format!("{} ", Color::Green.bold().paint("❯")));
// Status code 0
let actual = ModuleRenderer::new("character").status(0).collect();
assert_eq!(expected, actual);
// No status code
let actual = ModuleRenderer::new("character").collect();
assert_eq!(expected, actual);
}
#[test]
fn failure_status() {
let expected = Some(format!("{} ", Color::Red.bold().paint("❯")));
let exit_values = [1, 54321, -5000];
for status in &exit_values {
let actual = ModuleRenderer::new("character").status(*status).collect();
assert_eq!(expected, actual);
}
}
#[test]
fn custom_symbol() {
let expected_fail = Some(format!("{} ", Color::Red.bold().paint("✖")));
let expected_success = Some(format!("{} ", Color::Green.bold().paint("➜")));
let exit_values = [1, 54321, -5000];
// Test failure values
for status in &exit_values {
let actual = ModuleRenderer::new("character")
.config(toml::toml! {
[character]
success_symbol = "[➜](bold green)"
error_symbol = "[✖](bold red)"
})
.status(*status)
.collect();
assert_eq!(expected_fail, actual);
}
// Test success
let actual = ModuleRenderer::new("character")
.config(toml::toml! {
[character]
success_symbol = "[➜](bold green)"
error_symbol = "[✖](bold red)"
})
.status(0)
.collect();
assert_eq!(expected_success, actual);
}
#[test]
fn zsh_keymap() {
let expected_vicmd = Some(format!("{} ", Color::Green.bold().paint("❮")));
let expected_specified = Some(format!("{} ", Color::Green.bold().paint("V")));
let expected_other = Some(format!("{} ", Color::Green.bold().paint("❯")));
// zle keymap is vicmd
let actual = ModuleRenderer::new("character")
.shell(Shell::Zsh)
.keymap("vicmd")
.collect();
assert_eq!(expected_vicmd, actual);
// specified vicmd character
let actual = ModuleRenderer::new("character")
.config(toml::toml! {
[character]
vicmd_symbol = "[V](bold green)"
})
.shell(Shell::Zsh)
.keymap("vicmd")
.collect();
assert_eq!(expected_specified, actual);
// zle keymap is other
let actual = ModuleRenderer::new("character")
.shell(Shell::Zsh)
.keymap("visual")
.collect();
assert_eq!(expected_other, actual);
}
#[test]
fn fish_keymap() {
let expected_vicmd = Some(format!("{} ", Color::Green.bold().paint("❮")));
let expected_specified = Some(format!("{} ", Color::Green.bold().paint("V")));
let expected_visual = Some(format!("{} ", Color::Yellow.bold().paint("❮")));
let expected_replace = Some(format!("{} ", Color::Purple.bold().paint("❮")));
let expected_replace_one = expected_replace.as_deref();
let expected_other = Some(format!("{} ", Color::Green.bold().paint("❯")));
// fish keymap is default
let actual = ModuleRenderer::new("character")
.shell(Shell::Fish)
.keymap("default")
.collect();
assert_eq!(expected_vicmd, actual);
// specified vicmd character
let actual = ModuleRenderer::new("character")
.config(toml::toml! {
[character]
vicmd_symbol = "[V](bold green)"
})
.shell(Shell::Fish)
.keymap("default")
.collect();
assert_eq!(expected_specified, actual);
// fish keymap is visual
let actual = ModuleRenderer::new("character")
.shell(Shell::Fish)
.keymap("visual")
.collect();
assert_eq!(expected_visual, actual);
// fish keymap is replace
let actual = ModuleRenderer::new("character")
.shell(Shell::Fish)
.keymap("replace")
.collect();
assert_eq!(expected_replace, actual);
// fish keymap is replace_one
let actual = ModuleRenderer::new("character")
.shell(Shell::Fish)
.keymap("replace_one")
.collect();
assert_eq!(expected_replace_one, actual.as_deref());
// fish keymap is other
let actual = ModuleRenderer::new("character")
.shell(Shell::Fish)
.keymap("other")
.collect();
assert_eq!(expected_other, actual);
}
#[test]
fn cmd_keymap() {
let expected_vicmd = Some(format!("{} ", Color::Green.bold().paint("❮")));
let expected_specified = Some(format!("{} ", Color::Green.bold().paint("V")));
let expected_other = Some(format!("{} ", Color::Green.bold().paint("❯")));
// cmd keymap is vi
let actual = ModuleRenderer::new("character")
.shell(Shell::Cmd)
.keymap("vi")
.collect();
assert_eq!(expected_vicmd, actual);
// specified vicmd character
let actual = ModuleRenderer::new("character")
.config(toml::toml! {
[character]
vicmd_symbol = "[V](bold green)"
})
.shell(Shell::Cmd)
.keymap("vi")
.collect();
assert_eq!(expected_specified, actual);
// cmd keymap is other
let actual = ModuleRenderer::new("character")
.shell(Shell::Cmd)
.keymap("visual")
.collect();
assert_eq!(expected_other, actual);
}
#[test]
fn powershell_keymap() {
let expected_vicmd = Some(format!("{} ", Color::Green.bold().paint("❮")));
let expected_specified = Some(format!("{} ", Color::Green.bold().paint("V")));
let expected_other = Some(format!("{} ", Color::Green.bold().paint("❯")));
// powershell keymap is vi
let actual = ModuleRenderer::new("character")
.shell(Shell::PowerShell)
.keymap("vi")
.collect();
assert_eq!(expected_vicmd, actual);
// specified vicmd character
let actual = ModuleRenderer::new("character")
.config(toml::toml! {
[character]
vicmd_symbol = "[V](bold green)"
})
.shell(Shell::PowerShell)
.keymap("vi")
.collect();
assert_eq!(expected_specified, actual);
// powershell keymap is other
let actual = ModuleRenderer::new("character")
.shell(Shell::PowerShell)
.keymap("visual")
.collect();
assert_eq!(expected_other, actual);
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/zig.rs | src/modules/zig.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::zig::ZigConfig;
use crate::formatter::StringFormatter;
use crate::formatter::VersionFormatter;
/// Creates a module with the current Zig version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("zig");
let config = ZigConfig::try_load(module.config);
let is_zig_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_zig_project {
return None;
}
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|variable, _| match variable {
"symbol" => Some(config.symbol),
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map(|variable| match variable {
"version" => {
let zig_version = context.exec_cmd("zig", &["version"])?.stdout;
VersionFormatter::format_module_version(
module.get_name(),
zig_version.trim(),
config.version_format,
)
.map(Ok)
}
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `zig`:\n{error}");
return None;
}
});
Some(module)
}
#[cfg(test)]
mod tests {
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
use std::fs::File;
use std::io;
#[test]
fn folder_without_zig() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("zig.txt"))?.sync_all()?;
let actual = ModuleRenderer::new("zig").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_zig_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("main.zig"))?.sync_all()?;
let actual = ModuleRenderer::new("zig").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Yellow.bold().paint("↯ v0.6.0 ")));
assert_eq!(expected, actual);
dir.close()
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/bun.rs | src/modules/bun.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::bun::BunConfig;
use crate::formatter::StringFormatter;
use crate::formatter::VersionFormatter;
use crate::utils::get_command_string_output;
/// Creates a module with the current Bun version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("bun");
let config = BunConfig::try_load(module.config);
let is_bun_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_bun_project {
return None;
}
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,
})
.map(|variable| match variable {
"version" => {
let bun_version = get_bun_version(context)?;
VersionFormatter::format_module_version(
module.get_name(),
&bun_version,
config.version_format,
)
.map(Ok)
}
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `bun`:\n{error}");
return None;
}
});
Some(module)
}
fn get_bun_version(context: &Context) -> Option<String> {
context
.exec_cmd("bun", &["--version"])
.map(get_command_string_output)
.map(|s| parse_bun_version(&s))
}
fn parse_bun_version(bun_version: &str) -> String {
bun_version.trim_end().to_string()
}
#[cfg(test)]
mod tests {
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
use std::fs::File;
use std::io;
#[test]
fn folder_without_bun_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("bun").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_bun_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("bun.lockb"))?.sync_all()?;
let actual = ModuleRenderer::new("bun").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Red.bold().paint("🥟 v0.1.4 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_bun_file_text_lockfile() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("bun.lock"))?.sync_all()?;
let actual = ModuleRenderer::new("bun").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Red.bold().paint("🥟 v0.1.4 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn no_bun_installed() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("bun.lockb"))?.sync_all()?;
let actual = ModuleRenderer::new("bun")
.path(dir.path())
.cmd("bun --version", None)
.collect();
let expected = Some(format!("via {}", Color::Red.bold().paint("🥟 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn no_bun_installed_text_lockfile() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("bun.lock"))?.sync_all()?;
let actual = ModuleRenderer::new("bun")
.path(dir.path())
.cmd("bun --version", None)
.collect();
let expected = Some(format!("via {}", Color::Red.bold().paint("🥟 ")));
assert_eq!(expected, actual);
dir.close()
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/nats.rs | src/modules/nats.rs | 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: {e}\n");
drop(e);
})
.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,
})
.map(|variable| match variable {
"name" => Some(Ok(nats_context.get("name")?.as_str()?)),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `nats`:\n{error}");
return None;
}
});
Some(module)
}
#[cfg(test)]
mod tests {
use nu_ansi_term::Color;
use crate::test::ModuleRenderer;
#[test]
fn show_context() {
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);
}
#[test]
fn test_with_symbol() {
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);
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/cmake.rs | src/modules/cmake.rs | use super::{Context, Module, ModuleConfig};
use crate::formatter::VersionFormatter;
use crate::configs::cmake::CMakeConfig;
use crate::formatter::StringFormatter;
/// Creates a module with the current `CMake` version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("cmake");
let config = CMakeConfig::try_load(module.config);
let is_cmake_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_cmake_project {
return None;
}
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|variable, _| match variable {
"symbol" => Some(config.symbol),
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map(|variable| match variable {
"version" => {
let cmake_version =
parse_cmake_version(&context.exec_cmd("cmake", &["--version"])?.stdout)?;
VersionFormatter::format_module_version(
module.get_name(),
&cmake_version,
config.version_format,
)
.map(Ok)
}
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `cmake`: \n{error}");
return None;
}
});
Some(module)
}
fn parse_cmake_version(cmake_version: &str) -> Option<String> {
Some(
cmake_version
//split into ["cmake" "version" "3.10.2", ...]
.split_whitespace()
// get down to "3.10.2"
.nth(2)?
.to_string(),
)
}
#[cfg(test)]
mod tests {
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
use std::fs::File;
use std::io;
#[test]
fn folder_without_cmake_lists() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("cmake").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_cmake_lists() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("CMakeLists.txt"))?.sync_all()?;
let actual = ModuleRenderer::new("cmake").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Blue.bold().paint("△ v3.17.3 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn buildfolder_with_cmake_cache() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("CMakeCache.txt"))?.sync_all()?;
let actual = ModuleRenderer::new("cmake").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Blue.bold().paint("△ v3.17.3 ")));
assert_eq!(expected, actual);
dir.close()
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/fossil_branch.rs | src/modules/fossil_branch.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::fossil_branch::FossilBranchConfig;
use crate::formatter::StringFormatter;
use crate::modules::utils::truncate::truncate_text;
/// Creates a module with the Fossil branch of the check-out in the current directory
///
/// Will display the branch name if the current directory is a Fossil check-out
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("fossil_branch");
let config = FossilBranchConfig::try_load(module.config);
// As we default to disabled=true, we have to check here after loading our config module,
// before it was only checking against whatever is in the config starship.toml
if config.disabled {
return None;
}
let checkout_db = if cfg!(windows) {
"_FOSSIL_"
} else {
".fslckout"
};
// See if we're in a check-out by scanning upwards for a directory containing the checkout_db file
context
.begin_ancestor_scan()
.set_files(&[checkout_db])
.scan()?;
let len = if config.truncation_length <= 0 {
log::warn!(
"\"truncation_length\" should be a positive value, found {}",
config.truncation_length
);
usize::MAX
} else {
config.truncation_length as usize
};
let truncated_branch_name = {
let output = context.exec_cmd("fossil", &["branch", "current"])?.stdout;
truncate_text(output.trim(), len, config.truncation_symbol)
};
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|variable, _| match variable {
"symbol" => Some(config.symbol),
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map(|variable| match variable {
"branch" => Some(Ok(truncated_branch_name.as_str())),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `fossil_branch`:\n{error}");
return None;
}
});
Some(module)
}
#[cfg(test)]
mod tests {
use std::io;
use std::path::Path;
use nu_ansi_term::{Color, Style};
use crate::test::{FixtureProvider, ModuleRenderer, fixture_repo};
enum Expect<'a> {
BranchName(&'a str),
Empty,
NoTruncation,
Symbol(&'a str),
Style(Style),
TruncationSymbol(&'a str),
}
#[test]
fn show_nothing_on_empty_dir() -> io::Result<()> {
let checkout_dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("fossil_branch")
.path(checkout_dir.path())
.collect();
let expected = None;
assert_eq!(expected, actual);
checkout_dir.close()
}
#[test]
fn test_fossil_branch_disabled_per_default() -> io::Result<()> {
let tempdir = fixture_repo(FixtureProvider::Fossil)?;
let checkout_dir = tempdir.path();
expect_fossil_branch_with_config(
checkout_dir,
Some(toml::toml! {
// no "disabled=false" in config!
[fossil_branch]
truncation_length = 14
}),
&[Expect::Empty],
);
tempdir.close()
}
#[test]
fn test_fossil_branch_autodisabled() -> io::Result<()> {
let tempdir = tempfile::tempdir()?;
expect_fossil_branch_with_config(tempdir.path(), None, &[Expect::Empty]);
tempdir.close()
}
#[test]
fn test_fossil_branch() -> io::Result<()> {
let tempdir = fixture_repo(FixtureProvider::Fossil)?;
let checkout_dir = tempdir.path();
run_fossil(&["branch", "new", "topic-branch", "trunk"], checkout_dir)?;
run_fossil(&["update", "topic-branch"], checkout_dir)?;
expect_fossil_branch_with_config(
checkout_dir,
None,
&[Expect::BranchName("topic-branch"), Expect::NoTruncation],
);
tempdir.close()
}
#[test]
fn test_fossil_branch_subdir() -> io::Result<()> {
let tempdir = fixture_repo(FixtureProvider::Fossil)?;
let checkout_dir = tempdir.path();
expect_fossil_branch_with_config(
&checkout_dir.join("subdir"),
None,
&[Expect::BranchName("topic-branch"), Expect::NoTruncation],
);
tempdir.close()
}
#[test]
fn test_fossil_branch_configured() -> io::Result<()> {
let tempdir = fixture_repo(FixtureProvider::Fossil)?;
let checkout_dir = tempdir.path();
run_fossil(&["branch", "new", "topic-branch", "trunk"], checkout_dir)?;
run_fossil(&["update", "topic-branch"], checkout_dir)?;
expect_fossil_branch_with_config(
checkout_dir,
Some(toml::toml! {
[fossil_branch]
style = "underline blue"
symbol = "F "
truncation_length = 10
truncation_symbol = "%"
disabled = false
}),
&[
Expect::BranchName("topic-bran"),
Expect::Style(Color::Blue.underline()),
Expect::Symbol("F"),
Expect::TruncationSymbol("%"),
],
);
tempdir.close()
}
fn expect_fossil_branch_with_config(
checkout_dir: &Path,
config: Option<toml::Table>,
expectations: &[Expect],
) {
let actual = ModuleRenderer::new("fossil_branch")
.path(checkout_dir.to_str().unwrap())
.config(config.unwrap_or_else(|| {
toml::toml! {
[fossil_branch]
disabled = false
}
}))
.collect();
let mut expect_branch_name = "trunk";
let mut expect_style = Color::Purple.bold();
let mut expect_symbol = "\u{e0a0}";
let mut expect_truncation_symbol = "…";
for expect in expectations {
match expect {
Expect::Empty => {
assert_eq!(None, actual);
return;
}
Expect::Symbol(symbol) => expect_symbol = symbol,
Expect::TruncationSymbol(truncation_symbol) => {
expect_truncation_symbol = truncation_symbol;
}
Expect::NoTruncation => expect_truncation_symbol = "",
Expect::BranchName(branch_name) => expect_branch_name = branch_name,
Expect::Style(style) => expect_style = *style,
}
}
let expected = Some(format!(
"on {} ",
expect_style.paint(format!(
"{expect_symbol} {expect_branch_name}{expect_truncation_symbol}"
))
));
assert_eq!(expected, actual);
}
fn run_fossil(args: &[&str], _checkout_dir: &Path) -> io::Result<()> {
crate::utils::mock_cmd("fossil", args).ok_or(io::ErrorKind::Unsupported)?;
Ok(())
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/opa.rs | src/modules/opa.rs | /// Creates a module with the current Open Policy Agent version
use super::{Context, Module, ModuleConfig};
use crate::configs::opa::OpaConfig;
use crate::formatter::StringFormatter;
use crate::formatter::VersionFormatter;
use crate::utils::get_command_string_output;
/// Creates a module with the current Open Policy Agent version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("opa");
let config = OpaConfig::try_load(module.config);
let is_opa_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_opa_project {
return None;
}
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,
})
.map(|variable| match variable {
"version" => {
let opa_version = get_opa_version(context)?;
VersionFormatter::format_module_version(
module.get_name(),
&opa_version,
config.version_format,
)
.map(Ok)
}
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `opa`:\n{error}");
return None;
}
});
Some(module)
}
fn get_opa_version(context: &Context) -> Option<String> {
let version_output: String = context
.exec_cmd("opa", &["version"])
.map(get_command_string_output)?;
parse_opa_version(&version_output)
}
fn parse_opa_version(version_output: &str) -> Option<String> {
Some(version_output.split_whitespace().nth(1)?.to_string())
}
#[cfg(test)]
mod tests {
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
use std::fs::File;
use std::io;
#[test]
fn folder_without_opa_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("opa").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_opa_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("test.rego"))?.sync_all()?;
let actual = ModuleRenderer::new("opa").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Blue.bold().paint("🪖 v0.44.0 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn no_opa_installed() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("test.rego"))?.sync_all()?;
let actual = ModuleRenderer::new("opa")
.path(dir.path())
.cmd("opa version", None)
.collect();
let expected = Some(format!("via {}", Color::Blue.bold().paint("🪖 ")));
assert_eq!(expected, actual);
dir.close()
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/docker_context.rs | src/modules/docker_context.rs | use std::path::PathBuf;
use super::{Context, Module, ModuleConfig};
use crate::configs::docker_context::DockerContextConfig;
use crate::formatter::StringFormatter;
use crate::utils;
/// Creates a module with the currently active Docker context
///
/// Will display the Docker context if the following criteria are met:
/// - There is a non-empty environment variable named `DOCKER_HOST`
/// - Or there is a non-empty environment variable named `DOCKER_CONTEXT`
/// - Or there is a file named `$HOME/.docker/config.json`
/// - Or a file named `$DOCKER_CONFIG/config.json`
/// - The file is JSON and contains a field named `currentContext`
/// - The value of `currentContext` is not `default` or `desktop-linux`
/// - If multiple criteria are met, we use the following order to define the docker context:
/// - `DOCKER_HOST`, `DOCKER_CONTEXT`, $HOME/.docker/config.json, $`DOCKER_CONFIG/config.json`
/// - (This is the same order docker follows, as `DOCKER_HOST` and `DOCKER_CONTEXT` override the
/// config)
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("docker_context");
let config: DockerContextConfig = DockerContextConfig::try_load(module.config);
if config.only_with_files
&& !context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match()
{
return None;
}
let docker_config = PathBuf::from(
&context
.get_env_os("DOCKER_CONFIG")
.unwrap_or(context.get_home()?.join(".docker").into_os_string()),
)
.join("config.json");
let docker_context_env = ["DOCKER_MACHINE_NAME", "DOCKER_HOST", "DOCKER_CONTEXT"]
.into_iter()
.find_map(|env| context.get_env(env));
let ctx = if let Some(data) = docker_context_env {
data
} else {
if !docker_config.exists() {
return None;
}
let json = utils::read_file(docker_config).ok()?;
let parsed_json: serde_json::Value = serde_json::from_str(&json).ok()?;
parsed_json.get("currentContext")?.as_str()?.to_owned()
};
let default_contexts = ["default", "desktop-linux"];
if default_contexts.contains(&ctx.as_str()) || ctx.starts_with("unix://") {
return None;
}
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|variable, _| match variable {
"symbol" => Some(config.symbol),
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map(|variable| match variable {
"context" => Some(Ok(ctx.as_str())),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `docker_context`:\n{error}");
return None;
}
});
Some(module)
}
#[cfg(test)]
mod tests {
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
use std::fs::File;
use std::io::{self, Write};
#[test]
fn only_trigger_when_docker_config_exists() -> io::Result<()> {
let cfg_dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("docker_context")
.env("DOCKER_CONFIG", cfg_dir.path().to_string_lossy())
.collect();
let expected = None;
assert_eq!(expected, actual);
cfg_dir.close()
}
#[test]
fn test_with_compose_yml() -> io::Result<()> {
let cfg_dir = tempfile::tempdir()?;
let cfg_file = cfg_dir.path().join("config.json");
let pwd = tempfile::tempdir()?;
File::create(pwd.path().join("compose.yml"))?.sync_all()?;
let config_content = serde_json::json!({
"currentContext": "starship"
});
let mut docker_config = File::create(cfg_file)?;
docker_config.write_all(config_content.to_string().as_bytes())?;
docker_config.sync_all()?;
let actual = ModuleRenderer::new("docker_context")
.env("DOCKER_CONFIG", cfg_dir.path().to_string_lossy())
.path(pwd.path())
.collect();
let expected = Some(format!("via {} ", Color::Blue.bold().paint("🐳 starship")));
assert_eq!(expected, actual);
cfg_dir.close()?;
pwd.close()
}
#[test]
fn test_with_compose_yaml() -> io::Result<()> {
let cfg_dir = tempfile::tempdir()?;
let cfg_file = cfg_dir.path().join("config.json");
let pwd = tempfile::tempdir()?;
File::create(pwd.path().join("compose.yaml"))?.sync_all()?;
let config_content = serde_json::json!({
"currentContext": "starship"
});
let mut docker_config = File::create(cfg_file)?;
docker_config.write_all(config_content.to_string().as_bytes())?;
docker_config.sync_all()?;
let actual = ModuleRenderer::new("docker_context")
.env("DOCKER_CONFIG", cfg_dir.path().to_string_lossy())
.path(pwd.path())
.collect();
let expected = Some(format!("via {} ", Color::Blue.bold().paint("🐳 starship")));
assert_eq!(expected, actual);
cfg_dir.close()?;
pwd.close()
}
#[test]
fn test_with_docker_compose_yml() -> io::Result<()> {
let cfg_dir = tempfile::tempdir()?;
let cfg_file = cfg_dir.path().join("config.json");
let pwd = tempfile::tempdir()?;
File::create(pwd.path().join("docker-compose.yml"))?.sync_all()?;
let config_content = serde_json::json!({
"currentContext": "starship"
});
let mut docker_config = File::create(cfg_file)?;
docker_config.write_all(config_content.to_string().as_bytes())?;
docker_config.sync_all()?;
let actual = ModuleRenderer::new("docker_context")
.env("DOCKER_CONFIG", cfg_dir.path().to_string_lossy())
.path(pwd.path())
.collect();
let expected = Some(format!("via {} ", Color::Blue.bold().paint("🐳 starship")));
assert_eq!(expected, actual);
cfg_dir.close()?;
pwd.close()
}
#[test]
fn test_with_docker_compose_yaml() -> io::Result<()> {
let cfg_dir = tempfile::tempdir()?;
let cfg_file = cfg_dir.path().join("config.json");
let pwd = tempfile::tempdir()?;
File::create(pwd.path().join("docker-compose.yaml"))?.sync_all()?;
let config_content = serde_json::json!({
"currentContext": "starship"
});
let mut docker_config = File::create(cfg_file)?;
docker_config.write_all(config_content.to_string().as_bytes())?;
docker_config.sync_all()?;
let actual = ModuleRenderer::new("docker_context")
.env("DOCKER_CONFIG", cfg_dir.path().to_string_lossy())
.path(pwd.path())
.collect();
let expected = Some(format!("via {} ", Color::Blue.bold().paint("🐳 starship")));
assert_eq!(expected, actual);
cfg_dir.close()?;
pwd.close()
}
#[test]
fn test_with_dockerfile() -> io::Result<()> {
let cfg_dir = tempfile::tempdir()?;
let cfg_file = cfg_dir.path().join("config.json");
let pwd = tempfile::tempdir()?;
File::create(pwd.path().join("Dockerfile"))?.sync_all()?;
let config_content = serde_json::json!({
"currentContext": "starship"
});
let mut docker_config = File::create(cfg_file)?;
docker_config.write_all(config_content.to_string().as_bytes())?;
docker_config.sync_all()?;
let actual = ModuleRenderer::new("docker_context")
.env("DOCKER_CONFIG", cfg_dir.path().to_string_lossy())
.path(pwd.path())
.collect();
let expected = Some(format!("via {} ", Color::Blue.bold().paint("🐳 starship")));
assert_eq!(expected, actual);
cfg_dir.close()?;
pwd.close()
}
#[test]
fn test_no_docker_files() -> io::Result<()> {
let cfg_dir = tempfile::tempdir()?;
let cfg_file = cfg_dir.path().join("config.json");
let config_content = serde_json::json!({
"currentContext": "starship"
});
let mut docker_config = File::create(cfg_file)?;
docker_config.write_all(config_content.to_string().as_bytes())?;
docker_config.sync_all()?;
let actual = ModuleRenderer::new("docker_context")
.env("DOCKER_CONFIG", cfg_dir.path().to_string_lossy())
.collect();
let expected = None;
assert_eq!(expected, actual);
cfg_dir.close()
}
#[test]
fn test_no_scan_for_docker_files() -> io::Result<()> {
let cfg_dir = tempfile::tempdir()?;
let cfg_file = cfg_dir.path().join("config.json");
let config_content = serde_json::json!({
"currentContext": "starship"
});
let mut docker_config = File::create(cfg_file)?;
docker_config.write_all(config_content.to_string().as_bytes())?;
docker_config.sync_all()?;
let actual = ModuleRenderer::new("docker_context")
.env("DOCKER_CONFIG", cfg_dir.path().to_string_lossy())
.config(toml::toml! {
[docker_context]
only_with_files = false
})
.collect();
let expected = Some(format!("via {} ", Color::Blue.bold().paint("🐳 starship")));
assert_eq!(expected, actual);
cfg_dir.close()
}
#[test]
fn test_invalid_json() -> io::Result<()> {
let cfg_dir = tempfile::tempdir()?;
let cfg_file = cfg_dir.path().join("config.json");
let config_content = "not valid json";
let mut docker_config = File::create(cfg_file)?;
docker_config.write_all(config_content.to_string().as_bytes())?;
docker_config.sync_all()?;
let actual = ModuleRenderer::new("docker_context")
.env("DOCKER_CONFIG", cfg_dir.path().to_string_lossy())
.config(toml::toml! {
[docker_context]
only_with_files = false
})
.collect();
let expected = None;
assert_eq!(expected, actual);
cfg_dir.close()
}
#[test]
fn test_docker_host_env() -> io::Result<()> {
let cfg_dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("docker_context")
.env("DOCKER_HOST", "udp://starship@127.0.0.1:53")
.config(toml::toml! {
[docker_context]
only_with_files = false
})
.collect();
let expected = Some(format!(
"via {} ",
Color::Blue.bold().paint("🐳 udp://starship@127.0.0.1:53")
));
assert_eq!(expected, actual);
cfg_dir.close()
}
#[test]
fn test_docker_host_env_with_unix_path() -> io::Result<()> {
let cfg_dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("docker_context")
.env("DOCKER_HOST", "unix:///run/user/1001/podman/podman.sock")
.config(toml::toml! {
[docker_context]
only_with_files = false
})
.collect();
let expected = None;
assert_eq!(expected, actual);
cfg_dir.close()
}
#[test]
fn test_docker_context_env() -> io::Result<()> {
let cfg_dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("docker_context")
.env("DOCKER_CONTEXT", "starship")
.config(toml::toml! {
[docker_context]
only_with_files = false
})
.collect();
let expected = Some(format!("via {} ", Color::Blue.bold().paint("🐳 starship")));
assert_eq!(expected, actual);
cfg_dir.close()
}
#[test]
fn test_docker_context_default() -> io::Result<()> {
let cfg_dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("docker_context")
.env("DOCKER_CONTEXT", "default")
.config(toml::toml! {
[docker_context]
only_with_files = false
})
.collect();
let expected = None;
assert_eq!(expected, actual);
cfg_dir.close()
}
#[test]
fn test_docker_context_default_after_3_5() -> io::Result<()> {
let cfg_dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("docker_context")
.env("DOCKER_CONTEXT", "desktop-linux")
.config(toml::toml! {
[docker_context]
only_with_files = false
})
.collect();
let expected = None;
assert_eq!(expected, actual);
cfg_dir.close()
}
#[test]
fn test_docker_context_overrides_config() -> io::Result<()> {
let cfg_dir = tempfile::tempdir()?;
let cfg_file = cfg_dir.path().join("config.json");
let config_content = serde_json::json!({
"currentContext": "starship"
});
let mut docker_config = File::create(cfg_file)?;
docker_config.write_all(config_content.to_string().as_bytes())?;
docker_config.sync_all()?;
let actual = ModuleRenderer::new("docker_context")
.env("DOCKER_CONTEXT", "starship")
.env("DOCKER_CONFIG", cfg_dir.path().to_string_lossy())
.config(toml::toml! {
[docker_context]
only_with_files = false
})
.collect();
let expected = Some(format!("via {} ", Color::Blue.bold().paint("🐳 starship")));
assert_eq!(expected, actual);
cfg_dir.close()
}
#[test]
fn test_docker_host_overrides_docker_context_env_and_conf() -> io::Result<()> {
let cfg_dir = tempfile::tempdir()?;
let cfg_file = cfg_dir.path().join("config.json");
let config_content = serde_json::json!({
"currentContext": "starship"
});
let mut docker_config = File::create(cfg_file)?;
docker_config.write_all(config_content.to_string().as_bytes())?;
docker_config.sync_all()?;
let actual = ModuleRenderer::new("docker_context")
.env("DOCKER_HOST", "udp://starship@127.0.0.1:53")
.env("DOCKER_CONTEXT", "starship")
.env("DOCKER_CONFIG", cfg_dir.path().to_string_lossy())
.config(toml::toml! {
[docker_context]
only_with_files = false
})
.collect();
let expected = Some(format!(
"via {} ",
Color::Blue.bold().paint("🐳 udp://starship@127.0.0.1:53")
));
assert_eq!(expected, actual);
cfg_dir.close()
}
#[test]
fn test_docker_machine_name_overrides_other_env_vars_and_conf() -> io::Result<()> {
let cfg_dir = tempfile::tempdir()?;
let cfg_file = cfg_dir.path().join("config.json");
let config_content = serde_json::json!({
"currentContext": "starship"
});
let mut docker_config = File::create(cfg_file)?;
docker_config.write_all(config_content.to_string().as_bytes())?;
docker_config.sync_all()?;
let actual = ModuleRenderer::new("docker_context")
.env("DOCKER_MACHINE_NAME", "machine_name")
.env("DOCKER_HOST", "udp://starship@127.0.0.1:53")
.env("DOCKER_CONTEXT", "starship")
.env("DOCKER_CONFIG", cfg_dir.path().to_string_lossy())
.config(toml::toml! {
[docker_context]
only_with_files = false
})
.collect();
let expected = Some(format!(
"via {} ",
Color::Blue.bold().paint("🐳 machine_name")
));
assert_eq!(expected, actual);
cfg_dir.close()
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/lua.rs | src/modules/lua.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::lua::LuaConfig;
use crate::formatter::StringFormatter;
use crate::formatter::VersionFormatter;
use crate::utils::get_command_string_output;
/// Creates a module with the current Lua version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("lua");
let config = LuaConfig::try_load(module.config);
let is_lua_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_folders(&config.detect_folders)
.set_extensions(&config.detect_extensions)
.is_match();
if !is_lua_project {
return None;
}
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,
})
.map(|variable| match variable {
"version" => {
let lua_version_string =
get_command_string_output(context.exec_cmd(config.lua_binary, &["-v"])?);
let lua_version = parse_lua_version(&lua_version_string)?;
VersionFormatter::format_module_version(
module.get_name(),
&lua_version,
config.version_format,
)
.map(Ok)
}
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `lua`:\n{error}");
return None;
}
});
Some(module)
}
fn parse_lua_version(lua_version: &str) -> Option<String> {
// lua -v output looks like this:
// Lua 5.4.0 Copyright (C) 1994-2020 Lua.org, PUC-Rio
// luajit -v output looks like this:
// LuaJIT 2.0.5 -- Copyright (C) 2005-2017 Mike Pall. http://luajit.org/
let version = lua_version
// Lua: split into ["Lua", "5.4.0", "Copyright", ...]
// LuaJIT: split into ["LuaJIT", "2.0.5", "--", ...]
.split_whitespace()
// Lua: take "5.4.0"
// LuaJIT: take "2.0.5"
.nth(1)?;
Some(version.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
use std::fs::{self, File};
use std::io;
#[test]
fn folder_without_lua_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("lua").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_lua_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("main.lua"))?.sync_all()?;
let actual = ModuleRenderer::new("lua").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Blue.bold().paint("🌙 v5.4.0 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_lua_version() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join(".lua-version"))?.sync_all()?;
let actual = ModuleRenderer::new("lua").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Blue.bold().paint("🌙 v5.4.0 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_lua_folder() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let lua_dir = dir.path().join("lua");
fs::create_dir_all(lua_dir)?;
let actual = ModuleRenderer::new("lua").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Blue.bold().paint("🌙 v5.4.0 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn lua_binary_is_luajit() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("main.lua"))?.sync_all()?;
let config = toml::toml! {
[lua]
lua_binary = "luajit"
};
let actual = ModuleRenderer::new("lua")
.path(dir.path())
.config(config)
.collect();
let expected = Some(format!("via {}", Color::Blue.bold().paint("🌙 v2.0.5 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn test_parse_lua_version() {
let lua_input = "Lua 5.4.0 Copyright (C) 1994-2020 Lua.org, PUC-Rio";
assert_eq!(parse_lua_version(lua_input), Some("5.4.0".to_string()));
let luajit_input =
"LuaJIT 2.1.0-beta3 -- Copyright (C) 2005-2017 Mike Pall. http://luajit.org/";
assert_eq!(
parse_lua_version(luajit_input),
Some("2.1.0-beta3".to_string())
);
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/netns.rs | src/modules/netns.rs | use super::{Context, Module};
#[cfg(not(target_os = "linux"))]
pub fn module<'a>(_context: &'a Context) -> Option<Module<'a>> {
None
}
#[cfg(target_os = "linux")]
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
use crate::{config::ModuleConfig, configs::netns::NetnsConfig, formatter::StringFormatter};
fn netns_name(context: &Context) -> Option<String> {
context
.exec_cmd("ip", &["netns", "identify"])
.map(|output| output.stdout.trim().to_string())
.filter(|name| !name.is_empty())
}
let mut module = context.new_module("netns");
let config = NetnsConfig::try_load(module.config);
if config.disabled {
return None;
}
let netns_name = netns_name(context)?;
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|variable, _| match variable {
"symbol" => Some(config.symbol),
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map(|variable| match variable {
"name" => Some(Ok(&netns_name)),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `netns`: \n{error}");
return None;
}
});
Some(module)
}
#[cfg(test)]
mod tests {
use crate::test::ModuleRenderer;
#[cfg(target_os = "linux")]
use crate::utils::CommandOutput;
#[cfg(target_os = "linux")]
use nu_ansi_term::Color;
#[cfg(target_os = "linux")]
fn mock_ip_netns_identify(netns_name: &str) -> Option<CommandOutput> {
Some(CommandOutput {
stdout: format!("{netns_name}\n"),
stderr: String::new(),
})
}
#[test]
fn test_none_if_disabled() {
let expected = None;
let actual = ModuleRenderer::new("netns")
.config(toml::toml! {
[netns]
disabled = true
})
.collect();
assert_eq!(expected, actual);
}
#[test]
#[cfg(target_os = "linux")]
fn test_netns_identify() {
let actual = ModuleRenderer::new("netns")
.config(toml::toml! {
[netns]
disabled = false
})
.cmd("ip netns identify", mock_ip_netns_identify("test_netns"))
.collect();
let expected = Some(format!(
"{} ",
Color::Blue.bold().dimmed().paint("🛜 [test_netns]")
));
assert_eq!(actual, expected);
}
#[test]
#[cfg(target_os = "linux")]
fn test_netns_identify_empty() {
let actual = ModuleRenderer::new("netns")
.config(toml::toml! {
[netns]
disabled = false
})
.cmd("ip netns identify", mock_ip_netns_identify(""))
.collect();
let expected = None;
assert_eq!(actual, expected);
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/git_metrics.rs | src/modules/git_metrics.rs | use gix::bstr::{BStr, ByteSlice};
use gix::diff::blob::ResourceKind;
use gix::diff::blob::pipeline::WorktreeRoots;
use rayon::prelude::{IntoParallelRefIterator, ParallelIterator};
use regex::Regex;
use super::Context;
use crate::configs::git_status::GitStatusConfig;
use crate::modules::git_status::uses_reftables;
use crate::{
config::ModuleConfig, configs::git_metrics::GitMetricsConfig, formatter::StringFormatter,
formatter::string_formatter::StringFormatterError, module::Module,
};
/// Creates a module with the current added/deleted lines in the git repository at the
/// current directory
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("git_metrics");
let config: GitMetricsConfig = GitMetricsConfig::try_load(module.config);
// As we default to disabled=true, we have to check here after loading our config module,
// before it was only checking against whatever is in the config starship.toml
if config.disabled {
return None;
}
let repo = context.get_repo().ok()?;
let gix_repo = repo.open();
if gix_repo.is_bare() {
return None;
}
let status_module = context.new_module("git_status");
let status_config = GitStatusConfig::try_load(status_module.config);
// TODO: remove this special case once `gitoxide` can handle sparse indices for tree-index comparisons.
let stats = if repo.fs_monitor_value_is_true
|| status_config.use_git_executable
|| uses_reftables(&repo.repo.to_thread_local())
|| gix_repo.index_or_empty().ok()?.is_sparse()
{
let mut git_args = vec!["diff", "--shortstat"];
if config.ignore_submodules {
git_args.push("--ignore-submodules");
}
let diff = repo.exec_git(context, &git_args)?.stdout;
GitDiff::parse(&diff)
} else {
#[derive(Default)]
struct Diff {
added: usize,
deleted: usize,
}
impl Diff {
fn add(&mut self, c: Option<gix::diff::blob::sink::Counter<()>>) {
let Some(c) = c else { return };
self.added += c.insertions as usize;
self.deleted += c.removals as usize;
}
}
let status = super::git_status::get_static_repo_status(context, repo, &status_config)?;
let gix_repo = gix_repo.with_object_memory();
gix_repo.write_blob([]).ok()?; /* create empty blob */
let tree_index_cache = prevent_external_diff(
gix_repo
.diff_resource_cache(
gix::diff::blob::pipeline::Mode::ToGit,
WorktreeRoots::default(),
)
.ok()?,
);
let index_worktree_cache = prevent_external_diff(
gix_repo
.diff_resource_cache(
gix::diff::blob::pipeline::Mode::ToGit,
WorktreeRoots {
old_root: None,
new_root: gix_repo.workdir().map(ToOwned::to_owned),
},
)
.ok()?,
);
let diff = status
.changes
.par_iter()
.map_init(
{
let repo = gix_repo.into_sync();
move || {
let repo = repo.to_thread_local();
(repo, tree_index_cache.clone(), index_worktree_cache.clone())
}
},
|(repo, tree_index_cache, index_worktree_cache), change| {
use gix::status;
let mut diff = Diff::default();
match change {
status::Item::TreeIndex(change) => {
use gix::diff::index::Change;
match change {
Change::Addition {
entry_mode,
location,
id,
..
} => {
diff.added += count_lines(
location,
id.as_ref().into(),
*entry_mode,
tree_index_cache,
repo,
);
}
Change::Deletion {
entry_mode,
location,
id,
..
} => {
diff.deleted += count_lines(
location,
id.as_ref().into(),
*entry_mode,
tree_index_cache,
repo,
);
}
Change::Modification {
location,
previous_entry_mode,
previous_id,
entry_mode,
id,
..
} => {
let location = location.as_ref();
diff.add(diff_two_opt(
location,
previous_id.as_ref().to_owned(),
*previous_entry_mode,
location,
id.as_ref().to_owned(),
*entry_mode,
tree_index_cache,
repo,
));
}
Change::Rewrite {
source_location,
source_entry_mode,
source_id,
location,
entry_mode,
id,
copy,
..
} => {
if *copy {
diff.added += count_lines(
location,
id.as_ref().into(),
*entry_mode,
tree_index_cache,
repo,
);
} else {
diff.add(diff_two_opt(
source_location.as_ref(),
source_id.as_ref().to_owned(),
*source_entry_mode,
location,
id.as_ref().to_owned(),
*entry_mode,
tree_index_cache,
repo,
));
}
}
}
}
status::Item::IndexWorktree(change) => {
use gix::status::index_worktree::Item;
use gix::status::plumbing::index_as_worktree::{Change, EntryStatus};
match change {
Item::Modification {
rela_path,
entry,
status: EntryStatus::Change(Change::Removed),
..
} => {
diff.deleted += count_lines(
rela_path.as_bstr(),
entry.id,
entry.mode,
tree_index_cache,
repo,
);
}
Item::Modification {
rela_path,
entry,
status:
EntryStatus::Change(Change::Modification {
content_change: Some(()),
..
}),
..
} => {
let location = rela_path.as_bstr();
diff.add(diff_two_opt(
location,
entry.id,
entry.mode,
location,
repo.object_hash().null(),
entry.mode,
index_worktree_cache,
repo,
));
}
Item::Modification {
rela_path,
entry,
status: EntryStatus::IntentToAdd,
..
} => {
diff.added += count_lines(
rela_path.as_bstr(),
repo.object_hash().null(),
entry.mode,
index_worktree_cache,
repo,
);
}
Item::Rewrite { .. } => {
unreachable!("not activated")
}
_ => {}
}
}
}
diff
},
)
.reduce(Diff::default, |a, b| Diff {
added: a.added + b.added,
deleted: a.deleted + b.deleted,
});
GitDiff {
added: diff.added.to_string(),
deleted: diff.deleted.to_string(),
}
};
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_style(|variable| match variable {
"added_style" => Some(Ok(config.added_style)),
"deleted_style" => Some(Ok(config.deleted_style)),
_ => None,
})
.map(|variable| match variable {
"added" => GitDiff::get_variable(config.only_nonzero_diffs, &stats.added),
"deleted" => GitDiff::get_variable(config.only_nonzero_diffs, &stats.deleted),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `git_metrics`:\n{error}");
return None;
}
});
Some(module)
}
fn prevent_external_diff(mut cache: gix::diff::blob::Platform) -> gix::diff::blob::Platform {
cache.options.skip_internal_diff_if_external_is_configured = false;
cache
}
#[allow(clippy::too_many_arguments)]
fn diff_two_opt(
lhs_location: &BStr,
lhs_id: gix::ObjectId,
lhs_kind: gix::index::entry::Mode,
rhs_location: &BStr,
rhs_id: gix::ObjectId,
rhs_kind: gix::index::entry::Mode,
cache: &mut gix::diff::blob::Platform,
find: &impl gix::objs::FindObjectOrHeader,
) -> Option<gix::diff::blob::sink::Counter<()>> {
cache
.set_resource(
lhs_id,
lhs_kind.to_tree_entry_mode()?.kind(),
lhs_location,
ResourceKind::OldOrSource,
find,
)
.ok()?;
cache
.set_resource(
rhs_id,
rhs_kind.to_tree_entry_mode()?.kind(),
rhs_location,
ResourceKind::NewOrDestination,
find,
)
.ok()?;
count_diff_lines(cache.prepare_diff().ok()?)
}
fn count_lines(
location: &BStr,
id: gix::ObjectId,
kind: gix::index::entry::Mode,
cache: &mut gix::diff::blob::Platform,
find: &impl gix::objs::FindObjectOrHeader,
) -> usize {
diff_two_opt(
location,
id.kind().null(),
kind,
location,
id,
kind,
cache,
find,
)
.map_or(0, |diff| diff.insertions as usize)
}
fn count_diff_lines(
prep: gix::diff::blob::platform::prepare_diff::Outcome<'_>,
) -> Option<gix::diff::blob::sink::Counter<()>> {
use gix::diff::blob::platform::prepare_diff::Operation;
match prep.operation {
Operation::InternalDiff { algorithm } => {
let tokens = prep.interned_input();
let counter = gix::diff::blob::diff(
algorithm,
&tokens,
gix::diff::blob::sink::Counter::default(),
);
Some(counter)
}
Operation::ExternalCommand { .. } => {
unreachable!("we disabled that")
}
Operation::SourceOrDestinationIsBinary => None,
}
}
/// Represents the parsed output from a git diff.
#[derive(Default)]
struct GitDiff {
added: String,
deleted: String,
}
impl GitDiff {
/// Returns the first capture group given a regular expression and a string.
/// If it fails to get the capture group it will return "0".
fn get_matched_str<'a>(diff: &'a str, re: &Regex) -> &'a str {
match re.captures(diff) {
Some(caps) => caps.get(1).unwrap().as_str(),
_ => "0",
}
}
/// Parses the result of 'git diff --shortstat' as a `GitDiff` struct.
pub fn parse(diff: &str) -> Self {
let added_re = Regex::new(r"(\d+) \w+\(\+\)").unwrap();
let deleted_re = Regex::new(r"(\d+) \w+\(\-\)").unwrap();
Self {
added: Self::get_matched_str(diff, &added_re).to_owned(),
deleted: Self::get_matched_str(diff, &deleted_re).to_owned(),
}
}
pub fn get_variable(
only_nonzero_diffs: bool,
changed: &str,
) -> Option<Result<&str, StringFormatterError>> {
if only_nonzero_diffs {
match changed {
"0" => None,
_ => Some(Ok(changed)),
}
} else {
Some(Ok(changed))
}
}
}
#[cfg(test)]
mod tests {
use crate::utils::{create_command, write_file};
use std::ffi::OsStr;
use std::fs::OpenOptions;
use std::io::{self, Error, ErrorKind, Write};
use std::path::Path;
use std::process::Stdio;
use crate::modules::git_status::tests::make_sparse;
use crate::test::{FixtureProvider, ModuleRenderer, fixture_repo};
use nu_ansi_term::Color;
const NORMAL_AND_REFTABLES: [FixtureProvider; 2] =
[FixtureProvider::Git, FixtureProvider::GitReftable];
const BARE_AND_REFTABLE: [FixtureProvider; 2] =
[FixtureProvider::GitBare, FixtureProvider::GitBareReftable];
#[test]
fn shows_nothing_on_empty_dir() -> io::Result<()> {
let repo_dir = tempfile::tempdir()?;
let path = repo_dir.path();
let actual = render_metrics(path);
let expected = None;
assert_eq!(expected, actual);
repo_dir.close()
}
#[test]
fn shows_added_lines() -> io::Result<()> {
for mode in NORMAL_AND_REFTABLES {
let repo_dir = create_repo_with_commit(mode)?;
let path = repo_dir.path();
let the_file = path.join("the_file");
let mut the_file = OpenOptions::new().append(true).open(the_file)?;
writeln!(the_file, "Added line")?;
the_file.sync_all()?;
let actual = render_metrics(path);
let expected = Some(format!("{} ", Color::Green.bold().paint("+1"),));
assert_eq!(expected, actual);
repo_dir.close()?;
}
Ok(())
}
#[test]
fn shows_staged_addition() -> io::Result<()> {
for mode in NORMAL_AND_REFTABLES {
let repo_dir = create_repo_with_commit(mode)?;
let path = repo_dir.path();
std::fs::write(path.join("new-file"), "new line")?;
run_git_cmd(["add", "new-file"], Some(path), true)?;
let actual = render_metrics(path);
let expected = if matches!(mode, FixtureProvider::GitReftable) {
// TODO: detect staged changes as well - `git diff` using another `git diff --cached` call.
None
} else {
Some(format!("{} ", Color::Green.bold().paint("+1")))
};
assert_eq!(expected, actual);
repo_dir.close()?;
}
Ok(())
}
#[test]
fn shows_staged_rename_modification() -> io::Result<()> {
for mode in NORMAL_AND_REFTABLES {
let repo_dir = create_repo_with_commit(mode)?;
let path = repo_dir.path();
let the_file = path.join("the_file");
let mut the_file = OpenOptions::new().append(true).open(the_file)?;
writeln!(the_file, "Added line")?;
the_file.sync_all()?;
run_git_cmd(["add", "the_file"], Some(path), true)?;
run_git_cmd(["mv", "the_file", "that_file"], Some(path), true)?;
let actual = render_metrics(path);
let expected = if matches!(mode, FixtureProvider::GitReftable) {
// TODO: detect staged changes as well - `git diff` using another `git diff --cached` call.
None
} else {
Some(format!("{} ", Color::Green.bold().paint("+1")))
};
assert_eq!(expected, actual);
repo_dir.close()?;
}
Ok(())
}
#[test]
fn shows_staged_addition_intended() -> io::Result<()> {
for mode in NORMAL_AND_REFTABLES {
let repo_dir = create_repo_with_commit(mode)?;
let path = repo_dir.path();
std::fs::write(path.join("new-file"), "new line")?;
run_git_cmd(["add", "-N", "new-file"], Some(path), true)?;
let actual = render_metrics(path);
let expected = Some(format!("{} ", Color::Green.bold().paint("+1"),));
assert_eq!(expected, actual);
repo_dir.close()?;
}
Ok(())
}
#[test]
fn shows_staged_modification() -> io::Result<()> {
for mode in NORMAL_AND_REFTABLES {
let repo_dir = create_repo_with_commit(mode)?;
let path = repo_dir.path();
std::fs::write(path.join("the_file"), "modify all")?;
run_git_cmd(["add", "the_file"], Some(path), true)?;
let actual = render_metrics(path);
let expected = if matches!(mode, FixtureProvider::GitReftable) {
// TODO: detect staged changes as well - `git diff` using another `git diff --cached` call.
None
} else {
Some(format!(
"{} {} ",
Color::Green.bold().paint("+1"),
Color::Red.bold().paint("-3")
))
};
assert_eq!(expected, actual);
repo_dir.close()?;
}
Ok(())
}
#[test]
fn shows_deleted_lines() -> io::Result<()> {
for mode in NORMAL_AND_REFTABLES {
let repo_dir = create_repo_with_commit(mode)?;
let path = repo_dir.path();
let file_path = path.join("the_file");
write_file(file_path, "First Line\nSecond Line\n")?;
let actual = render_metrics(path);
let expected = Some(format!("{} ", Color::Red.bold().paint("-1")));
assert_eq!(expected, actual);
repo_dir.close()?;
}
Ok(())
}
#[test]
fn shows_deleted_lines_of_entire_file() -> io::Result<()> {
for mode in NORMAL_AND_REFTABLES {
let repo_dir = create_repo_with_commit(mode)?;
let path = repo_dir.path();
std::fs::remove_file(path.join("the_file"))?;
let actual = render_metrics(path);
let expected = Some(format!("{} ", Color::Red.bold().paint("-3")));
assert_eq!(expected, actual);
repo_dir.close()?;
}
Ok(())
}
#[test]
fn shows_staged_deletion() -> io::Result<()> {
for mode in NORMAL_AND_REFTABLES {
let repo_dir = create_repo_with_commit(mode)?;
let path = repo_dir.path();
run_git_cmd(["rm", "the_file"], Some(path), true)?;
let actual = render_metrics(path);
let expected = if matches!(mode, FixtureProvider::GitReftable) {
// TODO: detect staged changes as well - `git diff` using another `git diff --cached` call.
None
} else {
Some(format!("{} ", Color::Red.bold().paint("-3")))
};
assert_eq!(expected, actual);
repo_dir.close()?;
}
Ok(())
}
#[test]
fn shows_all_changes() -> io::Result<()> {
for mode in NORMAL_AND_REFTABLES {
let repo_dir = create_repo_with_commit(mode)?;
let path = repo_dir.path();
let file_path = path.join("the_file");
write_file(file_path, "\nSecond Line\n\nModified\nAdded\n")?;
let actual = render_metrics(path);
let expected = Some(format!(
"{} {} ",
Color::Green.bold().paint("+4"),
Color::Red.bold().paint("-2")
));
assert_eq!(expected, actual);
repo_dir.close()?;
}
Ok(())
}
#[test]
fn shows_nothing_if_no_changes() -> io::Result<()> {
for mode in NORMAL_AND_REFTABLES {
let repo_dir = create_repo_with_commit(mode)?;
let path = repo_dir.path();
let actual = render_metrics(path);
let expected = None;
assert_eq!(expected, actual);
repo_dir.close()?;
}
Ok(())
}
#[test]
fn shows_nothing_on_untracked() -> io::Result<()> {
for mode in NORMAL_AND_REFTABLES {
let repo_dir = create_repo_with_commit(mode)?;
let path = repo_dir.path();
std::fs::write(path.join("untracked"), "a line")?;
let actual = render_metrics(path);
let expected = None;
assert_eq!(expected, actual);
repo_dir.close()?;
}
Ok(())
}
#[test]
fn shows_nothing_if_no_changes_sparse() -> io::Result<()> {
for mode in NORMAL_AND_REFTABLES {
let repo_dir = create_repo_with_commit(mode)?;
let path = repo_dir.path();
make_sparse(path)?;
let actual = render_metrics(path);
let expected = None;
assert_eq!(expected, actual);
repo_dir.close()?;
}
Ok(())
}
#[test]
fn shows_all_if_only_nonzero_diffs_is_false() -> io::Result<()> {
for mode in NORMAL_AND_REFTABLES {
let repo_dir = create_repo_with_commit(mode)?;
let path = repo_dir.path();
let the_file = path.join("the_file");
let mut the_file = OpenOptions::new().append(true).open(the_file)?;
writeln!(the_file, "Added line")?;
the_file.sync_all()?;
let actual = ModuleRenderer::new("git_metrics")
.config(toml::toml! {
[git_metrics]
disabled = false
only_nonzero_diffs = true
})
.path(path)
.collect();
let expected = Some(format!("{} ", Color::Green.bold().paint("+1"),));
assert_eq!(expected, actual);
repo_dir.close()?;
}
Ok(())
}
#[test]
fn doesnt_generate_git_metrics_for_bare_repo() -> io::Result<()> {
for mode in BARE_AND_REFTABLE {
let repo_dir = fixture_repo(mode)?;
let actual = render_metrics(repo_dir.path());
assert_eq!(None, actual);
repo_dir.close()?;
}
Ok(())
}
#[test]
fn shows_all_changes_with_ignored_submodules() -> io::Result<()> {
for mode in NORMAL_AND_REFTABLES {
let repo_dir = create_repo_with_commit(mode)?;
let path = repo_dir.path();
let file_path = path.join("the_file");
write_file(file_path, "\nSecond Line\n\nModified\nAdded\n")?;
let actual = ModuleRenderer::new("git_metrics")
.config(toml::toml! {
[git_metrics]
disabled = false
ignore_submodules = true
})
.path(path)
.collect();
let expected = Some(format!(
"{} {} ",
Color::Green.bold().paint("+4"),
Color::Red.bold().paint("-2")
));
assert_eq!(expected, actual);
repo_dir.close()?;
}
Ok(())
}
#[test]
fn works_if_git_executable_is_used() -> io::Result<()> {
for mode in NORMAL_AND_REFTABLES {
let repo_dir = create_repo_with_commit(mode)?;
let path = repo_dir.path();
let file_path = path.join("the_file");
write_file(file_path, "\nSecond Line\n\nModified\nAdded\n")?;
let actual = ModuleRenderer::new("git_metrics")
.config(toml::toml! {
[git_status]
use_git_executable = true
[git_metrics]
disabled = false
})
.path(path)
.collect();
let expected = Some(format!(
"{} {} ",
Color::Green.bold().paint("+4"),
Color::Red.bold().paint("-2")
));
assert_eq!(expected, actual);
repo_dir.close()?;
}
Ok(())
}
fn render_metrics(path: &Path) -> Option<String> {
ModuleRenderer::new("git_metrics")
.config(toml::toml! {
[git_metrics]
disabled = false
})
.path(path)
.collect()
}
fn run_git_cmd<A, S>(args: A, dir: Option<&Path>, should_succeed: bool) -> io::Result<()>
where
A: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
let mut command = create_command("git")?;
command
.args(args)
.stdout(Stdio::null())
.stderr(Stdio::null())
.stdin(Stdio::null());
if let Some(dir) = dir {
command.current_dir(dir);
}
let status = command.status()?;
if should_succeed && !status.success() {
Err(Error::from(ErrorKind::Other))
} else {
Ok(())
}
}
fn create_repo_with_commit(provider: FixtureProvider) -> io::Result<tempfile::TempDir> {
let repo_dir = tempfile::tempdir()?;
let path = repo_dir.path();
let file = repo_dir.path().join("the_file");
// Initialize a new git repo
run_git_cmd(
["init", "--quiet"]
.into_iter()
.chain(
matches!(provider, FixtureProvider::GitReftable)
.then(|| "--ref-format=reftable"),
)
.chain(Some(path.to_str().expect("Path was not UTF-8"))),
None,
true,
)?;
// Set local author info
run_git_cmd(
["config", "--local", "user.email", "starship@example.com"],
Some(path),
true,
)?;
run_git_cmd(
["config", "--local", "user.name", "starship"],
Some(path),
true,
)?;
// Ensure on the expected branch.
// If build environment has `init.defaultBranch` global set
// it will default to an unknown branch, so need to make & change branch
run_git_cmd(
["checkout", "-b", "master"],
Some(path),
// command expected to fail if already on the expected branch
false,
)?;
// Write a file on master and commit it
write_file(file, "First Line\nSecond Line\nThird Line\n")?;
run_git_cmd(["add", "the_file"], Some(path), true)?;
run_git_cmd(
["commit", "--message", "Commit A", "--no-gpg-sign"],
Some(path),
true,
)?;
Ok(repo_dir)
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/fortran.rs | src/modules/fortran.rs | use std::{borrow::Cow, ops::Deref, sync::LazyLock};
use semver::Version;
use crate::{
config::ModuleConfig,
configs::fortran::FortranConfig,
formatter::{StringFormatter, VersionFormatter},
};
use super::{Context, Module};
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("fortran");
let config = FortranConfig::try_load(module.config);
let is_fortran_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_fortran_project {
return None;
}
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
let compiler_info = LazyLock::new(|| context.exec_cmds_return_first(&config.commands));
formatter
.map_meta(|var, _| match var {
"symbol" => Some(config.symbol),
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map(|variable| match variable {
"name" => {
let compiler_info = &compiler_info.deref().as_ref()?.stdout;
let compiler = if compiler_info.contains("GNU") {
"gfortran"
} else if compiler_info.contains("flang-new") || compiler_info.contains("flang")
{
"flang"
} else {
return None;
};
Some(Ok(Cow::Borrowed(compiler)))
}
"version" => {
let compiler_info = &compiler_info.deref().as_ref()?.stdout;
VersionFormatter::format_module_version(
module.get_name(),
compiler_info
.split_whitespace()
.find(|word| Version::parse(word).is_ok())?,
config.version_format,
)
.map(Cow::Owned)
.map(Ok)
}
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `fortran`:\n{}", error);
return None;
}
});
Some(module)
}
#[cfg(test)]
mod tests {
use std::{fs::File, io};
use nu_ansi_term::Color;
use crate::{test::ModuleRenderer, utils::CommandOutput};
#[test]
fn folder_without_fortran_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("fortran").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_f_fortran_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("test.f"))?.sync_all()?;
let actual = ModuleRenderer::new("fortran")
.cmd(
"gfortran --version",
Some(CommandOutput {
stdout: String::from(
"\
GNU Fortran (Homebrew GCC 14.2.0_1) 14.2.0
Copyright (C) 2024 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n",
),
stderr: String::default(),
}),
)
.path(dir.path())
.collect();
let expected = Some(format!(
"via {}",
Color::Purple.bold().paint("🅵 14.2.0-gfortran ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_f_fortran_file_but_no_compiler() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("test.f"))?.sync_all()?;
let actual = ModuleRenderer::new("fortran")
.cmd("gfortran --version", None)
.cmd("flang --version", None)
.cmd("flang-new --version", None)
.path(dir.path())
.collect();
let expected = Some(format!("via {}", Color::Purple.bold().paint("🅵 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_f_fortran_file_and_flang() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("test.f"))?.sync_all()?;
let actual = ModuleRenderer::new("fortran")
.cmd("gfortran --version", None)
.cmd(
"flang --version",
Some(CommandOutput {
stdout: String::from(
"\
Homebrew flang version 20.1.3
Target: arm64-apple-darwin24.3.0
Thread model: posix
InstalledDir: /opt/homebrew/Cellar/flang/20.1.3/libexec
Configuration file: /opt/homebrew/Cellar/flang/20.1.3/libexec/flang.cfg
Configuration file: /opt/homebrew/etc/clang/arm64-apple-darwin24.cfg",
),
stderr: String::default(),
}),
)
.path(dir.path())
.collect();
let expected = Some(format!(
"via {}",
Color::Purple.bold().paint("🅵 20.1.3-flang ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_f_fortran_file_without_gfortran_flang_falls_to_flang_new() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("test.f"))?.sync_all()?;
let actual = ModuleRenderer::new("fortran")
.cmd("gfortran --version", None)
.cmd("flang --version", None)
.cmd(
"flang-new --version",
Some(CommandOutput {
stdout: String::from(
"\
Homebrew flang version 20.1.3
Target: arm64-apple-darwin24.3.0
Thread model: posix
InstalledDir: /opt/homebrew/Cellar/flang/20.1.3/libexec
Configuration file: /opt/homebrew/Cellar/flang/20.1.3/libexec/flang.cfg
Configuration file: /opt/homebrew/etc/clang/arm64-apple-darwin24.cfg",
),
stderr: String::default(),
}),
)
.path(dir.path())
.collect();
let expected = Some(format!(
"via {}",
Color::Purple.bold().paint("🅵 20.1.3-flang ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_capital_f18_fortran_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("test.F18"))?.sync_all()?;
let actual = ModuleRenderer::new("fortran")
.cmd(
"gfortran --version",
Some(CommandOutput {
stdout: String::from(
"\
GNU Fortran (Homebrew GCC 14.2.0_1) 14.2.0
Copyright (C) 2024 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n",
),
stderr: String::default(),
}),
)
.path(dir.path())
.collect();
let expected = Some(format!(
"via {}",
Color::Purple.bold().paint("🅵 14.2.0-gfortran ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_fpm_config_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("fpm.toml"))?.sync_all()?;
let actual = ModuleRenderer::new("fortran")
.cmd(
"gfortran --version",
Some(CommandOutput {
stdout: String::from(
"\
GNU Fortran (Homebrew GCC 14.2.0_1) 14.2.0
Copyright (C) 2024 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n",
),
stderr: String::default(),
}),
)
.path(dir.path())
.collect();
let expected = Some(format!(
"via {}",
Color::Purple.bold().paint("🅵 14.2.0-gfortran ")
));
assert_eq!(expected, actual);
dir.close()
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/odin.rs | src/modules/odin.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::odin::OdinConfig;
use crate::formatter::StringFormatter;
/// Creates a module with the current Odin version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("odin");
let config = OdinConfig::try_load(module.config);
let is_odin_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_odin_project {
return None;
}
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|variable, _| match variable {
"symbol" => Some(config.symbol),
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map(|variable| match variable {
"version" => {
let odin_version = context.exec_cmd("odin", &["version"])?.stdout;
let trimmed_version = odin_version.split(' ').next_back()?.trim().to_string();
if config.show_commit {
return Some(Ok(trimmed_version));
}
let no_commit = trimmed_version.split(':').next()?.trim().to_string();
Some(Ok(no_commit))
}
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `odin`:\n{error}");
return None;
}
});
Some(module)
}
#[cfg(test)]
mod tests {
use crate::test::ModuleRenderer;
use crate::utils::CommandOutput;
use nu_ansi_term::Color;
use std::fs::File;
use std::io;
#[test]
fn folder_without_odin() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("odin.txt"))?.sync_all()?;
let actual = ModuleRenderer::new("odin").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_odin_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("main.odin"))?.sync_all()?;
let actual = ModuleRenderer::new("odin").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::LightBlue.bold().paint("Ø dev-2024-03 ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_odin_file_without_commit() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("main.odin"))?.sync_all()?;
let actual = ModuleRenderer::new("odin")
.cmd(
"odin version",
Some(CommandOutput {
stdout: String::from("odin version dev-2024-03\n"),
stderr: String::default(),
}),
)
.path(dir.path())
.collect();
let expected = Some(format!(
"via {}",
Color::LightBlue.bold().paint("Ø dev-2024-03 ")
));
assert_eq!(expected, actual);
dir.close()
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/crystal.rs | src/modules/crystal.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::crystal::CrystalConfig;
use crate::formatter::StringFormatter;
use crate::formatter::VersionFormatter;
/// Creates a module with the current Crystal version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("crystal");
let config: CrystalConfig = CrystalConfig::try_load(module.config);
let is_crystal_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_crystal_project {
return None;
}
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|variable, _| match variable {
"symbol" => Some(config.symbol),
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map(|variable| match variable {
"version" => {
let crystal_version = parse_crystal_version(
&context.exec_cmd("crystal", &["--version"])?.stdout,
)?;
VersionFormatter::format_module_version(
module.get_name(),
&crystal_version,
config.version_format,
)
}
.map(Ok),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `crystal`:\n{error}");
return None;
}
});
Some(module)
}
fn parse_crystal_version(crystal_version: &str) -> Option<String> {
Some(
crystal_version
// split into ["Crystal", "0.35.1", ...]
.split_whitespace()
// return "0.35.1"
.nth(1)?
.to_string(),
)
}
#[cfg(test)]
mod tests {
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
use std::fs::File;
use std::io;
#[test]
fn folder_without_crystal_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("crystal").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_shard_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("shard.yml"))?.sync_all()?;
let actual = ModuleRenderer::new("crystal").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Red.bold().paint("🔮 v0.35.1 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_cr_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("main.cr"))?.sync_all()?;
let actual = ModuleRenderer::new("crystal").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Red.bold().paint("🔮 v0.35.1 ")));
assert_eq!(expected, actual);
dir.close()
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/haxe.rs | src/modules/haxe.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::haxe::HaxeConfig;
use crate::formatter::StringFormatter;
use crate::formatter::VersionFormatter;
use serde_json as json;
use regex::Regex;
const HAXERC_VERSION_PATTERN: &str = "(?:[0-9a-zA-Z][-+0-9.a-zA-Z]+)";
/// Creates a module with the current Haxe version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("haxe");
let config = HaxeConfig::try_load(module.config);
let is_haxe_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_haxe_project {
return None;
}
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,
})
.map(|variable| match variable {
"version" => {
let haxe_version = get_haxe_version(context)?;
VersionFormatter::format_module_version(
module.get_name(),
&haxe_version,
config.version_format,
)
.map(Ok)
}
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `haxe`:\n{error}");
return None;
}
});
Some(module)
}
fn get_haxe_version(context: &Context) -> Option<String> {
get_haxerc_version(context).or_else(|| {
let cmd_output = context.exec_cmd("haxe", &["--version"])?;
parse_haxe_version(cmd_output.stdout.as_str())
})
}
fn get_haxerc_version(context: &Context) -> Option<String> {
let raw_json = context.read_file_from_pwd(".haxerc")?;
let package_json: json::Value = json::from_str(&raw_json).ok()?;
let raw_version = package_json.get("version")?.as_str()?;
if raw_version.contains('/') || raw_version.contains('\\') {
return None;
}
Some(raw_version.to_string())
}
fn parse_haxe_version(raw_version: &str) -> Option<String> {
let re = Regex::new(HAXERC_VERSION_PATTERN).ok()?;
if !re.is_match(raw_version) {
return None;
}
Some(raw_version.trim().to_string())
}
#[cfg(test)]
mod tests {
use super::parse_haxe_version;
use crate::{test::ModuleRenderer, utils::CommandOutput};
use nu_ansi_term::Color;
use serde_json as json;
use std::fs::File;
use std::io;
use std::io::Write;
use tempfile::TempDir;
#[test]
fn haxe_version() {
let ok_versions = [
"4.2.5",
"4.3.0-rc.1+",
"3.4.7abcdf",
"779b005",
"beta",
"alpha",
"latest",
"/git/779b005/bin/haxe",
"git/779b005/bin/haxe",
];
let all_some = ok_versions.iter().all(|&v| parse_haxe_version(v).is_some());
assert!(all_some);
let sample_haxe_output = "4.3.0-rc.1+\n";
assert_eq!(
Some("4.3.0-rc.1+".to_string()),
parse_haxe_version(sample_haxe_output)
);
}
#[test]
fn folder_without_haxe() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("haxe.txt"))?.sync_all()?;
let actual = ModuleRenderer::new("haxe")
.cmd(
"haxe --version",
Some(CommandOutput {
stdout: "4.3.0-rc.1+\n".to_owned(),
stderr: String::new(),
}),
)
.path(dir.path())
.collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_hxml_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("build.hxml"))?.sync_all()?;
let actual = ModuleRenderer::new("haxe")
.cmd(
"haxe --version",
Some(CommandOutput {
stdout: "4.3.0-rc.1+\n".to_owned(),
stderr: String::new(),
}),
)
.path(dir.path())
.collect();
let expected = Some(format!(
"via {}",
Color::Fixed(202).bold().paint("⌘ v4.3.0-rc.1+ ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_haxe_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("Main.hx"))?.sync_all()?;
let actual = ModuleRenderer::new("haxe")
.cmd(
"haxe --version",
Some(CommandOutput {
stdout: "4.3.0-rc.1+\n".to_owned(),
stderr: String::new(),
}),
)
.path(dir.path())
.collect();
let expected = Some(format!(
"via {}",
Color::Fixed(202).bold().paint("⌘ v4.3.0-rc.1+ ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_invalid_haxerc_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let haxerc_name = ".haxerc";
let haxerc_content = json::json!({
"resolveLibs": "scoped"
})
.to_string();
fill_config(&dir, haxerc_name, Some(&haxerc_content))?;
let actual = ModuleRenderer::new("haxe")
.cmd(
"haxe --version",
Some(CommandOutput {
stdout: "4.3.0-rc.1+\n".to_owned(),
stderr: String::new(),
}),
)
.path(dir.path())
.collect();
let expected = Some(format!(
"via {}",
Color::Fixed(202).bold().paint("⌘ v4.3.0-rc.1+ ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_haxerc_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let haxerc_name = ".haxerc";
let haxerc_content = json::json!({
"version": "4.2.5",
"resolveLibs": "scoped"
})
.to_string();
fill_config(&dir, haxerc_name, Some(&haxerc_content))?;
let actual = ModuleRenderer::new("haxe")
.cmd(
"haxe --version",
Some(CommandOutput {
stdout: "4.3.0-rc.1+\n".to_owned(),
stderr: String::new(),
}),
)
.path(dir.path())
.collect();
let expected = Some(format!(
"via {}",
Color::Fixed(202).bold().paint("⌘ v4.2.5 ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_haxerc_nightly_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let haxerc_name = ".haxerc";
let haxerc_content = json::json!({
"version": "779b005",
"resolveLibs": "scoped"
})
.to_string();
fill_config(&dir, haxerc_name, Some(&haxerc_content))?;
let actual = ModuleRenderer::new("haxe")
.cmd(
"haxe --version",
Some(CommandOutput {
stdout: "4.3.0-rc.1+\n".to_owned(),
stderr: String::new(),
}),
)
.path(dir.path())
.collect();
let expected = Some(format!(
"via {}",
Color::Fixed(202).bold().paint("⌘ v779b005 ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_haxerc_with_path() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let haxerc_name = ".haxerc";
let haxerc_content = json::json!({
"version": "/home/git/haxe/haxe.executable",
"resolveLibs": "scoped"
})
.to_string();
fill_config(&dir, haxerc_name, Some(&haxerc_content))?;
let actual = ModuleRenderer::new("haxe")
.cmd(
"haxe --version",
Some(CommandOutput {
stdout: "4.3.0-rc.1+\n".to_owned(),
stderr: String::new(),
}),
)
.path(dir.path())
.collect();
let expected = Some(format!(
"via {}",
Color::Fixed(202).bold().paint("⌘ v4.3.0-rc.1+ ")
));
assert_eq!(expected, actual);
dir.close()
}
fn fill_config(
project_dir: &TempDir,
file_name: &str,
contents: Option<&str>,
) -> io::Result<()> {
let mut file = File::create(project_dir.path().join(file_name))?;
file.write_all(contents.unwrap_or("").as_bytes())?;
file.sync_all()
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/kubernetes.rs | src/modules/kubernetes.rs | use serde_json::Value as JsonValue;
use yaml_rust2::{Yaml, YamlLoader};
use std::borrow::Cow;
use std::env;
use super::{Context, Module, ModuleConfig};
use crate::configs::kubernetes::KubernetesConfig;
use crate::formatter::StringFormatter;
use crate::utils;
#[derive(Default)]
struct KubeCtxComponents {
user: Option<String>,
namespace: Option<String>,
cluster: Option<String>,
}
fn get_current_kube_context_name<T: DataValue>(document: &T) -> Option<&str> {
document
.get("current-context")
.and_then(DataValue::as_str)
.filter(|s| !s.is_empty())
}
fn get_kube_ctx_components<T: DataValue>(
document: &T,
current_ctx_name: &str,
) -> Option<KubeCtxComponents> {
document
.get("contexts")?
.as_array()?
.iter()
.find(|ctx| ctx.get("name").and_then(DataValue::as_str) == Some(current_ctx_name))
.map(|ctx| KubeCtxComponents {
user: ctx
.get("context")
.and_then(|v| v.get("user"))
.and_then(DataValue::as_str)
.map(String::from),
namespace: ctx
.get("context")
.and_then(|v| v.get("namespace"))
.and_then(DataValue::as_str)
.map(String::from),
cluster: ctx
.get("context")
.and_then(|v| v.get("cluster"))
.and_then(DataValue::as_str)
.map(String::from),
})
}
fn get_aliased_name<'a>(
pattern: Option<&'a str>,
current_value: Option<&str>,
alias: Option<&'a str>,
) -> Option<String> {
let replacement = alias.or(current_value)?.to_string();
let Some(pattern) = pattern else {
// If user pattern not set, treat it as a match-all pattern
return Some(replacement);
};
// If a pattern is set, but we have no value, there is no match
let value = current_value?;
if value == pattern {
return Some(replacement);
}
let re = match regex::Regex::new(&format!("^{pattern}$")) {
Ok(re) => re,
Err(error) => {
log::warn!(
"Could not compile regular expression `{}`:\n{}",
&format!("^{pattern}$"),
error
);
return None;
}
};
let replaced = re.replace(value, replacement.as_str());
match replaced {
Cow::Owned(replaced) => Some(replaced),
// It didn't match...
Cow::Borrowed(_) => None,
}
}
#[derive(Debug)]
enum Document {
Json(JsonValue),
Yaml(Yaml),
}
trait DataValue {
fn get(&self, key: &str) -> Option<&Self>;
fn as_str(&self) -> Option<&str>;
fn as_array(&self) -> Option<Vec<&Self>>;
}
impl DataValue for JsonValue {
fn get(&self, key: &str) -> Option<&Self> {
self.get(key)
}
fn as_str(&self) -> Option<&str> {
self.as_str()
}
fn as_array(&self) -> Option<Vec<&Self>> {
self.as_array().map(|arr| arr.iter().collect())
}
}
impl DataValue for Yaml {
fn get(&self, key: &str) -> Option<&Self> {
match self {
Self::Hash(map) => map.get(&Self::String(key.to_string())),
_ => None,
}
}
fn as_str(&self) -> Option<&str> {
self.as_str()
}
fn as_array(&self) -> Option<Vec<&Self>> {
match self {
Self::Array(arr) => Some(arr.iter().collect()),
_ => None,
}
}
}
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("kubernetes");
let config: KubernetesConfig = KubernetesConfig::try_load(module.config);
// As we default to disabled=true, we have to check here after loading our config module,
// before it was only checking against whatever is in the config starship.toml
if config.disabled {
return None;
}
let have_env_config = !config.detect_env_vars.is_empty();
let have_env_vars = have_env_config.then(|| context.detect_env_vars(&config.detect_env_vars));
// If we have some config for doing the directory scan then we use it but if we don't then we
// assume we should treat it like the module is enabled to preserve backward compatibility.
let have_scan_config = [
&config.detect_files,
&config.detect_folders,
&config.detect_extensions,
]
.into_iter()
.any(|v| !v.is_empty());
let is_kube_project = have_scan_config.then(|| {
context.try_begin_scan().is_some_and(|scanner| {
scanner
.set_files(&config.detect_files)
.set_folders(&config.detect_folders)
.set_extensions(&config.detect_extensions)
.is_match()
})
});
if !is_kube_project.or(have_env_vars).unwrap_or(true) {
return None;
}
let default_config_file = context.get_home()?.join(".kube").join("config");
let kube_cfg = context
.get_env("KUBECONFIG")
.unwrap_or(default_config_file.to_str()?.to_string());
let raw_kubeconfigs = env::split_paths(&kube_cfg).map(|file| utils::read_file(file).ok());
let kubeconfigs = parse_kubeconfigs(raw_kubeconfigs);
let current_kube_ctx_name = kubeconfigs.iter().find_map(|v| match v {
Document::Json(json) => get_current_kube_context_name(json),
Document::Yaml(yaml) => get_current_kube_context_name(yaml),
})?;
// Even if we have multiple config files, the first key wins
// https://kubernetes.io/docs/concepts/configuration/organize-cluster-access-kubeconfig/
// > Never change the value or map key. ... Example: If two files specify a red-user,
// > use only values from the first file's red-user. Even if the second file has
// > non-conflicting entries under red-user, discard them.
// for that reason, we can pick the first context with that name
let ctx_components: KubeCtxComponents = kubeconfigs.iter().find_map(|kubeconfig| match kubeconfig {
Document::Json(json) => get_kube_ctx_components(json, current_kube_ctx_name),
Document::Yaml(yaml) => get_kube_ctx_components(yaml, current_kube_ctx_name),
}).unwrap_or_else(|| {
// TODO: figure out if returning is more sensible. But currently we have tests depending on this
log::warn!(
"Invalid KUBECONFIG: identified current-context `{}`, but couldn't find the context in any config file(s): `{}`.\n",
¤t_kube_ctx_name,
&kube_cfg
);
KubeCtxComponents::default()
});
// Select the first style that matches the context_pattern and,
// if it is defined, the user_pattern
let (matched_context_config, display_context, display_user) = config
.contexts
.iter()
.find_map(|context_config| {
let context_alias = get_aliased_name(
Some(context_config.context_pattern),
Some(current_kube_ctx_name),
context_config.context_alias,
)?;
let user_alias = get_aliased_name(
context_config.user_pattern,
ctx_components.user.as_deref(),
context_config.user_alias,
);
if matches!((context_config.user_pattern, &user_alias), (Some(_), None)) {
// defined pattern, but it didn't match
return None;
}
Some((Some(context_config), context_alias, user_alias))
})
.unwrap_or_else(|| (None, current_kube_ctx_name.to_string(), ctx_components.user));
// TODO: remove deprecated aliases after starship 2.0
let display_context =
deprecated::get_alias(display_context, &config.context_aliases, "context").unwrap();
let display_user =
display_user.and_then(|user| deprecated::get_alias(user, &config.user_aliases, "user"));
let display_style = matched_context_config
.and_then(|ctx_cfg| ctx_cfg.style)
.unwrap_or(config.style);
let display_symbol = matched_context_config
.and_then(|ctx_cfg| ctx_cfg.symbol)
.unwrap_or(config.symbol);
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|variable, _| match variable {
"symbol" => Some(display_symbol),
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(display_style)),
_ => None,
})
.map(|variable| match variable {
"context" => Some(Ok(Cow::Borrowed(display_context.as_str()))),
"namespace" => ctx_components
.namespace
.as_ref()
.map(|kube_ns| Ok(Cow::Borrowed(kube_ns.as_str()))),
"cluster" => ctx_components
.cluster
.as_ref()
.map(|kube_cluster| Ok(Cow::Borrowed(kube_cluster.as_str()))),
"user" => display_user
.as_ref()
.map(|kube_user| Ok(Cow::Borrowed(kube_user.as_str()))),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `kubernetes`: \n{error}");
return None;
}
});
Some(module)
}
fn parse_kubeconfigs<I>(raw_kubeconfigs: I) -> Vec<Document>
where
I: Iterator<Item = Option<String>>,
{
raw_kubeconfigs
.filter_map(|content| match content {
Some(value) => match value.chars().next() {
// Parsing as json is about an order of magnitude faster than parsing
// as yaml, so do that if possible.
Some('{') => match serde_json::from_str(&value) {
Ok(json) => Some(Document::Json(json)),
Err(_) => parse_yaml(&value),
},
_ => parse_yaml(&value),
},
_ => None,
})
.collect()
}
fn parse_yaml(s: &str) -> Option<Document> {
YamlLoader::load_from_str(s)
.ok()
.and_then(|yaml| yaml.into_iter().next().map(Document::Yaml))
}
mod deprecated {
use std::borrow::Cow;
use std::collections::HashMap;
pub fn get_alias<'a>(
current_value: String,
aliases: &'a HashMap<String, &'a str>,
name: &'a str,
) -> Option<String> {
let alias = if let Some(val) = aliases.get(current_value.as_str()) {
// simple match without regex
Some((*val).to_string())
} else {
// regex match
aliases.iter().find_map(|(k, v)| {
let re = regex::Regex::new(&format!("^{k}$")).ok()?;
let replaced = re.replace(current_value.as_str(), *v);
match replaced {
// We have a match if the replaced string is different from the original
Cow::Owned(replaced) => Some(replaced),
Cow::Borrowed(_) => None,
}
})
};
match alias {
Some(alias) => {
log::warn!(
"Usage of '{}_aliases' is deprecated and will be removed in 2.0; Use 'contexts' with '{}_alias' instead. (`{}` -> `{}`)",
&name,
&name,
¤t_value,
&alias
);
Some(alias)
}
None => Some(current_value),
}
}
}
#[cfg(test)]
mod tests {
use crate::modules::kubernetes::Document;
use crate::modules::kubernetes::parse_kubeconfigs;
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
use std::env;
use std::fs::{File, create_dir};
use std::io::{self, Write};
#[test]
fn test_none_when_disabled() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let filename = dir.path().join("config");
let mut file = File::create(&filename)?;
file.write_all(
b"
apiVersion: v1
clusters: []
contexts:
- context:
cluster: test_cluster
user: test_user
name: test_context
current-context: test_context
kind: Config
preferences: {}
users: []
",
)?;
file.sync_all()?;
let actual = ModuleRenderer::new("kubernetes")
.path(dir.path())
.env("KUBECONFIG", filename.to_string_lossy().as_ref())
.collect();
assert_eq!(None, actual);
dir.close()
}
#[test]
fn test_none_when_no_detected_files_folders_or_env_vars() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let filename = dir.path().join("config");
let mut file = File::create(&filename)?;
file.write_all(
b"
apiVersion: v1
clusters: []
contexts:
- context:
cluster: test_cluster
user: test_user
name: test_context
current-context: test_context
kind: Config
preferences: {}
users: []
",
)?;
file.sync_all()?;
let actual = ModuleRenderer::new("kubernetes")
.path(dir.path())
.env("KUBECONFIG", filename.to_string_lossy().as_ref())
.config(toml::toml! {
[kubernetes]
disabled = false
detect_files = ["k8s.ext"]
detect_extensions = ["k8s"]
detect_folders = ["k8s_folder"]
detect_env_vars = ["k8s_env_var"]
})
.collect();
assert_eq!(None, actual);
dir.close()
}
#[test]
fn test_with_detected_files_folder_and_env_vars() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let filename = dir.path().join("config");
let mut file = File::create(&filename)?;
file.write_all(
b"
apiVersion: v1
clusters: []
contexts:
- context:
cluster: test_cluster
user: test_user
name: test_context
current-context: test_context
kind: Config
preferences: {}
users: []
",
)?;
file.sync_all()?;
let dir_with_file = tempfile::tempdir()?;
File::create(dir_with_file.path().join("k8s.ext"))?.sync_all()?;
let actual_file = ModuleRenderer::new("kubernetes")
.path(dir_with_file.path())
.env("KUBECONFIG", filename.to_string_lossy().as_ref())
.config(toml::toml! {
[kubernetes]
disabled = false
detect_files = ["k8s.ext"]
detect_extensions = ["k8s"]
detect_folders = ["k8s_folder"]
})
.collect();
let dir_with_ext = tempfile::tempdir()?;
File::create(dir_with_ext.path().join("test.k8s"))?.sync_all()?;
let actual_ext = ModuleRenderer::new("kubernetes")
.path(dir_with_ext.path())
.env("KUBECONFIG", filename.to_string_lossy().as_ref())
.config(toml::toml! {
[kubernetes]
disabled = false
detect_files = ["k8s.ext"]
detect_extensions = ["k8s"]
detect_folders = ["k8s_folder"]
})
.collect();
let dir_with_dir = tempfile::tempdir()?;
create_dir(dir_with_dir.path().join("k8s_folder"))?;
let actual_dir = ModuleRenderer::new("kubernetes")
.path(dir_with_dir.path())
.env("KUBECONFIG", filename.to_string_lossy().as_ref())
.config(toml::toml! {
[kubernetes]
disabled = false
detect_files = ["k8s.ext"]
detect_extensions = ["k8s"]
detect_folders = ["k8s_folder"]
})
.collect();
let empty_dir = tempfile::tempdir()?;
let actual_env_var = ModuleRenderer::new("kubernetes")
.path(empty_dir.path())
.env("KUBECONFIG", filename.to_string_lossy().as_ref())
.env("TEST_K8S_ENV", "foo")
.config(toml::toml! {
[kubernetes]
disabled = false
detect_env_vars = ["TEST_K8S_ENV"]
})
.collect();
let actual_none = ModuleRenderer::new("kubernetes")
.path(empty_dir.path())
.env("KUBECONFIG", filename.to_string_lossy().as_ref())
.config(toml::toml! {
[kubernetes]
disabled = false
detect_files = ["k8s.ext"]
})
.collect();
let expected = Some(format!(
"{} in ",
Color::Cyan.bold().paint("☸ test_context")
));
assert_eq!(expected, actual_file);
assert_eq!(expected, actual_ext);
assert_eq!(expected, actual_dir);
assert_eq!(expected, actual_env_var);
assert_eq!(None, actual_none);
dir.close()
}
fn base_test_ctx_alias(ctx_name: &str, config: toml::Table, expected: &str) -> io::Result<()> {
let dir = tempfile::tempdir()?;
let filename = dir.path().join("config");
let mut file = File::create(&filename)?;
file.write_all(
format!(
"
apiVersion: v1
clusters: []
contexts: []
current-context: {ctx_name}
kind: Config
preferences: {{}}
users: []
"
)
.as_bytes(),
)?;
file.sync_all()?;
let actual = ModuleRenderer::new("kubernetes")
.path(dir.path())
.env("KUBECONFIG", filename.to_string_lossy().as_ref())
.config(config)
.collect();
let expected = Some(format!("{} in ", Color::Cyan.bold().paint(expected)));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn test_ctx_alias_simple() -> io::Result<()> {
base_test_ctx_alias(
"test_context",
toml::toml! {
[kubernetes]
disabled = false
[kubernetes.context_aliases]
"test_context" = "test_alias"
".*" = "literal match has precedence"
},
"☸ test_alias",
)
}
#[test]
fn test_ctx_alias_regex() -> io::Result<()> {
base_test_ctx_alias(
"namespace/openshift-cluster/user",
toml::toml! {
[kubernetes]
disabled = false
[kubernetes.context_aliases]
".*/openshift-cluster/.*" = "test_alias"
},
"☸ test_alias",
)
}
#[test]
fn test_ctx_alias_regex_replace() -> io::Result<()> {
base_test_ctx_alias(
"gke_infra-cluster-28cccff6_europe-west4_cluster-1",
toml::toml! {
[kubernetes]
disabled = false
[kubernetes.context_aliases]
"gke_.*_(?P<cluster>[\\w-]+)" = "example: $cluster"
},
"☸ example: cluster-1",
)
}
#[test]
fn test_config_context_ctx_alias_regex_replace() -> io::Result<()> {
base_test_ctx_alias(
"gke_infra-cluster-28cccff6_europe-west4_cluster-1",
toml::toml! {
[kubernetes]
disabled = false
[[kubernetes.contexts]]
context_pattern = "gke_.*_(?P<cluster>[\\w-]+)"
context_alias = "example: $cluster"
},
"☸ example: cluster-1",
)
}
#[test]
fn test_ctx_alias_broken_regex() -> io::Result<()> {
base_test_ctx_alias(
"input",
toml::toml! {
[kubernetes]
disabled = false
[kubernetes.context_aliases]
"input[.*" = "this does not match"
},
"☸ input",
)
}
#[test]
fn test_single_config_file_no_ns() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let filename = dir.path().join("config");
let mut file = File::create(&filename)?;
file.write_all(
b"
apiVersion: v1
clusters: []
contexts:
- context:
cluster: test_cluster
user: test_user
name: test_context
current-context: test_context
kind: Config
preferences: {}
users: []
",
)?;
file.sync_all()?;
let actual = ModuleRenderer::new("kubernetes")
.path(dir.path())
.env("KUBECONFIG", filename.to_string_lossy().as_ref())
.config(toml::toml! {
[kubernetes]
disabled = false
})
.collect();
let expected = Some(format!(
"{} in ",
Color::Cyan.bold().paint("☸ test_context")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn test_single_config_file_with_ns() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let filename = dir.path().join("config");
let mut file = File::create(&filename)?;
file.write_all(
b"
apiVersion: v1
clusters: []
contexts:
- context:
cluster: test_cluster
user: test_user
namespace: test_namespace
name: test_context
current-context: test_context
kind: Config
preferences: {}
users: []
",
)?;
file.sync_all()?;
let actual = ModuleRenderer::new("kubernetes")
.path(dir.path())
.env("KUBECONFIG", filename.to_string_lossy().as_ref())
.config(toml::toml! {
[kubernetes]
disabled = false
})
.collect();
let expected = Some(format!(
"{} in ",
Color::Cyan.bold().paint("☸ test_context (test_namespace)")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn test_single_config_file_with_multiple_ctxs() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let filename = dir.path().join("config");
let mut file = File::create(&filename)?;
file.write_all(
b"
apiVersion: v1
clusters: []
contexts:
- context:
cluster: another_cluster
user: another_user
namespace: another_namespace
name: another_context
- context:
cluster: test_cluster
user: test_user
namespace: test_namespace
name: test_context
current-context: test_context
kind: Config
preferences: {}
users: []
",
)?;
file.sync_all()?;
let actual = ModuleRenderer::new("kubernetes")
.path(dir.path())
.env("KUBECONFIG", filename.to_string_lossy().as_ref())
.config(toml::toml! {
[kubernetes]
disabled = false
})
.collect();
let expected = Some(format!(
"{} in ",
Color::Cyan.bold().paint("☸ test_context (test_namespace)")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn test_multiple_config_files_with_context_defined_once() -> io::Result<()> {
// test that we get the current context from the first config file in the KUBECONFIG,
// no matter if it is only defined in the latter
let dir = tempfile::tempdir()?;
let filename_cc = dir.path().join("config_cc");
let mut file_cc = File::create(&filename_cc)?;
file_cc.write_all(
b"
apiVersion: v1
clusters: []
contexts: []
current-context: test_context
kind: Config
preferences: {}
users: []
",
)?;
file_cc.sync_all()?;
let filename_ctx = dir.path().join("config_ctx");
let mut file_ctx = File::create(&filename_ctx)?;
file_ctx.write_all(
b"
apiVersion: v1
clusters: []
contexts:
- context:
cluster: test_cluster
user: test_user
namespace: test_namespace
name: test_context
kind: Config
preferences: {}
users: []
",
)?;
file_ctx.sync_all()?;
// Test current_context first
let actual_cc_first = ModuleRenderer::new("kubernetes")
.path(dir.path())
.env(
"KUBECONFIG",
env::join_paths([&filename_cc, &filename_ctx])
.unwrap()
.to_string_lossy(),
)
.config(toml::toml! {
[kubernetes]
disabled = false
})
.collect();
// And test with context and namespace first
let actual_ctx_first = ModuleRenderer::new("kubernetes")
.path(dir.path())
.env(
"KUBECONFIG",
env::join_paths([&filename_ctx, &filename_cc])
.unwrap()
.to_string_lossy(),
)
.config(toml::toml! {
[kubernetes]
disabled = false
})
.collect();
let expected = Some(format!(
"{} in ",
Color::Cyan.bold().paint("☸ test_context (test_namespace)")
));
assert_eq!(expected, actual_cc_first);
assert_eq!(expected, actual_ctx_first);
dir.close()
}
#[test]
fn test_multiple_config_files_with_context_defined_twice() -> io::Result<()> {
// tests that, if two files contain the same context,
// only the context config from the first is used.
let dir = tempfile::tempdir()?;
let config1 = dir.path().join("config1");
let mut file1 = File::create(&config1)?;
file1.write_all(
b"
apiVersion: v1
clusters: []
contexts:
- context:
cluster: test_cluster1
namespace: test_namespace1
name: test_context
current-context: test_context
kind: Config
preferences: {}
users: []
",
)?;
file1.sync_all()?;
let config2 = dir.path().join("config2");
let mut file2 = File::create(&config2)?;
file2.write_all(
b"
apiVersion: v1
clusters: []
contexts:
- context:
cluster: test_cluster2
user: test_user2
name: test_context
current-context: test_context
kind: Config
preferences: {}
users: []
",
)?;
file2.sync_all()?;
let paths1 = [config1.clone(), config2.clone()];
let kubeconfig_content1 = env::join_paths(paths1.iter()).unwrap();
let actual1 = ModuleRenderer::new("kubernetes")
.path(dir.path())
.env("KUBECONFIG", kubeconfig_content1.to_string_lossy())
.config(toml::toml! {
[kubernetes]
format = "($user )($cluster )($namespace )"
disabled = false
})
.collect();
let expected1 = Some("test_cluster1 test_namespace1 ".to_string());
assert_eq!(expected1, actual1);
let paths2 = [config2, config1];
let kubeconfig_content2 = env::join_paths(paths2.iter()).unwrap();
let actual2 = ModuleRenderer::new("kubernetes")
.path(dir.path())
.env("KUBECONFIG", kubeconfig_content2.to_string_lossy())
.config(toml::toml! {
[kubernetes]
format = "($user )($cluster )($namespace )"
disabled = false
})
.collect();
let expected2 = Some("test_user2 test_cluster2 ".to_string());
assert_eq!(expected2, actual2);
dir.close()
}
fn base_test_user_alias(
user_name: &str,
config: toml::Table,
expected: &str,
) -> io::Result<()> {
let dir = tempfile::tempdir()?;
let filename = dir.path().join("config");
let mut file = File::create(&filename)?;
file.write_all(
format!(
"
apiVersion: v1
clusters: []
contexts:
- context:
cluster: test_cluster
user: {user_name}
namespace: test_namespace
name: test_context
current-context: test_context
kind: Config
preferences: {{}}
users: []
"
)
.as_bytes(),
)?;
file.sync_all()?;
let actual = ModuleRenderer::new("kubernetes")
.path(dir.path())
.env("KUBECONFIG", filename.to_string_lossy().as_ref())
.config(config)
.collect();
let expected = Some(format!("{} in ", Color::Cyan.bold().paint(expected)));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn test_user_alias_simple() -> io::Result<()> {
base_test_user_alias(
"test_user",
toml::toml! {
[kubernetes]
disabled = false
format = "[$symbol$context( \\($user\\))]($style) in "
[kubernetes.user_aliases]
"test_user" = "test_alias"
".*" = "literal match has precedence"
},
"☸ test_context (test_alias)",
)
}
#[test]
fn test_user_alias_regex() -> io::Result<()> {
base_test_user_alias(
"openshift-cluster/user",
toml::toml! {
[kubernetes]
disabled = false
format = "[$symbol$context( \\($user\\))]($style) in "
[kubernetes.user_aliases]
"openshift-cluster/.*" = "test_alias"
},
"☸ test_context (test_alias)",
)
}
#[test]
fn test_user_alias_regex_replace() -> io::Result<()> {
base_test_user_alias(
"gke_infra-user-28cccff6_europe-west4_cluster-1",
toml::toml! {
[kubernetes]
disabled = false
format = "[$symbol$context( \\($user\\))]($style) in "
[kubernetes.user_aliases]
"gke_.*_(?P<cluster>[\\w-]+)" = "example: $cluster"
},
"☸ test_context (example: cluster-1)",
)
}
#[test]
fn test_config_context_user_alias_regex_replace() -> io::Result<()> {
base_test_user_alias(
"gke_infra-user-28cccff6_europe-west4_cluster-1",
toml::toml! {
[kubernetes]
disabled = false
format = "[$symbol$context( \\($user\\))]($style) in "
[[kubernetes.contexts]]
context_pattern = ".*"
user_pattern = "gke_.*_(?P<cluster>[\\w-]+)"
user_alias = "example: $cluster"
},
"☸ test_context (example: cluster-1)",
)
}
#[test]
fn test_user_alias_broken_regex() -> io::Result<()> {
base_test_user_alias(
"input",
toml::toml! {
[kubernetes]
disabled = false
format = "[$symbol$context( \\($user\\))]($style) in "
[kubernetes.user_aliases]
"input[.*" = "this does not match"
},
"☸ test_context (input)",
)
}
#[test]
fn test_user_should_use_default_if_no_matching_alias() -> io::Result<()> {
base_test_user_alias(
"gke_infra-user-28cccff6_europe-west4_cluster-1",
toml::toml! {
[kubernetes]
disabled = false
format = "[$symbol$context( \\($user\\))]($style) in "
[kubernetes.user_aliases]
"([A-Z])\\w+" = "this does not match"
"gke_infra-user-28cccff6" = "this does not match"
},
"☸ test_context (gke_infra-user-28cccff6_europe-west4_cluster-1)",
)
}
#[test]
fn test_kube_user() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let filename = dir.path().join("config");
let mut file = File::create(&filename)?;
file.write_all(
b"
apiVersion: v1
clusters: []
contexts:
- context:
cluster: test_cluster
user: test_user
namespace: test_namespace
name: test_context
current-context: test_context
kind: Config
preferences: {}
users: []
",
)?;
file.sync_all()?;
let actual = ModuleRenderer::new("kubernetes")
.path(dir.path())
.env("KUBECONFIG", filename.to_string_lossy().as_ref())
.config(toml::toml! {
[kubernetes]
format = "($user)"
disabled = false
})
.collect();
let expected = Some("test_user".to_string());
assert_eq!(expected, actual);
dir.close()
}
#[test]
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | true |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/cpp.rs | src/modules/cpp.rs | use super::{Context, Module};
use crate::modules::cc::{Lang, module as cc_module};
/// Creates a module with the current C compiler and version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
cc_module(context, Lang::Cpp)
}
#[cfg(test)]
mod tests {
use crate::{test::ModuleRenderer, utils::CommandOutput};
use nu_ansi_term::Color;
use std::fs::File;
use std::io;
#[test]
fn folder_without_cpp_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("cpp")
.config(toml::toml! {
[cpp]
disabled = false
})
.path(dir.path())
.collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_cpp_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("any.cpp"))?.sync_all()?;
// What happens when `c++ --version` says it's modern clang++?
// The case when it claims to be g++ is covered in folder_with_hpp_file,
let actual = ModuleRenderer::new("cpp")
.config(toml::toml! {
[cpp]
disabled = false
})
.cmd(
"c++ --version",
Some(CommandOutput {
stdout: String::from(
"\
clang version 19.1.7
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin",
),
stderr: String::default(),
}),
)
.path(dir.path())
.collect();
let expected = Some(format!(
"via {}",
Color::Fixed(149).bold().paint("C++ v19.1.7-clang++ ")
));
assert_eq!(expected, actual);
// What happens when `c++ --version` says it's ancient gcc?
let actual = ModuleRenderer::new("cpp")
.config(toml::toml! {
[cpp]
disabled = false
})
.cmd(
"c++ --version",
Some(CommandOutput {
stdout: String::from(
"\
c++ (GCC) 3.3.5
Copyright (C) 2003 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.",
),
stderr: String::default(),
}),
)
.path(dir.path())
.collect();
let expected = Some(format!(
"via {}",
Color::Fixed(149).bold().paint("C++ v3.3.5-g++ ")
));
assert_eq!(expected, actual);
// What happens with an unknown C++ compiler?
let actual = ModuleRenderer::new("cpp")
.config(toml::toml! {
[cpp]
disabled = false
})
.cmd(
"c++ --version",
Some(CommandOutput {
stdout: String::from("HISOFT-C++ Compiler V1.2\nCopyright © 1984 HISOFT"),
stderr: String::default(),
}),
)
.path(dir.path())
.collect();
let expected = Some(format!("via {}", Color::Fixed(149).bold().paint("C++ ")));
assert_eq!(expected, actual);
// What happens when 'c++ --version' doesn't work, but 'g++ --version' does?
// This stubs out `c++` but we'll fall back to `g++ --version`
let actual = ModuleRenderer::new("cpp")
.config(toml::toml! {
[cpp]
disabled = false
})
.cmd("c++ --version", None)
.path(dir.path())
.collect();
let expected = Some(format!(
"via {}",
Color::Fixed(149).bold().paint("C++ v14.2.1-g++ ")
));
assert_eq!(expected, actual);
// Now with both 'c++' and 'g++' not working, this should fall back to 'clang++ --version'
let actual = ModuleRenderer::new("cpp")
.config(toml::toml! {
[cpp]
disabled = false
})
.cmd("c++ --version", None)
.cmd("g++ --version", None)
.path(dir.path())
.collect();
let expected = Some(format!(
"via {}",
Color::Fixed(149).bold().paint("C++ v19.1.7-clang++ ")
));
assert_eq!(expected, actual);
// What happens when we can't find any of c++, g++ or clang++?
let actual = ModuleRenderer::new("cpp")
.config(toml::toml! {
[cpp]
disabled = false
})
.cmd("c++ --version", None)
.cmd("g++ --version", None)
.cmd("clang++ --version", None)
.path(dir.path())
.collect();
let expected = Some(format!("via {}", Color::Fixed(149).bold().paint("C++ ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_hpp_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("any.hpp"))?.sync_all()?;
let actual = ModuleRenderer::new("cpp")
.config(toml::toml! {
[cpp]
disabled = false
})
.path(dir.path())
.collect();
let expected = Some(format!(
"via {}",
Color::Fixed(149).bold().paint("C++ v14.2.1-g++ ")
));
assert_eq!(expected, actual);
dir.close()
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/git_state.rs | src/modules/git_state.rs | use gix::state::InProgress;
use std::path::PathBuf;
use super::{Context, Module, ModuleConfig};
use crate::configs::git_state::GitStateConfig;
use crate::context::Repo;
use crate::formatter::StringFormatter;
/// Creates a module with the state of the git repository at the current directory
///
/// During a git operation it will show: REBASING, BISECTING, MERGING, etc.
/// If the progress information is available (e.g. rebasing 3/10), it will show that too.
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("git_state");
let config: GitStateConfig = GitStateConfig::try_load(module.config);
let repo = context.get_repo().ok()?;
let state_description = get_state_description(repo, &config)?;
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|variable, _| match variable {
"state" => Some(state_description.label),
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map(|variable| match variable {
"progress_current" => state_description.current.as_ref().map(Ok),
"progress_total" => state_description.total.as_ref().map(Ok),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `git_state`:\n{error}");
return None;
}
});
Some(module)
}
/// Returns the state of the current repository
///
/// During a git operation it will show: REBASING, BISECTING, MERGING, etc.
fn get_state_description<'a>(
repo: &'a Repo,
config: &GitStateConfig<'a>,
) -> Option<StateDescription<'a>> {
match repo.state.as_ref()? {
InProgress::Merge => Some(StateDescription {
label: config.merge,
current: None,
total: None,
}),
InProgress::Revert | InProgress::RevertSequence => Some(StateDescription {
label: config.revert,
current: None,
total: None,
}),
InProgress::CherryPick | InProgress::CherryPickSequence => Some(StateDescription {
label: config.cherry_pick,
current: None,
total: None,
}),
InProgress::Bisect => Some(StateDescription {
label: config.bisect,
current: None,
total: None,
}),
InProgress::ApplyMailbox => Some(StateDescription {
label: config.am,
current: None,
total: None,
}),
InProgress::ApplyMailboxRebase => Some(StateDescription {
label: config.am_or_rebase,
current: None,
total: None,
}),
InProgress::Rebase | InProgress::RebaseInteractive => {
Some(describe_rebase(repo, config.rebase))
}
}
}
// TODO: Use future gitoxide API to get the state of the rebase
fn describe_rebase<'a>(repo: &'a Repo, rebase_config: &'a str) -> StateDescription<'a> {
/*
* Sadly, libgit2 seems to have some issues with reading the state of
* interactive rebases. So, instead, we'll poke a few of the .git files
* ourselves. This might be worth re-visiting this in the future...
*
* The following is based heavily on: https://github.com/magicmonty/bash-git-prompt
*/
let has_path = |relative_path: &str| {
let path = repo.path.join(PathBuf::from(relative_path));
path.exists()
};
let file_to_usize = |relative_path: &str| {
let path = repo.path.join(PathBuf::from(relative_path));
let contents = crate::utils::read_file(path).ok()?;
let quantity = contents.trim().parse::<usize>().ok()?;
Some(quantity)
};
let paths_to_progress = |current_path: &str, total_path: &str| {
let current = file_to_usize(current_path)?;
let total = file_to_usize(total_path)?;
Some((current, total))
};
let progress = if has_path("rebase-merge/msgnum") {
paths_to_progress("rebase-merge/msgnum", "rebase-merge/end")
} else if has_path("rebase-apply") {
paths_to_progress("rebase-apply/next", "rebase-apply/last")
} else {
None
};
let (current, total) = if let Some((c, t)) = progress {
(Some(format!("{c}")), Some(format!("{t}")))
} else {
(None, None)
};
StateDescription {
label: rebase_config,
current,
total,
}
}
struct StateDescription<'a> {
label: &'a str,
current: Option<String>,
total: Option<String>,
}
#[cfg(test)]
mod tests {
use nu_ansi_term::Color;
use std::ffi::OsStr;
use std::io::{self, Error, ErrorKind};
use std::path::Path;
use std::process::Stdio;
use crate::test::ModuleRenderer;
use crate::utils::{create_command, write_file};
#[test]
fn show_nothing_on_empty_dir() -> io::Result<()> {
let repo_dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("git_state")
.path(repo_dir.path())
.collect();
let expected = None;
assert_eq!(expected, actual);
repo_dir.close()
}
#[test]
fn shows_rebasing() -> io::Result<()> {
let repo_dir = create_repo_with_conflict()?;
let path = repo_dir.path();
run_git_cmd(["rebase", "other-branch"], Some(path), false)?;
let actual = ModuleRenderer::new("git_state").path(path).collect();
let expected = Some(format!("({}) ", Color::Yellow.bold().paint("REBASING 1/1")));
assert_eq!(expected, actual);
repo_dir.close()
}
#[test]
fn shows_merging() -> io::Result<()> {
let repo_dir = create_repo_with_conflict()?;
let path = repo_dir.path();
run_git_cmd(["merge", "other-branch"], Some(path), false)?;
let actual = ModuleRenderer::new("git_state").path(path).collect();
let expected = Some(format!("({}) ", Color::Yellow.bold().paint("MERGING")));
assert_eq!(expected, actual);
repo_dir.close()
}
#[test]
fn shows_cherry_picking() -> io::Result<()> {
let repo_dir = create_repo_with_conflict()?;
let path = repo_dir.path();
run_git_cmd(["cherry-pick", "other-branch"], Some(path), false)?;
let actual = ModuleRenderer::new("git_state").path(path).collect();
let expected = Some(format!(
"({}) ",
Color::Yellow.bold().paint("CHERRY-PICKING")
));
assert_eq!(expected, actual);
repo_dir.close()
}
#[test]
fn shows_bisecting() -> io::Result<()> {
let repo_dir = create_repo_with_conflict()?;
let path = repo_dir.path();
run_git_cmd(["bisect", "start"], Some(path), false)?;
let actual = ModuleRenderer::new("git_state").path(path).collect();
let expected = Some(format!("({}) ", Color::Yellow.bold().paint("BISECTING")));
assert_eq!(expected, actual);
repo_dir.close()
}
#[test]
fn shows_reverting() -> io::Result<()> {
let repo_dir = create_repo_with_conflict()?;
let path = repo_dir.path();
run_git_cmd(["revert", "--no-commit", "HEAD~1"], Some(path), false)?;
let actual = ModuleRenderer::new("git_state").path(path).collect();
let expected = Some(format!("({}) ", Color::Yellow.bold().paint("REVERTING")));
assert_eq!(expected, actual);
repo_dir.close()
}
fn run_git_cmd<A, S>(args: A, dir: Option<&Path>, should_succeed: bool) -> io::Result<()>
where
A: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
let mut command = create_command("git")?;
command
.args(args)
.stdout(Stdio::null())
.stderr(Stdio::null())
.stdin(Stdio::null());
if let Some(dir) = dir {
command.current_dir(dir);
}
let status = command.status()?;
if should_succeed && !status.success() {
Err(Error::from(ErrorKind::Other))
} else {
Ok(())
}
}
fn create_repo_with_conflict() -> io::Result<tempfile::TempDir> {
let repo_dir = tempfile::tempdir()?;
let path = repo_dir.path();
let conflicted_file = repo_dir.path().join("the_file");
// Initialize a new git repo
run_git_cmd(
[
"init",
"--quiet",
path.to_str().expect("Path was not UTF-8"),
],
None,
true,
)?;
// Set local author info
run_git_cmd(
["config", "--local", "user.email", "starship@example.com"],
Some(path),
true,
)?;
run_git_cmd(
["config", "--local", "user.name", "starship"],
Some(path),
true,
)?;
// Ensure on the expected branch.
// If build environment has `init.defaultBranch` global set
// it will default to an unknown branch, so need to make & change branch
run_git_cmd(
["checkout", "-b", "master"],
Some(path),
// command expected to fail if already on the expected branch
false,
)?;
// Write a file on master and commit it
write_file(&conflicted_file, "Version A")?;
run_git_cmd(["add", "the_file"], Some(path), true)?;
run_git_cmd(
["commit", "--message", "Commit A", "--no-gpg-sign"],
Some(path),
true,
)?;
// Switch to another branch, and commit a change to the file
run_git_cmd(["checkout", "-b", "other-branch"], Some(path), true)?;
write_file(&conflicted_file, "Version B")?;
run_git_cmd(
["commit", "--all", "--message", "Commit B", "--no-gpg-sign"],
Some(path),
true,
)?;
// Switch back to master, and commit a third change to the file
run_git_cmd(["checkout", "master"], Some(path), true)?;
write_file(conflicted_file, "Version C")?;
run_git_cmd(
["commit", "--all", "--message", "Commit C", "--no-gpg-sign"],
Some(path),
true,
)?;
Ok(repo_dir)
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/package.rs | src/modules/package.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::package::PackageConfig;
use crate::formatter::{StringFormatter, VersionFormatter};
use crate::utils::read_file;
use ini::Ini;
use jsonc_parser::ParseOptions;
use quick_xml::Reader as QXReader;
use quick_xml::events::Event as QXEvent;
use regex::Regex;
use serde_json as json;
use std::fs;
use std::io::Read;
use versions::Version;
/// Creates a module with the current package version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("package");
let config: PackageConfig = PackageConfig::try_load(module.config);
let module_version = get_version(context, &config)?;
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,
})
.map(|variable| match variable {
"version" => Some(Ok(&module_version)),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `package`:\n{error}");
return None;
}
});
Some(module)
}
fn get_node_package_version(context: &Context, config: &PackageConfig) -> Option<String> {
let file_contents = context.read_file_from_pwd("package.json")?;
let package_json: json::Value = json::from_str(&file_contents).ok()?;
if !config.display_private
&& package_json.get("private").and_then(json::Value::as_bool) == Some(true)
{
return None;
}
let raw_version = package_json.get("version")?.as_str()?;
if raw_version == "null" {
return None;
}
let formatted_version = format_version(raw_version, config.version_format)?;
if formatted_version == "v0.0.0-development" || formatted_version.starts_with("v0.0.0-semantic")
{
return Some("semantic".to_string());
}
Some(formatted_version)
}
fn get_jsr_package_version(context: &Context, config: &PackageConfig) -> Option<String> {
let (filename, contents) = ["deno.json", "deno.jsonc", "jsr.json", "jsr.jsonc"]
.iter()
.find_map(|filename| {
context
.read_file_from_pwd(filename)
.map(|contents| (filename, contents))
})?;
let json_content: json::Value = if filename.ends_with(".jsonc") {
jsonc_parser::parse_to_serde_value(&contents, &ParseOptions::default()).ok()??
} else {
json::from_str(&contents).ok()?
};
let raw_version = json_content.get("version")?.as_str()?;
format_version(raw_version, config.version_format)
}
fn get_poetry_version(pyproject: &toml::Table) -> Option<String> {
pyproject
.get("tool")?
.get("poetry")?
.get("version")?
.as_str()
.map(|s| s.to_owned())
}
fn parse_file_version_for_hatchling(context: &Context, path: &str) -> Option<String> {
let file_contents = read_file(context.current_dir.join(path)).ok()?;
// https://hatch.pypa.io/latest/version/
let re = Regex::new(r#"(__version__|VERSION)\s*=\s*["']([^"']+)["']"#).ok()?;
Some(
re.captures(&file_contents)
.and_then(|cap| cap.get(2))?
.as_str()
.to_owned(),
)
}
fn parse_hatchling_dynamic_version(context: &Context, pyproject: &toml::Table) -> Option<String> {
let version_path = pyproject
.get("tool")?
.get("hatch")?
.get("version")?
.get("path")?
.as_str()?;
parse_file_version_for_hatchling(context, version_path)
.filter(|s| Version::new(s.as_str()).is_some())
}
fn parse_pep621_dynamic_version(context: &Context, pyproject: &toml::Table) -> Option<String> {
// TODO: Flit, PDM, Setuptools
// https://packaging.python.org/en/latest/discussions/single-source-version#build-system-version-handling
parse_hatchling_dynamic_version(context, pyproject)
}
fn get_pep621_dynamic_version(context: &Context, pyproject: &toml::Table) -> Option<String> {
pyproject
.get("project")?
.get("dynamic")?
.as_array()?
.iter()
.any(|v| v.as_str() == Some("version"))
.then(|| parse_pep621_dynamic_version(context, pyproject))?
}
fn get_pep621_static_version(pyproject: &toml::Table) -> Option<String> {
pyproject
.get("project")?
.get("version")?
.as_str()
.map(|s| s.to_owned())
}
fn get_pep621_version(context: &Context, pyproject: &toml::Table) -> Option<String> {
get_pep621_static_version(pyproject).or_else(|| get_pep621_dynamic_version(context, pyproject))
}
fn get_pyproject_version(context: &Context, config: &PackageConfig) -> Option<String> {
let file_contents = context.read_file_from_pwd("pyproject.toml")?;
let pyproject_toml: toml::Table = toml::from_str(&file_contents).ok()?;
get_pep621_version(context, &pyproject_toml)
.or_else(|| get_poetry_version(&pyproject_toml))
.and_then(|raw_version| format_string_version(raw_version, config.version_format))
}
fn get_setup_cfg_version(context: &Context, config: &PackageConfig) -> Option<String> {
let file_contents = context.read_file_from_pwd("setup.cfg")?;
let ini = Ini::load_from_str(&file_contents).ok()?;
let raw_version = ini.get_from(Some("metadata"), "version")?;
if raw_version.starts_with("attr:") || raw_version.starts_with("file:") {
None
} else {
format_version(raw_version, config.version_format)
}
}
fn get_gradle_version(context: &Context, config: &PackageConfig) -> Option<String> {
context
.read_file_from_pwd("gradle.properties")
.and_then(|contents| {
let re = Regex::new(r"(?m)^\s*version\s*=\s*(?P<version>.*)").unwrap();
let caps = re.captures(&contents)?;
format_version(&caps["version"], config.version_format)
}).or_else(|| {
let build_file_contents = context.read_file_from_pwd("build.gradle")?;
let re = Regex::new(r#"(?m)^version( |\s*=\s*)['"](?P<version>[^'"]+)['"]$"#).unwrap(); /*dark magic*/
let caps = re.captures(&build_file_contents)?;
format_version(&caps["version"], config.version_format)
})
}
fn get_composer_version(context: &Context, config: &PackageConfig) -> Option<String> {
let file_contents = context.read_file_from_pwd("composer.json")?;
let composer_json: json::Value = json::from_str(&file_contents).ok()?;
let raw_version = composer_json.get("version")?.as_str()?;
format_version(raw_version, config.version_format)
}
fn get_julia_project_version(context: &Context, config: &PackageConfig) -> Option<String> {
let file_contents = context.read_file_from_pwd("Project.toml")?;
let project_toml: toml::Table = toml::from_str(&file_contents).ok()?;
let raw_version = project_toml.get("version")?.as_str()?;
format_version(raw_version, config.version_format)
}
fn get_helm_package_version(context: &Context, config: &PackageConfig) -> Option<String> {
let file_contents = context.read_file_from_pwd("Chart.yaml")?;
let yaml = yaml_rust2::YamlLoader::load_from_str(&file_contents).ok()?;
let version = yaml.first()?["version"].as_str()?;
format_version(version, config.version_format)
}
fn get_mix_version(context: &Context, config: &PackageConfig) -> Option<String> {
let file_contents = context.read_file_from_pwd("mix.exs")?;
let re = Regex::new(r#"(?m)version: "(?P<version>[^"]+)""#).unwrap();
let caps = re.captures(&file_contents)?;
format_version(&caps["version"], config.version_format)
}
fn get_maven_version(context: &Context, config: &PackageConfig) -> Option<String> {
let file_contents = context.read_file_from_pwd("pom.xml")?;
let mut reader = QXReader::from_str(&file_contents);
reader.config_mut().trim_text(true);
let mut buf = vec![];
let mut in_ver = false;
let mut depth = 0;
loop {
match reader.read_event_into(&mut buf) {
Ok(QXEvent::Start(ref e)) => {
in_ver = depth == 1 && e.name().as_ref() == b"version";
depth += 1;
}
Ok(QXEvent::End(_)) => {
in_ver = false;
depth -= 1;
}
Ok(QXEvent::Text(t)) if in_ver => {
let ver = t.decode().ok().map(std::borrow::Cow::into_owned);
return match ver {
// Ignore version which is just a property reference
Some(ref v) if !v.starts_with('$') => format_version(v, config.version_format),
_ => None,
};
}
Ok(QXEvent::Eof) => break,
Ok(_) => (),
Err(err) => {
log::warn!("Error parsing pom.xml`:\n{err}");
break;
}
}
}
None
}
fn get_meson_version(context: &Context, config: &PackageConfig) -> Option<String> {
let file_contents = context
.read_file_from_pwd("meson.build")?
.split_ascii_whitespace()
.collect::<String>();
let re = Regex::new(r"project\([^())]*,version:'(?P<version>[^']+)'[^())]*\)").unwrap();
let caps = re.captures(&file_contents)?;
format_version(&caps["version"], config.version_format)
}
fn get_vmod_version(context: &Context, config: &PackageConfig) -> Option<String> {
let file_contents = context.read_file_from_pwd("v.mod")?;
let re = Regex::new(r"(?m)^\s*version\s*:\s*'(?P<version>[^']+)'").unwrap();
let caps = re.captures(&file_contents)?;
format_version(&caps["version"], config.version_format)
}
fn get_vpkg_version(context: &Context, config: &PackageConfig) -> Option<String> {
let file_contents = context.read_file_from_pwd("vpkg.json")?;
let vpkg_json: json::Value = json::from_str(&file_contents).ok()?;
let raw_version = vpkg_json.get("version")?.as_str()?;
format_version(raw_version, config.version_format)
}
fn get_sbt_version(context: &Context, config: &PackageConfig) -> Option<String> {
let file_contents = context.read_file_from_pwd("build.sbt")?;
let re = Regex::new(r"(?m)^(.*/)*\s*version\s*:=\s*.(?P<version>[\d\.]+)").unwrap();
let caps = re.captures(&file_contents)?;
format_version(&caps["version"], config.version_format)
}
fn get_cargo_version(context: &Context, config: &PackageConfig) -> Option<String> {
let mut file_contents = context.read_file_from_pwd("Cargo.toml")?;
let mut cargo_toml: toml::Table = toml::from_str(&file_contents).ok()?;
let cargo_version = cargo_toml.get("package").and_then(|p| p.get("version"));
let raw_version = if let Some(v) = cargo_version.and_then(toml::Value::as_str) {
// regular version string
v
} else if cargo_version
.and_then(|v| v.get("workspace"))
.and_then(toml::Value::as_bool)
.unwrap_or_default()
{
// workspace version string (`package.version.workspace = true`)
// need to read the Cargo.toml file from the workspace root
let mut version = None;
if let Some(workspace) = cargo_toml.get("workspace") {
// current Cargo.toml file is also the workspace root
version = workspace.get("package")?.get("version")?.as_str();
} else {
// discover the workspace root
for path in context.current_dir.ancestors().skip(1) {
// Assume the workspace root is the first ancestor that contains a Cargo.toml file
if let Ok(mut file) = fs::File::open(path.join("Cargo.toml")) {
file_contents.clear(); // clear the buffer for reading new Cargo.toml
file.read_to_string(&mut file_contents).ok()?;
cargo_toml = toml::from_str(&file_contents).ok()?;
// Read workspace.package.version
version = cargo_toml
.get("workspace")?
.get("package")?
.get("version")?
.as_str();
break;
}
}
}
version?
} else {
// This might be a workspace file
cargo_toml
.get("workspace")?
.get("package")?
.get("version")?
.as_str()?
};
format_version(raw_version, config.version_format)
}
fn get_nimble_version(context: &Context, config: &PackageConfig) -> Option<String> {
if !context
.try_begin_scan()?
.set_extensions(&["nimble"])
.is_match()
{
return None;
}
let cmd_output = context.exec_cmd("nimble", &["dump", "--json"])?;
let nimble_json: json::Value = json::from_str(&cmd_output.stdout).ok()?;
let raw_version = nimble_json.get("version")?.as_str()?;
format_version(raw_version, config.version_format)
}
fn get_shard_version(context: &Context, config: &PackageConfig) -> Option<String> {
let file_contents = context.read_file_from_pwd("shard.yml")?;
let data = yaml_rust2::YamlLoader::load_from_str(&file_contents).ok()?;
let raw_version = data.first()?["version"].as_str()?;
format_version(raw_version, config.version_format)
}
fn get_daml_project_version(context: &Context, config: &PackageConfig) -> Option<String> {
let file_contents = context.read_file_from_pwd("daml.yaml")?;
let daml_yaml = yaml_rust2::YamlLoader::load_from_str(&file_contents).ok()?;
let raw_version = daml_yaml.first()?["version"].as_str()?;
format_version(raw_version, config.version_format)
}
fn get_dart_pub_version(context: &Context, config: &PackageConfig) -> Option<String> {
let file_contents = context.read_file_from_pwd("pubspec.yaml")?;
let data = yaml_rust2::YamlLoader::load_from_str(&file_contents).ok()?;
let raw_version = data.first()?["version"].as_str()?;
format_version(raw_version, config.version_format)
}
fn get_rlang_version(context: &Context, config: &PackageConfig) -> Option<String> {
let file_contents = context.read_file_from_pwd("DESCRIPTION")?;
let re = Regex::new(r"(?m)^Version:\s*(?P<version>.*$)").unwrap();
let caps = re.captures(&file_contents)?;
format_version(&caps["version"], config.version_format)
}
fn get_galaxy_version(context: &Context, config: &PackageConfig) -> Option<String> {
let file_contents = context.read_file_from_pwd("galaxy.yml")?;
let data = yaml_rust2::YamlLoader::load_from_str(&file_contents).ok()?;
let raw_version = data.first()?["version"].as_str()?;
format_version(raw_version, config.version_format)
}
fn get_version(context: &Context, config: &PackageConfig) -> Option<String> {
let package_version_fn: Vec<fn(&Context, &PackageConfig) -> Option<String>> = vec![
get_cargo_version,
get_nimble_version,
get_node_package_version,
get_jsr_package_version,
get_pyproject_version,
get_setup_cfg_version,
get_composer_version,
get_gradle_version,
get_julia_project_version,
get_mix_version,
get_helm_package_version,
get_maven_version,
get_meson_version,
get_shard_version,
get_vmod_version,
get_vpkg_version,
get_sbt_version,
get_daml_project_version,
get_dart_pub_version,
get_rlang_version,
get_galaxy_version,
];
package_version_fn.iter().find_map(|f| f(context, config))
}
fn format_string_version(version: String, version_format: &str) -> Option<String> {
let cleaned = version
.replace('"', "")
.trim()
.trim_start_matches('v')
.to_string();
VersionFormatter::format_module_version("package", &cleaned, version_format)
}
fn format_version(version: &str, version_format: &str) -> Option<String> {
format_string_version(version.to_string(), version_format)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{test::ModuleRenderer, utils::CommandOutput};
use nu_ansi_term::Color;
use std::fs::File;
use std::io;
use std::io::Write;
use tempfile::TempDir;
#[test]
fn test_format_version() {
let raw_expected = Some(String::from("v1.2.3"));
assert_eq!(format_version("1.2.3", "v${raw}"), raw_expected);
assert_eq!(format_version(" 1.2.3 ", "v${raw}"), raw_expected);
assert_eq!(format_version("1.2.3 ", "v${raw}"), raw_expected);
assert_eq!(format_version(" 1.2.3", "v${raw}"), raw_expected);
assert_eq!(format_version("\"1.2.3\"", "v${raw}"), raw_expected);
assert_eq!(format_version("v1.2.3", "v${raw}"), raw_expected);
assert_eq!(format_version(" v1.2.3 ", "v${raw}"), raw_expected);
assert_eq!(format_version(" v1.2.3", "v${raw}"), raw_expected);
assert_eq!(format_version("v1.2.3 ", "v${raw}"), raw_expected);
assert_eq!(format_version("\"v1.2.3\"", "v${raw}"), raw_expected);
let major_expected = Some(String::from("v1"));
assert_eq!(format_version("1.2.3", "v${major}"), major_expected);
assert_eq!(format_version(" 1.2.3 ", "v${major}"), major_expected);
assert_eq!(format_version("1.2.3 ", "v${major}"), major_expected);
assert_eq!(format_version(" 1.2.3", "v${major}"), major_expected);
assert_eq!(format_version("\"1.2.3\"", "v${major}"), major_expected);
assert_eq!(format_version("v1.2.3", "v${major}"), major_expected);
assert_eq!(format_version(" v1.2.3 ", "v${major}"), major_expected);
assert_eq!(format_version(" v1.2.3", "v${major}"), major_expected);
assert_eq!(format_version("v1.2.3 ", "v${major}"), major_expected);
assert_eq!(format_version("\"v1.2.3\"", "v${major}"), major_expected);
}
#[test]
fn test_extract_cargo_version() -> io::Result<()> {
let config_name = "Cargo.toml";
let config_content = toml::toml! {
[package]
name = "starship"
version = "0.1.0"
}
.to_string();
let project_dir = create_project_dir()?;
fill_config(&project_dir, config_name, Some(&config_content))?;
expect_output(&project_dir, Some("v0.1.0"), None);
project_dir.close()
}
#[test]
fn test_extract_cargo_version_ws_single() -> io::Result<()> {
let config_name = "Cargo.toml";
let config_content = toml::toml! {
[workspace.package]
version = "0.1.0"
[package]
name = "starship"
version.workspace = true
}
.to_string();
let project_dir = create_project_dir()?;
fill_config(&project_dir, config_name, Some(&config_content))?;
expect_output(&project_dir, Some("v0.1.0"), None);
project_dir.close()
}
#[test]
fn test_extract_cargo_version_ws() -> io::Result<()> {
let ws_config_name = "Cargo.toml";
let ws_config_content = toml::toml! {
[workspace.package]
version = "0.1.0"
}
.to_string();
let config_name = "member/Cargo.toml";
let config_content = toml::toml! {
[package]
version.workspace = true
}
.to_string();
let project_dir = create_project_dir()?;
fs::create_dir(project_dir.path().join("member"))?;
fill_config(&project_dir, ws_config_name, Some(&ws_config_content))?;
fill_config(&project_dir, config_name, Some(&config_content))?;
// Version can be read both from the workspace and the member.
expect_output(&project_dir, Some("v0.1.0"), None);
let actual = ModuleRenderer::new("package")
.path(project_dir.path().join("member"))
.collect();
let expected = Some(format!(
"is {} ",
Color::Fixed(208).bold().paint("📦 v0.1.0")
));
assert_eq!(actual, expected);
project_dir.close()
}
#[test]
fn test_extract_cargo_version_ws_false() -> io::Result<()> {
let ws_config_name = "Cargo.toml";
let ws_config_content = toml::toml! {
[workspace.package]
version = "0.1.0"
}
.to_string();
let config_name = "member/Cargo.toml";
let config_content = toml::toml! {
[package]
version.workspace = false
}
.to_string();
let project_dir = create_project_dir()?;
fs::create_dir(project_dir.path().join("member"))?;
fill_config(&project_dir, ws_config_name, Some(&ws_config_content))?;
fill_config(&project_dir, config_name, Some(&config_content))?;
// Version can be read both from the workspace and the member.
let actual = ModuleRenderer::new("package")
.path(project_dir.path().join("member"))
.collect();
let expected = None;
assert_eq!(actual, expected);
project_dir.close()
}
#[test]
fn test_extract_cargo_version_ws_missing_parent() -> io::Result<()> {
let config_name = "Cargo.toml";
let config_content = toml::toml! {
[package]
name = "starship"
version.workspace = true
}
.to_string();
let project_dir = create_project_dir()?;
fill_config(&project_dir, config_name, Some(&config_content))?;
expect_output(&project_dir, None, None);
project_dir.close()
}
#[test]
fn test_extract_nimble_package_version() -> io::Result<()> {
let config_name = "test_project.nimble";
let config_content = r#"
version = "0.1.0"
author = "Mr. nimble"
description = "A new awesome nimble package"
license = "MIT"
"#;
let project_dir = create_project_dir()?;
fill_config(&project_dir, config_name, Some(config_content))?;
let starship_config = toml::toml! {
[package]
disabled = false
};
let actual = ModuleRenderer::new("package")
.cmd(
"nimble dump --json",
Some(CommandOutput {
stdout: r#"
{
"name": "test_project.nimble",
"version": "0.1.0",
"author": "Mr. nimble",
"desc": "A new awesome nimble package",
"license": "MIT",
"skipDirs": [],
"skipFiles": [],
"skipExt": [],
"installDirs": [],
"installFiles": [],
"installExt": [],
"requires": [],
"bin": [],
"binDir": "",
"srcDir": "",
"backend": "c"
}
"#
.to_owned(),
stderr: String::new(),
}),
)
.path(project_dir.path())
.config(starship_config)
.collect();
let expected = Some(format!(
"is {} ",
Color::Fixed(208).bold().paint(format!("📦 {}", "v0.1.0"))
));
assert_eq!(actual, expected);
project_dir.close()
}
#[test]
fn test_extract_nimble_package_version_for_nimble_directory_when_nimble_is_not_available()
-> io::Result<()> {
let config_name = "test_project.nimble";
let config_content = r#"
version = "0.1.0"
author = "Mr. nimble"
description = "A new awesome nimble package"
license = "MIT"
"#;
let project_dir = create_project_dir()?;
fill_config(&project_dir, config_name, Some(config_content))?;
let starship_config = toml::toml! {
[package]
disabled = false
};
let actual = ModuleRenderer::new("package")
.cmd("nimble dump --json", None)
.path(project_dir.path())
.config(starship_config)
.collect();
let expected = None;
assert_eq!(actual, expected);
project_dir.close()
}
#[test]
fn test_extract_nimble_package_version_for_non_nimble_directory() -> io::Result<()> {
// Only create an empty directory. There's no .nimble file for this case.
let project_dir = create_project_dir()?;
let starship_config = toml::toml! {
[package]
disabled = false
};
let actual = ModuleRenderer::new("package")
.cmd("nimble dump --json", None)
.path(project_dir.path())
.config(starship_config)
.collect();
let expected = None;
assert_eq!(actual, expected);
project_dir.close()
}
#[test]
fn test_extract_package_version() -> io::Result<()> {
let config_name = "package.json";
let config_content = json::json!({
"name": "starship",
"version": "0.1.0"
})
.to_string();
let project_dir = create_project_dir()?;
fill_config(&project_dir, config_name, Some(&config_content))?;
expect_output(&project_dir, Some("v0.1.0"), None);
project_dir.close()
}
#[test]
fn test_extract_package_version_without_version() -> io::Result<()> {
let config_name = "package.json";
let config_content = json::json!({
"name": "starship"
})
.to_string();
let project_dir = create_project_dir()?;
fill_config(&project_dir, config_name, Some(&config_content))?;
expect_output(&project_dir, None, None);
project_dir.close()
}
#[test]
fn test_extract_package_version_with_null_version() -> io::Result<()> {
let config_name = "package.json";
let config_content = json::json!({
"name": "starship",
"version": null
})
.to_string();
let project_dir = create_project_dir()?;
fill_config(&project_dir, config_name, Some(&config_content))?;
expect_output(&project_dir, None, None);
project_dir.close()
}
#[test]
fn test_extract_package_version_with_null_string_version() -> io::Result<()> {
let config_name = "package.json";
let config_content = json::json!({
"name": "starship",
"version": "null"
})
.to_string();
let project_dir = create_project_dir()?;
fill_config(&project_dir, config_name, Some(&config_content))?;
expect_output(&project_dir, None, None);
project_dir.close()
}
#[test]
fn test_extract_private_package_version_with_default_config() -> io::Result<()> {
let config_name = "package.json";
let config_content = json::json!({
"name": "starship",
"version": "0.1.0",
"private": true
})
.to_string();
let project_dir = create_project_dir()?;
fill_config(&project_dir, config_name, Some(&config_content))?;
expect_output(&project_dir, None, None);
project_dir.close()
}
#[test]
fn test_extract_private_package_version_with_display_private() -> io::Result<()> {
let config_name = "package.json";
let config_content = json::json!({
"name": "starship",
"version": "0.1.0",
"private": true
})
.to_string();
let starship_config = toml::toml! {
[package]
display_private = true
};
let project_dir = create_project_dir()?;
fill_config(&project_dir, config_name, Some(&config_content))?;
expect_output(&project_dir, Some("v0.1.0"), Some(starship_config));
project_dir.close()
}
#[test]
fn test_node_package_version_semantic_development_version() -> io::Result<()> {
let config_name = "package.json";
let config_content = json::json!({
"name": "starship",
"version": "0.0.0-development"
})
.to_string();
let project_dir = create_project_dir()?;
fill_config(&project_dir, config_name, Some(&config_content))?;
expect_output(&project_dir, Some("semantic"), None);
project_dir.close()
}
#[test]
fn test_node_package_version_with_semantic_other_version() -> io::Result<()> {
let config_name = "package.json";
let config_content = json::json!({
"name": "starship",
"version": "v0.0.0-semantically-released"
})
.to_string();
let project_dir = create_project_dir()?;
fill_config(&project_dir, config_name, Some(&config_content))?;
expect_output(&project_dir, Some("semantic"), None);
project_dir.close()
}
#[test]
fn test_jsr_package_version_with_jsr_json() -> io::Result<()> {
let config_name = "jsr.json";
let config_content = json::json!({
"name": "starship",
"version": "0.1.0"
})
.to_string();
let project_dir = create_project_dir()?;
fill_config(&project_dir, config_name, Some(&config_content))?;
expect_output(&project_dir, Some("v0.1.0"), None);
project_dir.close()
}
#[test]
fn test_jsr_package_version_with_jsr_jsonc() -> io::Result<()> {
let config_name = "jsr.jsonc";
let config_content = r#"{
"name": "starship", // comment
"version": "0.1.0",
}"#
.to_string();
let project_dir = create_project_dir()?;
fill_config(&project_dir, config_name, Some(&config_content))?;
expect_output(&project_dir, Some("v0.1.0"), None);
project_dir.close()
}
#[test]
fn test_jsr_package_version_with_deno_json() -> io::Result<()> {
let config_name = "deno.json";
let config_content = json::json!({
"name": "starship",
"version": "0.1.0"
})
.to_string();
let project_dir = create_project_dir()?;
fill_config(&project_dir, config_name, Some(&config_content))?;
expect_output(&project_dir, Some("v0.1.0"), None);
project_dir.close()
}
#[test]
fn test_jsr_package_version_with_deno_jsonc() -> io::Result<()> {
let config_name = "deno.jsonc";
let config_content = r#"{
"name": "starship", // comment
"version": "0.1.0",
}"#
.to_string();
let project_dir = create_project_dir()?;
fill_config(&project_dir, config_name, Some(&config_content))?;
expect_output(&project_dir, Some("v0.1.0"), None);
project_dir.close()
}
#[test]
fn test_crystal_shard_version() -> io::Result<()> {
let config_name = "shard.yml";
let config_content = "name: starship\nversion: 1.2.3\n".to_string();
let project_dir = create_project_dir()?;
fill_config(&project_dir, config_name, Some(&config_content))?;
expect_output(&project_dir, Some("v1.2.3"), None);
project_dir.close()
}
#[test]
fn test_node_package_version_with_non_semantic_tag() -> io::Result<()> {
let config_name = "package.json";
let config_content = json::json!({
"name": "starship",
"version": "v0.0.0-alpha"
})
.to_string();
let project_dir = create_project_dir()?;
fill_config(&project_dir, config_name, Some(&config_content))?;
expect_output(&project_dir, Some("v0.0.0-alpha"), None);
project_dir.close()
}
#[test]
fn test_extract_poetry_version() -> io::Result<()> {
let config_name = "pyproject.toml";
let config_content = toml::toml! {
[tool.poetry]
name = "starship"
version = "0.1.0"
}
.to_string();
let project_dir = create_project_dir()?;
fill_config(&project_dir, config_name, Some(&config_content))?;
expect_output(&project_dir, Some("v0.1.0"), None);
project_dir.close()
}
#[test]
fn test_extract_poetry_version_without_version() -> io::Result<()> {
let config_name = "pyproject.toml";
let config_content = toml::toml! {
[tool.poetry]
name = "starship"
}
.to_string();
let project_dir = create_project_dir()?;
fill_config(&project_dir, config_name, Some(&config_content))?;
expect_output(&project_dir, None, None);
project_dir.close()
}
#[test]
fn test_extract_pep621_version() -> io::Result<()> {
let config_name = "pyproject.toml";
let config_content = toml::toml! {
[project]
name = "starship"
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | true |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/quarto.rs | src/modules/quarto.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::quarto::QuartoConfig;
use crate::formatter::{StringFormatter, VersionFormatter};
/// Creates a module with the current Quarto version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("quarto");
let config = QuartoConfig::try_load(module.config);
let is_quarto_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_quarto_project {
return None;
}
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,
})
.map(|variable| match variable {
"version" => {
let version = context
.exec_cmd("quarto", &["--version"])?
.stdout
.trim_end()
.to_owned();
VersionFormatter::format_module_version(
module.get_name(),
&version,
config.version_format,
)
.map(Ok)
}
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `quarto`:\n{error}");
return None;
}
});
Some(module)
}
#[cfg(test)]
mod tests {
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
use std::fs::File;
use std::io;
#[test]
fn read_quarto_not_present() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("quarto").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn read_quarto_present() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("test.qmd"))?.sync_all()?;
let actual = ModuleRenderer::new("quarto").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Rgb(117, 170, 219).bold().paint("⨁ v1.4.549 ")
));
assert_eq!(expected, actual);
dir.close()
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/swift.rs | src/modules/swift.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::swift::SwiftConfig;
use crate::formatter::StringFormatter;
use crate::formatter::VersionFormatter;
/// Creates a module with the current Swift version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("swift");
let config: SwiftConfig = SwiftConfig::try_load(module.config);
let is_swift_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_folders(&config.detect_folders)
.set_extensions(&config.detect_extensions)
.is_match();
if !is_swift_project {
return None;
}
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,
})
.map(|variable| match variable {
"version" => {
let swift_version =
parse_swift_version(&context.exec_cmd("swift", &["--version"])?.stdout)?;
VersionFormatter::format_module_version(
module.get_name(),
&swift_version,
config.version_format,
)
.map(Ok)
}
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `swift`:\n{error}");
return None;
}
});
Some(module)
}
fn parse_swift_version(swift_version: &str) -> Option<String> {
// split into ["Apple", "Swift", "version", "5.2.2", ...] or
// ["Swift", "version", "5.3-dev", ...]
let mut split = swift_version.split_whitespace();
let _ = split.position(|t| t == "version")?;
// return "5.2.2" or "5.3-dev"
let version = split.next()?;
Some(version.to_string())
}
#[cfg(test)]
mod tests {
use super::parse_swift_version;
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
use std::fs::File;
use std::io;
#[test]
fn test_parse_swift_version() {
let input = "Apple Swift version 5.2.2";
assert_eq!(parse_swift_version(input), Some(String::from("5.2.2")));
}
#[test]
fn test_parse_swift_version_without_org_name() {
let input = "Swift version 5.3-dev (LLVM ..., Swift ...)";
assert_eq!(parse_swift_version(input), Some(String::from("5.3-dev")));
}
#[test]
fn folder_without_swift_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("swift.txt"))?.sync_all()?;
let actual = ModuleRenderer::new("swift").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_package_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("Package.swift"))?.sync_all()?;
let actual = ModuleRenderer::new("swift").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Fixed(202).bold().paint("🐦 v5.2.2 ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_swift_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("main.swift"))?.sync_all()?;
let actual = ModuleRenderer::new("swift").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Fixed(202).bold().paint("🐦 v5.2.2 ")
));
assert_eq!(expected, actual);
dir.close()
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/memory_usage.rs | src/modules/memory_usage.rs | use systemstat::{
Platform, System,
data::{ByteSize, saturating_sub_bytes},
};
use super::{Context, Module, ModuleConfig};
use crate::configs::memory_usage::MemoryConfig;
use crate::formatter::StringFormatter;
// Display a `ByteSize` in a human readable format.
fn display_bs(bs: ByteSize) -> String {
let mut display_bytes = bs.to_string_as(true);
let mut keep = true;
// Skip decimals and the space before the byte unit.
display_bytes.retain(|c| match c {
' ' => {
keep = true;
false
}
'.' => {
keep = false;
false
}
_ => keep,
});
display_bytes
}
// Calculate the memory usage from total and free memory
fn pct(total: ByteSize, free: ByteSize) -> f64 {
100.0 * saturating_sub_bytes(total, free).0 as f64 / total.0 as f64
}
// Print usage string used/total
fn format_usage_total(total: ByteSize, free: ByteSize) -> String {
format!(
"{}/{}",
display_bs(saturating_sub_bytes(total, free)),
display_bs(total)
)
}
/// Creates a module with system memory usage information
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("memory_usage");
let config = MemoryConfig::try_load(module.config);
// As we default to disabled=true, we have to check here after loading our config module,
// before it was only checking against whatever is in the config starship.toml
if config.disabled {
return None;
}
let system = System::new();
// `memory_and_swap` only works on platforms that have an implementation for swap memory
// But getting both together is faster on some platforms (Windows/Linux)
let (memory, swap) = match system.memory_and_swap() {
// Ignore swap if total is 0
Ok((mem, swap)) if swap.total.0 > 0 => (mem, Some(swap)),
Ok((mem, _)) => (mem, None),
Err(e) => {
log::debug!(
"Failed to retrieve both memory and swap, falling back to memory only: {e}"
);
let mem = match system.memory() {
Ok(mem) => mem,
Err(e) => {
log::warn!("Failed to retrieve memory: {e}");
return None;
}
};
(mem, None)
}
};
let used_pct = pct(memory.total, memory.free);
if (used_pct.round() as i64) < config.threshold {
return None;
}
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,
})
.map(|variable| match variable {
"ram" => Some(Ok(format_usage_total(memory.total, memory.free))),
"ram_pct" => Some(Ok(format!("{used_pct:.0}%"))),
"swap" => Some(Ok(format_usage_total(
swap.as_ref()?.total,
swap.as_ref()?.free,
))),
"swap_pct" => Some(Ok(format!(
"{:.0}%",
pct(swap.as_ref()?.total, swap.as_ref()?.free)
))),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `memory_usage`:\n{error}");
return None;
}
});
Some(module)
}
#[cfg(test)]
mod test {
use super::*;
use crate::test::ModuleRenderer;
#[test]
fn test_format_usage_total() {
assert_eq!(
format_usage_total(ByteSize(1024 * 1024 * 1024), ByteSize(1024 * 1024 * 1024)),
"0B/1GiB"
);
assert_eq!(
format_usage_total(
ByteSize(1024 * 1024 * 1024),
ByteSize(1024 * 1024 * 1024 / 2)
),
"512MiB/1GiB"
);
assert_eq!(
format_usage_total(ByteSize(1024 * 1024 * 1024), ByteSize(0)),
"1GiB/1GiB"
);
}
#[test]
fn test_pct() {
assert_eq!(
pct(ByteSize(1024 * 1024 * 1024), ByteSize(1024 * 1024 * 1024)),
0.0
);
assert_eq!(
pct(
ByteSize(1024 * 1024 * 1024),
ByteSize(1024 * 1024 * 1024 / 2)
),
50.0
);
assert_eq!(pct(ByteSize(1024 * 1024 * 1024), ByteSize(0)), 100.0);
}
#[test]
fn zero_threshold() {
let output = ModuleRenderer::new("memory_usage")
.config(toml::toml! {
[memory_usage]
disabled = false
threshold = 0
})
.collect();
assert!(output.is_some());
}
#[test]
fn impossible_threshold() {
let output = ModuleRenderer::new("memory_usage")
.config(toml::toml! {
[memory_usage]
disabled = false
threshold = 9999
})
.collect();
assert!(output.is_none());
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/elixir.rs | src/modules/elixir.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::elixir::ElixirConfig;
use crate::formatter::StringFormatter;
use crate::formatter::VersionFormatter;
use std::ops::Deref;
use std::sync::LazyLock;
/// Create a module with the current Elixir version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("elixir");
let config = ElixirConfig::try_load(module.config);
let is_elixir_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_elixir_project {
return None;
}
let versions = LazyLock::new(|| get_elixir_version(context));
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,
})
.map(|variable| match variable {
"version" => versions
.deref()
.as_ref()
.map(|(_, elixir_version)| elixir_version)
.map(|elixir_version| {
VersionFormatter::format_module_version(
module.get_name(),
elixir_version,
config.version_format,
)
})?
.map(Ok),
"otp_version" => versions
.deref()
.as_ref()
.map(|(otp_version, _)| otp_version.to_string())
.map(Ok),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `elixir`:\n{error}");
return None;
}
});
Some(module)
}
fn get_elixir_version(context: &Context) -> Option<(String, String)> {
let output = context.exec_cmd("elixir", &["--version"])?.stdout;
parse_elixir_version(&output)
}
fn parse_elixir_version(version: &str) -> Option<(String, String)> {
let mut lines = version.lines();
// split line into ["Erlang/OTP", "22", "[erts-10.5]", ...], take "22"
let otp_version = lines.next()?.split_whitespace().nth(1)?;
// skip empty line
let _ = lines.next()?;
// split line into ["Elixir", "1.10", "(compiled", ...], take "1.10"
let elixir_version = lines.next()?.split_whitespace().nth(1)?;
Some((otp_version.to_string(), elixir_version.to_string()))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
use std::fs::File;
use std::io;
#[test]
fn test_parse_elixir_version() {
let stable_input = "\
Erlang/OTP 23 [erts-11.1.7] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1]
Elixir 1.11.3 (compiled with Erlang/OTP 21)
";
let rc_input = "\
Erlang/OTP 23 [erts-11.1.7] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1]
Elixir 1.12.0-rc.0 (31d2b99) (compiled with Erlang/OTP 21)
";
let dev_input = "\
Erlang/OTP 23 [erts-11.1.7] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1]
Elixir 1.13.0-dev (compiled with Erlang/OTP 23)
";
assert_eq!(
parse_elixir_version(stable_input),
Some(("23".to_string(), "1.11.3".to_string()))
);
assert_eq!(
parse_elixir_version(rc_input),
Some(("23".to_string(), "1.12.0-rc.0".to_string()))
);
assert_eq!(
parse_elixir_version(dev_input),
Some(("23".to_string(), "1.13.0-dev".to_string()))
);
}
#[test]
fn test_without_mix_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let expected = None;
let output = ModuleRenderer::new("elixir").path(dir.path()).collect();
assert_eq!(output, expected);
dir.close()
}
#[test]
fn test_with_mix_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("mix.exs"))?.sync_all()?;
let expected = Some(format!(
"via {}",
Color::Purple.bold().paint("💧 v1.10 (OTP 22) ")
));
let output = ModuleRenderer::new("elixir").path(dir.path()).collect();
assert_eq!(output, expected);
dir.close()
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/erlang.rs | src/modules/erlang.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::erlang::ErlangConfig;
use crate::formatter::StringFormatter;
use crate::formatter::VersionFormatter;
/// Create a module with the current Erlang version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("erlang");
let config = ErlangConfig::try_load(module.config);
let is_erlang_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_erlang_project {
return None;
}
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|variable, _| match variable {
"symbol" => Some(config.symbol),
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map(|variable| match variable {
"version" => {
let erlang_version = get_erlang_version(context)?;
VersionFormatter::format_module_version(
module.get_name(),
&erlang_version,
config.version_format,
)
.map(Ok)
}
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `erlang`:\n{error}");
return None;
}
});
Some(module)
}
fn get_erlang_version(context: &Context) -> Option<String> {
Some(context.exec_cmd(
"erl",
&[
"-noshell",
"-eval",
"Fn=filename:join([code:root_dir(),\"releases\",erlang:system_info(otp_release),\"OTP_VERSION\"]),\
{ok,Content}=file:read_file(Fn),\
io:format(\"~s\",[Content]),\
halt(0)."
]
)?.stdout.trim().to_string())
}
#[cfg(test)]
mod tests {
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
use std::fs::File;
use std::io;
#[test]
fn test_without_config() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let expected = None;
let output = ModuleRenderer::new("erlang").path(dir.path()).collect();
assert_eq!(output, expected);
dir.close()
}
#[test]
fn test_with_config() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("rebar.config"))?.sync_all()?;
let expected = Some(format!("via {}", Color::Red.bold().paint(" v22.1.3 ")));
let output = ModuleRenderer::new("erlang").path(dir.path()).collect();
assert_eq!(output, expected);
dir.close()
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/dotnet.rs | src/modules/dotnet.rs | use quick_xml::Reader;
use quick_xml::events::Event;
use std::ffi::OsStr;
use std::iter::Iterator;
use std::path::{Path, PathBuf};
use std::str;
use super::{Context, Module, ModuleConfig};
use crate::configs::dotnet::DotnetConfig;
use crate::formatter::StringFormatter;
use crate::utils;
type JValue = serde_json::Value;
use crate::formatter::VersionFormatter;
const GLOBAL_JSON_FILE: &str = "global.json";
const PROJECT_JSON_FILE: &str = "project.json";
/// A module which shows the latest (or pinned) version of the dotnet SDK
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("dotnet");
let config = DotnetConfig::try_load(module.config);
// First check if this is a DotNet Project before doing the O(n)
// check for the version using the JSON files
let is_dotnet_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_dotnet_project {
return None;
}
let dotnet_files = get_local_dotnet_files(context).ok()?;
// Internally, this module uses its own mechanism for version detection.
// Typically it is twice as fast as running `dotnet --version`.
let enable_heuristic = config.heuristic;
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map(|variable| match variable {
"symbol" => Some(Ok(config.symbol)),
_ => None,
})
.map(|variable| match variable {
"version" => {
let version = if enable_heuristic {
let repo_root = context.get_repo().ok().and_then(|r| r.workdir.as_deref());
estimate_dotnet_version(
context,
&dotnet_files,
&context.current_dir,
repo_root,
)
} else {
get_version_from_cli(context)
};
VersionFormatter::format_module_version(
module.get_name(),
&version?,
config.version_format,
)
.map(Ok)
}
"tfm" => find_current_tfm(&dotnet_files).map(Ok),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `dotnet`:\n{error}");
return None;
}
});
Some(module)
}
fn find_current_tfm(files: &[DotNetFile]) -> Option<String> {
let get_file_of_type = |t: FileType| files.iter().find(|f| f.file_type == t);
let relevant_file = get_file_of_type(FileType::ProjectFile)?;
get_tfm_from_project_file(relevant_file.path.as_path())
}
fn get_tfm_from_project_file(path: &Path) -> Option<String> {
let project_file = utils::read_file(path).ok()?;
let mut reader = Reader::from_str(&project_file);
reader.config_mut().trim_text(true);
let mut in_tfm = false;
let mut buf = Vec::new();
loop {
match reader.read_event_into(&mut buf) {
// for triggering namespaced events, use this instead:
// match reader.read_namespaced_event(&mut buf) {
Ok(Event::Start(ref e)) => {
// for namespaced:
// Ok((ref namespace_value, Event::Start(ref e)))
match e.name().as_ref() {
b"TargetFrameworks" => in_tfm = true,
b"TargetFramework" => in_tfm = true,
_ => in_tfm = false,
}
}
// unescape and decode the text event using the reader encoding
Ok(Event::Text(e)) => {
if in_tfm {
return e.decode().ok().map(std::borrow::Cow::into_owned);
}
}
Ok(Event::Eof) => break, // exits the loop when reaching end of file
Err(e) => {
log::error!(
"Error parsing project file {path:?} at position {pos}: {e:?}",
pos = reader.buffer_position()
);
return None;
}
_ => (), // There are several other `Event`s we do not consider here
}
// if we don't keep a borrow elsewhere, we can clear the buffer to keep memory usage low
buf.clear();
}
None
}
fn estimate_dotnet_version(
context: &Context,
files: &[DotNetFile],
current_dir: &Path,
repo_root: Option<&Path>,
) -> Option<String> {
let get_file_of_type = |t: FileType| files.iter().find(|f| f.file_type == t);
// It's important to check for a global.json or a solution file first,
// but otherwise we can take any relevant file. We'll take whichever is first.
let relevant_file = get_file_of_type(FileType::GlobalJson)
.or_else(|| get_file_of_type(FileType::SolutionFile))
.or_else(|| files.iter().next())?;
match relevant_file.file_type {
FileType::GlobalJson => get_pinned_sdk_version_from_file(relevant_file.path.as_path())
.or_else(|| get_latest_sdk_from_cli(context)),
FileType::SolutionFile => {
// With this heuristic, we'll assume that a "global.json" won't
// be found in any directory above the solution file.
get_latest_sdk_from_cli(context)
}
_ => {
// If we see a dotnet project, we'll check a small number of neighboring
// directories to see if we can find a global.json. Otherwise, assume the
// latest SDK is in use.
try_find_nearby_global_json(current_dir, repo_root)
.or_else(|| get_latest_sdk_from_cli(context))
}
}
}
/// Looks for a `global.json` which may exist in one of the parent directories of the current path.
/// If there is one present, and it contains valid version pinning information, then return that version.
///
/// The following places are scanned:
/// - The parent of the current directory
/// (Unless there is a git repository, and the parent is above the root of that repository)
/// - The root of the git repository
/// (If there is one)
fn try_find_nearby_global_json(current_dir: &Path, repo_root: Option<&Path>) -> Option<String> {
let current_dir_is_repo_root = repo_root == Some(current_dir);
let parent_dir = if current_dir_is_repo_root {
// Don't scan the parent directory if it's above the root of a git repository
None
} else {
current_dir.parent()
};
// Check the parent directory, or otherwise the repository root, for a global.json
let mut check_dirs = parent_dir
.iter()
.chain(&repo_root)
.copied() // Copies the reference, not the Path itself
.collect::<Vec<&Path>>();
// The parent directory and repository root may be the same directory,
// so avoid checking it twice.
check_dirs.dedup();
check_dirs
.iter()
// repo_root may be the same as the current directory. We don't need to scan it again.
.filter(|&&d| d != current_dir)
.find_map(|d| check_directory_for_global_json(d))
}
fn check_directory_for_global_json(path: &Path) -> Option<String> {
let global_json_path = path.join(GLOBAL_JSON_FILE);
log::debug!(
"Checking if global.json exists at: {}",
&global_json_path.display()
);
if global_json_path.exists() {
get_pinned_sdk_version_from_file(&global_json_path)
} else {
None
}
}
fn get_pinned_sdk_version_from_file(path: &Path) -> Option<String> {
let json_text = crate::utils::read_file(path).ok()?;
log::debug!(
"Checking if .NET SDK version is pinned in: {}",
path.display()
);
get_pinned_sdk_version(&json_text)
}
fn get_pinned_sdk_version(json: &str) -> Option<String> {
let parsed_json: JValue = serde_json::from_str(json).ok()?;
match parsed_json {
JValue::Object(root) => {
let sdk = root.get("sdk")?;
match sdk {
JValue::Object(sdk) => {
let version = sdk.get("version")?;
match version {
JValue::String(version_string) => {
let mut buffer = String::with_capacity(version_string.len() + 1);
buffer.push_str(version_string);
Some(buffer)
}
_ => None,
}
}
_ => None,
}
}
_ => None,
}
}
fn get_local_dotnet_files<'a>(context: &'a Context) -> Result<Vec<DotNetFile>, &'a std::io::Error> {
Ok(context
.dir_contents()?
.files()
.filter_map(|p| {
get_dotnet_file_type(p).map(|t| DotNetFile {
path: context.current_dir.join(p),
file_type: t,
})
})
.collect())
}
fn get_dotnet_file_type(path: &Path) -> Option<FileType> {
let file_name_lower = map_str_to_lower(path.file_name());
match file_name_lower.as_ref().map(AsRef::as_ref) {
Some(GLOBAL_JSON_FILE) => return Some(FileType::GlobalJson),
Some(PROJECT_JSON_FILE) => return Some(FileType::ProjectJson),
_ => (),
};
let extension_lower = map_str_to_lower(path.extension());
match extension_lower.as_ref().map(AsRef::as_ref) {
Some("sln") => return Some(FileType::SolutionFile),
Some("csproj" | "fsproj" | "xproj") => return Some(FileType::ProjectFile),
Some("props" | "targets") => return Some(FileType::MsBuildFile),
_ => (),
}
None
}
fn map_str_to_lower(value: Option<&OsStr>) -> Option<String> {
Some(value?.to_str()?.to_ascii_lowercase())
}
fn get_version_from_cli(context: &Context) -> Option<String> {
let version_output = context.exec_cmd("dotnet", &["--version"])?;
Some(version_output.stdout.trim().to_string())
}
fn get_latest_sdk_from_cli(context: &Context) -> Option<String> {
if let Some(sdks_output) = context.exec_cmd("dotnet", &["--list-sdks"]) {
fn parse_failed<T>() -> Option<T> {
log::warn!("Unable to parse the output from `dotnet --list-sdks`.");
None
}
let latest_sdk = sdks_output
.stdout
.lines()
.map(str::trim)
.rfind(|l| !l.is_empty())
.or_else(parse_failed)?;
let take_until = latest_sdk.find('[').or_else(parse_failed)? - 1;
if take_until > 1 {
let version = &latest_sdk[..take_until];
let mut buffer = String::with_capacity(version.len() + 1);
buffer.push_str(version);
Some(buffer)
} else {
parse_failed()
}
} else {
// Older versions of the dotnet cli do not support the --list-sdks command
// So, if the status code indicates failure, fall back to `dotnet --version`
log::debug!(
"Received a non-success exit code from `dotnet --list-sdks`. \
Falling back to `dotnet --version`.",
);
get_version_from_cli(context)
}
}
struct DotNetFile {
path: PathBuf,
file_type: FileType,
}
#[derive(PartialEq)]
enum FileType {
ProjectJson,
ProjectFile,
GlobalJson,
SolutionFile,
MsBuildFile,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test::ModuleRenderer;
use crate::utils::create_command;
use nu_ansi_term::Color;
use std::fs::{self, OpenOptions};
use std::io::{self, Write};
use tempfile::{self, TempDir};
use utils::{CommandOutput, write_file};
#[test]
fn shows_nothing_in_directory_with_zero_relevant_files() -> io::Result<()> {
let workspace = create_workspace(false)?;
expect_output(workspace.path(), None);
workspace.close()
}
#[test]
fn shows_latest_in_directory_with_directory_build_props_file() -> io::Result<()> {
let workspace = create_workspace(false)?;
touch_path(&workspace, "Directory.Build.props", None)?;
expect_output(
workspace.path(),
Some(format!(
"via {}",
Color::Blue.bold().paint(".NET v3.1.103 ")
)),
);
workspace.close()
}
#[test]
fn shows_latest_in_directory_with_directory_build_targets_file() -> io::Result<()> {
let workspace = create_workspace(false)?;
touch_path(&workspace, "Directory.Build.targets", None)?;
expect_output(
workspace.path(),
Some(format!(
"via {}",
Color::Blue.bold().paint(".NET v3.1.103 ")
)),
);
workspace.close()
}
#[test]
fn shows_latest_in_directory_with_packages_props_file() -> io::Result<()> {
let workspace = create_workspace(false)?;
touch_path(&workspace, "Packages.props", None)?;
expect_output(
workspace.path(),
Some(format!(
"via {}",
Color::Blue.bold().paint(".NET v3.1.103 ")
)),
);
workspace.close()
}
#[test]
fn shows_latest_in_directory_with_solution() -> io::Result<()> {
let workspace = create_workspace(false)?;
touch_path(&workspace, "solution.sln", None)?;
expect_output(workspace.path(), None);
workspace.close()
}
#[test]
fn shows_latest_in_directory_with_csproj() -> io::Result<()> {
let workspace = create_workspace(false)?;
let csproj = make_csproj_with_tfm("TargetFramework", "netstandard2.0");
touch_path(&workspace, "project.csproj", Some(&csproj))?;
expect_output(
workspace.path(),
Some(format!(
"via {}",
Color::Blue.bold().paint(".NET v3.1.103 🎯 netstandard2.0 ")
)),
);
workspace.close()
}
#[test]
fn shows_latest_in_directory_with_fsproj() -> io::Result<()> {
let workspace = create_workspace(false)?;
touch_path(&workspace, "project.fsproj", None)?;
expect_output(
workspace.path(),
Some(format!(
"via {}",
Color::Blue.bold().paint(".NET v3.1.103 ")
)),
);
workspace.close()
}
#[test]
fn shows_latest_in_directory_with_xproj() -> io::Result<()> {
let workspace = create_workspace(false)?;
touch_path(&workspace, "project.xproj", None)?;
expect_output(
workspace.path(),
Some(format!(
"via {}",
Color::Blue.bold().paint(".NET v3.1.103 ")
)),
);
workspace.close()
}
#[test]
fn shows_latest_in_directory_with_project_json() -> io::Result<()> {
let workspace = create_workspace(false)?;
touch_path(&workspace, "project.json", None)?;
expect_output(
workspace.path(),
Some(format!(
"via {}",
Color::Blue.bold().paint(".NET v3.1.103 ")
)),
);
workspace.close()
}
#[test]
fn shows_pinned_in_directory_with_global_json() -> io::Result<()> {
let workspace = create_workspace(false)?;
let global_json = make_pinned_sdk_json("1.2.3");
touch_path(&workspace, "global.json", Some(&global_json))?;
expect_output(
workspace.path(),
Some(format!("via {}", Color::Blue.bold().paint(".NET v1.2.3 "))),
);
workspace.close()
}
#[test]
fn shows_pinned_in_project_below_root_with_global_json() -> io::Result<()> {
let workspace = create_workspace(false)?;
let global_json = make_pinned_sdk_json("1.2.3");
let csproj = make_csproj_with_tfm("TargetFramework", "netstandard2.0");
touch_path(&workspace, "global.json", Some(&global_json))?;
touch_path(&workspace, "project/project.csproj", Some(&csproj))?;
expect_output(
&workspace.path().join("project"),
Some(format!(
"via {}",
Color::Blue.bold().paint(".NET v1.2.3 🎯 netstandard2.0 ")
)),
);
workspace.close()
}
#[test]
fn shows_pinned_in_deeply_nested_project_within_repository() -> io::Result<()> {
let workspace = create_workspace(true)?;
let global_json = make_pinned_sdk_json("1.2.3");
let csproj = make_csproj_with_tfm("TargetFramework", "netstandard2.0");
touch_path(&workspace, "global.json", Some(&global_json))?;
touch_path(
&workspace,
"deep/path/to/project/project.csproj",
Some(&csproj),
)?;
expect_output(
&workspace.path().join("deep/path/to/project"),
Some(format!(
"via {}",
Color::Blue.bold().paint(".NET v1.2.3 🎯 netstandard2.0 ")
)),
);
workspace.close()
}
#[test]
fn shows_single_tfm() -> io::Result<()> {
let workspace = create_workspace(false)?;
let csproj = make_csproj_with_tfm("TargetFramework", "netstandard2.0");
touch_path(&workspace, "project.csproj", Some(&csproj))?;
expect_output(
workspace.path(),
Some(format!(
"via {}",
Color::Blue.bold().paint(".NET v3.1.103 🎯 netstandard2.0 ")
)),
);
workspace.close()
}
#[test]
fn shows_multiple_tfms() -> io::Result<()> {
let workspace = create_workspace(false)?;
let csproj = make_csproj_with_tfm("TargetFrameworks", "netstandard2.0;net461");
touch_path(&workspace, "project.csproj", Some(&csproj))?;
expect_output(
workspace.path(),
Some(format!(
"via {}",
Color::Blue
.bold()
.paint(".NET v3.1.103 🎯 netstandard2.0;net461 ")
)),
);
workspace.close()
}
#[test]
fn version_from_dotnet_cli() -> io::Result<()> {
let dir = tempfile::tempdir()?;
write_file(dir.path().join("main.cs"), "")?;
let expected = Some(format!(
"via {}",
Color::Blue.bold().paint(".NET v8.0.301 ")
));
let actual = ModuleRenderer::new("dotnet")
.path(dir.path())
.cmd(
"dotnet --version",
Some(CommandOutput {
stdout: "8.0.301\n".to_string(),
stderr: String::new(),
}),
)
.config(toml::toml! {
[dotnet]
heuristic = false
detect_extensions = ["cs"]
})
.collect();
assert_eq!(expected, actual);
dir.close()
}
fn create_workspace(is_repo: bool) -> io::Result<TempDir> {
let repo_dir = tempfile::tempdir()?;
if is_repo {
create_command("git")?
.args(["init", "--quiet"])
.current_dir(repo_dir.path())
.output()?;
}
Ok(repo_dir)
}
fn touch_path(
workspace: &TempDir,
relative_path: &str,
contents: Option<&str>,
) -> io::Result<()> {
let path = workspace.path().join(relative_path);
fs::create_dir_all(
path.parent()
.expect("Expected relative_path to be a file in a directory"),
)?;
let mut file = OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(&path)?;
write!(file, "{}", contents.unwrap_or(""))?;
file.sync_data()
}
fn make_pinned_sdk_json(version: &str) -> String {
let json_text = r#"
{
"sdk": {
"version": "INSERT_VERSION"
}
}
"#;
json_text.replace("INSERT_VERSION", version)
}
fn make_csproj_with_tfm(tfm_element: &str, tfm: &str) -> String {
let json_text = r"
<Project>
<PropertyGroup>
<TFM_ELEMENT>TFM_VALUE</TFM_ELEMENT>
</PropertyGroup>
</Project>
";
json_text
.replace("TFM_ELEMENT", tfm_element)
.replace("TFM_VALUE", tfm)
}
fn expect_output(dir: &Path, expected: Option<String>) {
let actual = ModuleRenderer::new("dotnet").path(dir).collect();
assert_eq!(actual, expected);
}
#[test]
fn should_parse_version_from_global_json() {
let json_text = r#"
{
"sdk": {
"version": "1.2.3"
}
}
"#;
let version = get_pinned_sdk_version(json_text).unwrap();
assert_eq!("1.2.3", version);
}
#[test]
fn should_ignore_empty_global_json() {
let json_text = "{}";
let version = get_pinned_sdk_version(json_text);
assert!(version.is_none());
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/buf.rs | src/modules/buf.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::buf::BufConfig;
use crate::formatter::StringFormatter;
use crate::formatter::VersionFormatter;
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("buf");
let config: BufConfig = BufConfig::try_load(module.config);
let is_buf_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_buf_project {
return None;
}
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|variable, _| match variable {
"symbol" => Some(config.symbol),
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map(|variable| match variable {
"version" => {
let buf_version =
parse_buf_version(&context.exec_cmd("buf", &["--version"])?.stdout)?;
VersionFormatter::format_module_version(
module.get_name(),
&buf_version,
config.version_format,
)
}
.map(Ok),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `buf`:\n{error}");
return None;
}
});
Some(module)
}
fn parse_buf_version(buf_version: &str) -> Option<String> {
Some(buf_version.split_whitespace().next()?.to_string())
}
#[cfg(test)]
mod tests {
use super::parse_buf_version;
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
use std::fs::File;
use std::io;
#[test]
fn buf_version() {
let ok_versions = ["1.0.0", "1.1.0-dev"];
let not_ok_versions = ["foo", "1.0"];
let all_some = ok_versions.iter().all(|&v| parse_buf_version(v).is_some());
let all_none = not_ok_versions
.iter()
.any(|&v| parse_buf_version(v).is_some());
assert!(all_some);
assert!(all_none);
}
#[test]
fn folder_without_buf_config() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("buf").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_buf_config() {
let ok_files = ["buf.yaml", "buf.gen.yaml", "buf.work.yaml"];
let not_ok_files = ["buf.json"];
for file in ok_files {
let dir = tempfile::tempdir().unwrap();
File::create(dir.path().join(file))
.unwrap()
.sync_all()
.unwrap();
let actual = ModuleRenderer::new("buf").path(dir.path()).collect();
let expected = Some(format!("with {}", Color::Blue.bold().paint("🐃 v1.0.0 ")));
assert_eq!(expected, actual);
dir.close().unwrap();
}
for file in not_ok_files {
let dir = tempfile::tempdir().unwrap();
File::create(dir.path().join(file))
.unwrap()
.sync_all()
.unwrap();
let actual = ModuleRenderer::new("buf").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close().unwrap();
}
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/haskell.rs | src/modules/haskell.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::haskell::HaskellConfig;
use crate::formatter::StringFormatter;
/// Creates a module with the current Haskell version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("haskell");
let config = HaskellConfig::try_load(module.config);
let is_hs_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_hs_project {
return None;
}
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,
})
.map(|variable| match variable {
"version" => get_version(context).map(Ok),
"ghc_version" => get_ghc_version(context).map(Ok),
"snapshot" => get_snapshot(context).map(Ok),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `haskell`:\n{error}");
return None;
}
});
Some(module)
}
fn get_ghc_version(context: &Context) -> Option<String> {
Some(
context
.exec_cmd("ghc", &["--numeric-version"])?
.stdout
.trim()
.to_string(),
)
}
fn get_snapshot(context: &Context) -> Option<String> {
if !is_stack_project(context) {
return None;
}
let file_contents = context.read_file_from_pwd("stack.yaml")?;
let yaml = yaml_rust2::YamlLoader::load_from_str(&file_contents).ok()?;
let version = yaml.first()?["resolver"]
.as_str()
.or_else(|| yaml.first()?["snapshot"].as_str())
.filter(|s| s.starts_with("lts") || s.starts_with("nightly") || s.starts_with("ghc"))
.unwrap_or("<custom snapshot>");
Some(version.to_string())
}
fn get_version(context: &Context) -> Option<String> {
get_snapshot(context).or_else(|| get_ghc_version(context))
}
fn is_stack_project(context: &Context) -> bool {
match context.dir_contents() {
Ok(dir) => dir.has_file_name("stack.yaml"),
Err(_) => false,
}
}
#[cfg(test)]
mod tests {
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
use std::fs::File;
use std::io;
use std::io::Write;
#[test]
fn folder_without_hs_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("haskell").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_stack() -> io::Result<()> {
let cases = vec![
("resolver: lts-18.12\n", "lts-18.12"),
("snapshot: nightly-2011-11-11", "nightly-2011-11-11"),
("snapshot: ghc-8.10.7", "ghc-8.10.7"),
(
"snapshot: https://github.com/whatever/xxx.yaml\n",
"<custom snapshot>",
),
(
"resolver:\n url: https://github.com/whatever/xxx.yaml\n",
"<custom snapshot>",
),
(REANIMATE_STACK_YAML, "lts-14.27"),
];
for (yaml, resolver) in &cases {
let dir = tempfile::tempdir()?;
let mut file = File::create(dir.path().join("stack.yaml"))?;
file.write_all(yaml.as_bytes())?;
file.sync_all()?;
let actual = ModuleRenderer::new("haskell").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Purple.bold().paint(format!("λ {resolver} "))
));
assert_eq!(expected, actual);
dir.close()?;
}
Ok(())
}
#[test]
fn folder_cabal() -> io::Result<()> {
let should_trigger = vec!["a.hs", "b.hs-boot", "cabal.project"];
for hs_file in &should_trigger {
let dir = tempfile::tempdir()?;
File::create(dir.path().join(hs_file))?.sync_all()?;
let actual = ModuleRenderer::new("haskell").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Purple.bold().paint("λ 9.2.1 ")));
assert_eq!(expected, actual);
dir.close()?;
}
Ok(())
}
static REANIMATE_STACK_YAML: &str = r"
resolver: lts-14.27
allow-newer: false
packages:
- .
extra-deps:
- reanimate-svg-0.13.0.1
- chiphunk-0.1.2.1
- cubicbezier-0.6.0.6@sha256:2191ff47144d9a13a2784651a33d340cd31be1926a6c188925143103eb3c8db3
- fast-math-1.0.2@sha256:91181eb836e54413cc5a841e797c42b2264954e893ea530b6fc4da0dccf6a8b7
- matrices-0.5.0@sha256:b2761813f6a61c84224559619cc60a16a858ac671c8436bbac8ec89e85473058
- hmatrix-0.20.0.0@sha256:d79a9218e314f1a2344457c3851bd1d2536518ecb5f1a2fcd81daa45e46cd025,4870
- earcut-0.1.0.4@sha256:d5118b3eecf24d130263d81fb30f1ff56b1db43036582bfd1d8cc9ba3adae8be,1010
- tasty-rerun-1.1.17@sha256:d4a3ccb0f63f499f36edc71b33c0f91c850eddb22dd92b928aa33b8459f3734a,1373
- hgeometry-0.11.0.0@sha256:09ead201a6ac3492c0be8dda5a6b32792b9ae87cab730b8362d46ee8d5c2acb4,11714
- hgeometry-combinatorial-0.11.0.0@sha256:03176f235a1c49a415fe1266274dafca84deb917cbcbf9a654452686b4cd2bfe,8286
- vinyl-0.13.0@sha256:0f247cd3f8682b30881a07de18e6fec52d540646fbcb328420049cc8d63cd407,3724
- hashable-1.3.0.0@sha256:4c70f1407881059e93550d3742191254296b2737b793a742bd901348fb3e1fb1,5206
- network-3.1.2.1@sha256:188d6daea8cd91bc3553efd5a90a1e7c6d0425fa66a53baa74db5b6d9fd75c8b,4968
";
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/directory.rs | src/modules/directory.rs | #[cfg(not(target_os = "windows"))]
use super::utils::directory_nix as directory_utils;
#[cfg(target_os = "windows")]
use super::utils::directory_win as directory_utils;
use super::utils::path::PathExt as SPathExt;
use indexmap::IndexMap;
use path_slash::{PathBufExt, PathExt};
use std::borrow::Cow;
use std::iter::FromIterator;
use std::path::{Path, PathBuf};
use unicode_segmentation::UnicodeSegmentation;
use super::{Context, Module};
use super::utils::directory::truncate;
use crate::config::ModuleConfig;
use crate::configs::directory::DirectoryConfig;
use crate::formatter::StringFormatter;
/// Creates a module with the current logical or physical directory
///
/// Will perform path contraction, substitution, and truncation.
///
/// **Contraction**
/// - Paths beginning with the home directory or with a git repo right inside
/// the home directory will be contracted to `~`, or the set `HOME_SYMBOL`
/// - Paths containing a git repo will contract to begin at the repo root
///
/// **Substitution**
/// Paths will undergo user-provided substitutions of substrings
///
/// **Truncation**
/// Paths will be limited in length to `3` path components by default.
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("directory");
let config: DirectoryConfig = DirectoryConfig::try_load(module.config);
let home_dir = context
.get_home()
.expect("Unable to determine HOME_DIR for user");
let physical_dir = &context.current_dir;
let display_dir = if config.use_logical_path {
&context.logical_dir
} else {
&context.current_dir
};
log::debug!("Home dir: {:?}", &home_dir);
log::debug!("Physical dir: {:?}", &physical_dir);
log::debug!("Display dir: {:?}", &display_dir);
// Attempt repository path contraction (if we are in a git repository)
// Otherwise use the logical path, automatically contracting
let repo = if config.truncate_to_repo || config.repo_root_style.is_some() {
context.get_repo().ok()
} else {
None
};
let dir_string = if config.truncate_to_repo {
repo.and_then(|r| r.workdir.as_ref())
.filter(|&root| root != &home_dir)
.and_then(|root| contract_repo_path(display_dir, root))
} else {
None
};
let mut is_truncated = dir_string.is_some();
// the home directory if required.
let dir_string = dir_string
.unwrap_or_else(|| contract_path(display_dir, &home_dir, config.home_symbol).to_string());
#[cfg(windows)]
let dir_string = remove_extended_path_prefix(dir_string);
// Apply path substitutions
let dir_string = substitute_path(dir_string, &config.substitutions);
// Truncate the dir string to the maximum number of path components
let dir_string =
if let Some(truncated) = truncate(&dir_string, config.truncation_length as usize) {
is_truncated = true;
truncated
} else {
dir_string
};
let prefix = if is_truncated {
// Substitutions could have changed the prefix, so don't allow them and
// fish-style path contraction together
if config.fish_style_pwd_dir_length > 0 && config.substitutions.is_empty() {
// If user is using fish style path, we need to add the segment first
let contracted_home_dir = contract_path(display_dir, &home_dir, config.home_symbol);
to_fish_style(
config.fish_style_pwd_dir_length as usize,
&contracted_home_dir,
&dir_string,
)
} else {
String::from(config.truncation_symbol)
}
} else {
String::new()
};
let path_vec = match &repo.and_then(|r| r.workdir.as_ref()) {
Some(repo_root) if config.repo_root_style.is_some() => {
let contracted_path = contract_repo_path(display_dir, repo_root)?;
let repo_path_vec: Vec<&str> = contracted_path.split('/').collect();
let after_repo_root = contracted_path.replacen(repo_path_vec[0], "", 1);
let num_segments_after_root = after_repo_root.split('/').count();
if config.truncation_length == 0
|| ((num_segments_after_root - 1) as i64) < config.truncation_length
{
let root = repo_path_vec[0];
let before = before_root_dir(&dir_string, &contracted_path);
[prefix + before, root.to_string(), after_repo_root]
} else {
[String::new(), String::new(), prefix + dir_string.as_str()]
}
}
_ => [String::new(), String::new(), prefix + dir_string.as_str()],
};
let path_vec = if config.use_os_path_sep {
path_vec.map(|i| convert_path_sep(&i))
} else {
path_vec
};
let display_format = if path_vec[0].is_empty() && path_vec[1].is_empty() {
config.format
} else {
config.repo_root_format
};
let repo_root_style = config.repo_root_style.unwrap_or(config.style);
let before_repo_root_style = config.before_repo_root_style.unwrap_or(config.style);
let parsed = StringFormatter::new(display_format).and_then(|formatter| {
formatter
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
"read_only_style" => Some(Ok(config.read_only_style)),
"repo_root_style" => Some(Ok(repo_root_style)),
"before_repo_root_style" => Some(Ok(before_repo_root_style)),
_ => None,
})
.map(|variable| match variable {
"path" => Some(Ok(path_vec[2].as_str())),
"before_root_path" => Some(Ok(path_vec[0].as_str())),
"repo_root" => Some(Ok(path_vec[1].as_str())),
"read_only" => {
if is_readonly_dir(physical_dir) {
Some(Ok(config.read_only))
} else {
None
}
}
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `directory`:\n{error}");
return None;
}
});
Some(module)
}
#[cfg(windows)]
fn remove_extended_path_prefix(path: String) -> String {
fn try_trim_prefix<'a>(s: &'a str, prefix: &str) -> Option<&'a str> {
if !s.starts_with(prefix) {
return None;
}
Some(&s[prefix.len()..])
}
// Trim any Windows extended-path prefix from the display path
if let Some(unc) = try_trim_prefix(&path, r"\\?\UNC\") {
return format!(r"\\{unc}");
}
if let Some(p) = try_trim_prefix(&path, r"\\?\") {
return p.to_string();
}
path
}
fn is_readonly_dir(path: &Path) -> bool {
match directory_utils::is_write_allowed(path) {
Ok(res) => !res,
Err(e) => {
log::debug!("Failed to determine read only status of directory '{path:?}': {e}");
false
}
}
}
/// Contract the root component of a path
///
/// Replaces the `top_level_path` in a given `full_path` with the provided
/// `top_level_replacement`.
fn contract_path<'a>(
full_path: &'a Path,
top_level_path: &'a Path,
top_level_replacement: &'a str,
) -> Cow<'a, str> {
if !full_path.normalised_starts_with(top_level_path) {
return full_path.to_slash_lossy();
}
if full_path.normalised_equals(top_level_path) {
return Cow::from(top_level_replacement);
}
// Because we've done a normalised path comparison above
// we can safely ignore the Prefix components when doing this
// strip_prefix operation.
let sub_path = full_path
.without_prefix()
.strip_prefix(top_level_path.without_prefix())
.unwrap_or(full_path);
Cow::from(format!(
"{replacement}{separator}{path}",
replacement = top_level_replacement,
separator = "/",
path = sub_path.to_slash_lossy()
))
}
/// Contract the root component of a path based on the real path
///
/// Replaces the `top_level_path` in a given `full_path` with the provided
/// `top_level_replacement` by walking ancestors and comparing its real path.
fn contract_repo_path(full_path: &Path, top_level_path: &Path) -> Option<String> {
let top_level_real_path = real_path(top_level_path);
// Walk ancestors to preserve logical path in `full_path`.
// If we'd just `full_real_path.strip_prefix(top_level_real_path)`,
// then it wouldn't preserve logical path. It would've returned physical path.
for (i, ancestor) in full_path.ancestors().enumerate() {
let ancestor_real_path = real_path(ancestor);
if ancestor_real_path != top_level_real_path {
continue;
}
let components: Vec<_> = full_path.components().collect();
let repo_name = components[components.len() - i - 1]
.as_os_str()
.to_string_lossy();
if i == 0 {
return Some(repo_name.to_string());
}
let path = PathBuf::from_iter(&components[components.len() - i..]);
return Some(format!(
"{repo_name}{separator}{path}",
repo_name = repo_name,
separator = "/",
path = path.to_slash_lossy()
));
}
None
}
fn real_path<P: AsRef<Path>>(path: P) -> PathBuf {
let path = path.as_ref();
let mut buf = PathBuf::new();
for component in path.components() {
let next = buf.join(component);
if let Ok(realpath) = next.read_link() {
if realpath.is_absolute() {
buf = realpath;
} else {
buf.push(realpath);
}
} else {
buf = next;
}
}
buf.canonicalize().unwrap_or_else(|_| path.into())
}
/// Perform a list of string substitutions on the path
///
/// Given a list of (from, to) pairs, this will perform the string
/// substitutions, in order, on the path. Any non-pair of strings is ignored.
fn substitute_path(dir_string: String, substitutions: &IndexMap<String, &str>) -> String {
let mut substituted_dir = dir_string;
for substitution_pair in substitutions {
substituted_dir = substituted_dir.replace(substitution_pair.0, substitution_pair.1);
}
substituted_dir
}
/// Takes part before contracted path and replaces it with fish style path
///
/// Will take the first letter of each directory before the contracted path and
/// use that in the path instead. See the following example.
///
/// Absolute Path: `/Users/Bob/Projects/work/a_repo`
/// Contracted Path: `a_repo`
/// With Fish Style: `~/P/w/a_repo`
///
/// Absolute Path: `/some/Path/not/in_a/repo/but_nested`
/// Contracted Path: `in_a/repo/but_nested`
/// With Fish Style: `/s/P/n/in_a/repo/but_nested`
fn to_fish_style(pwd_dir_length: usize, dir_string: &str, truncated_dir_string: &str) -> String {
let replaced_dir_string = dir_string.trim_end_matches(truncated_dir_string);
let components = replaced_dir_string.split('/').collect::<Vec<&str>>();
if components.is_empty() {
return replaced_dir_string.to_string();
}
components
.into_iter()
.map(|word| -> String {
let chars = UnicodeSegmentation::graphemes(word, true).collect::<Vec<&str>>();
match word {
"" => String::new(),
_ if chars.len() <= pwd_dir_length => word.to_string(),
_ if word.starts_with('.') => chars[..=pwd_dir_length].join(""),
_ => chars[..pwd_dir_length].join(""),
}
})
.collect::<Vec<_>>()
.join("/")
}
/// Convert the path separators in `path` to the OS specific path separators.
fn convert_path_sep(path: &str) -> String {
PathBuf::from_slash(path).to_string_lossy().into_owned()
}
/// Get the path before the git repo root by trim the most right repo name.
fn before_root_dir<'a>(path: &'a str, repo: &'a str) -> &'a str {
match path.rsplit_once(repo) {
Some((a, _)) => a,
None => path,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test::ModuleRenderer;
use crate::utils::create_command;
use crate::utils::home_dir;
use nu_ansi_term::Color;
#[cfg(not(target_os = "windows"))]
use std::os::unix::fs::symlink;
#[cfg(target_os = "windows")]
use std::os::windows::fs::symlink_dir as symlink;
use std::path::Path;
use std::{fs, io};
use tempfile::TempDir;
#[test]
fn contract_home_directory() {
let full_path = Path::new("/Users/astronaut/schematics/rocket");
let home = Path::new("/Users/astronaut");
let output = contract_path(full_path, home, "~");
assert_eq!(output, "~/schematics/rocket");
}
#[test]
fn contract_repo_directory() -> io::Result<()> {
let tmp_dir = TempDir::new_in(home_dir().unwrap().as_path())?;
let repo_dir = tmp_dir.path().join("dev").join("rocket-controls");
let src_dir = repo_dir.join("src");
fs::create_dir_all(&src_dir)?;
init_repo(&repo_dir)?;
let src_variations = [src_dir.clone(), dunce::canonicalize(src_dir).unwrap()];
let repo_variations = [repo_dir.clone(), dunce::canonicalize(repo_dir).unwrap()];
for src_dir in &src_variations {
for repo_dir in &repo_variations {
let output = contract_repo_path(src_dir, repo_dir);
assert_eq!(output, Some("rocket-controls/src".to_string()));
}
}
tmp_dir.close()
}
#[test]
#[cfg(windows)]
fn contract_windows_style_home_directory() {
let path_variations = [
r"\\?\C:\Users\astronaut\schematics\rocket",
r"C:\Users\astronaut\schematics\rocket",
];
let home_path_variations = [r"\\?\C:\Users\astronaut", r"C:\Users\astronaut"];
for path in &path_variations {
for home_path in &home_path_variations {
let path = Path::new(path);
let home_path = Path::new(home_path);
let output = contract_path(path, home_path, "~");
assert_eq!(output, "~/schematics/rocket");
}
}
}
#[test]
#[cfg(target_os = "windows")]
fn contract_windows_style_repo_directory() {
let full_path = Path::new("C:\\Users\\astronaut\\dev\\rocket-controls\\src");
let repo_root = Path::new("C:\\Users\\astronaut\\dev\\rocket-controls");
let output = contract_path(full_path, repo_root, "rocket-controls");
assert_eq!(output, "rocket-controls/src");
}
#[test]
#[cfg(target_os = "windows")]
fn contract_windows_style_no_top_level_directory() {
let full_path = Path::new("C:\\Some\\Other\\Path");
let top_level_path = Path::new("C:\\Users\\astronaut");
let output = contract_path(full_path, top_level_path, "~");
assert_eq!(output, "C:/Some/Other/Path");
}
#[test]
#[cfg(target_os = "windows")]
fn contract_windows_style_root_directory() {
let full_path = Path::new("C:\\");
let top_level_path = Path::new("C:\\Users\\astronaut");
let output = contract_path(full_path, top_level_path, "~");
assert_eq!(output, "C:/");
}
#[test]
fn substitute_prefix_and_middle() {
let full_path = "/absolute/path/foo/bar/baz";
let mut substitutions = IndexMap::new();
substitutions.insert("/absolute/path".to_string(), "");
substitutions.insert("/bar/".to_string(), "/");
let output = substitute_path(full_path.to_string(), &substitutions);
assert_eq!(output, "/foo/baz");
}
#[test]
fn fish_style_with_user_home_contracted_path() {
let path = "~/starship/engines/booster/rocket";
let output = to_fish_style(1, path, "engines/booster/rocket");
assert_eq!(output, "~/s/");
}
#[test]
fn fish_style_with_user_home_contracted_path_and_dot_dir() {
let path = "~/.starship/engines/booster/rocket";
let output = to_fish_style(1, path, "engines/booster/rocket");
assert_eq!(output, "~/.s/");
}
#[test]
fn fish_style_with_no_contracted_path() {
// `truncation_length = 2`
let path = "/absolute/Path/not/in_a/repo/but_nested";
let output = to_fish_style(1, path, "repo/but_nested");
assert_eq!(output, "/a/P/n/i/");
}
#[test]
fn fish_style_with_pwd_dir_len_no_contracted_path() {
// `truncation_length = 2`
let path = "/absolute/Path/not/in_a/repo/but_nested";
let output = to_fish_style(2, path, "repo/but_nested");
assert_eq!(output, "/ab/Pa/no/in/");
}
#[test]
fn fish_style_with_duplicate_directories() {
let path = "~/starship/tmp/C++/C++/C++";
let output = to_fish_style(1, path, "C++");
assert_eq!(output, "~/s/t/C/C/");
}
#[test]
fn fish_style_with_unicode() {
let path = "~/starship/tmp/目录/a̐éö̲/目录";
let output = to_fish_style(1, path, "目录");
assert_eq!(output, "~/s/t/目/a̐/");
}
fn init_repo(path: &Path) -> io::Result<()> {
create_command("git")?
.args(["init"])
.current_dir(path)
.output()
.map(|_| ())
}
fn make_known_tempdir(root: &Path) -> io::Result<(TempDir, String)> {
fs::create_dir_all(root)?;
let dir = TempDir::new_in(root)?;
// the .to_string_lossy().to_string() here looks weird but is required
// to convert it from a Cow.
let path = dir
.path()
.file_name()
.unwrap()
.to_string_lossy()
.to_string();
Ok((dir, path))
}
#[cfg(not(target_os = "windows"))]
mod linux {
use super::*;
#[test]
#[ignore]
fn symlinked_subdirectory_git_repo_out_of_tree() -> io::Result<()> {
let tmp_dir = TempDir::new_in(home_dir().unwrap().as_path())?;
let repo_dir = tmp_dir.path().join("above-repo").join("rocket-controls");
let src_dir = repo_dir.join("src/meters/fuel-gauge");
let symlink_dir = tmp_dir.path().join("fuel-gauge");
fs::create_dir_all(&src_dir)?;
init_repo(&repo_dir)?;
symlink(&src_dir, &symlink_dir)?;
let actual = ModuleRenderer::new("directory")
.env("HOME", tmp_dir.path().to_str().unwrap())
.path(symlink_dir)
.collect();
let expected = Some(format!("{} ", Color::Cyan.bold().paint("~/fuel-gauge")));
assert_eq!(expected, actual);
tmp_dir.close()
}
#[test]
#[ignore]
fn git_repo_in_home_directory_truncate_to_repo_true() -> io::Result<()> {
let tmp_dir = TempDir::new_in(home_dir().unwrap().as_path())?;
let dir = tmp_dir.path().join("src/fuel-gauge");
fs::create_dir_all(&dir)?;
init_repo(tmp_dir.path())?;
let actual = ModuleRenderer::new("directory")
.config(toml::toml! {
[directory]
// `truncate_to_repo = true` should attempt to display the truncated path
truncate_to_repo = true
truncation_length = 5
})
.path(dir)
.env("HOME", tmp_dir.path().to_str().unwrap())
.collect();
let expected = Some(format!("{} ", Color::Cyan.bold().paint("~/src/fuel-gauge")));
assert_eq!(expected, actual);
tmp_dir.close()
}
#[test]
#[ignore]
fn directory_in_root() {
let actual = ModuleRenderer::new("directory").path("/etc").collect();
let expected = Some(format!(
"{}{} ",
Color::Cyan.bold().paint("/etc"),
Color::Red.normal().paint("🔒")
));
assert_eq!(expected, actual);
}
}
#[test]
fn home_directory_default_home_symbol() {
let actual = ModuleRenderer::new("directory")
.path(home_dir().unwrap())
.collect();
let expected = Some(format!("{} ", Color::Cyan.bold().paint("~")));
assert_eq!(expected, actual);
}
#[test]
fn home_directory_custom_home_symbol() {
let actual = ModuleRenderer::new("directory")
.path(home_dir().unwrap())
.config(toml::toml! {
[directory]
home_symbol = "🚀"
})
.collect();
let expected = Some(format!(
"{} ",
Color::Cyan.bold().paint(convert_path_sep("🚀"))
));
assert_eq!(expected, actual);
}
#[test]
fn home_directory_custom_home_symbol_subdirectories() {
let actual = ModuleRenderer::new("directory")
.path(home_dir().unwrap().join("path/subpath"))
.config(toml::toml! {
[directory]
home_symbol = "🚀"
})
.collect();
let expected = Some(format!(
"{} ",
Color::Cyan
.bold()
.paint(convert_path_sep("🚀/path/subpath"))
));
assert_eq!(expected, actual);
}
#[test]
fn substituted_truncated_path() {
let actual = ModuleRenderer::new("directory")
.path("/some/long/network/path/workspace/a/b/c/dev")
.config(toml::toml! {
[directory]
truncation_length = 4
[directory.substitutions]
"/some/long/network/path" = "/some/net"
"a/b/c" = "d"
})
.collect();
let expected = Some(format!(
"{} ",
Color::Cyan
.bold()
.paint(convert_path_sep("net/workspace/d/dev"))
));
assert_eq!(expected, actual);
}
#[test]
fn substitution_order() {
let actual = ModuleRenderer::new("directory")
.path("/path/to/sub")
.config(toml::toml! {
[directory.substitutions]
"/path/to/sub" = "/correct/order"
"/to/sub" = "/wrong/order"
})
.collect();
let expected = Some(format!(
"{} ",
Color::Cyan.bold().paint(convert_path_sep("/correct/order"))
));
assert_eq!(expected, actual);
}
#[test]
fn strange_substitution() {
let strange_sub = "/\\/;,!";
let actual = ModuleRenderer::new("directory")
.path("/foo/bar/regular/path")
.config(toml::toml! {
[directory]
truncation_length = 0
fish_style_pwd_dir_length = 2 // Overridden by substitutions
[directory.substitutions]
"regular" = strange_sub
})
.collect();
let expected = Some(format!(
"{} ",
Color::Cyan
.bold()
.paint(convert_path_sep(&format!("/foo/bar/{strange_sub}/path")))
));
assert_eq!(expected, actual);
}
#[test]
fn directory_in_home() -> io::Result<()> {
let (tmp_dir, name) = make_known_tempdir(home_dir().unwrap().as_path())?;
let dir = tmp_dir.path().join("starship");
fs::create_dir_all(&dir)?;
let actual = ModuleRenderer::new("directory").path(dir).collect();
let expected = Some(format!(
"{} ",
Color::Cyan
.bold()
.paint(convert_path_sep(&format!("~/{name}/starship")))
));
assert_eq!(expected, actual);
tmp_dir.close()
}
#[test]
fn truncated_directory_in_home() -> io::Result<()> {
let (tmp_dir, name) = make_known_tempdir(home_dir().unwrap().as_path())?;
let dir = tmp_dir.path().join("engine/schematics");
fs::create_dir_all(&dir)?;
let actual = ModuleRenderer::new("directory").path(dir).collect();
let expected = Some(format!(
"{} ",
Color::Cyan
.bold()
.paint(convert_path_sep(&format!("{name}/engine/schematics")))
));
assert_eq!(expected, actual);
tmp_dir.close()
}
#[test]
fn fish_directory_in_home() -> io::Result<()> {
let (tmp_dir, name) = make_known_tempdir(home_dir().unwrap().as_path())?;
let dir = tmp_dir.path().join("starship/schematics");
fs::create_dir_all(&dir)?;
let actual = ModuleRenderer::new("directory")
.config(toml::toml! {
[directory]
truncation_length = 1
fish_style_pwd_dir_length = 2
})
.path(&dir)
.collect();
let expected = Some(format!(
"{} ",
Color::Cyan.bold().paint(convert_path_sep(&format!(
"~/{}/st/schematics",
name.split_at(3).0
)))
));
assert_eq!(expected, actual);
tmp_dir.close()
}
#[test]
fn root_directory() {
// Note: We have disable the read_only settings here due to false positives when running
// the tests on Windows as a non-admin.
let actual = ModuleRenderer::new("directory")
.config(toml::toml! {
[directory]
read_only = ""
read_only_style = ""
})
.path("/")
.collect();
let expected = Some(format!(
"{} ",
Color::Cyan.bold().paint(convert_path_sep("/"))
));
assert_eq!(expected, actual);
}
#[test]
fn truncated_directory_in_root() -> io::Result<()> {
let (tmp_dir, name) = make_known_tempdir(Path::new("/tmp"))?;
let dir = tmp_dir.path().join("thrusters/rocket");
fs::create_dir_all(&dir)?;
let actual = ModuleRenderer::new("directory").path(dir).collect();
let expected = Some(format!(
"{} ",
Color::Cyan
.bold()
.paint(convert_path_sep(&format!("{name}/thrusters/rocket")))
));
assert_eq!(expected, actual);
tmp_dir.close()
}
#[test]
fn truncated_directory_config_large() -> io::Result<()> {
let (tmp_dir, _) = make_known_tempdir(Path::new("/tmp"))?;
let dir = tmp_dir.path().join("thrusters/rocket");
fs::create_dir_all(&dir)?;
let actual = ModuleRenderer::new("directory")
.config(toml::toml! {
[directory]
truncation_length = 100
})
.path(&dir)
.collect();
let dir_str = dir.to_slash_lossy().to_string();
let expected = Some(format!(
"{} ",
Color::Cyan.bold().paint(convert_path_sep(
&truncate(&dir_str, 100).unwrap_or(dir_str)
))
));
assert_eq!(expected, actual);
tmp_dir.close()
}
#[test]
fn fish_style_directory_config_large() -> io::Result<()> {
let (tmp_dir, _) = make_known_tempdir(Path::new("/tmp"))?;
let dir = tmp_dir.path().join("thrusters/rocket");
fs::create_dir_all(&dir)?;
let actual = ModuleRenderer::new("directory")
.config(toml::toml! {
[directory]
truncation_length = 1
fish_style_pwd_dir_length = 100
})
.path(&dir)
.collect();
let expected = Some(format!(
"{} ",
Color::Cyan.bold().paint(convert_path_sep(&to_fish_style(
100,
&dir.to_slash_lossy(),
""
)))
));
assert_eq!(expected, actual);
tmp_dir.close()
}
#[test]
fn truncated_directory_config_small() -> io::Result<()> {
let (tmp_dir, name) = make_known_tempdir(Path::new("/tmp"))?;
let dir = tmp_dir.path().join("rocket");
fs::create_dir_all(&dir)?;
let actual = ModuleRenderer::new("directory")
.config(toml::toml! {
[directory]
truncation_length = 2
})
.path(dir)
.collect();
let expected = Some(format!(
"{} ",
Color::Cyan
.bold()
.paint(convert_path_sep(&format!("{name}/rocket")))
));
assert_eq!(expected, actual);
tmp_dir.close()
}
#[test]
fn fish_directory_config_small() -> io::Result<()> {
let (tmp_dir, _) = make_known_tempdir(Path::new("/tmp"))?;
let dir = tmp_dir.path().join("thrusters/rocket");
fs::create_dir_all(&dir)?;
let actual = ModuleRenderer::new("directory")
.config(toml::toml! {
[directory]
truncation_length = 2
fish_style_pwd_dir_length = 1
})
.path(&dir)
.collect();
let expected = Some(format!(
"{} ",
Color::Cyan.bold().paint(convert_path_sep(&format!(
"{}/thrusters/rocket",
to_fish_style(1, &dir.to_slash_lossy(), "/thrusters/rocket")
)))
));
assert_eq!(expected, actual);
tmp_dir.close()
}
#[test]
#[ignore]
fn git_repo_root() -> io::Result<()> {
let tmp_dir = TempDir::new()?;
let repo_dir = tmp_dir.path().join("rocket-controls");
fs::create_dir(&repo_dir)?;
init_repo(&repo_dir).unwrap();
let actual = ModuleRenderer::new("directory").path(repo_dir).collect();
let expected = Some(format!(
"{} ",
Color::Cyan
.bold()
.paint(convert_path_sep("rocket-controls"))
));
assert_eq!(expected, actual);
tmp_dir.close()
}
#[test]
#[ignore]
fn directory_in_git_repo() -> io::Result<()> {
let tmp_dir = TempDir::new()?;
let repo_dir = tmp_dir.path().join("rocket-controls");
let dir = repo_dir.join("src");
fs::create_dir_all(&dir)?;
init_repo(&repo_dir).unwrap();
let actual = ModuleRenderer::new("directory").path(dir).collect();
let expected = Some(format!(
"{} ",
Color::Cyan
.bold()
.paint(convert_path_sep("rocket-controls/src"))
));
assert_eq!(expected, actual);
tmp_dir.close()
}
#[test]
#[ignore]
fn truncated_directory_in_git_repo() -> io::Result<()> {
let tmp_dir = TempDir::new()?;
let repo_dir = tmp_dir.path().join("rocket-controls");
let dir = repo_dir.join("src/meters/fuel-gauge");
fs::create_dir_all(&dir)?;
init_repo(&repo_dir).unwrap();
let actual = ModuleRenderer::new("directory").path(dir).collect();
let expected = Some(format!(
"{} ",
Color::Cyan
.bold()
.paint(convert_path_sep("src/meters/fuel-gauge"))
));
assert_eq!(expected, actual);
tmp_dir.close()
}
#[test]
#[ignore]
fn directory_in_git_repo_truncate_to_repo_false() -> io::Result<()> {
let tmp_dir = TempDir::new()?;
let repo_dir = tmp_dir.path().join("above-repo").join("rocket-controls");
let dir = repo_dir.join("src/meters/fuel-gauge");
fs::create_dir_all(&dir)?;
init_repo(&repo_dir).unwrap();
let actual = ModuleRenderer::new("directory")
.config(toml::toml! {
[directory]
// Don't truncate the path at all.
truncation_length = 5
truncate_to_repo = false
})
.path(dir)
.collect();
let expected = Some(format!(
"{} ",
Color::Cyan.bold().paint(convert_path_sep(
"above-repo/rocket-controls/src/meters/fuel-gauge"
))
));
assert_eq!(expected, actual);
tmp_dir.close()
}
#[test]
#[ignore]
fn fish_path_directory_in_git_repo_truncate_to_repo_false() -> io::Result<()> {
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | true |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/battery.rs | src/modules/battery.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::battery::BatteryConfig;
#[cfg(test)]
use mockall::automock;
use starship_battery as battery;
use crate::formatter::StringFormatter;
/// Creates a module for the battery percentage and charging state
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let battery_status = get_battery_status(context)?;
let BatteryStatus { state, percentage } = battery_status;
let mut module = context.new_module("battery");
let config: BatteryConfig = BatteryConfig::try_load(module.config);
// Parse config under `display`.
// Select the style that is most minimally greater than the current battery percentage.
// If no such style exists do not display battery module.
let display_style = config
.display
.iter()
.filter(|display_style| percentage <= display_style.threshold as f32)
.min_by_key(|display_style| display_style.threshold)?;
// Parse the format string and build the module
match StringFormatter::new(config.format) {
Ok(formatter) => {
let formatter = formatter
.map_meta(|variable, _| match variable {
"symbol" => match state {
battery::State::Full => Some(config.full_symbol),
battery::State::Charging => display_style
.charging_symbol
.or(Some(config.charging_symbol)),
battery::State::Discharging => display_style
.discharging_symbol
.or(Some(config.discharging_symbol)),
battery::State::Unknown => Some(config.unknown_symbol),
battery::State::Empty => Some(config.empty_symbol),
},
_ => None,
})
.map_style(|style| match style {
"style" => Some(Ok(display_style.style)),
_ => None,
})
.map(|variable| match variable {
"percentage" => Some(Ok(format!("{}%", percentage.round()))),
_ => None,
});
match formatter.parse(None, Some(context)) {
Ok(format_string) => {
module.set_segments(format_string);
Some(module)
}
Err(e) => {
log::warn!("Cannot parse `battery.format`: {e}");
None
}
}
}
Err(e) => {
log::warn!("Cannot load `battery.format`: {e}");
None
}
}
}
fn get_battery_status(context: &Context) -> Option<BatteryStatus> {
let battery_info = context.battery_info_provider.get_battery_info()?;
if battery_info.energy_full == 0.0 {
None
} else {
let battery = BatteryStatus {
percentage: battery_info.energy / battery_info.energy_full * 100.0,
state: battery_info.state,
};
log::debug!("Battery status: {battery:?}");
Some(battery)
}
}
/// the merge returns Charging if at least one is charging
/// Discharging if at least one is Discharging
/// Full if both are Full or one is Full and the other Unknown
/// Empty if both are Empty or one is Empty and the other Unknown
/// Unknown otherwise
fn merge_battery_states(state1: battery::State, state2: battery::State) -> battery::State {
use battery::State::{Charging, Discharging, Unknown};
if state1 == Charging || state2 == Charging {
Charging
} else if state1 == Discharging || state2 == Discharging {
Discharging
} else if state1 == state2 {
state1
} else if state1 == Unknown {
state2
} else if state2 == Unknown {
state1
} else {
Unknown
}
}
pub struct BatteryInfo {
energy: f32,
energy_full: f32,
state: battery::State,
}
#[derive(Debug)]
struct BatteryStatus {
percentage: f32,
state: battery::State,
}
#[cfg_attr(test, automock)]
pub trait BatteryInfoProvider {
fn get_battery_info(&self) -> Option<BatteryInfo>;
}
pub struct BatteryInfoProviderImpl;
impl BatteryInfoProvider for BatteryInfoProviderImpl {
fn get_battery_info(&self) -> Option<BatteryInfo> {
let battery_manager = battery::Manager::new().ok()?;
let batteries = battery_manager.batteries().ok()?;
Some(
batteries
.filter_map(|battery| match battery {
Ok(battery) => {
log::debug!("Battery found: {battery:?}");
let charge_rate = battery.state_of_charge().value;
let energy_full = battery.energy_full().value;
Some(BatteryInfo {
energy: charge_rate * energy_full,
energy_full,
state: battery.state(),
})
}
Err(e) => {
let level = if cfg!(target_os = "linux") {
log::Level::Info
} else {
log::Level::Warn
};
log::log!(level, "Unable to access battery information:\n{}", &e);
None
}
})
.fold(
BatteryInfo {
energy: 0.0,
energy_full: 0.0,
state: battery::State::Unknown,
},
|mut acc, x| {
acc.energy += x.energy;
acc.energy_full += x.energy_full;
acc.state = merge_battery_states(acc.state, x.state);
acc
},
),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
#[test]
fn no_battery_status() {
let mut mock = MockBatteryInfoProvider::new();
mock.expect_get_battery_info().times(1).returning(|| None);
let actual = ModuleRenderer::new("battery")
.config(toml::toml! {
[[battery.display]]
threshold = 100
style = ""
})
.battery_info_provider(&mock)
.collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn ignores_zero_capacity_battery() {
let mut mock = MockBatteryInfoProvider::new();
mock.expect_get_battery_info().times(1).returning(|| {
Some(BatteryInfo {
energy: 0.0,
energy_full: 0.0,
state: battery::State::Full,
})
});
let actual = ModuleRenderer::new("battery")
.config(toml::toml! {
[[battery.display]]
threshold = 100
style = ""
})
.battery_info_provider(&mock)
.collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn battery_full() {
let mut mock = MockBatteryInfoProvider::new();
mock.expect_get_battery_info().times(1).returning(|| {
Some(BatteryInfo {
energy: 1000.0,
energy_full: 1000.0,
state: battery::State::Full,
})
});
let actual = ModuleRenderer::new("battery")
.config(toml::toml! {
[[battery.display]]
threshold = 100
style = ""
})
.battery_info_provider(&mock)
.collect();
let expected = Some(String::from(" 100% "));
assert_eq!(expected, actual);
}
#[test]
fn battery_charging() {
let mut mock = MockBatteryInfoProvider::new();
mock.expect_get_battery_info().times(1).returning(|| {
Some(BatteryInfo {
energy: 800.0,
energy_full: 1000.0,
state: battery::State::Charging,
})
});
let actual = ModuleRenderer::new("battery")
.config(toml::toml! {
[[battery.display]]
threshold = 90
style = ""
})
.battery_info_provider(&mock)
.collect();
let expected = Some(String::from(" 80% "));
assert_eq!(expected, actual);
}
#[test]
fn battery_discharging() {
let mut mock = MockBatteryInfoProvider::new();
mock.expect_get_battery_info().times(1).returning(|| {
Some(BatteryInfo {
energy: 800.0,
energy_full: 1000.0,
state: battery::State::Discharging,
})
});
let actual = ModuleRenderer::new("battery")
.config(toml::toml! {
[[battery.display]]
threshold = 100
style = ""
})
.battery_info_provider(&mock)
.collect();
let expected = Some(String::from(" 80% "));
assert_eq!(expected, actual);
}
#[test]
fn battery_unknown() {
let mut mock = MockBatteryInfoProvider::new();
mock.expect_get_battery_info().times(1).returning(|| {
Some(BatteryInfo {
energy: 0.0,
energy_full: 1.0,
state: battery::State::Unknown,
})
});
let actual = ModuleRenderer::new("battery")
.config(toml::toml! {
[[battery.display]]
threshold = 100
style = ""
})
.battery_info_provider(&mock)
.collect();
let expected = Some(String::from(" 0% "));
assert_eq!(expected, actual);
}
#[test]
fn battery_empty() {
let mut mock = MockBatteryInfoProvider::new();
mock.expect_get_battery_info().times(1).returning(|| {
Some(BatteryInfo {
energy: 0.0,
energy_full: 1000.0,
state: battery::State::Empty,
})
});
let actual = ModuleRenderer::new("battery")
.config(toml::toml! {
[[battery.display]]
threshold = 100
style = ""
})
.battery_info_provider(&mock)
.collect();
let expected = Some(String::from(" 0% "));
assert_eq!(expected, actual);
}
#[test]
fn battery_hidden_when_percentage_above_threshold() {
let mut mock = MockBatteryInfoProvider::new();
mock.expect_get_battery_info().times(1).returning(|| {
Some(BatteryInfo {
energy: 600.0,
energy_full: 1000.0,
state: battery::State::Full,
})
});
let actual = ModuleRenderer::new("battery")
.config(toml::toml! {
[[battery.display]]
threshold = 50
style = ""
})
.battery_info_provider(&mock)
.collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn battery_uses_style() {
let mut mock = MockBatteryInfoProvider::new();
mock.expect_get_battery_info().times(1).returning(|| {
Some(BatteryInfo {
energy: 400.0,
energy_full: 1000.0,
state: battery::State::Discharging,
})
});
let actual = ModuleRenderer::new("battery")
.config(toml::toml! {
[[battery.display]]
threshold = 50
style = "bold red"
})
.battery_info_provider(&mock)
.collect();
let expected = Some(format!("{} ", Color::Red.bold().paint(" 40%")));
assert_eq!(expected, actual);
}
#[test]
fn battery_displayed_precision() {
let mut mock = MockBatteryInfoProvider::new();
mock.expect_get_battery_info().times(1).returning(|| {
Some(BatteryInfo {
energy: 129.87654,
energy_full: 1000.0,
state: battery::State::Discharging,
})
});
let actual = ModuleRenderer::new("battery")
.config(toml::toml! {
[[battery.display]]
threshold = 100
style = ""
})
.battery_info_provider(&mock)
.collect();
let expected = Some(String::from(" 13% "));
assert_eq!(expected, actual);
}
#[test]
fn battery_expected_style() {
let mut mock = MockBatteryInfoProvider::new();
mock.expect_get_battery_info().times(2).returning(|| {
Some(BatteryInfo {
energy: 50.0,
energy_full: 100.0,
state: battery::State::Discharging,
})
});
// Larger threshold first
let actual = ModuleRenderer::new("battery")
.config(toml::toml! {
[[battery.display]]
threshold = 100
style = "red"
[[battery.display]]
threshold = 60
style = "green bold"
})
.battery_info_provider(&mock)
.collect();
let expected = Some(format!("{} ", Color::Green.bold().paint(" 50%")));
assert_eq!(expected, actual);
// Smaller threshold first
let actual = ModuleRenderer::new("battery")
.config(toml::toml! {
[[battery.display]]
threshold = 60
style = "green bold"
[[battery.display]]
threshold = 100
style = "red"
})
.battery_info_provider(&mock)
.collect();
let expected = Some(format!("{} ", Color::Green.bold().paint(" 50%")));
assert_eq!(expected, actual);
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/php.rs | src/modules/php.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::php::PhpConfig;
use crate::formatter::StringFormatter;
use crate::formatter::VersionFormatter;
/// Creates a module with the current PHP version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("php");
let config: PhpConfig = PhpConfig::try_load(module.config);
let is_php_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_folders(&config.detect_folders)
.set_extensions(&config.detect_extensions)
.is_match();
if !is_php_project {
return None;
}
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|variable, _| match variable {
"symbol" => Some(config.symbol),
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map(|variable| match variable {
"version" => {
let php_version = context.exec_cmd(
"php",
&[
"-nr",
"echo PHP_MAJOR_VERSION.\".\".PHP_MINOR_VERSION.\".\".PHP_RELEASE_VERSION;",
],
)?.stdout;
VersionFormatter::format_module_version(module.get_name(), &php_version, config.version_format).map(Ok)
}
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `php`:\n{error}");
return None;
}
});
Some(module)
}
#[cfg(test)]
mod tests {
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
use std::fs::File;
use std::io;
#[test]
fn folder_without_php_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("php").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_composer_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("composer.json"))?.sync_all()?;
let actual = ModuleRenderer::new("php").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Fixed(147).bold().paint("🐘 v7.3.8 ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_php_version() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join(".php-version"))?.sync_all()?;
let actual = ModuleRenderer::new("php").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Fixed(147).bold().paint("🐘 v7.3.8 ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_php_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("any.php"))?.sync_all()?;
let actual = ModuleRenderer::new("php").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Fixed(147).bold().paint("🐘 v7.3.8 ")
));
assert_eq!(expected, actual);
dir.close()
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/cobol.rs | src/modules/cobol.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::cobol::CobolConfig;
use crate::formatter::StringFormatter;
use crate::formatter::VersionFormatter;
/// Creates a module with the current COBOL version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("cobol");
let config = CobolConfig::try_load(module.config);
let is_cobol_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_cobol_project {
return None;
}
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,
})
.map(|variable| match variable {
"version" => {
let cobol_version =
get_cobol_version(&context.exec_cmd("cobc", &["-version"])?.stdout)?;
VersionFormatter::format_module_version(
module.get_name(),
&cobol_version,
config.version_format,
)
.map(Ok)
}
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `cobol`:\n{error}");
return None;
}
});
Some(module)
}
fn get_cobol_version(cobol_stdout: &str) -> Option<String> {
// cobol output looks like this:
// cobc (GnuCOBOL) 3.1.2.0
// ...
Some(
cobol_stdout
// split into ["cobc", "(GNUCOBOL)", "3.1.2.0"...]
.split_whitespace()
// return "3.1.2.0"
.nth(2)?
.to_string(),
)
}
#[cfg(test)]
mod tests {
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
use std::fs::File;
use std::io;
#[test]
fn folder_without_cobol_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("cobol").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_lowercase_cob_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("main.cob"))?.sync_all()?;
let actual = ModuleRenderer::new("cobol").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Blue.bold().paint("⚙️ v3.1.2.0 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_lowercase_cbl_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("main.cbl"))?.sync_all()?;
let actual = ModuleRenderer::new("cobol").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Blue.bold().paint("⚙️ v3.1.2.0 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_capital_cob_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("MAIN.COB"))?.sync_all()?;
let actual = ModuleRenderer::new("cobol").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Blue.bold().paint("⚙️ v3.1.2.0 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_capital_cbl_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("MAIN.CBL"))?.sync_all()?;
let actual = ModuleRenderer::new("cobol").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Blue.bold().paint("⚙️ v3.1.2.0 ")));
assert_eq!(expected, actual);
dir.close()
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/meson.rs | src/modules/meson.rs | use super::{Context, Module, ModuleConfig};
use super::utils::truncate::truncate_text;
use crate::configs::meson::MesonConfig;
use crate::formatter::StringFormatter;
/// Creates a module with the current Meson dev environment
///
/// Will display the Meson environment if `$MESON_DEVENV` and `MESON_PROJECT_NAME` are set.
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let meson_env = context.get_env("MESON_DEVENV")?;
let project_env = context.get_env("MESON_PROJECT_NAME")?;
if meson_env != "1" || project_env.trim().is_empty() {
return None;
}
let mut module = context.new_module("meson");
let config: MesonConfig = MesonConfig::try_load(module.config);
let truncated_text = truncate_text(
&project_env,
config.truncation_length as usize,
config.truncation_symbol,
);
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|variable, _| match variable {
"symbol" => Some(config.symbol),
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map(|variable| match variable {
"project" => Some(Ok(&truncated_text)),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `meson`:\n{error}");
return None;
}
});
Some(module)
}
#[cfg(test)]
mod tests {
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
#[test]
fn not_in_env() {
let actual = ModuleRenderer::new("meson").collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn env_set() {
let actual = ModuleRenderer::new("meson")
.env("MESON_DEVENV", "1")
.env("MESON_PROJECT_NAME", "starship")
.collect();
let expected = Some(format!("via {} ", Color::Blue.bold().paint("⬢ starship")));
assert_eq!(expected, actual);
}
#[test]
fn env_invalid_devenv() {
let actual = ModuleRenderer::new("meson")
.env("MESON_DEVENV", "0")
.env("MESON_PROJECT_NAME", "starship")
.collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn env_invalid_project_name() {
let actual = ModuleRenderer::new("meson")
.env("MESON_DEVENV", "1")
.env("MESON_PROJECT_NAME", " ")
.collect();
let expected = None;
assert_eq!(expected, actual);
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/custom.rs | src/modules/custom.rs | use std::env;
use std::fmt::{self, Debug};
use std::io::Write;
use std::path::Path;
use std::process::{Command, Stdio};
use std::time::Duration;
use process_control::{ChildExt, Control, Output};
use super::{Context, Module, ModuleConfig};
use crate::{
config::Either, configs::custom::CustomConfig, formatter::StringFormatter,
utils::create_command,
};
/// Creates a custom module with some configuration
///
/// The relevant TOML config will set the files, extensions, and directories needed
/// for the module to be displayed. If none of them match, and optional "when"
/// command can be run -- if its result is 0, the module will be shown.
///
/// Finally, the content of the module itself is also set by a command.
pub fn module<'a>(name: &str, context: &'a Context) -> Option<Module<'a>> {
let toml_config = get_config(name, context)?;
let config = CustomConfig::load(toml_config);
if config.disabled {
return None;
}
if let Some(os) = config.os
&& os != env::consts::OS
&& !(os == "unix" && cfg!(unix))
{
return None;
}
if config.require_repo && context.get_repo().is_err() {
return None;
}
// Note: Forward config if `Module` ends up needing `config`
let mut module = Module::new(format!("custom.{name}"), config.description, None);
let mut is_match = context
.try_begin_scan()?
.set_extensions(&config.detect_extensions)
.set_files(&config.detect_files)
.set_folders(&config.detect_folders)
.is_match();
if !is_match {
is_match = match config.when {
Either::First(b) => b,
Either::Second(s) => exec_when(s, &config, context),
};
if !is_match {
return None;
}
}
let variables_closure = |variable: &str| match variable {
"output" => {
let output = exec_command(config.command, context, &config)?;
let trimmed = output.trim();
if trimmed.is_empty() {
None
} else {
Some(Ok(trimmed.to_string()))
}
}
_ => None,
};
let parsed = StringFormatter::new(config.format).and_then(|mut formatter| {
formatter = formatter
.map_meta(|var, _| match var {
"symbol" => Some(config.symbol),
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
});
if config.unsafe_no_escape {
formatter = formatter.map_no_escaping(variables_closure)
} else {
formatter = formatter.map(variables_closure)
}
formatter.parse(None, Some(context))
});
match parsed {
Ok(segments) => module.set_segments(segments),
Err(error) => {
log::warn!("Error in module `custom.{name}`:\n{error}");
}
};
Some(module)
}
/// Gets the TOML config for the custom module, handling the case where the module is not defined
fn get_config<'a>(module_name: &str, context: &'a Context<'a>) -> Option<&'a toml::Value> {
struct DebugCustomModules<'tmp>(&'tmp toml::value::Table);
impl Debug for DebugCustomModules<'_> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_list().entries(self.0.keys()).finish()
}
}
let config = context.config.get_custom_module_config(module_name);
if config.is_some() {
return config;
} else if let Some(modules) = context.config.get_custom_modules() {
log::debug!(
"top level format contains custom module {module_name:?}, but no configuration was provided. Configuration for the following modules were provided: {:?}",
DebugCustomModules(modules),
);
} else {
log::debug!(
"top level format contains custom module {module_name:?}, but no configuration was provided.",
);
};
None
}
/// Return the invoking shell, using `shell` and fallbacking in order to `STARSHIP_SHELL` and "sh"/"cmd"
fn get_shell<'a, 'b>(
shell_args: &'b [&'a str],
context: &Context,
) -> (std::borrow::Cow<'a, str>, &'b [&'a str]) {
if !shell_args.is_empty() {
(shell_args[0].into(), &shell_args[1..])
} else if let Some(env_shell) = context.get_env("STARSHIP_SHELL") {
(env_shell.into(), &[] as &[&str])
} else if cfg!(windows) {
// `/C` is added by `handle_shell`
("cmd".into(), &[] as &[&str])
} else {
("sh".into(), &[] as &[&str])
}
}
/// Attempt to run the given command in a shell by passing it as either `stdin` or an argument to `get_shell()`,
/// depending on the configuration or by invoking a platform-specific fallback shell if `shell` is empty.
fn shell_command(cmd: &str, config: &CustomConfig, context: &Context) -> Option<Output> {
let (shell, shell_args) = get_shell(config.shell.0.as_ref(), context);
let mut use_stdin = config.use_stdin;
let mut command = match create_command(shell.as_ref()) {
Ok(command) => command,
// Don't attempt to use fallback shell if the user specified a shell
Err(error) if !shell_args.is_empty() => {
log::debug!(
"Error creating command with STARSHIP_SHELL, falling back to fallback shell: {error}"
);
// Skip `handle_shell` and just set the shell and command
use_stdin = Some(!cfg!(windows));
if cfg!(windows) {
let mut c = create_command("cmd").ok()?;
c.arg("/C");
c
} else {
let mut c = create_command("/usr/bin/env").ok()?;
c.arg("sh");
c
}
}
_ => return None,
};
command
.current_dir(&context.current_dir)
.args(shell_args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let use_stdin = use_stdin.unwrap_or_else(|| handle_shell(&mut command, &shell, shell_args));
if !use_stdin {
command.arg(cmd);
}
let mut child = match command.spawn() {
Ok(child) => child,
Err(error) => {
log::debug!(
"Failed to run command with given shell or STARSHIP_SHELL env variable:: {error}"
);
return None;
}
};
if use_stdin {
child.stdin.as_mut()?.write_all(cmd.as_bytes()).ok()?;
}
let mut output = child.controlled_with_output();
if !config.ignore_timeout {
output = output
.time_limit(Duration::from_millis(context.root_config.command_timeout))
.terminate_for_timeout()
}
match output.wait().ok()? {
None => {
log::warn!("Executing custom command {cmd:?} timed out.");
log::warn!(
"You can set command_timeout in your config to a higher value or set ignore_timeout to true for this module to allow longer-running commands to keep executing."
);
None
}
Some(status) => Some(status),
}
}
/// Execute the given command capturing all output, and return whether it return 0
fn exec_when(cmd: &str, config: &CustomConfig, context: &Context) -> bool {
log::trace!("Running '{cmd}'");
if let Some(output) = shell_command(cmd, config, context) {
if !output.status.success() {
log::trace!("non-zero exit code '{:?}'", output.status.code());
log::trace!(
"stdout: {}",
std::str::from_utf8(&output.stdout).unwrap_or("<invalid utf8>")
);
log::trace!(
"stderr: {}",
std::str::from_utf8(&output.stderr).unwrap_or("<invalid utf8>")
);
}
output.status.success()
} else {
log::debug!("Cannot start command");
false
}
}
/// Execute the given command, returning its output on success
fn exec_command(cmd: &str, context: &Context, config: &CustomConfig) -> Option<String> {
log::trace!("Running '{cmd}'");
#[cfg(test)]
if cmd == "__starship_to_be_escaped" {
return Some("`to_be_escaped`".to_string());
}
if let Some(output) = shell_command(cmd, config, context) {
if !output.status.success() {
log::trace!("Non-zero exit code '{:?}'", output.status.code());
log::trace!(
"stdout: {}",
std::str::from_utf8(&output.stdout).unwrap_or("<invalid utf8>")
);
log::trace!(
"stderr: {}",
std::str::from_utf8(&output.stderr).unwrap_or("<invalid utf8>")
);
return None;
}
Some(String::from_utf8_lossy(&output.stdout).into())
} else {
None
}
}
/// If the specified shell refers to `PowerShell`, adds the arguments "-Command -" to the
/// given command.
/// Returns `false` if the shell shell expects scripts as arguments, `true` if as `stdin`.
fn handle_shell(command: &mut Command, shell: &str, shell_args: &[&str]) -> bool {
let shell_exe = Path::new(shell).file_stem();
let no_args = shell_args.is_empty();
match shell_exe.and_then(std::ffi::OsStr::to_str) {
Some("pwsh" | "powershell") => {
if no_args {
command.arg("-NoProfile").arg("-Command").arg("-");
}
true
}
Some("cmd") => {
if no_args {
command.arg("/C");
}
false
}
Some("nu") => {
if no_args {
command.arg("-c");
}
false
}
_ => true,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::context::Shell;
use crate::test::{FixtureProvider, ModuleRenderer, fixture_repo};
use nu_ansi_term::Color;
use std::fs::File;
use std::io;
#[cfg(not(windows))]
const SHELL: &[&str] = &["/bin/sh"];
#[cfg(windows)]
const SHELL: &[&str] = &["cmd"];
#[cfg(not(windows))]
const FAILING_COMMAND: &str = "false";
#[cfg(windows)]
const FAILING_COMMAND: &str = "color 00";
const UNKNOWN_COMMAND: &str = "ydelsyiedsieudleylse dyesdesl";
fn render_cmd(cmd: &str) -> io::Result<Option<String>> {
let dir = tempfile::tempdir()?;
let cmd = cmd.to_owned();
let shell = SHELL
.iter()
.map(std::borrow::ToOwned::to_owned)
.collect::<Vec<_>>();
let out = ModuleRenderer::new("custom.test")
.path(dir.path())
.config(toml::toml! {
[custom.test]
format = "$output"
command = cmd
shell = shell
when = true
ignore_timeout = true
})
.collect();
dir.close()?;
Ok(out)
}
fn render_when(cmd: &str) -> io::Result<bool> {
let dir = tempfile::tempdir()?;
let cmd = cmd.to_owned();
let shell = SHELL
.iter()
.map(std::borrow::ToOwned::to_owned)
.collect::<Vec<_>>();
let out = ModuleRenderer::new("custom.test")
.path(dir.path())
.config(toml::toml! {
[custom.test]
format = "test"
when = cmd
shell = shell
ignore_timeout = true
})
.collect()
.is_some();
dir.close()?;
Ok(out)
}
#[test]
fn when_returns_right_value() -> io::Result<()> {
assert!(render_cmd("echo hello")?.is_some());
assert!(render_cmd(FAILING_COMMAND)?.is_none());
Ok(())
}
#[test]
fn when_returns_false_if_invalid_command() -> io::Result<()> {
assert!(!render_when(UNKNOWN_COMMAND)?);
Ok(())
}
#[test]
#[cfg(not(windows))]
fn command_returns_right_string() -> io::Result<()> {
assert_eq!(render_cmd("echo hello")?, Some("hello".into()));
assert_eq!(render_cmd("echo 강남스타일")?, Some("강남스타일".into()));
Ok(())
}
#[test]
#[cfg(windows)]
fn command_returns_right_string() -> io::Result<()> {
assert_eq!(render_cmd("echo hello")?, Some("hello".into()));
assert_eq!(render_cmd("echo 강남스타일")?, Some("강남스타일".into()));
Ok(())
}
#[test]
#[cfg(not(windows))]
fn command_ignores_stderr() -> io::Result<()> {
assert_eq!(render_cmd("echo foo 1>&2; echo bar")?, Some("bar".into()));
assert_eq!(render_cmd("echo foo; echo bar 1>&2")?, Some("foo".into()));
Ok(())
}
#[test]
#[cfg(windows)]
fn command_ignores_stderr() -> io::Result<()> {
assert_eq!(render_cmd("echo foo 1>&2 & echo bar")?, Some("bar".into()));
assert_eq!(render_cmd("echo foo& echo bar 1>&2")?, Some("foo".into()));
Ok(())
}
#[test]
fn command_can_fail() -> io::Result<()> {
assert_eq!(render_cmd(FAILING_COMMAND)?, None);
assert_eq!(render_cmd(UNKNOWN_COMMAND)?, None);
Ok(())
}
#[test]
fn cwd_command() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let mut f = File::create(dir.path().join("a.txt"))?;
write!(f, "hello")?;
f.sync_all()?;
let cat = if cfg!(windows) { "type" } else { "cat" };
let cmd = format!("{cat} a.txt");
let actual = ModuleRenderer::new("custom.test")
.path(dir.path())
.config(toml::toml! {
[custom.test]
command = cmd
when = true
ignore_timeout = true
})
.collect();
let expected = Some(format!("{}", Color::Green.bold().paint("hello ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn cwd_when() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("a.txt"))?.sync_all()?;
let cat = if cfg!(windows) { "type" } else { "cat" };
let cmd = format!("{cat} a.txt");
let actual = ModuleRenderer::new("custom.test")
.path(dir.path())
.config(toml::toml! {
[custom.test]
format = "test"
when = cmd
ignore_timeout = true
})
.collect();
let expected = Some("test".to_owned());
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn use_stdin_false() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let shell = if cfg!(windows) {
vec![
"powershell".to_owned(),
"-NoProfile".to_owned(),
"-Command".to_owned(),
]
} else {
vec!["sh".to_owned(), "-c".to_owned()]
};
// `use_stdin = false` doesn't like Korean on Windows
let actual = ModuleRenderer::new("custom.test")
.path(dir.path())
.config(toml::toml! {
[custom.test]
command = "echo test"
when = true
use_stdin = false
shell = shell
ignore_timeout = true
})
.collect();
let expected = Some(format!("{}", Color::Green.bold().paint("test ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn use_stdin_true() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let shell = if cfg!(windows) {
vec![
"powershell".to_owned(),
"-NoProfile".to_owned(),
"-Command".to_owned(),
"-".to_owned(),
]
} else {
vec!["sh".to_owned()]
};
let actual = ModuleRenderer::new("custom.test")
.path(dir.path())
.config(toml::toml! {
[custom.test]
command = "echo 강남스타일"
when = true
use_stdin = true
ignore_timeout = true
shell = shell
})
.collect();
let expected = Some(format!("{}", Color::Green.bold().paint("강남스타일 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
#[cfg(not(windows))]
fn when_true_with_string() -> std::io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("custom.test")
.path(dir.path())
.config(toml::toml! {
[custom.test]
format = "test"
shell = ["sh"]
when = "true"
ignore_timeout = true
})
.collect();
let expected = Some("test".to_string());
assert_eq!(expected, actual);
dir.close()
}
#[test]
#[cfg(not(windows))]
fn when_false_with_string() -> std::io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("custom.test")
.path(dir.path())
.config(toml::toml! {
[custom.test]
format = "test"
shell = ["sh"]
when = "false"
ignore_timeout = true
})
.collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn when_true_with_bool() -> std::io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("custom.test")
.path(dir.path())
.config(toml::toml! {
[custom.test]
format = "test"
when = true
})
.collect();
let expected = Some("test".to_string());
assert_eq!(expected, actual);
dir.close()
}
#[test]
#[cfg(not(windows))]
fn when_false_with_bool() -> std::io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("custom.test")
.path(dir.path())
.config(toml::toml! {
[custom.test]
format = "test"
when = false
})
.collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn timeout_short_cmd() -> std::io::Result<()> {
let dir = tempfile::tempdir()?;
let shell = if cfg!(windows) {
"powershell".to_owned()
} else {
"sh".to_owned()
};
let when = if cfg!(windows) {
"$true".to_owned()
} else {
"true".to_owned()
};
// Use a long timeout to ensure that the test doesn't fail
let actual = ModuleRenderer::new("custom.test")
.path(dir.path())
.config(toml::toml! {
command_timeout = 100_000
[custom.test]
format = "test"
when = when
shell = shell
ignore_timeout = false
})
.collect();
let expected = Some("test".to_owned());
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn timeout_cmd() -> std::io::Result<()> {
let dir = tempfile::tempdir()?;
let shell = if cfg!(windows) {
"powershell".to_owned()
} else {
"sh".to_owned()
};
// Use a long timeout to ensure that the test doesn't fail
let actual = ModuleRenderer::new("custom.test")
.path(dir.path())
.config(toml::toml! {
[custom.test]
format = "test"
when = "sleep 3"
shell = shell
ignore_timeout = false
})
.collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn config_aliases_work() -> std::io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("a.txt"))?;
std::fs::create_dir(dir.path().join("dir"))?;
let actual = ModuleRenderer::new("custom.test")
.path(dir.path())
.config(toml::toml! {
[custom.test]
format = "test"
files = ["a.txt"]
})
.collect();
let expected = Some("test".to_string());
assert_eq!(expected, actual);
let actual = ModuleRenderer::new("custom.test")
.path(dir.path())
.config(toml::toml! {
[custom.test]
format = "test"
extensions = ["txt"]
})
.collect();
let expected = Some("test".to_string());
assert_eq!(expected, actual);
let actual = ModuleRenderer::new("custom.test")
.path(dir.path())
.config(toml::toml! {
[custom.test]
format = "test"
directories = ["dir"]
})
.collect();
let expected = Some("test".to_string());
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn disabled() {
let actual = ModuleRenderer::new("custom.test")
.config(toml::toml! {
[custom.test]
disabled = true
when = true
format = "test"
})
.collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn test_render_require_repo_not_in() -> io::Result<()> {
let repo_dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("custom.test")
.path(repo_dir.path())
.config(toml::toml! {
[custom.test]
when = true
require_repo = true
format = "test"
})
.collect();
let expected = None;
assert_eq!(expected, actual);
repo_dir.close()
}
#[test]
fn test_render_require_repo_in() -> io::Result<()> {
let repo_dir = fixture_repo(FixtureProvider::Git)?;
let actual = ModuleRenderer::new("custom.test")
.path(repo_dir.path())
.config(toml::toml! {
[custom.test]
when = true
require_repo = true
format = "test"
})
.collect();
let expected = Some("test".to_string());
assert_eq!(expected, actual);
repo_dir.close()
}
#[test]
fn output_is_escaped() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("custom.test")
.path(dir.path())
.config(toml::toml! {
[custom.test]
format = "$output"
command = "__starship_to_be_escaped"
when = true
ignore_timeout = true
})
.shell(Shell::Bash)
.collect();
let expected = Some("\\`to_be_escaped\\`".to_string());
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn unsafe_no_escape() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("custom.test")
.path(dir.path())
.config(toml::toml! {
[custom.test]
format = "$output"
command = "__starship_to_be_escaped"
when = true
ignore_timeout = true
unsafe_no_escape = true
})
.shell(Shell::Bash)
.collect();
let expected = Some("`to_be_escaped`".to_string());
assert_eq!(expected, actual);
dir.close()
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/utils/path.rs | src/modules/utils/path.rs | use std::path::Path;
pub trait PathExt {
/// Compare this path with another path, ignoring
/// the differences between Verbatim and Non-Verbatim paths.
fn normalised_equals(&self, other: &Path) -> bool;
/// Determine if this path starts wit with another path fragment, ignoring
/// the differences between Verbatim and Non-Verbatim paths.
fn normalised_starts_with(&self, other: &Path) -> bool;
/// Strips the path Prefix component from the Path, if there is one
/// E.g. `\\?\path\foo` => `\foo`
/// E.g. `\\?\C:\foo` => `\foo`
/// E.g. `\\?\UNC\server\share\foo` => `\foo`
/// E.g. `/foo/bar` => `/foo/bar`
fn without_prefix(&self) -> &Path;
}
#[cfg(windows)]
mod normalize {
use std::ffi::OsStr;
use std::path::{Component, Path, Prefix};
// allow because this mirrors std
#[allow(clippy::upper_case_acronyms)]
#[derive(Debug, PartialEq, Eq)]
pub enum NormalizedPrefix<'a> {
// No prefix, e.g. `\cat_pics` or `/cat_pics`
None,
/// Simple verbatim prefix, e.g. `\\?\cat_pics`.
Verbatim(&'a OsStr),
/// Device namespace prefix, e.g. `\\.\COM42`.
DeviceNS(&'a OsStr),
/// Prefix using Windows' _**U**niform **N**aming **C**onvention_, e.g. `\\server\share` or `\\?\UNC\server\share`
UNC(&'a OsStr, &'a OsStr),
/// Windows disk/drive prefix e.g. `C:` or `\\?\C:`
Disk(u8),
}
/// Normalise Verbatim and Non-Verbatim path prefixes into a comparable structure.
/// NOTE: "Verbatim" paths are the rust std library's name for Windows extended-path prefixed paths.
#[cfg(windows)]
fn normalize_prefix(prefix: Prefix) -> NormalizedPrefix {
match prefix {
Prefix::Verbatim(segment) => NormalizedPrefix::Verbatim(segment),
Prefix::VerbatimUNC(server, share) => NormalizedPrefix::UNC(server, share),
Prefix::VerbatimDisk(disk) => NormalizedPrefix::Disk(disk),
Prefix::DeviceNS(device) => NormalizedPrefix::DeviceNS(device),
Prefix::UNC(server, share) => NormalizedPrefix::UNC(server, share),
Prefix::Disk(disk) => NormalizedPrefix::Disk(disk),
}
}
#[cfg(windows)]
pub fn normalize_path(path: &Path) -> (NormalizedPrefix<'_>, &Path) {
let mut components = path.components();
if let Some(Component::Prefix(prefix)) = components.next() {
return (normalize_prefix(prefix.kind()), components.as_path());
}
(NormalizedPrefix::None, path)
}
}
#[cfg(windows)]
impl PathExt for Path {
fn normalised_starts_with(&self, other: &Path) -> bool {
// Do a structured comparison of two paths (normalising differences between path prefixes)
let (a_prefix, a_path) = normalize::normalize_path(self);
let (b_prefix, b_path) = normalize::normalize_path(other);
a_prefix == b_prefix && a_path.starts_with(b_path)
}
fn normalised_equals(&self, other: &Path) -> bool {
// Do a structured comparison of two paths (normalising differences between path prefixes)
let (a_prefix, a_path) = normalize::normalize_path(self);
let (b_prefix, b_path) = normalize::normalize_path(other);
a_prefix == b_prefix && a_path == b_path
}
fn without_prefix(&self) -> &Path {
let (_, path) = normalize::normalize_path(self);
path
}
}
// NOTE: Windows path prefixes are only parsed on Windows.
// On other platforms, we can fall back to the non-normalized versions of these routines.
#[cfg(not(windows))]
impl PathExt for Path {
#[inline]
fn normalised_starts_with(&self, other: &Path) -> bool {
self.starts_with(other)
}
#[inline]
fn normalised_equals(&self, other: &Path) -> bool {
self == other
}
#[inline]
fn without_prefix(&self) -> &Path {
self
}
}
#[cfg(test)]
#[cfg(windows)]
mod windows {
use super::*;
#[test]
fn normalised_equals() {
fn test_equals(a: &Path, b: &Path) {
assert!(a.normalised_equals(b));
assert!(b.normalised_equals(a));
}
// UNC paths
let verbatim_unc = Path::new(r"\\?\UNC\server\share\sub\path");
let unc = Path::new(r"\\server\share\sub\path");
test_equals(verbatim_unc, verbatim_unc);
test_equals(verbatim_unc, unc);
test_equals(unc, unc);
test_equals(unc, verbatim_unc);
// Disk paths
let verbatim_disk = Path::new(r"\\?\C:\test\path");
let disk = Path::new(r"C:\test\path");
test_equals(verbatim_disk, verbatim_disk);
test_equals(verbatim_disk, disk);
test_equals(disk, disk);
test_equals(disk, verbatim_disk);
// Other paths
let verbatim = Path::new(r"\\?\cat_pics");
let no_prefix = Path::new(r"\cat_pics");
let device_ns = Path::new(r"\\.\COM42");
test_equals(verbatim, verbatim);
test_equals(no_prefix, no_prefix);
test_equals(device_ns, device_ns);
}
#[test]
fn normalised_equals_differing_prefixes() {
fn test_not_equals(a: &Path, b: &Path) {
assert!(!a.normalised_equals(b));
assert!(!b.normalised_equals(a));
}
let verbatim_unc = Path::new(r"\\?\UNC\server\share\sub\path");
let unc = Path::new(r"\\server\share\sub\path");
let verbatim_disk = Path::new(r"\\?\C:\test\path");
let disk = Path::new(r"C:\test\path");
let verbatim = Path::new(r"\\?\cat_pics");
let no_prefix = Path::new(r"\cat_pics");
let device_ns = Path::new(r"\\.\COM42");
test_not_equals(verbatim_unc, verbatim_disk);
test_not_equals(unc, disk);
test_not_equals(disk, device_ns);
test_not_equals(device_ns, verbatim_disk);
test_not_equals(no_prefix, unc);
test_not_equals(no_prefix, verbatim);
}
#[test]
fn normalised_starts_with() {
fn test_starts_with(a: &Path, b: &Path) {
assert!(a.normalised_starts_with(b));
assert!(!b.normalised_starts_with(a));
}
// UNC paths
let verbatim_unc_a = Path::new(r"\\?\UNC\server\share\a\b\c\d");
let verbatim_unc_b = Path::new(r"\\?\UNC\server\share\a\b");
let unc_a = Path::new(r"\\server\share\a\b\c\d");
let unc_b = Path::new(r"\\server\share\a\b");
test_starts_with(verbatim_unc_a, verbatim_unc_b);
test_starts_with(unc_a, unc_b);
test_starts_with(verbatim_unc_a, unc_b);
test_starts_with(unc_a, verbatim_unc_b);
// Disk paths
let verbatim_disk_a = Path::new(r"\\?\C:\a\b\c\d");
let verbatim_disk_b = Path::new(r"\\?\C:\a\b");
let disk_a = Path::new(r"C:\a\b\c\d");
let disk_b = Path::new(r"C:\a\b");
test_starts_with(verbatim_disk_a, verbatim_disk_b);
test_starts_with(disk_a, disk_b);
test_starts_with(disk_a, verbatim_disk_b);
test_starts_with(verbatim_disk_a, disk_b);
// Other paths
let verbatim_a = Path::new(r"\\?\cat_pics\a\b\c\d");
let verbatim_b = Path::new(r"\\?\cat_pics\a\b");
let device_ns_a = Path::new(r"\\.\COM43\a\b\c\d");
let device_ns_b = Path::new(r"\\.\COM43\a\b");
let no_prefix_a = Path::new(r"\a\b\c\d");
let no_prefix_b = Path::new(r"\a\b");
test_starts_with(verbatim_a, verbatim_b);
test_starts_with(device_ns_a, device_ns_b);
test_starts_with(no_prefix_a, no_prefix_b);
}
#[test]
fn normalised_starts_with_differing_prefixes() {
fn test_not_starts_with(a: &Path, b: &Path) {
assert!(!a.normalised_starts_with(b));
assert!(!b.normalised_starts_with(a));
}
let verbatim_unc = Path::new(r"\\?\UNC\server\share\a\b\c\d");
let unc = Path::new(r"\\server\share\a\b\c\d");
let verbatim_disk = Path::new(r"\\?\C:\a\b\c\d");
let disk = Path::new(r"C:\a\b\c\d");
let verbatim = Path::new(r"\\?\cat_pics\a\b\c\d");
let device_ns = Path::new(r"\\.\COM43\a\b\c\d");
let no_prefix = Path::new(r"\a\b\c\d");
test_not_starts_with(verbatim_unc, device_ns);
test_not_starts_with(unc, device_ns);
test_not_starts_with(verbatim_disk, verbatim);
test_not_starts_with(disk, verbatim);
test_not_starts_with(disk, unc);
test_not_starts_with(verbatim_disk, no_prefix);
}
#[test]
fn without_prefix() {
// UNC paths
assert_eq!(
Path::new(r"\\?\UNC\server\share\sub\path").without_prefix(),
Path::new(r"\sub\path")
);
assert_eq!(
Path::new(r"\\server\share\sub\path").without_prefix(),
Path::new(r"\sub\path")
);
// Disk paths
assert_eq!(
Path::new(r"\\?\C:\sub\path").without_prefix(),
Path::new(r"\sub\path")
);
assert_eq!(
Path::new(r"C:\sub\path").without_prefix(),
Path::new(r"\sub\path")
);
// Other paths
assert_eq!(
Path::new(r"\\?\cat_pics\sub\path").without_prefix(),
Path::new(r"\sub\path")
);
assert_eq!(
Path::new(r"\\.\COM42\sub\path").without_prefix(),
Path::new(r"\sub\path")
);
// No prefix
assert_eq!(
Path::new(r"\cat_pics\sub\path").without_prefix(),
Path::new(r"\cat_pics\sub\path")
);
}
}
#[cfg(test)]
#[cfg(not(windows))]
mod nix {
use super::*;
#[test]
fn normalised_equals() {
let path_a = Path::new("/a/b/c/d");
let path_b = Path::new("/a/b/c/d");
assert!(path_a.normalised_equals(path_b));
assert!(path_b.normalised_equals(path_a));
let path_c = Path::new("/a/b");
assert!(!path_a.normalised_equals(path_c));
}
#[test]
fn normalised_equals_differing_prefixes() {
// Windows path prefixes are not parsed on *nix
let path_a = Path::new(r"\\?\UNC\server\share\a\b\c\d");
let path_b = Path::new(r"\\server\share\a\b\c\d");
assert!(!path_a.normalised_equals(path_b));
assert!(!path_b.normalised_equals(path_a));
assert!(path_a.normalised_equals(path_a));
}
#[test]
fn normalised_starts_with() {
let path_a = Path::new("/a/b/c/d");
let path_b = Path::new("/a/b");
assert!(path_a.normalised_starts_with(path_b));
assert!(!path_b.normalised_starts_with(path_a));
}
#[test]
fn normalised_starts_with_differing_prefixes() {
// Windows path prefixes are not parsed on *nix
let path_a = Path::new(r"\\?\UNC\server\share\a\b\c\d");
let path_b = Path::new(r"\\server\share\a\b");
assert!(!path_a.normalised_starts_with(path_b));
assert!(!path_b.normalised_starts_with(path_a));
assert!(path_a.normalised_starts_with(path_a));
}
#[test]
fn without_prefix() {
// Windows path prefixes are not parsed on *nix
// UNC paths
assert_eq!(
Path::new(r"\\?\UNC\server\share\sub\path").without_prefix(),
Path::new(r"\\?\UNC\server\share\sub\path")
);
assert_eq!(
Path::new(r"\\server\share\sub\path").without_prefix(),
Path::new(r"\\server\share\sub\path")
);
// Disk paths
assert_eq!(
Path::new(r"\\?\C:\sub\path").without_prefix(),
Path::new(r"\\?\C:\sub\path")
);
assert_eq!(
Path::new(r"C:\sub\path").without_prefix(),
Path::new(r"C:\sub\path")
);
// Other paths
assert_eq!(
Path::new(r"\\?\cat_pics\sub\path").without_prefix(),
Path::new(r"\\?\cat_pics\sub\path")
);
assert_eq!(
Path::new(r"\\.\COM42\sub\path").without_prefix(),
Path::new(r"\\.\COM42\sub\path")
);
// No prefix
assert_eq!(
Path::new(r"\cat_pics\sub\path").without_prefix(),
Path::new(r"\cat_pics\sub\path")
);
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/utils/mod.rs | src/modules/utils/mod.rs | pub mod directory;
#[cfg(target_os = "windows")]
pub mod directory_win;
#[cfg(not(target_os = "windows"))]
pub mod directory_nix;
pub mod path;
pub mod truncate;
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/utils/truncate.rs | src/modules/utils/truncate.rs | use unicode_segmentation::UnicodeSegmentation;
/// Truncate a string to only have a set number of characters
///
/// Will truncate a string to only show the last `length` character in the string.
/// If a length of `0` is provided, the string will not be truncated and the original
/// will be returned.
pub fn truncate_text(text: &str, length: usize, truncation_symbol: &str) -> String {
if length == 0 {
return String::from(text);
}
let truncated_graphemes = get_graphemes(text, length);
// The truncation symbol should only be added if we truncated
if length < graphemes_len(text) {
let truncation_symbol = get_graphemes(truncation_symbol, 1);
truncated_graphemes + truncation_symbol.as_str()
} else {
truncated_graphemes
}
}
fn get_graphemes(text: &str, length: usize) -> String {
UnicodeSegmentation::graphemes(text, true)
.take(length)
.collect::<Vec<&str>>()
.concat()
}
fn graphemes_len(text: &str) -> usize {
UnicodeSegmentation::graphemes(text, true).count()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_multi_char_truncation_symbol() {
let actual = truncate_text("1337_hello_world", 15, "apple");
assert_eq!("1337_hello_worla", actual);
}
#[test]
fn test_changed_truncation_symbol() {
test_truncate_length("1337_hello_world", 15, "1337_hello_worl", "%");
}
#[test]
fn test_no_truncation_symbol() {
test_truncate_length("1337_hello_world", 15, "1337_hello_worl", "");
}
#[test]
fn test_ascii_boundary_below() {
test_truncate_length("1337_hello_world", 15, "1337_hello_worl", "…");
}
#[test]
fn test_ascii_boundary_on() {
test_truncate_length("1337_hello_world", 16, "1337_hello_world", "");
}
#[test]
fn test_ascii_boundary_above() {
test_truncate_length("1337_hello_world", 17, "1337_hello_world", "");
}
#[test]
fn test_one() {
test_truncate_length("1337_hello_world", 1, "1", "…");
}
#[test]
fn test_negative() {
test_truncate_length("1337_hello_world", -1, "1337_hello_world", "");
}
#[test]
fn test_hindi_truncation() {
test_truncate_length("नमस्ते", 2, "नम", "…");
}
#[test]
fn test_hindi_truncation2() {
test_truncate_length("नमस्त", 2, "नम", "…");
}
#[test]
fn test_japanese_truncation() {
test_truncate_length("がんばってね", 4, "がんばっ", "…");
}
fn test_truncate_length(
text: &str,
truncate_length: i64,
expected: &str,
truncation_symbol: &str,
) {
let actual = truncate_text(text, truncate_length as usize, truncation_symbol);
assert_eq!(format!("{expected}{truncation_symbol}"), actual);
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/utils/directory_win.rs | src/modules/utils/directory_win.rs | use std::{mem, os::windows::ffi::OsStrExt, path::Path};
use windows::{
Win32::{
Foundation::{CloseHandle, ERROR_INSUFFICIENT_BUFFER, HANDLE},
Security::{
AccessCheck, DACL_SECURITY_INFORMATION, DuplicateToken, GENERIC_MAPPING,
GROUP_SECURITY_INFORMATION, GetFileSecurityW, MapGenericMask,
OWNER_SECURITY_INFORMATION, PRIVILEGE_SET, PSECURITY_DESCRIPTOR, SecurityImpersonation,
TOKEN_DUPLICATE, TOKEN_IMPERSONATE, TOKEN_QUERY, TOKEN_READ_CONTROL,
},
Storage::FileSystem::{
FILE_ALL_ACCESS, FILE_GENERIC_EXECUTE, FILE_GENERIC_READ, FILE_GENERIC_WRITE,
},
System::Threading::{GetCurrentProcess, OpenProcessToken},
UI::Shell::PathIsNetworkPathW,
},
core::{BOOL, PCWSTR},
};
struct Handle(HANDLE);
impl Drop for Handle {
fn drop(&mut self) {
if let Err(e) = unsafe { CloseHandle(self.0) } {
log::debug!("CloseHandle failed: {e:?}");
}
}
}
/// Checks if the current user has write access right to the `folder_path`
///
/// First, the function extracts DACL from the given directory and then calls `AccessCheck` against
/// the current process access token and directory's security descriptor.
/// Does not work for network drives and always returns true
pub fn is_write_allowed(folder_path: &Path) -> std::result::Result<bool, String> {
let wpath_vec: Vec<u16> = folder_path.as_os_str().encode_wide().chain([0]).collect();
let wpath = PCWSTR(wpath_vec.as_ptr());
if unsafe { PathIsNetworkPathW(wpath) }.as_bool() {
log::info!(
"Directory '{:?}' is a network drive, unable to check write permissions. See #1506 for details",
folder_path
);
return Ok(true);
}
let mut length = 0;
let rc = unsafe {
GetFileSecurityW(
wpath,
(OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION).0,
None,
0,
&mut length,
)
};
// expect ERROR_INSUFFICIENT_BUFFER
match rc.ok() {
Err(e) if e.code() == ERROR_INSUFFICIENT_BUFFER.into() => (),
result => {
return Err(format!(
"GetFileSecurityW returned unexpected return value when asked for the security descriptor size: {result:?}"
));
}
}
let mut buf = vec![0u8; length as usize];
let psecurity_descriptor = PSECURITY_DESCRIPTOR(buf.as_mut_ptr().cast::<std::ffi::c_void>());
let rc = unsafe {
GetFileSecurityW(
wpath,
(OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION).0,
Some(psecurity_descriptor),
length,
&mut length,
)
};
if let Err(e) = rc.ok() {
return Err(format!(
"GetFileSecurityW failed to retrieve the security descriptor: {e:?}"
));
}
let token = {
let mut token = HANDLE::default();
let rc = unsafe {
OpenProcessToken(
GetCurrentProcess(),
TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_READ_CONTROL,
&mut token,
)
};
if let Err(e) = rc {
return Err(format!(
"OpenProcessToken failed to retrieve current process' security token: {e:?}"
));
}
Handle(token)
};
let impersonated_token = {
let mut impersonated_token = HANDLE::default();
let rc = unsafe { DuplicateToken(token.0, SecurityImpersonation, &mut impersonated_token) };
if let Err(e) = rc {
return Err(format!("DuplicateToken failed: {e:?}"));
}
Handle(impersonated_token)
};
let mapping = GENERIC_MAPPING {
GenericRead: FILE_GENERIC_READ.0,
GenericWrite: FILE_GENERIC_WRITE.0,
GenericExecute: FILE_GENERIC_EXECUTE.0,
GenericAll: FILE_ALL_ACCESS.0,
};
let mut privileges: PRIVILEGE_SET = PRIVILEGE_SET::default();
let mut priv_size = mem::size_of::<PRIVILEGE_SET>() as _;
let mut granted_access = 0;
let mut access_rights = FILE_GENERIC_WRITE;
let mut result = BOOL::default();
unsafe { MapGenericMask(&mut access_rights.0, &mapping) };
let rc = unsafe {
AccessCheck(
psecurity_descriptor,
impersonated_token.0,
access_rights.0,
&mapping,
Some(&mut privileges),
&mut priv_size,
&mut granted_access,
&mut result,
)
};
if let Err(e) = rc {
return Err(format!("AccessCheck failed: {e:?}"));
}
Ok(result.as_bool())
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/utils/directory_nix.rs | src/modules/utils/directory_nix.rs | use nix::sys::stat::Mode;
use nix::unistd::{Gid, Uid};
use std::fs;
use std::os::unix::fs::MetadataExt;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
#[allow(clippy::doc_overindented_list_items)]
/// Checks if the current user can write to the `folder_path`.
///
/// It extracts Unix access rights from the directory and checks whether
/// 1) the current user is the owner of the directory and whether it has the write access
/// 2) the current user's primary group is the directory group owner whether if it has write access
/// 2a) (not implemented on macOS) one of the supplementary groups of the current user is the
/// directory group owner and whether it has write access
/// 3) 'others' part of the access mask has the write access
#[allow(clippy::useless_conversion)] // On some platforms it is not u32
pub fn is_write_allowed(folder_path: &Path) -> Result<bool, String> {
let meta =
fs::metadata(folder_path).map_err(|e| format!("Unable to stat() directory: {e:?}"))?;
let perms = meta.permissions().mode();
let euid = Uid::effective();
if euid.is_root() {
return Ok(true);
}
if meta.uid() == euid.as_raw() {
Ok(perms & u32::from(Mode::S_IWUSR.bits()) != 0)
} else if (meta.gid() == Gid::effective().as_raw())
|| (get_supplementary_groups().contains(&meta.gid()))
{
Ok(perms & u32::from(Mode::S_IWGRP.bits()) != 0)
} else {
Ok(perms & u32::from(Mode::S_IWOTH.bits()) != 0)
}
}
#[cfg(all(unix, not(any(target_os = "macos", target_os = "ios"))))]
fn get_supplementary_groups() -> Vec<u32> {
nix::unistd::getgroups()
.unwrap_or_default()
.into_iter()
.map(nix::unistd::Gid::as_raw)
.collect()
}
#[cfg(all(unix, any(target_os = "macos", target_os = "ios")))]
fn get_supplementary_groups() -> Vec<u32> {
// at the moment nix crate does not provide it for macOS
Vec::new()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[ignore]
fn read_only_test() {
assert_eq!(is_write_allowed(Path::new("/etc")), Ok(false));
assert!(match is_write_allowed(Path::new("/i_dont_exist")) {
Ok(_) => false,
Err(e) => e.starts_with("Unable to stat() directory"),
});
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/utils/directory.rs | src/modules/utils/directory.rs | /// Truncate a path to only have a set number of path components
///
/// Will truncate a path to only show the last `length` components in a path.
/// If a length of `0` is provided, the path will not be truncated.
/// A value will only be returned if the path has been truncated.
pub fn truncate(dir_string: &str, length: usize) -> Option<String> {
if length == 0 {
return None;
}
let mut components = dir_string.split('/').collect::<Vec<&str>>();
// If the first element is "" then there was a leading "/" and we should remove it so we can check the actual count of components
if components[0].is_empty() {
components.remove(0);
}
if components.len() <= length {
return None;
}
let truncated_components = &components[components.len() - length..];
Some(truncated_components.join("/"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn truncate_smaller_path_than_provided_length() {
let path = "~/starship";
let output = truncate(path, 3);
assert_eq!(output, None);
}
#[test]
fn truncate_same_path_as_provided_length() {
let path = "~/starship/engines";
let output = truncate(path, 3);
assert_eq!(output, None);
}
#[test]
fn truncate_slightly_larger_path_than_provided_length() {
let path = "~/starship/engines/booster";
let output = truncate(path, 3);
assert_eq!(output.as_deref(), Some("starship/engines/booster"));
}
#[test]
fn truncate_larger_path_than_provided_length() {
let path = "~/starship/engines/booster/rocket";
let output = truncate(path, 3);
assert_eq!(output.as_deref(), Some("engines/booster/rocket"));
}
#[test]
fn truncate_same_path_as_provided_length_from_root() {
let path = "/starship/engines/booster";
let output = truncate(path, 3);
assert_eq!(output, None);
}
#[test]
fn truncate_larger_path_than_provided_length_from_root() {
let path = "/starship/engines/booster/rocket";
let output = truncate(path, 3);
assert_eq!(output.as_deref(), Some("engines/booster/rocket"));
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/nodejs.rs | src/configs/nodejs.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct NodejsConfig<'a> {
pub format: &'a str,
pub version_format: &'a str,
pub symbol: &'a str,
pub style: &'a str,
pub disabled: bool,
pub not_capable_style: &'a str,
pub detect_extensions: Vec<&'a str>,
pub detect_files: Vec<&'a str>,
pub detect_folders: Vec<&'a str>,
}
impl Default for NodejsConfig<'_> {
fn default() -> Self {
Self {
format: "via [$symbol($version )]($style)",
version_format: "v${raw}",
symbol: " ",
style: "bold green",
disabled: false,
not_capable_style: "bold red",
detect_extensions: vec!["js", "mjs", "cjs", "ts", "mts", "cts"],
detect_files: vec![
"package.json",
".node-version",
".nvmrc",
"!bunfig.toml",
"!bun.lock",
"!bun.lockb",
],
detect_folders: vec!["node_modules"],
}
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/jobs.rs | src/configs/jobs.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct JobsConfig<'a> {
pub threshold: i64,
pub symbol_threshold: i64,
pub number_threshold: i64,
pub format: &'a str,
pub symbol: &'a str,
pub style: &'a str,
pub disabled: bool,
}
impl Default for JobsConfig<'_> {
fn default() -> Self {
Self {
threshold: 1,
symbol_threshold: 1,
number_threshold: 2,
format: "[$symbol$number]($style) ",
symbol: "✦",
style: "bold blue",
disabled: false,
}
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/username.rs | src/configs/username.rs | use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct UsernameConfig<'a> {
pub detect_env_vars: Vec<&'a str>,
pub format: &'a str,
pub style_root: &'a str,
pub style_user: &'a str,
pub show_always: bool,
pub disabled: bool,
pub aliases: IndexMap<String, &'a str>,
}
impl Default for UsernameConfig<'_> {
fn default() -> Self {
Self {
detect_env_vars: vec![],
format: "[$user]($style) in ",
style_root: "red bold",
style_user: "yellow bold",
show_always: false,
disabled: false,
aliases: IndexMap::new(),
}
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/perl.rs | src/configs/perl.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct PerlConfig<'a> {
pub format: &'a str,
pub version_format: &'a str,
pub symbol: &'a str,
pub style: &'a str,
pub disabled: bool,
pub detect_extensions: Vec<&'a str>,
pub detect_files: Vec<&'a str>,
pub detect_folders: Vec<&'a str>,
}
impl Default for PerlConfig<'_> {
fn default() -> Self {
Self {
format: "via [$symbol($version )]($style)",
version_format: "v${raw}",
symbol: "🐪 ",
style: "149 bold",
disabled: false,
detect_extensions: vec!["pl", "pm", "pod"],
detect_files: vec![
"Makefile.PL",
"Build.PL",
"cpanfile",
"cpanfile.snapshot",
"META.json",
"META.yml",
".perl-version",
],
detect_folders: vec![],
}
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/starship_root.rs | src/configs/starship_root.rs | use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Clone, Serialize, Deserialize, Debug)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct StarshipRootConfig {
#[serde(rename = "$schema")]
schema: String,
pub format: String,
pub right_format: String,
pub continuation_prompt: String,
pub scan_timeout: u64,
pub command_timeout: u64,
pub add_newline: bool,
pub follow_symlinks: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub palette: Option<String>,
pub palettes: HashMap<String, Palette>,
pub profiles: IndexMap<String, String>,
}
pub type Palette = HashMap<String, String>;
// List of default prompt order
// NOTE: If this const value is changed then Default prompt order subheading inside
// prompt heading of config docs needs to be updated according to changes made here.
pub const PROMPT_ORDER: &[&str] = &[
"username",
"hostname",
"localip",
"shlvl",
"singularity",
"kubernetes",
"nats",
"directory",
"vcsh",
"fossil_branch",
"fossil_metrics",
"git_branch",
"git_commit",
"git_state",
"git_metrics",
"git_status",
"hg_branch",
"hg_state",
"pijul_channel",
"docker_context",
"package",
// ↓ Toolchain version modules ↓
// (Let's keep these sorted alphabetically)
"bun",
"c",
"cmake",
"cobol",
"cpp",
"daml",
"dart",
"deno",
"dotnet",
"elixir",
"elm",
"erlang",
"fennel",
"fortran",
"gleam",
"golang",
"gradle",
"haskell",
"haxe",
"helm",
"java",
"julia",
"kotlin",
"lua",
"mojo",
"nim",
"nodejs",
"ocaml",
"odin",
"opa",
"perl",
"php",
"pulumi",
"purescript",
"python",
"quarto",
"raku",
"rlang",
"red",
"ruby",
"rust",
"scala",
"solidity",
"swift",
"terraform",
"typst",
"vlang",
"vagrant",
"xmake",
"zig",
// ↑ Toolchain version modules ↑
"buf",
"guix_shell",
"nix_shell",
"conda",
"pixi",
"meson",
"spack",
"memory_usage",
"aws",
"gcloud",
"openstack",
"azure",
"direnv",
"env_var",
"mise",
"crystal",
"custom",
"sudo",
"cmd_duration",
"line_break",
"jobs",
#[cfg(feature = "battery")]
"battery",
"time",
"status",
"container",
"netns",
"os",
"shell",
"character",
];
// On changes please also update `Default` for the `FullConfig` struct in `mod.rs`
impl Default for StarshipRootConfig {
fn default() -> Self {
Self {
schema: "https://starship.rs/config-schema.json".to_string(),
format: "$all".to_string(),
right_format: String::new(),
continuation_prompt: "[∙](bright-black) ".to_string(),
profiles: Default::default(),
scan_timeout: 30,
command_timeout: 500,
add_newline: true,
follow_symlinks: true,
palette: None,
palettes: HashMap::default(),
}
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/gradle.rs | src/configs/gradle.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct GradleConfig<'a> {
pub format: &'a str,
pub version_format: &'a str,
pub symbol: &'a str,
pub style: &'a str,
pub disabled: bool,
pub recursive: bool,
pub detect_extensions: Vec<&'a str>,
pub detect_files: Vec<&'a str>,
pub detect_folders: Vec<&'a str>,
}
impl Default for GradleConfig<'_> {
fn default() -> Self {
Self {
format: "via [$symbol($version )]($style)",
version_format: "v${raw}",
symbol: "🅶 ",
style: "bold bright-cyan",
disabled: false,
recursive: false,
detect_extensions: vec!["gradle", "gradle.kts"],
detect_files: vec![],
detect_folders: vec!["gradle"],
}
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/ruby.rs | src/configs/ruby.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct RubyConfig<'a> {
pub format: &'a str,
pub version_format: &'a str,
pub symbol: &'a str,
pub style: &'a str,
pub disabled: bool,
pub detect_extensions: Vec<&'a str>,
pub detect_files: Vec<&'a str>,
pub detect_folders: Vec<&'a str>,
pub detect_variables: Vec<&'a str>,
}
impl Default for RubyConfig<'_> {
fn default() -> Self {
Self {
format: "via [$symbol($version )]($style)",
version_format: "v${raw}",
symbol: "💎 ",
style: "bold red",
disabled: false,
detect_extensions: vec!["rb"],
detect_files: vec!["Gemfile", ".ruby-version"],
detect_folders: vec![],
detect_variables: vec!["RUBY_VERSION", "RBENV_VERSION"],
}
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/rust.rs | src/configs/rust.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct RustConfig<'a> {
pub format: &'a str,
pub version_format: &'a str,
pub symbol: &'a str,
pub style: &'a str,
pub disabled: bool,
pub detect_extensions: Vec<&'a str>,
pub detect_files: Vec<&'a str>,
pub detect_folders: Vec<&'a str>,
}
impl Default for RustConfig<'_> {
fn default() -> Self {
Self {
format: "via [$symbol($version )]($style)",
version_format: "v${raw}",
symbol: "🦀 ",
style: "bold red",
disabled: false,
detect_extensions: vec!["rs"],
detect_files: vec!["Cargo.toml"],
detect_folders: vec![],
}
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/aws.rs | src/configs/aws.rs | use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(default)]
/// ## AWS
///
/// The `aws` module shows the current AWS region and profile and an expiration timer when using temporary credentials.
/// The output of the module uses the `AWS_REGION`, `AWS_DEFAULT_REGION`, and `AWS_PROFILE` env vars and the `~/.aws/config` and `~/.aws/credentials` files as required.
///
/// The module will display a profile only if its credentials are present in `~/.aws/credentials` or if a `credential_process` or `sso_start_url` are defined in `~/.aws/config`. Alternatively, having any of the `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, or `AWS_SESSION_TOKEN` env vars defined will also suffice.
/// If the option `force_display` is set to `true`, all available information will be displayed even if no credentials per the conditions above are detected.
///
/// When using [aws-vault](https://github.com/99designs/aws-vault) the profile
/// is read from the `AWS_VAULT` env var and the credentials expiration date
/// is read from the `AWS_SESSION_EXPIRATION` or `AWS_CREDENTIAL_EXPIRATION`
/// var.
///
/// When using [awsu](https://github.com/kreuzwerker/awsu) the profile
/// is read from the `AWSU_PROFILE` env var.
///
/// When using [`AWSume`](https://awsu.me) the profile
/// is read from the `AWSUME_PROFILE` env var and the credentials expiration
/// date is read from the `AWSUME_EXPIRATION` env var.
///
/// When using [aws-sso-cli](https://github.com/synfinatic/aws-sso-cli) the profile
/// is read from the `AWS_SSO_PROFILE` env var.
pub struct AwsConfig<'a> {
/// The format for the module.
pub format: &'a str,
/// The symbol used before displaying the current AWS profile.
pub symbol: &'a str,
/// The style for the module.
pub style: &'a str,
/// Disables the AWS module.
pub disabled: bool,
/// Table of region aliases to display in addition to the AWS name.
pub region_aliases: HashMap<String, &'a str>,
/// Table of profile aliases to display in addition to the AWS name.
pub profile_aliases: HashMap<String, &'a str>,
/// The symbol displayed when the temporary credentials have expired.
pub expiration_symbol: &'a str,
/// If true displays info even if `credentials`, `credential_process` or `sso_start_url` have not been setup.
pub force_display: bool,
}
impl Default for AwsConfig<'_> {
fn default() -> Self {
Self {
format: "on [$symbol($profile )(\\($region\\) )(\\[$duration\\] )]($style)",
symbol: "☁️ ",
style: "bold yellow",
disabled: false,
region_aliases: HashMap::new(),
profile_aliases: HashMap::new(),
expiration_symbol: "X",
force_display: false,
}
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/typst.rs | src/configs/typst.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct TypstConfig<'a> {
pub format: &'a str,
pub version_format: &'a str,
pub symbol: &'a str,
pub style: &'a str,
pub disabled: bool,
pub detect_extensions: Vec<&'a str>,
pub detect_files: Vec<&'a str>,
pub detect_folders: Vec<&'a str>,
}
impl Default for TypstConfig<'_> {
fn default() -> Self {
Self {
format: "via [$symbol($version )]($style)",
version_format: "v${raw}",
symbol: "t ",
style: "bold #0093A7",
disabled: false,
detect_extensions: vec!["typ"],
detect_files: vec!["template.typ"],
detect_folders: vec![],
}
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/sudo.rs | src/configs/sudo.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct SudoConfig<'a> {
pub format: &'a str,
pub symbol: &'a str,
pub style: &'a str,
pub allow_windows: bool,
pub disabled: bool,
}
impl Default for SudoConfig<'_> {
fn default() -> Self {
Self {
format: "[as $symbol]($style)",
symbol: "🧙 ",
style: "bold blue",
allow_windows: false,
disabled: true,
}
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/fill.rs | src/configs/fill.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct FillConfig<'a> {
pub style: &'a str,
pub symbol: &'a str,
pub disabled: bool,
}
impl Default for FillConfig<'_> {
fn default() -> Self {
Self {
style: "bold black",
symbol: ".",
disabled: false,
}
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/cc.rs | src/configs/cc.rs | use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields),
schemars(bound = "CcConfig<'a, T>: std::default::Default, T: schemars::JsonSchema")
)]
#[serde(default)]
pub struct CcConfig<'a, T> {
#[serde(skip)]
pub marker: std::marker::PhantomData<T>,
pub format: &'a str,
pub version_format: &'a str,
pub style: &'a str,
pub symbol: &'a str,
pub disabled: bool,
pub detect_extensions: Vec<&'a str>,
pub detect_files: Vec<&'a str>,
pub detect_folders: Vec<&'a str>,
pub commands: Vec<Vec<&'a str>>,
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/guix_shell.rs | src/configs/guix_shell.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct GuixShellConfig<'a> {
pub format: &'a str,
pub symbol: &'a str,
pub style: &'a str,
pub disabled: bool,
}
impl Default for GuixShellConfig<'_> {
fn default() -> Self {
Self {
format: "via [$symbol]($style) ",
symbol: "🐃 ",
style: "yellow bold",
disabled: false,
}
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/localip.rs | src/configs/localip.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct LocalipConfig<'a> {
pub ssh_only: bool,
pub format: &'a str,
pub style: &'a str,
pub disabled: bool,
}
impl Default for LocalipConfig<'_> {
fn default() -> Self {
Self {
ssh_only: true,
format: "[$localipv4]($style) ",
style: "yellow bold",
disabled: true,
}
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/nim.rs | src/configs/nim.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct NimConfig<'a> {
pub format: &'a str,
pub version_format: &'a str,
pub symbol: &'a str,
pub style: &'a str,
pub disabled: bool,
pub detect_extensions: Vec<&'a str>,
pub detect_files: Vec<&'a str>,
pub detect_folders: Vec<&'a str>,
}
impl Default for NimConfig<'_> {
fn default() -> Self {
Self {
format: "via [$symbol($version )]($style)",
version_format: "v${raw}",
symbol: "👑 ",
style: "yellow bold",
disabled: false,
detect_extensions: vec!["nim", "nims", "nimble"],
detect_files: vec!["nim.cfg"],
detect_folders: vec![],
}
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/kotlin.rs | src/configs/kotlin.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct KotlinConfig<'a> {
pub format: &'a str,
pub version_format: &'a str,
pub symbol: &'a str,
pub style: &'a str,
pub kotlin_binary: &'a str,
pub disabled: bool,
pub detect_extensions: Vec<&'a str>,
pub detect_files: Vec<&'a str>,
pub detect_folders: Vec<&'a str>,
}
impl Default for KotlinConfig<'_> {
fn default() -> Self {
Self {
format: "via [$symbol($version )]($style)",
version_format: "v${raw}",
symbol: "🅺 ",
style: "bold blue",
kotlin_binary: "kotlin",
disabled: false,
detect_extensions: vec!["kt", "kts"],
detect_files: vec![],
detect_folders: vec![],
}
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/daml.rs | src/configs/daml.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct DamlConfig<'a> {
pub symbol: &'a str,
pub format: &'a str,
pub version_format: &'a str,
pub style: &'a str,
pub disabled: bool,
pub detect_extensions: Vec<&'a str>,
pub detect_files: Vec<&'a str>,
pub detect_folders: Vec<&'a str>,
}
impl Default for DamlConfig<'_> {
fn default() -> Self {
Self {
symbol: "Λ ",
format: "via [$symbol($version )]($style)",
version_format: "v${raw}",
style: "bold cyan",
disabled: false,
detect_extensions: vec![],
detect_files: vec!["daml.yaml"],
detect_folders: vec![],
}
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/cmd_duration.rs | src/configs/cmd_duration.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct CmdDurationConfig<'a> {
pub min_time: i64,
pub format: &'a str,
pub style: &'a str,
pub show_milliseconds: bool,
pub disabled: bool,
pub show_notifications: bool,
pub min_time_to_notify: i64,
#[serde(skip_serializing_if = "Option::is_none")]
pub notification_timeout: Option<u32>,
}
impl Default for CmdDurationConfig<'_> {
fn default() -> Self {
Self {
min_time: 2_000,
format: "took [$duration]($style) ",
show_milliseconds: false,
style: "yellow bold",
disabled: false,
show_notifications: false,
min_time_to_notify: 45_000,
notification_timeout: None,
}
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/env_var.rs | src/configs/env_var.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct EnvVarConfig<'a> {
pub symbol: &'a str,
pub style: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
pub variable: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
pub default: Option<&'a str>,
pub format: &'a str,
pub disabled: bool,
pub description: &'a str,
}
impl Default for EnvVarConfig<'_> {
fn default() -> Self {
Self {
symbol: "",
style: "black bold dimmed",
variable: None,
default: None,
format: "with [$env_value]($style) ",
disabled: false,
description: "<env_var module>",
}
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/openstack.rs | src/configs/openstack.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct OspConfig<'a> {
pub format: &'a str,
pub symbol: &'a str,
pub style: &'a str,
pub disabled: bool,
}
impl Default for OspConfig<'_> {
fn default() -> Self {
Self {
format: "on [$symbol$cloud(\\($project\\))]($style) ",
symbol: "☁️ ",
style: "bold yellow",
disabled: false,
}
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/shlvl.rs | src/configs/shlvl.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct ShLvlConfig<'a> {
pub threshold: i64,
pub format: &'a str,
pub symbol: &'a str,
pub repeat: bool,
pub repeat_offset: u64,
pub style: &'a str,
pub disabled: bool,
}
impl Default for ShLvlConfig<'_> {
fn default() -> Self {
Self {
threshold: 2,
format: "[$symbol$shlvl]($style) ",
symbol: "↕️ ", // extra space for emoji
repeat: false,
repeat_offset: 0,
style: "bold yellow",
disabled: true,
}
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/direnv.rs | src/configs/direnv.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct DirenvConfig<'a> {
pub format: &'a str,
pub symbol: &'a str,
pub style: &'a str,
pub disabled: bool,
pub detect_extensions: Vec<&'a str>,
pub detect_env_vars: Vec<&'a str>,
pub detect_files: Vec<&'a str>,
pub detect_folders: Vec<&'a str>,
pub allowed_msg: &'a str,
pub not_allowed_msg: &'a str,
pub denied_msg: &'a str,
pub loaded_msg: &'a str,
pub unloaded_msg: &'a str,
}
impl Default for DirenvConfig<'_> {
fn default() -> Self {
Self {
format: "[$symbol$loaded/$allowed]($style) ",
symbol: "direnv ",
style: "bold bright-yellow",
disabled: true,
detect_extensions: vec![],
detect_env_vars: vec!["DIRENV_FILE"],
detect_files: vec![".envrc"],
detect_folders: vec![],
allowed_msg: "allowed",
not_allowed_msg: "not allowed",
denied_msg: "denied",
loaded_msg: "loaded",
unloaded_msg: "not loaded",
}
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/mojo.rs | src/configs/mojo.rs | use nu_ansi_term::Color;
use serde::{Deserialize, Serialize};
pub const MOJO_DEFAULT_COLOR: Color = Color::Fixed(208);
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct MojoConfig<'a> {
pub format: &'a str,
pub symbol: &'a str,
pub style: &'a str,
pub disabled: bool,
pub detect_extensions: Vec<&'a str>,
pub detect_files: Vec<&'a str>,
pub detect_folders: Vec<&'a str>,
}
impl Default for MojoConfig<'_> {
fn default() -> Self {
Self {
format: "with [$symbol($version )]($style)",
symbol: "🔥 ",
style: "bold 208",
disabled: false,
detect_extensions: vec!["mojo", "🔥"],
detect_files: vec![],
detect_folders: vec![],
}
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/fennel.rs | src/configs/fennel.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct FennelConfig<'a> {
pub format: &'a str,
pub version_format: &'a str,
pub symbol: &'a str,
pub style: &'a str,
pub disabled: bool,
#[serde(alias = "detect_extentions")] // TODO: remove it after breaking change releases
pub detect_extensions: Vec<&'a str>,
pub detect_files: Vec<&'a str>,
pub detect_folders: Vec<&'a str>,
}
impl Default for FennelConfig<'_> {
fn default() -> Self {
Self {
format: "via [$symbol($version )]($style)",
version_format: "v${raw}",
symbol: "🧅 ",
style: "bold green",
disabled: true,
detect_extensions: vec!["fnl"],
detect_files: vec![],
detect_folders: vec![],
}
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/vagrant.rs | src/configs/vagrant.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct VagrantConfig<'a> {
pub format: &'a str,
pub version_format: &'a str,
pub symbol: &'a str,
pub style: &'a str,
pub disabled: bool,
pub detect_extensions: Vec<&'a str>,
pub detect_files: Vec<&'a str>,
pub detect_folders: Vec<&'a str>,
}
impl Default for VagrantConfig<'_> {
fn default() -> Self {
Self {
format: "via [$symbol($version )]($style)",
version_format: "v${raw}",
symbol: "⍱ ",
style: "cyan bold",
disabled: false,
detect_extensions: vec![],
detect_files: vec!["Vagrantfile"],
detect_folders: vec![],
}
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/line_break.rs | src/configs/line_break.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Deserialize, Serialize, Default)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct LineBreakConfig {
pub disabled: bool,
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/git_status.rs | src/configs/git_status.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct GitStatusConfig<'a> {
pub format: &'a str,
pub style: &'a str,
pub stashed: &'a str,
pub ahead: &'a str,
pub behind: &'a str,
pub up_to_date: &'a str,
pub diverged: &'a str,
pub conflicted: &'a str,
pub deleted: &'a str,
pub renamed: &'a str,
pub modified: &'a str,
pub staged: &'a str,
pub untracked: &'a str,
pub typechanged: &'a str,
pub ignore_submodules: bool,
pub disabled: bool,
pub use_git_executable: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub windows_starship: Option<&'a str>,
}
impl Default for GitStatusConfig<'_> {
fn default() -> Self {
Self {
format: "([\\[$all_status$ahead_behind\\]]($style) )",
style: "red bold",
stashed: "\\$",
ahead: "⇡",
behind: "⇣",
up_to_date: "",
diverged: "⇕",
conflicted: "=",
deleted: "✘",
renamed: "»",
modified: "!",
staged: "+",
untracked: "?",
typechanged: "",
ignore_submodules: false,
disabled: false,
use_git_executable: false,
windows_starship: None,
}
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/elm.rs | src/configs/elm.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct ElmConfig<'a> {
pub format: &'a str,
pub version_format: &'a str,
pub symbol: &'a str,
pub style: &'a str,
pub disabled: bool,
pub detect_extensions: Vec<&'a str>,
pub detect_files: Vec<&'a str>,
pub detect_folders: Vec<&'a str>,
}
impl Default for ElmConfig<'_> {
fn default() -> Self {
Self {
format: "via [$symbol($version )]($style)",
version_format: "v${raw}",
symbol: "🌳 ",
style: "cyan bold",
disabled: false,
detect_extensions: vec!["elm"],
detect_files: vec!["elm.json", "elm-package.json", ".elm-version"],
detect_folders: vec!["elm-stuff"],
}
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/dart.rs | src/configs/dart.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct DartConfig<'a> {
pub format: &'a str,
pub version_format: &'a str,
pub symbol: &'a str,
pub style: &'a str,
pub disabled: bool,
pub detect_extensions: Vec<&'a str>,
pub detect_files: Vec<&'a str>,
pub detect_folders: Vec<&'a str>,
}
impl Default for DartConfig<'_> {
fn default() -> Self {
Self {
format: "via [$symbol($version )]($style)",
version_format: "v${raw}",
symbol: "🎯 ",
style: "bold blue",
disabled: false,
detect_extensions: vec!["dart"],
detect_files: vec!["pubspec.yaml", "pubspec.yml", "pubspec.lock"],
detect_folders: vec![".dart_tool"],
}
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/gleam.rs | src/configs/gleam.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct GleamConfig<'a> {
pub format: &'a str,
pub version_format: &'a str,
pub symbol: &'a str,
pub style: &'a str,
pub disabled: bool,
pub detect_extensions: Vec<&'a str>,
pub detect_files: Vec<&'a str>,
pub detect_folders: Vec<&'a str>,
}
impl Default for GleamConfig<'_> {
fn default() -> Self {
Self {
format: "via [$symbol($version )]($style)",
version_format: "v${raw}",
symbol: "⭐ ",
style: "bold #FFAFF3",
disabled: false,
detect_extensions: vec!["gleam"],
detect_files: vec!["gleam.toml"],
detect_folders: vec![],
}
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/go.rs | src/configs/go.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct GoConfig<'a> {
pub format: &'a str,
pub version_format: &'a str,
pub symbol: &'a str,
pub style: &'a str,
pub disabled: bool,
pub not_capable_style: &'a str,
pub detect_extensions: Vec<&'a str>,
pub detect_files: Vec<&'a str>,
pub detect_folders: Vec<&'a str>,
}
impl Default for GoConfig<'_> {
fn default() -> Self {
Self {
format: "via [$symbol($version )]($style)",
version_format: "v${raw}",
symbol: "🐹 ",
style: "bold cyan",
disabled: false,
not_capable_style: "bold red",
detect_extensions: vec!["go"],
detect_files: vec![
"go.mod",
"go.sum",
"go.work",
"glide.yaml",
"Gopkg.yml",
"Gopkg.lock",
".go-version",
],
detect_folders: vec!["Godeps"],
}
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/scala.rs | src/configs/scala.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct ScalaConfig<'a> {
pub format: &'a str,
pub version_format: &'a str,
pub disabled: bool,
pub style: &'a str,
pub symbol: &'a str,
pub detect_extensions: Vec<&'a str>,
pub detect_files: Vec<&'a str>,
pub detect_folders: Vec<&'a str>,
}
impl Default for ScalaConfig<'_> {
fn default() -> Self {
Self {
format: "via [$symbol($version )]($style)",
version_format: "v${raw}",
disabled: false,
style: "red bold",
symbol: "🆂 ",
detect_extensions: vec!["sbt", "scala"],
detect_files: vec![".scalaenv", ".sbtenv", "build.sbt"],
detect_folders: vec![".metals"],
}
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/julia.rs | src/configs/julia.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct JuliaConfig<'a> {
pub format: &'a str,
pub version_format: &'a str,
pub symbol: &'a str,
pub style: &'a str,
pub disabled: bool,
pub detect_extensions: Vec<&'a str>,
pub detect_files: Vec<&'a str>,
pub detect_folders: Vec<&'a str>,
}
impl Default for JuliaConfig<'_> {
fn default() -> Self {
Self {
format: "via [$symbol($version )]($style)",
version_format: "v${raw}",
symbol: "ஃ ",
style: "bold purple",
disabled: false,
detect_extensions: vec!["jl"],
detect_files: vec!["Project.toml", "Manifest.toml"],
detect_folders: vec![],
}
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/purescript.rs | src/configs/purescript.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct PureScriptConfig<'a> {
pub format: &'a str,
pub version_format: &'a str,
pub symbol: &'a str,
pub style: &'a str,
pub disabled: bool,
pub detect_extensions: Vec<&'a str>,
pub detect_files: Vec<&'a str>,
pub detect_folders: Vec<&'a str>,
}
impl Default for PureScriptConfig<'_> {
fn default() -> Self {
Self {
format: "via [$symbol($version )]($style)",
version_format: "v${raw}",
symbol: "<=> ",
style: "bold white",
disabled: false,
detect_extensions: vec!["purs"],
detect_files: vec!["spago.dhall", "spago.yaml", "spago.lock"],
detect_folders: vec![],
}
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configs/vcsh.rs | src/configs/vcsh.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct VcshConfig<'a> {
pub symbol: &'a str,
pub style: &'a str,
pub format: &'a str,
pub disabled: bool,
}
impl Default for VcshConfig<'_> {
fn default() -> Self {
Self {
symbol: "",
style: "bold yellow",
format: "vcsh [$symbol$repo]($style) ",
disabled: false,
}
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.