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 |
|---|---|---|---|---|---|---|---|---|
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/assets/lazy_theme_set.rs | src/assets/lazy_theme_set.rs | use super::*;
use std::collections::BTreeMap;
use std::convert::TryFrom;
use serde_derive::{Deserialize, Serialize};
use once_cell::unsync::OnceCell;
use syntect::highlighting::{Theme, ThemeSet};
/// Same structure as a [`syntect::highlighting::ThemeSet`] but with themes
/// stored in raw serialized form, and deserialized on demand.
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct LazyThemeSet {
/// This is a [`BTreeMap`] because that's what [`syntect::highlighting::ThemeSet`] uses
themes: BTreeMap<String, LazyTheme>,
}
/// Stores raw serialized data for a theme with methods to lazily deserialize
/// (load) the theme.
#[derive(Debug, Serialize, Deserialize)]
struct LazyTheme {
serialized: Vec<u8>,
#[serde(skip, default = "OnceCell::new")]
deserialized: OnceCell<syntect::highlighting::Theme>,
}
impl LazyThemeSet {
/// Lazily load the given theme
pub fn get(&self, name: &str) -> Option<&Theme> {
self.themes.get(name).and_then(|lazy_theme| {
lazy_theme
.deserialized
.get_or_try_init(|| lazy_theme.deserialize())
.ok()
})
}
/// Returns the name of all themes.
pub fn themes(&self) -> impl Iterator<Item = &str> {
self.themes.keys().map(|name| name.as_ref())
}
}
impl LazyTheme {
fn deserialize(&self) -> Result<Theme> {
asset_from_contents(
&self.serialized[..],
"lazy-loaded theme",
COMPRESS_LAZY_THEMES,
)
}
}
impl TryFrom<LazyThemeSet> for ThemeSet {
type Error = Error;
/// Since the user might want to add custom themes to bat, we need a way to
/// convert from a `LazyThemeSet` to a regular [`ThemeSet`] so that more
/// themes can be added. This function does that pretty straight-forward
/// conversion.
fn try_from(lazy_theme_set: LazyThemeSet) -> Result<Self> {
let mut theme_set = ThemeSet::default();
for (name, lazy_theme) in lazy_theme_set.themes {
theme_set.themes.insert(name, lazy_theme.deserialize()?);
}
Ok(theme_set)
}
}
#[cfg(feature = "build-assets")]
impl TryFrom<ThemeSet> for LazyThemeSet {
type Error = Error;
/// To collect themes, a [`ThemeSet`] is needed. Once all desired themes
/// have been added, we need a way to convert that into [`LazyThemeSet`] so
/// that themes can be lazy-loaded later. This function does that
/// conversion.
fn try_from(theme_set: ThemeSet) -> Result<Self> {
let mut lazy_theme_set = LazyThemeSet::default();
for (name, theme) in theme_set.themes {
// All we have to do is to serialize the theme
let lazy_theme = LazyTheme {
serialized: crate::assets::build_assets::asset_to_contents(
&theme,
&format!("theme {name}"),
COMPRESS_LAZY_THEMES,
)?,
deserialized: OnceCell::new(),
};
// Ok done, now we can add it
lazy_theme_set.themes.insert(name, lazy_theme);
}
Ok(lazy_theme_set)
}
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/assets/serialized_syntax_set.rs | src/assets/serialized_syntax_set.rs | use std::path::PathBuf;
use syntect::parsing::SyntaxSet;
use super::*;
/// A SyntaxSet in serialized form, i.e. bincoded and flate2 compressed.
/// We keep it in this format since we want to load it lazily.
#[derive(Debug)]
pub enum SerializedSyntaxSet {
/// The data comes from a user-generated cache file.
FromFile(PathBuf),
/// The data to use is embedded into the bat binary.
FromBinary(&'static [u8]),
}
impl SerializedSyntaxSet {
pub fn deserialize(&self) -> Result<SyntaxSet> {
match self {
SerializedSyntaxSet::FromBinary(data) => Ok(from_binary(data, COMPRESS_SYNTAXES)),
SerializedSyntaxSet::FromFile(ref path) => {
asset_from_cache(path, "syntax set", COMPRESS_SYNTAXES)
}
}
}
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/assets/assets_metadata.rs | src/assets/assets_metadata.rs | use std::fs::File;
use std::path::Path;
use std::time::SystemTime;
use semver::Version;
use serde_derive::{Deserialize, Serialize};
use crate::error::*;
#[derive(Debug, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct AssetsMetadata {
bat_version: Option<String>,
creation_time: Option<SystemTime>,
}
const FILENAME: &str = "metadata.yaml";
impl AssetsMetadata {
#[cfg(feature = "build-assets")]
pub(crate) fn new(current_version: &str) -> AssetsMetadata {
AssetsMetadata {
bat_version: Some(current_version.to_owned()),
creation_time: Some(SystemTime::now()),
}
}
#[cfg(feature = "build-assets")]
pub(crate) fn save_to_folder(&self, path: &Path) -> Result<()> {
let file = File::create(path.join(FILENAME))?;
serde_yaml::to_writer(file, self)?;
Ok(())
}
fn try_load_from_folder(path: &Path) -> Result<Self> {
let file = File::open(path.join(FILENAME))?;
Ok(serde_yaml::from_reader(file)?)
}
/// Load metadata about the stored cache file from the given folder.
///
/// There are several possibilities:
/// - We find a `metadata.yaml` file and are able to parse it
/// - return the contained information
/// - We find a `metadata.yaml` file, but are not able to parse it
/// - return a [`Error::SerdeYamlError`]
/// - We do not find a `metadata.yaml` file but a `syntaxes.bin` or `themes.bin` file
/// - assume that these were created by an old version of bat and return
/// [`AssetsMetadata::default()`] without version information
/// - We do not find a `metadata.yaml` file and no cached assets
/// - no user provided assets are available, return `None`
pub fn load_from_folder(path: &Path) -> Result<Option<Self>> {
match Self::try_load_from_folder(path) {
Ok(metadata) => Ok(Some(metadata)),
Err(e) => {
if let Error::SerdeYamlError(_) = e {
Err(e)
} else if path.join("syntaxes.bin").exists() || path.join("themes.bin").exists() {
Ok(Some(Self::default()))
} else {
Ok(None)
}
}
}
}
pub fn is_compatible_with(&self, current_version: &str) -> bool {
let current_version =
Version::parse(current_version).expect("bat follows semantic versioning");
let stored_version = self
.bat_version
.as_ref()
.and_then(|ver| Version::parse(ver).ok());
if let Some(stored_version) = stored_version {
current_version.major == stored_version.major
&& current_version.minor == stored_version.minor
} else {
false
}
}
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/assets/build_assets/acknowledgements.rs | src/assets/build_assets/acknowledgements.rs | use std::fmt::Write;
use std::fs::read_to_string;
use std::path::{Path, PathBuf};
use walkdir::DirEntry;
use crate::error::*;
struct PathAndStem {
path: PathBuf,
stem: String,
relative_path: String,
}
/// Looks for LICENSE and NOTICE files in `source_dir`, does some rudimentary
/// analysis, and compiles them together in a single string that is meant to be
/// used in the output to `--acknowledgements`
pub fn build_acknowledgements(
source_dir: &Path,
include_acknowledgements: bool,
) -> Result<Option<String>> {
if !include_acknowledgements {
return Ok(None);
}
let mut acknowledgements = format!("{}\n\n", include_str!("../../../NOTICE"));
// Sort entries so the order is stable over time
let entries = walkdir::WalkDir::new(source_dir).sort_by(|a, b| a.path().cmp(b.path()));
for path_and_stem in entries
.into_iter()
.flatten()
.flat_map(|entry| to_path_and_stem(source_dir, entry))
{
if let Some(license_text) = handle_file(&path_and_stem)? {
append_to_acknowledgements(
&mut acknowledgements,
&path_and_stem.relative_path,
&license_text,
)
}
}
Ok(Some(acknowledgements))
}
fn to_path_and_stem(source_dir: &Path, entry: DirEntry) -> Option<PathAndStem> {
let path = entry.path();
Some(PathAndStem {
path: path.to_owned(),
stem: path.file_stem().map(|s| s.to_string_lossy().to_string())?,
relative_path: path
.strip_prefix(source_dir)
.map(|p| p.to_string_lossy().to_string())
.ok()?,
})
}
fn handle_file(path_and_stem: &PathAndStem) -> Result<Option<String>> {
if path_and_stem.stem == "NOTICE" {
handle_notice(&path_and_stem.path)
} else if path_and_stem.stem.eq_ignore_ascii_case("LICENSE") {
handle_license(&path_and_stem.path)
} else {
Ok(None)
}
}
fn handle_notice(path: &Path) -> Result<Option<String>> {
// Assume NOTICE as defined by Apache License 2.0. These must be part of acknowledgements.
Ok(Some(read_to_string(path)?))
}
fn handle_license(path: &Path) -> Result<Option<String>> {
let license_text = read_to_string(path)?;
if include_license_in_acknowledgments(&license_text) {
Ok(Some(license_text))
} else if license_not_needed_in_acknowledgements(&license_text) {
Ok(None)
} else {
Err(format!("ERROR: License is of unknown type: {path:?}").into())
}
}
fn include_license_in_acknowledgments(license_text: &str) -> bool {
let markers = vec![
// MIT
"The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.",
// BSD
"Redistributions in binary form must reproduce the above copyright notice,",
// Apache 2.0
"Apache License Version 2.0, January 2004 http://www.apache.org/licenses/",
"Licensed under the Apache License, Version 2.0 (the \"License\");",
// CC BY 4.0
"Creative Commons Attribution 4.0 International Public License",
];
license_contains_marker(license_text, &markers)
}
fn license_not_needed_in_acknowledgements(license_text: &str) -> bool {
let markers = vec![
// Public domain
"This is free and unencumbered software released into the public domain.",
// Public domain with stronger wording than above
"DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE",
// Special license of assets/syntaxes/01_Packages/LICENSE
"Permission to copy, use, modify, sell and distribute this software is granted. This software is provided \"as is\" without express or implied warranty, and with no claim as to its suitability for any purpose."
];
license_contains_marker(license_text, &markers)
}
fn license_contains_marker(license_text: &str, markers: &[&str]) -> bool {
let normalized_license_text = normalize_license_text(license_text);
markers.iter().any(|m| normalized_license_text.contains(m))
}
fn append_to_acknowledgements(
acknowledgements: &mut String,
relative_path: &str,
license_text: &str,
) {
write!(acknowledgements, "## {relative_path}\n\n{license_text}").ok();
// Make sure the last char is a newline to not mess up formatting later
if acknowledgements
.chars()
.last()
.expect("acknowledgements is not the empty string")
!= '\n'
{
acknowledgements.push('\n');
}
// Add two more newlines to make it easy to distinguish where this text ends
// and the next starts
acknowledgements.push_str("\n\n");
}
/// Replaces newlines with a space character, and replaces multiple spaces with one space.
/// This makes the text easier to analyze.
fn normalize_license_text(license_text: &str) -> String {
use regex::Regex;
let whitespace_and_newlines = Regex::new(r"\s").unwrap();
let as_single_line = whitespace_and_newlines.replace_all(license_text, " ");
let many_spaces = Regex::new(" +").unwrap();
many_spaces.replace_all(&as_single_line, " ").to_string()
}
#[cfg(test)]
mod tests {
#[cfg(test)]
use super::*;
#[test]
fn test_normalize_license_text() {
let license_text = "This is a license text with these terms:
* Complicated multi-line
term with indentation";
assert_eq!(
"This is a license text with these terms: * Complicated multi-line term with indentation".to_owned(),
normalize_license_text(license_text),
);
}
#[test]
fn test_normalize_license_text_with_windows_line_endings() {
let license_text = "This license text includes windows line endings\r
and we need to handle that.";
assert_eq!(
"This license text includes windows line endings and we need to handle that."
.to_owned(),
normalize_license_text(license_text),
);
}
#[test]
fn test_append_to_acknowledgements_adds_newline_if_missing() {
let mut acknowledgements = "preamble\n\n\n".to_owned();
append_to_acknowledgements(&mut acknowledgements, "some/path", "line without newline");
assert_eq!(
"preamble
## some/path
line without newline
",
acknowledgements
);
append_to_acknowledgements(&mut acknowledgements, "another/path", "line with newline\n");
assert_eq!(
"preamble
## some/path
line without newline
## another/path
line with newline
",
acknowledgements
);
}
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/syntax_mapping/ignored_suffixes.rs | src/syntax_mapping/ignored_suffixes.rs | use std::ffi::OsStr;
use std::fmt::Debug;
use std::path::Path;
use crate::error::*;
#[derive(Debug, Clone)]
pub struct IgnoredSuffixes<'a> {
values: Vec<&'a str>,
}
impl Default for IgnoredSuffixes<'_> {
fn default() -> Self {
Self {
values: vec![
// Editor etc backups
"~",
".bak",
".old",
".orig",
// Debian and derivatives apt/dpkg/ucf backups
".dpkg-dist",
".dpkg-new",
".dpkg-old",
".dpkg-tmp",
".ucf-dist",
".ucf-new",
".ucf-old",
// Red Hat and derivatives rpm backups
".rpmnew",
".rpmorig",
".rpmsave",
// Build system input/template files
".in",
],
}
}
}
impl<'a> IgnoredSuffixes<'a> {
pub fn add_suffix(&mut self, suffix: &'a str) {
self.values.push(suffix)
}
pub fn strip_suffix(&self, file_name: &'a str) -> Option<&'a str> {
for suffix in self.values.iter() {
if let Some(stripped_file_name) = file_name.strip_suffix(suffix) {
return Some(stripped_file_name);
}
}
None
}
/// If we find an ignored suffix on the file name, e.g. '~', we strip it and
/// then try again without it.
pub fn try_with_stripped_suffix<T, F>(&self, file_name: &'a OsStr, func: F) -> Result<Option<T>>
where
F: Fn(&'a OsStr) -> Result<Option<T>>,
{
if let Some(file_str) = Path::new(file_name).to_str() {
if let Some(stripped_file_name) = self.strip_suffix(file_str) {
return func(OsStr::new(stripped_file_name));
}
}
Ok(None)
}
}
#[test]
fn internal_suffixes() {
let ignored_suffixes = IgnoredSuffixes::default();
let file_names = ignored_suffixes
.values
.iter()
.map(|suffix| format!("test.json{suffix}"));
for file_name_str in file_names {
let file_name = OsStr::new(&file_name_str);
let expected_stripped_file_name = OsStr::new("test.json");
let stripped_file_name = ignored_suffixes
.try_with_stripped_suffix(file_name, |stripped_file_name| Ok(Some(stripped_file_name)));
assert_eq!(
expected_stripped_file_name,
stripped_file_name.unwrap().unwrap()
);
}
}
#[test]
fn external_suffixes() {
let mut ignored_suffixes = IgnoredSuffixes::default();
ignored_suffixes.add_suffix(".development");
ignored_suffixes.add_suffix(".production");
let file_names = ignored_suffixes
.values
.iter()
.map(|suffix| format!("test.json{suffix}"));
for file_name_str in file_names {
let file_name = OsStr::new(&file_name_str);
let expected_stripped_file_name = OsStr::new("test.json");
let stripped_file_name = ignored_suffixes
.try_with_stripped_suffix(file_name, |stripped_file_name| Ok(Some(stripped_file_name)));
assert_eq!(
expected_stripped_file_name,
stripped_file_name.unwrap().unwrap()
);
}
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/syntax_mapping/builtin.rs | src/syntax_mapping/builtin.rs | use std::env;
use globset::GlobMatcher;
use once_cell::sync::Lazy;
use crate::syntax_mapping::{make_glob_matcher, MappingTarget};
// Static syntax mappings generated from /src/syntax_mapping/builtins/ by the
// build script (/build/syntax_mapping.rs).
include!(concat!(
env!("OUT_DIR"),
"/codegen_static_syntax_mappings.rs"
));
// The defined matcher strings are analysed at compile time and converted into
// lazily-compiled `GlobMatcher`s. This is so that the string searches are moved
// from run time to compile time, thus improving startup performance.
//
// To any future maintainer (including possibly myself) wondering why there is
// not a `BuiltinMatcher` enum that looks like this:
//
// ```
// enum BuiltinMatcher {
// Fixed(&'static str),
// Dynamic(Lazy<Option<String>>),
// }
// ```
//
// Because there was. I tried it and threw it out.
//
// Naively looking at the problem from a distance, this may seem like a good
// design (strongly typed etc. etc.). It would also save on compiled size by
// extracting out common behaviour into functions. But while actually
// implementing the lazy matcher compilation logic, I realised that it's most
// convenient for `BUILTIN_MAPPINGS` to have the following type:
//
// `[(Lazy<Option<GlobMatcher>>, MappingTarget); N]`
//
// The benefit for this is that operations like listing all builtin mappings
// would be effectively memoised. The caller would not have to compile another
// `GlobMatcher` for rules that they have previously visited.
//
// Unfortunately, this means we are going to have to store a distinct closure
// for each rule anyway, which makes a `BuiltinMatcher` enum a pointless layer
// of indirection.
//
// In the current implementation, the closure within each generated rule simply
// calls either `build_matcher_fixed` or `build_matcher_dynamic`, depending on
// whether the defined matcher contains dynamic segments or not.
/// Compile a fixed glob string into a glob matcher.
///
/// A failure to compile is a fatal error.
///
/// Used internally by `Lazy<Option<GlobMatcher>>`'s lazy evaluation closure.
fn build_matcher_fixed(from: &str) -> GlobMatcher {
make_glob_matcher(from).expect("A builtin fixed glob matcher failed to compile")
}
/// Join a list of matcher segments to create a glob string, replacing all
/// environment variables, then compile to a glob matcher.
///
/// Returns `None` if any replacement fails, or if the joined glob string fails
/// to compile.
///
/// Used internally by `Lazy<Option<GlobMatcher>>`'s lazy evaluation closure.
fn build_matcher_dynamic(segs: &[MatcherSegment]) -> Option<GlobMatcher> {
// join segments
let mut buf = String::new();
for seg in segs {
match seg {
MatcherSegment::Text(s) => buf.push_str(s),
MatcherSegment::Env(var) => {
let replaced = env::var(var).ok()?;
buf.push_str(&replaced);
}
}
}
// compile glob matcher
let matcher = make_glob_matcher(&buf).ok()?;
Some(matcher)
}
/// A segment of a dynamic builtin matcher.
///
/// Used internally by `Lazy<Option<GlobMatcher>>`'s lazy evaluation closure.
#[derive(Clone, Debug)]
enum MatcherSegment {
Text(&'static str),
Env(&'static str),
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/tests/no_duplicate_extensions.rs | tests/no_duplicate_extensions.rs | use std::collections::HashSet;
use bat::assets::HighlightingAssets;
#[test]
fn no_duplicate_extensions() {
const KNOWN_EXCEPTIONS: &[&str] = &[
// The '.h' extension currently appears in multiple syntaxes: C, C++, Objective C,
// Objective C++
"h",
// In addition to the standard JavaScript syntax in 'Packages', we also ship the
// 'Javascript (Babel)' syntax.
"js",
// The "Ruby Haml" syntax also comes with a '.sass' extension. However, we make sure
// that 'sass' is mapped to the 'Sass' syntax.
"sass",
// The '.fs' extension appears in F# and GLSL.
// We default to F#.
"fs",
// SystemVerilog and Verilog both use .v files.
// We default to Verilog.
"v",
];
let assets = HighlightingAssets::from_binary();
let mut extensions = HashSet::new();
for syntax in assets.get_syntaxes().expect("this is a #[test]") {
for extension in &syntax.file_extensions {
assert!(
KNOWN_EXCEPTIONS.contains(&extension.as_str()) || extensions.insert(extension),
"File extension / pattern \"{extension}\" appears twice in the syntax set"
);
}
}
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/tests/integration_tests.rs | tests/integration_tests.rs | use predicates::boolean::PredicateBooleanExt;
use predicates::{prelude::predicate, str::PredicateStrExt};
use serial_test::serial;
use std::path::Path;
use std::str::from_utf8;
use tempfile::tempdir;
#[cfg(unix)]
mod unix {
pub use std::fs::File;
pub use std::io::{self, Write};
pub use std::path::PathBuf;
pub use std::process::Stdio;
pub use std::thread;
pub use std::time::Duration;
pub use assert_cmd::assert::OutputAssertExt;
pub use nix::pty::{openpty, OpenptyResult};
pub use wait_timeout::ChildExt;
pub const SAFE_CHILD_PROCESS_CREATION_TIME: Duration = Duration::from_millis(100);
pub const CHILD_WAIT_TIMEOUT: Duration = Duration::from_secs(15);
}
#[cfg(unix)]
use unix::*;
mod utils;
use utils::command::{bat, bat_with_config};
#[cfg(unix)]
use utils::command::bat_raw_command;
use utils::mocked_pagers;
const EXAMPLES_DIR: &str = "tests/examples";
fn get_config() -> &'static str {
if cfg!(windows) {
"bat-windows.conf"
} else {
"bat.conf"
}
}
#[test]
fn basic() {
bat()
.arg("test.txt")
.assert()
.success()
.stdout("hello world\n")
.stderr("");
}
#[test]
fn stdin() {
bat()
.write_stdin("foo\nbar\n")
.assert()
.success()
.stdout("foo\nbar\n");
}
#[test]
fn concatenate() {
bat()
.arg("test.txt")
.arg("test.txt")
.assert()
.success()
.stdout("hello world\nhello world\n");
}
#[test]
fn concatenate_stdin() {
bat()
.arg("test.txt")
.arg("-")
.arg("test.txt")
.write_stdin("stdin\n")
.assert()
.success()
.stdout("hello world\nstdin\nhello world\n");
}
#[test]
fn concatenate_empty_first() {
bat()
.arg("empty.txt")
.arg("test.txt")
.assert()
.success()
.stdout("hello world\n");
}
#[test]
fn concatenate_empty_last() {
bat()
.arg("test.txt")
.arg("empty.txt")
.assert()
.success()
.stdout("hello world\n");
}
#[test]
fn concatenate_empty_both() {
bat()
.arg("empty.txt")
.arg("empty.txt")
.assert()
.success()
.stdout("");
}
#[test]
fn concatenate_empty_between() {
bat()
.arg("test.txt")
.arg("empty.txt")
.arg("test.txt")
.assert()
.success()
.stdout("hello world\nhello world\n");
}
#[test]
fn concatenate_empty_first_and_last() {
bat()
.arg("empty.txt")
.arg("test.txt")
.arg("empty.txt")
.assert()
.success()
.stdout("hello world\n");
}
#[test]
fn concatenate_single_line() {
bat()
.arg("single-line.txt")
.arg("single-line.txt")
.assert()
.success()
.stdout("Single LineSingle Line");
}
#[test]
fn concatenate_single_line_empty() {
bat()
.arg("single-line.txt")
.arg("empty.txt")
.arg("single-line.txt")
.assert()
.success()
.stdout("Single LineSingle Line");
}
#[test]
fn line_numbers() {
bat()
.arg("multiline.txt")
.arg("--style=numbers")
.arg("--decorations=always")
.assert()
.success()
.stdout(" 1 line 1\n 2 line 2\n 3 line 3\n 4 line 4\n 5 line 5\n 6 line 6\n 7 line 7\n 8 line 8\n 9 line 9\n 10 line 10\n");
}
// Test that -n on command line shows line numbers even when piping (similar to `cat -n`)
#[test]
fn line_numbers_from_cli_in_loop_through_mode() {
bat()
.arg("multiline.txt")
.arg("-n")
.assert()
.success()
.stdout(" 1 line 1\n 2 line 2\n 3 line 3\n 4 line 4\n 5 line 5\n 6 line 6\n 7 line 7\n 8 line 8\n 9 line 9\n 10 line 10\n");
}
#[test]
fn style_from_env_var_ignored_and_line_numbers_from_cli_in_loop_through_mode() {
bat()
.env("BAT_STYLE", "full")
.arg("multiline.txt")
.arg("-n")
.arg("--decorations=auto")
.assert()
.success()
.stdout(" 1 line 1\n 2 line 2\n 3 line 3\n 4 line 4\n 5 line 5\n 6 line 6\n 7 line 7\n 8 line 8\n 9 line 9\n 10 line 10\n");
}
#[test]
fn numbers_ignored_from_cli_when_followed_by_plain_in_loop_through_mode() {
bat()
.arg("multiline.txt")
.arg("-np")
.arg("--decorations=auto")
.assert()
.success()
.stdout(
"line 1\nline 2\nline 3\nline 4\nline 5\nline 6\nline 7\nline 8\nline 9\nline 10\n",
);
}
#[test]
fn numbers_honored_from_cli_when_preceeded_by_plain_in_loop_through_mode() {
bat()
.arg("multiline.txt")
.arg("-pn")
.arg("--decorations=auto")
.assert()
.success()
.stdout(" 1 line 1\n 2 line 2\n 3 line 3\n 4 line 4\n 5 line 5\n 6 line 6\n 7 line 7\n 8 line 8\n 9 line 9\n 10 line 10\n");
}
#[test]
fn line_range_2_3() {
bat()
.arg("multiline.txt")
.arg("--line-range=2:3")
.assert()
.success()
.stdout("line 2\nline 3\n");
}
#[test]
fn line_range_up_to_2_from_back() {
bat()
.arg("multiline.txt")
.arg("--line-range=:-2")
.assert()
.success()
.stdout("line 1\nline 2\nline 3\nline 4\nline 5\nline 6\nline 7\nline 8\n");
}
#[test]
fn line_range_up_to_2_from_back_single_line_is_empty() {
bat()
.arg("single-line.txt")
.arg("--line-range=:-2")
.assert()
.success()
.stdout("");
}
#[test]
fn line_range_from_back_last_two() {
bat()
.arg("multiline.txt")
.arg("--line-range=-2:")
.assert()
.success()
.stdout("line 9\nline 10\n");
}
#[test]
fn line_range_from_back_last_two_single_line_eq_sep() {
bat()
.arg("single-line.txt")
.arg("--line-range=-2:")
.assert()
.success()
.stdout("Single Line");
}
#[test]
fn line_range_from_back_last_two_single_line_no_sep() {
bat()
.arg("single-line.txt")
.arg("--line-range")
.arg("-2:")
.assert()
.success()
.stdout("Single Line");
}
#[test]
fn line_range_first_two() {
bat()
.arg("multiline.txt")
.arg("--line-range=:2")
.assert()
.success()
.stdout("line 1\nline 2\n");
}
#[test]
fn line_range_last_3() {
bat()
.arg("multiline.txt")
.arg("--line-range=8:")
.assert()
.success()
.stdout("line 8\nline 9\nline 10\n");
}
#[test]
fn line_range_multiple() {
bat()
.arg("multiline.txt")
.arg("--line-range=1:2")
.arg("--line-range=4:4")
.assert()
.success()
.stdout("line 1\nline 2\nline 4\n");
}
#[test]
fn line_range_multiple_with_context() {
bat()
.arg("multiline.txt")
.arg("--line-range=2::1")
.arg("--line-range=8::1")
.assert()
.success()
.stdout("line 1\nline 2\nline 3\nline 7\nline 8\nline 9\n");
}
#[test]
fn line_range_context_around_single_line() {
bat()
.arg("multiline.txt")
.arg("--line-range=5::2")
.assert()
.success()
.stdout("line 3\nline 4\nline 5\nline 6\nline 7\n");
}
#[test]
fn line_range_context_around_single_line_minimal() {
bat()
.arg("multiline.txt")
.arg("--line-range=5::1")
.assert()
.success()
.stdout("line 4\nline 5\nline 6\n");
}
#[test]
fn line_range_context_around_range() {
bat()
.arg("multiline.txt")
.arg("--line-range=4:6:2")
.assert()
.success()
.stdout("line 2\nline 3\nline 4\nline 5\nline 6\nline 7\nline 8\n");
}
#[test]
fn line_range_context_at_file_boundaries() {
bat()
.arg("multiline.txt")
.arg("--line-range=1::2")
.assert()
.success()
.stdout("line 1\nline 2\nline 3\n");
}
#[test]
fn line_range_context_at_end_of_file() {
bat()
.arg("multiline.txt")
.arg("--line-range=10::2")
.assert()
.success()
.stdout("line 8\nline 9\nline 10\n");
}
#[test]
fn line_range_context_zero() {
bat()
.arg("multiline.txt")
.arg("--line-range=5::0")
.assert()
.success()
.stdout("line 5\n");
}
#[test]
fn line_range_context_negative_single_line() {
bat()
.arg("multiline.txt")
.arg("--line-range=5::-1")
.assert()
.failure()
.stderr(predicate::str::contains(
"Invalid context number in N::C format",
));
}
#[test]
fn line_range_context_negative_range() {
bat()
.arg("multiline.txt")
.arg("--line-range=5:6:-1")
.assert()
.failure()
.stderr(predicate::str::contains(
"Invalid context number in N:M:C format",
));
}
#[test]
fn line_range_context_non_numeric_single_line() {
bat()
.arg("multiline.txt")
.arg("--line-range=10::abc")
.assert()
.failure()
.stderr(predicate::str::contains(
"Invalid context number in N::C format",
));
}
#[test]
fn line_range_context_non_numeric_range() {
bat()
.arg("multiline.txt")
.arg("--line-range=10:12:xyz")
.assert()
.failure()
.stderr(predicate::str::contains(
"Invalid context number in N:M:C format",
));
}
#[test]
fn line_range_context_very_large() {
bat()
.arg("multiline.txt")
.arg("--line-range=10::999999")
.assert()
.success()
.stdout(
"line 1\nline 2\nline 3\nline 4\nline 5\nline 6\nline 7\nline 8\nline 9\nline 10\n",
);
}
#[test]
fn piped_output_with_implicit_auto_style() {
bat()
.write_stdin("hello\nworld\n")
.assert()
.success()
.stdout("hello\nworld\n");
}
#[test]
fn piped_output_with_line_number_flag() {
bat()
.arg("--number")
.write_stdin("hello\nworld\n")
.assert()
.success()
.stdout(" 1 hello\n 2 world\n");
}
#[test]
fn piped_output_with_line_numbers_style_flag() {
bat()
.arg("--style=numbers")
.write_stdin("hello\nworld\n")
.assert()
.success()
.stdout("hello\nworld\n");
}
#[test]
fn piped_output_with_line_numbers_with_header_grid_style_flag() {
// style ignored because non-interactive
bat()
.arg("--style=header,grid,numbers")
.write_stdin("hello\nworld\n")
.assert()
.success()
.stdout("hello\nworld\n");
}
#[test]
fn piped_output_with_auto_style() {
bat()
.arg("--style=auto")
.write_stdin("hello\nworld\n")
.assert()
.success()
.stdout("hello\nworld\n"); // Should be plain when piped
}
#[test]
#[cfg(not(target_os = "windows"))]
fn piped_output_with_default_style_flag() {
bat()
.arg("--style=default")
.arg("--decorations=always")
.write_stdin("hello\nworld\n")
.assert()
.success()
.stdout(
"─────┬──────────────────────────────────────────────────────────────────────────
│ STDIN
─────┼──────────────────────────────────────────────────────────────────────────
1 │ hello
2 │ world
─────┴──────────────────────────────────────────────────────────────────────────
",
);
}
#[test]
fn squeeze_blank() {
bat()
.arg("empty_lines.txt")
.arg("--squeeze-blank")
.assert()
.success()
.stdout("line 1\n\nline 5\n\nline 20\nline 21\n\nline 24\n\nline 26\n\nline 30\n");
}
#[test]
fn squeeze_blank_line_numbers() {
bat()
.arg("empty_lines.txt")
.arg("--squeeze-blank")
.arg("--decorations=always")
.arg("--number")
.assert()
.success()
.stdout(" 1 line 1\n 2 \n 5 line 5\n 6 \n 20 line 20\n 21 line 21\n 22 \n 24 line 24\n 25 \n 26 line 26\n 27 \n 30 line 30\n");
}
#[test]
fn squeeze_limit() {
bat()
.arg("empty_lines.txt")
.arg("--squeeze-blank")
.arg("--squeeze-limit=2")
.assert()
.success()
.stdout("line 1\n\n\nline 5\n\n\nline 20\nline 21\n\n\nline 24\n\nline 26\n\n\nline 30\n");
bat()
.arg("empty_lines.txt")
.arg("--squeeze-blank")
.arg("--squeeze-limit=5")
.assert()
.success()
.stdout("line 1\n\n\n\nline 5\n\n\n\n\n\nline 20\nline 21\n\n\nline 24\n\nline 26\n\n\n\nline 30\n");
}
#[test]
fn squeeze_limit_line_numbers() {
bat()
.arg("empty_lines.txt")
.arg("--squeeze-blank")
.arg("--squeeze-limit=2")
.arg("--decorations=always")
.arg("--number")
.assert()
.success()
.stdout(" 1 line 1\n 2 \n 3 \n 5 line 5\n 6 \n 7 \n 20 line 20\n 21 line 21\n 22 \n 23 \n 24 line 24\n 25 \n 26 line 26\n 27 \n 28 \n 30 line 30\n");
bat()
.arg("empty_lines.txt")
.arg("--squeeze-blank")
.arg("--squeeze-limit=5")
.arg("--decorations=always")
.arg("--number")
.assert()
.success()
.stdout(" 1 line 1\n 2 \n 3 \n 4 \n 5 line 5\n 6 \n 7 \n 8 \n 9 \n 10 \n 20 line 20\n 21 line 21\n 22 \n 23 \n 24 line 24\n 25 \n 26 line 26\n 27 \n 28 \n 29 \n 30 line 30\n");
}
#[test]
fn list_themes_with_colors() {
let default_theme_chunk = "Monokai Extended\x1B[0m (default)";
let default_light_theme_chunk = "Monokai Extended Light\x1B[0m (default light)";
bat()
.arg("--color=always")
.arg("--list-themes")
.assert()
.success()
.stdout(predicate::str::contains("DarkNeon").normalize())
.stdout(predicate::str::contains(default_theme_chunk).normalize())
.stdout(predicate::str::contains(default_light_theme_chunk).normalize())
.stdout(predicate::str::contains("Output the square of a number.").normalize());
}
#[test]
fn list_themes_without_colors() {
let default_theme_chunk = "Monokai Extended (default)";
let default_light_theme_chunk = "Monokai Extended Light (default light)";
bat()
.arg("--color=never")
.arg("--decorations=always") // trick bat into setting `Config::loop_through` to false
.arg("--list-themes")
.assert()
.success()
.stdout(predicate::str::contains("DarkNeon").normalize())
.stdout(predicate::str::contains(default_theme_chunk).normalize())
.stdout(predicate::str::contains(default_light_theme_chunk).normalize());
}
#[test]
fn list_themes_to_piped_output() {
bat().arg("--list-themes").assert().success().stdout(
predicate::str::contains("(default)")
.not()
.and(predicate::str::contains("(default light)").not())
.and(predicate::str::contains("(default dark)").not()),
);
}
#[test]
fn list_languages() {
bat()
.arg("--list-languages")
.assert()
.success()
.stdout(predicate::str::contains("Rust").normalize());
}
#[test]
#[cfg_attr(
any(not(feature = "git"), feature = "lessopen", target_os = "windows"),
ignore
)]
fn short_help() {
test_help("-h", "../doc/short-help.txt");
}
#[test]
#[cfg_attr(
any(not(feature = "git"), feature = "lessopen", target_os = "windows"),
ignore
)]
fn long_help() {
test_help("--help", "../doc/long-help.txt");
}
fn test_help(arg: &str, expect_file: &str) {
let assert = bat().arg(arg).assert();
expect_test::expect_file![expect_file]
.assert_eq(&String::from_utf8_lossy(&assert.get_output().stdout));
}
#[test]
fn short_help_with_highlighting() {
bat()
.arg("-h")
.arg("--paging=never")
.arg("--color=always")
.assert()
.success()
.stdout(predicate::str::contains("\x1B["))
.stdout(predicate::str::contains("Usage:"))
.stdout(predicate::str::contains("Options:"));
}
#[test]
fn long_help_with_highlighting() {
bat()
.arg("--help")
.arg("--paging=never")
.arg("--color=always")
.assert()
.success()
.stdout(predicate::str::contains("\x1B["))
.stdout(predicate::str::contains("Usage:"))
.stdout(predicate::str::contains("Options:"));
}
#[test]
fn help_with_color_never() {
bat()
.arg("--help")
.arg("--color=never")
.arg("--paging=never")
.assert()
.success()
.stdout(predicate::str::contains("\x1B[").not())
.stdout(predicate::str::contains("Usage:"));
}
#[cfg(unix)]
fn setup_temp_file(content: &[u8]) -> io::Result<(PathBuf, tempfile::TempDir)> {
let dir = tempfile::tempdir().expect("Couldn't create tempdir");
let path = dir.path().join("temp_file");
File::create(&path)?.write_all(content)?;
Ok((path, dir))
}
#[cfg(unix)]
#[test]
fn basic_io_cycle() -> io::Result<()> {
let (filename, dir) = setup_temp_file(b"I am not empty")?;
let file_out = Stdio::from(File::create(&filename)?);
let res = bat_raw_command()
.arg("test.txt")
.arg(&filename)
.stdout(file_out)
.assert();
drop(dir);
res.failure();
Ok(())
}
#[cfg(unix)]
#[test]
fn first_file_cyclic_is_ok() -> io::Result<()> {
let (filename, dir) = setup_temp_file(b"I am not empty")?;
let file_out = Stdio::from(File::create(&filename)?);
let res = bat_raw_command()
.arg(&filename)
.arg("test.txt")
.stdout(file_out)
.assert();
drop(dir);
res.success();
Ok(())
}
#[cfg(unix)]
#[test]
fn empty_file_cycle_is_ok() -> io::Result<()> {
let (filename, dir) = setup_temp_file(b"I am not empty")?;
let file_out = Stdio::from(File::create(&filename)?);
let res = bat_raw_command()
.arg("empty.txt")
.arg(&filename)
.stdout(file_out)
.assert();
drop(dir);
res.success();
Ok(())
}
#[cfg(unix)]
#[test]
fn stdin_to_stdout_cycle() -> io::Result<()> {
let (filename, dir) = setup_temp_file(b"I am not empty")?;
let file_in = Stdio::from(File::open(&filename)?);
let file_out = Stdio::from(File::create(&filename)?);
let res = bat_raw_command()
.arg("test.txt")
.arg("-")
.stdin(file_in)
.stdout(file_out)
.assert();
drop(dir);
res.failure();
Ok(())
}
#[cfg(unix)]
#[test]
fn bat_error_to_stderr() {
bat()
.arg("/tmp")
.assert()
.failure()
.stderr(predicate::str::contains("[bat error]"));
}
#[cfg(unix)]
#[test]
fn no_args_doesnt_break() {
// To simulate bat getting started from the shell, a process is created with stdin and stdout
// as the slave end of a pseudo terminal. Although both point to the same "file", bat should
// not exit, because in this case it is safe to read and write to the same fd, which is why
// this test exists.
let OpenptyResult { master, slave } = openpty(None, None).expect("Couldn't open pty.");
let mut master = File::from(master);
let stdin_file = File::from(slave);
let stdout_file = stdin_file.try_clone().unwrap();
let stdin = Stdio::from(stdin_file);
let stdout = Stdio::from(stdout_file);
let mut child = bat_raw_command()
.stdin(stdin)
.stdout(stdout)
.env("TERM", "dumb") // Suppresses color detection
.spawn()
.expect("Failed to start.");
// Some time for the child process to start and to make sure, that we can poll the exit status.
// Although this waiting period is not necessary, it is best to keep it in and be absolutely
// sure, that the try_wait does not error later.
thread::sleep(SAFE_CHILD_PROCESS_CREATION_TIME);
// The child process should be running and waiting for input,
// therefore no exit status should be available.
let exit_status = child
.try_wait()
.expect("Error polling exit status, this should never happen.");
assert!(exit_status.is_none());
// Write Ctrl-D (end of transmission) to the pty.
master
.write_all(&[0x04])
.expect("Couldn't write EOT character to master end.");
let exit_status = child
.wait_timeout(CHILD_WAIT_TIMEOUT)
.expect("Error polling exit status, this should never happen.")
.expect("Exit status not set, but the child should have exited already.");
assert!(exit_status.success());
}
#[test]
fn tabs_numbers() {
bat()
.arg("tabs.txt")
.arg("--tabs=4")
.arg("--style=numbers")
.arg("--decorations=always")
.assert()
.success()
.stdout(
" 1 1 2 3 4
2 1 ?
3 22 ?
4 333 ?
5 4444 ?
6 55555 ?
7 666666 ?
8 7777777 ?
9 88888888 ?
",
);
}
#[test]
fn tabs_passthrough_wrapped() {
bat()
.arg("tabs.txt")
.arg("--tabs=0")
.arg("--style=plain")
.arg("--decorations=always")
.assert()
.success()
.stdout(
" 1 2 3 4
1 ?
22 ?
333 ?
4444 ?
55555 ?
666666 ?
7777777 ?
88888888 ?
",
);
}
#[test]
fn tabs_4_wrapped() {
bat()
.arg("tabs.txt")
.arg("--tabs=4")
.arg("--style=plain")
.arg("--decorations=always")
.assert()
.success()
.stdout(
" 1 2 3 4
1 ?
22 ?
333 ?
4444 ?
55555 ?
666666 ?
7777777 ?
88888888 ?
",
);
}
#[test]
fn tabs_8_wrapped() {
bat()
.arg("tabs.txt")
.arg("--tabs=8")
.arg("--style=plain")
.arg("--decorations=always")
.assert()
.success()
.stdout(
" 1 2 3 4
1 ?
22 ?
333 ?
4444 ?
55555 ?
666666 ?
7777777 ?
88888888 ?
",
);
}
#[test]
fn tabs_passthrough() {
bat()
.arg("tabs.txt")
.arg("--tabs=0")
.arg("--style=plain")
.arg("--decorations=always")
.assert()
.success()
.stdout(
" 1 2 3 4
1 ?
22 ?
333 ?
4444 ?
55555 ?
666666 ?
7777777 ?
88888888 ?
",
);
}
#[test]
fn tabs_4() {
bat()
.arg("tabs.txt")
.arg("--tabs=4")
.arg("--style=plain")
.arg("--decorations=always")
.assert()
.success()
.stdout(
" 1 2 3 4
1 ?
22 ?
333 ?
4444 ?
55555 ?
666666 ?
7777777 ?
88888888 ?
",
);
}
#[test]
fn tabs_8() {
bat()
.arg("tabs.txt")
.arg("--tabs=8")
.arg("--style=plain")
.arg("--decorations=always")
.assert()
.success()
.stdout(
" 1 2 3 4
1 ?
22 ?
333 ?
4444 ?
55555 ?
666666 ?
7777777 ?
88888888 ?
",
);
}
#[test]
fn tabs_4_env_overrides_config() {
bat_with_config()
.env("BAT_CONFIG_PATH", "bat-tabs.conf")
.env("BAT_TABS", "4")
.arg("tabs.txt")
.arg("--style=plain")
.arg("--decorations=always")
.assert()
.success()
.stdout(
" 1 2 3 4
1 ?
22 ?
333 ?
4444 ?
55555 ?
666666 ?
7777777 ?
88888888 ?
",
);
}
#[test]
fn tabs_4_arg_overrides_env() {
bat_with_config()
.env("BAT_CONFIG_PATH", "bat-tabs.conf")
.env("BAT_TABS", "6")
.arg("tabs.txt")
.arg("--tabs=4")
.arg("--style=plain")
.arg("--decorations=always")
.assert()
.success()
.stdout(
" 1 2 3 4
1 ?
22 ?
333 ?
4444 ?
55555 ?
666666 ?
7777777 ?
88888888 ?
",
);
}
#[test]
fn tabs_4_arg_overrides_env_noconfig() {
bat()
.env("BAT_TABS", "6")
.arg("tabs.txt")
.arg("--tabs=4")
.arg("--style=plain")
.arg("--decorations=always")
.assert()
.success()
.stdout(
" 1 2 3 4
1 ?
22 ?
333 ?
4444 ?
55555 ?
666666 ?
7777777 ?
88888888 ?
",
);
}
#[test]
fn fail_non_existing() {
bat().arg("non-existing-file").assert().failure();
}
#[test]
fn fail_directory() {
bat().arg("sub_directory").assert().failure();
}
#[test]
fn do_not_exit_directory() {
bat()
.arg("sub_directory")
.arg("test.txt")
.assert()
.stdout("hello world\n")
.failure();
}
#[test]
#[serial]
fn pager_basic() {
mocked_pagers::with_mocked_versions_of_more_and_most_in_path(|| {
bat()
.env("PAGER", mocked_pagers::from("echo pager-output"))
.arg("--paging=always")
.arg("test.txt")
.assert()
.success()
.stdout(predicate::str::contains("pager-output\n").normalize());
});
}
#[test]
#[serial]
fn pager_basic_arg() {
mocked_pagers::with_mocked_versions_of_more_and_most_in_path(|| {
bat()
.arg(format!(
"--pager={}",
mocked_pagers::from("echo pager-output")
))
.arg("--paging=always")
.arg("test.txt")
.assert()
.success()
.stdout(predicate::str::contains("pager-output\n").normalize());
});
}
#[test]
#[serial]
fn pager_overwrite() {
mocked_pagers::with_mocked_versions_of_more_and_most_in_path(|| {
bat()
.env("PAGER", mocked_pagers::from("echo other-pager"))
.env("BAT_PAGER", mocked_pagers::from("echo pager-output"))
.arg("--paging=always")
.arg("test.txt")
.assert()
.success()
.stdout(predicate::str::contains("pager-output\n").normalize());
});
}
#[test]
fn pager_disable() {
bat()
.env("PAGER", "echo other-pager")
.env("BAT_PAGER", "")
.arg("--paging=always")
.arg("test.txt")
.assert()
.success()
.stdout(predicate::eq("hello world\n").normalize());
}
#[test]
#[serial]
fn pager_arg_override_env_withconfig() {
mocked_pagers::with_mocked_versions_of_more_and_most_in_path(|| {
bat_with_config()
.env("BAT_CONFIG_PATH", get_config())
.env("PAGER", mocked_pagers::from("echo another-pager"))
.env("BAT_PAGER", mocked_pagers::from("echo other-pager"))
.arg(format!(
"--pager={}",
mocked_pagers::from("echo pager-output")
))
.arg("--paging=always")
.arg("test.txt")
.assert()
.success()
.stdout(predicate::str::contains("pager-output\n").normalize());
});
}
#[test]
#[serial]
fn pager_arg_override_env_noconfig() {
mocked_pagers::with_mocked_versions_of_more_and_most_in_path(|| {
bat()
.env("PAGER", mocked_pagers::from("echo another-pager"))
.env("BAT_PAGER", mocked_pagers::from("echo other-pager"))
.arg(format!(
"--pager={}",
mocked_pagers::from("echo pager-output")
))
.arg("--paging=always")
.arg("test.txt")
.assert()
.success()
.stdout(predicate::str::contains("pager-output\n").normalize());
});
}
#[test]
#[serial]
fn pager_env_bat_pager_override_config() {
mocked_pagers::with_mocked_versions_of_more_and_most_in_path(|| {
bat_with_config()
.env("BAT_CONFIG_PATH", get_config())
.env("PAGER", mocked_pagers::from("echo other-pager"))
.env("BAT_PAGER", mocked_pagers::from("echo pager-output"))
.arg("--paging=always")
.arg("test.txt")
.assert()
.success()
.stdout(predicate::str::contains("pager-output\n").normalize());
});
}
#[test]
#[serial]
fn pager_env_pager_nooverride_config() {
mocked_pagers::with_mocked_versions_of_more_and_most_in_path(|| {
bat_with_config()
.env("BAT_CONFIG_PATH", get_config())
.env("PAGER", mocked_pagers::from("echo other-pager"))
.arg("--paging=always")
.arg("test.txt")
.assert()
.success()
.stdout(predicate::str::contains("dummy-pager-from-config\n").normalize());
});
}
#[test]
fn env_var_pager_value_bat() {
bat()
.env("PAGER", "bat")
.arg("--paging=always")
.arg("test.txt")
.assert()
.success()
.stdout(predicate::eq("hello world\n").normalize());
}
#[test]
fn env_var_bat_pager_value_bat() {
bat()
.env("BAT_PAGER", "bat")
.arg("--paging=always")
.arg("test.txt")
.assert()
.failure()
.stderr(predicate::str::contains("bat as a pager is disallowed"));
}
#[test]
fn pager_value_bat() {
bat()
.arg("--pager=bat")
.arg("--paging=always")
.arg("test.txt")
.assert()
.failure()
.stderr(predicate::str::contains("bat as a pager is disallowed"));
}
/// We shall use less instead of most if PAGER is used since PAGER
/// is a generic env var
#[test]
#[serial] // Because of PATH
fn pager_most_from_pager_env_var() {
mocked_pagers::with_mocked_versions_of_more_and_most_in_path(|| {
// If the output is not "I am most" then we know 'most' is not used
bat()
.env("PAGER", mocked_pagers::from("most"))
.arg("--paging=always")
.arg("test.txt")
.assert()
.success()
.stdout(predicate::eq("hello world\n").normalize());
});
}
/// If the bat-specific BAT_PAGER is used, obey the wish of the user
/// and allow 'most'
#[test]
#[serial] // Because of PATH
fn pager_most_from_bat_pager_env_var() {
mocked_pagers::with_mocked_versions_of_more_and_most_in_path(|| {
bat()
.env("BAT_PAGER", mocked_pagers::from("most"))
.arg("--paging=always")
.arg("test.txt")
.assert()
.success()
.stdout(predicate::str::contains("I am most"));
});
}
/// Same reasoning with --pager as with BAT_PAGER
#[test]
#[serial] // Because of PATH
fn pager_most_from_pager_arg() {
mocked_pagers::with_mocked_versions_of_more_and_most_in_path(|| {
bat()
.arg("--paging=always")
.arg(format!("--pager={}", mocked_pagers::from("most")))
.arg("test.txt")
.assert()
.success()
.stdout(predicate::str::contains("I am most"));
});
}
/// Make sure the logic for 'most' applies even if an argument is passed
#[test]
#[serial] // Because of PATH
fn pager_most_with_arg() {
mocked_pagers::with_mocked_versions_of_more_and_most_in_path(|| {
bat()
.env("PAGER", format!("{} -w", mocked_pagers::from("most")))
.arg("--paging=always")
.arg("test.txt")
.assert()
.success()
.stdout(predicate::eq("hello world\n").normalize());
});
}
/// Sanity check that 'more' is treated like 'most'
#[test]
#[serial] // Because of PATH
fn pager_more() {
mocked_pagers::with_mocked_versions_of_more_and_most_in_path(|| {
bat()
.env("PAGER", mocked_pagers::from("more"))
.arg("--paging=always")
.arg("test.txt")
.assert()
.success()
.stdout(predicate::eq("hello world\n").normalize());
});
}
#[test]
fn alias_pager_disable() {
bat()
.env("PAGER", "echo other-pager")
.arg("-P")
.arg("test.txt")
.assert()
.success()
.stdout(predicate::eq("hello world\n").normalize());
}
#[test]
#[serial]
fn alias_pager_disable_long_overrides_short() {
mocked_pagers::with_mocked_versions_of_more_and_most_in_path(|| {
bat()
.env("PAGER", mocked_pagers::from("echo pager-output"))
.arg("-P")
.arg("--paging=always")
.arg("test.txt")
.assert()
.success()
.stdout(predicate::str::contains("pager-output\n").normalize());
});
}
#[test]
fn disable_pager_if_disable_paging_flag_comes_after_paging() {
bat()
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | true |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/tests/test_pretty_printer.rs | tests/test_pretty_printer.rs | use bat::PrettyPrinter;
#[test]
fn syntaxes() {
let printer = PrettyPrinter::new();
let syntaxes: Vec<String> = printer.syntaxes().map(|s| s.name).collect();
// Just do some sanity checking
assert!(syntaxes.contains(&"Rust".to_string()));
assert!(syntaxes.contains(&"Java".to_string()));
assert!(!syntaxes.contains(&"this-language-does-not-exist".to_string()));
// This language exists but is hidden, so we should not see it; it shall
// have been filtered out before getting to us
assert!(!syntaxes.contains(&"Git Common".to_string()));
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/tests/github-actions.rs | tests/github-actions.rs | #[test]
fn all_jobs_not_missing_any_jobs() {
let yaml: serde_yaml::Value =
serde_yaml::from_reader(std::fs::File::open(".github/workflows/CICD.yml").unwrap())
.unwrap();
let jobs = yaml.get("jobs").unwrap();
// Get all jobs that all-jobs depends on:
//
// jobs:
// all-jobs:
// needs:
// - this
// - list
// - ...
let actual = jobs
.get("all-jobs")
.unwrap()
.get("needs")
.unwrap()
.as_sequence()
.unwrap();
// Get all jobs used in CI, except the ones we want to ignore:
//
// jobs:
// this: ...
// list: ...
// ...
let exceptions = [
"all-jobs", // 'all-jobs' should not reference itself
"winget", // only used when publishing a release
];
let expected = jobs
.as_mapping()
.unwrap()
.keys()
.filter(|k| !exceptions.contains(&k.as_str().unwrap_or_default()))
.map(ToOwned::to_owned)
.collect::<Vec<_>>();
// Make sure they match
assert_eq!(
*actual, expected,
"`all-jobs` should depend on all other jobs"
);
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/tests/assets.rs | tests/assets.rs | use bat::assets::HighlightingAssets;
/// This test ensures that we are not accidentally removing themes due to submodule updates.
/// It is 'ignore'd by default because it requires themes.bin to be up-to-date.
#[test]
#[ignore]
fn all_themes_are_present() {
let assets = HighlightingAssets::from_binary();
let mut themes: Vec<_> = assets.themes().collect();
themes.sort_unstable();
assert_eq!(
themes,
vec![
"1337",
"Catppuccin Frappe",
"Catppuccin Latte",
"Catppuccin Macchiato",
"Catppuccin Mocha",
"Coldark-Cold",
"Coldark-Dark",
"DarkNeon",
"Dracula",
"GitHub",
"Monokai Extended",
"Monokai Extended Bright",
"Monokai Extended Light",
"Monokai Extended Origin",
"Nord",
"OneHalfDark",
"OneHalfLight",
"Solarized (dark)",
"Solarized (light)",
"Sublime Snazzy",
"TwoDark",
"Visual Studio Dark+",
"ansi",
"base16",
"base16-256",
"gruvbox-dark",
"gruvbox-light",
"zenburn"
]
);
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/tests/system_wide_config.rs | tests/system_wide_config.rs | use predicates::{prelude::predicate, str::PredicateStrExt};
mod utils;
use utils::command::bat_with_config;
// This test is ignored, as it needs a special system wide config put into place.
// In order to run this tests, use `cargo test --test system_wide_config -- --ignored`
#[test]
#[ignore]
fn use_systemwide_config() {
bat_with_config()
.arg("test.txt")
.assert()
.success()
.stdout(predicate::eq("dummy-pager-from-system-config\n").normalize());
}
// This test is ignored, as it needs a special system wide config put into place
// In order to run this tests, use `cargo test --test system_wide_config -- --ignored`
#[test]
#[ignore]
fn config_overrides_system_config() {
bat_with_config()
.env("BAT_CONFIG_PATH", "bat.conf")
.arg("test.txt")
.assert()
.success()
.stdout(predicate::eq("dummy-pager-from-config\n").normalize());
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/tests/snapshot_tests.rs | tests/snapshot_tests.rs | #[cfg(feature = "git")]
mod tester;
macro_rules! snapshot_tests {
($($test_name: ident: $style: expr,)*) => {
$(
#[test]
#[cfg(feature = "git")]
fn $test_name() {
let bat_tester = tester::BatTester::default();
bat_tester.test_snapshot(stringify!($test_name), $style);
}
)*
};
}
snapshot_tests! {
changes: "changes",
grid: "grid",
header: "header",
numbers: "numbers",
rule: "rule",
changes_grid: "changes,grid",
changes_header: "changes,header",
changes_numbers: "changes,numbers",
changes_rule: "changes,rule",
grid_header: "grid,header",
grid_numbers: "grid,numbers",
grid_rule: "grid,rule",
header_numbers: "header,numbers",
header_rule: "header,rule",
changes_grid_header: "changes,grid,header",
changes_grid_numbers: "changes,grid,numbers",
changes_grid_rule: "changes,grid,rule",
changes_header_numbers: "changes,header,numbers",
changes_header_rule: "changes,header,rule",
grid_header_numbers: "grid,header,numbers",
grid_header_rule: "grid,header,rule",
header_numbers_rule: "header,numbers,rule",
changes_grid_header_numbers: "changes,grid,header,numbers",
changes_grid_header_rule: "changes,grid,header,rule",
changes_grid_header_numbers_rule: "changes,grid,header,numbers,rule",
full: "full",
plain: "plain",
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/tests/utils/command.rs | tests/utils/command.rs | #![allow(unused)] // Because indirectly included by e.g.integration_tests.rs, but not everything inside is used
use assert_cmd::cargo::CommandCargoExt;
use std::process::Command;
pub fn bat_raw_command_with_config() -> Command {
let mut cmd = Command::cargo_bin("bat").unwrap();
cmd.current_dir("tests/examples");
cmd.env_remove("BAT_CACHE_PATH");
cmd.env_remove("BAT_CONFIG_DIR");
cmd.env_remove("BAT_CONFIG_PATH");
cmd.env_remove("BAT_OPTS");
cmd.env_remove("BAT_PAGER");
cmd.env_remove("BAT_STYLE");
cmd.env_remove("BAT_TABS");
cmd.env_remove("BAT_THEME");
cmd.env_remove("COLORTERM");
cmd.env_remove("NO_COLOR");
cmd.env_remove("PAGER");
cmd.env_remove("LESSOPEN");
cmd.env_remove("LESSCLOSE");
cmd.env_remove("SHELL");
cmd
}
#[cfg(test)]
pub fn bat_raw_command() -> Command {
let mut cmd = bat_raw_command_with_config();
cmd.arg("--no-config");
cmd
}
#[cfg(test)]
pub fn bat_with_config() -> assert_cmd::Command {
assert_cmd::Command::from_std(bat_raw_command_with_config())
}
#[cfg(test)]
pub fn bat() -> assert_cmd::Command {
assert_cmd::Command::from_std(bat_raw_command())
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/tests/utils/mod.rs | tests/utils/mod.rs | pub mod command;
pub mod mocked_pagers;
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/tests/utils/mocked_pagers.rs | tests/utils/mocked_pagers.rs | #![allow(unused)] // Because indirectly included by e.g. system_wide_config.rs, but not used
use assert_cmd::Command;
use predicates::prelude::predicate;
use std::env;
use std::path::{Path, PathBuf};
/// For some tests we want mocked versions of some pagers
/// This fn returns the absolute path to the directory with these mocked pagers
fn get_mocked_pagers_dir() -> PathBuf {
let cargo_manifest_dir = env::var("CARGO_MANIFEST_DIR").expect("Missing CARGO_MANIFEST_DIR");
Path::new(&cargo_manifest_dir)
.join("tests")
.join("mocked-pagers")
}
/// On Unix: 'most' -> 'most'
/// On Windows: 'most' -> 'most.bat'
pub fn from(base: &str) -> String {
let mut cmd_and_args = shell_words::split(base).unwrap();
let suffix = if cfg!(windows) { ".bat" } else { "" };
let mut out_cmd = format!("{}{suffix}", cmd_and_args.first().unwrap());
if (cmd_and_args.len() > 1) {
out_cmd.push(' ');
out_cmd.push_str(cmd_and_args[1..].to_vec().join(" ").as_str());
}
out_cmd
}
/// Prepends a directory to the PATH environment variable
/// Returns the original value for later restoration
fn prepend_dir_to_path_env_var(dir: PathBuf) -> String {
// Get current PATH
let original_path = env::var("PATH").expect("No PATH?!");
// Add the new dir first
let mut split_paths = env::split_paths(&original_path).collect::<Vec<_>>();
split_paths.insert(0, dir);
// Set PATH with the new dir
let new_path = env::join_paths(split_paths).expect("Failed to join paths");
env::set_var("PATH", new_path);
// Return the original value for later restoration of it
original_path
}
/// Helper to restore the value of PATH
fn restore_path(original_path: String) {
env::set_var("PATH", original_path);
}
/// Allows test to run that require our mocked versions of 'more' and 'most'
/// in PATH. Temporarily changes PATH while the test code runs, and then restore it
/// to avoid pollution of global state
pub fn with_mocked_versions_of_more_and_most_in_path(actual_test: fn()) {
let original_path = prepend_dir_to_path_env_var(get_mocked_pagers_dir());
// Make sure our own variants of 'more' and 'most' are used
Command::new(from("more"))
.assert()
.success()
.stdout(predicate::str::contains("I am more"));
Command::new(from("most"))
.assert()
.success()
.stdout(predicate::str::contains("I am most"));
Command::new(from("echo"))
.arg("foobar")
.assert()
.success()
.stdout(predicate::str::contains("foobar"));
// Now run the actual test
actual_test();
// Make sure to restore PATH since it is global state
restore_path(original_path);
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/tests/syntax-tests/highlighted/Rust/output.rs | tests/syntax-tests/highlighted/Rust/output.rs | [38;2;249;38;114muse[0m[38;2;248;248;242m [0m[38;2;248;248;242mstd[0m[38;2;248;248;242m::[0m[38;2;248;248;242mio[0m[38;2;248;248;242m::[0m[38;2;248;248;242m{[0m[38;2;255;255;255mself[0m[38;2;248;248;242m,[0m[38;2;248;248;242m Write[0m[38;2;248;248;242m}[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m#[0m[38;2;248;248;242m[[0m[38;2;248;248;242mcfg[0m[38;2;248;248;242m([0m[38;2;248;248;242mfeature [0m[38;2;249;38;114m=[0m[38;2;248;248;242m [0m[38;2;230;219;116m"[0m[38;2;230;219;116mpaging[0m[38;2;230;219;116m"[0m[38;2;248;248;242m)[0m[38;2;248;248;242m][0m
[38;2;249;38;114muse[0m[38;2;248;248;242m [0m[38;2;248;248;242mstd[0m[38;2;248;248;242m::[0m[38;2;248;248;242mprocess[0m[38;2;248;248;242m::[0m[38;2;248;248;242mChild[0m[38;2;248;248;242m;[0m
[38;2;249;38;114muse[0m[38;2;248;248;242m [0m[38;2;249;38;114mcrate[0m[38;2;248;248;242m::[0m[38;2;248;248;242merror[0m[38;2;248;248;242m::[0m[38;2;249;38;114m*[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m#[0m[38;2;248;248;242m[[0m[38;2;248;248;242mcfg[0m[38;2;248;248;242m([0m[38;2;248;248;242mfeature [0m[38;2;249;38;114m=[0m[38;2;248;248;242m [0m[38;2;230;219;116m"[0m[38;2;230;219;116mpaging[0m[38;2;230;219;116m"[0m[38;2;248;248;242m)[0m[38;2;248;248;242m][0m
[38;2;249;38;114muse[0m[38;2;248;248;242m [0m[38;2;249;38;114mcrate[0m[38;2;248;248;242m::[0m[38;2;248;248;242mless[0m[38;2;248;248;242m::[0m[38;2;248;248;242mretrieve_less_version[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m#[0m[38;2;248;248;242m[[0m[38;2;248;248;242mcfg[0m[38;2;248;248;242m([0m[38;2;248;248;242mfeature [0m[38;2;249;38;114m=[0m[38;2;248;248;242m [0m[38;2;230;219;116m"[0m[38;2;230;219;116mpaging[0m[38;2;230;219;116m"[0m[38;2;248;248;242m)[0m[38;2;248;248;242m][0m
[38;2;249;38;114muse[0m[38;2;248;248;242m [0m[38;2;249;38;114mcrate[0m[38;2;248;248;242m::[0m[38;2;248;248;242mpaging[0m[38;2;248;248;242m::[0m[38;2;248;248;242mPagingMode[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m#[0m[38;2;248;248;242m[[0m[38;2;248;248;242mderive[0m[38;2;248;248;242m([0m[38;2;248;248;242mDebug[0m[38;2;248;248;242m)[0m[38;2;248;248;242m][0m
[38;2;249;38;114mpub[0m[38;2;248;248;242m [0m[3;38;2;102;217;239menum[0m[38;2;248;248;242m [0m[38;2;166;226;46mOutputType[0m[38;2;248;248;242m [0m[38;2;248;248;242m{[0m
[38;2;248;248;242m [0m[38;2;248;248;242m#[0m[38;2;248;248;242m[[0m[38;2;248;248;242mcfg[0m[38;2;248;248;242m([0m[38;2;248;248;242mfeature [0m[38;2;249;38;114m=[0m[38;2;248;248;242m [0m[38;2;230;219;116m"[0m[38;2;230;219;116mpaging[0m[38;2;230;219;116m"[0m[38;2;248;248;242m)[0m[38;2;248;248;242m][0m
[38;2;248;248;242m Pager[0m[38;2;248;248;242m([0m[38;2;248;248;242mChild[0m[38;2;248;248;242m)[0m[38;2;248;248;242m,[0m
[38;2;248;248;242m Stdout[0m[38;2;248;248;242m([0m[38;2;248;248;242mio[0m[38;2;248;248;242m::[0m[38;2;248;248;242mStdout[0m[38;2;248;248;242m)[0m[38;2;248;248;242m,[0m
[38;2;248;248;242m}[0m
[3;38;2;102;217;239mimpl[0m[38;2;248;248;242m [0m[38;2;166;226;46mOutputType[0m[38;2;248;248;242m [0m[38;2;248;248;242m{[0m
[38;2;248;248;242m [0m[38;2;248;248;242m#[0m[38;2;248;248;242m[[0m[38;2;248;248;242mcfg[0m[38;2;248;248;242m([0m[38;2;248;248;242mfeature [0m[38;2;249;38;114m=[0m[38;2;248;248;242m [0m[38;2;230;219;116m"[0m[38;2;230;219;116mpaging[0m[38;2;230;219;116m"[0m[38;2;248;248;242m)[0m[38;2;248;248;242m][0m
[38;2;248;248;242m [0m[38;2;249;38;114mpub[0m[38;2;248;248;242m [0m[3;38;2;102;217;239mfn[0m[38;2;248;248;242m [0m[38;2;166;226;46mfrom_mode[0m[38;2;248;248;242m([0m[3;38;2;253;151;31mmode[0m[38;2;248;248;242m:[0m[38;2;248;248;242m PagingMode, [0m[3;38;2;253;151;31mpager[0m[38;2;248;248;242m:[0m[38;2;248;248;242m [0m[3;38;2;166;226;46mOption[0m[38;2;248;248;242m<[0m[38;2;249;38;114m&[0m[3;38;2;102;217;239mstr[0m[38;2;248;248;242m>[0m[38;2;248;248;242m)[0m[38;2;248;248;242m [0m[38;2;248;248;242m->[0m[38;2;248;248;242m [0m[3;38;2;166;226;46mResult[0m[38;2;248;248;242m<[0m[3;38;2;102;217;239mSelf[0m[38;2;248;248;242m>[0m[38;2;248;248;242m [0m[38;2;248;248;242m{[0m
[38;2;248;248;242m [0m[38;2;249;38;114muse[0m[38;2;248;248;242m [0m[38;2;255;255;255mself[0m[38;2;248;248;242m::[0m[38;2;248;248;242mPagingMode[0m[38;2;248;248;242m::[0m[38;2;249;38;114m*[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[3;38;2;166;226;46mOk[0m[38;2;248;248;242m([0m[38;2;249;38;114mmatch[0m[38;2;248;248;242m mode [0m[38;2;248;248;242m{[0m
[38;2;248;248;242m Always [0m[38;2;249;38;114m=>[0m[38;2;248;248;242m [0m[38;2;248;248;242mOutputType[0m[38;2;248;248;242m::[0m[38;2;248;248;242mtry_pager[0m[38;2;248;248;242m([0m[38;2;190;132;255mfalse[0m[38;2;248;248;242m,[0m[38;2;248;248;242m pager[0m[38;2;248;248;242m)[0m[38;2;249;38;114m?[0m[38;2;248;248;242m,[0m
[38;2;248;248;242m QuitIfOneScreen [0m[38;2;249;38;114m=>[0m[38;2;248;248;242m [0m[38;2;248;248;242mOutputType[0m[38;2;248;248;242m::[0m[38;2;248;248;242mtry_pager[0m[38;2;248;248;242m([0m[38;2;190;132;255mtrue[0m[38;2;248;248;242m,[0m[38;2;248;248;242m pager[0m[38;2;248;248;242m)[0m[38;2;249;38;114m?[0m[38;2;248;248;242m,[0m
[38;2;248;248;242m [0m[38;2;249;38;114m_[0m[38;2;248;248;242m [0m[38;2;249;38;114m=>[0m[38;2;248;248;242m [0m[38;2;248;248;242mOutputType[0m[38;2;248;248;242m::[0m[38;2;248;248;242mstdout[0m[38;2;248;248;242m([0m[38;2;248;248;242m)[0m[38;2;248;248;242m,[0m
[38;2;248;248;242m [0m[38;2;248;248;242m}[0m[38;2;248;248;242m)[0m
[38;2;248;248;242m [0m[38;2;248;248;242m}[0m
[38;2;248;248;242m [0m[38;2;117;113;94m///[0m[38;2;117;113;94m Try to launch the pager. Fall back to stdout in case of errors.[0m
[38;2;248;248;242m [0m[38;2;248;248;242m#[0m[38;2;248;248;242m[[0m[38;2;248;248;242mcfg[0m[38;2;248;248;242m([0m[38;2;248;248;242mfeature [0m[38;2;249;38;114m=[0m[38;2;248;248;242m [0m[38;2;230;219;116m"[0m[38;2;230;219;116mpaging[0m[38;2;230;219;116m"[0m[38;2;248;248;242m)[0m[38;2;248;248;242m][0m
[38;2;248;248;242m [0m[3;38;2;102;217;239mfn[0m[38;2;248;248;242m [0m[38;2;166;226;46mtry_pager[0m[38;2;248;248;242m([0m[3;38;2;253;151;31mquit_if_one_screen[0m[38;2;248;248;242m:[0m[38;2;248;248;242m [0m[3;38;2;102;217;239mbool[0m[38;2;248;248;242m, [0m[3;38;2;253;151;31mpager_from_config[0m[38;2;248;248;242m:[0m[38;2;248;248;242m [0m[3;38;2;166;226;46mOption[0m[38;2;248;248;242m<[0m[38;2;249;38;114m&[0m[3;38;2;102;217;239mstr[0m[38;2;248;248;242m>[0m[38;2;248;248;242m)[0m[38;2;248;248;242m [0m[38;2;248;248;242m->[0m[38;2;248;248;242m [0m[3;38;2;166;226;46mResult[0m[38;2;248;248;242m<[0m[3;38;2;102;217;239mSelf[0m[38;2;248;248;242m>[0m[38;2;248;248;242m [0m[38;2;248;248;242m{[0m
[38;2;248;248;242m [0m[38;2;249;38;114muse[0m[38;2;248;248;242m [0m[38;2;248;248;242mstd[0m[38;2;248;248;242m::[0m[38;2;248;248;242menv[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114muse[0m[38;2;248;248;242m [0m[38;2;248;248;242mstd[0m[38;2;248;248;242m::[0m[38;2;248;248;242mffi[0m[38;2;248;248;242m::[0m[38;2;248;248;242mOsString[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114muse[0m[38;2;248;248;242m [0m[38;2;248;248;242mstd[0m[38;2;248;248;242m::[0m[38;2;248;248;242mpath[0m[38;2;248;248;242m::[0m[38;2;248;248;242mPathBuf[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114muse[0m[38;2;248;248;242m [0m[38;2;248;248;242mstd[0m[38;2;248;248;242m::[0m[38;2;248;248;242mprocess[0m[38;2;248;248;242m::[0m[38;2;248;248;242m{[0m[38;2;248;248;242mCommand[0m[38;2;248;248;242m,[0m[38;2;248;248;242m Stdio[0m[38;2;248;248;242m}[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[3;38;2;102;217;239mlet[0m[38;2;248;248;242m [0m[38;2;249;38;114mmut[0m[38;2;248;248;242m replace_arguments_to_less [0m[38;2;249;38;114m=[0m[38;2;248;248;242m [0m[38;2;190;132;255mfalse[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[3;38;2;102;217;239mlet[0m[38;2;248;248;242m pager_from_env [0m[38;2;249;38;114m=[0m[38;2;248;248;242m [0m[38;2;249;38;114mmatch[0m[38;2;248;248;242m [0m[38;2;248;248;242m([0m[38;2;248;248;242menv[0m[38;2;248;248;242m::[0m[38;2;248;248;242mvar[0m[38;2;248;248;242m([0m[38;2;230;219;116m"[0m[38;2;230;219;116mBAT_PAGER[0m[38;2;230;219;116m"[0m[38;2;248;248;242m)[0m[38;2;248;248;242m,[0m[38;2;248;248;242m [0m[38;2;248;248;242menv[0m[38;2;248;248;242m::[0m[38;2;248;248;242mvar[0m[38;2;248;248;242m([0m[38;2;230;219;116m"[0m[38;2;230;219;116mPAGER[0m[38;2;230;219;116m"[0m[38;2;248;248;242m)[0m[38;2;248;248;242m)[0m[38;2;248;248;242m [0m[38;2;248;248;242m{[0m
[38;2;248;248;242m [0m[38;2;248;248;242m([0m[3;38;2;166;226;46mOk[0m[38;2;248;248;242m([0m[38;2;248;248;242mbat_pager[0m[38;2;248;248;242m)[0m[38;2;248;248;242m,[0m[38;2;248;248;242m [0m[38;2;249;38;114m_[0m[38;2;248;248;242m)[0m[38;2;248;248;242m [0m[38;2;249;38;114m=>[0m[38;2;248;248;242m [0m[3;38;2;166;226;46mSome[0m[38;2;248;248;242m([0m[38;2;248;248;242mbat_pager[0m[38;2;248;248;242m)[0m[38;2;248;248;242m,[0m
[38;2;248;248;242m [0m[38;2;248;248;242m([0m[38;2;249;38;114m_[0m[38;2;248;248;242m,[0m[38;2;248;248;242m [0m[3;38;2;166;226;46mOk[0m[38;2;248;248;242m([0m[38;2;248;248;242mpager[0m[38;2;248;248;242m)[0m[38;2;248;248;242m)[0m[38;2;248;248;242m [0m[38;2;249;38;114m=>[0m[38;2;248;248;242m [0m[38;2;248;248;242m{[0m
[38;2;248;248;242m [0m[38;2;117;113;94m//[0m[38;2;117;113;94m less needs to be called with the '-R' option in order to properly interpret the[0m
[38;2;248;248;242m [0m[38;2;117;113;94m//[0m[38;2;117;113;94m ANSI color sequences printed by bat. If someone has set PAGER="less -F", we[0m
[38;2;248;248;242m [0m[38;2;117;113;94m//[0m[38;2;117;113;94m therefore need to overwrite the arguments and add '-R'.[0m
[38;2;248;248;242m [0m[38;2;117;113;94m//[0m
[38;2;248;248;242m [0m[38;2;117;113;94m//[0m[38;2;117;113;94m We only do this for PAGER (as it is not specific to 'bat'), not for BAT_PAGER[0m
[38;2;248;248;242m [0m[38;2;117;113;94m//[0m[38;2;117;113;94m or bats '--pager' command line option.[0m
[38;2;248;248;242m replace_arguments_to_less [0m[38;2;249;38;114m=[0m[38;2;248;248;242m [0m[38;2;190;132;255mtrue[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[3;38;2;166;226;46mSome[0m[38;2;248;248;242m([0m[38;2;248;248;242mpager[0m[38;2;248;248;242m)[0m
[38;2;248;248;242m [0m[38;2;248;248;242m}[0m
[38;2;248;248;242m [0m[38;2;249;38;114m_[0m[38;2;248;248;242m [0m[38;2;249;38;114m=>[0m[38;2;248;248;242m [0m[3;38;2;166;226;46mNone[0m[38;2;248;248;242m,[0m
[38;2;248;248;242m [0m[38;2;248;248;242m}[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[3;38;2;102;217;239mlet[0m[38;2;248;248;242m pager_from_config [0m[38;2;249;38;114m=[0m[38;2;248;248;242m pager_from_config[0m[38;2;248;248;242m.[0m[38;2;102;217;239mmap[0m[38;2;248;248;242m([0m[38;2;248;248;242m|[0m[3;38;2;253;151;31mp[0m[38;2;248;248;242m|[0m[38;2;248;248;242m [0m[38;2;248;248;242mp[0m[38;2;248;248;242m.[0m[38;2;102;217;239mto_string[0m[38;2;248;248;242m([0m[38;2;248;248;242m)[0m[38;2;248;248;242m)[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mif[0m[38;2;248;248;242m pager_from_config[0m[38;2;248;248;242m.[0m[38;2;102;217;239mis_some[0m[38;2;248;248;242m([0m[38;2;248;248;242m)[0m[38;2;248;248;242m [0m[38;2;248;248;242m{[0m
[38;2;248;248;242m replace_arguments_to_less [0m[38;2;249;38;114m=[0m[38;2;248;248;242m [0m[38;2;190;132;255mfalse[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;248;248;242m}[0m
[38;2;248;248;242m [0m[3;38;2;102;217;239mlet[0m[38;2;248;248;242m pager [0m[38;2;249;38;114m=[0m[38;2;248;248;242m pager_from_config[0m
[38;2;248;248;242m [0m[38;2;248;248;242m.[0m[38;2;102;217;239mor[0m[38;2;248;248;242m([0m[38;2;248;248;242mpager_from_env[0m[38;2;248;248;242m)[0m
[38;2;248;248;242m [0m[38;2;248;248;242m.[0m[38;2;102;217;239munwrap_or_else[0m[38;2;248;248;242m([0m[38;2;248;248;242m|[0m[38;2;248;248;242m|[0m[38;2;248;248;242m [0m[3;38;2;166;226;46mString[0m[38;2;248;248;242m::[0m[38;2;248;248;242mfrom[0m[38;2;248;248;242m([0m[38;2;230;219;116m"[0m[38;2;230;219;116mless[0m[38;2;230;219;116m"[0m[38;2;248;248;242m)[0m[38;2;248;248;242m)[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[3;38;2;102;217;239mlet[0m[38;2;248;248;242m pagerflags [0m[38;2;249;38;114m=[0m
[38;2;248;248;242m [0m[38;2;248;248;242mshell_words[0m[38;2;248;248;242m::[0m[38;2;248;248;242msplit[0m[38;2;248;248;242m([0m[38;2;249;38;114m&[0m[38;2;248;248;242mpager[0m[38;2;248;248;242m)[0m[38;2;248;248;242m.[0m[38;2;102;217;239mchain_err[0m[38;2;248;248;242m([0m[38;2;248;248;242m|[0m[38;2;248;248;242m|[0m[38;2;248;248;242m [0m[38;2;230;219;116m"[0m[38;2;230;219;116mCould not parse pager command.[0m[38;2;230;219;116m"[0m[38;2;248;248;242m)[0m[38;2;249;38;114m?[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mmatch[0m[38;2;248;248;242m pagerflags[0m[38;2;248;248;242m.[0m[38;2;102;217;239msplit_first[0m[38;2;248;248;242m([0m[38;2;248;248;242m)[0m[38;2;248;248;242m [0m[38;2;248;248;242m{[0m
[38;2;248;248;242m [0m[3;38;2;166;226;46mSome[0m[38;2;248;248;242m([0m[38;2;248;248;242m([0m[38;2;248;248;242mpager_name[0m[38;2;248;248;242m,[0m[38;2;248;248;242m args[0m[38;2;248;248;242m)[0m[38;2;248;248;242m)[0m[38;2;248;248;242m [0m[38;2;249;38;114m=>[0m[38;2;248;248;242m [0m[38;2;248;248;242m{[0m
[38;2;248;248;242m [0m[3;38;2;102;217;239mlet[0m[38;2;248;248;242m [0m[38;2;249;38;114mmut[0m[38;2;248;248;242m pager_path [0m[38;2;249;38;114m=[0m[38;2;248;248;242m [0m[38;2;248;248;242mPathBuf[0m[38;2;248;248;242m::[0m[38;2;248;248;242mfrom[0m[38;2;248;248;242m([0m[38;2;248;248;242mpager_name[0m[38;2;248;248;242m)[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mif[0m[38;2;248;248;242m pager_path[0m[38;2;248;248;242m.[0m[38;2;102;217;239mfile_stem[0m[38;2;248;248;242m([0m[38;2;248;248;242m)[0m[38;2;248;248;242m [0m[38;2;249;38;114m==[0m[38;2;248;248;242m [0m[3;38;2;166;226;46mSome[0m[38;2;248;248;242m([0m[38;2;249;38;114m&[0m[38;2;248;248;242mOsString[0m[38;2;248;248;242m::[0m[38;2;248;248;242mfrom[0m[38;2;248;248;242m([0m[38;2;230;219;116m"[0m[38;2;230;219;116mbat[0m[38;2;230;219;116m"[0m[38;2;248;248;242m)[0m[38;2;248;248;242m)[0m[38;2;248;248;242m [0m[38;2;248;248;242m{[0m
[38;2;248;248;242m pager_path [0m[38;2;249;38;114m=[0m[38;2;248;248;242m [0m[38;2;248;248;242mPathBuf[0m[38;2;248;248;242m::[0m[38;2;248;248;242mfrom[0m[38;2;248;248;242m([0m[38;2;230;219;116m"[0m[38;2;230;219;116mless[0m[38;2;230;219;116m"[0m[38;2;248;248;242m)[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;248;248;242m}[0m
[38;2;248;248;242m [0m[3;38;2;102;217;239mlet[0m[38;2;248;248;242m is_less [0m[38;2;249;38;114m=[0m[38;2;248;248;242m pager_path[0m[38;2;248;248;242m.[0m[38;2;102;217;239mfile_stem[0m[38;2;248;248;242m([0m[38;2;248;248;242m)[0m[38;2;248;248;242m [0m[38;2;249;38;114m==[0m[38;2;248;248;242m [0m[3;38;2;166;226;46mSome[0m[38;2;248;248;242m([0m[38;2;249;38;114m&[0m[38;2;248;248;242mOsString[0m[38;2;248;248;242m::[0m[38;2;248;248;242mfrom[0m[38;2;248;248;242m([0m[38;2;230;219;116m"[0m[38;2;230;219;116mless[0m[38;2;230;219;116m"[0m[38;2;248;248;242m)[0m[38;2;248;248;242m)[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[3;38;2;102;217;239mlet[0m[38;2;248;248;242m [0m[38;2;249;38;114mmut[0m[38;2;248;248;242m process [0m[38;2;249;38;114m=[0m[38;2;248;248;242m [0m[38;2;249;38;114mif[0m[38;2;248;248;242m is_less [0m[38;2;248;248;242m{[0m
[38;2;248;248;242m [0m[3;38;2;102;217;239mlet[0m[38;2;248;248;242m [0m[38;2;249;38;114mmut[0m[38;2;248;248;242m p [0m[38;2;249;38;114m=[0m[38;2;248;248;242m [0m[38;2;248;248;242mCommand[0m[38;2;248;248;242m::[0m[38;2;248;248;242mnew[0m[38;2;248;248;242m([0m[38;2;249;38;114m&[0m[38;2;248;248;242mpager_path[0m[38;2;248;248;242m)[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mif[0m[38;2;248;248;242m args[0m[38;2;248;248;242m.[0m[38;2;102;217;239mis_empty[0m[38;2;248;248;242m([0m[38;2;248;248;242m)[0m[38;2;248;248;242m [0m[38;2;249;38;114m||[0m[38;2;248;248;242m replace_arguments_to_less [0m[38;2;248;248;242m{[0m
[38;2;248;248;242m p[0m[38;2;248;248;242m.[0m[38;2;102;217;239marg[0m[38;2;248;248;242m([0m[38;2;230;219;116m"[0m[38;2;230;219;116m--RAW-CONTROL-CHARS[0m[38;2;230;219;116m"[0m[38;2;248;248;242m)[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mif[0m[38;2;248;248;242m quit_if_one_screen [0m[38;2;248;248;242m{[0m
[38;2;248;248;242m p[0m[38;2;248;248;242m.[0m[38;2;102;217;239marg[0m[38;2;248;248;242m([0m[38;2;230;219;116m"[0m[38;2;230;219;116m--quit-if-one-screen[0m[38;2;230;219;116m"[0m[38;2;248;248;242m)[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;248;248;242m}[0m
[38;2;248;248;242m [0m[38;2;117;113;94m//[0m[38;2;117;113;94m Passing '--no-init' fixes a bug with '--quit-if-one-screen' in older[0m
[38;2;248;248;242m [0m[38;2;117;113;94m//[0m[38;2;117;113;94m versions of 'less'. Unfortunately, it also breaks mouse-wheel support.[0m
[38;2;248;248;242m [0m[38;2;117;113;94m//[0m
[38;2;248;248;242m [0m[38;2;117;113;94m//[0m[38;2;117;113;94m See: http://www.greenwoodsoftware.com/less/news.530.html[0m
[38;2;248;248;242m [0m[38;2;117;113;94m//[0m
[38;2;248;248;242m [0m[38;2;117;113;94m//[0m[38;2;117;113;94m For newer versions (530 or 558 on Windows), we omit '--no-init' as it[0m
[38;2;248;248;242m [0m[38;2;117;113;94m//[0m[38;2;117;113;94m is not needed anymore.[0m
[38;2;248;248;242m [0m[38;2;249;38;114mmatch[0m[38;2;248;248;242m [0m[38;2;102;217;239mretrieve_less_version[0m[38;2;248;248;242m([0m[38;2;248;248;242m)[0m[38;2;248;248;242m [0m[38;2;248;248;242m{[0m
[38;2;248;248;242m [0m[3;38;2;166;226;46mNone[0m[38;2;248;248;242m [0m[38;2;249;38;114m=>[0m[38;2;248;248;242m [0m[38;2;248;248;242m{[0m
[38;2;248;248;242m p[0m[38;2;248;248;242m.[0m[38;2;102;217;239marg[0m[38;2;248;248;242m([0m[38;2;230;219;116m"[0m[38;2;230;219;116m--no-init[0m[38;2;230;219;116m"[0m[38;2;248;248;242m)[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;248;248;242m}[0m
[38;2;248;248;242m [0m[3;38;2;166;226;46mSome[0m[38;2;248;248;242m([0m[38;2;248;248;242mversion[0m[38;2;248;248;242m)[0m
[38;2;248;248;242m [0m[38;2;249;38;114mif[0m[38;2;248;248;242m [0m[38;2;248;248;242m([0m[38;2;248;248;242mversion [0m[38;2;249;38;114m<[0m[38;2;248;248;242m [0m[38;2;190;132;255m530[0m[38;2;248;248;242m [0m[38;2;249;38;114m||[0m[38;2;248;248;242m [0m[38;2;248;248;242m([0m[38;2;248;248;242mcfg![0m[38;2;248;248;242m([0m[38;2;248;248;242mwindows[0m[38;2;248;248;242m)[0m[38;2;248;248;242m [0m[38;2;249;38;114m&&[0m[38;2;248;248;242m version [0m[38;2;249;38;114m<[0m[38;2;248;248;242m [0m[38;2;190;132;255m558[0m[38;2;248;248;242m)[0m[38;2;248;248;242m)[0m[38;2;248;248;242m [0m[38;2;249;38;114m=>[0m
[38;2;248;248;242m [0m[38;2;248;248;242m{[0m
[38;2;248;248;242m p[0m[38;2;248;248;242m.[0m[38;2;102;217;239marg[0m[38;2;248;248;242m([0m[38;2;230;219;116m"[0m[38;2;230;219;116m--no-init[0m[38;2;230;219;116m"[0m[38;2;248;248;242m)[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;248;248;242m}[0m
[38;2;248;248;242m [0m[38;2;249;38;114m_[0m[38;2;248;248;242m [0m[38;2;249;38;114m=>[0m[38;2;248;248;242m [0m[38;2;248;248;242m{[0m[38;2;248;248;242m}[0m
[38;2;248;248;242m [0m[38;2;248;248;242m}[0m
[38;2;248;248;242m [0m[38;2;248;248;242m}[0m[38;2;248;248;242m [0m[38;2;249;38;114melse[0m[38;2;248;248;242m [0m[38;2;248;248;242m{[0m
[38;2;248;248;242m p[0m[38;2;248;248;242m.[0m[38;2;102;217;239margs[0m[38;2;248;248;242m([0m[38;2;248;248;242margs[0m[38;2;248;248;242m)[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;248;248;242m}[0m
[38;2;248;248;242m p[0m[38;2;248;248;242m.[0m[38;2;102;217;239menv[0m[38;2;248;248;242m([0m[38;2;230;219;116m"[0m[38;2;230;219;116mLESSCHARSET[0m[38;2;230;219;116m"[0m[38;2;248;248;242m,[0m[38;2;248;248;242m [0m[38;2;230;219;116m"[0m[38;2;230;219;116mUTF-8[0m[38;2;230;219;116m"[0m[38;2;248;248;242m)[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m p[0m
[38;2;248;248;242m [0m[38;2;248;248;242m}[0m[38;2;248;248;242m [0m[38;2;249;38;114melse[0m[38;2;248;248;242m [0m[38;2;248;248;242m{[0m
[38;2;248;248;242m [0m[3;38;2;102;217;239mlet[0m[38;2;248;248;242m [0m[38;2;249;38;114mmut[0m[38;2;248;248;242m p [0m[38;2;249;38;114m=[0m[38;2;248;248;242m [0m[38;2;248;248;242mCommand[0m[38;2;248;248;242m::[0m[38;2;248;248;242mnew[0m[38;2;248;248;242m([0m[38;2;249;38;114m&[0m[38;2;248;248;242mpager_path[0m[38;2;248;248;242m)[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m p[0m[38;2;248;248;242m.[0m[38;2;102;217;239margs[0m[38;2;248;248;242m([0m[38;2;248;248;242margs[0m[38;2;248;248;242m)[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m p[0m
[38;2;248;248;242m [0m[38;2;248;248;242m}[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[3;38;2;166;226;46mOk[0m[38;2;248;248;242m([0m[38;2;248;248;242mprocess[0m
[38;2;248;248;242m [0m[38;2;248;248;242m.[0m[38;2;102;217;239mstdin[0m[38;2;248;248;242m([0m[38;2;248;248;242mStdio[0m[38;2;248;248;242m::[0m[38;2;248;248;242mpiped[0m[38;2;248;248;242m([0m[38;2;248;248;242m)[0m[38;2;248;248;242m)[0m
[38;2;248;248;242m [0m[38;2;248;248;242m.[0m[38;2;102;217;239mspawn[0m[38;2;248;248;242m([0m[38;2;248;248;242m)[0m
[38;2;248;248;242m [0m[38;2;248;248;242m.[0m[38;2;102;217;239mmap[0m[38;2;248;248;242m([0m[38;2;248;248;242mOutputType[0m[38;2;248;248;242m::[0m[38;2;248;248;242mPager[0m[38;2;248;248;242m)[0m
[38;2;248;248;242m [0m[38;2;248;248;242m.[0m[38;2;102;217;239munwrap_or_else[0m[38;2;248;248;242m([0m[38;2;248;248;242m|[0m[38;2;248;248;242m_[0m[38;2;248;248;242m|[0m[38;2;248;248;242m [0m[38;2;248;248;242mOutputType[0m[38;2;248;248;242m::[0m[38;2;248;248;242mstdout[0m[38;2;248;248;242m([0m[38;2;248;248;242m)[0m[38;2;248;248;242m)[0m[38;2;248;248;242m)[0m
[38;2;248;248;242m [0m[38;2;248;248;242m}[0m
[38;2;248;248;242m [0m[3;38;2;166;226;46mNone[0m[38;2;248;248;242m [0m[38;2;249;38;114m=>[0m[38;2;248;248;242m [0m[3;38;2;166;226;46mOk[0m[38;2;248;248;242m([0m[38;2;248;248;242mOutputType[0m[38;2;248;248;242m::[0m[38;2;248;248;242mstdout[0m[38;2;248;248;242m([0m[38;2;248;248;242m)[0m[38;2;248;248;242m)[0m[38;2;248;248;242m,[0m
[38;2;248;248;242m [0m[38;2;248;248;242m}[0m
[38;2;248;248;242m [0m[38;2;248;248;242m}[0m
[38;2;248;248;242m [0m[38;2;249;38;114mpub[0m[38;2;248;248;242m([0m[38;2;249;38;114mcrate[0m[38;2;248;248;242m)[0m[38;2;248;248;242m [0m[3;38;2;102;217;239mfn[0m[38;2;248;248;242m [0m[38;2;166;226;46mstdout[0m[38;2;248;248;242m([0m[38;2;248;248;242m)[0m[38;2;248;248;242m [0m[38;2;248;248;242m->[0m[38;2;248;248;242m [0m[3;38;2;102;217;239mSelf[0m[38;2;248;248;242m [0m[38;2;248;248;242m{[0m
[38;2;248;248;242m [0m[38;2;248;248;242mOutputType[0m[38;2;248;248;242m::[0m[38;2;248;248;242mStdout[0m[38;2;248;248;242m([0m[38;2;248;248;242mio[0m[38;2;248;248;242m::[0m[38;2;248;248;242mstdout[0m[38;2;248;248;242m([0m[38;2;248;248;242m)[0m[38;2;248;248;242m)[0m
[38;2;248;248;242m [0m[38;2;248;248;242m}[0m
[38;2;248;248;242m [0m[38;2;248;248;242m#[0m[38;2;248;248;242m[[0m[38;2;248;248;242mcfg[0m[38;2;248;248;242m([0m[38;2;248;248;242mfeature [0m[38;2;249;38;114m=[0m[38;2;248;248;242m [0m[38;2;230;219;116m"[0m[38;2;230;219;116mpaging[0m[38;2;230;219;116m"[0m[38;2;248;248;242m)[0m[38;2;248;248;242m][0m
[38;2;248;248;242m [0m[38;2;249;38;114mpub[0m[38;2;248;248;242m([0m[38;2;249;38;114mcrate[0m[38;2;248;248;242m)[0m[38;2;248;248;242m [0m[3;38;2;102;217;239mfn[0m[38;2;248;248;242m [0m[38;2;166;226;46mis_pager[0m[38;2;248;248;242m([0m[38;2;249;38;114m&[0m[3;38;2;253;151;31mself[0m[38;2;248;248;242m)[0m[38;2;248;248;242m [0m[38;2;248;248;242m->[0m[38;2;248;248;242m [0m[3;38;2;102;217;239mbool[0m[38;2;248;248;242m [0m[38;2;248;248;242m{[0m
[38;2;248;248;242m [0m[38;2;249;38;114mif[0m[38;2;248;248;242m [0m[3;38;2;102;217;239mlet[0m[38;2;248;248;242m [0m[38;2;248;248;242mOutputType[0m[38;2;248;248;242m::[0m[38;2;248;248;242mPager[0m[38;2;248;248;242m([0m[38;2;249;38;114m_[0m[38;2;248;248;242m)[0m[38;2;248;248;242m [0m[38;2;249;38;114m=[0m[38;2;248;248;242m [0m[38;2;255;255;255mself[0m[38;2;248;248;242m [0m[38;2;248;248;242m{[0m
[38;2;248;248;242m [0m[38;2;190;132;255mtrue[0m
[38;2;248;248;242m [0m[38;2;248;248;242m}[0m[38;2;248;248;242m [0m[38;2;249;38;114melse[0m[38;2;248;248;242m [0m[38;2;248;248;242m{[0m
[38;2;248;248;242m [0m[38;2;190;132;255mfalse[0m
[38;2;248;248;242m [0m[38;2;248;248;242m}[0m
[38;2;248;248;242m [0m[38;2;248;248;242m}[0m
[38;2;248;248;242m [0m[38;2;248;248;242m#[0m[38;2;248;248;242m[[0m[38;2;248;248;242mcfg[0m[38;2;248;248;242m([0m[38;2;248;248;242mnot[0m[38;2;248;248;242m([0m[38;2;248;248;242mfeature [0m[38;2;249;38;114m=[0m[38;2;248;248;242m [0m[38;2;230;219;116m"[0m[38;2;230;219;116mpaging[0m[38;2;230;219;116m"[0m[38;2;248;248;242m)[0m[38;2;248;248;242m)[0m[38;2;248;248;242m][0m
[38;2;248;248;242m [0m[38;2;249;38;114mpub[0m[38;2;248;248;242m([0m[38;2;249;38;114mcrate[0m[38;2;248;248;242m)[0m[38;2;248;248;242m [0m[3;38;2;102;217;239mfn[0m[38;2;248;248;242m [0m[38;2;166;226;46mis_pager[0m[38;2;248;248;242m([0m[38;2;249;38;114m&[0m[3;38;2;253;151;31mself[0m[38;2;248;248;242m)[0m[38;2;248;248;242m [0m[38;2;248;248;242m->[0m[38;2;248;248;242m [0m[3;38;2;102;217;239mbool[0m[38;2;248;248;242m [0m[38;2;248;248;242m{[0m
[38;2;248;248;242m [0m[38;2;190;132;255mfalse[0m
[38;2;248;248;242m [0m[38;2;248;248;242m}[0m
[38;2;248;248;242m [0m[38;2;249;38;114mpub[0m[38;2;248;248;242m [0m[3;38;2;102;217;239mfn[0m[38;2;248;248;242m [0m[38;2;166;226;46mhandle[0m[38;2;248;248;242m([0m[38;2;249;38;114m&[0m[38;2;249;38;114mmut[0m[38;2;248;248;242m [0m[3;38;2;253;151;31mself[0m[38;2;248;248;242m)[0m[38;2;248;248;242m [0m[38;2;248;248;242m->[0m[38;2;248;248;242m [0m[3;38;2;166;226;46mResult[0m[38;2;248;248;242m<[0m[38;2;249;38;114m&[0m[38;2;249;38;114mmut[0m[38;2;248;248;242m dyn Write[0m[38;2;248;248;242m>[0m[38;2;248;248;242m [0m[38;2;248;248;242m{[0m
[38;2;248;248;242m [0m[3;38;2;166;226;46mOk[0m[38;2;248;248;242m([0m[38;2;249;38;114mmatch[0m[38;2;248;248;242m [0m[38;2;249;38;114m*[0m[38;2;255;255;255mself[0m[38;2;248;248;242m [0m[38;2;248;248;242m{[0m
[38;2;248;248;242m [0m[38;2;248;248;242m#[0m[38;2;248;248;242m[[0m[38;2;248;248;242mcfg[0m[38;2;248;248;242m([0m[38;2;248;248;242mfeature [0m[38;2;249;38;114m=[0m[38;2;248;248;242m [0m[38;2;230;219;116m"[0m[38;2;230;219;116mpaging[0m[38;2;230;219;116m"[0m[38;2;248;248;242m)[0m[38;2;248;248;242m][0m
[38;2;248;248;242m [0m[38;2;248;248;242mOutputType[0m[38;2;248;248;242m::[0m[38;2;248;248;242mPager[0m[38;2;248;248;242m([0m[38;2;249;38;114mref[0m[38;2;248;248;242m [0m[38;2;249;38;114mmut[0m[38;2;248;248;242m command[0m[38;2;248;248;242m)[0m[38;2;248;248;242m [0m[38;2;249;38;114m=>[0m[38;2;248;248;242m command[0m
[38;2;248;248;242m [0m[38;2;248;248;242m.[0m[38;2;248;248;242mstdin[0m
[38;2;248;248;242m [0m[38;2;248;248;242m.[0m[38;2;102;217;239mas_mut[0m[38;2;248;248;242m([0m[38;2;248;248;242m)[0m
[38;2;248;248;242m [0m[38;2;248;248;242m.[0m[38;2;102;217;239mchain_err[0m[38;2;248;248;242m([0m[38;2;248;248;242m|[0m[38;2;248;248;242m|[0m[38;2;248;248;242m [0m[38;2;230;219;116m"[0m[38;2;230;219;116mCould not open stdin for pager[0m[38;2;230;219;116m"[0m[38;2;248;248;242m)[0m[38;2;249;38;114m?[0m[38;2;248;248;242m,[0m
[38;2;248;248;242m [0m[38;2;248;248;242mOutputType[0m[38;2;248;248;242m::[0m[38;2;248;248;242mStdout[0m[38;2;248;248;242m([0m[38;2;249;38;114mref[0m[38;2;248;248;242m [0m[38;2;249;38;114mmut[0m[38;2;248;248;242m handle[0m[38;2;248;248;242m)[0m[38;2;248;248;242m [0m[38;2;249;38;114m=>[0m[38;2;248;248;242m handle[0m[38;2;248;248;242m,[0m
[38;2;248;248;242m [0m[38;2;248;248;242m}[0m[38;2;248;248;242m)[0m
[38;2;248;248;242m [0m[38;2;248;248;242m}[0m
[38;2;248;248;242m}[0m
[38;2;248;248;242m#[0m[38;2;248;248;242m[[0m[38;2;248;248;242mcfg[0m[38;2;248;248;242m([0m[38;2;248;248;242mfeature [0m[38;2;249;38;114m=[0m[38;2;248;248;242m [0m[38;2;230;219;116m"[0m[38;2;230;219;116mpaging[0m[38;2;230;219;116m"[0m[38;2;248;248;242m)[0m[38;2;248;248;242m][0m
[3;38;2;102;217;239mimpl[0m[38;2;248;248;242m [0m[38;2;248;248;242mDrop [0m[38;2;249;38;114mfor[0m[38;2;248;248;242m [0m[38;2;166;226;46mOutputType[0m[38;2;248;248;242m [0m[38;2;248;248;242m{[0m
[38;2;248;248;242m [0m[3;38;2;102;217;239mfn[0m[38;2;248;248;242m [0m[38;2;166;226;46mdrop[0m[38;2;248;248;242m([0m[38;2;249;38;114m&[0m[38;2;249;38;114mmut[0m[38;2;248;248;242m [0m[3;38;2;253;151;31mself[0m[38;2;248;248;242m)[0m[38;2;248;248;242m [0m[38;2;248;248;242m{[0m
[38;2;248;248;242m [0m[38;2;249;38;114mif[0m[38;2;248;248;242m [0m[3;38;2;102;217;239mlet[0m[38;2;248;248;242m [0m[38;2;248;248;242mOutputType[0m[38;2;248;248;242m::[0m[38;2;248;248;242mPager[0m[38;2;248;248;242m([0m[38;2;249;38;114mref[0m[38;2;248;248;242m [0m[38;2;249;38;114mmut[0m[38;2;248;248;242m command[0m[38;2;248;248;242m)[0m[38;2;248;248;242m [0m[38;2;249;38;114m=[0m[38;2;248;248;242m [0m[38;2;249;38;114m*[0m[38;2;255;255;255mself[0m[38;2;248;248;242m [0m[38;2;248;248;242m{[0m
[38;2;248;248;242m [0m[3;38;2;102;217;239mlet[0m[38;2;248;248;242m [0m[38;2;249;38;114m_[0m[38;2;248;248;242m [0m[38;2;249;38;114m=[0m[38;2;248;248;242m command[0m[38;2;248;248;242m.[0m[38;2;102;217;239mwait[0m[38;2;248;248;242m([0m[38;2;248;248;242m)[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;248;248;242m}[0m
[38;2;248;248;242m [0m[38;2;248;248;242m}[0m
[38;2;248;248;242m}[0m
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/tests/syntax-tests/source/Rust/output.rs | tests/syntax-tests/source/Rust/output.rs | use std::io::{self, Write};
#[cfg(feature = "paging")]
use std::process::Child;
use crate::error::*;
#[cfg(feature = "paging")]
use crate::less::retrieve_less_version;
#[cfg(feature = "paging")]
use crate::paging::PagingMode;
#[derive(Debug)]
pub enum OutputType {
#[cfg(feature = "paging")]
Pager(Child),
Stdout(io::Stdout),
}
impl OutputType {
#[cfg(feature = "paging")]
pub fn from_mode(mode: PagingMode, pager: Option<&str>) -> Result<Self> {
use self::PagingMode::*;
Ok(match mode {
Always => OutputType::try_pager(false, pager)?,
QuitIfOneScreen => OutputType::try_pager(true, pager)?,
_ => OutputType::stdout(),
})
}
/// Try to launch the pager. Fall back to stdout in case of errors.
#[cfg(feature = "paging")]
fn try_pager(quit_if_one_screen: bool, pager_from_config: Option<&str>) -> Result<Self> {
use std::env;
use std::ffi::OsString;
use std::path::PathBuf;
use std::process::{Command, Stdio};
let mut replace_arguments_to_less = false;
let pager_from_env = match (env::var("BAT_PAGER"), env::var("PAGER")) {
(Ok(bat_pager), _) => Some(bat_pager),
(_, Ok(pager)) => {
// less needs to be called with the '-R' option in order to properly interpret the
// ANSI color sequences printed by bat. If someone has set PAGER="less -F", we
// therefore need to overwrite the arguments and add '-R'.
//
// We only do this for PAGER (as it is not specific to 'bat'), not for BAT_PAGER
// or bats '--pager' command line option.
replace_arguments_to_less = true;
Some(pager)
}
_ => None,
};
let pager_from_config = pager_from_config.map(|p| p.to_string());
if pager_from_config.is_some() {
replace_arguments_to_less = false;
}
let pager = pager_from_config
.or(pager_from_env)
.unwrap_or_else(|| String::from("less"));
let pagerflags =
shell_words::split(&pager).chain_err(|| "Could not parse pager command.")?;
match pagerflags.split_first() {
Some((pager_name, args)) => {
let mut pager_path = PathBuf::from(pager_name);
if pager_path.file_stem() == Some(&OsString::from("bat")) {
pager_path = PathBuf::from("less");
}
let is_less = pager_path.file_stem() == Some(&OsString::from("less"));
let mut process = if is_less {
let mut p = Command::new(&pager_path);
if args.is_empty() || replace_arguments_to_less {
p.arg("--RAW-CONTROL-CHARS");
if quit_if_one_screen {
p.arg("--quit-if-one-screen");
}
// Passing '--no-init' fixes a bug with '--quit-if-one-screen' in older
// versions of 'less'. Unfortunately, it also breaks mouse-wheel support.
//
// See: http://www.greenwoodsoftware.com/less/news.530.html
//
// For newer versions (530 or 558 on Windows), we omit '--no-init' as it
// is not needed anymore.
match retrieve_less_version() {
None => {
p.arg("--no-init");
}
Some(version)
if (version < 530 || (cfg!(windows) && version < 558)) =>
{
p.arg("--no-init");
}
_ => {}
}
} else {
p.args(args);
}
p.env("LESSCHARSET", "UTF-8");
p
} else {
let mut p = Command::new(&pager_path);
p.args(args);
p
};
Ok(process
.stdin(Stdio::piped())
.spawn()
.map(OutputType::Pager)
.unwrap_or_else(|_| OutputType::stdout()))
}
None => Ok(OutputType::stdout()),
}
}
pub(crate) fn stdout() -> Self {
OutputType::Stdout(io::stdout())
}
#[cfg(feature = "paging")]
pub(crate) fn is_pager(&self) -> bool {
if let OutputType::Pager(_) = self {
true
} else {
false
}
}
#[cfg(not(feature = "paging"))]
pub(crate) fn is_pager(&self) -> bool {
false
}
pub fn handle(&mut self) -> Result<&mut dyn Write> {
Ok(match *self {
#[cfg(feature = "paging")]
OutputType::Pager(ref mut command) => command
.stdin
.as_mut()
.chain_err(|| "Could not open stdin for pager")?,
OutputType::Stdout(ref mut handle) => handle,
})
}
}
#[cfg(feature = "paging")]
impl Drop for OutputType {
fn drop(&mut self) {
if let OutputType::Pager(ref mut command) = *self {
let _ = command.wait();
}
}
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/tests/snapshots/sample.rs | tests/snapshots/sample.rs | struct Rectangle {
width: u32,
height: u32,
}
fn main() {
// width and height of a rectangle can be different
let rect1 = Rectangle { width: 30, height: 50 };
println!(
"The area of the rectangle is {} square pixels.",
area(&rect1)
);
}
fn area(rectangle: &Rectangle) -> u32 {
rectangle.width * rectangle.height
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/tests/tester/mod.rs | tests/tester/mod.rs | use std::env;
use std::fs::{self, File};
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::Command;
use tempfile::TempDir;
use git2::build::CheckoutBuilder;
use git2::Repository;
use git2::Signature;
pub struct BatTester {
/// Temporary working directory
temp_dir: TempDir,
/// Path to the *bat* executable
exe: PathBuf,
}
impl BatTester {
pub fn test_snapshot(&self, name: &str, style: &str) {
let output = Command::new(&self.exe)
.current_dir(self.temp_dir.path())
.args([
"sample.rs",
"--no-config",
"--paging=never",
"--color=never",
"--decorations=always",
"--terminal-width=80",
&format!("--style={style}"),
])
.output()
.expect("bat failed");
// have to do the replace because the filename in the header changes based on the current working directory
let actual = String::from_utf8_lossy(&output.stdout)
.as_ref()
.replace("tests/snapshots/", "");
let mut expected = String::new();
let mut file = File::open(format!("tests/snapshots/output/{name}.snapshot.txt"))
.expect("snapshot file missing");
file.read_to_string(&mut expected)
.expect("could not read snapshot file");
assert_eq!(expected, actual);
}
}
impl Default for BatTester {
fn default() -> Self {
let temp_dir = create_sample_directory().expect("sample directory");
let root = env::current_exe()
.expect("tests executable")
.parent()
.expect("tests executable directory")
.parent()
.expect("bat executable directory")
.to_path_buf();
let exe_name = if cfg!(windows) { "bat.exe" } else { "bat" };
let exe = root.join(exe_name);
BatTester { temp_dir, exe }
}
}
fn create_sample_directory() -> Result<TempDir, git2::Error> {
// Create temp directory and initialize repository
let temp_dir = TempDir::new().expect("Temp directory");
let repo = Repository::init(&temp_dir)?;
// Copy over `sample.rs`
let sample_path = temp_dir.path().join("sample.rs");
println!("{sample_path:?}");
fs::copy("tests/snapshots/sample.rs", &sample_path).expect("successful copy");
// Commit
let mut index = repo.index()?;
index.add_path(Path::new("sample.rs"))?;
let oid = index.write_tree()?;
let signature = Signature::now("bat test runner", "bat@test.runner")?;
let tree = repo.find_tree(oid)?;
let _ = repo.commit(
Some("HEAD"), // point HEAD to our new commit
&signature, // author
&signature, // committer
"initial commit",
&tree,
&[],
);
let mut opts = CheckoutBuilder::new();
repo.checkout_head(Some(opts.force()))?;
fs::copy("tests/snapshots/sample.modified.rs", &sample_path).expect("successful copy");
Ok(temp_dir)
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/build/syntax_mapping.rs | build/syntax_mapping.rs | use std::{
convert::Infallible,
env, fs,
path::{Path, PathBuf},
str::FromStr,
};
use anyhow::{anyhow, bail};
use indexmap::IndexMap;
use itertools::Itertools;
use once_cell::sync::Lazy;
use proc_macro2::TokenStream;
use quote::{quote, ToTokens, TokenStreamExt};
use regex::Regex;
use serde_derive::Deserialize;
use serde_with::DeserializeFromStr;
use walkdir::WalkDir;
/// Known mapping targets.
///
/// Corresponds to `syntax_mapping::MappingTarget`.
#[allow(clippy::enum_variant_names)]
#[derive(Clone, Debug, Eq, PartialEq, Hash, DeserializeFromStr)]
pub enum MappingTarget {
MapTo(String),
MapToUnknown,
MapExtensionToUnknown,
}
impl FromStr for MappingTarget {
type Err = Infallible;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"MappingTarget::MapToUnknown" => Ok(Self::MapToUnknown),
"MappingTarget::MapExtensionToUnknown" => Ok(Self::MapExtensionToUnknown),
syntax => Ok(Self::MapTo(syntax.into())),
}
}
}
impl ToTokens for MappingTarget {
fn to_tokens(&self, tokens: &mut TokenStream) {
let t = match self {
Self::MapTo(syntax) => quote! { MappingTarget::MapTo(#syntax) },
Self::MapToUnknown => quote! { MappingTarget::MapToUnknown },
Self::MapExtensionToUnknown => quote! { MappingTarget::MapExtensionToUnknown },
};
tokens.append_all(t);
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, DeserializeFromStr)]
/// A single matcher.
///
/// Codegen converts this into a `Lazy<Option<GlobMatcher>>`.
struct Matcher(Vec<MatcherSegment>);
/// Parse a matcher.
///
/// Note that this implementation is rather strict: it will greedily interpret
/// every valid environment variable replacement as such, then immediately
/// hard-error if it finds a '$' anywhere in the remaining text segments.
///
/// The reason for this strictness is I currently cannot think of a valid reason
/// why you would ever need '$' as plaintext in a glob pattern. Therefore any
/// such occurrences are likely human errors.
///
/// If we later discover some edge cases, it's okay to make it more permissive.
///
/// Revision history:
/// - 2024-02-20: allow `{` and `}` (glob brace expansion)
impl FromStr for Matcher {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
use MatcherSegment as Seg;
static VAR_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r"\$\{([\w\d_]+)\}").unwrap());
let mut segments = vec![];
let mut text_start = 0;
for capture in VAR_REGEX.captures_iter(s) {
let match_0 = capture.get(0).unwrap();
// text before this var
let text_end = match_0.start();
segments.push(Seg::Text(s[text_start..text_end].into()));
text_start = match_0.end();
// this var
segments.push(Seg::Env(capture.get(1).unwrap().as_str().into()));
}
// possible trailing text
segments.push(Seg::Text(s[text_start..].into()));
// cleanup empty text segments
let non_empty_segments = segments
.into_iter()
.filter(|seg| seg.text().map(|t| !t.is_empty()).unwrap_or(true))
.collect_vec();
// sanity check
if non_empty_segments
.windows(2)
.any(|segs| segs[0].is_text() && segs[1].is_text())
{
unreachable!("Parsed into consecutive text segments: {non_empty_segments:?}");
}
// guard empty case
if non_empty_segments.is_empty() {
bail!(r#"Parsed an empty matcher: "{s}""#);
}
// guard variable syntax leftover fragments
if non_empty_segments
.iter()
.filter_map(Seg::text)
.any(|t| t.contains('$'))
{
bail!(r#"Invalid matcher: "{s}""#);
}
Ok(Self(non_empty_segments))
}
}
impl ToTokens for Matcher {
fn to_tokens(&self, tokens: &mut TokenStream) {
let t = match self.0.as_slice() {
[] => unreachable!("0-length matcher should never be created"),
[MatcherSegment::Text(text)] => {
quote! { Lazy::new(|| Some(build_matcher_fixed(#text))) }
}
// parser logic ensures that this case can only happen when there are dynamic segments
segs @ [_, ..] => quote! { Lazy::new(|| build_matcher_dynamic(&[ #(#segs),* ])) },
};
tokens.append_all(t);
}
}
/// A segment in a matcher.
///
/// Corresponds to `syntax_mapping::MatcherSegment`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum MatcherSegment {
Text(String),
Env(String),
}
impl ToTokens for MatcherSegment {
fn to_tokens(&self, tokens: &mut TokenStream) {
let t = match self {
Self::Text(text) => quote! { MatcherSegment::Text(#text) },
Self::Env(env) => quote! { MatcherSegment::Env(#env) },
};
tokens.append_all(t);
}
}
#[allow(dead_code)]
impl MatcherSegment {
fn is_text(&self) -> bool {
matches!(self, Self::Text(_))
}
fn is_env(&self) -> bool {
matches!(self, Self::Env(_))
}
fn text(&self) -> Option<&str> {
match self {
Self::Text(t) => Some(t),
Self::Env(_) => None,
}
}
fn env(&self) -> Option<&str> {
match self {
Self::Text(_) => None,
Self::Env(t) => Some(t),
}
}
}
/// A struct that models a single .toml file in /src/syntax_mapping/builtins/.
#[derive(Clone, Debug, Deserialize)]
struct MappingDefModel {
mappings: IndexMap<MappingTarget, Vec<Matcher>>,
}
impl MappingDefModel {
fn into_mapping_list(self) -> MappingList {
let list = self
.mappings
.into_iter()
.flat_map(|(target, matchers)| {
matchers
.into_iter()
.map(|matcher| (matcher, target.clone()))
.collect::<Vec<_>>()
})
.collect();
MappingList(list)
}
}
#[derive(Clone, Debug)]
struct MappingList(Vec<(Matcher, MappingTarget)>);
impl ToTokens for MappingList {
fn to_tokens(&self, tokens: &mut TokenStream) {
let len = self.0.len();
let array_items = self
.0
.iter()
.map(|(matcher, target)| quote! { (#matcher, #target) });
let t = quote! {
/// Generated by build script from /src/syntax_mapping/builtins/.
pub(crate) static BUILTIN_MAPPINGS: [(Lazy<Option<GlobMatcher>>, MappingTarget); #len] = [#(#array_items),*];
};
tokens.append_all(t);
}
}
/// Get the list of paths to all mapping definition files that should be
/// included for the current target platform.
fn get_def_paths() -> anyhow::Result<Vec<PathBuf>> {
let source_subdirs = [
"common",
#[cfg(target_family = "unix")]
"unix-family",
#[cfg(any(
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
target_os = "macos"
))]
"bsd-family",
#[cfg(target_os = "linux")]
"linux",
#[cfg(target_os = "macos")]
"macos",
#[cfg(target_os = "windows")]
"windows",
];
let mut toml_paths = vec![];
for subdir_name in source_subdirs {
let subdir = Path::new("src/syntax_mapping/builtins").join(subdir_name);
if !subdir.try_exists()? {
// Directory might not exist due to this `cargo vendor` bug:
// https://github.com/rust-lang/cargo/issues/15080
continue;
}
let wd = WalkDir::new(subdir);
let paths = wd
.into_iter()
.filter_map_ok(|entry| {
let path = entry.path();
(path.is_file() && path.extension().map(|ext| ext == "toml").unwrap_or(false))
.then(|| path.to_owned())
})
.collect::<Result<Vec<_>, _>>()?;
toml_paths.extend(paths);
}
toml_paths.sort_by_key(|path| {
path.file_name()
.expect("file name should not terminate in ..")
.to_owned()
});
Ok(toml_paths)
}
fn read_all_mappings() -> anyhow::Result<MappingList> {
let mut all_mappings = vec![];
for path in get_def_paths()? {
let toml_string = fs::read_to_string(path)?;
let mappings = toml::from_str::<MappingDefModel>(&toml_string)?.into_mapping_list();
all_mappings.extend(mappings.0);
}
let duplicates = all_mappings
.iter()
.duplicates_by(|(matcher, _)| matcher)
.collect_vec();
if !duplicates.is_empty() {
bail!("Rules with duplicate matchers found: {duplicates:?}");
}
Ok(MappingList(all_mappings))
}
/// Build the static syntax mappings defined in /src/syntax_mapping/builtins/
/// into a .rs source file, which is to be inserted with `include!`.
pub fn build_static_mappings() -> anyhow::Result<()> {
println!("cargo:rerun-if-changed=src/syntax_mapping/builtins/");
let mappings = read_all_mappings()?;
// IMPRV: parse + unparse is a bit cringe, but there seems to be no better
// option given the limited APIs of `prettyplease`
let rs_src = syn::parse_file(&mappings.to_token_stream().to_string())?;
let rs_src_pretty = prettyplease::unparse(&rs_src);
let codegen_path = Path::new(&env::var_os("OUT_DIR").ok_or(anyhow!("OUT_DIR is unset"))?)
.join("codegen_static_syntax_mappings.rs");
fs::write(codegen_path, rs_src_pretty)?;
Ok(())
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/build/application.rs | build/application.rs | use std::{env, fs, path::PathBuf};
use crate::util::render_template;
/// Generate manpage and shell completions for the bat application.
pub fn gen_man_and_comp() -> anyhow::Result<()> {
println!("cargo:rerun-if-changed=assets/manual/");
println!("cargo:rerun-if-changed=assets/completions/");
println!("cargo:rerun-if-env-changed=PROJECT_NAME");
println!("cargo:rerun-if-env-changed=PROJECT_EXECUTABLE");
println!("cargo:rerun-if-env-changed=CARGO_PKG_VERSION");
println!("cargo:rerun-if-env-changed=BAT_ASSETS_GEN_DIR");
// Read environment variables.
let project_name = env::var("PROJECT_NAME").unwrap_or("bat".into());
let executable_name = env::var("PROJECT_EXECUTABLE").unwrap_or(project_name.clone());
let executable_name_uppercase = executable_name.to_uppercase();
let project_version = env::var("CARGO_PKG_VERSION")?;
let variables = [
("PROJECT_NAME", project_name),
("PROJECT_EXECUTABLE", executable_name),
("PROJECT_EXECUTABLE_UPPERCASE", executable_name_uppercase),
("PROJECT_VERSION", project_version),
]
.into_iter()
.collect();
let Some(out_dir) = env::var_os("BAT_ASSETS_GEN_DIR")
.or_else(|| env::var_os("OUT_DIR"))
.map(PathBuf::from)
else {
anyhow::bail!("BAT_ASSETS_GEN_DIR or OUT_DIR should be set for build.rs");
};
fs::create_dir_all(out_dir.join("assets/manual")).unwrap();
fs::create_dir_all(out_dir.join("assets/completions")).unwrap();
render_template(
&variables,
"assets/manual/bat.1.in",
out_dir.join("assets/manual/bat.1"),
)?;
render_template(
&variables,
"assets/completions/bat.bash.in",
out_dir.join("assets/completions/bat.bash"),
)?;
render_template(
&variables,
"assets/completions/bat.fish.in",
out_dir.join("assets/completions/bat.fish"),
)?;
render_template(
&variables,
"assets/completions/_bat.ps1.in",
out_dir.join("assets/completions/_bat.ps1"),
)?;
render_template(
&variables,
"assets/completions/bat.zsh.in",
out_dir.join("assets/completions/bat.zsh"),
)?;
println!(
"cargo:rustc-env=BAT_GENERATED_COMPLETION_BASH={}",
out_dir.join("assets/completions/bat.bash").display()
);
println!(
"cargo:rustc-env=BAT_GENERATED_COMPLETION_FISH={}",
out_dir.join("assets/completions/bat.fish").display()
);
println!(
"cargo:rustc-env=BAT_GENERATED_COMPLETION_PS1={}",
out_dir.join("assets/completions/_bat.ps1").display()
);
println!(
"cargo:rustc-env=BAT_GENERATED_COMPLETION_ZSH={}",
out_dir.join("assets/completions/bat.zsh").display()
);
Ok(())
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/build/util.rs | build/util.rs | #![allow(dead_code)]
use std::{collections::HashMap, fs, path::Path};
/// Generates a file from a template.
pub fn render_template(
variables: &HashMap<&str, String>,
in_file: &str,
out_file: impl AsRef<Path>,
) -> anyhow::Result<()> {
let mut content = fs::read_to_string(in_file)?;
for (variable_name, value) in variables {
// Replace {{variable_name}} by the value
let pattern = format!("{{{{{variable_name}}}}}");
content = content.replace(&pattern, value);
}
fs::write(out_file, content)?;
Ok(())
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/build/main.rs | build/main.rs | #[cfg(feature = "application")]
mod application;
mod syntax_mapping;
mod util;
fn main() -> anyhow::Result<()> {
// only watch manually-designated files
// see: https://doc.rust-lang.org/cargo/reference/build-scripts.html#rerun-if-changed
println!("cargo:rerun-if-changed=build/");
syntax_mapping::build_static_mappings()?;
#[cfg(feature = "application")]
application::gen_man_and_comp()?;
Ok(())
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/assets/theme_preview.rs | assets/theme_preview.rs | // Output the square of a number.
fn print_square(num: f64) {
let result = f64::powf(num, 2.0);
println!("The square of {num:.2} is {result:.2}.");
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/examples/inputs.rs | examples/inputs.rs | /// A small demonstration of the Input API.
/// This prints embedded bytes with a custom header and then reads from STDIN.
use bat::{Input, PrettyPrinter};
fn main() {
PrettyPrinter::new()
.header(true)
.grid(true)
.line_numbers(true)
.inputs(vec![
Input::from_bytes(b"echo 'Hello World!'")
.name("embedded.sh") // Dummy name provided to detect the syntax.
.kind("Embedded")
.title("An embedded shell script."),
Input::from_stdin().title("Standard Input").kind("FD"),
])
.print()
.unwrap();
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/examples/advanced.rs | examples/advanced.rs | /// A program that prints its own source code using the bat library
use bat::{PagingMode, PrettyPrinter, WrappingMode};
fn main() {
PrettyPrinter::new()
.header(true)
.grid(true)
.line_numbers(true)
.use_italics(true)
// The following line will be highlighted in the output:
.highlight(line!() as usize)
.theme("1337")
.wrapping_mode(WrappingMode::Character)
.paging_mode(PagingMode::QuitIfOneScreen)
.input_file(file!())
.print()
.unwrap();
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/examples/list_syntaxes_and_themes.rs | examples/list_syntaxes_and_themes.rs | /// A simple program that lists all supported syntaxes and themes.
use bat::PrettyPrinter;
fn main() {
let printer = PrettyPrinter::new();
println!("Syntaxes:");
for syntax in printer.syntaxes() {
println!("- {} ({})", syntax.name, syntax.file_extensions.join(", "));
}
println!();
println!("Themes:");
for theme in printer.themes() {
println!("- {theme}");
}
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/examples/simple.rs | examples/simple.rs | /// A simple program that prints its own source code using the bat library
use bat::PrettyPrinter;
fn main() {
PrettyPrinter::new().input_file(file!()).print().unwrap();
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/examples/yaml.rs | examples/yaml.rs | /// A program that serializes a Rust structure to YAML and pretty-prints the result
use bat::{Input, PrettyPrinter};
use serde::Serialize;
#[derive(Serialize)]
struct Person {
name: String,
height: f64,
adult: bool,
children: Vec<Person>,
}
fn main() {
let person = Person {
name: String::from("Anne Mustermann"),
height: 1.76f64,
adult: true,
children: vec![Person {
name: String::from("Max Mustermann"),
height: 1.32f64,
adult: false,
children: vec![],
}],
};
let mut bytes = Vec::with_capacity(128);
serde_yaml::to_writer(&mut bytes, &person).unwrap();
PrettyPrinter::new()
.language("yaml")
.line_numbers(true)
.grid(true)
.header(true)
.input(Input::from_bytes(&bytes).name("person.yaml").kind("File"))
.print()
.unwrap();
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/examples/buffer.rs | examples/buffer.rs | use bat::{
assets::HighlightingAssets, config::Config, controller::Controller, output::OutputHandle, Input,
};
fn main() {
let mut buffer = String::new();
let config = Config {
colored_output: true,
..Default::default()
};
let assets = HighlightingAssets::from_binary();
let controller = Controller::new(&config, &assets);
let input = Input::from_file(file!());
controller
.run(
vec![input.into()],
Some(&mut OutputHandle::FmtWrite(&mut buffer)),
)
.unwrap();
println!("{buffer}");
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/examples/cat.rs | examples/cat.rs | /// A very simple colorized `cat` clone, using `bat` as a library.
/// See `src/bin/bat` for the full `bat` application.
use bat::PrettyPrinter;
fn main() {
PrettyPrinter::new()
.header(true)
.grid(true)
.line_numbers(true)
.input_files(std::env::args_os().skip(1))
.print()
.unwrap();
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
rust-unofficial/awesome-rust | https://github.com/rust-unofficial/awesome-rust/blob/87566de6df053370ed1fe6f0baa242a2b96311c8/src/main.rs | src/main.rs | #![deny(warnings)]
use anyhow::{format_err, Result};
use chrono::{DateTime, Duration, Local};
use diffy::create_patch;
use futures::future::{select_all, BoxFuture, FutureExt};
use lazy_static::lazy_static;
use log::{debug, info, warn};
use pulldown_cmark::{Event, Parser, Tag};
use regex::Regex;
use reqwest::{header, redirect::Policy, Client, StatusCode, Url};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use std::env;
use std::io::Write;
use std::time;
use std::u8;
use std::{cmp::Ordering, fs};
use thiserror::Error;
use tokio::sync::Semaphore;
use tokio::sync::SemaphorePermit;
const MINIMUM_GITHUB_STARS: u32 = 50;
const MINIMUM_CARGO_DOWNLOADS: u32 = 2000;
// Allow overriding the needed stars for a section. "level" is the header level in the markdown, default is MINIMUM_GITHUB_STARS
// In general, we should just use the defaults. However, for some areas where there's not a lot of well-starred projects, but a
// a few that are say just below the thresholds, then it's worth reducing the thresholds so we can get a few more projects.
fn override_stars(level: u32, text: &str) -> Option<u32> {
if level == 2 && text.contains("Resources") {
// This is zero because a lot of the resources are non-github/non-cargo links and overriding for all would be annoying
// These should be evaluated with more primitive means
Some(0)
} else if level == 3 && (text.contains("Games") || text.contains("Emulators")) {
Some(40)
} else {
None // i.e. use defaults
}
}
lazy_static! {
// We don't explicitly check these, because they just bug out in GitHub. We're _hoping_ they don't go away!
static ref ASSUME_WORKS: Vec<String> = vec![
"https://www.reddit.com/r/rust/",
"https://opcfoundation.org/about/opc-technologies/opc-ua/",
"https://arangodb.com",
"https://git.sr.ht/~lessa/pepper",
"https://git.sr.ht/~pyrossh/rust-embed",
"https://www.gnu.org/software/emacs/",
"http://www.gnu.org/software/gsl/",
"https://labex.io/skilltrees/rust",
"https://github.com/TraceMachina/nativelink", // probably broken because @palfrey now works for them...
"https://www.vulkan.org/",
"https://gitlab.redox-os.org/redox-os/redox", // Cloudflare
"https://www.modbus.org/",
"https://portmedia.sourceforge.net/portmidi/",
].iter().map(|s| s.to_string()).collect();
// Overrides for popularity count, each needs a good reason (i.e. downloads/stars we don't support automatic counting of)
// Each is a URL that's "enough" for an item to pass the popularity checks
static ref POPULARITY_OVERRIDES: Vec<String> = vec![
"https://github.com/maidsafe", // Many repos of Rust code, collectively > 50 stars
"https://pijul.org", // Uses it's own VCS at https://nest.pijul.com/pijul/pijul with 190 stars at last check
"https://gitlab.com/veloren/veloren", // No direct gitlab support, but >1000 stars there
"https://gitlab.redox-os.org/redox-os/redox", // 394 stars
"https://amp.rs", // https://github.com/jmacdonald/amp has 2.9k stars
"https://marketplace.visualstudio.com/items?itemName=vadimcn.vscode-lldb", // > 350k downloads
"https://gitpod.io", // https://github.com/gitpod-io/gitpod has 4.7k stars
"https://wiki.gnome.org/Apps/Builder", // https://gitlab.gnome.org/GNOME/gnome-builder has 133 stars
"https://www.jetbrains.com/rust/", // popular closed-source IDE, free for non-commercial use
"https://marketplace.visualstudio.com/items?itemName=tamasfe.even-better-toml", // > 1M downloads
"https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer", // > 260k downloads
"https://marketplace.visualstudio.com/items?itemName=rust-lang.rust", // > 1M downloads
"https://docs.rs", // https://github.com/rust-lang/docs.rs has >600 stars
"https://github.com/rust-bio", // https://github.com/rust-bio/rust-bio on it's own has >900 stars
"https://github.com/contain-rs", // Lots of repos with good star counts
"https://github.com/georust", // Lots of repos with good star counts
"https://github.com/rust-qt", // Various high-stars repositories
"https://chromium.googlesource.com/chromiumos/platform/crosvm/", // Can't tell count directly, but various mirrors of it (e.g. https://github.com/dgreid/crosvm) have enough stars that it's got enough interest
"https://crates.io", // This one gets a free pass :)
"https://cloudsmith.com/product/formats/cargo-registry", // First private cargo registry (https://cloudsmith.com/blog/worlds-first-private-cargo-registry-w-cloudsmith-rust/) and not much in the way of other options yet. See also https://github.com/rust-unofficial/awesome-rust/pull/1141#discussion_r688711555
"https://gitlab.com/ttyperacer/terminal-typeracer", // GitLab repo with >40 stars.
"https://github.com/esp-rs", // Espressif Rust Organization (Organizations have no stars).
"https://github.com/arkworks-rs", // Rust ecosystem for zkSNARK programming (Organizations have no stars)
"https://marketplace.visualstudio.com/items?itemName=jinxdash.prettier-rust", // https://github.com/jinxdash/prettier-plugin-rust has >50 stars
"https://github.com/andoriyu/uclicious", // FIXME: CI hack. the crate has a higher count, but we don't refresh.
"https://marketplace.visualstudio.com/items?itemName=fill-labs.dependi", // marketplace link , but also has enough stars
"https://github.com/TraceMachina/nativelink", // 1.4k stars, probably broken because @palfrey now works for them...
"https://www.repoflow.io", // added per discussion in the RepoFlow pull request: https://github.com/rust-unofficial/awesome-rust/pull/2054 (see package downloads: https://app.repoflow.io/repoflow-public/package/f429fabf-6289-49c2-acd9-791b39eac746)
"https://framagit.org/ppom/reaction", // has 56 stars at time of writing
].iter().map(|s| s.to_string()).collect();
}
#[derive(Debug, Error, Serialize, Deserialize)]
enum CheckerError {
#[error("failed to try url")]
NotTried, // Generally shouldn't happen, but useful to have
#[error("http error: {status}")]
HttpError {
status: u16,
location: Option<String>,
},
#[error("too many requests")]
TooManyRequests,
#[error("reqwest error: {error}")]
ReqwestError { error: String },
#[error("travis build is unknown")]
TravisBuildUnknown,
#[error("travis build image with no branch")]
TravisBuildNoBranch,
}
fn formatter(err: &CheckerError, url: &String) -> String {
match err {
CheckerError::HttpError { status, location } => match location {
Some(loc) => {
format!("[{}] {} -> {}", status, url, loc)
}
None => {
format!("[{}] {}", status, url)
}
},
CheckerError::TravisBuildUnknown => {
format!("[Unknown travis build] {}", url)
}
CheckerError::TravisBuildNoBranch => {
format!("[Travis build image with no branch specified] {}", url)
}
_ => {
format!("{:?}", err)
}
}
}
struct MaxHandles {
remaining: Semaphore,
}
struct Handle<'a> {
_permit: SemaphorePermit<'a>,
}
impl MaxHandles {
fn new(max: usize) -> MaxHandles {
MaxHandles {
remaining: Semaphore::new(max),
}
}
async fn get(&'_ self) -> Handle<'_> {
let permit = self.remaining.acquire().await.unwrap();
Handle { _permit: permit }
}
}
impl<'a> Drop for Handle<'a> {
fn drop(&mut self) {
debug!("Dropping");
}
}
lazy_static! {
static ref CLIENT: Client = Client::builder()
.danger_accept_invalid_certs(true) // because some certs are out of date
.user_agent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:68.0) Gecko/20100101 Firefox/68.0") // so some sites (e.g. sciter.com) don't reject us
.redirect(Policy::none())
.pool_max_idle_per_host(0)
.timeout(time::Duration::from_secs(20))
.build().unwrap();
// This is to avoid errors with running out of file handles, so we only do 20 requests at a time
static ref HANDLES: MaxHandles = MaxHandles::new(20);
}
fn get_url(url: String) -> BoxFuture<'static, (String, Result<(), CheckerError>)> {
debug!("Need handle for {}", url);
async move {
let _handle = HANDLES.get().await;
get_url_core(url).await
}
.boxed()
}
lazy_static! {
static ref GITHUB_REPO_REGEX: Regex =
Regex::new(r"^https://github.com/(?P<org>[^/]+)/(?P<repo>[^/]+)(.*)").unwrap();
static ref GITHUB_API_REGEX: Regex = Regex::new(r"https://api.github.com/").unwrap();
static ref CRATE_REGEX: Regex =
Regex::new(r"https://crates.io/crates/(?P<crate>[^/]+)/?$").unwrap();
static ref ITEM_REGEX: Regex =
Regex::new(r"(?P<repo>(\S+)(/\S+)?)(?P<crate> \[\S*\])? - (?P<desc>\S.+)").unwrap();
}
#[derive(Deserialize, Debug)]
struct GitHubStars {
stargazers_count: u32,
archived: bool,
}
async fn get_stars(github_url: &str) -> Option<u32> {
warn!("Downloading GitHub stars for {}", github_url);
let rewritten = GITHUB_REPO_REGEX
.replace_all(github_url, "https://api.github.com/repos/$org/$repo")
.to_string();
let mut req = CLIENT.get(&rewritten);
if let Ok(username) = env::var("USERNAME_FOR_GITHUB") {
if let Ok(password) = env::var("TOKEN_FOR_GITHUB") {
// needs a token with at least public_repo scope
req = req.basic_auth(username, Some(password));
}
}
let resp = req.send().await;
match resp {
Err(err) => {
warn!("Error while getting {}: {}", github_url, err);
None
}
Ok(ok) => {
let raw = ok.text().await.unwrap();
let data = match serde_json::from_str::<GitHubStars>(&raw) {
Ok(val) => val,
Err(_) => {
panic!("{:?}", raw);
}
};
if data.archived {
warn!("{} is archived, so ignoring stars", github_url);
return Some(0);
}
Some(data.stargazers_count)
}
}
}
#[derive(Deserialize, Debug)]
struct CrateInfo {
downloads: u64,
}
#[derive(Deserialize, Debug)]
struct Crate {
#[serde(rename = "crate")]
info: CrateInfo,
}
async fn get_downloads(github_url: &str) -> Option<u64> {
warn!("Downloading Crates downloads for {}", github_url);
let rewritten = CRATE_REGEX
.replace_all(github_url, "https://crates.io/api/v1/crates/$crate")
.to_string();
let req = CLIENT.get(&rewritten);
let resp = req.send().await;
match resp {
Err(err) => {
warn!("Error while getting {}: {}", github_url, err);
None
}
Ok(ok) => {
let data = ok.json::<Crate>().await.unwrap();
Some(data.info.downloads)
}
}
}
fn get_url_core(url: String) -> BoxFuture<'static, (String, Result<(), CheckerError>)> {
async move {
if ASSUME_WORKS.contains(&url) || url.starts_with("https://medium.com") // cloudflare
{
info!("We assume {} just works...", url);
return (url, Ok(()));
}
if env::var("USERNAME_FOR_GITHUB").is_ok() && env::var("TOKEN_FOR_GITHUB").is_ok() && GITHUB_REPO_REGEX.is_match(&url) {
let rewritten = GITHUB_REPO_REGEX.replace_all(&url, "https://api.github.com/repos/$org/$repo");
info!("Replacing {} with {} to workaround rate limits on GitHub", url, rewritten);
let (_new_url, res) = get_url_core(rewritten.to_string()).await;
return (url, res);
}
let mut res: Result<(), CheckerError> = Err(CheckerError::NotTried);
for _ in 0..5u8 {
debug!("Running {}", url);
let mut req = CLIENT
.get(&url)
.header(header::ACCEPT, "image/svg+xml, text/html, */*;q=0.8");
if GITHUB_API_REGEX.is_match(&url) {
if let Ok(username) = env::var("USERNAME_FOR_GITHUB") {
if let Ok(password) = env::var("TOKEN_FOR_GITHUB") {
// needs a token with at least public_repo scope
info!("Using basic auth for {}", url);
req = req.basic_auth(username, Some(password));
}
}
}
let resp = req.send().await;
match resp {
Err(err) => {
warn!("Error while getting {}, retrying: {}", url, err);
res = Err(CheckerError::ReqwestError{error: err.to_string()});
continue;
}
Ok(ok) => {
let status = ok.status();
if !vec![StatusCode::OK, StatusCode::ACCEPTED].contains(&status) {
lazy_static! {
static ref ACTIONS_REGEX: Regex = Regex::new(r"https://github.com/(?P<org>[^/]+)/(?P<repo>[^/]+)/actions(?:\?workflow=.+)?").unwrap();
static ref YOUTUBE_VIDEO_REGEX: Regex = Regex::new(r"https://www.youtube.com/watch\?v=(?P<video_id>.+)").unwrap();
static ref YOUTUBE_PLAYLIST_REGEX: Regex = Regex::new(r"https://www.youtube.com/playlist\?list=(?P<playlist_id>.+)").unwrap();
static ref YOUTUBE_CONSENT_REGEX: Regex = Regex::new(r"https://consent.youtube.com/m\?continue=.+").unwrap();
static ref AZURE_BUILD_REGEX: Regex = Regex::new(r"https://dev.azure.com/[^/]+/[^/]+/_build").unwrap();
}
if status == StatusCode::NOT_FOUND && ACTIONS_REGEX.is_match(&url) {
let rewritten = ACTIONS_REGEX.replace_all(&url, "https://github.com/$org/$repo");
warn!("Got 404 with GitHub actions, so replacing {} with {}", url, rewritten);
let (_new_url, res) = get_url_core(rewritten.to_string()).await;
return (url, res);
}
if status == StatusCode::FOUND && YOUTUBE_VIDEO_REGEX.is_match(&url) {
// Based off of https://gist.github.com/tonY1883/a3b85925081688de569b779b4657439b
// Guesswork is that the img feed will cause less 302's than the main url
// See https://github.com/rust-unofficial/awesome-rust/issues/814 for original issue
let rewritten = YOUTUBE_VIDEO_REGEX.replace_all(&url, "http://img.youtube.com/vi/$video_id/mqdefault.jpg");
warn!("Got 302 with Youtube, so replacing {} with {}", url, rewritten);
let (_new_url, res) = get_url_core(rewritten.to_string()).await;
return (url, res);
};
if status == StatusCode::FOUND && YOUTUBE_PLAYLIST_REGEX.is_match(&url) {
let location = ok.headers().get("LOCATION").map(|h| h.to_str().unwrap()).unwrap_or_default();
if YOUTUBE_CONSENT_REGEX.is_match(location) {
warn!("Got Youtube consent link for {}, so assuming playlist is ok", url);
return (url, Ok(()));
}
};
if status == StatusCode::FOUND && AZURE_BUILD_REGEX.is_match(&url) {
// Azure build urls always redirect to a particular build id, so no stable url guarantees
let redirect = ok.headers().get(header::LOCATION).unwrap().to_str().unwrap();
let merged_url = Url::parse(&url).unwrap().join(redirect).unwrap();
info!("Got 302 from Azure devops, so replacing {} with {}", url, merged_url);
let (_new_url, res) = get_url_core(merged_url.into()).await;
return (url, res);
}
if status == StatusCode::TOO_MANY_REQUESTS {
// We get a lot of these, and we should not retry as they'll just fail again
warn!("Error while getting {}: {}", url, status);
return (url, Err(CheckerError::TooManyRequests));
}
if status.is_redirection() {
if status != StatusCode::TEMPORARY_REDIRECT && status != StatusCode::FOUND { // ignore temporary redirects
res = Err(CheckerError::HttpError {status: status.as_u16(), location: ok.headers().get(header::LOCATION).and_then(|h| h.to_str().ok()).map(|x| x.to_string())});
warn!("Redirect while getting {} - {}", url, status);
break;
}
} else {
warn!("Error while getting {}, retrying: {}", url, status);
res = Err(CheckerError::HttpError {status: status.as_u16(), location: None});
continue;
}
}
lazy_static! {
static ref TRAVIS_IMG_REGEX: Regex = Regex::new(r"https://api.travis-ci.(?:com|org)/[^/]+/.+\.svg(\?.+)?").unwrap();
static ref GITHUB_ACTIONS_REGEX: Regex = Regex::new(r"https://github.com/[^/]+/[^/]+/workflows/[^/]+/badge.svg(\?.+)?").unwrap();
}
if let Some(matches) = TRAVIS_IMG_REGEX.captures(&url) {
// Previously we checked the Content-Disposition headers, but sometimes that is incorrect
// We're now looking for the explicit text "unknown" in the middle of the SVG
let content = ok.text().await.unwrap();
if content.contains("unknown") {
res = Err(CheckerError::TravisBuildUnknown);
break;
}
let query = matches.get(1).map(|x| x.as_str()).unwrap_or("");
if !query.starts_with('?') || !query.contains("branch=") {
res = Err(CheckerError::TravisBuildNoBranch);
break;
}
}
debug!("Finished {}", url);
res = Ok(());
break;
}
}
}
(url, res)
}.boxed()
}
#[derive(Debug, Serialize, Deserialize)]
enum Working {
Yes,
No(CheckerError),
}
#[derive(Debug, Serialize, Deserialize)]
struct Link {
last_working: Option<DateTime<Local>>,
updated_at: DateTime<Local>,
working: Working,
}
type Results = BTreeMap<String, Link>;
#[derive(Debug, Serialize, Deserialize)]
struct PopularityData {
pub github_stars: BTreeMap<String, u32>,
pub cargo_downloads: BTreeMap<String, u32>,
}
#[tokio::main]
async fn main() -> Result<()> {
env_logger::init();
let markdown_input = fs::read_to_string("README.md").expect("Can't read README.md");
let parser = Parser::new(&markdown_input);
let mut used: BTreeSet<String> = BTreeSet::new();
let mut results: Results = fs::read_to_string("results/results.yaml")
.map_err(|e| format_err!("{}", e))
.and_then(|x| serde_yaml::from_str(&x).map_err(|e| format_err!("{}", e)))
.unwrap_or_default();
let mut popularity_data: PopularityData = fs::read_to_string("results/popularity.yaml")
.map_err(|e| format_err!("{}", e))
.and_then(|x| serde_yaml::from_str(&x).map_err(|e| format_err!("{}", e)))
.unwrap_or(PopularityData {
github_stars: BTreeMap::new(),
cargo_downloads: BTreeMap::new(),
});
let mut url_checks = vec![];
let min_between_checks: Duration = Duration::days(3);
let max_allowed_failed: Duration = Duration::days(7);
let mut do_check = |url: String| {
if !url.starts_with("http") {
return;
}
if used.contains(&url) {
return;
}
used.insert(url.clone());
if let Some(link) = results.get(&url) {
if let Working::Yes = link.working {
let since = Local::now() - link.updated_at;
if since < min_between_checks {
return;
}
}
}
let check = get_url(url).boxed();
url_checks.push(check);
};
let mut to_check: Vec<String> = vec![];
#[derive(Debug)]
struct ListInfo {
data: Vec<String>,
}
let mut list_items: Vec<ListInfo> = Vec::new();
let mut in_list_item = false;
let mut list_item: String = String::new();
let mut link_count: u8 = 0;
let mut github_stars: Option<u32> = None;
let mut cargo_downloads: Option<u32> = None;
let mut required_stars: u32 = MINIMUM_GITHUB_STARS;
let mut last_level: u32 = 0;
let mut star_override_level: Option<u32> = None;
for (event, _range) in parser.into_offset_iter() {
debug!("Event {:?}", event);
match event {
Event::Start(tag) => {
match tag {
Tag::Link(_link_type, url, _title) | Tag::Image(_link_type, url, _title) => {
if !url.starts_with('#') {
let new_url = url.to_string();
if POPULARITY_OVERRIDES.contains(&new_url) {
github_stars = Some(MINIMUM_GITHUB_STARS);
} else if GITHUB_REPO_REGEX.is_match(&url) && github_stars.is_none() {
let github_url = GITHUB_REPO_REGEX
.replace_all(&url, "https://github.com/$org/$repo")
.to_string();
let existing = popularity_data.github_stars.get(&github_url);
if let Some(stars) = existing {
// Use existing star data, but re-retrieve url to check aliveness
// Some will have overrides, so don't check the regex yet
github_stars = Some(*stars)
} else {
github_stars = get_stars(&github_url).await;
if let Some(raw_stars) = github_stars {
popularity_data.github_stars.insert(github_url, raw_stars);
if raw_stars >= required_stars {
fs::write(
"results/popularity.yaml",
serde_yaml::to_string(&popularity_data)?,
)?;
}
link_count += 1;
continue;
}
}
}
if CRATE_REGEX.is_match(&url) {
let existing = popularity_data.cargo_downloads.get(&new_url);
if let Some(downloads) = existing {
cargo_downloads = Some(*downloads);
} else {
let raw_downloads = get_downloads(&url).await;
if let Some(positive_downloads) = raw_downloads {
cargo_downloads = Some(
positive_downloads.clamp(0, u32::MAX as u64) as u32,
);
popularity_data
.cargo_downloads
.insert(new_url, cargo_downloads.unwrap());
if cargo_downloads.unwrap_or(0) >= MINIMUM_CARGO_DOWNLOADS {
fs::write(
"results/popularity.yaml",
serde_yaml::to_string(&popularity_data)?,
)?;
}
}
link_count += 1;
continue;
}
}
to_check.push(url.to_string());
link_count += 1;
}
}
Tag::List(_) => {
if in_list_item && !list_item.is_empty() {
list_items.last_mut().unwrap().data.push(list_item.clone());
in_list_item = false;
}
list_items.push(ListInfo { data: Vec::new() });
}
Tag::Item => {
if in_list_item && !list_item.is_empty() {
list_items.last_mut().unwrap().data.push(list_item.clone());
}
in_list_item = true;
list_item = String::new();
link_count = 0;
github_stars = None;
cargo_downloads = None;
}
Tag::Heading(level) => {
last_level = level;
if let Some(override_level) = star_override_level {
if level == override_level {
star_override_level = None;
required_stars = MINIMUM_GITHUB_STARS;
}
}
}
Tag::Paragraph => {}
_ => {
if in_list_item {
in_list_item = false;
}
}
}
}
Event::Text(text) => {
let possible_override = override_stars(last_level, &text);
if let Some(override_value) = possible_override {
star_override_level = Some(last_level);
required_stars = override_value;
}
if in_list_item {
list_item.push_str(&text);
}
}
Event::End(tag) => {
match tag {
Tag::Item => {
if !list_item.is_empty() {
if link_count > 0
&& github_stars.unwrap_or(0) < required_stars
&& cargo_downloads.unwrap_or(0) < MINIMUM_CARGO_DOWNLOADS
{
if github_stars.is_none() {
warn!("No valid github link for {list_item}");
}
if cargo_downloads.is_none() {
warn!("No valid crates link for {list_item}");
}
return Err(format_err!("Not high enough metrics ({:?} stars < {}, and {:?} cargo downloads < {}): {}", github_stars, required_stars, cargo_downloads, MINIMUM_CARGO_DOWNLOADS, list_item));
}
if link_count > 0 && !ITEM_REGEX.is_match(&list_item) {
if list_item.contains("—") {
warn!("\"{list_item}\" uses a '—' hyphen, not the '-' hyphen and we enforce the use of the latter one");
}
return Err(format_err!("Item does not match the template: \"{list_item}\". See https://github.com/rust-unofficial/awesome-rust/blob/main/CONTRIBUTING.md#tldr"));
}
list_items.last_mut().unwrap().data.push(list_item.clone());
list_item = String::new();
}
in_list_item = false
}
Tag::List(_) => {
let list_info = list_items.pop().unwrap();
if list_info.data.iter().any(|s| *s == "License")
&& list_info.data.iter().any(|s| *s == "Resources")
{
// Ignore wrong ordering in top-level list
continue;
}
let mut sorted_recent_list = list_info.data.to_vec();
sorted_recent_list.sort_by_key(|a| a.to_lowercase());
let joined_recent = list_info.data.join("\n");
let joined_sorted = sorted_recent_list.join("\n");
let patch = create_patch(&joined_recent, &joined_sorted);
if !patch.hunks().is_empty() {
println!("{}", patch);
return Err(format_err!("Sorting error"));
}
}
_ => {}
}
}
Event::Html(content) => {
// Allow ToC markers, nothing else
if !content.contains("<!-- toc") {
return Err(format_err!(
"Contains HTML content, not markdown: {}",
content
));
}
}
_ => {}
}
}
fs::write(
"results/popularity.yaml",
serde_yaml::to_string(&popularity_data)?,
)?;
to_check.sort_by(|a, b| {
let get_time = |k| results.get(k).map(|link| link.last_working);
let res_a = get_time(a);
let res_b = get_time(b);
match (res_a, res_b) {
(Some(a), Some(b)) => a.cmp(&b),
(Some(_), None) => Ordering::Less,
(None, Some(_)) => Ordering::Greater,
(None, None) => a.cmp(b),
}
});
for url in to_check {
do_check(url)
}
let results_keys = results.keys().cloned().collect::<BTreeSet<String>>();
let old_links = results_keys.difference(&used);
for link in old_links {
results.remove(link).unwrap();
}
fs::write("results/results.yaml", serde_yaml::to_string(&results)?)?;
let mut not_written = 0;
let mut last_written = Local::now();
while !url_checks.is_empty() {
debug!("Waiting for {}", url_checks.len());
let ((url, res), _index, remaining) = select_all(url_checks).await;
url_checks = remaining;
match res {
Ok(_) => {
print!("\u{2714} ");
if let Some(link) = results.get_mut(&url) {
link.updated_at = Local::now();
link.last_working = Some(Local::now());
link.working = Working::Yes;
} else {
results.insert(
url.clone(),
Link {
updated_at: Local::now(),
last_working: Some(Local::now()),
working: Working::Yes,
},
);
}
}
Err(err) => {
print!("\u{2718} ");
if let Some(link) = results.get_mut(&url) {
link.updated_at = Local::now();
link.working = Working::No(err);
} else {
results.insert(
url.clone(),
Link {
| rust | CC0-1.0 | 87566de6df053370ed1fe6f0baa242a2b96311c8 | 2026-01-04T15:31:59.375418Z | true |
rust-unofficial/awesome-rust | https://github.com/rust-unofficial/awesome-rust/blob/87566de6df053370ed1fe6f0baa242a2b96311c8/src/bin/hacktoberfest.rs | src/bin/hacktoberfest.rs | // Helper tool to dump all repos in awesome-rust that are tagged with "hacktoberfest"
use anyhow::{format_err, Result};
use chrono::{DateTime, Duration, Local};
use futures::future::{select_all, BoxFuture, FutureExt};
use lazy_static::lazy_static;
use log::{debug, warn};
use pulldown_cmark::{Event, Parser, Tag};
use regex::Regex;
use reqwest::redirect::Policy;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use std::env;
use std::fs;
use std::io::Write;
use std::time;
use std::u8;
use thiserror::Error;
use tokio::sync::Semaphore;
use tokio::sync::SemaphorePermit;
#[derive(Debug, Error, Serialize, Deserialize)]
enum CheckerError {
#[error("http error: {}", status)]
HttpError {
status: u16,
location: Option<String>,
},
}
struct MaxHandles {
remaining: Semaphore,
}
struct Handle<'a> {
_permit: SemaphorePermit<'a>,
}
impl MaxHandles {
fn new(max: usize) -> MaxHandles {
MaxHandles {
remaining: Semaphore::new(max),
}
}
async fn get(&'_ self) -> Handle<'_> {
let permit = self.remaining.acquire().await.unwrap();
Handle { _permit: permit }
}
}
impl<'a> Drop for Handle<'a> {
fn drop(&mut self) {
debug!("Dropping");
}
}
lazy_static! {
static ref CLIENT: Client = Client::builder()
.danger_accept_invalid_certs(true) // because some certs are out of date
.user_agent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:68.0) Gecko/20100101 Firefox/68.0") // so some sites (e.g. sciter.com) don't reject us
.redirect(Policy::none())
.pool_max_idle_per_host(0)
.timeout(time::Duration::from_secs(20))
.build().unwrap();
// This is to avoid errors with running out of file handles, so we only do 20 requests at a time
static ref HANDLES: MaxHandles = MaxHandles::new(20);
}
lazy_static! {
static ref GITHUB_REPO_REGEX: Regex =
Regex::new(r"^https://github.com/(?P<org>[^/]+)/(?P<repo>[^/]+)/?$").unwrap();
static ref GITHUB_API_REGEX: Regex = Regex::new(r"https://api.github.com/").unwrap();
}
#[derive(Deserialize, Debug)]
struct RepoInfo {
full_name: String,
description: Option<String>,
topics: Vec<String>,
}
async fn get_hacktoberfest_core(github_url: String) -> Result<Info, CheckerError> {
warn!("Downloading Hacktoberfest label for {}", github_url);
let rewritten = GITHUB_REPO_REGEX
.replace_all(&github_url, "https://api.github.com/repos/$org/$repo")
.to_string();
let mut req = CLIENT.get(&rewritten);
if let Ok(username) = env::var("USERNAME_FOR_GITHUB") {
if let Ok(password) = env::var("TOKEN_FOR_GITHUB") {
// needs a token with at least public_repo scope
req = req.basic_auth(username, Some(password));
}
}
let resp = req.send().await;
match resp {
Err(err) => {
warn!("Error while getting {}: {}", github_url, err);
Err(CheckerError::HttpError {
status: err.status().unwrap().as_u16(),
location: Some(github_url.to_string()),
})
}
Ok(ok) => {
if !ok.status().is_success() {
return Err(CheckerError::HttpError {
status: ok.status().as_u16(),
location: None,
});
}
let raw = ok.text().await.unwrap();
match serde_json::from_str::<RepoInfo>(&raw) {
Ok(val) => Ok(Info {
name: val.full_name,
description: val.description.unwrap_or_default(),
hacktoberfest: val.topics.iter().any(|t| *t == "hacktoberfest"),
}),
Err(_) => {
panic!("{}", raw);
}
}
}
}
}
fn get_hacktoberfest(url: String) -> BoxFuture<'static, (String, Result<Info, CheckerError>)> {
debug!("Need handle for {}", url);
async move {
let _handle = HANDLES.get().await;
(url.clone(), get_hacktoberfest_core(url).await)
}
.boxed()
}
#[derive(Debug, Serialize, Deserialize)]
struct Info {
hacktoberfest: bool,
name: String,
description: String,
}
#[derive(Debug, Serialize, Deserialize)]
struct Link {
updated_at: DateTime<Local>,
info: Info,
}
type Results = BTreeMap<String, Link>;
#[tokio::main]
async fn main() -> Result<()> {
env_logger::init();
let markdown_input = fs::read_to_string("README.md").expect("Can't read README.md");
let parser = Parser::new(&markdown_input);
let mut used: BTreeSet<String> = BTreeSet::new();
let mut results: Results = fs::read_to_string("results/hacktoberfest.yaml")
.map_err(|e| format_err!("{}", e))
.and_then(|x| serde_yaml::from_str(&x).map_err(|e| format_err!("{}", e)))
.unwrap_or_default();
let mut url_checks = vec![];
let mut do_check = |url: String| {
if !url.starts_with("http") {
return;
}
if used.contains(&url) {
return;
}
used.insert(url.clone());
if results.contains_key(&url) {
return;
}
let check = get_hacktoberfest(url).boxed();
url_checks.push(check);
};
let mut to_check: Vec<String> = vec![];
for (event, _) in parser.into_offset_iter() {
if let Event::Start(tag) = event {
if let Tag::Link(_link_type, url, _title) | Tag::Image(_link_type, url, _title) = tag {
if GITHUB_REPO_REGEX.is_match(&url) {
to_check.push(url.to_string());
}
}
}
}
for url in to_check {
do_check(url)
}
let results_keys = results.keys().cloned().collect::<BTreeSet<String>>();
let old_links = results_keys.difference(&used);
for link in old_links {
results.remove(link).unwrap();
}
fs::write("results/results.yaml", serde_yaml::to_string(&results)?)?;
let mut not_written = 0;
let mut last_written = Local::now();
let mut failed: u32 = 0;
while !url_checks.is_empty() {
debug!("Waiting for {}", url_checks.len());
let ((url, res), _index, remaining) = select_all(url_checks).await;
url_checks = remaining;
match res {
Ok(info) => {
print!("\u{2714} ");
if let Some(link) = results.get_mut(&url) {
link.updated_at = Local::now();
link.info = info
} else {
results.insert(
url.clone(),
Link {
updated_at: Local::now(),
info,
},
);
}
}
Err(_) => {
print!("\u{2718} ");
println!("{}", url);
failed += 1;
}
}
std::io::stdout().flush().unwrap();
not_written += 1;
let duration = Local::now() - last_written;
if duration > Duration::seconds(5) || not_written > 20 {
fs::write(
"results/hacktoberfest.yaml",
serde_yaml::to_string(&results)?,
)?;
not_written = 0;
last_written = Local::now();
}
}
fs::write(
"results/hacktoberfest.yaml",
serde_yaml::to_string(&results)?,
)?;
println!();
if failed == 0 {
println!("All awesome-rust repos tagged with 'hacktoberfest'");
let mut sorted_repos = results
.keys()
.map(|s| s.to_string())
.collect::<Vec<String>>();
sorted_repos.sort_by_key(|a| a.to_lowercase());
for name in sorted_repos {
let link = results.get(&name).unwrap();
if link.info.hacktoberfest {
println!(
"* [{}]({}) - {}",
link.info.name, name, link.info.description
)
}
}
Ok(())
} else {
Err(format_err!("{} urls with errors", failed))
}
}
| rust | CC0-1.0 | 87566de6df053370ed1fe6f0baa242a2b96311c8 | 2026-01-04T15:31:59.375418Z | false |
rust-unofficial/awesome-rust | https://github.com/rust-unofficial/awesome-rust/blob/87566de6df053370ed1fe6f0baa242a2b96311c8/src/bin/cleanup.rs | src/bin/cleanup.rs | // Cleans up `README.md`
// Usage: cargo run --bin cleanup
use std::fs;
use std::fs::File;
use std::io::Read;
fn fix_dashes(lines: Vec<String>) -> Vec<String> {
let mut fixed_lines: Vec<String> = Vec::with_capacity(lines.len());
let mut within_content = false;
for line in lines {
if within_content {
fixed_lines.push(line.replace(" — ", " - "));
} else {
if line.starts_with("## Applications") {
within_content = true;
}
fixed_lines.push(line.to_string());
}
}
fixed_lines
}
fn main() {
// Read the awesome file.
let mut file = File::open("README.md").expect("Failed to read the file");
let mut contents = String::new();
file.read_to_string(&mut contents)
.expect("Failed to read file contents");
// Split contents into lines.
let lines: Vec<String> = contents.lines().map(|l| l.to_string()).collect();
// Fix the dashes.
let fixed_contents = fix_dashes(lines);
// Write the awesome file.
fs::write("README.md", fixed_contents.join("\n").as_bytes())
.expect("Failed to write to the file");
}
| rust | CC0-1.0 | 87566de6df053370ed1fe6f0baa242a2b96311c8 | 2026-01-04T15:31:59.375418Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/build.rs | build.rs | use std::fs::{self, File};
use std::io;
use std::io::Write;
use shadow_rs::SdResult;
fn main() -> SdResult<()> {
shadow_rs::ShadowBuilder::builder()
.hook(gen_presets_hook)
.build()?;
#[cfg(windows)]
{
let mut res = winres::WindowsResource::new();
res.set_manifest_file("starship.exe.manifest")
.set_icon("media/icon.ico");
res.compile()?;
}
Ok(())
}
fn gen_presets_hook(mut file: &File) -> SdResult<()> {
println!("cargo:rerun-if-changed=docs/public/presets/toml");
let paths = fs::read_dir("docs/public/presets/toml")?;
let mut sortedpaths = paths.collect::<io::Result<Vec<_>>>()?;
sortedpaths.sort_by_key(std::fs::DirEntry::path);
let mut presets = String::new();
let mut match_arms = String::new();
for unwrapped in sortedpaths {
let file_name = unwrapped.file_name();
let full_path = dunce::canonicalize(unwrapped.path())?;
let full_path = full_path.to_str().expect("failed to convert to string");
let name = file_name
.to_str()
.and_then(|v| v.strip_suffix(".toml"))
.expect("Failed to process filename");
presets.push_str(format!("print::Preset(\"{name}\"),\n").as_str());
match_arms.push_str(format!(r#""{name}" => include_bytes!(r"{full_path}"),"#).as_str());
}
writeln!(
file,
r"
use crate::print;
pub fn get_preset_list<'a>() -> &'a [print::Preset] {{
&[
{presets}
]
}}
pub fn get_preset_content(name: &str) -> &[u8] {{
match name {{
{match_arms}
_ => unreachable!(),
}}
}}
"
)?;
Ok(())
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/config.rs | src/config.rs | use crate::configs::Palette;
use crate::context::Context;
use crate::serde_utils::{ValueDeserializer, ValueRef};
use crate::utils;
use nu_ansi_term::Color;
use serde::{
Deserialize, Deserializer, Serialize, de::Error as SerdeError, de::value::Error as ValueError,
};
use std::borrow::Cow;
use std::clone::Clone;
use std::collections::HashMap;
use std::ffi::OsStr;
use std::io::ErrorKind;
use toml::Value;
/// Root config of a module.
pub trait ModuleConfig<'a, E>
where
Self: Default,
E: SerdeError,
{
/// Construct a `ModuleConfig` from a toml value.
fn from_config<V: Into<ValueRef<'a>>>(config: V) -> Result<Self, E>;
/// Loads the TOML value into the config.
/// Missing values are set to their default values.
/// On error, logs an error message.
fn load<V: Into<ValueRef<'a>>>(config: V) -> Self {
match Self::from_config(config) {
Ok(config) => config,
Err(e) => {
log::warn!("Failed to load config value: {e}");
Self::default()
}
}
}
/// Helper function that will call `ModuleConfig::from_config(config)` if config is Some,
/// or `ModuleConfig::default()` if config is None.
fn try_load<V: Into<ValueRef<'a>>>(config: Option<V>) -> Self {
config.map(Into::into).map(Self::load).unwrap_or_default()
}
}
impl<'a, T: Deserialize<'a> + Default> ModuleConfig<'a, ValueError> for T {
/// Create `ValueDeserializer` wrapper and use it to call `Deserialize::deserialize` on it.
fn from_config<V: Into<ValueRef<'a>>>(config: V) -> Result<Self, ValueError> {
let config = config.into();
let deserializer = ValueDeserializer::new(config);
T::deserialize(deserializer).or_else(|err| {
// If the error is an unrecognized key, print a warning and run
// deserialize ignoring that error. Otherwise, just return the error
if err.to_string().contains("Unknown key") {
log::warn!("{err}");
let deserializer2 = ValueDeserializer::new(config).with_allow_unknown_keys();
T::deserialize(deserializer2)
} else {
Err(err)
}
})
}
}
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(untagged)]
pub enum Either<A, B> {
First(A),
Second(B),
}
/// A wrapper around `Vec<T>` that implements `ModuleConfig`, and either
/// accepts a value of type `T` or a list of values of type `T`.
#[derive(Clone, Default, Serialize)]
pub struct VecOr<T>(pub Vec<T>);
impl<'de, T> Deserialize<'de> for VecOr<T>
where
T: Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let either = Either::<Vec<T>, T>::deserialize(deserializer)?;
match either {
Either::First(v) => Ok(Self(v)),
Either::Second(s) => Ok(Self(vec![s])),
}
}
}
#[cfg(feature = "config-schema")]
impl<T> schemars::JsonSchema for VecOr<T>
where
T: schemars::JsonSchema + Sized,
{
fn schema_name() -> Cow<'static, str> {
Either::<T, Vec<T>>::schema_name()
}
fn schema_id() -> Cow<'static, str> {
let mod_path = module_path!();
Cow::Owned(format!("{mod_path}::{}", Self::schema_name()))
}
fn json_schema(generator: &mut schemars::generate::SchemaGenerator) -> schemars::Schema {
Either::<T, Vec<T>>::json_schema(generator)
}
}
/// Root config of starship.
#[derive(Default)]
pub struct StarshipConfig {
pub config: Option<toml::Table>,
}
impl StarshipConfig {
/// Initialize the Config struct
pub fn initialize(config_file_path: Option<&OsStr>) -> Self {
Self::config_from_file(config_file_path)
.map(|config| Self {
config: Some(config),
})
.unwrap_or_default()
}
/// Create a config from a starship configuration file
fn config_from_file(config_file_path: Option<&OsStr>) -> Option<toml::Table> {
let toml_content = Self::read_config_content_as_str(config_file_path)?;
match toml::from_str(&toml_content) {
Ok(parsed) => {
log::debug!("Config parsed: {:?}", &parsed);
Some(parsed)
}
Err(error) => {
log::error!("Unable to parse the config file: {error}");
None
}
}
}
pub fn read_config_content_as_str(config_file_path: Option<&OsStr>) -> Option<String> {
if config_file_path.is_none() {
log::debug!(
"Unable to determine `config_file_path`. Perhaps `utils::home_dir` is not defined on your platform?"
);
return None;
}
let config_file_path = config_file_path.as_ref().unwrap();
match utils::read_file(config_file_path) {
Ok(content) => {
log::trace!("Config file content: \"\n{}\"", &content);
Some(content)
}
Err(e) => {
let level = if e.kind() == ErrorKind::NotFound {
log::Level::Debug
} else {
log::Level::Error
};
log::log!(level, "Unable to read config file content: {}", &e);
None
}
}
}
/// Get the subset of the table for a module by its name
pub fn get_module_config(&self, module_name: &str) -> Option<&Value> {
let module_config = self.get_config(&[module_name]);
if module_config.is_some() {
log::debug!(
"Config found for \"{}\": {:?}",
&module_name,
&module_config
);
}
module_config
}
/// Get the value of the config in a specific path
pub fn get_config(&self, path: &[&str]) -> Option<&Value> {
let mut prev_table = self.config.as_ref()?;
assert_ne!(
path.len(),
0,
"Starship::get_config called with an empty path"
);
let (table_options, _) = path.split_at(path.len() - 1);
// Assumes all keys except the last in path has a table
for option in table_options {
if let Some(value) = prev_table.get(*option) {
if let Some(value) = value.as_table() {
prev_table = value;
} else {
log::trace!(
"No config found for \"{}\": \"{}\" is not a table",
path.join("."),
&option
);
return None;
}
} else if prev_table.contains_key(*option) {
log::trace!(
"No config found for \"{}\": \"{}\" is not a table",
path.join("."),
&option
);
return None;
}
}
let last_option = path.last().unwrap();
let value = prev_table.get(*last_option);
if value.is_none() {
log::trace!(
"No config found for \"{}\": Option \"{}\" not found",
path.join("."),
&last_option
);
}
value
}
/// Get the subset of the table for a custom module by its name
pub fn get_custom_module_config(&self, module_name: &str) -> Option<&Value> {
let module_config = self.get_config(&["custom", module_name]);
if module_config.is_some() {
log::debug!(
"Custom config found for \"{}\": {:?}",
&module_name,
&module_config
);
}
module_config
}
/// Get the table of all the registered custom modules, if any
pub fn get_custom_modules(&self) -> Option<&toml::value::Table> {
self.get_config(&["custom"])?.as_table()
}
/// Get the table of all the registered `env_var` modules, if any
pub fn get_env_var_modules(&self) -> Option<&toml::value::Table> {
self.get_config(&["env_var"])?.as_table()
}
}
/// Deserialize a style string in the starship format with serde
pub fn deserialize_style<'de, D>(de: D) -> Result<Style, D::Error>
where
D: Deserializer<'de>,
{
Cow::<'_, str>::deserialize(de).and_then(|s| {
parse_style_string(s.as_ref(), None).ok_or_else(|| D::Error::custom("Invalid style string"))
})
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum PrevColor {
Fg,
Bg,
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
/// Wrapper for `nu_ansi_term::Style` that supports referencing the previous style's foreground/background color.
pub struct Style {
style: nu_ansi_term::Style,
bg: Option<PrevColor>,
fg: Option<PrevColor>,
}
impl Style {
pub fn to_ansi_style(&self, prev: Option<&nu_ansi_term::Style>) -> nu_ansi_term::Style {
let Some(prev_style) = prev else {
return self.style;
};
let mut current = self.style;
if let Some(prev_color) = self.bg {
match prev_color {
PrevColor::Fg => current.background = prev_style.foreground,
PrevColor::Bg => current.background = prev_style.background,
}
}
if let Some(prev_color) = self.fg {
match prev_color {
PrevColor::Fg => current.foreground = prev_style.foreground,
PrevColor::Bg => current.foreground = prev_style.background,
}
}
current
}
fn map_style<F>(&self, f: F) -> Self
where
F: FnOnce(&nu_ansi_term::Style) -> nu_ansi_term::Style,
{
Self {
style: f(&self.style),
..*self
}
}
fn fg(&self, prev_color: PrevColor) -> Self {
Self {
fg: Some(prev_color),
..*self
}
}
fn bg(&self, prev_color: PrevColor) -> Self {
Self {
bg: Some(prev_color),
..*self
}
}
}
impl From<nu_ansi_term::Style> for Style {
fn from(value: nu_ansi_term::Style) -> Self {
Self {
style: value,
..Default::default()
}
}
}
impl From<nu_ansi_term::Color> for Style {
fn from(value: nu_ansi_term::Color) -> Self {
Self {
style: value.into(),
..Default::default()
}
}
}
/** Parse a style string which represents an ansi style. Valid tokens in the style
string include the following:
- 'fg:<color>' (specifies that the color read should be a foreground color)
- 'bg:<color>' (specifies that the color read should be a background color)
- 'underline'
- 'bold'
- 'italic'
- 'inverted'
- 'blink'
- '`prev_fg`' (specifies the color should be the previous foreground color)
- '`prev_bg`' (specifies the color should be the previous background color)
- '<color>' (see the `parse_color_string` doc for valid color strings)
*/
pub fn parse_style_string(style_string: &str, context: Option<&Context>) -> Option<Style> {
style_string
.split_whitespace()
.try_fold(Style::default(), |style, token| {
let token = token.to_lowercase();
// Check for FG/BG identifiers and strip them off if appropriate
// If col_fg is true, color the foreground. If it's false, color the background.
let (token, col_fg) = if token.as_str().starts_with("fg:") {
(token.trim_start_matches("fg:").to_owned(), true)
} else if token.as_str().starts_with("bg:") {
(token.trim_start_matches("bg:").to_owned(), false)
} else {
(token, true) // Bare colors are assumed to color the foreground
};
match token.as_str() {
"underline" => Some(style.map_style(nu_ansi_term::Style::underline)),
"bold" => Some(style.map_style(nu_ansi_term::Style::bold)),
"italic" => Some(style.map_style(nu_ansi_term::Style::italic)),
"dimmed" => Some(style.map_style(nu_ansi_term::Style::dimmed)),
"inverted" => Some(style.map_style(nu_ansi_term::Style::reverse)),
"blink" => Some(style.map_style(nu_ansi_term::Style::blink)),
"hidden" => Some(style.map_style(nu_ansi_term::Style::hidden)),
"strikethrough" => Some(style.map_style(nu_ansi_term::Style::strikethrough)),
"prev_fg" if col_fg => Some(style.fg(PrevColor::Fg)),
"prev_fg" => Some(style.bg(PrevColor::Fg)),
"prev_bg" if col_fg => Some(style.fg(PrevColor::Bg)),
"prev_bg" => Some(style.bg(PrevColor::Bg)),
// When the string is supposed to be a color:
// Decide if we yield none, reset background or set color.
color_string => {
if color_string == "none" && col_fg {
None // fg:none yields no style.
} else {
// Either bg or valid color or both.
let parsed = parse_color_string(
color_string,
context.and_then(|x| {
get_palette(
&x.root_config.palettes,
x.root_config.palette.as_deref(),
)
}),
);
// bg + invalid color = reset the background to default.
if !col_fg && parsed.is_none() {
let mut new_style = style;
new_style.style.background = Option::None;
Some(new_style)
} else {
// Valid color, apply color to either bg or fg
parsed.map(|ansi_color| {
if col_fg {
style.map_style(|s| s.fg(ansi_color))
} else {
style.map_style(|s| s.on(ansi_color))
}
})
}
}
}
}
})
}
/** Parse a string that represents a color setting, returning None if this fails
There are three valid color formats:
- #RRGGBB (a hash followed by an RGB hex)
- u8 (a number from 0-255, representing an ANSI color)
- colstring (one of the 16 predefined color strings or a custom user-defined color)
*/
fn parse_color_string(
color_string: &str,
palette: Option<&Palette>,
) -> Option<nu_ansi_term::Color> {
// Parse RGB hex values
log::trace!("Parsing color_string: {color_string}");
if color_string.starts_with('#') {
log::trace!("Attempting to read hexadecimal color string: {color_string}");
if color_string.len() != 7 {
log::debug!("Could not parse hexadecimal string: {color_string}");
return None;
}
let r: u8 = u8::from_str_radix(&color_string[1..3], 16).ok()?;
let g: u8 = u8::from_str_radix(&color_string[3..5], 16).ok()?;
let b: u8 = u8::from_str_radix(&color_string[5..7], 16).ok()?;
log::trace!("Read RGB color string: {r},{g},{b}");
return Some(Color::Rgb(r, g, b));
}
// Parse a u8 (ansi color)
if let Result::Ok(ansi_color_num) = color_string.parse::<u8>() {
log::trace!("Read ANSI color string: {ansi_color_num}");
return Some(Color::Fixed(ansi_color_num));
}
// Check palette for a matching user-defined color
if let Some(palette_color) = palette.as_ref().and_then(|x| x.get(color_string)) {
log::trace!("Read user-defined color string: {color_string} defined as {palette_color}");
return parse_color_string(palette_color, None);
}
// Check for any predefined color strings
// There are no predefined enums for bright colors, so we use Color::Fixed
let predefined_color = match color_string.to_lowercase().as_str() {
"black" => Some(Color::Black),
"red" => Some(Color::Red),
"green" => Some(Color::Green),
"yellow" => Some(Color::Yellow),
"blue" => Some(Color::Blue),
"purple" => Some(Color::Purple),
"cyan" => Some(Color::Cyan),
"white" => Some(Color::White),
"bright-black" => Some(Color::DarkGray), // "bright-black" is dark grey
"bright-red" => Some(Color::LightRed),
"bright-green" => Some(Color::LightGreen),
"bright-yellow" => Some(Color::LightYellow),
"bright-blue" => Some(Color::LightBlue),
"bright-purple" => Some(Color::LightPurple),
"bright-cyan" => Some(Color::LightCyan),
"bright-white" => Some(Color::LightGray),
_ => None,
};
if predefined_color.is_some() {
log::trace!("Read predefined color: {color_string}");
} else {
log::debug!("Could not parse color in string: {color_string}");
}
predefined_color
}
fn get_palette<'a>(
palettes: &'a HashMap<String, Palette>,
palette_name: Option<&str>,
) -> Option<&'a Palette> {
if let Some(palette_name) = palette_name {
let palette = palettes.get(palette_name);
if palette.is_some() {
log::trace!("Found color palette: {palette_name}");
} else {
log::warn!("Could not find color palette: {palette_name}");
}
palette
} else {
log::trace!("No color palette specified, using defaults");
None
}
}
#[cfg(test)]
mod tests {
use super::*;
use nu_ansi_term::Style as AnsiStyle;
// Small wrapper to allow deserializing Style without a struct with #[serde(deserialize_with=)]
#[derive(Default, Clone, Debug, PartialEq)]
struct StyleWrapper(Style);
impl<'de> Deserialize<'de> for StyleWrapper {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserialize_style(deserializer).map(Self)
}
}
#[test]
fn test_load_config() {
#[derive(Clone, Default, Deserialize)]
struct TestConfig<'a> {
pub symbol: &'a str,
pub disabled: bool,
pub some_array: Vec<&'a str>,
}
let config = toml::toml! {
symbol = "T "
disabled = true
some_array = ["A"]
};
let rust_config = TestConfig::from_config(&config).unwrap();
assert_eq!(rust_config.symbol, "T ");
assert!(rust_config.disabled);
assert_eq!(rust_config.some_array, vec!["A"]);
}
#[test]
fn test_load_nested_config() {
#[derive(Clone, Default, Deserialize)]
#[serde(default)]
struct TestConfig<'a> {
#[serde(borrow)]
pub untracked: SegmentDisplayConfig<'a>,
#[serde(borrow)]
pub modified: SegmentDisplayConfig<'a>,
}
#[derive(PartialEq, Debug, Clone, Default, Deserialize)]
#[serde(default)]
struct SegmentDisplayConfig<'a> {
pub value: &'a str,
#[serde(deserialize_with = "deserialize_style")]
pub style: Style,
}
let config = toml::toml! {
untracked.value = "x"
modified = { value = "∙", style = "red" }
};
let git_status_config = TestConfig::from_config(&config).unwrap();
assert_eq!(
git_status_config.untracked,
SegmentDisplayConfig {
value: "x",
style: Style::default(),
}
);
assert_eq!(
git_status_config.modified,
SegmentDisplayConfig {
value: "∙",
style: Color::Red.normal().into(),
}
);
}
#[test]
fn test_load_optional_config() {
#[derive(Clone, Default, Deserialize)]
#[serde(default)]
struct TestConfig<'a> {
pub optional: Option<&'a str>,
pub hidden: Option<&'a str>,
}
let config = toml::toml! {
optional = "test"
};
let rust_config = TestConfig::from_config(&config).unwrap();
assert_eq!(rust_config.optional, Some("test"));
assert_eq!(rust_config.hidden, None);
}
#[test]
fn test_load_enum_config() {
#[derive(Clone, Default, Deserialize)]
#[serde(default)]
struct TestConfig {
pub switch_a: Switch,
pub switch_b: Switch,
pub switch_c: Switch,
}
#[derive(Debug, PartialEq, Clone, Default)]
enum Switch {
On,
#[default]
Off,
}
impl<'de> Deserialize<'de> for Switch {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
match s.to_ascii_lowercase().as_str() {
"on" => Ok(Self::On),
_ => Ok(Self::Off),
}
}
}
let config = toml::toml! {
switch_a = "on"
switch_b = "any"
};
let rust_config = TestConfig::from_config(&config).unwrap();
assert_eq!(rust_config.switch_a, Switch::On);
assert_eq!(rust_config.switch_b, Switch::Off);
assert_eq!(rust_config.switch_c, Switch::Off);
}
#[test]
fn test_load_unknown_key_config() {
#[derive(Clone, Default, Deserialize)]
#[serde(default)]
struct TestConfig<'a> {
pub foo: &'a str,
}
let config = toml::toml! {
foo = "test"
bar = "ignore me"
};
let rust_config = TestConfig::from_config(&config);
assert!(rust_config.is_ok());
assert_eq!(rust_config.unwrap().foo, "test");
}
#[test]
fn test_from_string() {
let config = Value::String(String::from("S"));
assert_eq!(<&str>::from_config(&config).unwrap(), "S");
}
#[test]
fn test_from_bool() {
let config = Value::Boolean(true);
assert!(<bool>::from_config(&config).unwrap());
}
#[test]
fn test_from_i64() {
let config = Value::Integer(42);
assert_eq!(<i64>::from_config(&config).unwrap(), 42);
}
#[test]
fn test_from_style() {
let config = Value::from("red bold");
assert_eq!(
<StyleWrapper>::from_config(&config).unwrap().0,
Color::Red.bold().into()
);
}
#[test]
fn test_from_hex_color_style() {
let config = Value::from("#00000");
assert!(<StyleWrapper>::from_config(&config).is_err());
let config = Value::from("#0000000");
assert!(<StyleWrapper>::from_config(&config).is_err());
let config = Value::from("#NOTHEX");
assert!(<StyleWrapper>::from_config(&config).is_err());
let config = Value::from("#a12BcD");
assert_eq!(
<StyleWrapper>::from_config(&config).unwrap().0,
Color::Rgb(0xA1, 0x2B, 0xCD).into()
);
}
#[test]
fn test_from_vec() {
let config: Value = Value::Array(vec![Value::from("S")]);
assert_eq!(<Vec<&str>>::from_config(&config).unwrap(), vec!["S"]);
}
#[test]
fn test_from_option() {
let config: Value = Value::String(String::from("S"));
assert_eq!(<Option<&str>>::from_config(&config).unwrap(), Some("S"));
}
#[test]
fn table_get_styles_bold_italic_underline_green_dimmed_silly_caps() {
let config = Value::from("bOlD ItAlIc uNdErLiNe GrEeN diMMeD");
let mystyle = <StyleWrapper>::from_config(&config).unwrap().0;
assert!(mystyle.to_ansi_style(None).is_bold);
assert!(mystyle.to_ansi_style(None).is_italic);
assert!(mystyle.to_ansi_style(None).is_underline);
assert!(mystyle.to_ansi_style(None).is_dimmed);
assert_eq!(
mystyle.to_ansi_style(None),
AnsiStyle::new()
.bold()
.italic()
.underline()
.dimmed()
.fg(Color::Green)
);
}
#[test]
fn table_get_styles_bold_italic_underline_green_dimmed_inverted_silly_caps() {
let config = Value::from("bOlD ItAlIc uNdErLiNe GrEeN diMMeD InVeRTed");
let mystyle = <StyleWrapper>::from_config(&config).unwrap().0;
assert!(mystyle.to_ansi_style(None).is_bold);
assert!(mystyle.to_ansi_style(None).is_italic);
assert!(mystyle.to_ansi_style(None).is_underline);
assert!(mystyle.to_ansi_style(None).is_dimmed);
assert!(mystyle.to_ansi_style(None).is_reverse);
assert_eq!(
mystyle.to_ansi_style(None),
AnsiStyle::new()
.bold()
.italic()
.underline()
.dimmed()
.reverse()
.fg(Color::Green)
);
}
#[test]
fn table_get_styles_bold_italic_underline_green_dimmed_blink_silly_caps() {
let config = Value::from("bOlD ItAlIc uNdErLiNe GrEeN diMMeD bLiNk");
let mystyle = <StyleWrapper>::from_config(&config).unwrap().0;
assert!(mystyle.to_ansi_style(None).is_bold);
assert!(mystyle.to_ansi_style(None).is_italic);
assert!(mystyle.to_ansi_style(None).is_underline);
assert!(mystyle.to_ansi_style(None).is_dimmed);
assert!(mystyle.to_ansi_style(None).is_blink);
assert_eq!(
mystyle.to_ansi_style(None),
AnsiStyle::new()
.bold()
.italic()
.underline()
.dimmed()
.blink()
.fg(Color::Green)
);
}
#[test]
fn table_get_styles_bold_italic_underline_green_dimmed_hidden_silly_caps() {
let config = Value::from("bOlD ItAlIc uNdErLiNe GrEeN diMMeD hIDDen");
let mystyle = <StyleWrapper>::from_config(&config).unwrap().0;
assert!(mystyle.to_ansi_style(None).is_bold);
assert!(mystyle.to_ansi_style(None).is_italic);
assert!(mystyle.to_ansi_style(None).is_underline);
assert!(mystyle.to_ansi_style(None).is_dimmed);
assert!(mystyle.to_ansi_style(None).is_hidden);
assert_eq!(
mystyle.to_ansi_style(None),
AnsiStyle::new()
.bold()
.italic()
.underline()
.dimmed()
.hidden()
.fg(Color::Green)
);
}
#[test]
fn table_get_styles_bold_italic_underline_green_dimmed_strikethrough_silly_caps() {
let config = Value::from("bOlD ItAlIc uNdErLiNe GrEeN diMMeD StRiKEthROUgh");
let mystyle = <StyleWrapper>::from_config(&config).unwrap().0;
assert!(mystyle.to_ansi_style(None).is_bold);
assert!(mystyle.to_ansi_style(None).is_italic);
assert!(mystyle.to_ansi_style(None).is_underline);
assert!(mystyle.to_ansi_style(None).is_dimmed);
assert!(mystyle.to_ansi_style(None).is_strikethrough);
assert_eq!(
mystyle.to_ansi_style(None),
AnsiStyle::new()
.bold()
.italic()
.underline()
.dimmed()
.strikethrough()
.fg(Color::Green)
);
}
#[test]
fn table_get_styles_plain_and_broken_styles() {
// Test a "plain" style with no formatting
let config = Value::from("");
let plain_style = <StyleWrapper>::from_config(&config).unwrap().0;
assert_eq!(plain_style.to_ansi_style(None), AnsiStyle::new());
// Test a string that's clearly broken
let config = Value::from("djklgfhjkldhlhk;j");
assert!(<StyleWrapper>::from_config(&config).is_err());
// Test a string that's nullified by `none`
let config = Value::from("fg:red bg:green bold none");
assert!(<StyleWrapper>::from_config(&config).is_err());
// Test a string that's nullified by `none` at the start
let config = Value::from("none fg:red bg:green bold");
assert!(<StyleWrapper>::from_config(&config).is_err());
}
#[test]
fn table_get_styles_with_none() {
// Test that none on the end will result in None, overriding bg:none
let config = Value::from("fg:red bg:none none");
assert!(<StyleWrapper>::from_config(&config).is_err());
// Test that none in front will result in None, overriding bg:none
let config = Value::from("none fg:red bg:none");
assert!(<StyleWrapper>::from_config(&config).is_err());
// Test that none in the middle will result in None, overriding bg:none
let config = Value::from("fg:red none bg:none");
assert!(<StyleWrapper>::from_config(&config).is_err());
// Test that fg:none will result in None
let config = Value::from("fg:none bg:black");
assert!(<StyleWrapper>::from_config(&config).is_err());
// Test that bg:none will yield a style
let config = Value::from("fg:red bg:none");
assert_eq!(
<StyleWrapper>::from_config(&config).unwrap().0,
Color::Red.normal().into()
);
// Test that bg:none will yield a style
let config = Value::from("fg:red bg:none bold");
assert_eq!(
<StyleWrapper>::from_config(&config).unwrap().0,
Color::Red.bold().into()
);
// Test that bg:none will overwrite the previous background colour
let config = Value::from("fg:red bg:green bold bg:none");
assert_eq!(
<StyleWrapper>::from_config(&config).unwrap().0,
Color::Red.bold().into()
);
}
#[test]
fn table_get_styles_previous() {
// Test that previous has no effect when there is no previous style
let both_prevfg = <StyleWrapper>::from_config(&Value::from(
"bold fg:black fg:prev_bg bg:prev_fg underline",
))
.unwrap()
.0;
assert_eq!(
both_prevfg.to_ansi_style(None),
AnsiStyle::default().fg(Color::Black).bold().underline()
);
// But if there is a style on the previous string, then use that
let prev_style = AnsiStyle::new()
.underline()
.fg(Color::Yellow)
.on(Color::Red);
assert_eq!(
both_prevfg.to_ansi_style(Some(&prev_style)),
AnsiStyle::new()
.fg(Color::Red)
.on(Color::Yellow)
.bold()
.underline()
);
// Test that all the combinations of previous colors work
let fg_prev_fg = <StyleWrapper>::from_config(&Value::from("fg:prev_fg"))
.unwrap()
.0;
assert_eq!(
fg_prev_fg.to_ansi_style(Some(&prev_style)),
AnsiStyle::new().fg(Color::Yellow)
);
let fg_prev_bg = <StyleWrapper>::from_config(&Value::from("fg:prev_bg"))
.unwrap()
.0;
assert_eq!(
fg_prev_bg.to_ansi_style(Some(&prev_style)),
AnsiStyle::new().fg(Color::Red)
);
let bg_prev_fg = <StyleWrapper>::from_config(&Value::from("bg:prev_fg"))
.unwrap()
.0;
assert_eq!(
bg_prev_fg.to_ansi_style(Some(&prev_style)),
AnsiStyle::new().on(Color::Yellow)
);
let bg_prev_bg = <StyleWrapper>::from_config(&Value::from("bg:prev_bg"))
.unwrap()
.0;
assert_eq!(
bg_prev_bg.to_ansi_style(Some(&prev_style)),
AnsiStyle::new().on(Color::Red)
);
}
#[test]
fn table_get_styles_ordered() {
// Test a background style with inverted order (also test hex + ANSI)
let config = Value::from("bg:#050505 underline fg:120");
let flipped_style = <StyleWrapper>::from_config(&config).unwrap().0;
assert_eq!(
flipped_style.to_ansi_style(None),
AnsiStyle::new()
.underline()
.fg(Color::Fixed(120))
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | true |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/lib.rs | src/lib.rs | #![warn(clippy::disallowed_methods)]
#[macro_use]
extern crate shadow_rs;
use std::thread::available_parallelism;
shadow!(shadow);
// Lib is present to allow for benchmarking
pub mod bug_report;
pub mod config;
pub mod configs;
pub mod configure;
pub mod context;
pub mod context_env;
pub mod formatter;
pub mod init;
pub mod logger;
pub mod module;
mod modules;
pub mod print;
mod segment;
mod serde_utils;
mod utils;
#[cfg(test)]
mod test;
/// Return the number of threads starship should use, if configured.
pub fn num_configured_starship_threads() -> Option<usize> {
std::env::var("STARSHIP_NUM_THREADS")
.ok()
.and_then(|s| s.parse().ok())
}
/// Return the maximum number of threads for the global thread-pool.
pub fn num_rayon_threads() -> usize {
num_configured_starship_threads()
// Default to the number of logical cores,
// but restrict the number of threads to 8
.unwrap_or_else(|| available_parallelism().map(usize::from).unwrap_or(1).min(8))
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/logger.rs | src/logger.rs | use crate::utils;
use log::{Level, LevelFilter, Metadata, Record};
use nu_ansi_term::Color;
use std::sync::OnceLock;
use std::{
cmp,
collections::HashSet,
env,
fs::{self, File, OpenOptions},
io::Write,
path::{Path, PathBuf},
sync::{Mutex, RwLock},
};
pub struct StarshipLogger {
log_file: OnceLock<Result<Mutex<File>, std::io::Error>>,
log_file_path: PathBuf,
log_file_content: RwLock<HashSet<String>>,
log_level: Level,
}
/// Returns the path to the log directory.
pub fn get_log_dir() -> PathBuf {
env::var_os("STARSHIP_CACHE")
.map(PathBuf::from)
.unwrap_or_else(|| {
utils::home_dir()
.map(|home| home.join(".cache"))
.or_else(dirs::cache_dir)
.unwrap_or_else(std::env::temp_dir)
.join("starship")
})
}
/// Deletes all log files in the log directory that were modified more than 24 hours ago.
pub fn cleanup_log_files<P: AsRef<Path>>(path: P) {
let log_dir = path.as_ref();
let Ok(log_files) = fs::read_dir(log_dir) else {
// Avoid noisily handling errors in this cleanup function.
return;
};
for file in log_files {
// Skip files that can't be read.
let Ok(file) = file else {
continue;
};
// Avoid deleting files that don't look like log files.
if !file
.path()
.file_name()
.unwrap_or_default()
.to_str()
.unwrap_or_default()
.starts_with("session_")
|| file.path().extension() != Some("log".as_ref())
{
continue;
}
// Read metadata to check file age.
let Ok(metadata) = file.metadata() else {
continue;
};
// Avoid handling anything that isn't a file.
if !metadata.is_file() {
continue;
}
// Get the file's modification time.
let Ok(modified) = metadata.modified() else {
continue;
};
// Delete the file if it hasn't changed in 24 hours.
if modified.elapsed().unwrap_or_default().as_secs() > 60 * 60 * 24 {
let _ = fs::remove_file(file.path());
}
}
}
impl Default for StarshipLogger {
fn default() -> Self {
let log_dir = get_log_dir();
if let Err(err) = fs::create_dir_all(&log_dir) {
eprintln!("Unable to create log dir {log_dir:?}: {err:?}!");
};
let session_log_file = log_dir.join(format!(
"session_{}.log",
env::var("STARSHIP_SESSION_KEY").unwrap_or_default()
));
Self {
log_file_content: RwLock::new(
fs::read_to_string(&session_log_file)
.unwrap_or_default()
.lines()
.map(std::string::ToString::to_string)
.collect(),
),
log_file: OnceLock::new(),
log_file_path: session_log_file,
log_level: env::var("STARSHIP_LOG")
.map(|level| match level.to_ascii_lowercase().as_str() {
"trace" => Level::Trace,
"debug" => Level::Debug,
"info" => Level::Info,
"warn" => Level::Warn,
"error" => Level::Error,
_ => Level::Warn,
})
.unwrap_or_else(|_| Level::Warn),
}
}
}
impl StarshipLogger {
/// Override the minimum log level
pub fn set_log_level(&mut self, level: log::Level) {
self.log_level = level;
}
/// Override the log level path
/// This won't change anything if a log file was already opened
pub fn set_log_file_path(&mut self, path: PathBuf) {
let contents = fs::read_to_string(&path)
.unwrap_or_default()
.lines()
.map(std::string::ToString::to_string)
.collect();
self.log_file_content = RwLock::new(contents);
self.log_file_path = path;
}
}
impl log::Log for StarshipLogger {
fn enabled(&self, metadata: &Metadata) -> bool {
metadata.level() <= self.log_level
}
fn log(&self, record: &Record) {
// Early return if the log level is not enabled
if !self.enabled(record.metadata()) {
return;
}
let to_print = format!(
"[{}] - ({}): {}",
record.level(),
record.module_path().unwrap_or_default(),
record.args()
);
// A log message is only printed or written to the log file,
// if it's not already in the log file or has been printed in this session.
// To help with debugging, duplicate detection only runs if the log level is warn or lower
let is_debug = record.level() > Level::Warn;
let is_duplicate = {
!is_debug
&& self
.log_file_content
.read()
.map(|c| c.contains(to_print.as_str()))
.unwrap_or(false)
};
if is_duplicate {
return;
}
// Write warning messages to the log file
// If log level is error, only write error messages to the log file
if record.level() <= cmp::min(Level::Warn, self.log_level) {
let log_file = match self.log_file.get_or_init(|| {
OpenOptions::new()
.create(true)
.append(true)
.open(&self.log_file_path)
.map(Mutex::new)
}) {
Ok(log_file) => log_file,
Err(err) => {
eprintln!(
"Unable to open session log file {:?}: {err:?}!",
self.log_file_path
);
return;
}
};
let mut file_handle = match log_file.lock() {
Ok(file_handle) => file_handle,
Err(err) => {
eprintln!("Log file writer mutex was poisoned! {err:?}",);
return;
}
};
if let Err(err) = writeln!(file_handle, "{to_print}") {
eprintln!("Unable to write to session log file {err:?}!",);
};
}
// Print messages to stderr
eprintln!(
"[{}] - ({}): {}",
match record.level() {
Level::Trace => Color::Blue.dimmed().paint(format!("{}", record.level())),
Level::Debug => Color::Cyan.paint(format!("{}", record.level())),
Level::Info => Color::White.paint(format!("{}", record.level())),
Level::Warn => Color::Yellow.paint(format!("{}", record.level())),
Level::Error => Color::Red.paint(format!("{}", record.level())),
},
record.module_path().unwrap_or_default(),
record.args()
);
// Add to duplicate detection set
if let Ok(mut c) = self.log_file_content.write() {
c.insert(to_print);
}
}
fn flush(&self) {
if let Some(Ok(m)) = self.log_file.get() {
let result = match m.lock() {
Ok(mut file) => file.flush(),
Err(err) => return eprintln!("Log file writer mutex was poisoned: {err:?}"),
};
if let Err(err) = result {
eprintln!("Unable to flush the log file: {err:?}");
}
}
}
}
pub fn init() {
log::set_boxed_logger(Box::<StarshipLogger>::default()).unwrap();
log::set_max_level(LevelFilter::Trace);
}
#[cfg(test)]
mod test {
use super::*;
use crate::utils::read_file;
use log::Log;
use std::fs::{File, FileTimes};
use std::io;
use std::time::SystemTime;
#[test]
fn test_log_to_file() -> io::Result<()> {
let log_dir = tempfile::tempdir()?;
let log_file = log_dir.path().join("test.log");
let mut logger = StarshipLogger::default();
logger.set_log_file_path(log_file.clone());
logger.set_log_level(Level::Warn);
// Load at all log levels
logger.log(
&Record::builder()
.level(Level::Error)
.args(format_args!("error"))
.build(),
);
logger.log(
&Record::builder()
.level(Level::Warn)
.args(format_args!("warn"))
.build(),
);
logger.log(
&Record::builder()
.level(Level::Info)
.args(format_args!("info"))
.build(),
);
logger.log(
&Record::builder()
.level(Level::Debug)
.args(format_args!("debug"))
.build(),
);
logger.log(
&Record::builder()
.level(Level::Trace)
.args(format_args!("trace"))
.build(),
);
// Print duplicate messages
logger.log(
&Record::builder()
.level(Level::Warn)
.args(format_args!("warn"))
.build(),
);
logger.log(
&Record::builder()
.level(Level::Error)
.args(format_args!("error"))
.build(),
);
logger.flush();
drop(logger);
let content = read_file(log_file)?;
assert_eq!(content, "[ERROR] - (): error\n[WARN] - (): warn\n");
log_dir.close()
}
#[test]
fn test_dedup_from_file() -> io::Result<()> {
let log_dir = tempfile::tempdir()?;
let log_file = log_dir.path().join("test.log");
{
let mut file = File::create(&log_file)?;
file.write_all(b"[WARN] - (): warn\n")?;
file.sync_all()?;
}
let mut logger = StarshipLogger::default();
logger.set_log_file_path(log_file.clone());
logger.set_log_level(Level::Warn);
// This message should not be printed or written to the log file
logger.log(
&Record::builder()
.level(Level::Warn)
.args(format_args!("warn"))
.build(),
);
// This message should be printed and written to the log file
logger.log(
&Record::builder()
.level(Level::Warn)
.args(format_args!("warn2"))
.build(),
);
logger.flush();
drop(logger);
let content = read_file(log_file)?;
assert_eq!(content, "[WARN] - (): warn\n[WARN] - (): warn2\n");
log_dir.close()
}
#[test]
fn test_cleanup() -> io::Result<()> {
let log_dir = tempfile::tempdir()?;
// Should not be deleted
let non_matching_file = log_dir.path().join("non-matching.log");
let non_matching_file2 = log_dir.path().join("session_.exe");
let new_file = log_dir.path().join("session_new.log");
let directory = log_dir.path().join("session_dir.log");
// Should be deleted
let old_file = log_dir.path().join("session_old.log");
for file in &[
&non_matching_file,
&non_matching_file2,
&new_file,
&old_file,
] {
File::create(file)?;
}
fs::create_dir(&directory)?;
let times = FileTimes::new()
.set_accessed(SystemTime::UNIX_EPOCH)
.set_modified(SystemTime::UNIX_EPOCH);
// Set all files except the new file to be older than 24 hours
for file in &[
&non_matching_file,
&non_matching_file2,
&old_file,
&directory,
] {
let Ok(f) = File::open(file) else {
panic!("Unable to open file {file:?}!")
};
match f.set_times(times) {
Err(err) if err.kind() == io::ErrorKind::PermissionDenied => {
// Ignore permission errors (e.g. on Windows)
eprintln!("Unable to set file times for {file:?}: {err:?}");
return Ok(());
}
other => other,
}?;
f.sync_all()?;
}
cleanup_log_files(log_dir.path());
for file in &[
&non_matching_file,
&non_matching_file2,
&new_file,
&directory,
] {
assert!(file.exists(), "File {file:?} should exist");
}
assert!(!old_file.exists(), "File {old_file:?} should not exist");
log_dir.close()
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/module.rs | src/module.rs | use crate::segment;
use crate::segment::{FillSegment, Segment};
use nu_ansi_term::{AnsiString, AnsiStrings, Style as AnsiStyle};
use std::fmt;
use std::time::Duration;
// List of all modules
// Default ordering is handled in configs/starship_root.rs
pub const ALL_MODULES: &[&str] = &[
"aws",
"azure",
#[cfg(feature = "battery")]
"battery",
"buf",
"bun",
"c",
"character",
"cmake",
"cmd_duration",
"cobol",
"conda",
"container",
"cpp",
"crystal",
"daml",
"dart",
"deno",
"directory",
"direnv",
"docker_context",
"dotnet",
"elixir",
"elm",
"erlang",
"fennel",
"fill",
"fortran",
"fossil_branch",
"fossil_metrics",
"gcloud",
"git_branch",
"git_commit",
"git_metrics",
"git_state",
"git_status",
"gleam",
"golang",
"gradle",
"guix_shell",
"haskell",
"haxe",
"helm",
"hg_branch",
"hg_state",
"hostname",
"java",
"jobs",
"julia",
"kotlin",
"kubernetes",
"line_break",
"localip",
"lua",
"memory_usage",
"meson",
"mise",
"mojo",
"nats",
"netns",
"nim",
"nix_shell",
"nodejs",
"ocaml",
"odin",
"opa",
"openstack",
"os",
"package",
"perl",
"php",
"pijul_channel",
"pixi",
"pulumi",
"purescript",
"python",
"quarto",
"raku",
"red",
"rlang",
"ruby",
"rust",
"scala",
"shell",
"shlvl",
"singularity",
"solidity",
"spack",
"status",
"sudo",
"swift",
"terraform",
"time",
"typst",
"username",
"vagrant",
"vcsh",
"vlang",
"xmake",
"zig",
];
/// A module is a collection of segments showing data for a single integration
/// (e.g. The git module shows the current git branch and status)
pub struct Module<'a> {
/// The module's configuration map if available
pub config: Option<&'a toml::Value>,
/// The module's name, to be used in configuration and logging.
name: String,
/// The module's description
description: String,
/// The collection of segments that compose this module.
pub segments: Vec<Segment>,
/// the time it took to compute this module
pub duration: Duration,
}
impl<'a> Module<'a> {
/// Creates a module with no segments.
pub fn new(
name: impl Into<String>,
desc: impl Into<String>,
config: Option<&'a toml::Value>,
) -> Self {
Self {
config,
name: name.into(),
description: desc.into(),
segments: Vec::new(),
duration: Duration::default(),
}
}
/// Set segments in module
pub fn set_segments(&mut self, segments: Vec<Segment>) {
self.segments = segments;
}
/// Get module's name
pub fn get_name(&self) -> &String {
&self.name
}
/// Get module's description
pub fn get_description(&self) -> &String {
&self.description
}
/// Whether a module has non-empty segments
pub fn is_empty(&self) -> bool {
self.segments
.iter()
// no trim: if we add spaces/linebreaks it's not "empty" as we change the final output
.all(|segment| segment.value().is_empty())
}
/// Get values of the module's segments
pub fn get_segments(&self) -> Vec<&str> {
self.segments.iter().map(segment::Segment::value).collect()
}
/// Returns a vector of colored `AnsiString` elements to be later used with
/// `AnsiStrings()` to optimize ANSI codes
pub fn ansi_strings(&self) -> Vec<AnsiString<'_>> {
self.ansi_strings_for_width(None)
}
pub fn ansi_strings_for_width(&self, width: Option<usize>) -> Vec<AnsiString<'_>> {
let mut iter = self.segments.iter().peekable();
let mut ansi_strings: Vec<AnsiString> = Vec::new();
while iter.peek().is_some() {
ansi_strings.extend(ansi_line(&mut iter, width));
}
ansi_strings
}
}
impl fmt::Display for Module<'_> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let ansi_strings = self.ansi_strings();
write!(f, "{}", AnsiStrings(&ansi_strings))
}
}
fn ansi_line<'a, I>(segments: &mut I, term_width: Option<usize>) -> Vec<AnsiString<'a>>
where
I: Iterator<Item = &'a Segment>,
{
let mut used = 0usize;
let mut current: Vec<AnsiString> = Vec::new();
let mut chunks: Vec<(Vec<AnsiString>, &FillSegment)> = Vec::new();
let mut prev_style: Option<AnsiStyle> = None;
for segment in segments {
match segment {
Segment::Fill(fs) => {
chunks.push((current, fs));
current = Vec::new();
prev_style = None;
}
_ => {
used += segment.width_graphemes();
let current_segment_string = segment.ansi_string(prev_style.as_ref());
prev_style = Some(*current_segment_string.style_ref());
current.push(current_segment_string);
}
}
if matches!(segment, Segment::LineTerm) {
break;
}
}
if chunks.is_empty() {
current
} else {
let fill_size = term_width
.and_then(|tw| if tw > used { Some(tw - used) } else { None })
.map(|remaining| remaining / chunks.len());
chunks
.into_iter()
.flat_map(|(strs, fill)| {
let fill_string = fill.ansi_string(
fill_size,
strs.last().map(nu_ansi_term::AnsiGenericString::style_ref),
);
strs.into_iter().chain(std::iter::once(fill_string))
})
.chain(current)
.collect::<Vec<AnsiString>>()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_all_modules_is_in_alphabetical_order() {
let mut sorted_modules: Vec<&str> = ALL_MODULES.to_vec();
sorted_modules.sort_unstable();
assert_eq!(sorted_modules.as_slice(), ALL_MODULES);
}
#[test]
fn test_module_is_empty_with_no_segments() {
let name = "unit_test";
let desc = "This is a unit test";
let module = Module {
config: None,
name: name.to_string(),
description: desc.to_string(),
segments: Vec::new(),
duration: Duration::default(),
};
assert!(module.is_empty());
}
#[test]
fn test_module_is_empty_with_all_empty_segments() {
let name = "unit_test";
let desc = "This is a unit test";
let module = Module {
config: None,
name: name.to_string(),
description: desc.to_string(),
segments: Segment::from_text(None, ""),
duration: Duration::default(),
};
assert!(module.is_empty());
}
#[test]
fn test_module_is_not_empty_with_linebreak_only() {
let name = "unit_test";
let desc = "This is a unit test";
let module = Module {
config: None,
name: name.to_string(),
description: desc.to_string(),
segments: Segment::from_text(None, "\n"),
duration: Duration::default(),
};
assert!(!module.is_empty());
}
#[test]
fn test_module_is_not_empty_with_space_only() {
let name = "unit_test";
let desc = "This is a unit test";
let module = Module {
config: None,
name: name.to_string(),
description: desc.to_string(),
segments: Segment::from_text(None, " "),
duration: Duration::default(),
};
assert!(!module.is_empty());
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/bug_report.rs | src/bug_report.rs | use crate::shadow;
use crate::utils::{self, DEFAULT_COMMAND_TIMEOUT_MS, exec_cmd};
use nu_ansi_term::Style;
use std::fs;
use std::path::PathBuf;
use std::time::Duration;
pub fn create() {
println!("{}\n", shadow::VERSION.trim());
let os_info = os_info::get();
let environment = Environment {
os_type: os_info.os_type(),
os_version: os_info.version().clone(),
shell_info: get_shell_info(),
terminal_info: get_terminal_info(),
starship_config: get_starship_config(),
};
let issue_body = get_github_issue_body(&environment);
println!(
"{}\n{issue_body}\n\n",
Style::new().bold().paint("Generated bug report:")
);
println!("Forward the pre-filled report above to GitHub in your browser?");
println!(
"{} To avoid any sensitive data from being exposed, please review the included information before proceeding. Data forwarded to GitHub is subject to GitHub's privacy policy.",
Style::new().bold().paint("Warning:")
);
println!(
"Enter `{}` to accept, or anything else to decline, and `{}` to confirm your choice:\n",
Style::new().bold().paint("y"),
Style::new().bold().paint("Enter key")
);
let mut input = String::new();
let _ = std::io::stdin().read_line(&mut input);
if input.trim().to_lowercase() == "y" {
let link = make_github_issue_link(&issue_body);
if let Err(e) = open::that(&link) {
println!("Failed to open issue report in your browser: {e}");
println!(
"Please copy the above report and open an issue manually, or try opening the following link:\n{link}"
);
}
} else {
println!(
"Will not open an issue in your browser! Please copy the above report and open an issue manually."
);
}
println!("Thanks for using the Starship bug report tool!");
}
const UNKNOWN_SHELL: &str = "<unknown shell>";
const UNKNOWN_TERMINAL: &str = "<unknown terminal>";
const UNKNOWN_VERSION: &str = "<unknown version>";
const UNKNOWN_CONFIG: &str = "<unknown config>";
const GITHUB_CHAR_LIMIT: usize = 8100; // Magic number accepted by Github
struct Environment {
os_type: os_info::Type,
os_version: os_info::Version,
shell_info: ShellInfo,
terminal_info: TerminalInfo,
starship_config: String,
}
fn get_pkg_branch_tag() -> &'static str {
#[allow(clippy::const_is_empty)]
if !shadow::TAG.is_empty() {
return shadow::TAG;
}
shadow::BRANCH
}
fn get_github_issue_body(environment: &Environment) -> String {
let shell_syntax = match environment.shell_info.name.as_ref() {
"powershell" | "pwsh" => "pwsh",
"fish" => "fish",
"cmd" => "lua",
// GitHub does not seem to support elvish syntax highlighting.
"elvish" => "bash",
_ => "bash",
};
format!("#### Current Behavior
<!-- A clear and concise description of the behavior. -->
#### Expected Behavior
<!-- A clear and concise description of what you expected to happen. -->
#### Additional context/Screenshots
<!-- Add any other context about the problem here. If applicable, add screenshots to help explain. -->
#### Possible Solution
<!--- Only if you have suggestions on a fix for the bug -->
#### Environment
- Starship version: {starship_version}
- {shell_name} version: {shell_version}
- Operating system: {os_name} {os_version}
- Terminal emulator: {terminal_name} {terminal_version}
- Git Commit Hash: {git_commit_hash}
- Branch/Tag: {pkg_branch_tag}
- Rust Version: {rust_version}
- Rust channel: {rust_channel} {build_rust_channel}
- Build Time: {build_time}
#### Relevant Shell Configuration
```{shell_syntax}
{shell_config}
```
#### Starship Configuration
```toml
{starship_config}
```",
starship_version = shadow::PKG_VERSION,
shell_name = environment.shell_info.name,
shell_version = environment.shell_info.version,
terminal_name = environment.terminal_info.name,
terminal_version = environment.terminal_info.version,
os_name = environment.os_type,
os_version = environment.os_version,
shell_config = environment.shell_info.config,
starship_config = environment.starship_config,
git_commit_hash = shadow::SHORT_COMMIT,
pkg_branch_tag = get_pkg_branch_tag(),
rust_version = shadow::RUST_VERSION,
rust_channel = shadow::RUST_CHANNEL,
build_rust_channel = shadow::BUILD_RUST_CHANNEL,
build_time = shadow::BUILD_TIME,
shell_syntax = shell_syntax,
)
}
fn make_github_issue_link(body: &str) -> String {
let escaped = urlencoding::encode(body).replace("%20", "+");
format!(
"https://github.com/starship/starship/issues/new?template={}&body={}",
urlencoding::encode("Bug_report.md"),
escaped
)
.chars()
.take(GITHUB_CHAR_LIMIT)
.collect()
}
#[derive(Debug)]
struct ShellInfo {
name: String,
version: String,
config: String,
}
fn get_shell_info() -> ShellInfo {
let shell = std::env::var("STARSHIP_SHELL");
if shell.is_err() {
return ShellInfo {
name: UNKNOWN_SHELL.to_string(),
version: UNKNOWN_VERSION.to_string(),
config: UNKNOWN_CONFIG.to_string(),
};
}
let shell = shell.unwrap();
let version = get_shell_version(&shell);
let config = get_config_path(&shell)
.and_then(|config_path| fs::read_to_string(config_path).ok())
.map_or_else(
|| UNKNOWN_CONFIG.to_string(),
|config| config.trim().to_string(),
);
ShellInfo {
name: shell,
version,
config,
}
}
#[derive(Debug)]
struct TerminalInfo {
name: String,
version: String,
}
fn get_terminal_info() -> TerminalInfo {
let terminal = std::env::var("TERM_PROGRAM")
.or_else(|_| std::env::var("LC_TERMINAL"))
.unwrap_or_else(|_| UNKNOWN_TERMINAL.to_string());
let version = std::env::var("TERM_PROGRAM_VERSION")
.or_else(|_| std::env::var("LC_TERMINAL_VERSION"))
.unwrap_or_else(|_| UNKNOWN_VERSION.to_string());
TerminalInfo {
name: terminal,
version,
}
}
fn get_config_path(shell: &str) -> Option<PathBuf> {
if shell == "nu" {
return dirs::config_dir().map(|config_dir| config_dir.join("nushell").join("config.nu"));
}
utils::home_dir().and_then(|home_dir| {
match shell {
"bash" => Some(".bashrc"),
"fish" => Some(".config/fish/config.fish"),
"ion" => Some(".config/ion/initrc"),
"powershell" | "pwsh" => {
if cfg!(windows) {
Some("Documents/PowerShell/Microsoft.PowerShell_profile.ps1")
} else {
Some(".config/powershell/Microsoft.PowerShell_profile.ps1")
}
}
"zsh" => Some(".zshrc"),
"elvish" => Some(".elvish/rc.elv"),
"tcsh" => Some(".tcshrc"),
"xonsh" => Some(".xonshrc"),
"cmd" => Some("AppData/Local/clink/starship.lua"),
_ => None,
}
.map(|path| home_dir.join(path))
})
}
fn get_starship_config() -> String {
std::env::var("STARSHIP_CONFIG")
.map(PathBuf::from)
.ok()
.or_else(|| {
utils::home_dir().map(|mut home_dir| {
home_dir.push(".config/starship.toml");
home_dir
})
})
.and_then(|config_path| fs::read_to_string(config_path).ok())
.unwrap_or_else(|| UNKNOWN_CONFIG.to_string())
}
fn get_shell_version(shell: &str) -> String {
let time_limit = Duration::from_millis(DEFAULT_COMMAND_TIMEOUT_MS);
match shell {
"powershell" => exec_cmd(
shell,
&["(Get-Host | Select Version | Format-Table -HideTableHeaders | Out-String).trim()"],
time_limit,
),
_ => exec_cmd(shell, &["--version"], time_limit),
}
.map_or_else(
|| UNKNOWN_VERSION.to_string(),
|output| output.stdout.trim().to_string(),
)
}
#[cfg(test)]
mod tests {
use super::*;
use std::env;
#[test]
fn test_make_github_link() {
let environment = Environment {
os_type: os_info::Type::Linux,
os_version: os_info::Version::Semantic(1, 2, 3),
shell_info: ShellInfo {
name: "test_shell".to_string(),
version: "2.3.4".to_string(),
config: "No config".to_string(),
},
terminal_info: TerminalInfo {
name: "test_terminal".to_string(),
version: "5.6.7".to_string(),
},
starship_config: "No Starship config".to_string(),
};
let body = get_github_issue_body(&environment);
let link = make_github_issue_link(&body);
assert!(link.contains(clap::crate_version!()));
assert!(link.contains("Linux"));
assert!(link.contains("1.2.3"));
assert!(link.contains("test_shell"));
assert!(link.contains("2.3.4"));
assert!(link.contains("No+config"));
assert!(link.contains("No+Starship+config"));
}
#[test]
#[cfg(not(windows))]
fn test_get_config_path() {
let config_path = get_config_path("bash");
assert_eq!(
utils::home_dir().unwrap().join(".bashrc"),
config_path.unwrap()
);
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/utils.rs | src/utils.rs | use process_control::{ChildExt, Control};
use std::ffi::OsStr;
use std::fmt::Debug;
use std::fs::read_to_string;
use std::io::{Error, ErrorKind, Result};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
use crate::context::Context;
use crate::context::Shell;
/// Default timeout for command execution in milliseconds
pub const DEFAULT_COMMAND_TIMEOUT_MS: u64 = 500;
/// Create a `PathBuf` from an absolute path, where the root directory will be mocked in test
#[cfg(not(test))]
#[inline]
#[allow(dead_code)]
pub fn context_path<S: AsRef<OsStr> + ?Sized>(_context: &Context, s: &S) -> PathBuf {
PathBuf::from(s)
}
/// Create a `PathBuf` from an absolute path, where the root directory will be mocked in test
#[cfg(test)]
#[allow(dead_code)]
pub fn context_path<S: AsRef<OsStr> + ?Sized>(context: &Context, s: &S) -> PathBuf {
let requested_path = PathBuf::from(s);
if requested_path.is_absolute() {
let mut path = PathBuf::from(context.root_dir.path());
path.extend(requested_path.components().skip(1));
path
} else {
requested_path
}
}
/// Return the string contents of a file
pub fn read_file<P: AsRef<Path> + Debug>(file_name: P) -> Result<String> {
log::trace!("Trying to read from {file_name:?}");
let result = read_to_string(file_name);
if result.is_err() {
log::debug!("Error reading file: {result:?}");
} else {
log::trace!("File read successfully");
}
result
}
/// Write a string to a file
#[cfg(test)]
pub fn write_file<P: AsRef<Path>, S: AsRef<str>>(file_name: P, text: S) -> Result<()> {
use std::io::Write;
let file_name = file_name.as_ref();
let text = text.as_ref();
log::trace!("Trying to write {text:?} to {file_name:?}");
let mut file = match std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(file_name)
{
Ok(file) => file,
Err(err) => {
log::warn!("Error creating file: {err:?}");
return Err(err);
}
};
match file.write_all(text.as_bytes()) {
Ok(()) => {
log::trace!("File {file_name:?} written successfully");
}
Err(err) => {
log::warn!("Error writing to file: {err:?}");
return Err(err);
}
}
file.sync_all()
}
/// Reads command output from stderr or stdout depending on to which stream program streamed it's output
pub fn get_command_string_output(command: CommandOutput) -> String {
if command.stdout.is_empty() {
command.stderr
} else {
command.stdout
}
}
/// Attempt to resolve `binary_name` from and creates a new `Command` pointing at it
/// This allows executing cmd files on Windows and prevents running executable from cwd on Windows
/// This function also initializes std{err,out,in} to protect against processes changing the console mode
pub fn create_command<T: AsRef<OsStr>>(binary_name: T) -> Result<Command> {
let binary_name = binary_name.as_ref();
log::trace!("Creating Command for binary {binary_name:?}");
let full_path = match which::which(binary_name) {
Ok(full_path) => {
log::trace!("Using {full_path:?} as {binary_name:?}");
full_path
}
Err(error) => {
log::trace!("Unable to find {binary_name:?} in PATH, {error:?}");
return Err(Error::new(ErrorKind::NotFound, error));
}
};
#[allow(clippy::disallowed_methods)]
let mut cmd = Command::new(full_path);
cmd.stderr(Stdio::piped())
.stdout(Stdio::piped())
.stdin(Stdio::null());
Ok(cmd)
}
#[derive(Debug, Clone)]
pub struct CommandOutput {
pub stdout: String,
pub stderr: String,
}
impl PartialEq for CommandOutput {
fn eq(&self, other: &Self) -> bool {
self.stdout == other.stdout && self.stderr == other.stderr
}
}
#[cfg(test)]
pub fn display_command<T: AsRef<OsStr> + Debug, U: AsRef<OsStr> + Debug>(
cmd: T,
args: &[U],
) -> String {
std::iter::once(cmd.as_ref())
.chain(args.iter().map(AsRef::as_ref))
.map(|i| i.to_string_lossy().into_owned())
.collect::<Vec<String>>()
.join(" ")
}
/// Execute a command and return the output on stdout and stderr if successful
pub fn exec_cmd<T: AsRef<OsStr> + Debug, U: AsRef<OsStr> + Debug>(
cmd: T,
args: &[U],
time_limit: Duration,
) -> Option<CommandOutput> {
log::trace!("Executing command {cmd:?} with args {args:?}");
#[cfg(test)]
if let Some(o) = mock_cmd(&cmd, args) {
return o;
}
internal_exec_cmd(cmd, args, time_limit)
}
#[cfg(test)]
pub fn mock_cmd<T: AsRef<OsStr> + Debug, U: AsRef<OsStr> + Debug>(
cmd: T,
args: &[U],
) -> Option<Option<CommandOutput>> {
let command = display_command(&cmd, args);
let out = match command.as_str() {
"bun --version" => Some(CommandOutput {
stdout: String::from("0.1.4\n"),
stderr: String::default(),
}),
"buf --version" => Some(CommandOutput {
stdout: String::from("1.0.0"),
stderr: String::default(),
}),
"cc --version" => Some(CommandOutput {
stdout: String::from(
"\
FreeBSD clang version 11.0.1 (git@github.com:llvm/llvm-project.git llvmorg-11.0.1-0-g43ff75f2c3fe)
Target: x86_64-unknown-freebsd13.0
Thread model: posix
InstalledDir: /usr/bin",
),
stderr: String::default(),
}),
"gcc --version" => Some(CommandOutput {
stdout: String::from(
"\
cc (Debian 10.2.1-6) 10.2.1 20210110
Copyright (C) 2020 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(),
}),
"clang --version" => Some(CommandOutput {
stdout: String::from(
"\
OpenBSD clang version 11.1.0
Target: amd64-unknown-openbsd7.0
Thread model: posix
InstalledDir: /usr/bin",
),
stderr: String::default(),
}),
"c++ --version" => Some(CommandOutput {
stdout: String::from(
"\
c++ (GCC) 14.2.1 20240910
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.",
),
stderr: String::default(),
}),
"g++ --version" => Some(CommandOutput {
stdout: String::from(
"\
g++ (GCC) 14.2.1 20240910
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.",
),
stderr: String::default(),
}),
"clang++ --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(),
}),
"cobc -version" => Some(CommandOutput {
stdout: String::from(
"\
cobc (GnuCOBOL) 3.1.2.0
Copyright (C) 2020 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Written by Keisuke Nishida, Roger While, Ron Norman, Simon Sobisch, Edward Hart
Built Dec 24 2020 19:08:58
Packaged Dec 23 2020 12:04:58 UTC
C version \"10.2.0\"",
),
stderr: String::default(),
}),
"crystal --version" => Some(CommandOutput {
stdout: String::from(
"\
Crystal 0.35.1 (2020-06-19)
LLVM: 10.0.0
Default target: x86_64-apple-macosx\n",
),
stderr: String::default(),
}),
"dart --version" => Some(CommandOutput {
stdout: String::default(),
stderr: String::from(
"Dart VM version: 2.8.4 (stable) (Wed Jun 3 12:26:04 2020 +0200) on \"macos_x64\"",
),
}),
"deno -V" => Some(CommandOutput {
stdout: String::from("deno 1.8.3\n"),
stderr: String::default(),
}),
"dummy_command" => Some(CommandOutput {
stdout: String::from("stdout ok!\n"),
stderr: String::from("stderr ok!\n"),
}),
"elixir --version" => Some(CommandOutput {
stdout: String::from(
"\
Erlang/OTP 22 [erts-10.6.4] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [hipe]
Elixir 1.10 (compiled with Erlang/OTP 22)\n",
),
stderr: String::default(),
}),
"elm --version" => Some(CommandOutput {
stdout: String::from("0.19.1\n"),
stderr: String::default(),
}),
"fennel --version" => Some(CommandOutput {
stdout: String::from("Fennel 1.2.1 on PUC Lua 5.4\n"),
stderr: String::default(),
}),
"fossil branch current" => Some(CommandOutput {
stdout: String::from("topic-branch"),
stderr: String::default(),
}),
"fossil branch new topic-branch trunk" | "fossil update topic-branch" => {
Some(CommandOutput {
stdout: String::default(),
stderr: String::default(),
})
}
"fossil diff -i --numstat" => Some(CommandOutput {
stdout: String::from(
"\
3 2 README.md
3 2 TOTAL over 1 changed files",
),
stderr: String::default(),
}),
"gleam --version" => Some(CommandOutput {
stdout: String::from("gleam 1.0.0\n"),
stderr: String::default(),
}),
"go version" => Some(CommandOutput {
stdout: String::from("go version go1.12.1 linux/amd64\n"),
stderr: String::default(),
}),
"ghc --numeric-version" => Some(CommandOutput {
stdout: String::from("9.2.1\n"),
stderr: String::default(),
}),
"helm version --short" => Some(CommandOutput {
stdout: String::from("v3.1.1+gafe7058\n"),
stderr: String::default(),
}),
s if s.ends_with("java -Xinternalversion") => Some(CommandOutput {
stdout: String::from(
"OpenJDK 64-Bit Server VM (13.0.2+8) for bsd-amd64 JRE (13.0.2+8), built on Feb 6 2020 02:07:52 by \"brew\" with clang 4.2.1 Compatible Apple LLVM 11.0.0 (clang-1100.0.33.17)",
),
stderr: String::default(),
}),
"scala-cli version --scala" => Some(CommandOutput {
stdout: String::from("3.4.1"),
stderr: String::default(),
}),
"scalac -version" => Some(CommandOutput {
stdout: String::from(
"Scala compiler version 2.13.5 -- Copyright 2002-2020, LAMP/EPFL and Lightbend, Inc.",
),
stderr: String::default(),
}),
"julia --version" => Some(CommandOutput {
stdout: String::from("julia version 1.4.0\n"),
stderr: String::default(),
}),
"kotlin -version" => Some(CommandOutput {
stdout: String::from("Kotlin version 1.4.21-release-411 (JRE 14.0.1+7)\n"),
stderr: String::default(),
}),
"kotlinc -version" => Some(CommandOutput {
stdout: String::from("info: kotlinc-jvm 1.4.21 (JRE 14.0.1+7)\n"),
stderr: String::default(),
}),
"lua -v" => Some(CommandOutput {
stdout: String::from("Lua 5.4.0 Copyright (C) 1994-2020 Lua.org, PUC-Rio\n"),
stderr: String::default(),
}),
"luajit -v" => Some(CommandOutput {
stdout: String::from(
"LuaJIT 2.0.5 -- Copyright (C) 2005-2017 Mike Pall. http://luajit.org/\n",
),
stderr: String::default(),
}),
"mojo --version" => Some(CommandOutput {
stdout: String::from("mojo 24.4.0 (2cb57382)\n"),
stderr: String::default(),
}),
"nats context info --json" => Some(CommandOutput {
stdout: String::from("{\"name\":\"localhost\",\"url\":\"nats://localhost:4222\"}"),
stderr: String::default(),
}),
"nim --version" => Some(CommandOutput {
stdout: String::from(
"\
Nim Compiler Version 1.2.0 [Linux: amd64]
Compiled at 2020-04-03
Copyright (c) 2006-2020 by Andreas Rumpf
git hash: 7e83adff84be5d0c401a213eccb61e321a3fb1ff
active boot switches: -d:release\n",
),
stderr: String::default(),
}),
"node --version" => Some(CommandOutput {
stdout: String::from("v12.0.0\n"),
stderr: String::default(),
}),
"ocaml -vnum" => Some(CommandOutput {
stdout: String::from("4.10.0\n"),
stderr: String::default(),
}),
"odin version" => Some(CommandOutput {
stdout: String::from("odin version dev-2024-03:fc587c507\n"),
stderr: String::default(),
}),
"opa version" => Some(CommandOutput {
stdout: String::from(
"Version: 0.44.0
Build Commit: e8d488f
Build Timestamp: 2022-09-07T23:50:25Z
Build Hostname: 119428673f4c
Go Version: go1.19.1
Platform: linux/amd64
WebAssembly: unavailable
",
),
stderr: String::default(),
}),
"opam switch show --safe" => Some(CommandOutput {
stdout: String::from("default\n"),
stderr: String::default(),
}),
"typst --version" => Some(CommandOutput {
stdout: String::from("typst 0.10 (360cc9b9)"),
stderr: String::default(),
}),
"esy ocaml -vnum" => Some(CommandOutput {
stdout: String::from("4.08.1\n"),
stderr: String::default(),
}),
"perl -e printf q#%vd#,$^V;" => Some(CommandOutput {
stdout: String::from("5.26.1"),
stderr: String::default(),
}),
"php -nr echo PHP_MAJOR_VERSION.\".\".PHP_MINOR_VERSION.\".\".PHP_RELEASE_VERSION;" => {
Some(CommandOutput {
stdout: String::from("7.3.8"),
stderr: String::default(),
})
}
"pijul channel" => Some(CommandOutput {
stdout: String::from(" main\n* tributary-48198"),
stderr: String::default(),
}),
"pijul channel new tributary-48198" => Some(CommandOutput {
stdout: String::default(),
stderr: String::default(),
}),
"pijul channel switch tributary-48198" => Some(CommandOutput {
stdout: String::from("Outputting repository ↖"),
stderr: String::default(),
}),
"pixi --version" => Some(CommandOutput {
stdout: String::from("pixi 0.33.0"),
stderr: String::default(),
}),
"pulumi version" => Some(CommandOutput {
stdout: String::from("1.2.3-ver.1631311768+e696fb6c"),
stderr: String::default(),
}),
"purs --version" => Some(CommandOutput {
stdout: String::from("0.13.5\n"),
stderr: String::default(),
}),
"pyenv version-name" => Some(CommandOutput {
stdout: String::from("system\n"),
stderr: String::default(),
}),
"python --version" => None,
"python2 --version" => Some(CommandOutput {
stdout: String::default(),
stderr: String::from("Python 2.7.17\n"),
}),
"python3 --version" => Some(CommandOutput {
stdout: String::from("Python 3.8.0\n"),
stderr: String::default(),
}),
"quarto --version" => Some(CommandOutput {
stdout: String::from("1.4.549\n"),
stderr: String::default(),
}),
"R --version" => Some(CommandOutput {
stdout: String::default(),
stderr: String::from(
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/."#,
),
}),
"raku --version" => Some(CommandOutput {
stdout: String::from(
"\
Welcome to Rakudo™ v2021.12.
Implementing the Raku® Programming Language v6.d.
Built on MoarVM version 2021.12.\n",
),
stderr: String::default(),
}),
"red --version" => Some(CommandOutput {
stdout: String::from("0.6.4\n"),
stderr: String::default(),
}),
"ruby -v" => Some(CommandOutput {
stdout: String::from("ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-linux-gnu]\n"),
stderr: String::default(),
}),
"solc --version" => Some(CommandOutput {
stdout: String::from(
"solc, the solidity compiler commandline interface
Version: 0.8.16+commit.07a7930e.Linux.g++",
),
stderr: String::default(),
}),
"solcjs --version" => Some(CommandOutput {
stdout: String::from("0.8.15+commit.e14f2714.Emscripten.clang"),
stderr: String::default(),
}),
"swift --version" => Some(CommandOutput {
stdout: String::from(
"\
Apple Swift version 5.2.2 (swiftlang-1103.0.32.6 clang-1103.0.32.51)
Target: x86_64-apple-darwin19.4.0\n",
),
stderr: String::default(),
}),
"vagrant --version" => Some(CommandOutput {
stdout: String::from("Vagrant 2.2.10\n"),
stderr: String::default(),
}),
"v version" => Some(CommandOutput {
stdout: String::from("V 0.2 30c0659"),
stderr: String::default(),
}),
"xmake --version" => Some(CommandOutput {
stdout: String::from(
r"xmake v2.9.5+HEAD.0db4fe6, A cross-platform build utility based on Lua
Copyright (C) 2015-present Ruki Wang, tboox.org, xmake.io
_
__ ___ __ __ __ _| | ______
\ \/ / | \/ |/ _ | |/ / __ \
> < | \__/ | /_| | < ___/
/_/\_\_|_| |_|\__ \|_|\_\____|
by ruki, xmake.io
👉 Manual: https://xmake.io/#/getting_started
🙏 Donate: https://xmake.io/#/sponsor",
),
stderr: String::default(),
}),
"zig version" => Some(CommandOutput {
stdout: String::from("0.6.0\n"),
stderr: String::default(),
}),
"cmake --version" => Some(CommandOutput {
stdout: String::from(
"\
cmake version 3.17.3
CMake suite maintained and supported by Kitware (kitware.com/cmake).\n",
),
stderr: String::default(),
}),
"dotnet --version" => Some(CommandOutput {
stdout: String::from("3.1.103"),
stderr: String::default(),
}),
"dotnet --list-sdks" => Some(CommandOutput {
stdout: String::from("3.1.103 [/usr/share/dotnet/sdk]"),
stderr: String::default(),
}),
"terraform version" => Some(CommandOutput {
stdout: String::from("Terraform v0.12.14\n"),
stderr: String::default(),
}),
s if s.starts_with("erl -noshell -eval") => Some(CommandOutput {
stdout: String::from("22.1.3\n"),
stderr: String::default(),
}),
_ => return None,
};
Some(out)
}
/// Wraps ANSI color escape sequences in the shell-appropriate wrappers.
pub fn wrap_colorseq_for_shell(ansi: String, shell: Shell) -> String {
const ESCAPE_BEGIN: char = '\u{1b}';
const ESCAPE_END: char = 'm';
wrap_seq_for_shell(ansi, shell, ESCAPE_BEGIN, ESCAPE_END)
}
/// Many shells cannot deal with raw unprintable characters and miscompute the cursor position,
/// leading to strange visual bugs like duplicated/missing chars. This function wraps a specified
/// sequence in shell-specific escapes to avoid these problems.
pub fn wrap_seq_for_shell(
ansi: String,
shell: Shell,
escape_begin: char,
escape_end: char,
) -> String {
let (beg, end) = match shell {
// \[ and \]
Shell::Bash => ("\u{5c}\u{5b}", "\u{5c}\u{5d}"),
// %{ and %}
Shell::Tcsh | Shell::Zsh => ("\u{25}\u{7b}", "\u{25}\u{7d}"),
_ => return ansi,
};
// ANSI escape codes cannot be nested, so we can keep track of whether we're
// in an escape or not with a single boolean variable
let mut escaped = false;
let final_string: String = ansi
.chars()
.map(|x| {
if x == escape_begin && !escaped {
escaped = true;
format!("{beg}{escape_begin}")
} else if x == escape_end && escaped {
escaped = false;
format!("{escape_end}{end}")
} else {
x.to_string()
}
})
.collect();
final_string
}
fn internal_exec_cmd<T: AsRef<OsStr> + Debug, U: AsRef<OsStr> + Debug>(
cmd: T,
args: &[U],
time_limit: Duration,
) -> Option<CommandOutput> {
let mut cmd = create_command(cmd).ok()?;
cmd.args(args);
exec_timeout(&mut cmd, time_limit)
}
pub fn exec_timeout(cmd: &mut Command, time_limit: Duration) -> Option<CommandOutput> {
let start = Instant::now();
let process = match cmd.spawn() {
Ok(process) => process,
Err(error) => {
log::info!("Unable to run {:?}, {:?}", cmd.get_program(), error);
return None;
}
};
match process
.controlled_with_output()
.time_limit(time_limit)
.terminate_for_timeout()
.wait()
{
Ok(Some(output)) => {
let stdout_string = match String::from_utf8(output.stdout) {
Ok(stdout) => stdout,
Err(error) => {
log::warn!("Unable to decode stdout: {error:?}");
return None;
}
};
let stderr_string = match String::from_utf8(output.stderr) {
Ok(stderr) => stderr,
Err(error) => {
log::warn!("Unable to decode stderr: {error:?}");
return None;
}
};
log::trace!(
"stdout: {:?}, stderr: {:?}, exit code: \"{:?}\", took {:?}",
stdout_string,
stderr_string,
output.status.code(),
start.elapsed()
);
if !output.status.success() {
return None;
}
Some(CommandOutput {
stdout: stdout_string,
stderr: stderr_string,
})
}
Ok(None) => {
log::warn!("Executing command {:?} timed out.", cmd.get_program());
log::warn!(
"You can set command_timeout in your config to a higher value to allow longer-running commands to keep executing."
);
None
}
Err(error) => {
log::info!(
"Executing command {:?} failed by: {:?}",
cmd.get_program(),
error
);
None
}
}
}
// Render the time into a nice human-readable string
pub fn render_time(raw_millis: u128, show_millis: bool) -> String {
// Fast returns for zero cases to render something
match (raw_millis, show_millis) {
(0, true) => return "0ms".into(),
(0..=999, false) => return "0s".into(),
_ => (),
}
// Calculate a simple breakdown into days/hours/minutes/seconds/milliseconds
let (millis, raw_seconds) = (raw_millis % 1000, raw_millis / 1000);
let (seconds, raw_minutes) = (raw_seconds % 60, raw_seconds / 60);
let (minutes, raw_hours) = (raw_minutes % 60, raw_minutes / 60);
let (hours, days) = (raw_hours % 24, raw_hours / 24);
// Calculate how long the string will be to allocate once in most cases
let result_capacity = match raw_millis {
1..=59 => 3,
60..=3599 => 6,
3600..=86399 => 9,
_ => 12,
} + if show_millis { 5 } else { 0 };
let components = [(days, "d"), (hours, "h"), (minutes, "m"), (seconds, "s")];
// Concat components ito result starting from the first non-zero one
let result = components.iter().fold(
String::with_capacity(result_capacity),
|acc, (component, suffix)| match component {
0 if acc.is_empty() => acc,
n => acc + &n.to_string() + suffix,
},
);
if show_millis {
result + &millis.to_string() + "ms"
} else {
result
}
}
pub fn home_dir() -> Option<PathBuf> {
dirs::home_dir()
}
const HEXTABLE: &[char] = &[
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
];
/// Encode a u8 slice into a hexadecimal string.
pub fn encode_to_hex(slice: &[u8]) -> String {
// let mut j = 0;
let mut dst = Vec::with_capacity(slice.len() * 2);
for &v in slice {
dst.push(HEXTABLE[(v >> 4) as usize] as u8);
dst.push(HEXTABLE[(v & 0x0f) as usize] as u8);
}
String::from_utf8(dst).unwrap()
}
pub trait PathExt {
/// Get device / volume info
fn device_id(&self) -> Option<u64>;
}
#[cfg(windows)]
impl PathExt for Path {
fn device_id(&self) -> Option<u64> {
// Maybe it should use unimplemented!
Some(42u64)
}
}
#[cfg(not(windows))]
impl PathExt for Path {
#[cfg(target_os = "linux")]
fn device_id(&self) -> Option<u64> {
use std::os::linux::fs::MetadataExt;
Some(self.metadata().ok()?.st_dev())
}
#[cfg(all(unix, not(target_os = "linux")))]
fn device_id(&self) -> Option<u64> {
use std::os::unix::fs::MetadataExt;
Some(self.metadata().ok()?.dev())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn render_time_test_0ms() {
assert_eq!(render_time(0_u128, true), "0ms");
}
#[test]
fn render_time_test_0s() {
assert_eq!(render_time(0_u128, false), "0s");
}
#[test]
fn render_time_test_500ms() {
assert_eq!(render_time(500_u128, true), "500ms");
}
#[test]
fn render_time_test_500ms_no_millis() {
assert_eq!(render_time(500_u128, false), "0s");
}
#[test]
fn render_time_test_10s() {
assert_eq!(render_time(10_000_u128, true), "10s0ms");
}
#[test]
fn render_time_test_90s() {
assert_eq!(render_time(90_000_u128, true), "1m30s0ms");
}
#[test]
fn render_time_test_10110s() {
assert_eq!(render_time(10_110_000_u128, true), "2h48m30s0ms");
}
#[test]
fn render_time_test_1d() {
assert_eq!(render_time(86_400_000_u128, false), "1d0h0m0s");
}
#[test]
fn exec_mocked_command() {
let result = exec_cmd(
"dummy_command",
&[] as &[&OsStr],
Duration::from_millis(DEFAULT_COMMAND_TIMEOUT_MS),
);
let expected = Some(CommandOutput {
stdout: String::from("stdout ok!\n"),
stderr: String::from("stderr ok!\n"),
});
assert_eq!(result, expected);
}
// While the exec_cmd should work on Windows some of these tests assume a Unix-like
// environment.
#[test]
#[cfg(not(windows))]
fn exec_no_output() {
let result = internal_exec_cmd(
"true",
&[] as &[&OsStr],
Duration::from_millis(DEFAULT_COMMAND_TIMEOUT_MS),
);
let expected = Some(CommandOutput {
stdout: String::new(),
stderr: String::new(),
});
assert_eq!(result, expected);
}
#[test]
#[cfg(not(windows))]
fn exec_with_output_stdout() {
let result = internal_exec_cmd(
"/bin/sh",
&["-c", "echo hello"],
Duration::from_millis(DEFAULT_COMMAND_TIMEOUT_MS),
);
let expected = Some(CommandOutput {
stdout: String::from("hello\n"),
stderr: String::new(),
});
assert_eq!(result, expected);
}
#[test]
#[cfg(not(windows))]
fn exec_with_output_stderr() {
let result = internal_exec_cmd(
"/bin/sh",
&["-c", "echo hello >&2"],
Duration::from_millis(DEFAULT_COMMAND_TIMEOUT_MS),
);
let expected = Some(CommandOutput {
stdout: String::new(),
stderr: String::from("hello\n"),
});
assert_eq!(result, expected);
}
#[test]
#[cfg(not(windows))]
fn exec_with_output_both() {
let result = internal_exec_cmd(
"/bin/sh",
&["-c", "echo hello; echo world >&2"],
Duration::from_millis(DEFAULT_COMMAND_TIMEOUT_MS),
);
let expected = Some(CommandOutput {
stdout: String::from("hello\n"),
stderr: String::from("world\n"),
});
assert_eq!(result, expected);
}
#[test]
#[cfg(not(windows))]
fn exec_with_non_zero_exit_code() {
let result = internal_exec_cmd(
"false",
&[] as &[&OsStr],
Duration::from_millis(DEFAULT_COMMAND_TIMEOUT_MS),
);
let expected = None;
assert_eq!(result, expected);
}
#[test]
#[cfg(not(windows))]
fn exec_slow_command() {
let result = internal_exec_cmd(
"sleep",
&["500"],
Duration::from_millis(DEFAULT_COMMAND_TIMEOUT_MS),
);
let expected = None;
assert_eq!(result, expected);
}
#[test]
fn test_color_sequence_wrappers() {
let test0 = "\x1b2mhellomynamekeyes\x1b2m"; // BEGIN: \x1b END: m
let test1 = "\x1b]330;mlol\x1b]0m"; // BEGIN: \x1b END: m
let test2 = "\u{1b}J"; // BEGIN: \x1b END: J
let test3 = "OH NO"; // BEGIN: O END: O
let test4 = "herpaderp";
let test5 = "";
let zresult0 = wrap_seq_for_shell(test0.to_string(), Shell::Zsh, '\x1b', 'm');
let zresult1 = wrap_seq_for_shell(test1.to_string(), Shell::Zsh, '\x1b', 'm');
let zresult2 = wrap_seq_for_shell(test2.to_string(), Shell::Zsh, '\x1b', 'J');
let zresult3 = wrap_seq_for_shell(test3.to_string(), Shell::Zsh, 'O', 'O');
let zresult4 = wrap_seq_for_shell(test4.to_string(), Shell::Zsh, '\x1b', 'm');
let zresult5 = wrap_seq_for_shell(test5.to_string(), Shell::Zsh, '\x1b', 'm');
assert_eq!(&zresult0, "%{\x1b2m%}hellomynamekeyes%{\x1b2m%}");
assert_eq!(&zresult1, "%{\x1b]330;m%}lol%{\x1b]0m%}");
assert_eq!(&zresult2, "%{\x1bJ%}");
assert_eq!(&zresult3, "%{OH NO%}");
assert_eq!(&zresult4, "herpaderp");
assert_eq!(&zresult5, "");
let bresult0 = wrap_seq_for_shell(test0.to_string(), Shell::Bash, '\x1b', 'm');
let bresult1 = wrap_seq_for_shell(test1.to_string(), Shell::Bash, '\x1b', 'm');
let bresult2 = wrap_seq_for_shell(test2.to_string(), Shell::Bash, '\x1b', 'J');
let bresult3 = wrap_seq_for_shell(test3.to_string(), Shell::Bash, 'O', 'O');
let bresult4 = wrap_seq_for_shell(test4.to_string(), Shell::Bash, '\x1b', 'm');
let bresult5 = wrap_seq_for_shell(test5.to_string(), Shell::Bash, '\x1b', 'm');
assert_eq!(&bresult0, "\\[\x1b2m\\]hellomynamekeyes\\[\x1b2m\\]");
assert_eq!(&bresult1, "\\[\x1b]330;m\\]lol\\[\x1b]0m\\]");
assert_eq!(&bresult2, "\\[\x1bJ\\]");
assert_eq!(&bresult3, "\\[OH NO\\]");
assert_eq!(&bresult4, "herpaderp");
assert_eq!(&bresult5, "");
}
#[test]
fn test_get_command_string_output() {
let case1 = CommandOutput {
stdout: String::from("stdout"),
stderr: String::from("stderr"),
};
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | true |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/context_env.rs | src/context_env.rs | #[cfg(test)]
use std::collections::HashMap;
#[cfg(not(test))]
use std::env;
use std::ffi::OsString;
#[derive(Default)]
pub struct Env<'a> {
/// A `HashMap` of environment variable mocks
#[cfg(test)]
pub env: HashMap<&'a str, String>,
#[cfg(not(test))]
_marker: std::marker::PhantomData<&'a ()>,
}
#[cfg_attr(not(test), allow(clippy::needless_lifetimes))]
impl<'a> Env<'a> {
// Retrieves a environment variable from the os or from a table if in testing mode
#[cfg(test)]
pub fn get_env<K: AsRef<str>>(&self, key: K) -> Option<String> {
self.env
.get(key.as_ref())
.map(std::string::ToString::to_string)
}
#[cfg(not(test))]
#[inline]
pub fn get_env<K: AsRef<str>>(&self, key: K) -> Option<String> {
env::var(key.as_ref()).ok()
}
// Retrieves a environment variable from the os or from a table if in testing mode (os version)
#[cfg(test)]
pub fn get_env_os<K: AsRef<str>>(&self, key: K) -> Option<OsString> {
self.env.get(key.as_ref()).map(OsString::from)
}
#[cfg(not(test))]
#[inline]
pub fn get_env_os<K: AsRef<str>>(&self, key: K) -> Option<OsString> {
env::var_os(key.as_ref())
}
#[cfg(test)]
pub fn insert(&mut self, k: &'a str, v: String) -> Option<String> {
self.env.insert(k, v)
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/main.rs | src/main.rs | #![warn(clippy::disallowed_methods)]
use clap::crate_authors;
use std::io;
use std::path::PathBuf;
use std::time::SystemTime;
use clap::{CommandFactory, Parser, Subcommand, ValueEnum};
use clap_complete::generate;
use rand::Rng;
use starship::context::{Context, Properties, Target};
use starship::module::ALL_MODULES;
use starship::{bug_report, configure, init, logger, num_rayon_threads, print, shadow};
#[derive(Parser, Debug)]
#[clap(
author=crate_authors!(),
version=shadow::PKG_VERSION,
long_version=shadow::CLAP_LONG_VERSION,
about="The cross-shell prompt for astronauts. ☄🌌️",
subcommand_required=true,
arg_required_else_help=true,
)]
struct Cli {
#[clap(subcommand)]
command: Commands,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
enum CompletionShell {
Bash,
Elvish,
Fish,
Nushell,
#[clap(name = "powershell", alias = "pwsh", alias = "power-shell")]
PowerShell,
Zsh,
}
fn generate_shell(shell: impl clap_complete::Generator) {
generate(
shell,
&mut Cli::command(),
"starship",
&mut io::stdout().lock(),
);
}
fn generate_completions(shell: CompletionShell) {
match shell {
CompletionShell::Bash => generate_shell(clap_complete::Shell::Bash),
CompletionShell::Elvish => generate_shell(clap_complete::Shell::Elvish),
CompletionShell::Fish => generate_shell(clap_complete::Shell::Fish),
CompletionShell::PowerShell => generate_shell(clap_complete::Shell::PowerShell),
CompletionShell::Zsh => generate_shell(clap_complete::Shell::Zsh),
CompletionShell::Nushell => generate_shell(clap_complete_nushell::Nushell),
}
}
#[derive(Subcommand, Debug)]
enum Commands {
/// Create a pre-populated GitHub issue with information about your configuration
BugReport,
/// Generate starship shell completions for your shell to stdout
Completions {
#[clap(value_enum)]
shell: CompletionShell,
},
/// Edit the starship configuration
Config {
/// Configuration key to edit
#[clap(requires = "value")]
name: Option<String>,
/// Value to place into that key
value: Option<String>,
},
/// Explains the currently showing modules
Explain(Properties),
/// Prints the shell function used to execute starship
Init {
shell: String,
#[clap(long)]
print_full_init: bool,
},
/// Prints a specific prompt module
Module {
/// The name of the module to be printed
#[clap(required_unless_present("list"))]
name: Option<String>,
/// List out all supported modules
#[clap(short, long)]
list: bool,
#[clap(flatten)]
properties: Properties,
},
/// Prints a preset config
Preset {
/// The name of preset to be printed
#[clap(required_unless_present("list"), value_enum)]
name: Option<print::Preset>,
/// Output the preset to a file instead of stdout
#[clap(short, long, conflicts_with = "list")]
output: Option<PathBuf>,
/// List out all preset names
#[clap(short, long)]
list: bool,
},
/// Prints the computed starship configuration
PrintConfig {
/// Print the default instead of the computed config
#[clap(short, long)]
default: bool,
/// Configuration keys to print
name: Vec<String>,
},
/// Prints the full starship prompt
Prompt {
/// Print the right prompt (instead of the standard left prompt)
#[clap(long)]
right: bool,
/// Print the prompt with the specified profile name (instead of the standard left prompt)
#[clap(long, conflicts_with = "right")]
profile: Option<String>,
/// Print the continuation prompt (instead of the standard left prompt)
#[clap(long, conflicts_with = "right", conflicts_with = "profile")]
continuation: bool,
#[clap(flatten)]
properties: Properties,
},
/// Generate random session key
Session,
/// Prints time in milliseconds
#[clap(hide = true)]
Time,
/// Prints timings of all active modules
Timings(Properties),
/// Toggle a given starship module
Toggle {
/// The name of the module to be toggled
name: String,
/// The key of the config to be toggled
#[clap(default_value = "disabled")]
value: String,
},
#[cfg(feature = "config-schema")]
/// Generate a schema for the starship configuration as JSON-schema
ConfigSchema,
}
fn main() {
// Configure the current terminal on windows to support ANSI escape sequences.
#[cfg(windows)]
let _ = nu_ansi_term::enable_ansi_support();
logger::init();
init_global_threadpool();
// Delete old log files
rayon::spawn(|| {
let log_dir = logger::get_log_dir();
logger::cleanup_log_files(log_dir);
});
let args = match Cli::try_parse() {
Ok(args) => args,
Err(e) => {
// if the error is not printed to stderr, this means it was not really
// an error but rather some information is going to be listed, therefore
// we won't print the arguments passed
let is_info_only = !e.use_stderr();
// print the error and void panicking in case of stdout/stderr closing unexpectedly
let _ = e.print();
// if there was no mistake by the user and we're only going to display information,
// we won't put arguments or exit with non-zero code
let exit_code = if is_info_only {
0
} else {
use io::Write;
// print the arguments
// avoid panicking in case of stderr closing
let mut stderr = io::stderr();
let _ = writeln!(
stderr,
"\nNOTE:\n passed arguments: {:?}",
// collect into a vec to format args as a slice
std::env::args().skip(1).collect::<Vec<_>>()
);
// clap exits with status 2 on error:
// https://docs.rs/clap/latest/clap/struct.Error.html#method.exit
2
};
std::process::exit(exit_code);
}
};
log::trace!("Parsed arguments: {args:#?}");
match args.command {
Commands::Init {
shell,
print_full_init,
} => {
if print_full_init {
init::init_main(&shell).expect("can't init_main");
} else {
init::init_stub(&shell).expect("can't init_stub");
}
}
Commands::Prompt {
properties,
right,
profile,
continuation,
} => {
let target = match (right, profile, continuation) {
(true, _, _) => Target::Right,
(_, Some(profile_name), _) => Target::Profile(profile_name),
(_, _, true) => Target::Continuation,
(_, _, _) => Target::Main,
};
print::prompt(properties, target);
}
Commands::Module {
name,
list,
properties,
} => {
if list {
println!("Supported modules list");
println!("----------------------");
for modules in ALL_MODULES {
println!("{modules}");
}
}
if let Some(module_name) = name {
print::module(&module_name, properties);
}
}
Commands::Preset { name, list, output } => print::preset_command(name, output, list),
Commands::Config { name, value } => {
let context = Context::default();
if let Some(name) = name {
if let Some(value) = value {
configure::update_configuration(&context, &name, &value);
}
} else if let Err(reason) = configure::edit_configuration(&context, None) {
eprintln!("Could not edit configuration: {reason}");
std::process::exit(1);
}
}
Commands::PrintConfig { default, name } => {
configure::print_configuration(&Context::default(), default, &name);
}
Commands::Toggle { name, value } => {
configure::toggle_configuration(&Context::default(), &name, &value);
}
Commands::BugReport => bug_report::create(),
Commands::Time => {
match SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.ok()
{
Some(time) => println!("{}", time.as_millis()),
None => println!("{}", -1),
}
}
Commands::Explain(props) => print::explain(props),
Commands::Timings(props) => print::timings(props),
Commands::Completions { shell } => generate_completions(shell),
Commands::Session => println!(
"{}",
rand::rng()
.sample_iter(rand::distr::Alphanumeric)
.take(16)
.map(char::from)
.collect::<String>()
),
#[cfg(feature = "config-schema")]
Commands::ConfigSchema => print::print_schema(),
}
}
/// Initialize global `rayon` thread pool
fn init_global_threadpool() {
rayon::ThreadPoolBuilder::new()
.num_threads(num_rayon_threads())
.build_global()
.expect("Failed to initialize worker thread pool");
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/context.rs | src/context.rs | use crate::config::{ModuleConfig, StarshipConfig};
use crate::configs::StarshipRootConfig;
use crate::context_env::Env;
use crate::module::Module;
use crate::utils::{CommandOutput, PathExt, create_command, exec_timeout, read_file};
use crate::modules;
use crate::utils;
use clap::Parser;
use gix::{
Repository, ThreadSafeRepository,
repository::Kind,
sec::{self as git_sec, trust::DefaultForLevel},
state as git_state,
};
#[cfg(test)]
use std::collections::HashMap;
use std::collections::HashSet;
use std::env;
use std::ffi::{OsStr, OsString};
use std::fmt::Debug;
use std::fs;
use std::marker::PhantomData;
use std::num::ParseIntError;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::string::String;
use std::sync::{Arc, OnceLock, mpsc};
use std::thread;
use std::time::{Duration, Instant};
use terminal_size::terminal_size;
/// Context contains data or common methods that may be used by multiple modules.
/// The data contained within Context will be relevant to this particular rendering
/// of the prompt.
pub struct Context<'a> {
/// The deserialized configuration map from the user's `starship.toml` file.
pub config: StarshipConfig,
/// The current working directory that starship is being called in.
pub current_dir: PathBuf,
/// A logical directory path which should represent the same directory as `current_dir`,
/// though may appear different.
/// E.g. when navigating to a `PSDrive` in `PowerShell`, or a path without symlinks resolved.
pub logical_dir: PathBuf,
/// A struct containing directory contents in a lookup-optimized format.
dir_contents: OnceLock<Result<DirContents, std::io::Error>>,
/// Properties to provide to modules.
pub properties: Properties,
/// Private field to store Git information for modules who need it
repo: OnceLock<Result<Repo, Box<gix::discover::Error>>>,
/// The shell the user is assumed to be running
pub shell: Shell,
/// Which prompt to print (main, right, ...)
pub target: Target,
/// Width of terminal, or zero if width cannot be detected.
pub width: usize,
/// A `HashMap` of environment variable mocks
pub env: Env<'a>,
/// A `HashMap` of command mocks
#[cfg(test)]
pub cmd: HashMap<&'a str, Option<CommandOutput>>,
/// a mock of the root directory
#[cfg(test)]
pub root_dir: tempfile::TempDir,
#[cfg(feature = "battery")]
pub battery_info_provider: &'a (dyn crate::modules::BatteryInfoProvider + Send + Sync),
/// Starship root config
pub root_config: StarshipRootConfig,
/// Avoid issues with unused lifetimes when features are disabled
_marker: PhantomData<&'a ()>,
}
impl<'a> Context<'a> {
/// Identify the current working directory and create an instance of Context
/// for it. "logical-path" is used when a shell allows the "current working directory"
/// to be something other than a file system path (like powershell provider specific paths).
pub fn new(arguments: Properties, target: Target) -> Self {
let shell = Context::get_shell();
// Retrieve the "current directory".
// If the path argument is not set fall back to the OS current directory.
let path = arguments
.path
.clone()
.or_else(|| env::current_dir().ok())
.or_else(|| env::var("PWD").map(PathBuf::from).ok())
.or_else(|| arguments.logical_path.clone())
.unwrap_or_default();
// Retrieve the "logical directory".
// If the path argument is not set fall back to the PWD env variable set by many shells
// or to the other path.
let logical_path = arguments
.logical_path
.clone()
.or_else(|| env::var("PWD").map(PathBuf::from).ok())
.unwrap_or_else(|| path.clone());
Self::new_with_shell_and_path(
arguments,
shell,
target,
path,
logical_path,
Default::default(),
)
}
/// Create a new instance of Context for the provided directory
pub fn new_with_shell_and_path(
mut properties: Properties,
shell: Shell,
target: Target,
path: PathBuf,
logical_path: PathBuf,
env: Env<'a>,
) -> Self {
let config = StarshipConfig::initialize(get_config_path_os(&env).as_deref());
// If the vector is zero-length, we should pretend that we didn't get a
// pipestatus at all (since this is the input `--pipestatus=""`)
if properties
.pipestatus
.as_deref()
.is_some_and(|p| p.len() == 1 && p[0].is_empty())
{
properties.pipestatus = None;
}
log::trace!(
"Received completed pipestatus of {:?}",
properties.pipestatus
);
// If status-code is empty, set it to None
if matches!(properties.status_code.as_deref(), Some("")) {
properties.status_code = None;
}
// Canonicalize the current path to resolve symlinks, etc.
// NOTE: On Windows this may convert the path to extended-path syntax.
let current_dir = Context::expand_tilde(path);
let current_dir = dunce::canonicalize(¤t_dir).unwrap_or(current_dir);
let logical_dir = logical_path;
let root_config = config
.config
.as_ref()
.map_or_else(StarshipRootConfig::default, StarshipRootConfig::load);
let width = properties.terminal_width;
Self {
config,
properties,
current_dir,
logical_dir,
dir_contents: OnceLock::new(),
repo: OnceLock::new(),
shell,
target,
width,
env,
#[cfg(test)]
root_dir: tempfile::TempDir::new().unwrap(),
#[cfg(test)]
cmd: HashMap::new(),
#[cfg(feature = "battery")]
battery_info_provider: &crate::modules::BatteryInfoProviderImpl,
root_config,
_marker: PhantomData,
}
}
/// Sets the context config, overwriting the existing config
pub fn set_config(mut self, config: toml::Table) -> Self {
self.root_config = StarshipRootConfig::load(&config);
self.config = StarshipConfig {
config: Some(config),
};
self
}
// Tries to retrieve home directory from a table in testing mode or else retrieves it from the os
pub fn get_home(&self) -> Option<PathBuf> {
home_dir(&self.env)
}
// Retrieves a environment variable from the os or from a table if in testing mode
#[inline]
pub fn get_env<K: AsRef<str>>(&self, key: K) -> Option<String> {
self.env.get_env(key)
}
// Retrieves a environment variable from the os or from a table if in testing mode (os version)
#[inline]
pub fn get_env_os<K: AsRef<str>>(&self, key: K) -> Option<OsString> {
self.env.get_env_os(key)
}
/// Convert a `~` in a path to the home directory
pub fn expand_tilde(dir: PathBuf) -> PathBuf {
if dir.starts_with("~") {
let without_home = dir.strip_prefix("~").unwrap();
return utils::home_dir().unwrap().join(without_home);
}
dir
}
/// Create a new module
pub fn new_module(&self, name: &str) -> Module<'_> {
let config = self.config.get_module_config(name);
let desc = modules::description(name);
Module::new(name, desc, config)
}
/// Check if `disabled` option of the module is true in configuration file.
pub fn is_module_disabled_in_config(&self, name: &str) -> bool {
let config = self.config.get_module_config(name);
// If the segment has "disabled" set to "true", don't show it
let disabled = config.and_then(|table| table.as_table()?.get("disabled")?.as_bool());
disabled == Some(true)
}
/// Returns true when a negated environment variable is defined in `env_vars` and is present
fn has_negated_env_var(&self, env_vars: &'a [&'a str]) -> bool {
env_vars
.iter()
.filter_map(|env_var| env_var.strip_prefix('!'))
.any(|env_var| self.get_env(env_var).is_some())
}
/// Returns true if `detect_env_vars` is empty,
/// or if at least one environment variable is set and no negated environment variable is set
pub fn detect_env_vars(&'a self, env_vars: &'a [&'a str]) -> bool {
if env_vars.is_empty() {
return true;
}
if self.has_negated_env_var(env_vars) {
return false;
}
// Returns true if at least one environment variable is set
let mut iter = env_vars
.iter()
.filter(|env_var| !env_var.starts_with('!'))
.peekable();
iter.peek().is_none() || iter.any(|env_var| self.get_env(env_var).is_some())
}
/// Returns an enum indicating if `detect_env_vars` contains negated or non-negated variables
pub fn detect_env_vars2(&'a self, env_vars: &'a [&'a str]) -> Detected {
if env_vars.is_empty() {
return Detected::Empty;
}
if self.has_negated_env_var(env_vars) {
return Detected::Negated;
}
let mut iter = env_vars
.iter()
.filter(|env_var| !env_var.starts_with('!'))
.peekable();
if iter.any(|env_var| self.get_env(env_var).is_some()) {
Detected::Yes
} else {
Detected::No
}
}
// returns a new ScanDir struct with reference to current dir_files of context
// see ScanDir for methods
pub fn try_begin_scan(&'a self) -> Option<ScanDir<'a>> {
Some(ScanDir {
dir_contents: self.dir_contents().ok()?,
files: &[],
folders: &[],
extensions: &[],
})
}
/// Begins an ancestor scan at the current directory, see [`ScanAncestors`] for available
/// methods.
pub fn begin_ancestor_scan(&'a self) -> ScanAncestors<'a> {
ScanAncestors {
path: &self.current_dir,
files: &[],
folders: &[],
}
}
/// Will lazily get repo root and branch when a module requests it.
pub fn get_repo(&self) -> Result<&Repo, &gix::discover::Error> {
self.repo
.get_or_init(|| -> Result<Repo, Box<gix::discover::Error>> {
// custom open options
let mut git_open_opts_map =
git_sec::trust::Mapping::<gix::open::Options>::default();
// Load all the configuration as it affects aspects of the
// `git_status` and `git_metrics` modules.
let config = gix::open::permissions::Config {
git_binary: true,
system: true,
git: true,
user: true,
env: true,
includes: true,
};
// change options for config permissions without touching anything else
git_open_opts_map.reduced =
git_open_opts_map
.reduced
.permissions(gix::open::Permissions {
config,
..gix::open::Permissions::default_for_level(git_sec::Trust::Reduced)
});
git_open_opts_map.full =
git_open_opts_map.full.permissions(gix::open::Permissions {
config,
..gix::open::Permissions::default_for_level(git_sec::Trust::Full)
});
let shared_repo =
match ThreadSafeRepository::discover_with_environment_overrides_opts(
&self.current_dir,
gix::discover::upwards::Options {
match_ceiling_dir_or_error: false,
..Default::default()
},
git_open_opts_map,
) {
Ok(repo) => repo,
Err(e) => {
log::debug!("Failed to find git repo: {e}");
return Err(Box::new(e));
}
};
let repository = shared_repo.to_thread_local();
log::trace!(
"Found git repo: {repository:?}, (trust: {:?})",
repository.git_dir_trust()
);
let branch = get_current_branch(&repository);
let remote =
get_remote_repository_info(&repository, branch.as_ref().map(AsRef::as_ref));
let path = repository.path().to_path_buf();
let fs_monitor_value_is_true = repository
.config_snapshot()
.boolean("core.fsmonitor")
.unwrap_or(false);
Ok(Repo {
repo: shared_repo,
branch: branch.map(|b| b.shorten().to_string()),
workdir: repository.workdir().map(PathBuf::from),
path,
state: repository.state(),
remote,
fs_monitor_value_is_true,
kind: repository.kind(),
})
})
.as_ref()
.map_err(std::convert::AsRef::as_ref)
}
pub fn dir_contents(&self) -> Result<&DirContents, &std::io::Error> {
self.dir_contents
.get_or_init(|| {
let timeout = self.root_config.scan_timeout;
DirContents::from_path_with_timeout(
&self.current_dir,
Duration::from_millis(timeout),
self.root_config.follow_symlinks,
)
})
.as_ref()
}
fn get_shell() -> Shell {
let shell = env::var("STARSHIP_SHELL").unwrap_or_default();
match shell.as_str() {
"bash" => Shell::Bash,
"fish" => Shell::Fish,
"ion" => Shell::Ion,
"pwsh" => Shell::Pwsh,
"powershell" => Shell::PowerShell,
"zsh" => Shell::Zsh,
"elvish" => Shell::Elvish,
"tcsh" => Shell::Tcsh,
"nu" => Shell::Nu,
"xonsh" => Shell::Xonsh,
"cmd" => Shell::Cmd,
_ => Shell::Unknown,
}
}
// TODO: This should be used directly by clap parse
pub fn get_cmd_duration(&self) -> Option<u128> {
self.properties
.cmd_duration
.as_deref()
.and_then(|cd| cd.parse::<u128>().ok())
}
/// Execute a command and return the output on stdout and stderr if successful
#[inline]
pub fn exec_cmd<T: AsRef<OsStr> + Debug, U: AsRef<OsStr> + Debug>(
&self,
cmd: T,
args: &[U],
) -> Option<CommandOutput> {
log::trace!("Executing command {cmd:?} with args {args:?} from context");
#[cfg(test)]
{
let command = crate::utils::display_command(&cmd, args);
if let Some(output) = self
.cmd
.get(command.as_str())
.cloned()
.or_else(|| crate::utils::mock_cmd(&cmd, args))
{
return output;
}
}
let mut cmd = create_command(cmd).ok()?;
cmd.args(args).current_dir(&self.current_dir);
exec_timeout(
&mut cmd,
Duration::from_millis(self.root_config.command_timeout),
)
}
/// Attempt to execute several commands with `exec_cmd`, return the results of the first that works
pub fn exec_cmds_return_first(&self, commands: &[Vec<&str>]) -> Option<CommandOutput> {
commands
.iter()
.find_map(|attempt| self.exec_cmd(attempt[0], &attempt[1..]))
}
/// Returns the string contents of a file from the current working directory
pub fn read_file_from_pwd(&self, file_name: &str) -> Option<String> {
if !self.try_begin_scan()?.set_files(&[file_name]).is_match() {
log::debug!(
"Not attempting to read {file_name} because, it was not found during scan."
);
return None;
}
read_file(self.current_dir.join(file_name)).ok()
}
pub fn get_config_path_os(&self) -> Option<OsString> {
get_config_path_os(&self.env)
}
}
impl Default for Context<'_> {
fn default() -> Self {
Self::new(Default::default(), Target::Main)
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum Detected {
/// `detect_env_vars` was empty.
Empty,
/// A negated variable was found.
Negated,
/// A non-negated variable was found.
Yes,
/// No non-negated variables were found.
No,
}
fn home_dir(env: &Env) -> Option<PathBuf> {
if cfg!(test)
&& let Some(home) = env.get_env("HOME")
{
return Some(PathBuf::from(home));
}
utils::home_dir()
}
fn get_config_path_os(env: &Env) -> Option<OsString> {
if let Some(config_path) = env.get_env_os("STARSHIP_CONFIG") {
return Some(config_path);
}
Some(home_dir(env)?.join(".config").join("starship.toml").into())
}
#[derive(Debug)]
pub struct DirContents {
// HashSet of all files, no folders, relative to the base directory given at construction.
files: HashSet<PathBuf>,
// HashSet of all file names, e.g. the last section without any folders, as strings.
file_names: HashSet<String>,
// HashSet of all folders, relative to the base directory given at construction.
folders: HashSet<PathBuf>,
// HashSet of all extensions found, without dots, e.g. "js" instead of ".js".
extensions: HashSet<String>,
}
impl DirContents {
#[cfg(test)]
fn from_path(base: &Path, follow_symlinks: bool) -> Result<Self, std::io::Error> {
Self::from_path_with_timeout(base, Duration::from_secs(30), follow_symlinks)
}
fn from_path_with_timeout(
base: &Path,
timeout: Duration,
follow_symlinks: bool,
) -> Result<Self, std::io::Error> {
let _ = fs::read_dir(base)?; // Early return if invalid base
let start = Instant::now();
let mut remaining_time = timeout;
let mut folders: HashSet<PathBuf> = HashSet::new();
let mut files: HashSet<PathBuf> = HashSet::new();
let mut file_names: HashSet<String> = HashSet::new();
let mut extensions: HashSet<String> = HashSet::new();
let base_path = base;
let base = Arc::from(base);
let (tx, rx) = mpsc::channel();
{
let worker = move || {
let dir_iter = fs::read_dir(base).unwrap();
let _ = dir_iter
.filter_map(|entry| entry.ok())
.try_for_each(|entry| tx.send(entry));
};
let _ = thread::Builder::new()
.name("from_path_with_timeout worker".into())
.spawn(worker)?;
}
loop {
// TODO: use `recv_deadline` instead once stable
let msg = if cfg!(test) {
// recv() errors out only when the corresponding sender closes.
// See mpsc::RecvError.
rx.recv().map_err(|_| mpsc::RecvTimeoutError::Disconnected)
} else {
rx.recv_timeout(remaining_time)
};
match msg {
Ok(entry) => {
let path = PathBuf::from(entry.path().strip_prefix(base_path).unwrap());
let is_dir = match follow_symlinks {
true => entry.path().is_dir(),
false => fs::symlink_metadata(entry.path())
.map(|m| m.is_dir())
.unwrap_or(false),
};
if is_dir {
folders.insert(path);
} else {
if !path.to_string_lossy().starts_with('.') {
// Extract the file extensions (yes, that's plural) from a filename.
// Why plural? Consider the case of foo.tar.gz. It's a compressed
// tarball (tar.gz), and it's a gzipped file (gz). We should be able
// to match both.
// find the minimal extension on a file. ie, the gz in foo.tar.gz
// NB the .to_string_lossy().to_string() here looks weird but is
// required to convert it from a Cow.
path.extension()
.map(|ext| extensions.insert(ext.to_string_lossy().to_string()));
// find the full extension on a file. ie, the tar.gz in foo.tar.gz
path.file_name().map(|file_name| {
file_name
.to_string_lossy()
.split_once('.')
.map(|(_, after)| extensions.insert(after.to_string()))
});
}
if let Some(file_name) = path.file_name() {
// this .to_string_lossy().to_string() is also required
file_names.insert(file_name.to_string_lossy().to_string());
}
files.insert(path);
}
if remaining_time <= Duration::from_millis(0) && rx.try_recv().is_err() {
// Timed-out, and rx has been drained.
log::warn!("Scanning current directory timed out.");
log::warn!(
"You can set scan_timeout in your config to a higher value to allow longer-running scans to keep executing."
);
break;
}
// recv_deadline is nightly: calculate the remaining time instead.
// after loop break to give chance to drain rx
remaining_time =
timeout.saturating_sub(Instant::now().saturating_duration_since(start));
}
Err(_) => {
// Timeout or Disconnected occurred
break;
}
}
}
log::trace!(
"Building HashSets of directory files, folders and extensions took {:?}",
start.elapsed()
);
Ok(Self {
files,
file_names,
folders,
extensions,
})
}
pub fn files(&self) -> impl Iterator<Item = &PathBuf> {
self.files.iter()
}
pub fn has_file(&self, path: &str) -> bool {
self.files.contains(Path::new(path))
}
pub fn has_file_name(&self, name: &str) -> bool {
self.file_names.contains(name)
}
pub fn has_folder(&self, path: &str) -> bool {
self.folders.contains(Path::new(path))
}
pub fn has_extension(&self, ext: &str) -> bool {
self.extensions.contains(ext)
}
pub fn has_any_positive_file_name(&self, names: &[&str]) -> bool {
names
.iter()
.any(|name| !name.starts_with('!') && self.has_file_name(name))
}
pub fn has_any_positive_folder(&self, paths: &[&str]) -> bool {
paths
.iter()
.any(|path| !path.starts_with('!') && self.has_folder(path))
}
pub fn has_any_positive_extension(&self, exts: &[&str]) -> bool {
exts.iter()
.any(|ext| !ext.starts_with('!') && self.has_extension(ext))
}
pub fn has_no_negative_file_name(&self, names: &[&str]) -> bool {
!names
.iter()
.any(|name| name.starts_with('!') && self.has_file_name(&name[1..]))
}
pub fn has_no_negative_folder(&self, paths: &[&str]) -> bool {
!paths
.iter()
.any(|path| path.starts_with('!') && self.has_folder(&path[1..]))
}
pub fn has_no_negative_extension(&self, exts: &[&str]) -> bool {
!exts
.iter()
.any(|ext| ext.starts_with('!') && self.has_extension(&ext[1..]))
}
}
pub struct Repo {
pub repo: ThreadSafeRepository,
/// If `current_dir` is a git repository or is contained within one,
/// this is the short name of the current branch name of that repo,
/// i.e. `main`.
pub branch: Option<String>,
/// If `current_dir` is a git repository or is contained within one,
/// this is the path to the root of that repo.
pub workdir: Option<PathBuf>,
/// The path of the repository's `.git` directory.
pub path: PathBuf,
/// State
pub state: Option<git_state::InProgress>,
/// Remote repository
pub remote: Option<Remote>,
/// Contains `true` if the value of `core.fsmonitor` is set to `true`.
/// If not `true`, `fsmonitor` is explicitly disabled in git commands.
pub(crate) fs_monitor_value_is_true: bool,
// Kind of repository, work tree or bare
pub kind: Kind,
}
impl Repo {
/// Opens the associated git repository.
pub fn open(&self) -> Repository {
self.repo.to_thread_local()
}
/// Wrapper to execute external git commands.
/// Handles adding the appropriate `--git-dir` and `--work-tree` flags to the command.
/// Also handles additional features required for security, such as disabling `fsmonitor`.
/// At this time, mocking is not supported.
pub fn exec_git<T: AsRef<OsStr> + Debug>(
&self,
context: &Context,
git_args: impl IntoIterator<Item = T>,
) -> Option<CommandOutput> {
let mut command = create_command("git").ok()?;
// A value of `true` should not execute external commands.
let fsm_config_value = if self.fs_monitor_value_is_true {
"core.fsmonitor=true"
} else {
"core.fsmonitor="
};
command.env("GIT_OPTIONAL_LOCKS", "0").args([
OsStr::new("-C"),
context.current_dir.as_os_str(),
OsStr::new("--git-dir"),
self.path.as_os_str(),
OsStr::new("-c"),
OsStr::new(fsm_config_value),
]);
// Bare repositories might not have a workdir, so we need to check for that.
if let Some(wt) = self.workdir.as_ref() {
command.args([OsStr::new("--work-tree"), wt.as_os_str()]);
}
command.args(git_args);
log::trace!("Executing git command: {command:?}");
exec_timeout(
&mut command,
Duration::from_millis(context.root_config.command_timeout),
)
}
}
/// Remote repository
pub struct Remote {
pub branch: Option<String>,
pub name: Option<String>,
}
// A struct of Criteria which will be used to verify current PathBuf is
// of X language, criteria can be set via the builder pattern
pub struct ScanDir<'a> {
dir_contents: &'a DirContents,
files: &'a [&'a str],
folders: &'a [&'a str],
extensions: &'a [&'a str],
}
impl<'a> ScanDir<'a> {
#[must_use]
pub const fn set_files(mut self, files: &'a [&'a str]) -> Self {
self.files = files;
self
}
#[must_use]
pub const fn set_extensions(mut self, extensions: &'a [&'a str]) -> Self {
self.extensions = extensions;
self
}
#[must_use]
pub const fn set_folders(mut self, folders: &'a [&'a str]) -> Self {
self.folders = folders;
self
}
/// based on the current `PathBuf` check to see
/// if any of this criteria match or exist and returning a boolean
pub fn is_match(&self) -> bool {
// if there exists a file with a file/folder/ext we've said we don't want,
// fail the match straight away
self.dir_contents.has_no_negative_extension(self.extensions)
&& self.dir_contents.has_no_negative_file_name(self.files)
&& self.dir_contents.has_no_negative_folder(self.folders)
&& (self
.dir_contents
.has_any_positive_extension(self.extensions)
|| self.dir_contents.has_any_positive_file_name(self.files)
|| self.dir_contents.has_any_positive_folder(self.folders))
}
}
/// Scans the ancestors of a given path until a directory containing one of the given files or
/// folders is found.
pub struct ScanAncestors<'a> {
path: &'a Path,
files: &'a [&'a str],
folders: &'a [&'a str],
}
impl<'a> ScanAncestors<'a> {
#[must_use]
pub const fn set_files(mut self, files: &'a [&'a str]) -> Self {
self.files = files;
self
}
#[must_use]
pub const fn set_folders(mut self, folders: &'a [&'a str]) -> Self {
self.folders = folders;
self
}
/// Scans upwards starting from the initial path until a directory containing one of the given
/// files or folders is found.
///
/// The scan does not cross device boundaries.
pub fn scan(&self) -> Option<PathBuf> {
let path = self.path;
let initial_device_id = path.device_id();
// We want to avoid reallocations during the search so we pre-allocate a buffer with enough
// capacity to hold the longest path + any marker (we could find the length of the longest
// marker programmatically but that would actually cost more than preallocating a few bytes too many).
let mut buf = PathBuf::with_capacity(path.as_os_str().len() + 15);
path.clone_into(&mut buf);
loop {
if initial_device_id != buf.device_id() {
break;
}
for file in self.files {
// Then for each file, we look for `buf/file`
buf.push(file);
if buf.is_file() {
buf.pop();
return Some(buf);
}
// Removing the last pushed item means removing `file`, to replace it with either
// the next `file` or the first `folder`, if any
buf.pop();
}
for folder in self.folders {
// Then for each folder, we look for `buf/folder`
buf.push(folder);
if buf.is_dir() {
buf.pop();
return Some(buf);
}
buf.pop();
}
// Then we go up one level until there is no more level to go up with
if !buf.pop() {
break;
}
}
None
}
}
fn get_current_branch(repository: &Repository) -> Option<gix::refs::FullName> {
repository.head_name().ok()?
}
fn get_remote_repository_info(
repository: &Repository,
branch_name: Option<&gix::refs::FullNameRef>,
) -> Option<Remote> {
let branch_name = branch_name?;
let branch = repository
.branch_remote_ref_name(branch_name, gix::remote::Direction::Fetch)
.and_then(std::result::Result::ok)
.map(|r| r.shorten().to_string());
let name = repository
.branch_remote_name(branch_name.shorten(), gix::remote::Direction::Fetch)
.map(|n| n.as_bstr().to_string());
Some(Remote { branch, name })
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Shell {
Bash,
Fish,
Ion,
Pwsh,
PowerShell,
Zsh,
Elvish,
Tcsh,
Nu,
Xonsh,
Cmd,
Unknown,
}
/// Which kind of prompt target to print (main prompt, rprompt, ...)
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Target {
Main,
Right,
Continuation,
Profile(String),
}
/// Properties as passed on from the shell as arguments
#[derive(Parser, Debug)]
pub struct Properties {
/// The status code of the previously run command as an unsigned or signed 32bit integer
#[clap(short = 's', long = "status")]
pub status_code: Option<String>,
/// Bash, Fish and Zsh support returning codes for each process in a pipeline.
#[clap(long, value_delimiter = ' ')]
pub pipestatus: Option<Vec<String>>,
/// The width of the current interactive terminal.
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | true |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/configure.rs | src/configure.rs | use std::fmt::Write as _;
use std::process;
use std::process::Stdio;
use std::str::FromStr;
use crate::config::ModuleConfig;
use crate::config::StarshipConfig;
use crate::configs::PROMPT_ORDER;
use crate::context::Context;
use crate::utils;
use std::fs::File;
use std::io::Write;
use toml_edit::DocumentMut;
#[cfg(not(windows))]
const STD_EDITOR: &str = "vi";
#[cfg(windows)]
const STD_EDITOR: &str = "notepad.exe";
pub fn update_configuration(context: &Context, name: &str, value: &str) {
let mut doc = get_configuration_edit(context);
match handle_update_configuration(&mut doc, name, value) {
Err(e) => {
eprintln!("{e}");
process::exit(1);
}
_ => write_configuration(context, &doc),
}
}
fn handle_update_configuration(
doc: &mut DocumentMut,
name: &str,
value: &str,
) -> Result<(), String> {
let mut keys = name.split('.');
let first_key = keys.next().unwrap_or_default();
if first_key.is_empty() {
return Err("Empty table keys are not supported".to_owned());
}
let table = doc.as_table_mut();
let mut current_item = table.entry(first_key).or_insert_with(toml_edit::table);
for key in keys {
if !current_item.is_table_like() {
return Err("This command can only index into TOML tables".to_owned());
}
if key.is_empty() {
return Err("Empty table keys are not supported".to_owned());
}
let table = current_item.as_table_like_mut().unwrap();
if !table.contains_key(key) {
table.insert(key, toml_edit::table());
}
current_item = table.get_mut(key).unwrap();
}
let mut new_value = toml_edit::Value::from_str(value)
.map_or_else(|_| toml_edit::value(value), toml_edit::Item::Value);
if let Some(value) = current_item.as_value() {
*new_value.as_value_mut().unwrap().decor_mut() = value.decor().clone();
}
*current_item = new_value;
Ok(())
}
pub fn print_configuration(context: &Context, use_default: bool, paths: &[String]) -> String {
let config = if use_default {
// Get default config
let default_config = crate::configs::FullConfig::default();
// Convert back to Value because toml can't serialize FullConfig directly
toml::value::Value::try_from(default_config).unwrap()
} else {
// Get config as toml::Value
let user_config = get_configuration(context);
// Convert into FullConfig and fill in default values
let user_config = crate::configs::FullConfig::load(&user_config);
// Convert back to Value because toml can't serialize FullConfig directly
toml::value::Value::try_from(user_config).unwrap()
};
println!("# Warning: This config does not include keys that have an unset value\n");
// These are only used for format specifiers so don't print them if we aren't showing formats.
if paths.is_empty()
|| paths
.iter()
.any(|path| path == "format" || path == "right_format")
{
println!(
"# $all is shorthand for {}",
PROMPT_ORDER
.iter()
.fold(String::new(), |mut output, module_name| {
let _ = write!(output, "${module_name}");
output
})
);
// Unwrapping is fine because config is based on FullConfig
let custom_modules = config.get("custom").unwrap().as_table().unwrap();
if !use_default && !custom_modules.is_empty() {
println!(
"# $custom (excluding any modules already listed in `format`) is shorthand for {}",
custom_modules.keys().fold(String::new(), |mut output, b| {
let _ = write!(output, "${{custom.{b}}}");
output
})
);
}
}
let print_config = if paths.is_empty() {
config
} else {
extract_toml_paths(config, paths)
};
let string_config = toml::to_string_pretty(&print_config).unwrap();
println!("{string_config}");
string_config
}
fn extract_toml_paths(mut config: toml::Value, paths: &[String]) -> toml::Value {
// Extract all the requested sections into a new configuration.
let mut subset = toml::value::Table::new();
let Some(config) = config.as_table_mut() else {
// This function doesn't make any sense if the root is not a table.
return toml::Value::Table(subset);
};
'paths: for path in paths {
let path_segments: Vec<_> = path.split('.').collect();
let (&end, parents) = path_segments.split_last().unwrap_or((&"", &[]));
// Locate the parent table to remove the value from.
let mut source_cursor = &mut *config;
for &segment in parents {
source_cursor = if let Some(child) = source_cursor
.get_mut(segment)
.and_then(toml::Value::as_table_mut)
{
child
} else {
// We didn't find a value for this path, so move on to the next path.
continue 'paths;
}
}
// Extract the value to move.
let Some(value) = source_cursor.remove(end) else {
// We didn't find a value for this path, so move on to the next path.
continue 'paths;
};
// Create a destination for that value.
let mut destination_cursor = &mut subset;
for &segment in &path_segments[..path_segments.len() - 1] {
// Because we initialize `subset` to be a table, and only add additional values that
// exist in `config`, it's impossible for the value here to not be a table.
destination_cursor = destination_cursor
.entry(segment)
.or_insert_with(|| toml::Value::Table(toml::value::Table::new()))
.as_table_mut()
.unwrap();
}
destination_cursor.insert(end.to_owned(), value);
}
toml::Value::Table(subset)
}
pub fn toggle_configuration(context: &Context, name: &str, key: &str) {
let mut doc = get_configuration_edit(context);
match handle_toggle_configuration(&mut doc, name, key) {
Err(e) => {
eprintln!("{e}");
process::exit(1);
}
_ => write_configuration(context, &doc),
}
}
fn handle_toggle_configuration(doc: &mut DocumentMut, name: &str, key: &str) -> Result<(), String> {
if name.is_empty() || key.is_empty() {
return Err("Empty table keys are not supported".to_owned());
}
let table = doc.as_table_mut();
let values = table
.get_mut(name)
.ok_or_else(|| format!("Given module '{name}' not found in config file"))?
.as_table_like_mut()
.ok_or_else(|| format!("Given config entry '{key}' is not a module"))?;
let old_value = values
.get(key)
.ok_or_else(|| format!("Given config key '{key}' must exist in config file"))?;
let old = old_value
.as_bool()
.ok_or_else(|| format!("Given config key '{key}' must be in 'boolean' format"))?;
let mut new_value = toml_edit::value(!old);
// Above code already checks if it is a value (bool)
*new_value.as_value_mut().unwrap().decor_mut() = old_value.as_value().unwrap().decor().clone();
values.insert(key, new_value);
Ok(())
}
pub fn get_configuration(context: &Context) -> toml::Table {
let starship_config = StarshipConfig::initialize(context.get_config_path_os().as_deref());
starship_config.config.unwrap_or_default()
}
pub fn get_configuration_edit(context: &Context) -> DocumentMut {
let config_file_path = context.get_config_path_os();
let toml_content = StarshipConfig::read_config_content_as_str(config_file_path.as_deref());
toml_content
.unwrap_or_default()
.parse::<DocumentMut>()
.expect("Failed to load starship config")
}
pub fn write_configuration(context: &Context, doc: &DocumentMut) {
let config_path = context.get_config_path_os().unwrap_or_else(|| {
eprintln!("config path required to write configuration");
process::exit(1);
});
let config_str = doc.to_string();
File::create(config_path)
.and_then(|mut file| file.write_all(config_str.as_ref()))
.expect("Error writing starship config");
}
pub fn edit_configuration(
context: &Context,
editor_override: Option<&str>,
) -> Result<(), Box<dyn std::error::Error>> {
// Argument currently only used for testing, but could be used to specify
// an editor override on the command line.
let config_path = context.get_config_path_os().unwrap_or_else(|| {
eprintln!("config path required to edit configuration");
process::exit(1);
});
let editor_cmd = shell_words::split(&get_editor(editor_override))?;
let mut command = match utils::create_command(&editor_cmd[0]) {
Ok(cmd) => cmd,
Err(e) => {
eprintln!(
"Unable to find editor {:?}. Are $VISUAL and $EDITOR set correctly?",
editor_cmd[0]
);
return Err(Box::new(e));
}
};
let res = command
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.args(&editor_cmd[1..])
.arg(config_path)
.status();
if let Err(e) = res {
eprintln!("Unable to launch editor {editor_cmd:?}");
return Err(Box::new(e));
}
Ok(())
}
fn get_editor(editor_override: Option<&str>) -> String {
if let Some(cmd) = editor_override {
cmd.to_string()
} else {
get_editor_internal(std::env::var("VISUAL").ok(), std::env::var("EDITOR").ok())
}
}
fn get_editor_internal(visual: Option<String>, editor: Option<String>) -> String {
let editor_name = visual.unwrap_or_default();
if !editor_name.is_empty() {
return editor_name;
}
let editor_name = editor.unwrap_or_default();
if !editor_name.is_empty() {
return editor_name;
}
STD_EDITOR.into()
}
#[cfg(test)]
mod tests {
use std::{fs::create_dir, io, path::PathBuf};
use tempfile::TempDir;
use toml_edit::Item;
use crate::{
context::{Properties, Shell, Target},
context_env::Env,
};
use super::*;
// This is every possible permutation, 3² = 9.
#[test]
fn visual_set_editor_set() {
let actual = get_editor_internal(Some("foo".into()), Some("bar".into()));
assert_eq!("foo", actual);
}
#[test]
fn visual_set_editor_empty() {
let actual = get_editor_internal(Some("foo".into()), None);
assert_eq!("foo", actual);
}
#[test]
fn visual_set_editor_not_set() {
let actual = get_editor_internal(Some("foo".into()), None);
assert_eq!("foo", actual);
}
#[test]
fn visual_empty_editor_set() {
let actual = get_editor_internal(Some(String::new()), Some("bar".into()));
assert_eq!("bar", actual);
}
#[test]
fn visual_empty_editor_empty() {
let actual = get_editor_internal(Some(String::new()), Some(String::new()));
assert_eq!(STD_EDITOR, actual);
}
#[test]
fn visual_empty_editor_not_set() {
let actual = get_editor_internal(Some(String::new()), None);
assert_eq!(STD_EDITOR, actual);
}
#[test]
fn visual_not_set_editor_set() {
let actual = get_editor_internal(None, Some("bar".into()));
assert_eq!("bar", actual);
}
#[test]
fn visual_not_set_editor_empty() {
let actual = get_editor_internal(None, Some(String::new()));
assert_eq!(STD_EDITOR, actual);
}
#[test]
fn visual_not_set_editor_not_set() {
let actual = get_editor_internal(None, None);
assert_eq!(STD_EDITOR, actual);
}
#[test]
fn no_panic_when_editor_unparsable() {
let outcome = edit_configuration(&Context::default(), Some("\"vim"));
assert!(outcome.is_err());
}
#[test]
fn no_panic_when_editor_not_found() {
let outcome = edit_configuration(&Context::default(), Some("this_editor_does_not_exist"));
assert!(outcome.is_err());
}
#[test]
fn test_extract_toml_paths() {
let config = toml::toml! {
extract_root = true
ignore_root = false
[extract_section]
ok = true
[extract_section.subsection]
ok = true
[ignore_section]
ok = false
[extract_subsection]
ok = false
[extract_subsection.extracted]
ok = true
[extract_subsection.ignored]
ok = false
};
let expected_config = toml::toml! {
extract_root = true
[extract_section]
ok = true
[extract_section.subsection]
ok = true
[extract_subsection.extracted]
ok = true
};
let actual_config = extract_toml_paths(
toml::Value::Table(config),
&[
"extract_root".to_owned(),
"extract_section".to_owned(),
"extract_subsection.extracted".to_owned(),
],
);
assert_eq!(toml::Value::Table(expected_config), actual_config);
}
fn create_doc() -> DocumentMut {
let config = concat!(
" # comment\n",
" [status] # comment\n",
"disabled = false # comment\n",
"# comment\n",
"\n"
);
config.parse::<DocumentMut>().unwrap()
}
#[test]
fn test_toggle_simple() {
let mut doc = create_doc();
assert!(!doc["status"]["disabled"].as_bool().unwrap());
handle_toggle_configuration(&mut doc, "status", "disabled").unwrap();
assert!(doc["status"]["disabled"].as_bool().unwrap());
let new_config = concat!(
" # comment\n",
" [status] # comment\n",
"disabled = true # comment\n",
"# comment\n",
"\n"
);
assert_eq!(doc.to_string(), new_config);
}
#[test]
fn test_toggle_missing_module() {
let mut doc = create_doc();
assert!(handle_toggle_configuration(&mut doc, "missing_module", "disabled").is_err());
}
#[test]
fn test_toggle_missing_key() {
let mut doc = create_doc();
assert!(handle_toggle_configuration(&mut doc, "status", "missing").is_err());
}
#[test]
fn test_toggle_wrong_type() {
let mut doc = create_doc();
doc["status"]["disabled"] = toml_edit::value("a");
assert!(handle_toggle_configuration(&mut doc, "status", "disabled").is_err());
doc["format"] = toml_edit::value("$all");
assert!(handle_toggle_configuration(&mut doc, "format", "disabled").is_err());
}
#[test]
fn test_toggle_empty() {
let mut doc = create_doc();
doc["status"][""] = toml_edit::value(true);
doc[""]["disabled"] = toml_edit::value(true);
assert!(handle_toggle_configuration(&mut doc, "status", "").is_err());
assert!(handle_toggle_configuration(&mut doc, "", "disabled").is_err());
}
#[test]
fn test_update_config_wrong_type() {
let mut doc = create_doc();
assert!(
handle_update_configuration(&mut doc, "status.disabled.not_a_table", "true").is_err()
);
}
#[test]
fn test_update_config_simple() {
let mut doc = create_doc();
assert!(!doc["status"]["disabled"].as_bool().unwrap());
handle_update_configuration(&mut doc, "status.disabled", "true").unwrap();
assert!(doc["status"]["disabled"].as_bool().unwrap());
let new_config = concat!(
" # comment\n",
" [status] # comment\n",
"disabled = true # comment\n",
"# comment\n",
"\n"
);
assert_eq!(doc.to_string(), new_config);
}
#[test]
fn test_update_config_parse() {
let mut doc = create_doc();
handle_update_configuration(&mut doc, "test", "true").unwrap();
assert!(doc["test"].as_bool().unwrap());
handle_update_configuration(&mut doc, "test", "0").unwrap();
assert_eq!(doc["test"].as_integer().unwrap(), 0);
handle_update_configuration(&mut doc, "test", "0.0").unwrap();
assert!(doc["test"].is_float());
handle_update_configuration(&mut doc, "test", "a string").unwrap();
assert_eq!(doc["test"].as_str().unwrap(), "a string");
handle_update_configuration(&mut doc, "test", "\"true\"").unwrap();
assert_eq!(doc["test"].as_str().unwrap(), "true");
}
#[test]
fn test_update_config_empty() {
let mut doc = create_doc();
assert!(handle_update_configuration(&mut doc, "", "true").is_err());
assert!(handle_update_configuration(&mut doc, ".....", "true").is_err());
assert!(handle_update_configuration(&mut doc, "a.a.a..a.a", "true").is_err());
assert!(handle_update_configuration(&mut doc, "a.a.a.a.a.", "true").is_err());
assert!(handle_update_configuration(&mut doc, ".a.a.a.a.a", "true").is_err());
}
#[test]
fn test_update_config_deep() {
let mut doc = create_doc();
handle_update_configuration(&mut doc, "a.b.c.d.e.f.g.h", "true").unwrap();
assert!(
doc["a"]["b"]["c"]["d"]["e"]["f"]["g"]["h"]
.as_bool()
.unwrap()
);
}
#[test]
fn write_and_get_configuration_test() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let context = setup_config(&dir, true, StarshipConfigEnvScenario::NotSpecified)?;
let mut doc = get_configuration_edit(&context);
doc["directory"]["format"] = Item::Value("myformat".into());
write_configuration(&context, &doc);
let doc_reloaded = get_configuration_edit(&context);
assert_eq!(
"myformat",
doc_reloaded["directory"]["format"].as_str().unwrap()
);
dir.close()
}
const PRINT_CONFIG_DEFAULT: &str = "[custom]";
const PRINT_CONFIG_HOME: &str = "[custom.home]";
const PRINT_CONFIG_ENV: &str = "[custom.STARSHIP_CONFIG]";
#[test]
fn print_configuration_scenarios() -> io::Result<()> {
run_print_configuration_test(
"~/.config/starship.toml, no STARSHIP_CONFIG uses home",
true,
StarshipConfigEnvScenario::NotSpecified,
PRINT_CONFIG_HOME,
)?;
run_print_configuration_test(
"no ~/.config/starship.toml, no STARSHIP_CONFIG uses default",
false,
StarshipConfigEnvScenario::NotSpecified,
PRINT_CONFIG_DEFAULT,
)?;
run_print_configuration_test(
"~/.config/starship.toml, STARSHIP_CONFIG nonexisting file uses default",
true,
StarshipConfigEnvScenario::NonExistingFile,
PRINT_CONFIG_DEFAULT,
)?;
run_print_configuration_test(
"~/.config/starship.toml, STARSHIP_CONFIG existing file uses STARSHIP_CONFIG file",
true,
StarshipConfigEnvScenario::ExistingFile,
PRINT_CONFIG_ENV,
)?;
Ok(())
}
#[derive(Clone, Copy)]
enum StarshipConfigEnvScenario {
NotSpecified,
NonExistingFile,
ExistingFile,
}
fn run_print_configuration_test(
message: &str,
home_file_exists: bool,
starship_config_env_scenario: StarshipConfigEnvScenario,
expected_first_line: &str,
) -> io::Result<()> {
let dir = tempfile::tempdir()?;
let context = setup_config(&dir, home_file_exists, starship_config_env_scenario)?;
let config = print_configuration(&context, false, &["custom".to_string()]);
let first_line = config.split('\n').next().unwrap();
assert_eq!(expected_first_line, first_line, "{message}");
dir.close()
}
fn setup_config(
dir: &TempDir,
home_file_exists: bool,
starship_config_env_scenario: StarshipConfigEnvScenario,
) -> io::Result<Context<'_>> {
let config_path = dir.path().to_path_buf().join(".config");
create_dir(&config_path)?;
let home_starship_toml = config_path.join("starship.toml");
let env_toml = dir.path().join("env.toml");
if home_file_exists {
let mut home_file = File::create(home_starship_toml)?;
home_file.write_all(PRINT_CONFIG_HOME.as_bytes())?;
}
let env_starship_config = match starship_config_env_scenario {
StarshipConfigEnvScenario::NotSpecified => None,
StarshipConfigEnvScenario::NonExistingFile => Some(env_toml),
StarshipConfigEnvScenario::ExistingFile => {
let mut env_toml_file = File::create(&env_toml)?;
env_toml_file.write_all(PRINT_CONFIG_ENV.as_bytes())?;
Some(env_toml)
}
};
let mut env = Env::default();
if let Some(v) = env_starship_config {
env.insert("STARSHIP_CONFIG", v.to_string_lossy().to_string());
}
env.insert(
"HOME",
dir.path().to_path_buf().to_string_lossy().to_string(),
);
Ok(Context::new_with_shell_and_path(
Properties::default(),
Shell::Unknown,
Target::Main,
PathBuf::default(),
PathBuf::default(),
env,
))
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/segment.rs | src/segment.rs | use crate::{
config::Style,
print::{Grapheme, UnicodeWidthGraphemes},
};
use nu_ansi_term::{AnsiString, Style as AnsiStyle};
use unicode_segmentation::UnicodeSegmentation;
/// Type that holds text with an associated style
#[derive(Clone)]
pub struct TextSegment {
/// The segment's style. If None, will inherit the style of the module containing it.
style: Option<Style>,
/// The string value of the current segment.
value: String,
}
impl TextSegment {
// Returns the AnsiString of the segment value
fn ansi_string(&self, prev: Option<&AnsiStyle>) -> AnsiString<'_> {
match self.style {
Some(style) => style.to_ansi_style(prev).paint(&self.value),
None => AnsiString::from(&self.value),
}
}
}
/// Type that holds fill text with an associated style
#[derive(Clone)]
pub struct FillSegment {
/// The segment's style. If None, will inherit the style of the module containing it.
style: Option<Style>,
/// The string value of the current segment.
value: String,
}
impl FillSegment {
// Returns the AnsiString of the segment value, not including its prefix and suffix
pub fn ansi_string(&self, width: Option<usize>, prev: Option<&AnsiStyle>) -> AnsiString<'_> {
let s = match width {
Some(w) => self
.value
.graphemes(true)
.cycle()
.scan(0usize, |len, g| {
*len += Grapheme(g).width();
if *len <= w { Some(g) } else { None }
})
.collect::<String>(),
None => String::from(&self.value),
};
match self.style {
Some(style) => style.to_ansi_style(prev).paint(s),
None => AnsiString::from(s),
}
}
}
#[cfg(test)]
mod fill_seg_tests {
use super::FillSegment;
use nu_ansi_term::Color;
#[test]
fn ansi_string_width() {
let width: usize = 10;
let style = Color::Blue.bold();
let inputs = vec![
(".", ".........."),
(".:", ".:.:.:.:.:"),
("-:-", "-:--:--:--"),
("🟦", "🟦🟦🟦🟦🟦"),
("🟢🔵🟡", "🟢🔵🟡🟢🔵"),
];
for (text, expected) in &inputs {
let f = FillSegment {
value: String::from(*text),
style: Some(style.into()),
};
let actual = f.ansi_string(Some(width), None);
assert_eq!(style.paint(*expected), actual);
}
}
}
/// A segment is a styled text chunk ready for printing.
#[derive(Clone)]
pub enum Segment {
Text(TextSegment),
Fill(FillSegment),
LineTerm,
}
impl Segment {
/// Creates new segments from a text with a style; breaking out `LineTerminators`.
pub fn from_text<T>(style: Option<Style>, value: T) -> Vec<Self>
where
T: Into<String>,
{
let mut segs: Vec<Self> = Vec::new();
value.into().split(LINE_TERMINATOR).for_each(|s| {
if !segs.is_empty() {
segs.push(Self::LineTerm);
}
segs.push(Self::Text(TextSegment {
value: String::from(s),
style,
}));
});
segs
}
/// Creates a new fill segment
pub fn fill<T>(style: Option<Style>, value: T) -> Self
where
T: Into<String>,
{
Self::Fill(FillSegment {
style,
value: value.into(),
})
}
pub fn style(&self) -> Option<AnsiStyle> {
match self {
Self::Fill(fs) => fs.style.map(|cs| cs.to_ansi_style(None)),
Self::Text(ts) => ts.style.map(|cs| cs.to_ansi_style(None)),
Self::LineTerm => None,
}
}
pub fn set_style_if_empty(&mut self, style: Option<Style>) {
match self {
Self::Fill(fs) => {
if fs.style.is_none() {
fs.style = style;
}
}
Self::Text(ts) => {
if ts.style.is_none() {
ts.style = style;
}
}
Self::LineTerm => {}
}
}
pub fn value(&self) -> &str {
match self {
Self::Fill(fs) => &fs.value,
Self::Text(ts) => &ts.value,
Self::LineTerm => LINE_TERMINATOR_STRING,
}
}
// Returns the AnsiString of the segment value, not including its prefix and suffix
pub fn ansi_string(&self, prev: Option<&AnsiStyle>) -> AnsiString<'_> {
match self {
Self::Fill(fs) => fs.ansi_string(None, prev),
Self::Text(ts) => ts.ansi_string(prev),
Self::LineTerm => AnsiString::from(LINE_TERMINATOR_STRING),
}
}
pub fn width_graphemes(&self) -> usize {
match self {
Self::Fill(fs) => fs.value.width_graphemes(),
Self::Text(ts) => ts.value.width_graphemes(),
Self::LineTerm => 0,
}
}
}
const LINE_TERMINATOR: char = '\n';
const LINE_TERMINATOR_STRING: &str = "\n";
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/serde_utils.rs | src/serde_utils.rs | use crate::module::ALL_MODULES;
use serde::de::{
Deserializer, Error, IntoDeserializer, Visitor,
value::{Error as ValueError, MapDeserializer, SeqDeserializer},
};
use std::{cmp::Ordering, fmt};
use toml::Value;
/// A `toml::Value` that borrows its contents instead of owning them.
#[derive(Debug, Clone, Copy)]
pub enum ValueRef<'a> {
Boolean(bool),
Integer(i64),
Float(f64),
String(&'a str),
Datetime(&'a toml::value::Datetime),
Array(&'a [Value]),
Table(&'a toml::map::Map<String, Value>),
}
impl<'de> From<&'de Value> for ValueRef<'de> {
fn from(value: &'de Value) -> Self {
match value {
Value::Boolean(b) => Self::Boolean(*b),
Value::Integer(i) => Self::Integer(*i),
Value::Float(f) => Self::Float(*f),
Value::String(s) => Self::String(s),
Value::Array(a) => Self::Array(a),
Value::Table(t) => Self::Table(t),
Value::Datetime(d) => Self::Datetime(d),
}
}
}
impl<'de> From<&'de toml::Table> for ValueRef<'de> {
fn from(value: &'de toml::Table) -> Self {
Self::Table(value)
}
}
/// A helper struct for deserializing a TOML value references with serde.
/// This also prints a warning and suggestions if a key is unknown.
#[derive(Debug)]
pub struct ValueDeserializer<'de> {
value: ValueRef<'de>,
info: Option<StructInfo>,
current_key: Option<&'de str>,
error_on_ignored: bool,
}
/// When deserializing a struct, this struct stores information about the struct.
#[derive(Debug, Clone, Copy)]
struct StructInfo {
fields: &'static [&'static str],
name: &'static str,
}
impl<'de> ValueDeserializer<'de> {
pub fn new<T: Into<ValueRef<'de>>>(value: T) -> Self {
Self {
value: value.into(),
info: None,
current_key: None,
error_on_ignored: true,
}
}
fn with_info(
value: ValueRef<'de>,
info: Option<StructInfo>,
current_key: &'de str,
ignored: bool,
) -> Self {
Self {
value,
info,
current_key: Some(current_key),
error_on_ignored: ignored,
}
}
pub fn with_allow_unknown_keys(self) -> Self {
Self {
error_on_ignored: false,
..self
}
}
}
impl ValueDeserializer<'_> {
/// Prettify an error message by adding the current key and struct name to it.
fn error<T: fmt::Display>(&self, msg: T) -> ValueError {
match (self.current_key, self.info) {
(Some(key), Some(StructInfo { name, .. })) => {
// Prettify name of struct
let display_name = name.strip_suffix("Config").unwrap_or(name);
ValueError::custom(format!("Error in '{display_name}' at '{key}': {msg}",))
}
// Handling other cases leads to duplicates in the error message.
_ => ValueError::custom(msg),
}
}
}
impl<'de> IntoDeserializer<'de> for ValueDeserializer<'de> {
type Deserializer = Self;
fn into_deserializer(self) -> Self {
self
}
}
impl<'de> Deserializer<'de> for ValueDeserializer<'de> {
type Error = ValueError;
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
match self.value {
ValueRef::Boolean(b) => visitor.visit_bool(b),
ValueRef::Integer(i) => visitor.visit_i64(i),
ValueRef::Float(f) => visitor.visit_f64(f),
ValueRef::String(s) => visitor.visit_borrowed_str(s),
ValueRef::Array(a) => {
let seq = SeqDeserializer::new(a.iter().map(ValueDeserializer::new));
seq.deserialize_seq(visitor)
}
ValueRef::Table(t) => {
let map = MapDeserializer::new(t.iter().map(|(k, v)| {
(
k.as_str(),
ValueDeserializer::with_info(
v.into(),
self.info,
k.as_str(),
self.error_on_ignored,
),
)
}));
map.deserialize_map(visitor)
}
ValueRef::Datetime(d) => visitor.visit_string(d.to_string()),
}
.map_err(|e| self.error(e))
}
// Save a reference to the struct fields and name for later use in error messages.
fn deserialize_struct<V>(
mut self,
name: &'static str,
fields: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
self.info = Some(StructInfo { fields, name });
self.deserialize_any(visitor)
}
// Always `Some` because TOML doesn't have a null type.
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_some(self)
}
// Handle ignored Values. (Values at unknown keys in TOML)
fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
if self
.info
.filter(|StructInfo { name, .. }| name == &"StarshipRootConfig")
.and(self.current_key)
.is_some_and(|key| ALL_MODULES.contains(&key) || key == "custom" || key == "env_var")
{
return visitor.visit_none();
}
if !self.error_on_ignored {
return visitor.visit_none();
}
let did_you_mean = match (self.current_key, self.info) {
(Some(key), Some(StructInfo { fields, .. })) => fields
.iter()
.filter_map(|field| {
let score = strsim::jaro_winkler(key, field);
(score > 0.8).then_some((score, field))
})
.max_by(|(score_a, _field_a), (score_b, _field_b)| {
score_a.partial_cmp(score_b).unwrap_or(Ordering::Equal)
}),
_ => None,
};
let did_you_mean = did_you_mean
.map(|(_score, field)| format!(" (Did you mean '{field}'?)"))
.unwrap_or_default();
Err(self.error(format!("Unknown key{did_you_mean}")))
}
fn deserialize_newtype_struct<V>(
self,
_name: &'static str,
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_newtype_struct(self)
}
// Handle most deserialization cases by deferring to `deserialize_any`.
serde::forward_to_deserialize_any! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq
bytes byte_buf map unit_struct tuple_struct enum tuple identifier
}
}
#[cfg(test)]
mod test {
use crate::configs::StarshipRootConfig;
use super::*;
use serde::Deserialize;
#[test]
fn test_deserialize_bool() {
let value = Value::Boolean(true);
let deserializer = ValueDeserializer::new(&value);
let result: bool = bool::deserialize(deserializer).unwrap();
assert!(result);
}
#[test]
fn test_deserialize_i64() {
let value = Value::Integer(42);
let deserializer = ValueDeserializer::new(&value);
let result: i64 = i64::deserialize(deserializer).unwrap();
assert_eq!(result, 42);
}
#[test]
#[allow(clippy::approx_constant)]
fn test_deserialize_f64() {
let value = Value::Float(3.14);
let deserializer = ValueDeserializer::new(&value);
let result: f64 = f64::deserialize(deserializer).unwrap();
assert_eq!(result, 3.14);
}
#[test]
fn test_deserialize_string() {
let value = Value::String("hello".to_string());
let deserializer = ValueDeserializer::new(&value);
let result: String = String::deserialize(deserializer).unwrap();
assert_eq!(result, "hello");
}
#[test]
fn test_deserialize_str() {
let value = toml::toml! {
foo = "bar"
};
let deserializer = ValueDeserializer::new(&value);
#[derive(Deserialize)]
struct StrWrapper<'a> {
foo: &'a str,
}
let result = StrWrapper::deserialize(deserializer).unwrap();
assert_eq!(result.foo, "bar");
}
#[test]
fn test_deserialize_datetime() {
let value = toml::toml! {
foo = 2018-01-01T00:00:00Z
};
let deserializer = ValueDeserializer::new(&value);
#[derive(Deserialize)]
struct DateWrapper {
foo: String,
}
let result = DateWrapper::deserialize(deserializer).unwrap();
assert_eq!(result.foo, "2018-01-01T00:00:00Z");
}
#[test]
fn test_deserialize_array() {
let value = toml::toml! {
foo = [1, 2, 3]
};
let deserializer = ValueDeserializer::new(&value);
#[derive(Deserialize)]
struct ArrayWrapper {
foo: Vec<i32>,
}
let result = ArrayWrapper::deserialize(deserializer).unwrap();
assert_eq!(result.foo, vec![1, 2, 3]);
}
#[test]
fn test_deserialize_map() {
let value = toml::toml! {
[foo]
a = 1
b = 2
};
let deserializer = ValueDeserializer::new(&value);
#[derive(Deserialize)]
struct MapWrapper {
foo: std::collections::HashMap<String, i32>,
}
let result = MapWrapper::deserialize(deserializer).unwrap();
assert_eq!(
result.foo,
std::collections::HashMap::from_iter(vec![("a".to_string(), 1), ("b".to_string(), 2)])
);
}
#[test]
fn test_deserialize_newtype_struct() {
let value = toml::toml! {
foo = "bar"
};
#[derive(Deserialize)]
struct NewtypeWrapper(String);
#[derive(Deserialize)]
struct Sample {
foo: NewtypeWrapper,
}
let deserializer = ValueDeserializer::new(&value);
let result = Sample::deserialize(deserializer).unwrap();
assert_eq!(result.foo.0, "bar".to_owned());
}
#[test]
fn test_deserialize_unknown() {
let value = toml::toml! {
foo = "bar"
unknown_key = 1
};
let deserializer = ValueDeserializer::new(&value);
#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct Sample {
foo: String,
}
let result = Sample::deserialize(deserializer).unwrap_err();
assert_eq!(
format!("{result}"),
"Error in 'Sample' at 'unknown_key': Unknown key"
);
}
#[test]
fn test_deserialize_unknown_root_config() {
let value = toml::toml! {
unknown_key = "foo"
};
let deserializer = ValueDeserializer::new(&value);
let result = StarshipRootConfig::deserialize(deserializer).unwrap_err();
assert_eq!(
format!("{result}"),
"Error in 'StarshipRoot' at 'unknown_key': Unknown key"
);
let deserializer2 = ValueDeserializer::new(&value).with_allow_unknown_keys();
let result = StarshipRootConfig::deserialize(deserializer2);
assert!(result.is_ok());
}
#[test]
fn test_deserialize_unknown_root_module() {
let value = toml::toml! {
[rust]
disabled = true
};
let deserializer = ValueDeserializer::new(&value);
let result = StarshipRootConfig::deserialize(deserializer);
assert!(result.is_ok());
}
#[test]
fn test_deserialize_unknown_typo() {
let value = toml::toml! {
food = "bar"
};
let deserializer = ValueDeserializer::new(&value);
#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct Sample {
foo: String,
}
let result = Sample::deserialize(deserializer).unwrap_err();
assert_eq!(
format!("{result}"),
"Error in 'Sample' at 'food': Unknown key (Did you mean 'foo'?)"
);
}
#[test]
fn test_deserialize_wrong_type() {
let value = toml::toml! {
foo = 1
};
let deserializer = ValueDeserializer::new(&value);
#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct Sample {
foo: String,
}
let result = Sample::deserialize(deserializer).unwrap_err();
assert_eq!(
format!("{result}"),
"Error in 'Sample' at 'foo': invalid type: integer `1`, expected a string"
);
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/print.rs | src/print.rs | use clap::{ValueEnum, builder::PossibleValue};
use nu_ansi_term::AnsiStrings;
use rayon::prelude::*;
use regex::Regex;
use std::collections::BTreeSet;
use std::fmt::{Debug, Write as FmtWrite};
use std::io::{self, Write};
use std::path::PathBuf;
use std::sync::OnceLock;
use std::time::Duration;
use terminal_size::terminal_size;
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthChar;
use crate::configs::PROMPT_ORDER;
use crate::context::{Context, Properties, Shell, Target};
use crate::formatter::{StringFormatter, VariableHolder};
use crate::module::ALL_MODULES;
use crate::module::Module;
use crate::modules;
use crate::segment::Segment;
use crate::shadow;
use crate::utils::wrap_colorseq_for_shell;
pub struct Grapheme<'a>(pub &'a str);
impl Grapheme<'_> {
pub fn width(&self) -> usize {
self.0
.chars()
.filter_map(UnicodeWidthChar::width)
.max()
.unwrap_or(0)
}
}
pub trait UnicodeWidthGraphemes {
fn width_graphemes(&self) -> usize;
}
static ANSI_REGEX: OnceLock<Regex> = OnceLock::new();
fn ansi_strip() -> &'static Regex {
ANSI_REGEX.get_or_init(|| Regex::new(r"\x1B\[[0-9;]*m").unwrap())
}
impl<T> UnicodeWidthGraphemes for T
where
T: AsRef<str>,
{
fn width_graphemes(&self) -> usize {
ansi_strip()
.replace_all(self.as_ref(), "")
.into_owned()
.graphemes(true)
.map(Grapheme)
.map(|g| g.width())
.sum()
}
}
#[test]
fn test_grapheme_aware_width() {
// UnicodeWidthStr::width would return 8
assert_eq!(2, "👩👩👦👦".width_graphemes());
assert_eq!(1, "Ü".width_graphemes());
assert_eq!(11, "normal text".width_graphemes());
// Magenta string test
assert_eq!(11, "\x1B[35;6mnormal text".width_graphemes());
}
pub fn prompt(args: Properties, target: Target) {
let context = Context::new(args, target);
let stdout = io::stdout();
let mut handle = stdout.lock();
write!(handle, "{}", get_prompt(&context)).unwrap();
}
pub fn get_prompt(context: &Context) -> String {
let config = &context.root_config;
let mut buf = String::new();
match std::env::var_os("TERM") {
Some(term) if term == "dumb" => {
log::error!("Under a 'dumb' terminal (TERM=dumb).");
buf.push_str("Starship disabled due to TERM=dumb > ");
return buf;
}
_ => {}
}
// A workaround for a fish bug (see #739,#279). Applying it to all shells
// breaks things (see #808,#824,#834). Should only be printed in fish.
if Shell::Fish == context.shell && context.target == Target::Main {
buf.push_str("\x1b[J"); // An ASCII control code to clear screen
}
let (formatter, modules) = load_formatter_and_modules(context);
let formatter = formatter.map_variables_to_segments(|module| {
// Make $all display all modules not explicitly referenced
if module == "all" {
Some(Ok(all_modules_uniq(&modules)
.par_iter()
.flat_map(|module| {
handle_module(module, context, &modules)
.into_iter()
.flat_map(|module| module.segments)
.collect::<Vec<Segment>>()
})
.collect::<Vec<_>>()))
} else if context.is_module_disabled_in_config(module) {
None
} else {
// Get segments from module
Some(Ok(handle_module(module, context, &modules)
.into_iter()
.flat_map(|module| module.segments)
.collect::<Vec<Segment>>()))
}
});
// Creates a root module and prints it.
let mut root_module = Module::new("Starship Root", "The root module", None);
root_module.set_segments(
formatter
.parse(None, Some(context))
.expect("Unexpected error returned in root format variables"),
);
let module_strings = root_module.ansi_strings_for_width(Some(context.width));
if config.add_newline && context.target != Target::Continuation {
// continuation prompts normally do not include newlines, but they can
writeln!(buf).unwrap();
}
// AnsiStrings strips redundant ANSI color sequences, so apply it before modifying the ANSI
// color sequences for this specific shell
let shell_wrapped_output =
wrap_colorseq_for_shell(AnsiStrings(&module_strings).to_string(), context.shell);
write!(buf, "{shell_wrapped_output}").unwrap();
if context.target == Target::Right {
// right prompts generally do not allow newlines
buf = buf.replace('\n', "");
}
// escape \n and ! characters for tcsh
if context.shell == Shell::Tcsh {
buf = buf.replace('!', "\\!");
// space is required before newline
buf = buf.replace('\n', " \\n");
}
buf
}
pub fn module(module_name: &str, args: Properties) {
let context = Context::new(args, Target::Main);
let module = get_module(module_name, &context).unwrap_or_default();
print!("{module}");
}
pub fn get_module(module_name: &str, context: &Context) -> Option<String> {
modules::handle(module_name, context).map(|m| m.to_string())
}
pub fn timings(args: Properties) {
let context = Context::new(args, Target::Main);
struct ModuleTiming {
name: String,
name_len: usize,
value: String,
duration: Duration,
duration_len: usize,
}
let mut modules = compute_modules(&context)
.iter()
.filter(|module| !module.is_empty() || module.duration.as_millis() > 0)
.map(|module| ModuleTiming {
name: String::from(module.get_name().as_str()),
name_len: module.get_name().width_graphemes(),
value: nu_ansi_term::AnsiStrings(&module.ansi_strings())
.to_string()
.replace('\n', "\\n"),
duration: module.duration,
duration_len: format_duration(&module.duration).width_graphemes(),
})
.collect::<Vec<ModuleTiming>>();
modules.sort_by(|a, b| b.duration.cmp(&a.duration));
let max_name_width = modules.iter().map(|i| i.name_len).max().unwrap_or(0);
let max_duration_width = modules.iter().map(|i| i.duration_len).max().unwrap_or(0);
println!("\n Here are the timings of modules in your prompt (>=1ms or output):");
// for now we do not expect a wrap around at the end... famous last words
// Overall a line looks like this: " {module name} - {duration} - "{module value}"".
for timing in &modules {
println!(
" {}{} - {}{} - \"{}\"",
timing.name,
" ".repeat(max_name_width - (timing.name_len)),
" ".repeat(max_duration_width - (timing.duration_len)),
format_duration(&timing.duration),
timing.value
);
}
}
pub fn explain(args: Properties) {
let context = Context::new(args, Target::Main);
struct ModuleInfo {
value: String,
value_len: usize,
desc: String,
duration: String,
}
static DONT_PRINT: &[&str] = &["line_break"];
let modules = compute_modules(&context)
.into_iter()
.filter(|module| !DONT_PRINT.contains(&module.get_name().as_str()))
// this contains empty modules which should not print
.filter(|module| !module.is_empty())
.map(|module| {
let value = module.get_segments().join("");
ModuleInfo {
value: nu_ansi_term::AnsiStrings(&module.ansi_strings()).to_string(),
value_len: value.width_graphemes()
+ format_duration(&module.duration).width_graphemes(),
desc: module.get_description().clone(),
duration: format_duration(&module.duration),
}
})
.collect::<Vec<ModuleInfo>>();
let max_module_width = modules.iter().map(|i| i.value_len).max().unwrap_or(0);
// In addition to the module width itself there are also 11 padding characters in each line.
// Overall a line looks like this: " "{module value}" ({xxxms}) - {description}".
const PADDING_WIDTH: usize = 11;
let desc_width = terminal_size()
.map(|(w, _)| w.0 as usize)
// Add padding length to module length to avoid text overflow. This line also assures desc_width >= 0.
.map(|width| width - std::cmp::min(width, max_module_width + PADDING_WIDTH));
println!("\n Here's a breakdown of your prompt:");
for info in modules {
if let Some(desc_width) = desc_width {
// Custom Textwrapping!
let mut current_pos = 0;
let mut escaping = false;
// Print info
print!(
" \"{}\" ({}){} - ",
info.value,
info.duration,
" ".repeat(max_module_width - (info.value_len))
);
for g in info.desc.graphemes(true) {
// Handle ANSI escape sequences
if g == "\x1B" {
escaping = true;
}
if escaping {
print!("{g}");
escaping = !(("a"..="z").contains(&g) || ("A"..="Z").contains(&g));
continue;
}
// Handle normal wrapping
current_pos += Grapheme(g).width();
// Wrap when hitting max width or newline
if g == "\n" || current_pos > desc_width {
// trim spaces on linebreak
if g == " " && desc_width > 1 {
continue;
}
print!("\n{}", " ".repeat(max_module_width + PADDING_WIDTH));
if g == "\n" {
current_pos = 0;
continue;
}
current_pos = 1;
}
print!("{g}");
}
println!();
} else {
println!(
" {}{} - {}",
info.value,
" ".repeat(max_module_width - info.value_len),
info.desc,
);
}
}
}
fn compute_modules<'a>(context: &'a Context) -> Vec<Module<'a>> {
let mut prompt_order: Vec<Module<'a>> = Vec::new();
let (_formatter, modules) = load_formatter_and_modules(context);
for module in &modules {
// Manually add all modules if `$all` is encountered
if module == "all" {
for module in all_modules_uniq(&modules) {
let modules = handle_module(&module, context, &modules);
prompt_order.extend(modules);
}
} else {
let modules = handle_module(module, context, &modules);
prompt_order.extend(modules);
}
}
prompt_order
}
fn handle_module<'a>(
module: &str,
context: &'a Context,
module_list: &BTreeSet<String>,
) -> Vec<Module<'a>> {
let mut modules: Vec<Module> = Vec::new();
if ALL_MODULES.contains(&module) {
// Write out a module if it isn't disabled
if !context.is_module_disabled_in_config(module) {
modules.extend(modules::handle(module, context));
}
} else if module.starts_with("custom.") || module.starts_with("env_var.") {
// custom.<name> and env_var.<name> are special cases and handle disabled modules themselves
modules.extend(modules::handle(module, context));
} else if matches!(module, "custom" | "env_var") {
// env var is a spacial case and may contain a top-level module definition
if module == "env_var" {
modules.extend(modules::handle(module, context));
}
// Write out all custom modules, except for those that are explicitly set
modules.extend(
context
.config
.get_config(&[module])
.and_then(|config| config.as_table().map(toml::map::Map::iter))
.into_iter()
.flatten()
.collect::<Vec<_>>()
.par_iter()
.filter_map(|(child, config)| {
// Some env var keys may be part of a top-level module definition
if module == "env_var" && !config.is_table() {
None
} else if should_add_implicit_module(module, child, config, module_list) {
Some(modules::handle(&format!("{module}.{child}"), context))
} else {
None
}
})
.flatten()
.collect::<Vec<Module>>(),
);
} else {
log::debug!(
"Expected top level format to contain value from {ALL_MODULES:?}. Instead received {module}",
);
}
modules
}
fn should_add_implicit_module(
parent_module: &str,
child_module: &str,
config: &toml::Value,
module_list: &BTreeSet<String>,
) -> bool {
let explicit_module_name = format!("{parent_module}.{child_module}");
let is_explicitly_specified = module_list.contains(&explicit_module_name);
if is_explicitly_specified {
// The module is already specified explicitly, so we skip it
return false;
}
let false_value = toml::Value::Boolean(false);
!config
.get("disabled")
.unwrap_or(&false_value)
.as_bool()
.unwrap_or(false)
}
pub fn format_duration(duration: &Duration) -> String {
let milis = duration.as_millis();
if milis == 0 {
"<1ms".to_string()
} else {
format!("{:?}ms", &milis)
}
}
/// Return the modules from $all that are not already in the list
fn all_modules_uniq(module_list: &BTreeSet<String>) -> Vec<String> {
let mut prompt_order: Vec<String> = Vec::new();
for module in PROMPT_ORDER {
if !module_list.contains(*module) {
prompt_order.push(String::from(*module));
}
}
prompt_order
}
/// Load the correct formatter for the context (ie left prompt or right prompt)
/// and the list of all modules used in a format string
fn load_formatter_and_modules<'a>(context: &'a Context) -> (StringFormatter<'a>, BTreeSet<String>) {
let config = &context.root_config;
if context.target == Target::Continuation {
let cf = &config.continuation_prompt;
let formatter = StringFormatter::new(cf);
return match formatter {
Ok(f) => {
let modules = f.get_variables().into_iter().collect();
(f, modules)
}
Err(e) => {
log::error!("Error parsing continuation prompt: {e}");
(StringFormatter::raw(">"), BTreeSet::new())
}
};
}
let (left_format_str, right_format_str): (&str, &str) = match context.target {
Target::Main | Target::Right => (&config.format, &config.right_format),
Target::Profile(ref name) => {
if let Some(lf) = config.profiles.get(name) {
(lf, "")
} else {
log::error!("Profile {name:?} not found");
return (StringFormatter::raw(">"), BTreeSet::new());
}
}
Target::Continuation => unreachable!("Continuation prompt should have been handled above"),
};
let lf = StringFormatter::new(left_format_str);
let rf = StringFormatter::new(right_format_str);
if let Err(ref e) = lf {
let name = if let Target::Profile(ref profile_name) = context.target {
format!("profile.{profile_name}")
} else {
"format".to_string()
};
log::error!("Error parsing {name:?}: {e}");
}
if let Err(ref e) = rf {
log::error!("Error parsing right_format: {e}");
}
let modules = [&lf, &rf]
.into_iter()
.flatten()
.flat_map(VariableHolder::get_variables)
.collect();
let main_formatter = match context.target {
Target::Main | Target::Profile(_) => lf,
Target::Right => rf,
Target::Continuation => unreachable!("Continuation prompt should have been handled above"),
};
match main_formatter {
Ok(f) => (f, modules),
_ => (StringFormatter::raw(">"), BTreeSet::new()),
}
}
#[cfg(feature = "config-schema")]
pub fn print_schema() {
let schema = schemars::schema_for!(crate::configs::FullConfig);
println!("{}", serde_json::to_string_pretty(&schema).unwrap());
}
#[derive(Clone, Debug)]
pub struct Preset(pub &'static str);
impl ValueEnum for Preset {
fn value_variants<'a>() -> &'a [Self] {
shadow::get_preset_list()
}
fn to_possible_value(&self) -> Option<PossibleValue> {
Some(PossibleValue::new(self.0))
}
}
pub fn preset_command(name: Option<Preset>, output: Option<PathBuf>, list: bool) {
if list {
println!("{}", preset_list());
return;
}
let variant = name.expect("name argument must be specified");
let content = shadow::get_preset_content(variant.0);
if let Some(output) = output {
if let Err(err) = std::fs::write(output, content) {
eprintln!("Error writing preset to file: {err}");
std::process::exit(1);
}
} else if let Err(err) = std::io::stdout().write_all(content) {
eprintln!("Error writing preset to stdout: {err}");
std::process::exit(1);
}
}
fn preset_list() -> String {
Preset::value_variants()
.iter()
.fold(String::new(), |mut output, b| {
let _ = writeln!(output, "{}", b.0);
output
})
}
#[cfg(test)]
mod test {
use super::*;
use crate::test::default_context;
use crate::utils;
const NULL_DEVICE: &str = if cfg!(windows) { "NUL" } else { "/dev/null" };
#[test]
fn main_prompt() {
let mut context = default_context().set_config(toml::toml! {
add_newline=false
format="$character"
[character]
format=">\n>"
});
context.target = Target::Main;
let expected = String::from(">\n>");
let actual = get_prompt(&context);
assert_eq!(expected, actual);
}
#[test]
fn right_prompt() {
let mut context = default_context().set_config(toml::toml! {
right_format="$character"
[character]
format=">\n>"
});
context.target = Target::Right;
let expected = String::from(">>"); // should strip new lines
let actual = get_prompt(&context);
assert_eq!(expected, actual);
}
#[test]
fn prompt_with_all() -> io::Result<()> {
let mut context = default_context().set_config(toml::toml! {
add_newline = false
right_format= "$directory$line_break"
format="$all"
[character]
format=">"
});
context.env.insert("HOME", NULL_DEVICE.to_string());
let dir = tempfile::tempdir().unwrap();
context.current_dir = dir.path().to_path_buf();
let expected = String::from(">");
let actual = get_prompt(&context);
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn rprompt_with_all() -> io::Result<()> {
let mut context = default_context().set_config(toml::toml! {
format= "$directory$line_break"
right_format="$all"
[character]
format=">"
});
context.env.insert("HOME", NULL_DEVICE.to_string());
let dir = tempfile::tempdir().unwrap();
context.current_dir = dir.path().to_path_buf();
context.target = Target::Right;
let expected = String::from(">");
let actual = get_prompt(&context);
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn custom_prompt() {
let mut context = default_context().set_config(toml::toml! {
add_newline = false
[profiles]
test="0_0$character"
[character]
format=">>"
});
context.target = Target::Profile("test".to_string());
let expected = String::from("0_0>>");
let actual = get_prompt(&context);
assert_eq!(expected, actual);
}
#[test]
fn custom_prompt_fallback() {
let mut context = default_context().set_config(toml::toml! {
add_newline=false
[profiles]
test="0_0$character"
[character]
format=">>"
});
context.target = Target::Profile("wrong_prompt".to_string());
let expected = String::from(">");
let actual = get_prompt(&context);
assert_eq!(expected, actual);
}
#[test]
fn continuation_prompt() {
let mut context = default_context().set_config(toml::toml! {
continuation_prompt="><>"
});
context.target = Target::Continuation;
let expected = String::from("><>");
let actual = get_prompt(&context);
assert_eq!(expected, actual);
}
#[test]
fn preset_list_returns_one_or_more_items() {
assert!(preset_list().lines().count() > 0);
}
#[test]
fn preset_command_does_not_panic_on_correct_inputs() {
preset_command(None, None, true);
for v in Preset::value_variants() {
preset_command(Some(v.clone()), None, false);
}
}
#[test]
fn preset_command_output_to_file() -> std::io::Result<()> {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("preset.toml");
preset_command(Some(Preset("nerd-font-symbols")), Some(path.clone()), false);
let actual = utils::read_file(&path)?;
let expected = include_str!("../docs/public/presets/toml/nerd-font-symbols.toml");
assert_eq!(actual, expected);
dir.close()
}
#[test]
#[cfg(feature = "config-schema")]
fn print_schema_does_not_panic() {
print_schema();
}
#[test]
fn custom_expands() -> std::io::Result<()> {
let dir = tempfile::tempdir()?;
let mut context = default_context().set_config(toml::toml! {
format="$custom"
[custom.a]
when=true
format="a"
[custom.b]
when=true
format="b"
});
context.current_dir = dir.path().to_path_buf();
let expected = String::from("\nab");
let actual = get_prompt(&context);
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn env_expands() {
let mut context = default_context().set_config(toml::toml! {
format="$env_var"
[env_var]
format="$env_value"
variable = "a"
[env_var.b]
format="$env_value"
[env_var.c]
format="$env_value"
});
context.env.insert("a", "a".to_string());
context.env.insert("b", "b".to_string());
context.env.insert("c", "c".to_string());
let expected = String::from("\nabc");
let actual = get_prompt(&context);
assert_eq!(expected, actual);
}
#[test]
fn custom_mixed() -> std::io::Result<()> {
let dir = tempfile::tempdir()?;
let mut context = default_context().set_config(toml::toml! {
format="${custom.c}$custom${custom.b}"
[custom.a]
when=true
format="a"
[custom.b]
when=true
format="b"
[custom.c]
when=true
format="c"
});
context.current_dir = dir.path().to_path_buf();
let expected = String::from("\ncab");
let actual = get_prompt(&context);
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn env_mixed() {
let mut context = default_context().set_config(toml::toml! {
format="${env_var.c}$env_var${env_var.b}"
[env_var]
format="$env_value"
variable = "d"
[env_var.a]
format="$env_value"
[env_var.b]
format="$env_value"
[env_var.c]
format="$env_value"
});
context.env.insert("a", "a".to_string());
context.env.insert("b", "b".to_string());
context.env.insert("c", "c".to_string());
context.env.insert("d", "d".to_string());
let expected = String::from("\ncdab");
let actual = get_prompt(&context);
assert_eq!(expected, actual);
}
#[test]
fn custom_subset() -> std::io::Result<()> {
let dir = tempfile::tempdir()?;
let mut context = default_context().set_config(toml::toml! {
format="${custom.b}"
[custom.a]
when=true
format="a"
[custom.b]
when=true
format="b"
});
context.current_dir = dir.path().to_path_buf();
let expected = String::from("\nb");
let actual = get_prompt(&context);
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn custom_missing() -> std::io::Result<()> {
let dir = tempfile::tempdir()?;
let mut context = default_context().set_config(toml::toml! {
format="${custom.b}"
[custom.a]
when=true
format="a"
});
context.current_dir = dir.path().to_path_buf();
let expected = String::from("\n");
let actual = get_prompt(&context);
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/formatter/version.rs | src/formatter/version.rs | use super::StringFormatter;
use super::string_formatter::StringFormatterError;
use crate::segment;
use std::ops::Deref;
use std::sync::LazyLock;
use versions::Versioning;
pub struct VersionFormatter<'a> {
formatter: StringFormatter<'a>,
}
impl<'a> VersionFormatter<'a> {
/// Creates an instance of a `VersionFormatter` from a format string
///
/// Like the `StringFormatter`, this will throw an error when the string isn't
/// parseable.
pub fn new(format: &'a str) -> Result<Self, StringFormatterError> {
let formatter = StringFormatter::new(format)?;
Ok(Self { formatter })
}
/// Format version string using provided format
pub fn format_version(
version: &'a str,
format: &'a str,
) -> Result<String, StringFormatterError> {
Self::new(format).and_then(|formatter| formatter.format(version))
}
/// Formats a version structure into a readable string
pub fn format(self, version: &'a str) -> Result<String, StringFormatterError> {
let parsed = LazyLock::new(|| Versioning::new(version));
let formatted = self
.formatter
.map(|variable| match variable {
"raw" => Some(Ok(version.to_string())),
"major" => match parsed.deref().as_ref() {
Some(Versioning::Ideal(v)) => Some(Ok(v.major.to_string())),
Some(Versioning::General(v)) => Some(Ok(v.nth_lenient(0)?.to_string())),
_ => None,
},
"minor" => match parsed.deref().as_ref() {
Some(Versioning::Ideal(v)) => Some(Ok(v.minor.to_string())),
Some(Versioning::General(v)) => Some(Ok(v.nth_lenient(1)?.to_string())),
_ => None,
},
"patch" => match parsed.deref().as_ref() {
Some(Versioning::Ideal(v)) => Some(Ok(v.patch.to_string())),
Some(Versioning::General(v)) => Some(Ok(v.nth_lenient(2)?.to_string())),
_ => None,
},
_ => None,
})
.parse(None, None);
formatted.map(|segments| {
segments
.iter()
.map(segment::Segment::value)
.collect::<String>()
})
}
pub fn format_module_version(
module_name: &str,
version: &str,
version_format: &str,
) -> Option<String> {
match VersionFormatter::format_version(version, version_format) {
Ok(formatted) => Some(formatted),
Err(error) => {
log::warn!("Error formatting `{module_name}` version:\n{error}");
Some(format!("v{version}"))
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const VERSION_FORMAT: &str = "major:${major} minor:${minor} patch:${patch} raw:${raw}";
#[test]
fn test_semver_full() {
assert_eq!(
VersionFormatter::format_version("1.2.3", VERSION_FORMAT),
Ok("major:1 minor:2 patch:3 raw:1.2.3".to_string())
);
}
#[test]
fn test_semver_partial() {
assert_eq!(
VersionFormatter::format_version("1.2", VERSION_FORMAT),
Ok("major:1 minor:2 patch: raw:1.2".to_string())
);
}
#[test]
fn test_general() {
assert_eq!(
VersionFormatter::format_version("1.2-a.3", VERSION_FORMAT),
Ok("major:1 minor:2 patch: raw:1.2-a.3".to_string())
);
}
#[test]
fn test_dummy() {
assert_eq!(
VersionFormatter::format_version("dummy version", VERSION_FORMAT),
Ok("major: minor: patch: raw:dummy version".to_string())
);
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/formatter/parser.rs | src/formatter/parser.rs | // Can't rename internal Pest names
#![allow(clippy::upper_case_acronyms)]
use pest::{Parser, error::Error, iterators::Pair};
use pest_derive::*;
use super::model::*;
#[derive(Parser)]
#[grammar = "formatter/spec.pest"]
struct IdentParser;
fn parse_value(value: Pair<Rule>) -> FormatElement {
match value.as_rule() {
Rule::text => FormatElement::Text(parse_text(value).into()),
Rule::variable => FormatElement::Variable(parse_variable(value).into()),
Rule::textgroup => FormatElement::TextGroup(parse_textgroup(value)),
Rule::conditional => {
FormatElement::Conditional(parse_format(value.into_inner().next().unwrap()))
}
_ => unreachable!(),
}
}
fn parse_textgroup(textgroup: Pair<Rule>) -> TextGroup {
let mut inner_rules = textgroup.into_inner();
let format = inner_rules.next().unwrap();
let style = inner_rules.next().unwrap();
TextGroup {
format: parse_format(format),
style: parse_style(style),
}
}
fn parse_variable(variable: Pair<'_, Rule>) -> &str {
variable.into_inner().next().unwrap().as_str()
}
fn parse_text(text: Pair<Rule>) -> String {
text.into_inner()
.flat_map(|pair| pair.as_str().chars())
.collect()
}
fn parse_format(format: Pair<Rule>) -> Vec<FormatElement> {
format.into_inner().map(parse_value).collect()
}
fn parse_style(style: Pair<Rule>) -> Vec<StyleElement> {
style
.into_inner()
.map(|pair| match pair.as_rule() {
Rule::string => StyleElement::Text(pair.as_str().into()),
Rule::variable => StyleElement::Variable(parse_variable(pair).into()),
_ => unreachable!(),
})
.collect()
}
pub fn parse(format: &str) -> Result<Vec<FormatElement<'_>>, Box<Error<Rule>>> {
IdentParser::parse(Rule::expression, format)
.map(|pairs| {
pairs
.take_while(|pair| pair.as_rule() != Rule::EOI)
.map(parse_value)
.collect()
})
.map_err(Box::new)
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/formatter/model.rs | src/formatter/model.rs | use std::borrow::Cow;
use std::collections::BTreeSet;
/// Type that holds a number of variables of type `T`
pub trait VariableHolder<T> {
fn get_variables(&self) -> BTreeSet<T>;
}
/// Type that holds a number of style variables of type `T`
pub trait StyleVariableHolder<T> {
fn get_style_variables(&self) -> BTreeSet<T>;
}
#[derive(Clone)]
pub struct TextGroup<'a> {
pub format: Vec<FormatElement<'a>>,
pub style: Vec<StyleElement<'a>>,
}
#[derive(Clone)]
pub enum FormatElement<'a> {
Text(Cow<'a, str>),
Variable(Cow<'a, str>),
TextGroup(TextGroup<'a>),
Conditional(Vec<Self>),
}
#[derive(Clone)]
pub enum StyleElement<'a> {
Text(Cow<'a, str>),
Variable(Cow<'a, str>),
}
impl<'a> VariableHolder<Cow<'a, str>> for FormatElement<'a> {
fn get_variables(&self) -> BTreeSet<Cow<'a, str>> {
match self {
Self::Variable(var) => {
let mut variables = BTreeSet::new();
variables.insert(var.clone());
variables
}
Self::TextGroup(textgroup) => textgroup.format.get_variables(),
Self::Conditional(format) => format.get_variables(),
_ => Default::default(),
}
}
}
impl<'a> VariableHolder<Cow<'a, str>> for Vec<FormatElement<'a>> {
fn get_variables(&self) -> BTreeSet<Cow<'a, str>> {
self.iter().fold(BTreeSet::new(), |mut acc, el| {
acc.extend(el.get_variables());
acc
})
}
}
impl<'a> VariableHolder<Cow<'a, str>> for &[FormatElement<'a>] {
fn get_variables(&self) -> BTreeSet<Cow<'a, str>> {
self.iter().fold(BTreeSet::new(), |mut acc, el| {
acc.extend(el.get_variables());
acc
})
}
}
impl<'a> StyleVariableHolder<Cow<'a, str>> for StyleElement<'a> {
fn get_style_variables(&self) -> BTreeSet<Cow<'a, str>> {
match self {
Self::Variable(var) => {
let mut variables = BTreeSet::new();
variables.insert(var.clone());
variables
}
_ => Default::default(),
}
}
}
impl<'a> StyleVariableHolder<Cow<'a, str>> for Vec<StyleElement<'a>> {
fn get_style_variables(&self) -> BTreeSet<Cow<'a, str>> {
self.iter().fold(BTreeSet::new(), |mut acc, el| {
acc.extend(el.get_style_variables());
acc
})
}
}
impl<'a> StyleVariableHolder<Cow<'a, str>> for Vec<FormatElement<'a>> {
fn get_style_variables(&self) -> BTreeSet<Cow<'a, str>> {
self.iter().fold(BTreeSet::new(), |mut acc, el| match el {
FormatElement::TextGroup(textgroup) => {
acc.extend(textgroup.style.get_style_variables());
acc.extend(textgroup.format.get_style_variables());
acc
}
FormatElement::Conditional(format) => {
acc.extend(format.get_style_variables());
acc
}
_ => acc,
})
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/formatter/mod.rs | src/formatter/mod.rs | pub mod model;
mod parser;
pub mod string_formatter;
mod version;
pub use model::{StyleVariableHolder, VariableHolder};
pub use string_formatter::StringFormatter;
pub use version::VersionFormatter;
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/formatter/string_formatter.rs | src/formatter/string_formatter.rs | use pest::error::Error as PestError;
use rayon::prelude::*;
use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet};
use std::error::Error;
use std::fmt;
use crate::config::{Style, parse_style_string};
use crate::context::{Context, Shell};
use crate::segment::Segment;
use super::model::*;
use super::parser::{Rule, parse};
#[derive(Clone)]
enum VariableValue<'a> {
Plain(Cow<'a, str>),
NoEscapingPlain(Cow<'a, str>),
Styled(Vec<Segment>),
Meta(Vec<FormatElement<'a>>),
}
impl Default for VariableValue<'_> {
fn default() -> Self {
Self::Plain(Cow::Borrowed(""))
}
}
type VariableMapType<'a> =
BTreeMap<String, Option<Result<VariableValue<'a>, StringFormatterError>>>;
type StyleVariableMapType<'a> =
BTreeMap<String, Option<Result<Cow<'a, str>, StringFormatterError>>>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StringFormatterError {
Custom(String),
Parse(Box<PestError<Rule>>),
}
impl fmt::Display for StringFormatterError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Custom(error) => write!(f, "{error}"),
Self::Parse(error) => write!(f, "{error}"),
}
}
}
impl Error for StringFormatterError {}
impl From<String> for StringFormatterError {
fn from(error: String) -> Self {
Self::Custom(error)
}
}
pub struct StringFormatter<'a> {
format: Vec<FormatElement<'a>>,
variables: VariableMapType<'a>,
style_variables: StyleVariableMapType<'a>,
}
impl<'a> StringFormatter<'a> {
/// Creates an instance of `StringFormatter` from a format string
///
/// This method will throw an Error when the given format string fails to parse.
pub fn new(format: &'a str) -> Result<Self, StringFormatterError> {
let format = parse(format).map_err(StringFormatterError::Parse)?;
// Cache all variables
let variables = format
.get_variables()
.into_iter()
.map(|key| (key.to_string(), None))
.collect::<VariableMapType>();
let style_variables = format
.get_style_variables()
.into_iter()
.map(|key| (key.to_string(), None))
.collect::<StyleVariableMapType>();
Ok(Self {
format,
variables,
style_variables,
})
}
/// A `StringFormatter` that does no formatting, parse just returns the raw text
pub fn raw(text: &'a str) -> Self {
Self {
format: vec![FormatElement::Text(text.into())],
variables: BTreeMap::new(),
style_variables: BTreeMap::new(),
}
}
/// Maps variable name to its value
///
/// You should provide a function or closure that accepts the variable name `name: &str` as a
/// parameter and returns the one of the following values:
///
/// - `None`: This variable will be reserved for further mappers. If it is `None` when
/// `self.parse()` is called, it will be dropped.
///
/// - `Some(Err(StringFormatterError))`: This variable will throws `StringFormatterError` when
/// `self.parse()` is called. Return this if some fatal error occurred and the format string
/// should not be rendered.
///
/// - `Some(Ok(_))`: The value of this variable will be displayed in the format string.
///
#[must_use]
pub fn map<T, M>(mut self, mapper: M) -> Self
where
T: Into<Cow<'a, str>>,
M: Fn(&str) -> Option<Result<T, StringFormatterError>> + Sync,
{
self.variables
.par_iter_mut()
.filter(|(_, value)| value.is_none())
.for_each(|(key, value)| {
*value = mapper(key).map(|var| var.map(|var| VariableValue::Plain(var.into())));
});
self
}
/// Maps variable name into a value which is wrapped to prevent escaping later
///
/// This should be used for variables that should not be escaped before inclusion in the prompt
///
/// See `StringFormatter::map` for description on the parameters.
///
#[must_use]
pub fn map_no_escaping<T, M>(mut self, mapper: M) -> Self
where
T: Into<Cow<'a, str>>,
M: Fn(&str) -> Option<Result<T, StringFormatterError>> + Sync,
{
self.variables
.par_iter_mut()
.filter(|(_, value)| value.is_none())
.for_each(|(key, value)| {
*value = mapper(key)
.map(|var| var.map(|var| VariableValue::NoEscapingPlain(var.into())));
});
self
}
/// Maps a meta-variable to a format string containing other variables.
///
/// This function should be called **before** other map methods so that variables found in
/// the format strings of meta-variables can be cached properly.
///
/// See `StringFormatter::map` for description on the parameters.
#[must_use]
pub fn map_meta<M>(mut self, mapper: M) -> Self
where
M: Fn(&str, &BTreeSet<String>) -> Option<&'a str> + Sync,
{
let variables = self.get_variables();
let (variables, style_variables) = self
.variables
.iter_mut()
.filter(|(_, value)| value.is_none())
.fold(
(VariableMapType::new(), StyleVariableMapType::new()),
|(mut v, mut sv), (key, value)| {
*value = mapper(key, &variables).map(|format| {
StringFormatter::new(format).map(|formatter| {
let StringFormatter {
format,
mut variables,
mut style_variables,
} = formatter;
// Add variables in meta variables to self
v.append(&mut variables);
sv.append(&mut style_variables);
VariableValue::Meta(format)
})
});
(v, sv)
},
);
self.variables.extend(variables);
self.style_variables.extend(style_variables);
self
}
/// Maps variable name to an array of segments
///
/// See `StringFormatter::map` for description on the parameters.
#[must_use]
pub fn map_variables_to_segments<M>(mut self, mapper: M) -> Self
where
M: Fn(&str) -> Option<Result<Vec<Segment>, StringFormatterError>> + Sync,
{
self.variables
.par_iter_mut()
.filter(|(_, value)| value.is_none())
.for_each(|(key, value)| {
*value = mapper(key).map(|var| var.map(VariableValue::Styled));
});
self
}
/// Maps variable name in a style string to its value
///
/// See `StringFormatter::map` for description on the parameters.
#[must_use]
pub fn map_style<T, M>(mut self, mapper: M) -> Self
where
T: Into<Cow<'a, str>>,
M: Fn(&str) -> Option<Result<T, StringFormatterError>> + Sync,
{
self.style_variables
.par_iter_mut()
.filter(|(_, value)| value.is_none())
.for_each(|(key, value)| {
*value = mapper(key).map(|var| var.map(Into::into));
});
self
}
/// Parse the format string and consume self.
///
/// This method will throw an Error in the following conditions:
///
/// - Format string in meta variables fails to parse
/// - Variable mapper returns an error.
pub fn parse(
self,
default_style: Option<Style>,
context: Option<&Context>,
) -> Result<Vec<Segment>, StringFormatterError> {
fn parse_textgroup<'a>(
textgroup: TextGroup<'a>,
variables: &'a VariableMapType<'a>,
style_variables: &'a StyleVariableMapType<'a>,
context: Option<&Context>,
) -> Result<Vec<Segment>, StringFormatterError> {
let style = parse_style(textgroup.style, style_variables, context);
parse_format(
textgroup.format,
style.transpose()?,
variables,
style_variables,
context,
)
}
fn parse_style<'a>(
style: Vec<StyleElement>,
variables: &'a StyleVariableMapType<'a>,
context: Option<&Context>,
) -> Option<Result<Style, StringFormatterError>> {
let style_strings = style
.into_iter()
.map(|style| match style {
StyleElement::Text(text) => Ok(text),
StyleElement::Variable(name) => {
let variable = variables.get(name.as_ref()).unwrap_or(&None);
match variable {
Some(style_string) => style_string.clone(),
None => Ok("".into()),
}
}
})
.collect::<Result<Vec<Cow<str>>, StringFormatterError>>();
style_strings
.map(|style_strings| {
let style_string: String =
style_strings.iter().flat_map(|s| s.chars()).collect();
parse_style_string(&style_string, context)
})
.transpose()
}
fn parse_format<'a>(
format: Vec<FormatElement<'a>>,
style: Option<Style>,
variables: &'a VariableMapType<'a>,
style_variables: &'a StyleVariableMapType<'a>,
context: Option<&Context>,
) -> Result<Vec<Segment>, StringFormatterError> {
let results: Result<Vec<Vec<Segment>>, StringFormatterError> = format
.into_iter()
.map(|el| {
match el {
FormatElement::Text(text) => Ok(Segment::from_text(
style,
shell_prompt_escape(
text,
match context {
None => Shell::Unknown,
Some(c) => c.shell,
},
),
)),
FormatElement::TextGroup(textgroup) => {
parse_textgroup(textgroup, variables, style_variables, context)
}
FormatElement::Variable(name) => variables
.get(name.as_ref())
.expect("Uncached variable found")
.as_ref()
.map(|segments| match segments.clone()? {
VariableValue::Styled(segments) => Ok(segments
.into_iter()
.map(|mut segment| {
// Derive upper style if the style of segments are none.
segment.set_style_if_empty(style);
segment
})
.collect()),
VariableValue::Plain(text) => Ok(Segment::from_text(
style,
shell_prompt_escape(
text,
match context {
None => Shell::Unknown,
Some(c) => c.shell,
},
),
)),
VariableValue::NoEscapingPlain(text) => {
Ok(Segment::from_text(style, text))
}
VariableValue::Meta(format) => {
let formatter = StringFormatter {
format,
variables: clone_without_meta(variables),
style_variables: style_variables.clone(),
};
formatter.parse(style, context)
}
})
.unwrap_or_else(|| Ok(Vec::new())),
FormatElement::Conditional(format) => {
// Show the conditional format string if all the variables inside are not
// none or empty string.
fn should_show_elements<'a>(
format_elements: &[FormatElement],
variables: &'a VariableMapType<'a>,
) -> bool {
format_elements.get_variables().iter().any(|var| {
variables
.get(var.as_ref())
// false if can't find the variable in format string
.is_some_and(|map_result| {
let map_result = map_result.as_ref();
map_result
.and_then(|result| result.as_ref().ok())
// false if the variable is None or Err, or a meta variable
// that shouldn't show
.is_some_and(|result| match result {
// If the variable is a meta variable, also
// check the format string inside it.
VariableValue::Meta(meta_elements) => {
let meta_variables =
clone_without_meta(variables);
should_show_elements(
meta_elements,
&meta_variables,
)
}
VariableValue::Plain(plain_value) => {
!plain_value.is_empty()
}
VariableValue::NoEscapingPlain(
no_escaping_plain_value,
) => !no_escaping_plain_value.is_empty(),
VariableValue::Styled(segments) => segments
.iter()
.any(|x| !x.value().is_empty()),
})
})
})
}
let should_show: bool = should_show_elements(&format, variables);
if should_show {
parse_format(format, style, variables, style_variables, context)
} else {
Ok(Vec::new())
}
}
}
})
.collect();
Ok(results?.into_iter().flatten().collect())
}
parse_format(
self.format,
default_style,
&self.variables,
&self.style_variables,
context,
)
}
}
impl VariableHolder<String> for StringFormatter<'_> {
fn get_variables(&self) -> BTreeSet<String> {
self.variables.keys().cloned().collect()
}
}
impl StyleVariableHolder<String> for StringFormatter<'_> {
fn get_style_variables(&self) -> BTreeSet<String> {
self.style_variables.keys().cloned().collect()
}
}
fn clone_without_meta<'a>(variables: &VariableMapType<'a>) -> VariableMapType<'a> {
variables
.iter()
.map(|(key, value)| {
let value = match value {
Some(Ok(value)) => match value {
VariableValue::Meta(_) => None,
other => Some(Ok(other.clone())),
},
Some(Err(e)) => Some(Err(e.clone())),
None => None,
};
(key.clone(), value)
})
.collect()
}
/// Escape interpretable characters for the shell prompt
pub fn shell_prompt_escape<T>(text: T, shell: Shell) -> String
where
T: Into<String>,
{
// Handle other interpretable characters
match shell {
// Bash might interpret backslashes, backticks and $
// see #658 for more details
Shell::Bash => text
.into()
.replace('\\', r"\\")
.replace('$', r"\$")
.replace('`', r"\`"),
Shell::Zsh => {
// % is an escape in zsh, see PROMPT in `man zshmisc`
text.into().replace('%', "%%")
}
_ => text.into(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use nu_ansi_term::Color;
// match_next(result: IterMut<Segment>, value, style)
macro_rules! match_next {
($iter:ident, $value:literal, $($style:tt)+) => {
let _next = $iter.next().unwrap();
assert_eq!(_next.value(), $value);
assert_eq!(_next.style(), $($style)+);
}
}
fn empty_mapper(_: &str) -> Option<Result<String, StringFormatterError>> {
None
}
#[test]
fn test_default_style() {
const FORMAT_STR: &str = "text";
let style = Some(Color::Red.bold());
let formatter = StringFormatter::new(FORMAT_STR).unwrap().map(empty_mapper);
let result = formatter.parse(style.map(Into::into), None).unwrap();
let mut result_iter = result.iter();
match_next!(result_iter, "text", style);
}
#[test]
fn test_textgroup_text_only() {
const FORMAT_STR: &str = "[text](red bold)";
let formatter = StringFormatter::new(FORMAT_STR).unwrap().map(empty_mapper);
let result = formatter.parse(None, None).unwrap();
let mut result_iter = result.iter();
match_next!(result_iter, "text", Some(Color::Red.bold()));
}
#[test]
fn test_variable_only() {
const FORMAT_STR: &str = "$var1";
let formatter = StringFormatter::new(FORMAT_STR)
.unwrap()
.map(|variable| match variable {
"var1" => Some(Ok("text1".to_owned())),
_ => None,
});
let result = formatter.parse(None, None).unwrap();
let mut result_iter = result.iter();
match_next!(result_iter, "text1", None);
}
#[test]
fn test_variable_in_style() {
const FORMAT_STR: &str = "[root]($style)";
let root_style = Some(Color::Red.bold());
let formatter = StringFormatter::new(FORMAT_STR)
.unwrap()
.map_style(|variable| match variable {
"style" => Some(Ok("red bold".to_owned())),
_ => None,
});
let result = formatter.parse(None, None).unwrap();
let mut result_iter = result.iter();
match_next!(result_iter, "root", root_style);
}
#[test]
fn test_scoped_variable() {
const FORMAT_STR: &str = "${env:PWD}";
let formatter = StringFormatter::new(FORMAT_STR)
.unwrap()
.map(|variable| Some(Ok(format!("${{{variable}}}"))));
let result = formatter.parse(None, None).unwrap();
let mut result_iter = result.iter();
match_next!(result_iter, "${env:PWD}", None);
}
#[test]
fn test_escaped_chars() {
const FORMAT_STR: &str = r"\\\[\$text\]\(red bold\)";
let formatter = StringFormatter::new(FORMAT_STR).unwrap().map(empty_mapper);
let result = formatter.parse(None, None).unwrap();
let mut result_iter = result.iter();
match_next!(result_iter, r"\[$text](red bold)", None);
}
#[test]
fn test_nested_textgroup() {
const FORMAT_STR: &str = "outer [middle [inner](blue)](red bold)";
let outer_style = Some(Color::Green.normal());
let middle_style = Some(Color::Red.bold());
let inner_style = Some(Color::Blue.normal());
let formatter = StringFormatter::new(FORMAT_STR).unwrap().map(empty_mapper);
let result = formatter.parse(outer_style.map(Into::into), None).unwrap();
let mut result_iter = result.iter();
match_next!(result_iter, "outer ", outer_style);
match_next!(result_iter, "middle ", middle_style);
match_next!(result_iter, "inner", inner_style);
}
#[test]
fn test_style_variable_nested() {
const STYLE_VAR_NAME: &str = "style";
let format_string = format!("[[text](${STYLE_VAR_NAME})](blue)");
let inner_style = Some(Color::Red.bold());
let formatter = StringFormatter::new(&format_string)
.unwrap()
.map_style(|variable| match variable {
STYLE_VAR_NAME => Some(Ok("red bold".to_owned())),
_ => None,
});
assert_eq!(
BTreeSet::from([STYLE_VAR_NAME.into()]),
formatter.get_style_variables()
);
let result = formatter.parse(None, None).unwrap();
let mut result_iter = result.iter();
match_next!(result_iter, "text", inner_style);
}
#[test]
fn test_styled_variable_as_text() {
const FORMAT_STR: &str = "[$var](red bold)";
let var_style = Some(Color::Red.bold());
let formatter = StringFormatter::new(FORMAT_STR)
.unwrap()
.map(|variable| match variable {
"var" => Some(Ok("text".to_owned())),
_ => None,
});
let result = formatter.parse(None, None).unwrap();
let mut result_iter = result.iter();
match_next!(result_iter, "text", var_style);
}
#[test]
fn test_styled_variable_as_segments() {
const FORMAT_STR: &str = "[$var](red bold)";
let var_style = Some(Color::Red.bold());
let styled_style = Some(Color::Green.italic());
let styled_no_modifier_style = Some(Color::Green.normal());
let mut segments: Vec<Segment> = Vec::new();
segments.extend(Segment::from_text(None, "styleless"));
segments.extend(Segment::from_text(styled_style.map(Into::into), "styled"));
segments.extend(Segment::from_text(
styled_no_modifier_style.map(Into::into),
"styled_no_modifier",
));
let formatter = StringFormatter::new(FORMAT_STR)
.unwrap()
.map_variables_to_segments(|variable| match variable {
"var" => Some(Ok(segments.clone())),
_ => None,
});
let result = formatter.parse(None, None).unwrap();
let mut result_iter = result.iter();
match_next!(result_iter, "styleless", var_style);
match_next!(result_iter, "styled", styled_style);
match_next!(result_iter, "styled_no_modifier", styled_no_modifier_style);
}
#[test]
fn test_meta_variable() {
const FORMAT_STR: &str = "$all";
const FORMAT_STR__ALL: &str = "$a$b";
let formatter = StringFormatter::new(FORMAT_STR)
.unwrap()
.map_meta(|var, _| match var {
"all" => Some(FORMAT_STR__ALL),
_ => None,
})
.map(|var| match var {
"a" => Some(Ok("$a")),
"b" => Some(Ok("$b")),
_ => None,
});
let result = formatter.parse(None, None).unwrap();
let mut result_iter = result.iter();
match_next!(result_iter, "$a", None);
match_next!(result_iter, "$b", None);
}
#[test]
fn test_multiple_mapper() {
const FORMAT_STR: &str = "$a$b$c";
let formatter = StringFormatter::new(FORMAT_STR)
.unwrap()
.map(|var| match var {
"a" => Some(Ok("$a")),
"b" => Some(Ok("$b")),
_ => None,
})
.map(|var| match var {
"b" => Some(Ok("$B")),
"c" => Some(Ok("$c")),
_ => None,
});
let result = formatter.parse(None, None).unwrap();
let mut result_iter = result.iter();
match_next!(result_iter, "$a", None);
match_next!(result_iter, "$b", None);
match_next!(result_iter, "$c", None);
}
#[test]
fn test_conditional() {
const FORMAT_STR: &str = "($some) should render but ($none) shouldn't";
let formatter = StringFormatter::new(FORMAT_STR)
.unwrap()
.map(|var| match var {
"some" => Some(Ok("$some")),
_ => None,
});
let result = formatter.parse(None, None).unwrap();
let mut result_iter = result.iter();
match_next!(result_iter, "$some", None);
match_next!(result_iter, " should render but ", None);
match_next!(result_iter, " shouldn't", None);
}
#[test]
fn test_empty() {
const FORMAT_STR: &str = "(@$empty)";
let formatter = StringFormatter::new(FORMAT_STR)
.unwrap()
.map(|var| match var {
"empty" => Some(Ok("")),
_ => None,
});
let result = formatter.parse(None, None).unwrap();
assert_eq!(result.len(), 0);
}
#[test]
fn test_styled_empty() {
const FORMAT_STR: &str = "[(@$empty)](red bold)";
let formatter = StringFormatter::new(FORMAT_STR)
.unwrap()
.map(|variable| match variable {
"empty" => Some(Ok("")),
_ => None,
});
let result = formatter.parse(None, None).unwrap();
assert_eq!(result.len(), 0);
}
#[test]
fn test_nested_conditional() {
const FORMAT_STR: &str = "($some ($none)) and ($none ($some))";
let formatter = StringFormatter::new(FORMAT_STR)
.unwrap()
.map(|var| match var {
"some" => Some(Ok("$some")),
_ => None,
});
let result = formatter.parse(None, None).unwrap();
let mut result_iter = result.iter();
match_next!(result_iter, "$some", None);
match_next!(result_iter, " ", None);
match_next!(result_iter, " and ", None);
match_next!(result_iter, " ", None);
match_next!(result_iter, "$some", None);
}
#[test]
fn test_conditional_meta_variable() {
const FORMAT_STR: &str = r"(\[$all\]) ";
let formatter = StringFormatter::new(FORMAT_STR)
.unwrap()
.map_meta(|var, _| match var {
"all" => Some("$some"),
_ => None,
});
let result = formatter.parse(None, None).unwrap();
let mut result_iter = result.iter();
match_next!(result_iter, " ", None);
}
#[test]
fn test_variable_holder() {
const FORMAT_STR: &str = "($a [($b) $c](none $s)) $d [t]($t)";
let expected_variables = vec!["a", "b", "c", "d"]
.into_iter()
.map(String::from)
.collect();
let formatter = StringFormatter::new(FORMAT_STR).unwrap().map(empty_mapper);
let variables = formatter.get_variables();
assert_eq!(variables, expected_variables);
}
#[test]
fn test_style_variable_holder() {
const FORMAT_STR: &str = "($a [($b) $c](none $s)) $d [t]($t)";
let expected_variables = vec!["s", "t"].into_iter().map(String::from).collect();
let formatter = StringFormatter::new(FORMAT_STR).unwrap().map(empty_mapper);
let variables = formatter.get_style_variables();
assert_eq!(variables, expected_variables);
}
#[test]
fn test_parse_error() {
// brackets without escape
{
const FORMAT_STR: &str = "[";
assert!(StringFormatter::new(FORMAT_STR).is_err());
}
// Dollar without variable
{
const FORMAT_STR: &str = "$ ";
assert!(StringFormatter::new(FORMAT_STR).is_err());
}
}
#[test]
fn test_variable_error() {
const FORMAT_STR: &str = "$never$some";
let never_error = StringFormatterError::Custom("NEVER".to_owned());
let segments = StringFormatter::new(FORMAT_STR).and_then(|formatter| {
formatter
.map(|var| match var {
"some" => Some(Ok("some")),
"never" => Some(Err(never_error.clone())),
_ => None,
})
.parse(None, None)
});
assert!(segments.is_err());
}
#[test]
fn test_bash_escape() {
let test = "$(echo a)";
assert_eq!(
shell_prompt_escape(test.to_owned(), Shell::Bash),
r"\$(echo a)"
);
assert_eq!(
shell_prompt_escape(test.to_owned(), Shell::PowerShell),
test
);
let test = r"\$(echo a)";
assert_eq!(
shell_prompt_escape(test.to_owned(), Shell::Bash),
r"\\\$(echo a)"
);
assert_eq!(
shell_prompt_escape(test.to_owned(), Shell::PowerShell),
test
);
let test = r"`echo a`";
assert_eq!(
shell_prompt_escape(test.to_owned(), Shell::Bash),
r"\`echo a\`"
);
assert_eq!(
shell_prompt_escape(test.to_owned(), Shell::PowerShell),
test
);
}
#[test]
fn test_zsh_escape() {
let test = "10%";
assert_eq!(shell_prompt_escape(test.to_owned(), Shell::Zsh), "10%%");
assert_eq!(
shell_prompt_escape(test.to_owned(), Shell::PowerShell),
test
);
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/test/mod.rs | src/test/mod.rs | use crate::context::{Context, Properties, Shell, Target};
use crate::context_env::Env;
use crate::logger::StarshipLogger;
use crate::{
config::StarshipConfig,
utils::{CommandOutput, create_command},
};
use log::{Level, LevelFilter};
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::LazyLock;
use std::sync::Once;
use tempfile::TempDir;
static FIXTURE_DIR: LazyLock<PathBuf> =
LazyLock::new(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("src/test/fixtures/"));
static GIT_FIXTURE: LazyLock<PathBuf> = LazyLock::new(|| FIXTURE_DIR.join("git-repo.bundle"));
static HG_FIXTURE: LazyLock<PathBuf> = LazyLock::new(|| FIXTURE_DIR.join("hg-repo.bundle"));
static LOGGER: Once = Once::new();
fn init_logger() {
let mut logger = StarshipLogger::default();
// Don't log to files during tests
let nul = if cfg!(windows) { "nul" } else { "/dev/null" };
let nul = PathBuf::from(nul);
// Maximum log level
log::set_max_level(LevelFilter::Trace);
logger.set_log_level(Level::Trace);
logger.set_log_file_path(nul);
log::set_boxed_logger(Box::new(logger)).unwrap();
}
pub fn default_context() -> Context<'static> {
let mut context = Context::new_with_shell_and_path(
Properties::default(),
Shell::Unknown,
Target::Main,
PathBuf::new(),
PathBuf::new(),
Env::default(),
);
context.config = StarshipConfig { config: None };
context
}
/// Render a specific starship module by name
pub struct ModuleRenderer<'a> {
name: &'a str,
context: Context<'a>,
}
impl<'a> ModuleRenderer<'a> {
/// Creates a new `ModuleRenderer`
pub fn new(name: &'a str) -> Self {
// Start logger
LOGGER.call_once(init_logger);
let context = default_context();
Self { name, context }
}
/// Creates a new `ModuleRenderer` with `HOME` set to a `TempDir`
pub fn new_with_home(name: &'a str) -> io::Result<(Self, tempfile::TempDir)> {
let module_renderer = ModuleRenderer::new(name);
let homedir = tempfile::tempdir()?;
let home = dunce::canonicalize(homedir.path())?;
Ok((module_renderer.env("HOME", home.to_str().unwrap()), homedir))
}
pub fn path<T>(mut self, path: T) -> Self
where
T: Into<PathBuf>,
{
self.context.current_dir = path.into();
self.context
.logical_dir
.clone_from(&self.context.current_dir);
self
}
pub fn root_path(&self) -> &Path {
self.context.root_dir.path()
}
pub fn logical_path<T>(mut self, path: T) -> Self
where
T: Into<PathBuf>,
{
self.context.logical_dir = path.into();
self
}
/// Sets the config of the underlying context
pub fn config(mut self, config: toml::Table) -> Self {
self.context = self.context.set_config(config);
self
}
/// Adds the variable to the `env_mocks` of the underlying context
pub fn env<V: Into<String>>(mut self, key: &'a str, val: V) -> Self {
self.context.env.insert(key, val.into());
self
}
/// Adds the command to the `command_mocks` of the underlying context
pub fn cmd(mut self, key: &'a str, val: Option<CommandOutput>) -> Self {
self.context.cmd.insert(key, val);
self
}
pub fn shell(mut self, shell: Shell) -> Self {
self.context.shell = shell;
self
}
pub fn jobs(mut self, jobs: i64) -> Self {
self.context.properties.jobs = jobs;
self
}
pub fn cmd_duration(mut self, duration: u64) -> Self {
self.context.properties.cmd_duration = Some(duration.to_string());
self
}
pub fn keymap<T>(mut self, keymap: T) -> Self
where
T: Into<String>,
{
self.context.properties.keymap = keymap.into();
self
}
pub fn status(mut self, status: i64) -> Self {
self.context.properties.status_code = Some(status.to_string());
self
}
pub fn width(mut self, width: usize) -> Self {
self.context.width = width;
self
}
#[cfg(feature = "battery")]
pub fn battery_info_provider(
mut self,
battery_info_provider: &'a (dyn crate::modules::BatteryInfoProvider + Send + Sync),
) -> Self {
self.context.battery_info_provider = battery_info_provider;
self
}
pub fn pipestatus(mut self, status: &[i64]) -> Self {
self.context.properties.pipestatus = Some(
status
.iter()
.map(std::string::ToString::to_string)
.collect(),
);
self
}
/// Renders the module returning its output
pub fn collect(self) -> Option<String> {
let ret = crate::print::get_module(self.name, &self.context);
// all tests rely on the fact that an empty module produces None as output as the
// convention was that there would be no module but None. This is nowadays not anymore
// the case (to get durations for all modules). So here we make it so, that an empty
// module returns None in the tests...
ret.filter(|s| !s.is_empty())
}
}
impl<'a> From<ModuleRenderer<'a>> for Context<'a> {
fn from(renderer: ModuleRenderer<'a>) -> Self {
renderer.context
}
}
#[derive(Clone, Copy)]
pub enum FixtureProvider {
Fossil,
Git,
GitReftable,
GitBare,
GitBareReftable,
Hg,
Pijul,
}
pub fn fixture_repo(provider: FixtureProvider) -> io::Result<TempDir> {
match provider {
FixtureProvider::Fossil => {
let checkout_db = if cfg!(windows) {
"_FOSSIL_"
} else {
".fslckout"
};
let path = tempfile::tempdir()?;
fs::create_dir(path.path().join("subdir"))?;
fs::OpenOptions::new()
.create(true)
.write(true)
.truncate(false)
.open(path.path().join(checkout_db))?
.sync_all()?;
Ok(path)
}
FixtureProvider::Git | FixtureProvider::GitReftable => {
let path = tempfile::tempdir()?;
create_command("git")?
.current_dir(path.path())
.arg("clone")
.args(
matches!(provider, FixtureProvider::GitReftable)
.then(|| "--ref-format=reftable"),
)
.args(["-b", "master"])
.arg(GIT_FIXTURE.as_os_str())
.arg(path.path())
.output()?;
create_command("git")?
.args(["config", "--local", "user.email", "starship@example.com"])
.current_dir(path.path())
.output()?;
create_command("git")?
.args(["config", "--local", "user.name", "starship"])
.current_dir(path.path())
.output()?;
// Prevent intermittent test failures and ensure that the result of git commands
// are available during I/O-contentious tests, by having git run `fsync`.
// This is especially important on Windows.
// Newer, more far-reaching git setting for `fsync`, that's not yet widely supported:
create_command("git")?
.args(["config", "--local", "core.fsync", "all"])
.current_dir(path.path())
.output()?;
// Older git setting for `fsync` for compatibility with older git versions:
create_command("git")?
.args(["config", "--local", "core.fsyncObjectFiles", "true"])
.current_dir(path.path())
.output()?;
create_command("git")?
.args(["reset", "--hard", "HEAD"])
.current_dir(path.path())
.output()?;
Ok(path)
}
FixtureProvider::GitBare | FixtureProvider::GitBareReftable => {
let path = tempfile::tempdir()?;
create_command("git")?
.current_dir(path.path())
.arg("clone")
.args(
matches!(provider, FixtureProvider::GitBareReftable)
.then(|| "--ref-format=reftable"),
)
.args(["-b", "master", "--bare"])
.arg(GIT_FIXTURE.as_os_str())
.arg(path.path())
.output()?;
Ok(path)
}
FixtureProvider::Hg => {
let path = tempfile::tempdir()?;
create_command("hg")?
.current_dir(path.path())
.arg("clone")
.arg(HG_FIXTURE.as_os_str())
.arg(path.path())
.output()?;
Ok(path)
}
FixtureProvider::Pijul => {
let path = tempfile::tempdir()?;
fs::create_dir(path.path().join(".pijul"))?;
Ok(path)
}
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/nodejs.rs | src/modules/nodejs.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::nodejs::NodejsConfig;
use crate::formatter::{StringFormatter, VersionFormatter};
use regex::Regex;
use semver::Version;
use semver::VersionReq;
use serde_json as json;
use std::ops::Deref;
use std::sync::LazyLock;
/// Creates a module with the current Node.js version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("nodejs");
let config = NodejsConfig::try_load(module.config);
let is_js_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
let is_esy_project = context
.try_begin_scan()?
.set_folders(&["esy.lock"])
.is_match();
if !is_js_project || is_esy_project {
return None;
}
let nodejs_version = LazyLock::new(|| {
context
.exec_cmd("node", &["--version"])
.map(|cmd| cmd.stdout)
});
let engines_version = LazyLock::new(|| get_engines_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" => {
let in_engines_range = check_engines_version(
nodejs_version.as_deref(),
engines_version.as_deref(),
);
if in_engines_range {
Some(Ok(config.style))
} else {
Some(Ok(config.not_capable_style))
}
}
_ => None,
})
.map(|variable| match variable {
"version" => {
let node_ver = nodejs_version
.deref()
.as_ref()?
.trim_start_matches('v')
.trim();
VersionFormatter::format_module_version(
module.get_name(),
node_ver,
config.version_format,
)
.map(Ok)
}
"engines_version" => {
let in_engines_range = check_engines_version(
nodejs_version.as_deref(),
engines_version.as_deref(),
);
let eng_ver = engines_version.as_deref()?.to_string();
(!in_engines_range).then_some(Ok(eng_ver))
}
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `nodejs`:\n{error}");
return None;
}
});
Some(module)
}
fn get_engines_version(context: &Context) -> Option<String> {
let json_str = context.read_file_from_pwd("package.json")?;
let package_json: json::Value = json::from_str(&json_str).ok()?;
let raw_version = package_json.get("engines")?.get("node")?.as_str()?;
Some(raw_version.to_string())
}
fn check_engines_version(nodejs_version: Option<&str>, engines_version: Option<&str>) -> bool {
let (Some(nodejs_version), Some(engines_version)) = (nodejs_version, engines_version) else {
return true;
};
let Ok(r) = VersionReq::parse(engines_version) else {
return true;
};
let re = Regex::new(r"\d+\.\d+\.\d+").unwrap();
let version = re
.captures(nodejs_version)
.unwrap()
.get(0)
.unwrap()
.as_str();
let v = match Version::parse(version) {
Ok(v) => v,
Err(_e) => return true,
};
r.matches(&v)
}
#[cfg(test)]
mod tests {
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
use std::fs::{self, File};
use std::io;
use std::io::Write;
#[test]
fn folder_without_node_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("nodejs").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_package_json() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("package.json"))?.sync_all()?;
let actual = ModuleRenderer::new("nodejs").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Green.bold().paint(" v12.0.0 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_package_json_and_esy_lock() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("package.json"))?.sync_all()?;
let esy_lock = dir.path().join("esy.lock");
fs::create_dir_all(esy_lock)?;
let actual = ModuleRenderer::new("nodejs").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_node_version() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join(".node-version"))?.sync_all()?;
let actual = ModuleRenderer::new("nodejs").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Green.bold().paint(" v12.0.0 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_nvmrc() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join(".nvmrc"))?.sync_all()?;
let actual = ModuleRenderer::new("nodejs").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Green.bold().paint(" v12.0.0 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_js_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("index.js"))?.sync_all()?;
let actual = ModuleRenderer::new("nodejs").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Green.bold().paint(" v12.0.0 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_mjs_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("index.mjs"))?.sync_all()?;
let actual = ModuleRenderer::new("nodejs").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Green.bold().paint(" v12.0.0 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_cjs_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("index.cjs"))?.sync_all()?;
let actual = ModuleRenderer::new("nodejs").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Green.bold().paint(" v12.0.0 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_ts_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("index.ts"))?.sync_all()?;
let actual = ModuleRenderer::new("nodejs").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Green.bold().paint(" v12.0.0 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_node_modules() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let node_modules = dir.path().join("node_modules");
fs::create_dir_all(node_modules)?;
let actual = ModuleRenderer::new("nodejs").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Green.bold().paint(" v12.0.0 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn engines_node_version_match() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let mut file = File::create(dir.path().join("package.json"))?;
file.write_all(
b"{
\"engines\":{
\"node\":\">=12.0.0\"
}
}",
)?;
file.sync_all()?;
let actual = ModuleRenderer::new("nodejs").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Green.bold().paint(" v12.0.0 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn engines_node_version_not_match() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let mut file = File::create(dir.path().join("package.json"))?;
file.write_all(
b"{
\"engines\":{
\"node\":\"<12.0.0\"
}
}",
)?;
file.sync_all()?;
let actual = ModuleRenderer::new("nodejs").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Red.bold().paint(" v12.0.0 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn show_expected_version_when_engines_does_not_match() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let mut file = File::create(dir.path().join("package.json"))?;
file.write_all(
b"{
\"engines\":{
\"node\":\"<=11.0.0\"
}
}",
)?;
file.sync_all()?;
let actual = ModuleRenderer::new("nodejs")
.path(dir.path())
.config(toml::toml! {
[nodejs]
format = "via [$symbol($version )($engines_version )]($style)"
})
.collect();
let expected = Some(format!(
"via {}",
Color::Red.bold().paint(" v12.0.0 <=11.0.0 ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn do_not_show_expected_version_if_engines_match() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let mut file = File::create(dir.path().join("package.json"))?;
file.write_all(
b"{
\"engines\":{
\"node\":\">=12.0.0\"
}
}",
)?;
file.sync_all()?;
let actual = ModuleRenderer::new("nodejs")
.path(dir.path())
.config(toml::toml! [
[nodejs]
format = "via [$symbol($version )($engines_version )]($style)"
])
.collect();
let expected = Some(format!("via {}", Color::Green.bold().paint(" v12.0.0 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn do_not_show_expected_version_if_no_set_engines_version() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("package.json"))?.sync_all()?;
let actual = ModuleRenderer::new("nodejs")
.path(dir.path())
.config(toml::toml! {
[nodejs]
format = "via [$symbol($version )($engines_version )]($style)"
})
.collect();
let expected = Some(format!("via {}", Color::Green.bold().paint(" v12.0.0 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn no_node_installed() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("index.js"))?.sync_all()?;
let actual = ModuleRenderer::new("nodejs")
.path(dir.path())
.cmd("node --version", None)
.collect();
let expected = Some(format!("via {}", Color::Green.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/golang.rs | src/modules/golang.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::go::GoConfig;
use crate::formatter::StringFormatter;
use crate::formatter::VersionFormatter;
use regex::Regex;
use semver::Version;
use semver::VersionReq;
use std::ops::Deref;
use std::sync::LazyLock;
/// Creates a module with the current Go version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("golang");
let config = GoConfig::try_load(module.config);
let is_go_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_go_project {
return None;
}
let golang_version =
LazyLock::new(|| parse_go_version(&context.exec_cmd("go", &["version"])?.stdout));
let mod_version = LazyLock::new(|| get_go_mod_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" => {
let in_mod_range =
check_go_version(golang_version.as_deref(), mod_version.as_deref());
if in_mod_range {
Some(Ok(config.style))
} else {
Some(Ok(config.not_capable_style))
}
}
_ => None,
})
.map(|variable| match variable {
"version" => {
let go_ver = golang_version.deref().as_ref()?;
VersionFormatter::format_module_version(
module.get_name(),
go_ver,
config.version_format,
)
.map(Ok)
}
"mod_version" => {
let in_mod_range =
check_go_version(golang_version.as_deref(), mod_version.as_deref());
let mod_ver = mod_version.as_deref()?.to_string();
(!in_mod_range).then_some(Ok(mod_ver))
}
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `golang`:\n{error}");
return None;
}
});
Some(module)
}
fn parse_go_version(go_stdout: &str) -> Option<String> {
// go version output looks like this:
// go version go1.13.3 linux/amd64
let version = go_stdout
// split into ("", "1.12.4 linux/amd64")
.split_once("go version go")?
// return "1.12.4 linux/amd64"
.1
// split into ["1.12.4", "linux/amd64"]
.split_whitespace()
// return "1.12.4"
.next()?;
Some(version.to_string())
}
fn get_go_mod_version(context: &Context) -> Option<String> {
let mod_str = context.read_file_from_pwd("go.mod")?;
let re = Regex::new(r"(?:go\s)(\d+(\.\d+)+)").unwrap();
if let Some(cap) = re.captures(&mod_str) {
let mod_ver = cap.get(1)?.as_str();
Some(mod_ver.to_string())
} else {
None
}
}
fn check_go_version(go_version: Option<&str>, mod_version: Option<&str>) -> bool {
let (Some(go_version), Some(mod_version)) = (go_version, mod_version) else {
return true;
};
let Ok(r) = VersionReq::parse(mod_version) else {
return true;
};
let Ok(v) = Version::parse(go_version) else {
return true;
};
r.matches(&v)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
use std::fs::{self, File};
use std::io;
use std::io::Write;
#[test]
fn folder_without_go_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("golang").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_go_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("main.go"))?.sync_all()?;
let actual = ModuleRenderer::new("golang").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Cyan.bold().paint("🐹 v1.12.1 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_go_mod() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("go.mod"))?.sync_all()?;
let actual = ModuleRenderer::new("golang").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Cyan.bold().paint("🐹 v1.12.1 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_go_sum() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("go.sum"))?.sync_all()?;
let actual = ModuleRenderer::new("golang").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Cyan.bold().paint("🐹 v1.12.1 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_go_work() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("go.work"))?.sync_all()?;
let actual = ModuleRenderer::new("golang").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Cyan.bold().paint("🐹 v1.12.1 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_godeps() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let godeps = dir.path().join("Godeps");
fs::create_dir_all(godeps)?;
let actual = ModuleRenderer::new("golang").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Cyan.bold().paint("🐹 v1.12.1 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_glide_yaml() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("glide.yaml"))?.sync_all()?;
let actual = ModuleRenderer::new("golang").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Cyan.bold().paint("🐹 v1.12.1 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_gopkg_yml() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("Gopkg.yml"))?.sync_all()?;
let actual = ModuleRenderer::new("golang").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Cyan.bold().paint("🐹 v1.12.1 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_gopkg_lock() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("Gopkg.lock"))?.sync_all()?;
let actual = ModuleRenderer::new("golang").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Cyan.bold().paint("🐹 v1.12.1 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_go_version() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join(".go-version"))?.sync_all()?;
let actual = ModuleRenderer::new("golang").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Cyan.bold().paint("🐹 v1.12.1 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn test_format_go_version() {
let input = "go version go1.12 darwin/amd64";
assert_eq!(parse_go_version(input), Some("1.12".to_string()));
}
#[test]
fn show_mod_version_if_not_matching_go_version() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let mut file = File::create(dir.path().join("go.mod"))?;
file.write_all(
b"package test\n\n
go 1.16",
)?;
file.sync_all()?;
let actual = ModuleRenderer::new("golang")
.path(dir.path())
.config(toml::toml! {
[golang]
format = "via [$symbol($version )($mod_version )]($style)"
})
.collect();
let expected = Some(format!(
"via {}",
Color::Red.bold().paint("🐹 v1.12.1 1.16 ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn hide_mod_version_when_it_matches_go_version() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let mut file = File::create(dir.path().join("go.mod"))?;
file.write_all(
b"package test\n\n
go 1.12",
)?;
file.sync_all()?;
let actual = ModuleRenderer::new("golang")
.path(dir.path())
.config(toml::toml! {
[golang]
format = "via [$symbol($version )($mod_version )]($style)"
})
.collect();
let expected = Some(format!("via {}", Color::Cyan.bold().paint("🐹 v1.12.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/jobs.rs | src/modules/jobs.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::jobs::JobsConfig;
use crate::formatter::StringFormatter;
/// Creates a segment to show if there are any active jobs running
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("jobs");
let config = JobsConfig::try_load(module.config);
if config.threshold < 0 {
log::warn!(
"threshold in [jobs] ({}) was less than zero",
config.threshold
);
return None;
}
if config.symbol_threshold < 0 {
log::warn!(
"symbol_threshold in [jobs] ({}) was less than zero",
config.symbol_threshold
);
return None;
}
if config.number_threshold < 0 {
log::warn!(
"number_threshold in [jobs] ({}) was less than zero",
config.number_threshold
);
return None;
}
let props = &context.properties;
let num_of_jobs = props.jobs;
if num_of_jobs == 0
&& config.threshold > 0
&& config.number_threshold > 0
&& config.symbol_threshold > 0
{
return None;
}
let default_threshold = 1;
let mut module_symbol = "";
let mut module_number = String::new();
if config.threshold == default_threshold {
if num_of_jobs >= config.symbol_threshold {
module_symbol = config.symbol;
}
if num_of_jobs >= config.number_threshold {
module_number = num_of_jobs.to_string();
}
} else {
log::warn!(
"`threshold` in [jobs] is deprecated. Please remove it and use `symbol_threshold` and `number_threshold`."
);
// The symbol should be shown if there are *any* background
// jobs running.
if num_of_jobs > 0 {
module_symbol = config.symbol;
}
if num_of_jobs > config.threshold || config.threshold == 0 {
module_symbol = config.symbol;
module_number = num_of_jobs.to_string();
}
}
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|var, _| match var {
"symbol" => Some(module_symbol),
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map(|variable| match variable {
"number" => Some(Ok(module_number.clone())),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `jobs`:\n{error}");
return None;
}
});
Some(module)
}
#[cfg(test)]
mod test {
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
#[test]
fn config_blank_job_0() {
let actual = ModuleRenderer::new("jobs").jobs(0).collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn config_blank_job_1() {
let actual = ModuleRenderer::new("jobs").jobs(1).collect();
let expected = Some(format!("{} ", Color::Blue.bold().paint("✦")));
assert_eq!(expected, actual);
}
#[test]
fn config_blank_job_2() {
let actual = ModuleRenderer::new("jobs").jobs(2).collect();
let expected = Some(format!("{} ", Color::Blue.bold().paint("✦2")));
assert_eq!(expected, actual);
}
#[test]
fn config_default_is_present_jobs_1() {
let actual = ModuleRenderer::new("jobs")
.config(toml::toml! {
[jobs]
threshold = 1
})
.jobs(1)
.collect();
let expected = Some(format!("{} ", Color::Blue.bold().paint("✦")));
assert_eq!(expected, actual);
}
#[test]
fn config_default_is_present_jobs_2() {
let actual = ModuleRenderer::new("jobs")
.config(toml::toml! {
[jobs]
threshold = 1
})
.jobs(2)
.collect();
let expected = Some(format!("{} ", Color::Blue.bold().paint("✦2")));
assert_eq!(expected, actual);
}
#[test]
fn config_conflicting_thresholds_default_jobs_1() {
let actual = ModuleRenderer::new("jobs")
.config(toml::toml! {
[jobs]
threshold = 1
number_threshold = 2
})
.jobs(1)
.collect();
let expected = Some(format!("{} ", Color::Blue.bold().paint("✦")));
assert_eq!(expected, actual);
}
#[test]
fn config_conflicting_thresholds_default_no_symbol_jobs_1() {
let actual = ModuleRenderer::new("jobs")
.config(toml::toml! {
[jobs]
threshold = 1
symbol_threshold = 0
number_threshold = 2
})
.jobs(1)
.collect();
let expected = Some(format!("{} ", Color::Blue.bold().paint("✦")));
assert_eq!(expected, actual);
}
#[test]
fn config_conflicting_thresholds_no_symbol_jobs_1() {
let actual = ModuleRenderer::new("jobs")
.config(toml::toml! {
[jobs]
threshold = 0
symbol_threshold = 0
number_threshold = 2
})
.jobs(1)
.collect();
let expected = Some(format!("{} ", Color::Blue.bold().paint("✦1")));
assert_eq!(expected, actual);
}
#[test]
fn config_conflicting_thresholds_jobs_2() {
let actual = ModuleRenderer::new("jobs")
.config(toml::toml! {
[jobs]
threshold = 1
number_threshold = 2
})
.jobs(2)
.collect();
let expected = Some(format!("{} ", Color::Blue.bold().paint("✦2")));
assert_eq!(expected, actual);
}
#[test]
fn config_2_job_2() {
let actual = ModuleRenderer::new("jobs")
.config(toml::toml! {
[jobs]
threshold = 2
})
.jobs(2)
.collect();
let expected = Some(format!("{} ", Color::Blue.bold().paint("✦")));
assert_eq!(expected, actual);
}
#[test]
fn config_number_2_job_2() {
let actual = ModuleRenderer::new("jobs")
.config(toml::toml! {
[jobs]
number_threshold = 2
})
.jobs(2)
.collect();
let expected = Some(format!("{} ", Color::Blue.bold().paint("✦2")));
assert_eq!(expected, actual);
}
#[test]
fn config_number_2_symbol_3_job_2() {
let actual = ModuleRenderer::new("jobs")
.config(toml::toml! {
[jobs]
number_threshold = 2
symbol_threshold = 3
})
.jobs(2)
.collect();
let expected = Some(format!("{} ", Color::Blue.bold().paint("2")));
assert_eq!(expected, actual);
}
#[test]
fn config_2_job_3() {
let actual = ModuleRenderer::new("jobs")
.config(toml::toml! {
[jobs]
threshold = 2
})
.jobs(3)
.collect();
let expected = Some(format!("{} ", Color::Blue.bold().paint("✦3")));
assert_eq!(expected, actual);
}
#[test]
fn config_thresholds_0_jobs_0() {
let actual = ModuleRenderer::new("jobs")
.config(toml::toml! {
[jobs]
number_threshold = 0
symbol_threshold = 0
})
.jobs(0)
.collect();
let expected = Some(format!("{} ", Color::Blue.bold().paint("✦0")));
assert_eq!(expected, actual);
}
#[test]
fn config_thresholds_0_jobs_1() {
let actual = ModuleRenderer::new("jobs")
.config(toml::toml! {
[jobs]
number_threshold = 0
symbol_threshold = 0
})
.jobs(1)
.collect();
let expected = Some(format!("{} ", Color::Blue.bold().paint("✦1")));
assert_eq!(expected, actual);
}
#[test]
fn config_0_job_0() {
let actual = ModuleRenderer::new("jobs")
.config(toml::toml! {
[jobs]
threshold = 0
})
.jobs(0)
.collect();
let expected = Some(format!("{} ", Color::Blue.bold().paint("✦0")));
assert_eq!(expected, actual);
}
#[test]
fn config_0_job_1() {
let actual = ModuleRenderer::new("jobs")
.config(toml::toml! {
[jobs]
threshold = 0
})
.jobs(1)
.collect();
let expected = Some(format!("{} ", Color::Blue.bold().paint("✦1")));
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/username.rs | src/modules/username.rs | use super::{Context, Detected, Module, ModuleConfig};
use crate::configs::username::UsernameConfig;
use crate::formatter::StringFormatter;
#[cfg(not(target_os = "windows"))]
const USERNAME_ENV_VAR: &str = "USER";
#[cfg(target_os = "windows")]
const USERNAME_ENV_VAR: &str = "USERNAME";
/// Creates a module with the current user's username
///
/// Will display the username if any of the following criteria are met:
/// - The current user is root (UID = 0) [1]
/// - The current user isn't the same as the one that is logged in (`$LOGNAME` != `$USER`) [2]
/// - The user is currently connected as an SSH session (`$SSH_CONNECTION`) [3]
/// - The option `username.detect_env_vars` is set with a not negated environment variable [4]
/// Does not display the username:
/// - If the option `username.detect_env_vars` is set with a negated environment variable [A]
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
#[cfg(not(any(test, target_os = "android")))]
let mut username = whoami::username()
.inspect_err(|e| log::debug!("Failed to get username {e:?}"))
.ok()
.or_else(|| context.get_env(USERNAME_ENV_VAR))?;
#[cfg(any(test, target_os = "android"))]
let mut username = context.get_env(USERNAME_ENV_VAR)?;
let mut module = context.new_module("username");
let config: UsernameConfig = UsernameConfig::try_load(module.config);
let has_detected_env_var = context.detect_env_vars2(&config.detect_env_vars);
let is_root = is_root_user();
if cfg!(target_os = "windows") && is_root {
username = "Administrator".to_string();
}
let show_username = config.show_always
|| is_root // [1]
|| !is_login_user(context, &username) // [2]
|| is_ssh_session(context) // [3]
|| has_detected_env_var == Detected::Yes; // [4]
if !show_username || has_detected_env_var == Detected::Negated {
return None; // [A]
}
if let Some(&alias) = config.aliases.get(&username) {
username = alias.to_string();
}
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_style(|variable| match variable {
"style" => {
let module_style = if is_root {
config.style_root
} else {
config.style_user
};
Some(Ok(module_style))
}
_ => None,
})
.map(|variable| match variable {
"user" => Some(Ok(&username)),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `username`:\n{error}");
return None;
}
});
Some(module)
}
fn is_login_user(context: &Context, username: &str) -> bool {
context
.get_env("LOGNAME")
.is_none_or(|logname| logname == username)
}
#[cfg(all(target_os = "windows", not(test)))]
fn is_root_user() -> bool {
use deelevate::{PrivilegeLevel, Token};
let token = match Token::with_current_process() {
Ok(token) => token,
Err(e) => {
log::warn!("Failed to get process token: {e:?}");
return false;
}
};
matches!(
match token.privilege_level() {
Ok(level) => level,
Err(e) => {
log::warn!("Failed to get privilege level: {e:?}");
return false;
}
},
PrivilegeLevel::Elevated | PrivilegeLevel::HighIntegrityAdmin
)
}
#[cfg(test)]
fn is_root_user() -> bool {
false
}
#[cfg(all(not(target_os = "windows"), not(test)))]
fn is_root_user() -> bool {
nix::unistd::geteuid() == nix::unistd::ROOT
}
fn is_ssh_session(context: &Context) -> bool {
let ssh_env = ["SSH_CONNECTION", "SSH_CLIENT", "SSH_TTY"];
ssh_env.iter().any(|env| context.get_env_os(env).is_some())
}
#[cfg(test)]
mod tests {
use crate::test::ModuleRenderer;
// TODO: Add tests for if root user (UID == 0)
// Requires mocking
#[test]
fn ssh_with_empty_detect_env_vars() {
let actual = ModuleRenderer::new("username")
.env(super::USERNAME_ENV_VAR, "astronaut")
.env("SSH_CONNECTION", "192.168.223.17 36673 192.168.223.229 22")
// Test output should not change when run by root/non-root user
.config(toml::toml! {
[username]
style_root = ""
style_user = ""
detect_env_vars = []
})
.collect();
let expected = Some("astronaut in ");
assert_eq!(expected, actual.as_deref());
}
#[test]
fn ssh_with_matching_detect_env_vars() {
let actual = ModuleRenderer::new("username")
.env(super::USERNAME_ENV_VAR, "astronaut")
.env("SSH_CONNECTION", "192.168.223.17 36673 192.168.223.229 22")
.env("FORCE_USERNAME", "true")
// Test output should not change when run by root/non-root user
.config(toml::toml! {
[username]
style_root = ""
style_user = ""
detect_env_vars = ["FORCE_USERNAME"]
})
.collect();
let expected = Some("astronaut in ");
assert_eq!(expected, actual.as_deref());
}
#[test]
fn ssh_with_matching_negated_detect_env_vars() {
let actual = ModuleRenderer::new("username")
.env(super::USERNAME_ENV_VAR, "astronaut")
.env("SSH_CONNECTION", "192.168.223.17 36673 192.168.223.229 22")
.env("NEGATED", "true")
// Test output should not change when run by root/non-root user
.config(toml::toml! {
[username]
style_root = ""
style_user = ""
detect_env_vars = ["!NEGATED"]
})
.collect();
let expected = None;
assert_eq!(expected, actual.as_deref());
}
#[test]
fn no_env_variables() {
let actual = ModuleRenderer::new("username").collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
#[ignore]
fn no_logname_env_variable() {
let actual = ModuleRenderer::new("username")
.env(super::USERNAME_ENV_VAR, "astronaut")
.collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
#[ignore]
fn logname_equals_user() {
let actual = ModuleRenderer::new("username")
.env("LOGNAME", "astronaut")
.env(super::USERNAME_ENV_VAR, "astronaut")
.collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn ssh_wo_username() {
// SSH connection w/o username
let actual = ModuleRenderer::new("username")
.env("SSH_CONNECTION", "192.168.223.17 36673 192.168.223.229 22")
.collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn current_user_not_logname() {
let actual = ModuleRenderer::new("username")
.env("LOGNAME", "astronaut")
.env(super::USERNAME_ENV_VAR, "cosmonaut")
// Test output should not change when run by root/non-root user
.config(toml::toml! {
[username]
style_root = ""
style_user = ""
})
.collect();
let expected = Some("cosmonaut in ");
assert_eq!(expected, actual.as_deref());
}
#[test]
fn ssh_connection() {
let actual = ModuleRenderer::new("username")
.env(super::USERNAME_ENV_VAR, "astronaut")
.env("SSH_CONNECTION", "192.168.223.17 36673 192.168.223.229 22")
// Test output should not change when run by root/non-root user
.config(toml::toml! {
[username]
style_root = ""
style_user = ""
})
.collect();
let expected = Some("astronaut in ");
assert_eq!(expected, actual.as_deref());
}
#[test]
fn ssh_connection_tty() {
let actual = ModuleRenderer::new("username")
.env(super::USERNAME_ENV_VAR, "astronaut")
.env("SSH_TTY", "/dev/pts/0")
// Test output should not change when run by root/non-root user
.config(toml::toml! {
[username]
style_root = ""
style_user = ""
})
.collect();
let expected = Some("astronaut in ");
assert_eq!(expected, actual.as_deref());
}
#[test]
fn ssh_connection_client() {
let actual = ModuleRenderer::new("username")
.env(super::USERNAME_ENV_VAR, "astronaut")
.env("SSH_CLIENT", "192.168.0.101 39323 22")
// Test output should not change when run by root/non-root user
.config(toml::toml! {
[username]
style_root = ""
style_user = ""
})
.collect();
let expected = Some("astronaut in ");
assert_eq!(expected, actual.as_deref());
}
#[test]
fn show_always() {
let actual = ModuleRenderer::new("username")
.env(super::USERNAME_ENV_VAR, "astronaut")
// Test output should not change when run by root/non-root user
.config(toml::toml! {
[username]
show_always = true
style_root = ""
style_user = ""
})
.collect();
let expected = Some("astronaut in ");
assert_eq!(expected, actual.as_deref());
}
#[test]
fn show_always_false() {
let actual = ModuleRenderer::new("username")
.env(super::USERNAME_ENV_VAR, "astronaut")
// Test output should not change when run by root/non-root user
.config(toml::toml! {
[username]
show_always = false
style_root = ""
style_user = ""
})
.collect();
let expected = None;
assert_eq!(expected, actual.as_deref());
}
#[test]
fn test_alias() {
let actual = ModuleRenderer::new("username")
.env(super::USERNAME_ENV_VAR, "astronaut")
.config(toml::toml! {
[username]
show_always = true
aliases = { "astronaut" = "skywalker" }
style_root = ""
style_user = ""
})
.collect();
let expected = Some("skywalker in ");
assert_eq!(expected, actual.as_deref());
}
#[test]
fn test_alias_emoji() {
let actual = ModuleRenderer::new("username")
.env(super::USERNAME_ENV_VAR, "kaas")
.config(toml::toml! {
[username]
show_always = true
aliases = { "a" = "b", "kaas" = "🧀" }
style_root = ""
style_user = ""
})
.collect();
let expected = Some("🧀 in ");
assert_eq!(expected, actual.as_deref());
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/perl.rs | src/modules/perl.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::perl::PerlConfig;
use crate::formatter::StringFormatter;
use crate::formatter::VersionFormatter;
/// Creates a module with the current perl version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("perl");
let config: PerlConfig = PerlConfig::try_load(module.config);
let is_perl_project = context
.try_begin_scan()?
.set_extensions(&config.detect_extensions)
.set_files(&config.detect_files)
.set_folders(&config.detect_folders)
.is_match();
if !is_perl_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 perl_version = context
.exec_cmd("perl", &["-e", "printf q#%vd#,$^V;"])?
.stdout;
VersionFormatter::format_module_version(
module.get_name(),
&perl_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 `perl`:\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_perl_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("perl").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_makefile_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("Makefile.PL"))?.sync_all()?;
let actual = ModuleRenderer::new("perl").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Fixed(149).bold().paint("🐪 v5.26.1 ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_buildfile_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("Build.PL"))?.sync_all()?;
let actual = ModuleRenderer::new("perl").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Fixed(149).bold().paint("🐪 v5.26.1 ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_cpanfile_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("cpanfile"))?.sync_all()?;
let actual = ModuleRenderer::new("perl").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Fixed(149).bold().paint("🐪 v5.26.1 ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_cpanfile_snapshot_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("cpanfile.snapshot"))?.sync_all()?;
let actual = ModuleRenderer::new("perl").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Fixed(149).bold().paint("🐪 v5.26.1 ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_meta_json_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("META.json"))?.sync_all()?;
let actual = ModuleRenderer::new("perl").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Fixed(149).bold().paint("🐪 v5.26.1 ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_meta_yml_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("META.yml"))?.sync_all()?;
let actual = ModuleRenderer::new("perl").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Fixed(149).bold().paint("🐪 v5.26.1 ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_perl_version() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join(".perl-version"))?.sync_all()?;
let actual = ModuleRenderer::new("perl").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Fixed(149).bold().paint("🐪 v5.26.1 ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_perl_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("any.pl"))?.sync_all()?;
let actual = ModuleRenderer::new("perl").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Fixed(149).bold().paint("🐪 v5.26.1 ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_perl_module_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("any.pm"))?.sync_all()?;
let actual = ModuleRenderer::new("perl").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Fixed(149).bold().paint("🐪 v5.26.1 ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_perldoc_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("any.pod"))?.sync_all()?;
let actual = ModuleRenderer::new("perl").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Fixed(149).bold().paint("🐪 v5.26.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/gradle.rs | src/modules/gradle.rs | use std::path::Path;
use crate::{
config::ModuleConfig,
configs::gradle::GradleConfig,
context::Context,
formatter::{StringFormatter, VersionFormatter},
module::Module,
utils,
};
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("gradle");
let config = GradleConfig::try_load(module.config);
let is_gradle_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_gradle_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 gradle_version = {
let properties = get_wrapper_properties_file(context, config.recursive)?;
parse_gradle_version_from_properties(&properties)?
};
VersionFormatter::format_module_version(
module.get_name(),
&gradle_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 `gradle`:\n{error}");
return None;
}
});
Some(module)
}
fn parse_gradle_version_from_properties(wrapper_properties: &str) -> Option<String> {
// example gradle.properties content
/*
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
*/
let version = wrapper_properties
.lines()
.find(|line| line.starts_with("distributionUrl="))?
.rsplit_once('/')?
.1
.strip_prefix("gradle-")?
.rsplit_once('-')?
.0;
Some(version.to_string())
}
/// Tries to find the gradle-wrapper.properties file.
fn get_wrapper_properties_file(context: &Context, recursive: bool) -> Option<String> {
let read_wrapper_properties = |base_dir: &Path| {
utils::read_file(base_dir.join("gradle/wrapper/gradle-wrapper.properties")).ok()
};
// Try current directory first
if context
.try_begin_scan()?
.set_folders(&["gradle"])
.is_match()
&& let Some(properties) = read_wrapper_properties(&context.current_dir)
{
return Some(properties);
}
// Try parent directories if recursive
if recursive {
for dir in context.current_dir.ancestors().skip(1) {
if let Some(properties) = read_wrapper_properties(dir) {
return Some(properties);
}
}
}
None
}
#[cfg(test)]
mod tests {
use nu_ansi_term::Color;
use super::*;
use crate::test::ModuleRenderer;
use std::fs::{self, File};
use std::io::{self, Write};
#[test]
fn folder_without_gradle_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("gradle").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_gradle_wrapper_properties() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let properties = dir
.path()
.join("gradle")
.join("wrapper")
.join("gradle-wrapper.properties");
// create gradle/wrapper/ directories
fs::create_dir_all(properties.parent().unwrap())?;
// create build.gradle file to mark it as a gradle project
File::create(dir.path().join("build.gradle"))?.sync_all()?;
let mut file = File::create(properties)?;
file.write_all(
b"\
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\\://services.gradle.org/distributions/gradle-7.5.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists",
)?;
file.sync_all()?;
let actual = ModuleRenderer::new("gradle").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::LightCyan.bold().paint("🅶 v7.5.1 ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn gradle_wrapper_recursive() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let properties = dir
.path()
.join("gradle")
.join("wrapper")
.join("gradle-wrapper.properties");
// create gradle/wrapper/ directories
fs::create_dir_all(properties.parent().unwrap())?;
// create build.gradle file to mark it as a gradle project
File::create(dir.path().join("build.gradle"))?.sync_all()?;
let mut file = File::create(properties)?;
file.write_all(
b"\
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\\://services.gradle.org/distributions/gradle-7.5.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists",
)?;
file.sync_all()?;
let target_dir = dir.path().join("working_dir");
fs::create_dir(&target_dir)?;
File::create(target_dir.join("build.gradle.kts"))?.sync_all()?;
let actual = ModuleRenderer::new("gradle")
.config(toml::toml! {
[gradle]
recursive = true
})
.path(target_dir)
.collect();
let expected = Some(format!(
"via {}",
Color::LightCyan.bold().paint("🅶 v7.5.1 ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn test_format_wrapper_properties() {
let input = "\
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\\://services.gradle.org/distributions/gradle-7.5.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
";
assert_eq!(
parse_gradle_version_from_properties(input),
Some("7.5.1".to_string())
);
}
#[test]
fn test_format_wrapper_properties_unstable_versions() {
let input = |version: &str| {
format!(
"\
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\\://services.gradle.org/distributions/gradle-{version}-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
"
)
};
assert_eq!(
parse_gradle_version_from_properties(&input("8.1-rc-1")),
Some("8.1-rc-1".to_string())
);
assert_eq!(
parse_gradle_version_from_properties(&input("7.5.1-20220729132837+0000")),
Some("7.5.1-20220729132837+0000".to_string())
);
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/ruby.rs | src/modules/ruby.rs | use regex::Regex;
use super::{Context, Module, ModuleConfig};
use crate::configs::ruby::RubyConfig;
use crate::formatter::{StringFormatter, VersionFormatter};
/// Creates a module with the current Ruby version
///
/// Will display the Ruby version if any of the following criteria are met:
/// - Current directory contains a `.rb` file
/// - Current directory contains a `Gemfile` or `.ruby-version` file
/// - The environment variables `RUBY_VERSION` or `RBENV_VERSION` are set
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("ruby");
let config = RubyConfig::try_load(module.config);
let is_rb_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
let is_rb_env = &config
.detect_variables
.iter()
.any(|variable| context.get_env(variable).is_some());
if !is_rb_project && !is_rb_env {
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" => format_ruby_version(
&context.exec_cmd("ruby", &["-v"])?.stdout,
config.version_format,
)
.map(Ok),
"gemset" => {
format_rvm_gemset(&context.exec_cmd("rvm", &["current"])?.stdout).map(Ok)
}
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `ruby`:\n{error}");
return None;
}
});
Some(module)
}
fn format_ruby_version(ruby_version: &str, version_format: &str) -> Option<String> {
let version = ruby_version
// split into ["ruby", "2.6.0p0", "linux/amd64"]
.split_whitespace()
// return "2.6.0p0"
.nth(1)?
// split into ["2.6.0", "0"]
.split('p')
// return "2.6.0"
.next()?;
match VersionFormatter::format_version(version, version_format) {
Ok(formatted) => Some(formatted),
Err(error) => {
log::warn!("Error formatting `ruby` version:\n{error}");
Some(format!("v{version}"))
}
}
}
fn format_rvm_gemset(current: &str) -> Option<String> {
let gemset_re = Regex::new(r"@(\S+)").unwrap();
if let Some(gemset) = gemset_re.captures(current) {
let gemset_name = gemset.get(1)?.as_str();
return Some(gemset_name.to_string());
}
None
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test::ModuleRenderer;
use crate::utils::CommandOutput;
use nu_ansi_term::Color;
use std::fs::File;
use std::io;
#[test]
fn folder_without_ruby_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("ruby").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_gemfile() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("Gemfile"))?.sync_all()?;
let actual = ModuleRenderer::new("ruby").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Red.bold().paint("💎 v2.5.1 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_ruby_version() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join(".ruby-version"))?.sync_all()?;
let actual = ModuleRenderer::new("ruby").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Red.bold().paint("💎 v2.5.1 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_rb_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("any.rb"))?.sync_all()?;
let actual = ModuleRenderer::new("ruby").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Red.bold().paint("💎 v2.5.1 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn with_ruby_version_env() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("ruby")
.path(dir.path())
.env("RUBY_VERSION", "2.5.1")
.collect();
let expected = Some(format!("via {}", Color::Red.bold().paint("💎 v2.5.1 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn with_rbenv_version_env() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("ruby")
.path(dir.path())
.env("RBENV_VERSION", "2.6.8")
.collect();
// rbenv variable is only detected; its value is not used
let expected = Some(format!("via {}", Color::Red.bold().paint("💎 v2.5.1 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn rvm_gemset_active() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("any.rb"))?.sync_all()?;
let actual = ModuleRenderer::new("ruby")
.path(dir.path())
.cmd(
"rvm current",
Some(CommandOutput {
stdout: String::from("ruby-2.5.1@test\n"),
stderr: String::default(),
}),
)
.config(toml::toml! {
[ruby]
format = "via [$symbol($version)@($gemset )]($style)"
version_format = "${raw}"
})
.collect();
let expected = Some(format!("via {}", Color::Red.bold().paint("💎 2.5.1@test ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn rvm_gemset_not_active() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("any.rb"))?.sync_all()?;
let actual = ModuleRenderer::new("ruby")
.path(dir.path())
.cmd(
"rvm current",
Some(CommandOutput {
// with no gemset, `rvm current` outputs an empty string
stdout: String::default(),
stderr: String::default(),
}),
)
.config(toml::toml! {
[ruby]
format = "via [$symbol($version)(@$gemset) ]($style)"
})
.collect();
let expected = Some(format!("via {}", Color::Red.bold().paint("💎 v2.5.1 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn test_format_ruby_version() {
let config = RubyConfig::default();
assert_eq!(
format_ruby_version(
"ruby 2.1.10p492 (2016-04-01 revision 54464) [x86_64-darwin19.0]",
config.version_format
),
Some("v2.1.10".to_string())
);
assert_eq!(
format_ruby_version(
"ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-linux-gnu]",
config.version_format
),
Some("v2.5.1".to_string())
);
assert_eq!(
format_ruby_version(
"ruby 2.7.0p0 (2019-12-25 revision 647ee6f091) [x86_64-linux-musl]",
config.version_format
),
Some("v2.7.0".to_string())
);
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/rust.rs | src/modules/rust.rs | use std::fs;
use std::path::{Path, PathBuf};
use std::process::Output;
use serde::Deserialize;
use std::collections::HashMap;
use super::{Context, Module, ModuleConfig};
use crate::configs::rust::RustConfig;
use crate::formatter::{StringFormatter, VersionFormatter};
use crate::utils::create_command;
use home::rustup_home;
use std::sync::OnceLock;
use guess_host_triple::guess_host_triple;
type VersionString = String;
type ToolchainString = String;
/// A struct to cache the output of any commands that need to be run.
struct RustToolingEnvironmentInfo {
/// Rustup settings parsed from $HOME/.rustup/settings.toml
rustup_settings: OnceLock<RustupSettings>,
/// Rustc toolchain overrides as contained in the environment or files
env_toolchain_override: OnceLock<Option<String>>,
/// The output of `rustup rustc --version` with a fixed toolchain
rustup_rustc_output: OnceLock<RustupRunRustcVersionOutcome>,
/// The output of running rustc -vV. Only called if rustup rustc fails or
/// is unavailable.
rustc_verbose_output: OnceLock<Option<(VersionString, ToolchainString)>>,
}
impl RustToolingEnvironmentInfo {
fn new() -> Self {
Self {
rustup_settings: OnceLock::new(),
env_toolchain_override: OnceLock::new(),
rustup_rustc_output: OnceLock::new(),
rustc_verbose_output: OnceLock::new(),
}
}
fn get_rustup_settings(&self, context: &Context) -> &RustupSettings {
self.rustup_settings
.get_or_init(|| RustupSettings::load(context).unwrap_or_default())
}
/// Gets any environmental toolchain overrides without downloading cargo toolchains
fn get_env_toolchain_override(&self, context: &Context) -> Option<&str> {
// `$CARGO_HOME/bin/rustc(.exe) --version` may attempt installing a rustup toolchain.
// https://github.com/starship/starship/issues/417
//
// To display appropriate versions preventing `rustc` from downloading toolchains, we have to
// check
// 1. `$RUSTUP_TOOLCHAIN`
// 2. The override list from ~/.rustup/settings.toml (like `rustup override list`)
// 3. `rust-toolchain` or `rust-toolchain.toml` in `.` or parent directories
// 4. The `default_toolchain` from ~/.rustup/settings.toml (like `rustup default`)
// 5. `rustup default` (in addition to the above, this also looks at global fallback config files)
// as `rustup` does.
// https://github.com/rust-lang/rustup.rs/tree/eb694fcada7becc5d9d160bf7c623abe84f8971d#override-precedence
//
// Probably we have no other way to know whether any toolchain override is specified for the
// current directory. The following commands also cause toolchain installations.
// - `rustup show`
// - `rustup show active-toolchain`
// - `rustup which`
self.env_toolchain_override
.get_or_init(|| {
let out = env_rustup_toolchain(context)
.or_else(|| {
self.get_rustup_settings(context)
.lookup_override(context.current_dir.as_path())
})
.or_else(|| find_rust_toolchain_file(context))
.or_else(|| {
self.get_rustup_settings(context)
.default_toolchain()
.map(std::string::ToString::to_string)
})
.or_else(|| execute_rustup_default(context));
log::debug!("Environmental toolchain override is {out:?}");
out
})
.as_deref()
}
/// Gets the output of running `rustup rustc --version` with a toolchain
/// specified by `self.get_env_toolchain_override()`
fn get_rustup_rustc_version(&self, context: &Context) -> &RustupRunRustcVersionOutcome {
self.rustup_rustc_output.get_or_init(|| {
let out = if let Some(toolchain) = self.get_env_toolchain_override(context) {
// First try running ~/.rustup/toolchains/<toolchain>/bin/rustc --version
rustup_home()
.map(|rustup_folder| {
rustup_folder
.join("toolchains")
.join(toolchain)
.join("bin")
.join("rustc")
})
.and_then(|rustc| {
log::trace!("Running rustc --version directly with {rustc:?}");
create_command(rustc).map(|mut cmd| {
cmd.arg("--version");
cmd
})
})
.or_else(|_| {
// If that fails, try running rustup rustup run <toolchain> rustc --version
// Depending on the source of the toolchain override, it might not have been a full toolchain name ("stable" or "nightly").
log::trace!("Running rustup {toolchain} rustc --version");
create_command("rustup").map(|mut cmd| {
cmd.args(["run", toolchain, "rustc", "--version"]);
cmd
})
})
.and_then(|mut cmd| cmd.current_dir(&context.current_dir).output())
.map(extract_toolchain_from_rustup_run_rustc_version)
.unwrap_or(RustupRunRustcVersionOutcome::RustupNotWorking)
} else {
RustupRunRustcVersionOutcome::ToolchainUnknown
};
log::debug!("Rustup rustc version is {out:?}");
out
})
}
/// Gets the (version, toolchain) string as returned by `rustc -vV`
fn get_rustc_verbose_version(&self, context: &Context) -> Option<(&str, &str)> {
let toolchain = self.get_rustup_settings(context).default_toolchain();
self.rustc_verbose_output
.get_or_init(|| {
let Output { status, stdout, .. } = create_command("rustc")
.and_then(|mut cmd| {
cmd.args(["-Vv"]).current_dir(&context.current_dir).output()
})
.ok()?;
if !status.success() {
return None;
}
let out =
format_rustc_version_verbose(std::str::from_utf8(&stdout).ok()?, toolchain);
log::debug!("Rustup verbose version is {out:?}");
out
})
.as_ref()
.map(|(x, y)| (&x[..], &y[..]))
}
}
/// Creates a module with the current Rust version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("rust");
let config = RustConfig::try_load(module.config);
let is_rs_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_rs_project {
return None;
}
let rust_env_info = RustToolingEnvironmentInfo::new();
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_module_version(context, &config, &rust_env_info).map(Ok),
"numver" => get_module_numeric_version(context, &config, &rust_env_info).map(Ok),
"toolchain" => get_toolchain_version(context, &config, &rust_env_info).map(Ok),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `rust`:\n{error}");
return None;
}
});
Some(module)
}
fn get_module_version(
context: &Context,
config: &RustConfig,
rust_env_info: &RustToolingEnvironmentInfo,
) -> Option<String> {
type Outcome = RustupRunRustcVersionOutcome;
match rust_env_info.get_rustup_rustc_version(context) {
Outcome::RustcVersion(rustc_version) => {
format_rustc_version(rustc_version, config.version_format)
}
Outcome::RustupNotWorking | Outcome::ToolchainUnknown => {
// If `rustup` can't be executed, or there is no environmental toolchain, we can
// execute `rustc --version` without triggering a toolchain download
format_rustc_version(&execute_rustc_version(context)?, config.version_format)
}
Outcome::ToolchainNotInstalled(name) => Some(name.to_string()),
Outcome::Err => None,
}
}
fn get_module_numeric_version(
context: &Context,
_config: &RustConfig,
rust_env_info: &RustToolingEnvironmentInfo,
) -> Option<String> {
type Outcome = RustupRunRustcVersionOutcome;
match rust_env_info.get_rustup_rustc_version(context) {
Outcome::RustcVersion(version) => {
let release = version.split_whitespace().nth(1).unwrap_or(version);
Some(format_semver(release))
}
Outcome::RustupNotWorking | Outcome::ToolchainUnknown => {
let (numver, _toolchain) = rust_env_info.get_rustc_verbose_version(context)?;
Some(numver.to_string())
}
Outcome::ToolchainNotInstalled(_) | RustupRunRustcVersionOutcome::Err => None,
}
}
fn get_toolchain_version(
context: &Context,
_config: &RustConfig,
rust_env_info: &RustToolingEnvironmentInfo,
) -> Option<String> {
type Outcome = RustupRunRustcVersionOutcome;
let settings_host_triple = rust_env_info
.get_rustup_settings(context)
.default_host_triple();
let default_host_triple = if settings_host_triple.is_none() {
guess_host_triple()
} else {
settings_host_triple
};
match rust_env_info.get_rustup_rustc_version(context) {
Outcome::RustcVersion(_) | Outcome::ToolchainNotInstalled(_) => {
let toolchain_override = rust_env_info
.get_env_toolchain_override(context)
// This match arm should only trigger if the toolchain override
// is not None because of how get_rustup_rustc_version works
.expect("Toolchain override was None: programming error.");
Some(format_toolchain(toolchain_override, default_host_triple))
}
Outcome::RustupNotWorking | Outcome::ToolchainUnknown => {
let (_numver, toolchain) = rust_env_info.get_rustc_verbose_version(context)?;
Some(format_toolchain(toolchain, default_host_triple))
}
Outcome::Err => None,
}
}
fn env_rustup_toolchain(context: &Context) -> Option<String> {
log::trace!("Searching for rustup toolchain in environment.");
let val = context.get_env("RUSTUP_TOOLCHAIN")?;
Some(val.trim().to_owned())
}
fn execute_rustup_default(context: &Context) -> Option<String> {
log::trace!("Searching for toolchain with rustup default");
// `rustup default` output is:
// stable-x86_64-apple-darwin (default)
context
.exec_cmd("rustup", &["default"])?
.stdout
.split_whitespace()
.next()
.map(str::to_owned)
}
fn find_rust_toolchain_file(context: &Context) -> Option<String> {
log::trace!("Searching for toolchain in toolchain file");
// Look for 'rust-toolchain' or 'rust-toolchain.toml' as rustup does.
// for more information:
// https://rust-lang.github.io/rustup/overrides.html#the-toolchain-file
// for the implementation in 'rustup':
// https://github.com/rust-lang/rustup/blob/a45e4cd21748b04472fce51ba29999ee4b62bdec/src/config.rs#L631
#[derive(Deserialize)]
struct OverrideFile {
toolchain: ToolchainSection,
}
#[derive(Deserialize)]
struct ToolchainSection {
channel: Option<String>,
}
fn read_channel(path: &Path, only_toml: bool) -> Option<String> {
let contents = fs::read_to_string(path).ok()?;
match contents.lines().count() {
0 => None,
1 if !only_toml => Some(contents),
_ => {
toml::from_str::<OverrideFile>(&contents)
.ok()?
.toolchain
.channel
}
}
.filter(|c| !c.trim().is_empty())
.map(|c| c.trim().to_owned())
}
if context
.dir_contents()
.is_ok_and(|dir| dir.has_file("rust-toolchain"))
&& let Some(toolchain) = read_channel(Path::new("rust-toolchain"), false)
{
return Some(toolchain);
}
if context
.dir_contents()
.is_ok_and(|dir| dir.has_file("rust-toolchain.toml"))
&& let Some(toolchain) = read_channel(Path::new("rust-toolchain.toml"), true)
{
return Some(toolchain);
}
let mut dir = &*context.current_dir;
loop {
if let Some(toolchain) = read_channel(&dir.join("rust-toolchain"), false) {
return Some(toolchain);
}
if let Some(toolchain) = read_channel(&dir.join("rust-toolchain.toml"), true) {
return Some(toolchain);
}
dir = dir.parent()?;
}
}
fn extract_toolchain_from_rustup_run_rustc_version(output: Output) -> RustupRunRustcVersionOutcome {
if output.status.success() {
if let Ok(output) = String::from_utf8(output.stdout) {
return RustupRunRustcVersionOutcome::RustcVersion(output);
}
} else if let Ok(stderr) = String::from_utf8(output.stderr)
&& stderr.starts_with("error: toolchain '")
&& stderr.ends_with("' is not installed\n")
{
let stderr = stderr
["error: toolchain '".len()..stderr.len() - "' is not installed\n".len()]
.to_owned();
return RustupRunRustcVersionOutcome::ToolchainNotInstalled(stderr);
}
RustupRunRustcVersionOutcome::Err
}
fn execute_rustc_version(context: &Context) -> Option<String> {
context
.exec_cmd("rustc", &["--version"])
.map(|o| o.stdout)
.filter(|s| !s.is_empty())
}
fn format_rustc_version(rustc_version: &str, version_format: &str) -> Option<String> {
let version = rustc_version
// split into ["rustc", "1.34.0", ...]
.split_whitespace()
// get down to "1.34.0"
.nth(1)?;
match VersionFormatter::format_version(version, version_format) {
Ok(formatted) => Some(formatted),
Err(error) => {
log::warn!("Error formatting `rust` version:\n{error}");
Some(format!("v{version}"))
}
}
}
fn format_toolchain(toolchain: &str, default_host_triple: Option<&str>) -> String {
default_host_triple
.map_or(toolchain, |triple| {
toolchain.trim_end_matches(&format!("-{triple}"))
})
.to_owned()
}
fn format_rustc_version_verbose(stdout: &str, toolchain: Option<&str>) -> Option<(String, String)> {
let (mut release, mut host) = (None, None);
for line in stdout.lines() {
if line.starts_with("release: ") {
release = Some(line.trim_start_matches("release: "));
}
if line.starts_with("host: ") {
host = Some(line.trim_start_matches("host: "));
}
}
let (release, host) = (release?, host?);
let version = format_semver(release);
let toolchain = toolchain.map_or_else(|| host.to_string(), ToOwned::to_owned);
Some((version, toolchain))
}
fn format_semver(semver: &str) -> String {
format!("v{}", semver.find('-').map_or(semver, |i| &semver[..i]))
}
#[derive(Debug, PartialEq)]
enum RustupRunRustcVersionOutcome {
RustcVersion(String),
ToolchainNotInstalled(String),
ToolchainUnknown,
RustupNotWorking,
Err,
}
#[derive(Default, Debug, PartialEq, Deserialize)]
struct RustupSettings {
default_host_triple: Option<String>,
default_toolchain: Option<String>,
overrides: HashMap<PathBuf, String>,
version: Option<String>,
}
#[inline]
#[cfg(windows)]
fn strip_dos_path(path: PathBuf) -> PathBuf {
// Use the display version of the path to strip \\?\
let path = path.to_string_lossy();
PathBuf::from(path.strip_prefix(r"\\?\").unwrap_or(&path))
}
#[inline]
#[cfg(not(windows))]
fn strip_dos_path(path: PathBuf) -> PathBuf {
path
}
impl RustupSettings {
fn load(_context: &Context) -> Option<Self> {
let path = rustup_home().ok()?.join("settings.toml");
Self::from_toml_str(&fs::read_to_string(path).ok()?)
}
fn from_toml_str(toml_str: &str) -> Option<Self> {
let settings = toml::from_str::<Self>(toml_str).ok()?;
if settings.version.as_deref() == Some("12") {
Some(settings)
} else {
log::warn!(
r#"Rustup settings version is {:?}, expected "12""#,
settings.version
);
None
}
}
fn default_host_triple(&self) -> Option<&str> {
self.default_host_triple.as_deref()
}
fn default_toolchain(&self) -> Option<&str> {
self.default_toolchain.as_deref()
}
fn lookup_override(&self, cwd: &Path) -> Option<String> {
let cwd = strip_dos_path(cwd.to_owned());
self.overrides
.iter()
.map(|(dir, toolchain)| (strip_dos_path(dir.clone()), toolchain))
.filter(|(dir, _)| cwd.starts_with(dir))
.max_by_key(|(dir, _)| dir.components().count())
.map(|(_, name)| name.clone())
}
}
#[cfg(test)]
mod tests {
use crate::context::{Properties, Shell, Target};
use crate::context_env::Env;
use std::io;
use std::process::{ExitStatus, Output};
use std::sync::LazyLock;
use super::*;
#[test]
fn test_rustup_settings_from_toml_value() {
assert_eq!(
RustupSettings::from_toml_str(
r#"
default_host_triple = "x86_64-unknown-linux-gnu"
default_toolchain = "stable"
version = "12"
[overrides]
"/home/user/src/starship" = "1.40.0-x86_64-unknown-linux-gnu"
"#
),
Some(RustupSettings {
default_host_triple: Some("x86_64-unknown-linux-gnu".to_owned()),
default_toolchain: Some("stable".to_owned()),
overrides: vec![(
"/home/user/src/starship".into(),
"1.40.0-x86_64-unknown-linux-gnu".to_owned(),
)]
.into_iter()
.collect(),
version: Some("12".to_string())
}),
);
// Invalid or missing version key causes a failure
assert_eq!(
RustupSettings::from_toml_str(
r#"
default_host_triple = "x86_64-unknown-linux-gnu"
default_toolchain = "stable"
[overrides]
"/home/user/src/starship" = "1.39.0-x86_64-unknown-linux-gnu"
"#
),
None,
);
}
#[test]
fn test_override_matches_correct_directories() {
let test_settings = RustupSettings::from_toml_str(
r#"
default_host_triple = "x86_64-unknown-linux-gnu"
default_toolchain = "stable"
version = "12"
[overrides]
"/home/user/src/a" = "beta-x86_64-unknown-linux-gnu"
"/home/user/src/b" = "nightly-x86_64-unknown-linux-gnu"
"/home/user/src/b/d c" = "stable-x86_64-pc-windows-msvc"
"#,
)
.unwrap();
static OVERRIDES_CWD_A: &str = "/home/user/src/a/src";
static OVERRIDES_CWD_B: &str = "/home/user/src/b/tests";
static OVERRIDES_CWD_C: &str = "/home/user/src/c/examples";
static OVERRIDES_CWD_D: &str = "/home/user/src/b/d c/spaces";
static OVERRIDES_CWD_E: &str = "/home/user/src/b_and_more";
static OVERRIDES_CWD_F: &str = "/home/user/src/b";
static BETA_TOOLCHAIN: &str = "beta-x86_64-unknown-linux-gnu";
static NIGHTLY_TOOLCHAIN: &str = "nightly-x86_64-unknown-linux-gnu";
static STABLE_TOOLCHAIN: &str = "stable-x86_64-pc-windows-msvc";
assert_eq!(
test_settings.lookup_override(OVERRIDES_CWD_A.as_ref()),
Some(BETA_TOOLCHAIN.to_string())
);
assert_eq!(
test_settings.lookup_override(OVERRIDES_CWD_B.as_ref()),
Some(NIGHTLY_TOOLCHAIN.to_string())
);
assert_eq!(
test_settings.lookup_override(OVERRIDES_CWD_C.as_ref()),
None
);
assert_eq!(
test_settings.lookup_override(OVERRIDES_CWD_D.as_ref()),
Some(STABLE_TOOLCHAIN.to_string())
);
assert_eq!(
test_settings.lookup_override(OVERRIDES_CWD_E.as_ref()),
None
);
assert_eq!(
test_settings.lookup_override(OVERRIDES_CWD_F.as_ref()),
Some(NIGHTLY_TOOLCHAIN.to_string())
);
}
#[test]
#[cfg(windows)]
fn test_extract_toolchain_from_override_with_dospath() {
let test_settings = RustupSettings::from_toml_str(
r#"
default_host_triple = "x86_64-unknown-linux-gnu"
default_toolchain = "stable"
version = "12"
[overrides]
"C:\\src1" = "beta-x86_64-unknown-linux-gnu"
"\\\\?\\C:\\src2" = "beta-x86_64-unknown-linux-gnu"
"#,
)
.unwrap();
static OVERRIDES_CWD_A: &str = r"\\?\C:\src1";
static OVERRIDES_CWD_B: &str = r"C:\src1";
static OVERRIDES_CWD_C: &str = r"\\?\C:\src2";
static OVERRIDES_CWD_D: &str = r"C:\src2";
static BETA_TOOLCHAIN: &str = "beta-x86_64-unknown-linux-gnu";
assert_eq!(
test_settings.lookup_override(OVERRIDES_CWD_A.as_ref()),
Some(BETA_TOOLCHAIN.to_string())
);
assert_eq!(
test_settings.lookup_override(OVERRIDES_CWD_B.as_ref()),
Some(BETA_TOOLCHAIN.to_string())
);
assert_eq!(
test_settings.lookup_override(OVERRIDES_CWD_C.as_ref()),
Some(BETA_TOOLCHAIN.to_string())
);
assert_eq!(
test_settings.lookup_override(OVERRIDES_CWD_D.as_ref()),
Some(BETA_TOOLCHAIN.to_string())
);
}
#[cfg(any(unix, windows))]
#[test]
fn test_extract_toolchain_from_rustup_run_rustc_version() {
#[cfg(unix)]
use std::os::unix::process::ExitStatusExt as _;
#[cfg(windows)]
use std::os::windows::process::ExitStatusExt as _;
static RUSTC_VERSION: LazyLock<Output> = LazyLock::new(|| Output {
status: ExitStatus::from_raw(0),
stdout: b"rustc 1.34.0\n"[..].to_owned(),
stderr: vec![],
});
assert_eq!(
extract_toolchain_from_rustup_run_rustc_version(RUSTC_VERSION.clone()),
RustupRunRustcVersionOutcome::RustcVersion("rustc 1.34.0\n".to_owned()),
);
static TOOLCHAIN_NAME: LazyLock<Output> = LazyLock::new(|| Output {
status: ExitStatus::from_raw(1),
stdout: vec![],
stderr: b"error: toolchain 'channel-triple' is not installed\n"[..].to_owned(),
});
assert_eq!(
extract_toolchain_from_rustup_run_rustc_version(TOOLCHAIN_NAME.clone()),
RustupRunRustcVersionOutcome::ToolchainNotInstalled("channel-triple".to_owned()),
);
static INVALID_STDOUT: LazyLock<Output> = LazyLock::new(|| Output {
status: ExitStatus::from_raw(0),
stdout: b"\xc3\x28"[..].to_owned(),
stderr: vec![],
});
assert_eq!(
extract_toolchain_from_rustup_run_rustc_version(INVALID_STDOUT.clone()),
RustupRunRustcVersionOutcome::Err,
);
static INVALID_STDERR: LazyLock<Output> = LazyLock::new(|| Output {
status: ExitStatus::from_raw(1),
stdout: vec![],
stderr: b"\xc3\x28"[..].to_owned(),
});
assert_eq!(
extract_toolchain_from_rustup_run_rustc_version(INVALID_STDERR.clone()),
RustupRunRustcVersionOutcome::Err,
);
static UNEXPECTED_FORMAT_OF_ERROR: LazyLock<Output> = LazyLock::new(|| Output {
status: ExitStatus::from_raw(1),
stdout: vec![],
stderr: b"error:"[..].to_owned(),
});
assert_eq!(
extract_toolchain_from_rustup_run_rustc_version(UNEXPECTED_FORMAT_OF_ERROR.clone()),
RustupRunRustcVersionOutcome::Err,
);
}
#[test]
fn test_format_rustc_version() {
let config = RustConfig::default();
let rustc_stable = "rustc 1.34.0 (91856ed52 2019-04-10)";
let rustc_beta = "rustc 1.34.0-beta.1 (2bc1d406d 2019-04-10)";
let rustc_nightly = "rustc 1.34.0-nightly (b139669f3 2019-04-10)";
assert_eq!(
format_rustc_version(rustc_nightly, config.version_format),
Some("v1.34.0-nightly".to_string())
);
assert_eq!(
format_rustc_version(rustc_beta, config.version_format),
Some("v1.34.0-beta.1".to_string())
);
assert_eq!(
format_rustc_version(rustc_stable, config.version_format),
Some("v1.34.0".to_string())
);
assert_eq!(
format_rustc_version("rustc 1.34.0", config.version_format),
Some("v1.34.0".to_string())
);
}
#[test]
fn test_find_rust_toolchain_file() -> io::Result<()> {
// `rust-toolchain` with toolchain in one line
let dir = tempfile::tempdir()?;
fs::write(dir.path().join("rust-toolchain"), "1.34.0")?;
let context = Context::new_with_shell_and_path(
Default::default(),
Shell::Unknown,
Target::Main,
dir.path().into(),
dir.path().into(),
Env::default(),
);
assert_eq!(
find_rust_toolchain_file(&context),
Some("1.34.0".to_owned())
);
dir.close()?;
// `rust-toolchain` in toml format
let dir = tempfile::tempdir()?;
fs::write(
dir.path().join("rust-toolchain"),
"[toolchain]\nchannel = \"1.34.0\"",
)?;
let context = Context::new_with_shell_and_path(
Properties::default(),
Shell::Unknown,
Target::Main,
dir.path().into(),
dir.path().into(),
Env::default(),
);
assert_eq!(
find_rust_toolchain_file(&context),
Some("1.34.0".to_owned())
);
dir.close()?;
// `rust-toolchain` in toml format with new lines
let dir = tempfile::tempdir()?;
fs::write(
dir.path().join("rust-toolchain"),
"\n\n[toolchain]\n\n\nchannel = \"1.34.0\"",
)?;
let context = Context::new_with_shell_and_path(
Default::default(),
Shell::Unknown,
Target::Main,
dir.path().into(),
dir.path().into(),
Env::default(),
);
assert_eq!(
find_rust_toolchain_file(&context),
Some("1.34.0".to_owned())
);
dir.close()?;
// `rust-toolchain` in parent directory.
let dir = tempfile::tempdir()?;
let child_dir_path = dir.path().join("child");
fs::create_dir(&child_dir_path)?;
fs::write(
dir.path().join("rust-toolchain"),
"\n\n[toolchain]\n\n\nchannel = \"1.34.0\"",
)?;
let context = Context::new_with_shell_and_path(
Properties::default(),
Shell::Unknown,
Target::Main,
child_dir_path.clone(),
child_dir_path,
Env::default(),
);
assert_eq!(
find_rust_toolchain_file(&context),
Some("1.34.0".to_owned())
);
dir.close()?;
// `rust-toolchain.toml` with toolchain in one line
// This should not work!
// See https://rust-lang.github.io/rustup/overrides.html#the-toolchain-file
let dir = tempfile::tempdir()?;
fs::write(dir.path().join("rust-toolchain.toml"), "1.34.0")?;
let context = Context::new_with_shell_and_path(
Properties::default(),
Shell::Unknown,
Target::Main,
dir.path().into(),
dir.path().into(),
Env::default(),
);
assert_eq!(find_rust_toolchain_file(&context), None);
dir.close()?;
// `rust-toolchain.toml` in toml format
let dir = tempfile::tempdir()?;
fs::write(
dir.path().join("rust-toolchain.toml"),
"[toolchain]\nchannel = \"1.34.0\"",
)?;
let context = Context::new_with_shell_and_path(
Properties::default(),
Shell::Unknown,
Target::Main,
dir.path().into(),
dir.path().into(),
Env::default(),
);
assert_eq!(
find_rust_toolchain_file(&context),
Some("1.34.0".to_owned())
);
dir.close()?;
// `rust-toolchain.toml` in toml format with new lines
let dir = tempfile::tempdir()?;
fs::write(
dir.path().join("rust-toolchain.toml"),
"\n\n[toolchain]\n\n\nchannel = \"1.34.0\"",
)?;
let context = Context::new_with_shell_and_path(
Properties::default(),
Shell::Unknown,
Target::Main,
dir.path().into(),
dir.path().into(),
Env::default(),
);
assert_eq!(
find_rust_toolchain_file(&context),
Some("1.34.0".to_owned())
);
dir.close()?;
// `rust-toolchain.toml` in parent directory.
let dir = tempfile::tempdir()?;
let child_dir_path = dir.path().join("child");
fs::create_dir(&child_dir_path)?;
fs::write(
dir.path().join("rust-toolchain.toml"),
"\n\n[toolchain]\n\n\nchannel = \"1.34.0\"",
)?;
let context = Context::new_with_shell_and_path(
Properties::default(),
Shell::Unknown,
Target::Main,
child_dir_path.clone(),
child_dir_path,
Env::default(),
);
assert_eq!(
find_rust_toolchain_file(&context),
Some("1.34.0".to_owned())
);
dir.close()
}
#[test]
fn test_format_rustc_version_verbose() {
macro_rules! test {
() => {};
(($input:expr, $toolchain:expr) => $expected:expr $(,$($rest:tt)*)?) => {
assert_eq!(
format_rustc_version_verbose($input, $toolchain)
.as_ref()
.map(|(s1, s2)| (&**s1, &**s2)),
$expected,
);
test!($($($rest)*)?);
};
}
static STABLE: &str = r"rustc 1.40.0 (73528e339 2019-12-16)
binary: rustc
commit-hash: 73528e339aae0f17a15ffa49a8ac608f50c6cf14
commit-date: 2019-12-16
host: x86_64-unknown-linux-gnu
release: 1.40.0
LLVM version: 9.0
";
static BETA: &str = r"rustc 1.41.0-beta.1 (eb3f7c2d3 2019-12-17)
binary: rustc
commit-hash: eb3f7c2d3aec576f47eba854cfbd3c1187b8a2a0
commit-date: 2019-12-17
host: x86_64-unknown-linux-gnu
release: 1.41.0-beta.1
LLVM version: 9.0
";
static NIGHTLY: &str = r"rustc 1.42.0-nightly (da3629b05 2019-12-29)
binary: rustc
commit-hash: da3629b05f8f1b425a738bfe9fe9aedd47c5417a
commit-date: 2019-12-29
host: x86_64-unknown-linux-gnu
release: 1.42.0-nightly
LLVM version: 9.0
";
test!(
(STABLE, None) => Some(("v1.40.0", "x86_64-unknown-linux-gnu")),
(STABLE, Some("stable")) => Some(("v1.40.0", "stable")),
(BETA, None) => Some(("v1.41.0", "x86_64-unknown-linux-gnu")),
(BETA, Some("beta")) => Some(("v1.41.0", "beta")),
(NIGHTLY, None) => Some(("v1.42.0", "x86_64-unknown-linux-gnu")),
(NIGHTLY, Some("nightly")) => Some(("v1.42.0", "nightly")),
("", None) => None,
("", Some("stable")) => None,
);
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/aws.rs | src/modules/aws.rs | use std::cell::OnceCell;
use std::collections::HashMap;
use std::path::PathBuf;
use std::str::FromStr;
use chrono::DateTime;
use ini::Ini;
use serde_json as json;
use sha1::{Digest, Sha1};
use super::{Context, Module, ModuleConfig};
use crate::configs::aws::AwsConfig;
use crate::formatter::StringFormatter;
use crate::utils::render_time;
type Profile = String;
type Region = String;
type AwsConfigFile = OnceCell<Option<Ini>>;
type AwsCredsFile = OnceCell<Option<Ini>>;
fn get_credentials_file_path(context: &Context) -> Option<PathBuf> {
context
.get_env("AWS_SHARED_CREDENTIALS_FILE")
.or_else(|| context.get_env("AWS_CREDENTIALS_FILE"))
.and_then(|path| PathBuf::from_str(&path).ok())
.or_else(|| {
let mut home = context.get_home()?;
home.push(".aws/credentials");
Some(home)
})
}
fn get_config_file_path(context: &Context) -> Option<PathBuf> {
context
.get_env("AWS_CONFIG_FILE")
.and_then(|path| PathBuf::from_str(&path).ok())
.or_else(|| {
let mut home = context.get_home()?;
home.push(".aws/config");
Some(home)
})
}
// Initialize the AWS config file once
fn get_config<'a>(context: &Context, config: &'a OnceCell<Option<Ini>>) -> Option<&'a Ini> {
config
.get_or_init(|| {
let path = get_config_file_path(context)?;
Ini::load_from_file(path).ok()
})
.as_ref()
}
// Initialize the AWS credentials file once
fn get_creds<'a>(context: &Context, config: &'a OnceCell<Option<Ini>>) -> Option<&'a Ini> {
config
.get_or_init(|| {
let path = get_credentials_file_path(context)?;
Ini::load_from_file(path).ok()
})
.as_ref()
}
// Get the section for a given profile name in the config file.
fn get_profile_config<'a>(
config: &'a Ini,
profile: Option<&Profile>,
) -> Option<&'a ini::Properties> {
match profile {
Some(profile) => config.section(Some(format!("profile {profile}"))),
None => config.section(Some("default")),
}
}
// Get the section for a given profile name in the credentials file.
fn get_profile_creds<'a>(
config: &'a Ini,
profile: Option<&Profile>,
) -> Option<&'a ini::Properties> {
match profile {
None => config.section(Some("default")),
_ => config.section(profile),
}
}
fn get_aws_region_from_config(
context: &Context,
aws_profile: &Option<Profile>,
aws_config: &AwsConfigFile,
) -> Option<Region> {
let config = get_config(context, aws_config)?;
let section = get_profile_config(config, aws_profile.as_ref())?;
section.get("region").map(std::borrow::ToOwned::to_owned)
}
fn get_aws_profile_and_region(
context: &Context,
aws_config: &AwsConfigFile,
) -> (Option<Profile>, Option<Region>) {
let profile_env_vars = [
"AWSU_PROFILE",
"AWS_VAULT",
"AWSUME_PROFILE",
"AWS_PROFILE",
"AWS_SSO_PROFILE",
];
let region_env_vars = ["AWS_REGION", "AWS_DEFAULT_REGION"];
let profile = profile_env_vars
.iter()
.find_map(|env_var| context.get_env(env_var));
let region = region_env_vars
.iter()
.find_map(|env_var| context.get_env(env_var));
match (profile, region) {
(Some(p), Some(r)) => (Some(p), Some(r)),
(None, Some(r)) => (None, Some(r)),
(Some(p), None) => (
Some(p.clone()),
get_aws_region_from_config(context, &Some(p), aws_config),
),
(None, None) => (None, get_aws_region_from_config(context, &None, aws_config)),
}
}
fn get_credentials_duration(
context: &Context,
aws_profile: Option<&Profile>,
aws_config: &AwsConfigFile,
aws_creds: &AwsCredsFile,
) -> Option<i64> {
let expiration_env_vars = [
"AWS_CREDENTIAL_EXPIRATION",
"AWS_SESSION_EXPIRATION",
"AWSUME_EXPIRATION",
];
let expiration_date = if let Some(expiration_date) = expiration_env_vars
.into_iter()
.find_map(|env_var| context.get_env(env_var))
{
// get expiration from environment variables
chrono::DateTime::parse_from_rfc3339(&expiration_date).ok()
} else if let Some(section) =
get_creds(context, aws_creds).and_then(|creds| get_profile_creds(creds, aws_profile))
{
// get expiration from credentials file
let expiration_keys = ["expiration", "x_security_token_expires"];
expiration_keys
.iter()
.find_map(|expiration_key| section.get(expiration_key))
.and_then(|expiration| DateTime::parse_from_rfc3339(expiration).ok())
} else {
// get expiration from cached SSO credentials
let config = get_config(context, aws_config)?;
let section = get_profile_config(config, aws_profile)?;
let start_url = section.get("sso_start_url")?;
// https://github.com/boto/botocore/blob/d7ff05fac5bf597246f9e9e3fac8f22d35b02e64/botocore/utils.py#L3350
let cache_key = crate::utils::encode_to_hex(&Sha1::digest(start_url.as_bytes()));
// https://github.com/aws/aws-cli/blob/b3421dcdd443db95999364e94266c0337b45cc43/awscli/customizations/sso/utils.py#L89
let mut sso_cred_path = context.get_home()?;
sso_cred_path.push(format!(".aws/sso/cache/{cache_key}.json"));
let sso_cred_json: json::Value =
json::from_str(&crate::utils::read_file(&sso_cred_path).ok()?).ok()?;
let expires_at = sso_cred_json.get("expiresAt")?.as_str();
DateTime::parse_from_rfc3339(expires_at?).ok()
}?;
Some(expiration_date.timestamp() - chrono::Local::now().timestamp())
}
fn alias_name(name: Option<String>, aliases: &HashMap<String, &str>) -> Option<String> {
name.as_ref()
.and_then(|n| aliases.get(n))
.map(|&a| a.to_string())
.or(name)
}
fn has_credential_process_or_sso(
context: &Context,
aws_profile: Option<&Profile>,
aws_config: &AwsConfigFile,
aws_creds: &AwsCredsFile,
) -> Option<bool> {
let config = get_config(context, aws_config)?;
let credentials = get_creds(context, aws_creds);
let empty_section = ini::Properties::new();
// We use the aws_profile here because `get_profile_config()` treats None
// as "special" and falls back to the "[default]"; otherwise this tries
// to look up "[profile default]" which doesn't exist
let config_section = get_profile_config(config, aws_profile).or(Some(&empty_section))?;
let credential_section = match credentials {
Some(credentials) => get_profile_creds(credentials, aws_profile),
None => None,
};
Some(
config_section.contains_key("credential_process")
|| config_section.contains_key("sso_session")
|| config_section.contains_key("sso_start_url")
|| credential_section?.contains_key("credential_process")
|| credential_section?.contains_key("sso_start_url"),
)
}
fn has_defined_credentials(
context: &Context,
aws_profile: Option<&Profile>,
aws_creds: &AwsCredsFile,
) -> Option<bool> {
let valid_env_vars = [
"AWS_ACCESS_KEY_ID",
"AWS_SECRET_ACCESS_KEY",
"AWS_SESSION_TOKEN",
];
// accept if set through environment variable
if valid_env_vars
.iter()
.any(|env_var| context.get_env(env_var).is_some())
{
return Some(true);
}
let creds = get_creds(context, aws_creds)?;
let section = get_profile_creds(creds, aws_profile)?;
Some(section.contains_key("aws_access_key_id"))
}
// https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html#cli-configure-files-settings
fn has_source_profile(
context: &Context,
aws_profile: Option<&Profile>,
aws_config: &AwsConfigFile,
aws_creds: &AwsCredsFile,
) -> Option<bool> {
let config = get_config(context, aws_config)?;
let config_section = get_profile_config(config, aws_profile)?;
let source_profile = config_section
.get("source_profile")
.map(std::borrow::ToOwned::to_owned);
let has_credential_process =
has_credential_process_or_sso(context, source_profile.as_ref(), aws_config, aws_creds)
.unwrap_or(false);
let has_credentials =
has_defined_credentials(context, source_profile.as_ref(), aws_creds).unwrap_or(false);
Some(has_credential_process || has_credentials)
}
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("aws");
let config: AwsConfig = AwsConfig::try_load(module.config);
let aws_config = OnceCell::new();
let aws_creds = OnceCell::new();
let (aws_profile, aws_region) = get_aws_profile_and_region(context, &aws_config);
if aws_profile.is_none() && aws_region.is_none() {
return None;
}
// only display in the presence of credential_process, source_profile or valid credentials
if !config.force_display
&& !has_credential_process_or_sso(context, aws_profile.as_ref(), &aws_config, &aws_creds)
.unwrap_or(false)
&& !has_source_profile(context, aws_profile.as_ref(), &aws_config, &aws_creds)
.unwrap_or(false)
&& !has_defined_credentials(context, aws_profile.as_ref(), &aws_creds).unwrap_or(false)
{
return None;
}
let duration = {
get_credentials_duration(context, aws_profile.as_ref(), &aws_config, &aws_creds).map(
|duration| {
if duration > 0 {
render_time((duration * 1000) as u128, false)
} else {
config.expiration_symbol.to_string()
}
},
)
};
let mapped_region = alias_name(aws_region, &config.region_aliases);
let mapped_profile = alias_name(aws_profile, &config.profile_aliases);
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 {
"profile" => mapped_profile.as_ref().map(Ok),
"region" => mapped_region.as_ref().map(Ok),
"duration" => duration.as_ref().map(Ok),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `aws`: \n{error}");
return None;
}
});
Some(module)
}
#[cfg(test)]
mod tests {
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
use std::fs::{File, create_dir};
use std::io::{self, Write};
#[test]
#[ignore]
fn no_region_set() {
let actual = ModuleRenderer::new("aws").collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn region_set() -> io::Result<()> {
let (module_renderer, dir) = ModuleRenderer::new_with_home("aws")?;
let actual = module_renderer
.env("AWS_REGION", "ap-northeast-2")
.env("AWS_ACCESS_KEY_ID", "dummy")
.collect();
let expected = Some(format!(
"on {}",
Color::Yellow.bold().paint("☁️ (ap-northeast-2) ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn region_set_with_alias() -> io::Result<()> {
let (module_renderer, dir) = ModuleRenderer::new_with_home("aws")?;
let actual = module_renderer
.env("AWS_REGION", "ap-southeast-2")
.env("AWS_ACCESS_KEY_ID", "dummy")
.config(toml::toml! {
[aws.region_aliases]
ap-southeast-2 = "au"
})
.collect();
let expected = Some(format!("on {}", Color::Yellow.bold().paint("☁️ (au) ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn default_region_set() -> io::Result<()> {
let (module_renderer, dir) = ModuleRenderer::new_with_home("aws")?;
let actual = module_renderer
.env("AWS_REGION", "ap-northeast-2")
.env("AWS_DEFAULT_REGION", "ap-northeast-1")
.env("AWS_ACCESS_KEY_ID", "dummy")
.collect();
let expected = Some(format!(
"on {}",
Color::Yellow.bold().paint("☁️ (ap-northeast-2) ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn profile_set() {
let actual = ModuleRenderer::new("aws")
.env("AWS_PROFILE", "astronauts")
.env("AWS_ACCESS_KEY_ID", "dummy")
.collect();
let expected = Some(format!(
"on {}",
Color::Yellow.bold().paint("☁️ astronauts ")
));
assert_eq!(expected, actual);
}
#[test]
fn profile_set_from_aws_vault() {
let actual = ModuleRenderer::new("aws")
.env("AWS_VAULT", "astronauts-vault")
.env("AWS_PROFILE", "astronauts-profile")
.env("AWS_ACCESS_KEY_ID", "dummy")
.collect();
let expected = Some(format!(
"on {}",
Color::Yellow.bold().paint("☁️ astronauts-vault ")
));
assert_eq!(expected, actual);
}
#[test]
fn profile_set_from_awsu() {
let actual = ModuleRenderer::new("aws")
.env("AWSU_PROFILE", "astronauts-awsu")
.env("AWS_PROFILE", "astronauts-profile")
.env("AWS_ACCESS_KEY_ID", "dummy")
.collect();
let expected = Some(format!(
"on {}",
Color::Yellow.bold().paint("☁️ astronauts-awsu ")
));
assert_eq!(expected, actual);
}
#[test]
fn profile_set_from_awsume() {
let actual = ModuleRenderer::new("aws")
.env("AWSUME_PROFILE", "astronauts-awsume")
.env("AWS_PROFILE", "astronauts-profile")
.env("AWS_ACCESS_KEY_ID", "dummy")
.collect();
let expected = Some(format!(
"on {}",
Color::Yellow.bold().paint("☁️ astronauts-awsume ")
));
assert_eq!(expected, actual);
}
#[test]
fn profile_set_from_awsssocli() {
let actual = ModuleRenderer::new("aws")
.env("AWS_SSO_PROFILE", "astronauts-awsssocli")
.env("AWS_ACCESS_KEY_ID", "dummy")
.collect();
let expected = Some(format!(
"on {}",
Color::Yellow.bold().paint("☁️ astronauts-awsssocli ")
));
assert_eq!(expected, actual);
}
#[test]
fn profile_and_region_set() {
let actual = ModuleRenderer::new("aws")
.env("AWS_PROFILE", "astronauts")
.env("AWS_REGION", "ap-northeast-2")
.env("AWS_ACCESS_KEY_ID", "dummy")
.collect();
let expected = Some(format!(
"on {}",
Color::Yellow
.bold()
.paint("☁️ astronauts (ap-northeast-2) ")
));
assert_eq!(expected, actual);
}
#[test]
fn profile_set_with_alias() {
let actual = ModuleRenderer::new("aws")
.env("AWS_PROFILE", "CORPORATION-CORP_astronauts_ACCESS_GROUP")
.env("AWS_REGION", "ap-northeast-2")
.env("AWS_ACCESS_KEY_ID", "dummy")
.config(toml::toml! {
[aws.profile_aliases]
CORPORATION-CORP_astronauts_ACCESS_GROUP = "astro"
})
.collect();
let expected = Some(format!(
"on {}",
Color::Yellow.bold().paint("☁️ astro (ap-northeast-2) ")
));
assert_eq!(expected, actual);
}
#[test]
fn region_and_profile_both_set_with_alias() {
let actual = ModuleRenderer::new("aws")
.env("AWS_PROFILE", "CORPORATION-CORP_astronauts_ACCESS_GROUP")
.env("AWS_REGION", "ap-southeast-2")
.env("AWS_ACCESS_KEY_ID", "dummy")
.config(toml::toml! {
[aws.profile_aliases]
CORPORATION-CORP_astronauts_ACCESS_GROUP = "astro"
[aws.region_aliases]
ap-southeast-2 = "au"
})
.collect();
let expected = Some(format!(
"on {}",
Color::Yellow.bold().paint("☁️ astro (au) ")
));
assert_eq!(expected, actual);
}
#[test]
fn credentials_file_is_ignored_when_is_directory() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let creds_path = dir.path().join("credentials");
create_dir(&creds_path)?;
let config_path = dir.path().join("config");
File::create(&config_path)?.sync_all()?;
assert!(
ModuleRenderer::new("aws")
.env(
"AWS_SHARED_CREDENTIALS_FILE",
creds_path.to_string_lossy().as_ref(),
)
.env("AWS_CONFIG_FILE", config_path.to_string_lossy().as_ref())
.collect()
.is_none()
);
dir.close()
}
#[test]
fn config_file_path_is_ignored_when_is_directory() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let config_path = dir.path().join("config");
create_dir(&config_path)?;
let creds_path = dir.path().join("credentials");
File::create(&creds_path)?.sync_all()?;
assert!(
ModuleRenderer::new("aws")
.env("AWS_CONFIG_FILE", config_path.to_string_lossy().as_ref())
.env(
"AWS_SHARED_CREDENTIALS_FILE",
creds_path.to_string_lossy().as_ref(),
)
.collect()
.is_none()
);
dir.close()
}
#[test]
fn default_profile_set() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let config_path = dir.path().join("config");
let mut file = File::create(&config_path)?;
file.write_all(
"[default]
region = us-east-1
credential_process = /opt/bin/awscreds-retriever
[profile astronauts]
region = us-east-2
"
.as_bytes(),
)?;
let actual = ModuleRenderer::new("aws")
.env("AWS_CONFIG_FILE", config_path.to_string_lossy().as_ref())
.collect();
let expected = Some(format!(
"on {}",
Color::Yellow.bold().paint("☁️ (us-east-1) ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn profile_and_config_set() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let config_path = dir.path().join("config");
let mut file = File::create(&config_path)?;
file.write_all(
"[default]
region = us-east-1
[profile astronauts]
region = us-east-2
credential_process = /opt/bin/awscreds-retriever
"
.as_bytes(),
)?;
let actual = ModuleRenderer::new("aws")
.env("AWS_CONFIG_FILE", config_path.to_string_lossy().as_ref())
.env("AWS_PROFILE", "astronauts")
.config(toml::toml! {
[aws]
})
.collect();
let expected = Some(format!(
"on {}",
Color::Yellow.bold().paint("☁️ astronauts (us-east-2) ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn profile_and_region_set_with_display_all() {
let actual = ModuleRenderer::new("aws")
.env("AWS_PROFILE", "astronauts")
.env("AWS_REGION", "ap-northeast-1")
.env("AWS_ACCESS_KEY_ID", "dummy")
.collect();
let expected = Some(format!(
"on {}",
Color::Yellow
.bold()
.paint("☁️ astronauts (ap-northeast-1) ")
));
assert_eq!(expected, actual);
}
#[test]
fn profile_set_with_display_all() {
let actual = ModuleRenderer::new("aws")
.env("AWS_PROFILE", "astronauts")
.env("AWS_ACCESS_KEY_ID", "dummy")
.collect();
let expected = Some(format!(
"on {}",
Color::Yellow.bold().paint("☁️ astronauts ")
));
assert_eq!(expected, actual);
}
#[test]
fn region_set_with_display_all() -> io::Result<()> {
let (module_renderer, dir) = ModuleRenderer::new_with_home("aws")?;
let actual = module_renderer
.env("AWS_REGION", "ap-northeast-1")
.env("AWS_ACCESS_KEY_ID", "dummy")
.collect();
let expected = Some(format!(
"on {}",
Color::Yellow.bold().paint("☁️ (ap-northeast-1) ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn profile_and_region_set_with_display_region() {
let actual = ModuleRenderer::new("aws")
.env("AWS_PROFILE", "astronauts")
.env("AWS_DEFAULT_REGION", "ap-northeast-1")
.env("AWS_ACCESS_KEY_ID", "dummy")
.config(toml::toml! {
[aws]
format = "on [$symbol$region]($style) "
})
.collect();
let expected = Some(format!(
"on {} ",
Color::Yellow.bold().paint("☁️ ap-northeast-1")
));
assert_eq!(expected, actual);
}
#[test]
fn profile_and_region_set_with_display_profile() {
let actual = ModuleRenderer::new("aws")
.env("AWS_PROFILE", "astronauts")
.env("AWS_REGION", "ap-northeast-1")
.env("AWS_ACCESS_KEY_ID", "dummy")
.config(toml::toml! {
[aws]
format = "on [$symbol$profile]($style) "
})
.collect();
let expected = Some(format!(
"on {} ",
Color::Yellow.bold().paint("☁️ astronauts")
));
assert_eq!(expected, actual);
}
#[test]
fn region_set_with_display_profile() {
let actual = ModuleRenderer::new("aws")
.env("AWS_REGION", "ap-northeast-1")
.env("AWS_ACCESS_KEY_ID", "dummy")
.config(toml::toml! {
[aws]
format = "on [$symbol$profile]($style) "
})
.collect();
let expected = Some(format!("on {} ", Color::Yellow.bold().paint("☁️ ")));
assert_eq!(expected, actual);
}
#[test]
fn expiration_date_set() {
use chrono::{DateTime, SecondsFormat, Utc};
let expiration_env_vars = ["AWS_SESSION_EXPIRATION", "AWS_CREDENTIAL_EXPIRATION"];
for env_var in expiration_env_vars {
let now_plus_half_hour: DateTime<Utc> =
DateTime::from_timestamp(chrono::Local::now().timestamp() + 1800, 0).unwrap();
let actual = ModuleRenderer::new("aws")
.env("AWS_PROFILE", "astronauts")
.env("AWS_REGION", "ap-northeast-2")
.env("AWS_ACCESS_KEY_ID", "dummy")
.env(
env_var,
now_plus_half_hour.to_rfc3339_opts(SecondsFormat::Secs, true),
)
.collect();
let possible_values = [
"30m2s", "30m1s", "30m0s", "29m59s", "29m58s", "29m57s", "29m56s", "29m55s",
];
let possible_values = possible_values.map(|duration| {
let segment_colored = format!("☁️ astronauts (ap-northeast-2) [{duration}] ");
Some(format!(
"on {}",
Color::Yellow.bold().paint(segment_colored)
))
});
assert!(
possible_values.contains(&actual),
"time is not in range: {actual:?}"
);
}
}
#[test]
fn expiration_date_set_from_file() -> io::Result<()> {
use chrono::{DateTime, Utc};
let dir = tempfile::tempdir()?;
let credentials_path = dir.path().join("credentials");
let mut file = File::create(&credentials_path)?;
let now_plus_half_hour: DateTime<Utc> =
DateTime::from_timestamp(chrono::Local::now().timestamp() + 1800, 0).unwrap();
let expiration_date = now_plus_half_hour.to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
let expiration_keys = ["expiration", "x_security_token_expires"];
for key in expiration_keys {
file.write_all(
format!(
"[astronauts]
aws_access_key_id=dummy
aws_secret_access_key=dummy
{key}={expiration_date}
"
)
.as_bytes(),
)
.unwrap();
let credentials_env_vars = ["AWS_SHARED_CREDENTIALS_FILE", "AWS_CREDENTIALS_FILE"];
for env_var in credentials_env_vars {
let actual = ModuleRenderer::new("aws")
.env("AWS_PROFILE", "astronauts")
.env("AWS_REGION", "ap-northeast-2")
.env(env_var, credentials_path.to_string_lossy().as_ref())
.collect();
// In principle, "30m" should be correct. However, bad luck in scheduling
// on shared runners may delay it.
let possible_values = [
"30m2s", "30m1s", "30m0s", "29m59s", "29m58s", "29m57s", "29m56s", "29m55s",
];
let possible_values = possible_values.map(|duration| {
let segment_colored = format!("☁️ astronauts (ap-northeast-2) [{duration}] ");
Some(format!(
"on {}",
Color::Yellow.bold().paint(segment_colored)
))
});
assert!(
possible_values.contains(&actual),
"time is not in range: {actual:?}"
);
}
}
dir.close()
}
#[test]
fn profile_and_region_set_show_duration() {
let actual = ModuleRenderer::new("aws")
.env("AWS_PROFILE", "astronauts")
.env("AWS_REGION", "ap-northeast-2")
.env("AWS_ACCESS_KEY_ID", "dummy")
.collect();
let expected = Some(format!(
"on {}",
Color::Yellow
.bold()
.paint("☁️ astronauts (ap-northeast-2) ")
));
assert_eq!(expected, actual);
}
#[test]
fn expiration_date_set_expired() {
use chrono::{DateTime, SecondsFormat, Utc};
let now: DateTime<Utc> =
DateTime::from_timestamp(chrono::Local::now().timestamp() - 1800, 0).unwrap();
let symbol = "!!!";
let actual = ModuleRenderer::new("aws")
.config(toml::toml! {
[aws]
expiration_symbol = symbol
})
.env("AWS_PROFILE", "astronauts")
.env("AWS_REGION", "ap-northeast-2")
.env("AWS_ACCESS_KEY_ID", "dummy")
.env(
"AWS_SESSION_EXPIRATION",
now.to_rfc3339_opts(SecondsFormat::Secs, true),
)
.collect();
let expected = Some(format!(
"on {}",
Color::Yellow
.bold()
.paint(format!("☁️ astronauts (ap-northeast-2) [{symbol}] "))
));
assert_eq!(expected, actual);
}
#[test]
#[ignore]
fn region_not_set_with_display_region() {
let actual = ModuleRenderer::new("aws")
.config(toml::toml! {
[aws]
format = "on [$symbol$region]($style) "
})
.collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn missing_any_credentials() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let credential_path = dir.path().join("credentials");
File::create(&credential_path)?;
let config_path = dir.path().join("config");
let mut config_file = File::create(&config_path)?;
config_file.write_all(
"[default]
region = us-east-1
output = json
[profile astronauts]
region = us-east-2
"
.as_bytes(),
)?;
let actual = ModuleRenderer::new("aws")
.env("AWS_CONFIG_FILE", config_path.to_string_lossy().as_ref())
.env(
"AWS_CREDENTIALS_FILE",
credential_path.to_string_lossy().as_ref(),
)
.collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn missing_any_credentials_but_display_empty() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let config_path = dir.path().join("config");
let mut file = File::create(&config_path)?;
file.write_all(
"[profile astronauts]
region = us-east-2
"
.as_bytes(),
)?;
let actual = ModuleRenderer::new("aws")
.config(toml::toml! {
[aws]
force_display = true
})
.env("AWS_CONFIG_FILE", config_path.to_string_lossy().as_ref())
.env("AWS_PROFILE", "astronauts")
.collect();
let expected = Some(format!(
"on {}",
Color::Yellow.bold().paint("☁️ astronauts (us-east-2) ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn access_key_credential_set() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let credentials_path = dir.path().join("credentials");
let mut file = File::create(&credentials_path)?;
file.write_all(
"[astronauts]
aws_access_key_id=dummy
aws_secret_access_key=dummy
"
.as_bytes(),
)?;
let actual = ModuleRenderer::new("aws")
.env("AWS_PROFILE", "astronauts")
.env("AWS_REGION", "ap-northeast-2")
.env(
"AWS_SHARED_CREDENTIALS_FILE",
credentials_path.to_string_lossy().as_ref(),
)
.collect();
let expected = Some(format!(
"on {}",
Color::Yellow
.bold()
.paint("☁️ astronauts (ap-northeast-2) ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn credential_process_set() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let config_path = dir.path().join("config");
let mut file = File::create(&config_path)?;
file.write_all(
"[default]
region = ap-northeast-2
credential_process = /opt/bin/awscreds-retriever
"
.as_bytes(),
)?;
let actual = ModuleRenderer::new("aws")
.env("AWS_CONFIG_FILE", config_path.to_string_lossy().as_ref())
.collect();
let expected = Some(format!(
"on {}",
Color::Yellow.bold().paint("☁️ (ap-northeast-2) ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn credential_process_set_in_credentials() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let config_path = dir.path().join("config");
let credential_path = dir.path().join("credentials");
let mut file = File::create(&config_path)?;
file.write_all(
"[default]
region = ap-northeast-2
"
.as_bytes(),
)?;
let mut file = File::create(&credential_path)?;
file.write_all(
"[default]
credential_process = /opt/bin/awscreds-for-tests
"
.as_bytes(),
)?;
let actual = ModuleRenderer::new("aws")
.env("AWS_CONFIG_FILE", config_path.to_string_lossy().as_ref())
.env(
"AWS_CREDENTIALS_FILE",
credential_path.to_string_lossy().as_ref(),
)
.collect();
let expected = Some(format!(
"on {}",
Color::Yellow.bold().paint("☁️ (ap-northeast-2) ")
));
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/typst.rs | src/modules/typst.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::typst::TypstConfig;
use crate::formatter::{StringFormatter, VersionFormatter};
/// Creates a module with the current Typst version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("typst");
let config = TypstConfig::try_load(module.config);
let is_typst_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_typst_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 = get_typst_config(context)?;
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 `typst`:\n{error}");
return None;
}
});
Some(module)
}
fn get_typst_config(context: &Context) -> Option<String> {
context
.exec_cmd("typst", &["--version"])?
.stdout
.trim()
.strip_prefix("typst ")
.and_then(|version| version.split_whitespace().next().map(ToOwned::to_owned))
}
#[cfg(test)]
mod tests {
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
use std::fs::File;
use std::io;
#[test]
fn read_typst_not_present() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("typst").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn read_typst_present() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("test.typ"))?.sync_all()?;
let actual = ModuleRenderer::new("typst").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Rgb(0, 147, 167).bold().paint("t v0.10 ")
));
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/sudo.rs | src/modules/sudo.rs | use std::env;
use super::{Context, Module, ModuleConfig};
use crate::configs::sudo::SudoConfig;
use crate::formatter::StringFormatter;
/// Creates a module with sudo credential cache status
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("sudo");
let config = SudoConfig::try_load(module.config);
if config.disabled {
return None;
}
if !config.allow_windows && env::consts::FAMILY == "windows" {
return None;
}
let is_sudo_cached = context.exec_cmd("sudo", &["-n", "true"]).is_some();
if !is_sudo_cached {
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,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `sudo`:\n{error}");
return None;
}
});
Some(module)
}
#[cfg(test)]
mod tests {
use crate::{test::ModuleRenderer, utils::CommandOutput};
use nu_ansi_term::Color;
#[test]
fn test_sudo_not_cached() {
let actual = ModuleRenderer::new("sudo")
.cmd("sudo -n true", None)
.config(toml::toml! {
[sudo]
disabled = false
allow_windows = true
})
.collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn test_sudo_cached() {
let actual = ModuleRenderer::new("sudo")
.cmd(
"sudo -n true",
Some(CommandOutput {
stdout: String::new(),
stderr: String::new(),
}),
)
.config(toml::toml! {
[sudo]
disabled = false
allow_windows = true
})
.collect();
let expected = Some(format!("{}", Color::Blue.bold().paint("as 🧙 ")));
assert_eq!(expected, actual);
}
#[test]
#[cfg(windows)]
fn test_allow_windows_disabled_blocks_windows() {
let actual = ModuleRenderer::new("sudo")
.cmd(
"sudo -n true",
Some(CommandOutput {
stdout: String::new(),
stderr: String::new(),
}),
)
.config(toml::toml! {
[sudo]
disabled = false
allow_windows = false
})
.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/fill.rs | src/modules/fill.rs | use super::{Context, Module};
use crate::config::{ModuleConfig, parse_style_string};
use crate::configs::fill::FillConfig;
use crate::segment::Segment;
/// Creates a module that fills the any extra space on the line.
///
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("fill");
let config: FillConfig = FillConfig::try_load(module.config);
if config.disabled {
return None;
}
let style = parse_style_string(config.style, Some(context));
module.set_segments(vec![Segment::fill(style, config.symbol)]);
Some(module)
}
#[cfg(test)]
mod tests {
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
#[test]
fn basic() {
let actual = ModuleRenderer::new("fill")
.config(toml::toml! {
[fill]
style = "bold green"
symbol = "*-"
})
.collect();
let expected = Some(format!("{}", Color::Green.bold().paint("*-")));
assert_eq!(expected, actual);
}
#[test]
fn module_disabled() {
let actual = ModuleRenderer::new("fill")
.config(toml::toml! {
[fill]
disabled = true
})
.collect();
let expected = Option::<String>::None;
assert_eq!(expected, actual);
}
#[test]
fn module_enabled() {
let actual = ModuleRenderer::new("fill")
.config(toml::toml! {
[fill]
disabled = false
})
.collect();
let expected = Some(format!("{}", Color::Black.bold().paint(".")));
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/cc.rs | src/modules/cc.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::c::{CConfig, CConfigMarker};
use crate::configs::cc::CcConfig;
use crate::configs::cpp::{CppConfig, CppConfigMarker};
use crate::formatter::StringFormatter;
use crate::formatter::VersionFormatter;
use crate::segment::Segment;
use semver::Version;
use std::borrow::Cow;
use std::ops::Deref;
use std::sync::LazyLock;
#[derive(Clone, Copy)]
pub enum Lang {
C,
Cpp,
}
fn is_cc_project<T>(config: &CcConfig<T>, context: &Context) -> Option<bool> {
Some(
context
.try_begin_scan()?
.set_extensions(&config.detect_extensions)
.set_files(&config.detect_files)
.set_folders(&config.detect_folders)
.is_match(),
)
}
fn parse_module<T>(
context: &Context,
module: &mut Module,
config: CcConfig<T>,
compilers: [(&str, &str); 2],
) -> Result<Vec<Segment>, crate::formatter::string_formatter::StringFormatterError> {
StringFormatter::new(config.format).and_then(|formatter| {
let cc_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 cc_compiler_info = &cc_compiler_info.deref().as_ref()?.stdout;
let cc_compiler =
compilers
.iter()
.find_map(|(compiler_name, compiler_hint)| {
cc_compiler_info
.contains(compiler_hint)
.then_some(*compiler_name)
})?;
Some(Ok(Cow::Borrowed(cc_compiler)))
}
"version" => {
let cc_compiler_info = &cc_compiler_info.deref().as_ref()?.stdout;
VersionFormatter::format_module_version(
module.get_name(),
cc_compiler_info
.split_whitespace()
.find(|word| Version::parse(word).is_ok())?,
config.version_format,
)
.map(Cow::Owned)
.map(Ok)
}
_ => None,
})
.parse(None, Some(context))
})
}
fn create_module<'a, T>(
context: &'a Context,
lang: &str,
compilers: [(&str, &str); 2],
mut module: Module<'a>,
config: CcConfig<T>,
) -> Option<Module<'a>> {
if config.disabled {
return None;
}
if !is_cc_project(&config, context)? {
return None;
}
let parsed = parse_module(context, &mut module, config, compilers);
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `cc` for `lang: {lang}` :\n{error}");
return None;
}
});
Some(module)
}
pub fn module<'a>(context: &'a Context, lang: Lang) -> Option<Module<'a>> {
match lang {
Lang::C => {
let lang = "c";
let compilers = [("clang", "clang"), ("gcc", "Free Software Foundation")];
let module = context.new_module(lang);
let config = CConfig::try_load(module.config);
create_module::<CConfigMarker>(context, lang, compilers, module, config)
}
Lang::Cpp => {
let lang = "cpp";
let compilers = [("clang++", "clang"), ("g++", "Free Software Foundation")];
let module = context.new_module(lang);
let config = CppConfig::try_load(module.config);
create_module::<CppConfigMarker>(context, lang, compilers, module, config)
}
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/guix_shell.rs | src/modules/guix_shell.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::guix_shell::GuixShellConfig;
use crate::formatter::StringFormatter;
/// Creates a module showing if inside a guix-shell
///
/// The module will use the `$GUIX_ENVIRONMENT` environment variable to determine if it's
/// inside a guix-shell and the name of it.
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("guix_shell");
let config: GuixShellConfig = GuixShellConfig::try_load(module.config);
let is_guix_shell = context.get_env("GUIX_ENVIRONMENT").is_some();
if !is_guix_shell {
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,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `guix_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("guix_shell").collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn env_variables() {
let actual = ModuleRenderer::new("guix_shell")
.env(
"GUIX_ENVIRONMENT",
"/gnu/store/7vmfs4khf4fllsh83kqkxssbw3437qsh-profile",
)
.collect();
let expected = Some(format!("via {} ", Color::Yellow.bold().paint("🐃 ")));
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/localip.rs | src/modules/localip.rs | use super::{Context, Module};
use crate::config::ModuleConfig;
use crate::configs::localip::LocalipConfig;
use crate::formatter::StringFormatter;
use std::io::Error;
use std::net::UdpSocket;
fn get_local_ipv4() -> Result<String, Error> {
let socket = UdpSocket::bind("0.0.0.0:0")?;
socket.connect("192.0.2.0:80")?;
let addr = socket.local_addr()?;
Ok(addr.ip().to_string())
}
/// Creates a module with the ipv4 address of the local machine.
///
/// The IP address is gathered from the local endpoint of an UDP socket
/// connected to a reserved IPv4 remote address, which is an accurate and fast
/// way, especially if there are multiple IP addresses available.
/// There should be no actual packets send over the wire.
///
/// Will display the ip if all of the following criteria are met:
/// - `localip.disabled` is false
/// - `localip.ssh_only` is false OR the user is currently connected as an SSH session (`$SSH_CONNECTION`)
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("localip");
let config: LocalipConfig = LocalipConfig::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 ssh_connection = context.get_env("SSH_CONNECTION");
if config.ssh_only && ssh_connection.is_none() {
return None;
}
let localip = match get_local_ipv4() {
Ok(ip) => ip,
Err(e) => {
// ErrorKind::NetworkUnreachable is unstable
if cfg!(target_os = "linux") && e.raw_os_error() == Some(101) {
"NetworkUnreachable".to_string()
} else {
log::warn!("unable to determine local ipv4 address: {e}");
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 {
"localipv4" => Some(Ok(&localip)),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `localip`:\n{error}");
return None;
}
});
Some(module)
}
#[cfg(test)]
mod tests {
use crate::modules::localip::get_local_ipv4;
use crate::test::ModuleRenderer;
use nu_ansi_term::{Color, Style};
macro_rules! get_localip {
() => {
match get_local_ipv4() {
Ok(ip) => ip,
Err(e) => {
println!(
"localip was not tested because socket connection failed! \
This could be caused by an unconventional network setup. \
Error: {e}"
);
return;
}
}
};
}
#[test]
fn is_ipv4_format() {
let localip = get_localip!();
assert!(
regex::Regex::new(r"^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$")
.unwrap()
.is_match(&localip)
);
}
#[test]
fn ssh_only_false() {
let localip = get_localip!();
let actual = ModuleRenderer::new("localip")
.config(toml::toml! {
[localip]
ssh_only = false
disabled = false
})
.collect();
let expected = Some(format!("{} ", style().paint(localip)));
assert_eq!(expected, actual);
}
#[test]
fn no_ssh() {
let actual = ModuleRenderer::new("localip")
.config(toml::toml! {
[localip]
ssh_only = true
disabled = false
})
.collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn ssh() {
let localip = get_localip!();
let actual = ModuleRenderer::new("localip")
.config(toml::toml! {
[localip]
ssh_only = true
disabled = false
})
.env("SSH_CONNECTION", "something")
.collect();
let expected = Some(format!("{} ", style().paint(localip)));
assert_eq!(expected, actual);
}
#[test]
fn config_blank() {
let actual = ModuleRenderer::new("localip")
.env("SSH_CONNECTION", "something")
.collect();
let expected = None;
assert_eq!(expected, actual);
}
fn style() -> Style {
Color::Yellow.bold()
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/nim.rs | src/modules/nim.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::nim::NimConfig;
use crate::formatter::StringFormatter;
use crate::formatter::VersionFormatter;
/// Creates a module with the current Nim version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("nim");
let config = NimConfig::try_load(module.config);
let is_nim_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_files)
.is_match();
if !is_nim_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" => context
.exec_cmd("nim", &["--version"])
.map(|command_output| command_output.stdout)
.and_then(|nim_version_output| {
let nim_version = parse_nim_version(&nim_version_output)?;
VersionFormatter::format_module_version(
module.get_name(),
nim_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 `nim`:\n{error}");
return None;
}
});
Some(module)
}
fn parse_nim_version(version_cmd_output: &str) -> Option<&str> {
version_cmd_output
.lines()
// First line has the version
.next()?
.split(' ')
.find(|&s| s.chars().all(|c| c.is_ascii_digit() || c == '.'))
}
#[cfg(test)]
mod tests {
use super::parse_nim_version;
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
use std::fs::File;
use std::io;
#[test]
fn nim_version() {
let ok_versions = ["1.1.1", "2", "."];
let not_ok_versions = ["abc", " \n.", ". ", "abc."];
let all_some = ok_versions.iter().all(|&v| parse_nim_version(v).is_some());
let all_none = not_ok_versions
.iter()
.any(|&v| parse_nim_version(v).is_some());
assert!(all_some);
assert!(all_none);
let sample_nimc_output = "Nim Compiler Version 1.2.0 [Linux: amd64]
Compiled at 2020-04-03
Copyright (c) 2006-2020 by Andreas Rumpf
git hash: 7e83adff84be5d0c401a213eccb61e321a3fb1ff
active boot switches: -d:release\n";
assert_eq!(Some("1.2.0"), parse_nim_version(sample_nimc_output));
}
#[test]
fn folder_without_nim() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("nim.txt"))?.sync_all()?;
let actual = ModuleRenderer::new("nim").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_nimble_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("main.nimble"))?.sync_all()?;
let actual = ModuleRenderer::new("nim").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Yellow.bold().paint("👑 v1.2.0 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_nim_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("main.nim"))?.sync_all()?;
let actual = ModuleRenderer::new("nim").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Yellow.bold().paint("👑 v1.2.0 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_nims_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("main.nims"))?.sync_all()?;
let actual = ModuleRenderer::new("nim").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Yellow.bold().paint("👑 v1.2.0 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_cfg_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("cfg.nim"))?.sync_all()?;
let actual = ModuleRenderer::new("nim").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Yellow.bold().paint("👑 v1.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/kotlin.rs | src/modules/kotlin.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::kotlin::KotlinConfig;
use crate::formatter::StringFormatter;
use crate::formatter::VersionFormatter;
use crate::utils::get_command_string_output;
use regex::Regex;
const KOTLIN_VERSION_PATTERN: &str = "(?P<version>[\\d\\.]+[\\d\\.]+[\\d\\.]+)";
/// Creates a module with the current Kotlin version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("kotlin");
let config = KotlinConfig::try_load(module.config);
let is_kotlin_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_kotlin_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 kotlin_version = get_kotlin_version(context, config.kotlin_binary)?;
VersionFormatter::format_module_version(
module.get_name(),
&kotlin_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 `kotlin`:\n{error}");
return None;
}
});
Some(module)
}
fn get_kotlin_version(context: &Context, kotlin_binary: &str) -> Option<String> {
let command = context.exec_cmd(kotlin_binary, &["-version"])?;
let kotlin_version_string = get_command_string_output(command);
parse_kotlin_version(&kotlin_version_string)
}
fn parse_kotlin_version(kotlin_stdout: &str) -> Option<String> {
// kotlin -version output looks like this:
// Kotlin version 1.4.21-release-411 (JRE 14.0.1+7)
// kotlinc -version output looks like this:
// info: kotlinc-jvm 1.4.21 (JRE 14.0.1+7)
let re = Regex::new(KOTLIN_VERSION_PATTERN).ok()?;
let captures = re.captures(kotlin_stdout)?;
let version = &captures["version"];
Some(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 folder_without_kotlin_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("kotlin").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_kotlin_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("main.kt"))?.sync_all()?;
let actual = ModuleRenderer::new("kotlin").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Blue.bold().paint("🅺 v1.4.21 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_kotlin_script_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("main.kts"))?.sync_all()?;
let actual = ModuleRenderer::new("kotlin").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Blue.bold().paint("🅺 v1.4.21 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn kotlin_binary_is_kotlin_runtime() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("main.kt"))?.sync_all()?;
let config = toml::toml! {
[kotlin]
kotlin_binary = "kotlin"
};
let actual = ModuleRenderer::new("kotlin")
.path(dir.path())
.config(config)
.collect();
let expected = Some(format!("via {}", Color::Blue.bold().paint("🅺 v1.4.21 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn kotlin_binary_is_kotlin_compiler() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("main.kt"))?.sync_all()?;
let config = toml::toml! {
[kotlin]
kotlin_binary = "kotlinc"
};
let actual = ModuleRenderer::new("kotlin")
.path(dir.path())
.config(config)
.collect();
let expected = Some(format!("via {}", Color::Blue.bold().paint("🅺 v1.4.21 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn test_parse_kotlin_version_from_runtime() {
let kotlin_input = "Kotlin version 1.4.21-release-411 (JRE 14.0.1+7)";
assert_eq!(
parse_kotlin_version(kotlin_input),
Some("1.4.21".to_string())
);
}
#[test]
fn test_parse_kotlin_version_from_compiler() {
let kotlin_input = "info: kotlinc-jvm 1.4.21 (JRE 14.0.1+7)";
assert_eq!(
parse_kotlin_version(kotlin_input),
Some("1.4.21".to_string())
);
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/daml.rs | src/modules/daml.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::daml::DamlConfig;
use crate::formatter::{StringFormatter, VersionFormatter};
const DAML_SDK_VERSION: &str = "sdk-version";
const DAML_SDK_VERSION_ENV: &str = "DAML_SDK_VERSION";
const DAML_YAML: &str = "daml.yaml";
/// Creates a module with the current Daml version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("daml");
let config: DamlConfig = DamlConfig::try_load(module.config);
let is_daml_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_daml_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 daml_sdk_version = get_daml_sdk_version(context)?;
VersionFormatter::format_module_version(
module.get_name(),
&daml_sdk_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 `daml`:\n{error}");
return None;
}
});
Some(module)
}
fn get_daml_sdk_version(context: &Context) -> Option<String> {
context
.get_env(DAML_SDK_VERSION_ENV)
.or_else(|| read_sdk_version_from_daml_yaml(context))
}
fn read_sdk_version_from_daml_yaml(context: &Context) -> 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 sdk_version = daml_yaml.first()?[DAML_SDK_VERSION].as_str()?;
Some(sdk_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::{Result, Write};
#[test]
fn folder_without_daml_yaml() -> Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("daml").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_daml_yaml() -> Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join(DAML_YAML))?.write_all(b"sdk-version: 2.2.0\n")?;
let actual = ModuleRenderer::new("daml").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Cyan.bold().paint("Λ v2.2.0 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_daml_yaml_without_sdk_version_entry() -> Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join(DAML_YAML))?.write_all(b"version: 1.0.0\n")?;
let actual = ModuleRenderer::new("daml").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Cyan.bold().paint("Λ ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_daml_yaml_and_daml_sdk_version() -> Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join(DAML_YAML))?.write_all(b"sdk-version: 2.2.0\n")?;
let actual = ModuleRenderer::new("daml")
.env(DAML_SDK_VERSION_ENV, "2.0.0")
.path(dir.path())
.collect();
let expected = Some(format!("via {}", Color::Cyan.bold().paint("Λ v2.0.0 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_without_daml_yaml_with_daml_sdk_version() -> Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("daml")
.env(DAML_SDK_VERSION_ENV, "2.0.0")
.path(dir.path())
.collect();
let expected = None;
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/cmd_duration.rs | src/modules/cmd_duration.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::cmd_duration::CmdDurationConfig;
use crate::formatter::StringFormatter;
use crate::utils::render_time;
/// Outputs the time it took the last command to execute
///
/// Will only print if last command took more than a certain amount of time to
/// execute. Default is two seconds, but can be set by config option `min_time`.
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("cmd_duration");
let config: CmdDurationConfig = CmdDurationConfig::try_load(module.config);
if config.min_time < 0 {
log::warn!(
"min_time in [cmd_duration] ({}) was less than zero",
config.min_time
);
return None;
}
let elapsed = context.get_cmd_duration()?;
let config_min = config.min_time as u128;
if elapsed < config_min {
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 {
"duration" => Some(Ok(render_time(elapsed, config.show_milliseconds))),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `cmd_duration`: \n{error}");
return None;
}
});
Some(undistract_me(module, &config, context, elapsed))
}
#[cfg(not(feature = "notify"))]
fn undistract_me<'a>(
module: Module<'a>,
_config: &CmdDurationConfig,
_context: &'a Context,
_elapsed: u128,
) -> Module<'a> {
module
}
#[cfg(feature = "notify")]
fn undistract_me<'a>(
module: Module<'a>,
config: &CmdDurationConfig,
context: &'a Context,
elapsed: u128,
) -> Module<'a> {
use notify_rust::{Notification, Timeout};
use nu_ansi_term::{AnsiStrings, unstyle};
if config.show_notifications && config.min_time_to_notify as u128 <= elapsed {
if cfg!(target_os = "linux") {
let in_graphical_session = ["DISPLAY", "WAYLAND_DISPLAY", "MIR_SOCKET"]
.iter()
.find_map(|&var| context.get_env(var).filter(|val| !val.is_empty()))
.is_some();
if !in_graphical_session {
return module;
};
}
// On macOS 26+ notify-rust will get stuck finding the current application identifier
// so we set it manually to the default terminal app.
#[cfg(target_os = "macos")]
let _ = notify_rust::set_application("com.apple.Terminal");
let body = format!(
"Command execution {}",
unstyle(&AnsiStrings(&module.ansi_strings()))
);
let timeout = match config.notification_timeout {
Some(v) => Timeout::Milliseconds(v),
None => Timeout::Default,
};
let mut notification = Notification::new();
notification
.summary("Command finished")
.body(&body)
.icon("utilities-terminal")
.timeout(timeout);
if let Err(err) = notification.show() {
log::trace!("Cannot show notification: {err}");
}
}
module
}
#[cfg(test)]
mod tests {
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
#[test]
fn config_blank_duration_1s() {
let actual = ModuleRenderer::new("cmd_duration")
.cmd_duration(1000)
.collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn config_blank_duration_5s() {
let actual = ModuleRenderer::new("cmd_duration")
.cmd_duration(5000)
.collect();
let expected = Some(format!("took {} ", Color::Yellow.bold().paint("5s")));
assert_eq!(expected, actual);
}
#[test]
fn config_5s_duration_3s() {
let actual = ModuleRenderer::new("cmd_duration")
.config(toml::toml! {
[cmd_duration]
min_time = 5000
})
.cmd_duration(3000)
.collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn config_5s_duration_10s() {
let actual = ModuleRenderer::new("cmd_duration")
.config(toml::toml! {
[cmd_duration]
min_time = 5000
})
.cmd_duration(10000)
.collect();
let expected = Some(format!("took {} ", Color::Yellow.bold().paint("10s")));
assert_eq!(expected, actual);
}
#[test]
fn config_1s_duration_prefix_underwent() {
let actual = ModuleRenderer::new("cmd_duration")
.config(toml::toml! {
[cmd_duration]
format = "underwent [$duration]($style) "
})
.cmd_duration(1000)
.collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn config_5s_duration_prefix_underwent() {
let actual = ModuleRenderer::new("cmd_duration")
.config(toml::toml! {
[cmd_duration]
format = "underwent [$duration]($style) "
})
.cmd_duration(5000)
.collect();
let expected = Some(format!("underwent {} ", Color::Yellow.bold().paint("5s")));
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/env_var.rs | src/modules/env_var.rs | use super::{Context, Module};
use std::borrow::Cow;
use crate::config::ModuleConfig;
use crate::configs::env_var::EnvVarConfig;
use crate::formatter::StringFormatter;
/// Creates a module with the value of the chosen environment variable
///
/// Will display the environment variable's value if all of the following criteria are met:
/// - `env_var.disabled` is absent or false
/// - `env_var.variable` is defined
/// - a variable named as the value of `env_var.variable` is defined
pub fn module<'a>(name: Option<&str>, context: &'a Context) -> Option<Module<'a>> {
let toml_config = match name {
Some(name) => context
.config
.get_config(&["env_var", name])
.map(Cow::Borrowed),
None => context
.config
.get_module_config("env_var")
.and_then(filter_config)
.map(Cow::Owned)
.map(Some)?,
};
let mod_name = match name {
Some(name) => format!("env_var.{name}"),
None => "env_var".to_owned(),
};
let config = EnvVarConfig::try_load(toml_config.as_deref());
// Note: Forward config if `Module` ends up needing `config`
let mut module = Module::new(mod_name, config.description, None);
if config.disabled {
return None;
}
let variable_name = config.variable.or(name)?;
let env_value = context.get_env(variable_name);
let env_value = env_value.as_deref().or(config.default)?;
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 {
"env_value" => Some(Ok(env_value)),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `env_var`:\n{error}");
return None;
}
});
Some(module)
}
/// Filter `config` to only includes non-table values
/// This filters the top-level table to only include its specific configuration
fn filter_config(config: &toml::Value) -> Option<toml::Value> {
let o = config
.as_table()
.map(|table| {
table
.iter()
.filter(|(_key, val)| !val.is_table())
.map(|(key, val)| (key.clone(), val.clone()))
.collect::<toml::value::Table>()
})
.filter(|table| !table.is_empty())
.map(toml::Value::Table);
log::trace!("Filtered top-level env_var config: {o:?}");
o
}
#[cfg(test)]
mod test {
use crate::test::ModuleRenderer;
use nu_ansi_term::{Color, Style};
const TEST_VAR_VALUE: &str = "astronauts";
#[test]
fn empty_config() {
let actual = ModuleRenderer::new("env_var").collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn fallback_config() {
let actual = ModuleRenderer::new("env_var")
.config(toml::toml! {
[env_var]
variable="TEST_VAR"
})
.env("TEST_VAR", TEST_VAR_VALUE)
.collect();
let expected = Some(format!("with {} ", style().paint(TEST_VAR_VALUE)));
assert_eq!(expected, actual);
}
#[test]
fn defined_variable() {
let actual = ModuleRenderer::new("env_var.TEST_VAR")
.config(toml::toml! {
[env_var.TEST_VAR]
})
.env("TEST_VAR", TEST_VAR_VALUE)
.collect();
let expected = Some(format!("with {} ", style().paint(TEST_VAR_VALUE)));
assert_eq!(expected, actual);
}
#[test]
fn undefined_variable() {
let actual = ModuleRenderer::new("env_var.TEST_VAR")
.config(toml::toml! {
[env_var.TEST_VAR]
})
.collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn default_has_no_effect() {
let actual = ModuleRenderer::new("env_var.TEST_VAR")
.config(toml::toml! {
[env_var.TEST_VAR]
default = "N/A"
})
.env("TEST_VAR", TEST_VAR_VALUE)
.collect();
let expected = Some(format!("with {} ", style().paint(TEST_VAR_VALUE)));
assert_eq!(expected, actual);
}
#[test]
fn default_takes_effect() {
let actual = ModuleRenderer::new("env_var.UNDEFINED_TEST_VAR")
.config(toml::toml! {
[env_var.UNDEFINED_TEST_VAR]
default = "N/A"
})
.collect();
let expected = Some(format!("with {} ", style().paint("N/A")));
assert_eq!(expected, actual);
}
#[test]
fn symbol() {
let actual = ModuleRenderer::new("env_var.TEST_VAR")
.config(toml::toml! {
[env_var.TEST_VAR]
format = "with [■ $env_value](black bold dimmed) "
})
.env("TEST_VAR", TEST_VAR_VALUE)
.collect();
let expected = Some(format!(
"with {} ",
style().paint(format!("■ {TEST_VAR_VALUE}"))
));
assert_eq!(expected, actual);
}
#[test]
fn prefix() {
let actual = ModuleRenderer::new("env_var.TEST_VAR")
.config(toml::toml! {
[env_var.TEST_VAR]
format = "with [_$env_value](black bold dimmed) "
})
.env("TEST_VAR", TEST_VAR_VALUE)
.collect();
let expected = Some(format!(
"with {} ",
style().paint(format!("_{TEST_VAR_VALUE}"))
));
assert_eq!(expected, actual);
}
#[test]
fn suffix() {
let actual = ModuleRenderer::new("env_var.TEST_VAR")
.config(toml::toml! {
[env_var.TEST_VAR]
format = "with [${env_value}_](black bold dimmed) "
})
.env("TEST_VAR", TEST_VAR_VALUE)
.collect();
let expected = Some(format!(
"with {} ",
style().paint(format!("{TEST_VAR_VALUE}_"))
));
assert_eq!(expected, actual);
}
#[test]
fn display_few() {
let actual1 = ModuleRenderer::new("env_var.TEST_VAR")
.config(toml::toml! {
[env_var.TEST_VAR]
[env_var.TEST_VAR2]
})
.env("TEST_VAR", TEST_VAR_VALUE)
.env("TEST_VAR2", TEST_VAR_VALUE)
.collect();
let actual2 = ModuleRenderer::new("env_var.TEST_VAR2")
.config(toml::toml! {
[env_var.TEST_VAR]
[env_var.TEST_VAR2]
})
.env("TEST_VAR", TEST_VAR_VALUE)
.env("TEST_VAR2", TEST_VAR_VALUE)
.collect();
let expected = Some(format!("with {} ", style().paint(TEST_VAR_VALUE)));
assert_eq!(expected, actual1);
assert_eq!(expected, actual2);
}
#[test]
fn mixed() {
let cfg = toml::toml! {
[env_var]
variable = "TEST_VAR_OUTER"
format = "$env_value"
[env_var.TEST_VAR_INNER]
format = "$env_value"
};
let actual_inner = ModuleRenderer::new("env_var.TEST_VAR_INNER")
.config(cfg.clone())
.env("TEST_VAR_OUTER", "outer")
.env("TEST_VAR_INNER", "inner")
.collect();
assert_eq!(
actual_inner.as_deref(),
Some("inner"),
"inner module should be rendered"
);
let actual_outer = ModuleRenderer::new("env_var")
.config(cfg)
.env("TEST_VAR_OUTER", "outer")
.env("TEST_VAR_INNER", "inner")
.collect();
assert_eq!(
actual_outer.as_deref(),
Some("outer"),
"outer module should be rendered"
);
}
#[test]
fn no_config() {
let actual = ModuleRenderer::new("env_var.TEST_VAR")
.env("TEST_VAR", TEST_VAR_VALUE)
.collect();
let expected = Some(format!("with {} ", style().paint(TEST_VAR_VALUE)));
assert_eq!(expected, actual);
}
#[test]
fn disabled_child() {
let actual = ModuleRenderer::new("env_var.TEST_VAR")
.config(toml::toml! {
[env_var.TEST_VAR]
disabled = true
})
.env("TEST_VAR", TEST_VAR_VALUE)
.collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn disabled_root() {
let actual = ModuleRenderer::new("env_var")
.config(toml::toml! {
[env_var]
disabled = true
})
.env("TEST_VAR", TEST_VAR_VALUE)
.collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn variable_override() {
let actual = ModuleRenderer::new("env_var.TEST_VAR")
.config(toml::toml! {
[env_var.TEST_VAR]
variable = "TEST_VAR2"
})
.env("TEST_VAR", "implicit name")
.env("TEST_VAR2", "explicit name")
.collect();
let expected = Some(format!("with {} ", style().paint("explicit name")));
assert_eq!(expected, actual);
}
fn style() -> Style {
// default style
Color::Black.bold().dimmed()
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/openstack.rs | src/modules/openstack.rs | use yaml_rust2::YamlLoader;
use super::{Context, Module, ModuleConfig};
use crate::configs::openstack::OspConfig;
use crate::formatter::StringFormatter;
use crate::utils;
type Cloud = String;
type Project = String;
fn get_osp_project_from_config(context: &Context, osp_cloud: &str) -> Option<Project> {
// Attempt to follow OpenStack standards for clouds.yaml location:
// 1st = $PWD/clouds.yaml, 2nd = $HOME/.config/openstack/clouds.yaml, 3rd = /etc/openstack/clouds.yaml
let config = [
context.get_env("PWD").map(|pwd| pwd + "/clouds.yaml"),
context.get_home().map(|home| {
home.join(".config/openstack/clouds.yaml")
.display()
.to_string()
}),
Some(String::from("/etc/openstack/clouds.yaml")),
];
config
.iter()
.filter_map(|file| {
let config = utils::read_file(file.as_ref()?).ok()?;
let clouds = YamlLoader::load_from_str(config.as_str()).ok()?;
clouds.first()?["clouds"][osp_cloud]["auth"]["project_name"]
.as_str()
.map(ToOwned::to_owned)
})
.find(|s| !s.is_empty())
}
fn get_osp_cloud_and_project(context: &Context) -> (Option<Cloud>, Option<Project>) {
match (
context.get_env("OS_CLOUD"),
context.get_env("OS_PROJECT_NAME"),
) {
(Some(p), Some(r)) => (Some(p), Some(r)),
(None, Some(r)) => (None, Some(r)),
(Some(ref p), None) => (Some(p.clone()), get_osp_project_from_config(context, p)),
(None, None) => (None, None),
}
}
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("openstack");
let config: OspConfig = OspConfig::try_load(module.config);
let (osp_cloud, osp_project) = get_osp_cloud_and_project(context);
osp_cloud.as_ref()?;
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 {
"cloud" => osp_cloud.as_ref().map(Ok),
"project" => osp_project.as_ref().map(Ok),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::error!("Error in module `openstack`: \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 parse_valid_config() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let config_path = dir.path().join("clouds.yaml");
let mut file = File::create(config_path)?;
file.write_all(
b"---
clouds:
corp:
auth:
auth_url: https://overcloud.example.com:13000/v3
project_name: testproject
identity_api_version: '3'
interface: public
",
)?;
let actual = ModuleRenderer::new("openstack")
.env("PWD", dir.path().to_str().unwrap())
.env("OS_CLOUD", "corp")
.config(toml::toml! {
[openstack]
})
.collect();
let expected = Some(format!(
"on {} ",
Color::Yellow.bold().paint("☁️ corp(testproject)")
));
assert_eq!(actual, expected);
dir.close()
}
#[test]
fn parse_broken_config() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let config_path = dir.path().join("clouds.yaml");
let mut file = File::create(config_path)?;
file.write_all(
b"---
dummy_yaml
",
)?;
let actual = ModuleRenderer::new("openstack")
.env("PWD", dir.path().to_str().unwrap())
.env("OS_CLOUD", "test")
.config(toml::toml! {
[openstack]
})
.collect();
let expected = Some(format!("on {} ", Color::Yellow.bold().paint("☁️ test")));
assert_eq!(actual, expected);
dir.close()
}
#[test]
fn dont_crash_on_empty_config() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let config_path = dir.path().join("clouds.yaml");
let mut file = File::create(config_path)?;
file.write_all(b"")?;
drop(file);
let actual = ModuleRenderer::new("openstack")
.env("PWD", dir.path().to_str().unwrap())
.env("OS_CLOUD", "test")
.config(toml::toml! {
[openstack]
})
.collect();
let expected = Some(format!("on {} ", Color::Yellow.bold().paint("☁️ test")));
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/shlvl.rs | src/modules/shlvl.rs | use super::{Context, Module};
use crate::config::ModuleConfig;
use crate::configs::shlvl::ShLvlConfig;
use crate::formatter::StringFormatter;
use std::borrow::Cow;
use std::convert::TryInto;
const SHLVL_ENV_VAR: &str = "SHLVL";
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let props = &context.properties;
let shlvl = props
.shlvl
.or_else(|| context.get_env(SHLVL_ENV_VAR)?.parse::<i64>().ok())?;
let mut module = context.new_module("shlvl");
let config: ShLvlConfig = ShLvlConfig::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 || shlvl < config.threshold {
return None;
}
let shlvl_str = &shlvl.to_string();
let mut repeat_count: usize = if config.repeat {
shlvl.try_into().unwrap_or(1)
} else {
1
};
if config.repeat_offset > 0 {
repeat_count =
repeat_count.saturating_sub(config.repeat_offset.try_into().unwrap_or(usize::MAX));
if repeat_count == 0 {
return None;
}
}
let symbol = if repeat_count == 1 {
Cow::Borrowed(config.symbol)
} else {
Cow::Owned(config.symbol.repeat(repeat_count))
};
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|var, _| match var {
"symbol" => Some(symbol.as_ref()),
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map(|variable| match variable {
"shlvl" => Some(Ok(shlvl_str)),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `shlvl`:\n{error}");
return None;
}
});
Some(module)
}
#[cfg(test)]
mod tests {
use nu_ansi_term::{Color, Style};
use crate::test::ModuleRenderer;
use super::SHLVL_ENV_VAR;
fn style() -> Style {
// default style
Color::Yellow.bold()
}
#[test]
fn empty_config() {
let actual = ModuleRenderer::new("shlvl")
.config(toml::toml! {
[shlvl]
})
.env(SHLVL_ENV_VAR, "2")
.collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn enabled() {
let actual = ModuleRenderer::new("shlvl")
.config(toml::toml! {
[shlvl]
disabled = false
})
.env(SHLVL_ENV_VAR, "2")
.collect();
let expected = Some(format!("{} ", style().paint("↕️ 2")));
assert_eq!(expected, actual);
}
#[test]
fn no_level() {
let actual = ModuleRenderer::new("shlvl")
.config(toml::toml! {
[shlvl]
disabled = false
})
.collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn enabled_config_level_1() {
let actual = ModuleRenderer::new("shlvl")
.config(toml::toml! {
[shlvl]
disabled = false
})
.env(SHLVL_ENV_VAR, "1")
.collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn lower_threshold() {
let actual = ModuleRenderer::new("shlvl")
.config(toml::toml! {
[shlvl]
threshold = 1
disabled = false
})
.env(SHLVL_ENV_VAR, "1")
.collect();
let expected = Some(format!("{} ", style().paint("↕️ 1")));
assert_eq!(expected, actual);
}
#[test]
fn higher_threshold() {
let actual = ModuleRenderer::new("shlvl")
.config(toml::toml! {
[shlvl]
threshold = 3
disabled = false
})
.env(SHLVL_ENV_VAR, "1")
.collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn custom_style() {
let actual = ModuleRenderer::new("shlvl")
.config(toml::toml! {
[shlvl]
style = "Red Underline"
disabled = false
})
.env(SHLVL_ENV_VAR, "2")
.collect();
let expected = Some(format!("{} ", Color::Red.underline().paint("↕️ 2")));
assert_eq!(expected, actual);
}
#[test]
fn custom_symbol() {
let actual = ModuleRenderer::new("shlvl")
.config(toml::toml! {
[shlvl]
symbol = "shlvl is "
disabled = false
})
.env(SHLVL_ENV_VAR, "2")
.collect();
let expected = Some(format!("{} ", style().paint("shlvl is 2")));
assert_eq!(expected, actual);
}
#[test]
fn formatting() {
let actual = ModuleRenderer::new("shlvl")
.config(toml::toml! {
[shlvl]
format = "$symbol going down [$shlvl]($style) GOING UP "
disabled = false
})
.env(SHLVL_ENV_VAR, "2")
.collect();
let expected = Some(format!("↕️ going down {} GOING UP ", style().paint("2")));
assert_eq!(expected, actual);
}
#[test]
fn repeat() {
let actual = ModuleRenderer::new("shlvl")
.config(toml::toml! {
[shlvl]
format = "[$symbol>]($style) "
symbol = "~"
repeat = true
disabled = false
})
.env(SHLVL_ENV_VAR, "3")
.collect();
let expected = Some(format!("{} ", style().paint("~~~>")));
assert_eq!(expected, actual);
}
#[test]
fn repeat_offset() {
fn get_actual(shlvl: usize, repeat_offset: usize, threshold: usize) -> Option<String> {
ModuleRenderer::new("shlvl")
.config(toml::toml! {
[shlvl]
format = "[$symbol]($style)"
symbol = "~"
repeat = true
repeat_offset = repeat_offset
disabled = false
threshold = threshold
})
.env(SHLVL_ENV_VAR, format!("{shlvl}"))
.collect()
}
assert_eq!(
get_actual(2, 0, 0),
Some(format!("{}", style().paint("~~")))
);
assert_eq!(get_actual(2, 1, 0), Some(format!("{}", style().paint("~"))));
assert_eq!(get_actual(2, 2, 0), None); // offset same as shlvl; hide
assert_eq!(get_actual(2, 3, 0), None); // offset larger than shlvl; hide
assert_eq!(get_actual(2, 1, 3), None); // high threshold; hide
// threshold not high enough; hide
assert_eq!(get_actual(2, 1, 2), Some(format!("{}", style().paint("~"))));
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/direnv.rs | src/modules/direnv.rs | use std::borrow::Cow;
use std::path::PathBuf;
use std::str::FromStr;
use super::{Context, Module, ModuleConfig};
use crate::configs::direnv::DirenvConfig;
use crate::formatter::StringFormatter;
use serde::Deserialize;
/// Creates a module with the current direnv rc
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("direnv");
let config = DirenvConfig::try_load(module.config);
let has_detected_env_var = context.detect_env_vars(&config.detect_env_vars);
let direnv_applies = !config.disabled
&& (has_detected_env_var
|| context
.try_begin_scan()?
.set_extensions(&config.detect_extensions)
.set_files(&config.detect_files)
.set_folders(&config.detect_folders)
.is_match());
if !direnv_applies {
return None;
}
// the `--json` flag is silently ignored for direnv versions <2.33.0
let direnv_status = &context.exec_cmd("direnv", &["status", "--json"])?.stdout;
let state = match DirenvState::from_str(direnv_status) {
Ok(s) => s,
Err(e) => {
log::warn!("{e}");
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(Cow::from(config.symbol))),
"rc_path" => Some(Ok(state.rc_path.to_string_lossy())),
"allowed" => Some(Ok(match state.allowed {
AllowStatus::Allowed => Cow::from(config.allowed_msg),
AllowStatus::NotAllowed => Cow::from(config.not_allowed_msg),
AllowStatus::Denied => Cow::from(config.denied_msg),
})),
"loaded" => state
.loaded
.then_some(config.loaded_msg)
.or(Some(config.unloaded_msg))
.map(Cow::from)
.map(Ok),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(e) => {
log::warn!("{e}");
return None;
}
});
Some(module)
}
struct DirenvState {
pub rc_path: PathBuf,
pub allowed: AllowStatus,
pub loaded: bool,
}
impl FromStr for DirenvState {
type Err = Cow<'static, str>;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match serde_json::from_str::<RawDirenvState>(s) {
Ok(raw) => Ok(Self {
rc_path: raw.state.found_rc.path,
allowed: raw.state.found_rc.allowed.try_into()?,
loaded: matches!(
raw.state.loaded_rc.allowed.try_into()?,
AllowStatus::Allowed
),
}),
Err(_) => Self::from_lines(s),
}
}
}
impl DirenvState {
fn from_lines(s: &str) -> Result<Self, Cow<'static, str>> {
let mut rc_path = PathBuf::new();
let mut allowed = None;
let mut loaded = true;
for line in s.lines() {
if let Some(path) = line.strip_prefix("Found RC path") {
rc_path = PathBuf::from_str(path.trim()).map_err(|e| Cow::from(e.to_string()))?
} else if let Some(value) = line.strip_prefix("Found RC allowed") {
allowed = Some(AllowStatus::from_str(value.trim())?);
} else if line.contains("No .envrc or .env loaded") {
loaded = false;
};
}
if rc_path.as_os_str().is_empty() || allowed.is_none() {
return Err(Cow::from("unknown direnv state"));
}
Ok(Self {
rc_path,
allowed: allowed.unwrap(),
loaded,
})
}
}
#[derive(Debug)]
enum AllowStatus {
Allowed,
NotAllowed,
Denied,
}
impl FromStr for AllowStatus {
type Err = Cow<'static, str>;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"0" | "true" => Ok(Self::Allowed),
"1" => Ok(Self::NotAllowed),
"2" | "false" => Ok(Self::Denied),
_ => Err(Cow::from("invalid allow status")),
}
}
}
impl TryFrom<u8> for AllowStatus {
type Error = Cow<'static, str>;
fn try_from(u: u8) -> Result<Self, Self::Error> {
match u {
0 => Ok(Self::Allowed),
1 => Ok(Self::NotAllowed),
2 => Ok(Self::Denied),
_ => Err(Cow::from("unknown integer allow status")),
}
}
}
#[derive(Debug, Deserialize)]
struct RawDirenvState {
pub state: State,
}
#[derive(Debug, Deserialize)]
struct State {
#[serde(rename = "foundRC")]
pub found_rc: RCStatus,
#[serde(rename = "loadedRC")]
pub loaded_rc: RCStatus,
}
#[derive(Debug, Deserialize)]
struct RCStatus {
pub allowed: u8,
pub path: PathBuf,
}
#[cfg(test)]
mod tests {
use serde_json::json;
use crate::test::ModuleRenderer;
use crate::utils::CommandOutput;
use nu_ansi_term::Color;
use std::io;
use std::path::Path;
#[test]
fn folder_without_rc_files_pre_2_33() {
let renderer = ModuleRenderer::new("direnv")
.config(toml::toml! {
[direnv]
disabled = false
})
.cmd(
"direnv status --json",
Some(CommandOutput {
stdout: status_cmd_output_without_rc(),
stderr: String::default(),
}),
);
assert_eq!(None, renderer.collect());
}
#[test]
fn folder_without_rc_files() {
let renderer = ModuleRenderer::new("direnv")
.config(toml::toml! {
[direnv]
disabled = false
})
.cmd(
"direnv status --json",
Some(CommandOutput {
stdout: status_cmd_output_without_rc_json(),
stderr: String::default(),
}),
);
assert_eq!(None, renderer.collect());
}
#[test]
fn folder_with_unloaded_rc_file_pre_2_33() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let rc_path = dir.path().join(".envrc");
std::fs::File::create(rc_path)?.sync_all()?;
let actual = ModuleRenderer::new("direnv")
.config(toml::toml! {
[direnv]
disabled = false
})
.path(dir.path())
.cmd(
"direnv status --json",
Some(CommandOutput {
stdout: status_cmd_output_with_rc(dir.path(), false, "0", true),
stderr: String::default(),
}),
)
.collect();
let expected = Some(format!(
"{} ",
Color::LightYellow.bold().paint("direnv not loaded/allowed")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_unloaded_rc_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let rc_path = dir.path().join(".envrc");
std::fs::File::create(rc_path)?.sync_all()?;
let actual = ModuleRenderer::new("direnv")
.config(toml::toml! {
[direnv]
disabled = false
})
.path(dir.path())
.cmd(
"direnv status --json",
Some(CommandOutput {
stdout: status_cmd_output_with_rc_json(dir.path(), 1, 0),
stderr: String::default(),
}),
)
.collect();
let expected = Some(format!(
"{} ",
Color::LightYellow.bold().paint("direnv not loaded/allowed")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_loaded_rc_file_pre_2_33() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let rc_path = dir.path().join(".envrc");
std::fs::File::create(rc_path)?.sync_all()?;
let actual = ModuleRenderer::new("direnv")
.config(toml::toml! {
[direnv]
disabled = false
})
.path(dir.path())
.cmd(
"direnv status --json",
Some(CommandOutput {
stdout: status_cmd_output_with_rc(dir.path(), true, "0", true),
stderr: String::default(),
}),
)
.collect();
let expected = Some(format!(
"{} ",
Color::LightYellow.bold().paint("direnv loaded/allowed")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_loaded_rc_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let rc_path = dir.path().join(".envrc");
std::fs::File::create(rc_path)?.sync_all()?;
let actual = ModuleRenderer::new("direnv")
.config(toml::toml! {
[direnv]
disabled = false
})
.path(dir.path())
.cmd(
"direnv status --json",
Some(CommandOutput {
stdout: status_cmd_output_with_rc_json(dir.path(), 0, 0),
stderr: String::default(),
}),
)
.collect();
let expected = Some(format!(
"{} ",
Color::LightYellow.bold().paint("direnv loaded/allowed")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_loaded_rc_file_in_subdirectory() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let rc_path = dir.path().join(".envrc");
let sub_dir_path = dir.path().join("sub_dir");
std::fs::File::create(rc_path)?.sync_all()?;
std::fs::DirBuilder::new()
.recursive(true)
.create(&sub_dir_path)?;
let actual = ModuleRenderer::new("direnv")
.config(toml::toml! {
[direnv]
disabled = false
})
.path(&sub_dir_path)
.env("DIRENV_FILE", "file")
.cmd(
"direnv status --json",
Some(CommandOutput {
stdout: status_cmd_output_with_rc_json(dir.path(), 0, 0),
stderr: String::default(),
}),
)
.collect();
let expected = Some(format!(
"{} ",
Color::LightYellow.bold().paint("direnv loaded/allowed")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_loaded_and_denied_rc_file_pre_2_33() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let rc_path = dir.path().join(".envrc");
std::fs::File::create(rc_path)?.sync_all()?;
let actual = ModuleRenderer::new("direnv")
.config(toml::toml! {
[direnv]
disabled = false
})
.path(dir.path())
.cmd(
"direnv status --json",
Some(CommandOutput {
stdout: status_cmd_output_with_rc(dir.path(), true, "2", true),
stderr: String::default(),
}),
)
.collect();
let expected = Some(format!(
"{} ",
Color::LightYellow.bold().paint("direnv loaded/denied")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_loaded_and_not_allowed_rc_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let rc_path = dir.path().join(".envrc");
std::fs::File::create(rc_path)?.sync_all()?;
let actual = ModuleRenderer::new("direnv")
.config(toml::toml! {
[direnv]
disabled = false
})
.path(dir.path())
.cmd(
"direnv status --json",
Some(CommandOutput {
stdout: status_cmd_output_with_rc_json(dir.path(), 0, 1),
stderr: String::default(),
}),
)
.collect();
let expected = Some(format!(
"{} ",
Color::LightYellow.bold().paint("direnv loaded/not allowed")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_loaded_and_denied_rc_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let rc_path = dir.path().join(".envrc");
std::fs::File::create(rc_path)?.sync_all()?;
let actual = ModuleRenderer::new("direnv")
.config(toml::toml! {
[direnv]
disabled = false
})
.path(dir.path())
.cmd(
"direnv status --json",
Some(CommandOutput {
stdout: status_cmd_output_with_rc_json(dir.path(), 0, 2),
stderr: String::default(),
}),
)
.collect();
let expected = Some(format!(
"{} ",
Color::LightYellow.bold().paint("direnv loaded/denied")
));
assert_eq!(expected, actual);
dir.close()
}
fn status_cmd_output_without_rc() -> String {
String::from(
r"\
direnv exec path /usr/bin/direnv
DIRENV_CONFIG /home/test/.config/direnv
bash_path /usr/bin/bash
disable_stdin false
warn_timeout 5s
whitelist.prefix []
whitelist.exact map[]
No .envrc or .env loaded
No .envrc or .env found",
)
}
fn status_cmd_output_without_rc_json() -> String {
json!({
"config": {
"ConfigDir": config_dir(),
"SelfPath": self_path(),
},
"state": {
"foundRC": null,
"loadedRC": null,
}
})
.to_string()
}
fn status_cmd_output_with_rc(
dir: impl AsRef<Path>,
loaded: bool,
allowed: &str,
use_legacy_boolean_flags: bool,
) -> String {
let rc_path = dir.as_ref().join(".envrc");
let rc_path = rc_path.to_string_lossy();
let allowed_value = match (use_legacy_boolean_flags, allowed) {
(true, "0") => "true",
(true, ..) => "false",
(false, val) => val,
};
let loaded = if loaded {
format!(
r#"\
Loaded RC path {rc_path}
Loaded watch: ".envrc" - 2023-04-30T09:51:04-04:00
Loaded watch: "../.local/share/direnv/allow/abcd" - 2023-04-30T09:52:58-04:00
Loaded RC allowed {allowed_value}
Loaded RC allowPath
"#
)
} else {
String::from("No .envrc or .env loaded")
};
let state = allowed.to_string();
format!(
r#"\
direnv exec path /usr/bin/direnv
DIRENV_CONFIG /home/test/.config/direnv
bash_path /usr/bin/bash
disable_stdin false
warn_timeout 5s
whitelist.prefix []
whitelist.exact map[]
{loaded}
Found RC path {rc_path}
Found watch: ".envrc" - 2023-04-25T18:45:54-04:00
Found watch: "../.local/share/direnv/allow/abcd" - 1969-12-31T19:00:00-05:00
Found RC allowed {state}
Found RC allowPath /home/test/.local/share/direnv/allow/abcd
"#
)
}
fn status_cmd_output_with_rc_json(dir: impl AsRef<Path>, loaded: u8, allowed: u8) -> String {
let rc_path = dir.as_ref().join(".envrc");
let rc_path = rc_path.to_string_lossy();
json!({
"config": {
"ConfigDir": config_dir(),
"SelfPath": self_path(),
},
"state": {
"foundRC": {
"allowed": allowed,
"path": rc_path,
},
"loadedRC": {
"allowed": loaded,
"path": rc_path,
}
}
})
.to_string()
}
#[cfg(windows)]
fn config_dir() -> &'static str {
r"C:\\Users\\test\\AppData\\Local\\direnv"
}
#[cfg(not(windows))]
fn config_dir() -> &'static str {
"/home/test/.config/direnv"
}
#[cfg(windows)]
fn self_path() -> &'static str {
r"C:\\Program Files\\direnv\\direnv.exe"
}
#[cfg(not(windows))]
fn self_path() -> &'static str {
"/usr/bin/direnv"
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/mojo.rs | src/modules/mojo.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::mojo::MojoConfig;
use crate::formatter::StringFormatter;
use std::sync::LazyLock;
/// Creates a module with the current Mojo version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("mojo");
let config = MojoConfig::try_load(module.config);
let is_mojo_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_mojo_project {
return None;
}
let version_hash = LazyLock::new(|| get_mojo_version(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 {
"version" => match &*version_hash {
Some((version, _)) => Some(Ok(version)),
_ => None,
},
"hash" => match &*version_hash {
Some((_, Some(hash))) => Some(Ok(hash)),
_ => None,
},
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `mojo`:\n{error}");
return None;
}
});
Some(module)
}
fn get_mojo_version(context: &Context) -> Option<(String, Option<String>)> {
let mojo_version_output = context.exec_cmd("mojo", &["--version"])?.stdout;
let version_items = mojo_version_output
.split_ascii_whitespace()
.collect::<Vec<&str>>();
let (version, hash) = match version_items[..] {
[_, version] => (version.trim().to_string(), None),
[_, version, hash, ..] => (version.trim().to_string(), Some(hash.trim().to_string())),
_ => {
log::debug!("Unexpected `mojo --version` output: {mojo_version_output}");
return None;
}
};
Some((version, hash))
}
#[cfg(test)]
mod tests {
use crate::configs::mojo::MOJO_DEFAULT_COLOR;
use crate::test::ModuleRenderer;
use crate::utils::CommandOutput;
use std::fs::File;
use std::io;
#[test]
fn folder_without_mojo() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("mojo.txt"))?.sync_all()?;
let actual = ModuleRenderer::new("mojo").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_mojo_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("main.mojo"))?.sync_all()?;
let actual = ModuleRenderer::new("mojo")
.path(dir.path())
.collect()
.unwrap();
let expected = format!("with {}", MOJO_DEFAULT_COLOR.bold().paint("🔥 24.4.0 "));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_mojo_file_emoji() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("main.🔥"))?.sync_all()?;
let actual = ModuleRenderer::new("mojo")
.path(dir.path())
.collect()
.unwrap();
let expected = format!("with {}", MOJO_DEFAULT_COLOR.bold().paint("🔥 24.4.0 "));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_mojo_file_with_commit() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("main.mojo"))?.sync_all()?;
let actual = ModuleRenderer::new("mojo")
.config(toml::toml! {
[mojo]
format = "with [$symbol($version )($hash )]($style)"
})
.path(dir.path())
.collect()
.unwrap();
let expected = format!(
"with {}",
MOJO_DEFAULT_COLOR.bold().paint("🔥 24.4.0 (2cb57382) ")
);
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_mojo_file_with_no_commit_available() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("main.mojo"))?.sync_all()?;
let actual = ModuleRenderer::new("mojo")
.config(toml::toml! {
[mojo]
show_commit = true
})
.cmd(
"mojo --version",
Some(CommandOutput {
stdout: String::from("mojo 24.4.0\n"),
stderr: String::default(),
}),
)
.path(dir.path())
.collect();
let expected = Some(format!(
"with {}",
MOJO_DEFAULT_COLOR.bold().paint("🔥 24.4.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/fennel.rs | src/modules/fennel.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::fennel::FennelConfig;
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("fennel");
let config = FennelConfig::try_load(module.config);
let is_fnl_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_fnl_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 fennel_version_string =
get_command_string_output(context.exec_cmd("fennel", &["--version"])?);
let fennel_version = parse_fennel_version(&fennel_version_string)?;
VersionFormatter::format_module_version(
module.get_name(),
&fennel_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 `fennel`:\n{error}");
return None;
}
});
Some(module)
}
fn parse_fennel_version(fennel_version: &str) -> Option<String> {
// fennel -v output looks like this:
// Fennel 1.2.1 on PUC Lua 5.4
let version = fennel_version
// split into ["Fennel", "1.2.1", "on", ...]
.split_whitespace()
// take "1.2.1"
.nth(1)?;
Some(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 folder_without_fennel_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("fennel").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_fennel_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("man.fnl"))?.sync_all()?;
let actual = ModuleRenderer::new("fennel").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Green.bold().paint("🧅 v1.2.1 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn test_parse_fennel_version() {
let fennel_input = "Fennel 1.2.1 on PUC Lua 5.4";
assert_eq!(
parse_fennel_version(fennel_input),
Some("1.2.1".to_string())
);
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/vagrant.rs | src/modules/vagrant.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::vagrant::VagrantConfig;
use crate::formatter::StringFormatter;
use crate::formatter::VersionFormatter;
/// Creates a module with the current Vagrant version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("vagrant");
let config = VagrantConfig::try_load(module.config);
let is_vagrant_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_vagrant_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 vagrant_version = parse_vagrant_version(
&context.exec_cmd("vagrant", &["--version"])?.stdout,
)?;
VersionFormatter::format_module_version(
module.get_name(),
&vagrant_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 `vagrant`:\n{error}");
return None;
}
});
Some(module)
}
fn parse_vagrant_version(vagrant_stdout: &str) -> Option<String> {
// `vagrant --version` output looks like this:
// Vagrant 2.2.10
let version = vagrant_stdout
// split into ["Vagrant", "2.2.10"]
.split_whitespace()
// return "2.2.10"
.nth(1)?;
Some(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 folder_without_vagrant_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("vagrant").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_vagrant_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("Vagrantfile"))?.sync_all()?;
let actual = ModuleRenderer::new("vagrant").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Cyan.bold().paint("⍱ v2.2.10 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn test_parse_vagrant_version() {
let vagrant = "Vagrant 2.2.10\n";
assert_eq!(parse_vagrant_version(vagrant), Some("2.2.10".to_string()));
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/line_break.rs | src/modules/line_break.rs | use super::{Context, Module};
use crate::segment::Segment;
/// Creates a module for the line break
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("line_break");
module.set_segments(vec![Segment::LineTerm]);
Some(module)
}
#[cfg(test)]
mod test {
use crate::test::ModuleRenderer;
#[test]
fn produces_result() {
let expected = Some(String::from("\n"));
let actual = ModuleRenderer::new("line_break").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/git_status.rs | src/modules/git_status.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::git_status::GitStatusConfig;
use crate::formatter::StringFormatter;
use crate::segment::Segment;
use crate::{context, num_configured_starship_threads, num_rayon_threads};
use gix::bstr::ByteVec;
use gix::status::Submodule;
use regex::Regex;
use std::path::PathBuf;
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, OnceLock};
const ALL_STATUS_FORMAT: &str =
"$conflicted$stashed$deleted$renamed$modified$typechanged$staged$untracked";
/// Creates a module with the Git branch in the current directory
///
/// Will display the branch name if the current directory is a git repo
/// By default, the following symbols will be used to represent the repo's status:
/// - `=` – This branch has merge conflicts
/// - `⇡` – This branch is ahead of the branch being tracked
/// - `⇣` – This branch is behind of the branch being tracked
/// - `⇕` – This branch has diverged from the branch being tracked
/// - `` – This branch is up-to-date with the branch being tracked
/// - `?` — There are untracked files in the working directory
/// - `$` — A stash exists for the local repository
/// - `!` — There are file modifications in the working directory
/// - `+` — A new file has been added to the staging area
/// - `»` — A renamed file has been added to the staging area
/// - `✘` — A file's deletion has been added to the staging area
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("git_status");
let config: GitStatusConfig = GitStatusConfig::try_load(module.config);
// Return None if not in git repository
let repo = context.get_repo().ok()?;
if repo.kind.is_bare() {
log::debug!("This is a bare repository, git_status is not applicable");
return None;
}
if let Some(git_status) = git_status_wsl(context, &config) {
if git_status.is_empty() {
return None;
}
module.set_segments(Segment::from_text(None, git_status));
return Some(module);
}
let info = GitStatusInfo::load(context, repo, config.clone());
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|variable, _| match variable {
"all_status" => Some(ALL_STATUS_FORMAT),
_ => None,
})
.map_style(|variable: &str| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map_variables_to_segments(|variable: &str| {
let segments = match variable {
"stashed" => info.get_stashed().and_then(|count| {
format_count(config.stashed, "git_status.stashed", context, count)
}),
"ahead_behind" => info.get_ahead_behind().and_then(|(ahead, behind)| {
let (ahead, behind) = (ahead?, behind?);
if ahead > 0 && behind > 0 {
format_text(
config.diverged,
"git_status.diverged",
context,
|variable| match variable {
"ahead_count" => Some(ahead.to_string()),
"behind_count" => Some(behind.to_string()),
_ => None,
},
)
} else if ahead > 0 && behind == 0 {
format_count(config.ahead, "git_status.ahead", context, ahead)
} else if behind > 0 && ahead == 0 {
format_count(config.behind, "git_status.behind", context, behind)
} else {
format_symbol(config.up_to_date, "git_status.up_to_date", context)
}
}),
"conflicted" => info.get_conflicted().and_then(|count| {
format_count(config.conflicted, "git_status.conflicted", context, count)
}),
"deleted" => info.get_deleted().and_then(|count| {
format_count(config.deleted, "git_status.deleted", context, count)
}),
"renamed" => info.get_renamed().and_then(|count| {
format_count(config.renamed, "git_status.renamed", context, count)
}),
"modified" => info.get_modified().and_then(|count| {
format_count(config.modified, "git_status.modified", context, count)
}),
"staged" => info.get_staged().and_then(|count| {
format_count(config.staged, "git_status.staged", context, count)
}),
"untracked" => info.get_untracked().and_then(|count| {
format_count(config.untracked, "git_status.untracked", context, count)
}),
"typechanged" => info.get_typechanged().and_then(|count| {
format_count(config.typechanged, "git_status.typechanged", context, count)
}),
_ => None,
};
segments.map(Ok)
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => {
if segments.is_empty() {
return None;
}
segments
}
Err(error) => {
log::warn!("Error in module `git_status`:\n{error}");
return None;
}
});
Some(module)
}
struct GitStatusInfo<'a> {
context: &'a Context<'a>,
repo: &'a context::Repo,
config: GitStatusConfig<'a>,
repo_status: OnceLock<Option<Arc<RepoStatus>>>,
stashed_count: OnceLock<Option<usize>>,
}
impl<'a> GitStatusInfo<'a> {
pub fn load(
context: &'a Context,
repo: &'a context::Repo,
config: GitStatusConfig<'a>,
) -> Self {
Self {
context,
repo,
config,
repo_status: OnceLock::new(),
stashed_count: OnceLock::new(),
}
}
pub fn get_ahead_behind(&self) -> Option<(Option<usize>, Option<usize>)> {
self.get_repo_status().map(|data| (data.ahead, data.behind))
}
pub fn get_repo_status(&self) -> Option<&RepoStatus> {
self.repo_status
.get_or_init(|| {
get_static_repo_status(self.context, self.repo, &self.config).or_else(|| {
log::debug!("get_repo_status: git status execution failed");
None
})
})
.as_deref()
}
pub fn get_stashed(&self) -> &Option<usize> {
self.stashed_count.get_or_init(|| {
get_stashed_count(self.repo).or_else(|| {
log::debug!("get_stashed_count: git stash execution failed");
None
})
})
}
pub fn get_conflicted(&self) -> Option<usize> {
self.get_repo_status().map(|data| data.conflicted)
}
pub fn get_deleted(&self) -> Option<usize> {
self.get_repo_status().map(|data| data.deleted)
}
pub fn get_renamed(&self) -> Option<usize> {
self.get_repo_status().map(|data| data.renamed)
}
pub fn get_modified(&self) -> Option<usize> {
self.get_repo_status().map(|data| data.modified)
}
pub fn get_staged(&self) -> Option<usize> {
self.get_repo_status().map(|data| data.staged)
}
pub fn get_untracked(&self) -> Option<usize> {
self.get_repo_status().map(|data| data.untracked)
}
pub fn get_typechanged(&self) -> Option<usize> {
self.get_repo_status().map(|data| data.typechanged)
}
}
/// Return a globally shared version the repository status so it can be reused.
/// It's shared so those who received a copy can keep it, even if the next call uses a different
/// path so the cache is trashed.
///
/// The trashing is only expected when tests run though, as otherwise one path is used with a variety of modules.
pub(crate) fn get_static_repo_status(
context: &Context,
repo: &context::Repo,
config: &GitStatusConfig,
) -> Option<Arc<RepoStatus>> {
static REPO_STATUS: parking_lot::Mutex<Option<(Arc<RepoStatus>, PathBuf)>> =
parking_lot::Mutex::new(None);
let mut status = REPO_STATUS.lock();
let needs_update = status
.as_ref()
.is_none_or(|(_status, status_path)| status_path != &context.current_dir);
if needs_update {
*status = get_repo_status(context, repo, config)
.map(|status| (Arc::new(status), context.current_dir.clone()));
}
status.as_ref().map(|(status, _)| Arc::clone(status))
}
pub(crate) fn uses_reftables(repo: &gix::Repository) -> bool {
repo.config_snapshot()
.string("extensions.refstorage")
.is_some_and(|kind| kind.as_ref() == "reftable")
}
/// Gets the number of files in various git states (staged, modified, deleted, etc...)
fn get_repo_status(
context: &Context,
repo: &context::Repo,
config: &GitStatusConfig,
) -> Option<RepoStatus> {
log::debug!("New repo status created");
let mut repo_status = RepoStatus::default();
let gix_repo = repo.open();
// TODO: remove this special case once `gitoxide` can handle sparse indices for tree-index comparisons.
let has_untracked = !config.untracked.is_empty();
let git_config = gix_repo.config_snapshot();
if config.use_git_executable
|| repo.fs_monitor_value_is_true
|| uses_reftables(&repo.repo.to_thread_local())
|| gix_repo.index_or_empty().ok()?.is_sparse()
{
let mut args = vec!["status", "--porcelain=2"];
// for performance reasons, only pass flags if necessary...
let has_ahead_behind = !config.ahead.is_empty() || !config.behind.is_empty();
let has_up_to_date_diverged = !config.up_to_date.is_empty() || !config.diverged.is_empty();
if has_ahead_behind || has_up_to_date_diverged {
args.push("--branch");
}
// ... and add flags that omit information the user doesn't want
if !has_untracked {
args.push("--untracked-files=no");
}
if config.ignore_submodules {
args.push("--ignore-submodules=dirty");
} else if !has_untracked {
args.push("--ignore-submodules=untracked");
}
let status_output = repo.exec_git(context, &args)?;
let statuses = status_output.stdout.lines();
statuses.for_each(|status| {
if status.starts_with("# branch.ab ") {
repo_status.set_ahead_behind(status);
} else if !status.starts_with('#') {
repo_status.add(status);
}
});
} else {
let is_interrupted = Arc::new(AtomicBool::new(false));
std::thread::Builder::new()
.name("starship timer".into())
.stack_size(256 * 1024)
.spawn({
let is_interrupted = is_interrupted.clone();
let abort_after =
std::time::Duration::from_millis(context.root_config.command_timeout);
move || {
std::thread::sleep(abort_after);
is_interrupted.store(true, std::sync::atomic::Ordering::SeqCst);
}
})
.expect("should be able to spawn timer thread");
// We don't show details in submodules.
let check_dirty = true;
let status = gix_repo
.status(gix::features::progress::Discard)
.ok()?
.index_worktree_submodules(if config.ignore_submodules {
Submodule::Given {
ignore: gix::submodule::config::Ignore::Dirty,
check_dirty,
}
} else if !has_untracked {
Submodule::Given {
ignore: gix::submodule::config::Ignore::Untracked,
check_dirty,
}
} else {
Submodule::AsConfigured { check_dirty }
})
.index_worktree_options_mut(|opts| {
opts.thread_limit = if cfg!(target_os = "macos") {
Some(num_configured_starship_threads().unwrap_or(
// TODO: figure out good defaults for other platforms, maybe make it configurable.
// Git uses everything (if repo-size permits), but that's not the best choice for MacOS.
3,
))
} else {
Some(num_rayon_threads())
};
if config.untracked.is_empty() {
opts.dirwalk_options.take();
} else if let Some(opts) = opts.dirwalk_options.as_mut() {
opts.set_emit_untracked(gix::dir::walk::EmissionMode::Matching)
.set_emit_ignored(None)
.set_emit_pruned(false)
.set_emit_empty_directories(false);
}
})
.tree_index_track_renames(if config.renamed.is_empty() {
gix::status::tree_index::TrackRenames::Disabled
} else {
gix::status::tree_index::TrackRenames::Given(sanitize_rename_tracking(
// Get configured diff-rename configuration, or use default settings.
gix::diff::new_rewrites(&git_config, true)
.unwrap_or_default()
.0
.unwrap_or_default(),
))
})
.should_interrupt_owned(is_interrupted.clone());
// This will start the status machinery, collecting status items in the background.
// Thus, we can do some work in this thread without blocking, before starting to count status items.
let status = status.into_iter(None).ok()?;
// for performance reasons, only pass flags if necessary...
let has_ahead_behind = !config.ahead.is_empty() || !config.behind.is_empty();
let has_up_to_date_or_diverged =
!config.up_to_date.is_empty() || !config.diverged.is_empty();
if (has_ahead_behind || has_up_to_date_or_diverged)
&& let Some(branch_name) = gix_repo.head_name().ok().flatten().and_then(|ref_name| {
Vec::from(gix::bstr::BString::from(ref_name))
.into_string()
.ok()
})
{
let output = repo.exec_git(
context,
["for-each-ref", "--format", "%(upstream) %(upstream:track)"]
.into_iter()
.map(ToOwned::to_owned)
.chain(Some(branch_name)),
)?;
if let Some(line) = output.stdout.lines().next() {
repo_status.set_ahead_behind_for_each_ref(line);
}
}
for change in status.filter_map(Result::ok) {
use gix::status;
match &change {
status::Item::TreeIndex(change) => {
use gix::diff::index::Change;
match change {
Change::Addition { .. } | Change::Modification { .. } => {
repo_status.staged += 1;
}
Change::Deletion { .. } => {
repo_status.deleted += 1;
}
Change::Rewrite { .. } => {
repo_status.renamed += 1;
}
}
}
status::Item::IndexWorktree(change) => {
use gix::status::index_worktree::Item;
use gix::status::plumbing::index_as_worktree::{Change, EntryStatus};
match change {
Item::Modification {
status: EntryStatus::Conflict { .. },
..
} => {
repo_status.conflicted += 1;
}
Item::Modification {
status: EntryStatus::Change(Change::Removed),
..
} => {
repo_status.deleted += 1;
}
Item::Modification {
status:
EntryStatus::IntentToAdd
| EntryStatus::Change(
Change::Modification { .. } | Change::SubmoduleModification(_),
),
..
} => {
repo_status.modified += 1;
}
Item::Modification {
status: EntryStatus::Change(Change::Type { .. }),
..
} => {
repo_status.typechanged += 1;
}
Item::DirectoryContents {
entry:
gix::dir::Entry {
status: gix::dir::entry::Status::Untracked,
..
},
..
} => {
repo_status.untracked += 1;
}
Item::Rewrite { .. } => {
unreachable!(
"this kind of rename tracking isn't enabled by default and specific to gitoxide"
)
}
_ => {}
}
}
}
// Keep it for potential reuse by `git_metrics`
repo_status.changes.push(change);
}
if is_interrupted.load(std::sync::atomic::Ordering::Relaxed) {
repo_status = RepoStatus {
ahead: repo_status.ahead,
behind: repo_status.behind,
..Default::default()
};
}
}
Some(repo_status)
}
fn sanitize_rename_tracking(mut config: gix::diff::Rewrites) -> gix::diff::Rewrites {
config.limit = 100;
config
}
fn get_stashed_count(repo: &context::Repo) -> Option<usize> {
let repo = repo.open();
let reference = match repo.try_find_reference("refs/stash") {
// Only proceed if the found reference has the expected name (not tags/refs/stash etc.)
Ok(Some(reference)) if reference.name().as_bstr() == b"refs/stash".as_slice() => reference,
// No stash reference found
Ok(_) => return Some(0),
Err(err) => {
log::debug!("Error finding stash reference: {err}");
return None;
}
};
match reference.log_iter().all() {
Ok(Some(log)) => Some(log.count()),
Ok(None) => {
log::debug!("No reflog found for stash");
Some(0)
}
Err(err) => {
log::debug!("Error getting stash log: {err}");
None
}
}
}
#[derive(Default, Debug, Clone)]
pub(crate) struct RepoStatus {
ahead: Option<usize>,
behind: Option<usize>,
pub(crate) changes: Vec<gix::status::Item>,
conflicted: usize,
deleted: usize,
renamed: usize,
modified: usize,
staged: usize,
typechanged: usize,
untracked: usize,
}
impl RepoStatus {
fn is_deleted(short_status: &str) -> bool {
// is_wt_deleted || is_index_deleted
short_status.contains('D')
}
fn is_modified(short_status: &str) -> bool {
// is_wt_modified || is_wt_added
short_status.ends_with('M') || short_status.ends_with('A')
}
fn is_staged(short_status: &str) -> bool {
// is_index_modified || is_index_added || is_index_typechanged
short_status.starts_with('M')
|| short_status.starts_with('A')
|| short_status.starts_with('T')
}
fn is_typechanged(short_status: &str) -> bool {
short_status.ends_with('T')
}
fn parse_normal_status(&mut self, short_status: &str) {
if Self::is_deleted(short_status) {
self.deleted += 1;
}
if Self::is_modified(short_status) {
self.modified += 1;
}
if Self::is_staged(short_status) {
self.staged += 1;
}
if Self::is_typechanged(short_status) {
self.typechanged += 1;
}
}
fn add(&mut self, s: &str) {
match s.chars().next() {
Some('1') => self.parse_normal_status(&s[2..4]),
Some('2') => {
self.renamed += 1;
self.parse_normal_status(&s[2..4]);
}
Some('u') => self.conflicted += 1,
Some('?') => self.untracked += 1,
Some('!') => (),
Some(_) => log::error!("Unknown line type in git status output"),
None => log::error!("Missing line type in git status output"),
}
}
fn set_ahead_behind(&mut self, s: &str) {
let re = Regex::new(r"branch\.ab \+([0-9]+) \-([0-9]+)").unwrap();
if let Some(caps) = re.captures(s) {
self.ahead = caps.get(1).unwrap().as_str().parse::<usize>().ok();
self.behind = caps.get(2).unwrap().as_str().parse::<usize>().ok();
}
}
fn set_ahead_behind_for_each_ref(&mut self, mut s: &str) {
if s == " " || s.ends_with(" [gone]") {
self.ahead = None;
self.behind = None;
return;
}
s = s
.split_once(' ')
.unwrap()
.1
.trim_matches(|c| c == '[' || c == ']');
for pair in s.split(',') {
let mut tokens = pair.trim().splitn(2, ' ');
if let (Some(name), Some(number)) = (tokens.next(), tokens.next()) {
let storage = match name {
"ahead" => &mut self.ahead,
"behind" => &mut self.behind,
_ => return,
};
*storage = number.parse().ok();
}
}
for field in [&mut self.ahead, &mut self.behind] {
if field.is_none() {
*field = Some(0);
}
}
}
}
fn format_text<F>(
format_str: &str,
config_path: &str,
context: &Context,
mapper: F,
) -> Option<Vec<Segment>>
where
F: Fn(&str) -> Option<String> + Send + Sync,
{
if let Ok(formatter) = StringFormatter::new(format_str) {
formatter
.map(|variable| mapper(variable).map(Ok))
.parse(None, Some(context))
.ok()
} else {
log::warn!("Error parsing format string `{}`", &config_path);
None
}
}
fn format_count(
format_str: &str,
config_path: &str,
context: &Context,
count: usize,
) -> Option<Vec<Segment>> {
if count == 0 {
return None;
}
format_text(
format_str,
config_path,
context,
|variable| match variable {
"count" => Some(count.to_string()),
_ => None,
},
)
}
fn format_symbol(format_str: &str, config_path: &str, context: &Context) -> Option<Vec<Segment>> {
format_text(format_str, config_path, context, |_variable| None)
}
#[cfg(target_os = "linux")]
fn git_status_wsl(context: &Context, conf: &GitStatusConfig) -> Option<String> {
use crate::utils::create_command;
use nix::sys::utsname::uname;
use std::env;
use std::ffi::OsString;
use std::io::ErrorKind;
let starship_exe = conf.windows_starship?;
// Ensure this is WSL
// This is lowercase in WSL1 and uppercase in WSL2, just skip the first letter
if !uname()
.ok()?
.release()
.to_string_lossy()
.contains("icrosoft")
{
return None;
}
log::trace!("Using WSL mode");
// Get Windows path
let wslpath = create_command("wslpath")
.map(|mut c| {
c.arg("-w").arg(&context.current_dir);
c
})
.and_then(|mut c| c.output());
let winpath = match wslpath {
Ok(r) => r,
Err(e) => {
// Not found might means this might not be WSL after all
let level = if e.kind() == ErrorKind::NotFound {
log::Level::Debug
} else {
log::Level::Error
};
log::log!(level, "Failed to get Windows path:\n{e:?}");
return None;
}
};
let winpath = match std::str::from_utf8(&winpath.stdout) {
Ok(r) => r.trim_end(),
Err(e) => {
log::error!("Failed to parse Windows path:\n{e:?}");
return None;
}
};
log::trace!("Windows path: {winpath}");
// In Windows or Linux dir?
if winpath.starts_with(r"\\wsl") {
log::trace!("Not a Windows path");
return None;
}
// Get foreign starship to use WSL config
// https://devblogs.microsoft.com/commandline/share-environment-vars-between-wsl-and-windows/
let wslenv = env::var("WSLENV").map_or_else(
|_| "STARSHIP_CONFIG/wp".to_string(),
|e| e + ":STARSHIP_CONFIG/wp",
);
let exe = create_command(starship_exe)
.map(|mut c| {
c.env(
"STARSHIP_CONFIG",
context
.get_config_path_os()
.unwrap_or_else(|| OsString::from("/dev/null")),
)
.env("WSLENV", wslenv)
.args(["module", "git_status", "--path", winpath]);
c
})
.and_then(|mut c| c.output());
let out = match exe {
Ok(r) => r,
Err(e) => {
log::error!("Failed to run Git Status module on Windows:\n{e}");
return None;
}
};
match String::from_utf8(out.stdout) {
Ok(r) => Some(r),
Err(e) => {
log::error!("Failed to parse Windows Git Status module status output:\n{e}");
None
}
}
}
#[cfg(not(target_os = "linux"))]
fn git_status_wsl(_context: &Context, _conf: &GitStatusConfig) -> Option<String> {
None
}
#[cfg(test)]
pub(crate) mod tests {
use crate::test::{FixtureProvider, ModuleRenderer, fixture_repo};
use crate::utils::create_command;
use nu_ansi_term::{AnsiStrings, Color};
use std::ffi::OsStr;
use std::fs::{self, File, OpenOptions};
use std::io::{self, prelude::*};
use std::path::Path;
const NORMAL_AND_REFTABLES: [FixtureProvider; 2] =
[FixtureProvider::Git, FixtureProvider::GitReftable];
const BARE_AND_REFTABLE: [FixtureProvider; 2] =
[FixtureProvider::GitBare, FixtureProvider::GitBareReftable];
#[allow(clippy::unnecessary_wraps)]
fn format_output(symbols: &str) -> Option<String> {
Some(format!(
"{} ",
Color::Red.bold().paint(format!("[{symbols}]"))
))
}
#[test]
fn show_nothing_on_empty_dir() -> io::Result<()> {
let repo_dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("git_status")
.path(repo_dir.path())
.collect();
let expected = None;
assert_eq!(expected, actual);
repo_dir.close()
}
#[test]
fn shows_behind() -> io::Result<()> {
for mode in NORMAL_AND_REFTABLES {
let repo_dir = fixture_repo(mode)?;
behind(repo_dir.path())?;
let actual = ModuleRenderer::new("git_status")
.path(repo_dir.path())
.collect();
let expected = format_output("⇣");
assert_eq!(expected, actual);
repo_dir.close()?;
}
Ok(())
}
#[test]
fn shows_behind_with_count() -> io::Result<()> {
for mode in NORMAL_AND_REFTABLES {
let repo_dir = fixture_repo(mode)?;
behind(repo_dir.path())?;
let actual = ModuleRenderer::new("git_status")
.config(toml::toml! {
[git_status]
behind = "⇣$count"
})
.path(repo_dir.path())
.collect();
let expected = format_output("⇣1");
assert_eq!(expected, actual);
repo_dir.close()?;
}
Ok(())
}
#[test]
fn shows_ahead() -> io::Result<()> {
for mode in NORMAL_AND_REFTABLES {
let repo_dir = fixture_repo(mode)?;
File::create(repo_dir.path().join("readme.md"))?.sync_all()?;
ahead(repo_dir.path())?;
let actual = ModuleRenderer::new("git_status")
.path(repo_dir.path())
.collect();
let expected = format_output("⇡");
assert_eq!(expected, actual);
repo_dir.close()?;
}
Ok(())
}
#[test]
fn shows_ahead_with_count() -> io::Result<()> {
for mode in NORMAL_AND_REFTABLES {
let repo_dir = fixture_repo(mode)?;
File::create(repo_dir.path().join("readme.md"))?.sync_all()?;
ahead(repo_dir.path())?;
let actual = ModuleRenderer::new("git_status")
.config(toml::toml! {
[git_status]
ahead="⇡$count"
})
.path(repo_dir.path())
.collect();
let expected = format_output("⇡1");
assert_eq!(expected, actual);
repo_dir.close()?;
}
Ok(())
}
#[test]
fn shows_diverged() -> io::Result<()> {
for mode in NORMAL_AND_REFTABLES {
let repo_dir = fixture_repo(mode)?;
diverge(repo_dir.path())?;
let actual = ModuleRenderer::new("git_status")
.path(repo_dir.path())
.collect();
let expected = format_output("⇕");
assert_eq!(expected, actual);
repo_dir.close()?;
}
Ok(())
}
#[test]
fn shows_diverged_with_count() -> io::Result<()> {
for mode in NORMAL_AND_REFTABLES {
let repo_dir = fixture_repo(mode)?;
diverge(repo_dir.path())?;
let actual = ModuleRenderer::new("git_status")
.config(toml::toml! {
[git_status]
diverged=r"⇕⇡$ahead_count⇣$behind_count"
})
.path(repo_dir.path())
.collect();
let expected = format_output("⇕⇡1⇣1");
assert_eq!(expected, actual);
repo_dir.close()?;
}
Ok(())
}
#[test]
fn shows_up_to_date_with_upstream() -> io::Result<()> {
for mode in NORMAL_AND_REFTABLES {
let repo_dir = fixture_repo(mode)?;
let actual = ModuleRenderer::new("git_status")
.config(toml::toml! {
[git_status]
up_to_date="✓"
})
.path(repo_dir.path())
.collect();
let expected = format_output("✓");
assert_eq!(expected, actual);
repo_dir.close()?;
}
Ok(())
}
#[test]
fn hides_up_to_date_on_untracked_branch() -> io::Result<()> {
for mode in NORMAL_AND_REFTABLES {
let repo_dir = fixture_repo(mode)?;
create_branch(repo_dir.path())?;
let actual = ModuleRenderer::new("git_status")
.config(toml::toml! {
[git_status]
up_to_date="✓"
})
.path(repo_dir.path())
.collect();
let expected = None;
assert_eq!(expected, actual);
repo_dir.close()?;
}
Ok(())
}
#[test]
fn hides_up_to_date_on_gone_branch() -> io::Result<()> {
for mode in NORMAL_AND_REFTABLES {
let repo_dir = fixture_repo(mode)?;
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | true |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/elm.rs | src/modules/elm.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::elm::ElmConfig;
use crate::formatter::StringFormatter;
use crate::formatter::VersionFormatter;
/// Creates a module with the current Elm version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("elm");
let config: ElmConfig = ElmConfig::try_load(module.config);
let is_elm_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_elm_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 elm_version = context.exec_cmd("elm", &["--version"])?.stdout;
VersionFormatter::format_module_version(
module.get_name(),
elm_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 `elm`:\n{error}");
return None;
}
});
Some(module)
}
#[cfg(test)]
mod tests {
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
use std::fs::{self, File};
use std::io;
#[test]
fn folder_without_elm() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("elm").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_elm_json() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("elm.json"))?.sync_all()?;
let actual = ModuleRenderer::new("elm").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Cyan.bold().paint("🌳 v0.19.1 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_elm_package_json() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("elm-package.json"))?.sync_all()?;
let actual = ModuleRenderer::new("elm").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Cyan.bold().paint("🌳 v0.19.1 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_elm_version() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join(".elm-version"))?.sync_all()?;
let actual = ModuleRenderer::new("elm").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Cyan.bold().paint("🌳 v0.19.1 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_elm_stuff_directory() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let elmstuff = dir.path().join("elm-stuff");
fs::create_dir_all(elmstuff)?;
let actual = ModuleRenderer::new("elm").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Cyan.bold().paint("🌳 v0.19.1 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_elm_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("main.elm"))?.sync_all()?;
let actual = ModuleRenderer::new("elm").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Cyan.bold().paint("🌳 v0.19.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/dart.rs | src/modules/dart.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::dart::DartConfig;
use crate::formatter::StringFormatter;
use crate::formatter::VersionFormatter;
use crate::utils::get_command_string_output;
/// Creates a module with the current Dart version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("dart");
let config: DartConfig = DartConfig::try_load(module.config);
let is_dart_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_dart_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 command = context.exec_cmd("dart", &["--version"])?;
let dart_version = parse_dart_version(&get_command_string_output(command))?;
VersionFormatter::format_module_version(
module.get_name(),
&dart_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 `dart`:\n{error}");
return None;
}
});
Some(module)
}
fn parse_dart_version(dart_version: &str) -> Option<String> {
Some(
dart_version
// split into ["Dart", "VM", "version:", "2.8.4", "(stable)", ...]
.split_whitespace()
// return "2.8.4"
.nth(3)?
.to_string(),
)
}
#[cfg(test)]
mod tests {
use crate::test::ModuleRenderer;
use crate::utils::CommandOutput;
use nu_ansi_term::Color;
use std::fs::{self, File};
use std::io;
#[test]
fn folder_without_dart_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("dart").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_dart_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("any.dart"))?.sync_all()?;
let actual = ModuleRenderer::new("dart").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Blue.bold().paint("🎯 v2.8.4 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_dart_tool_directory() -> io::Result<()> {
let dir = tempfile::tempdir()?;
fs::create_dir_all(dir.path().join(".dart_tool"))?;
let actual = ModuleRenderer::new("dart").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Blue.bold().paint("🎯 v2.8.4 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_pubspec_yaml_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("pubspec.yaml"))?.sync_all()?;
let actual = ModuleRenderer::new("dart").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Blue.bold().paint("🎯 v2.8.4 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_pubspec_yml_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("pubspec.yml"))?.sync_all()?;
let actual = ModuleRenderer::new("dart").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Blue.bold().paint("🎯 v2.8.4 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_pubspec_lock_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("pubspec.lock"))?.sync_all()?;
let actual = ModuleRenderer::new("dart").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Blue.bold().paint("🎯 v2.8.4 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn detect_version_output_in_stdout() -> io::Result<()> {
// after dart 2.15.0, version info output in stdout.
let dir = tempfile::tempdir()?;
File::create(dir.path().join("any.dart"))?.sync_all()?;
let actual = ModuleRenderer::new("dart")
.cmd(
"dart --version",
Some(CommandOutput {
stdout: String::from("Dart SDK version: 2.15.1 (stable) (Tue Dec 14 13:32:21 2021 +0100) on \"linux_x64\""),
stderr: String::default(),
}),
)
.path(dir.path())
.collect();
let expected = Some(format!("via {}", Color::Blue.bold().paint("🎯 v2.15.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/gleam.rs | src/modules/gleam.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::gleam::GleamConfig;
use crate::formatter::StringFormatter;
use crate::formatter::VersionFormatter;
/// Creates a module with the current Gleam version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("gleam");
let config = GleamConfig::try_load(module.config);
let is_gleam_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_gleam_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 gleam_version =
parse_gleam_version(&context.exec_cmd("gleam", &["--version"])?.stdout)?;
VersionFormatter::format_module_version(
module.get_name(),
&gleam_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 `gleam`:\n{error}");
return None;
}
});
Some(module)
}
fn parse_gleam_version(version: &str) -> Option<String> {
let version = version.split_whitespace().last()?;
Some(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_folder_without_gleam_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("gleam").path(dir.path()).collect();
let expected = None;
assert_eq!(actual, expected);
dir.close()
}
#[test]
fn test_folder_with_gleam_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("hello.gleam"))?.sync_all()?;
let actual = ModuleRenderer::new("gleam").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Rgb(255, 175, 243).bold().paint("⭐ v1.0.0 ")
));
assert_eq!(actual, expected);
dir.close()
}
#[test]
fn test_folder_with_gleam_toml() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("gleam.toml"))?.sync_all()?;
let actual = ModuleRenderer::new("gleam").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Rgb(255, 175, 243).bold().paint("⭐ v1.0.0 ")
));
assert_eq!(actual, expected);
dir.close()
}
#[test]
fn test_parse_gleam_version() {
let version = "gleam 1.0.0";
assert_eq!(parse_gleam_version(version), Some("1.0.0".to_string()));
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/scala.rs | src/modules/scala.rs | use crate::configs::scala::ScalaConfig;
use crate::formatter::StringFormatter;
use super::{Context, Module, ModuleConfig};
use crate::formatter::VersionFormatter;
use crate::utils::get_command_string_output;
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("scala");
let config: ScalaConfig = ScalaConfig::try_load(module.config);
let is_scala_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_scala_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 scala_version = get_scala_version(context)?;
VersionFormatter::format_module_version(
module.get_name(),
&scala_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 `scala`:\n{error}");
return None;
}
});
Some(module)
}
fn get_scala_version(context: &Context) -> Option<String> {
// try to get the version from scala-cli first as it is faster
// and return ONLY the version which save us from parsing the version string
context
.exec_cmd("scala-cli", &["version", "--scala"])
.filter(|out| !out.stdout.is_empty())
.map(|std_out_only| std_out_only.stdout.trim().to_string())
.or_else(|| {
let command = context.exec_cmd("scalac", &["-version"])?;
let scala_version_string = get_command_string_output(command);
parse_scala_version(&scala_version_string)
})
}
fn parse_scala_version(scala_version_string: &str) -> Option<String> {
let version = scala_version_string
// split into ["Scala", "compiler", "version", "2.13.5", "--", ...]
.split_whitespace()
// take "2.13.5"
.nth(3)?;
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 test_parse_scala_version() {
let scala_2_13 =
"Scala compiler version 2.13.5 -- Copyright 2002-2020, LAMP/EPFL and Lightbend, Inc.";
assert_eq!(parse_scala_version(scala_2_13), Some("2.13.5".to_string()));
}
#[test]
fn test_parse_dotty_version() {
let dotty_version = "Scala compiler version 3.0.0-RC1 -- Copyright 2002-2021, LAMP/EPFL";
assert_eq!(
parse_scala_version(dotty_version),
Some("3.0.0-RC1".to_string())
);
}
#[test]
fn folder_without_scala_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("scala").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_scala_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("Test.scala"))?.sync_all()?;
let actual = ModuleRenderer::new("scala").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Red.bold().paint("🆂 v3.4.1 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_scala_file_using_scala_cli_only() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("Test.scala"))?.sync_all()?;
let actual = ModuleRenderer::new("scala")
// for test purpose only real use case will have both in path
.cmd("scalac -version", None)
.path(dir.path())
.collect();
let expected = Some(format!("via {}", Color::Red.bold().paint("🆂 v3.4.1 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_scala_file_no_scala_installed() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("Test.scala"))?.sync_all()?;
let actual = ModuleRenderer::new("scala")
.cmd("scala-cli version --scala", None)
.cmd("scalac -version", None)
.path(dir.path())
.collect();
let expected = Some(format!("via {}", Color::Red.bold().paint("🆂 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_sbt_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("build.sbt"))?.sync_all()?;
let actual = ModuleRenderer::new("scala").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Red.bold().paint("🆂 v3.4.1 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_scala_env_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join(".scalaenv"))?.sync_all()?;
let actual = ModuleRenderer::new("scala").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Red.bold().paint("🆂 v3.4.1 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_sbt_env_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join(".sbtenv"))?.sync_all()?;
let actual = ModuleRenderer::new("scala").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Red.bold().paint("🆂 v3.4.1 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_metals_dir() -> io::Result<()> {
let dir = tempfile::tempdir()?;
fs::create_dir_all(dir.path().join(".metals"))?;
let actual = ModuleRenderer::new("scala").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Red.bold().paint("🆂 v3.4.1 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_sbt_file_without_scala_cli() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("build.sbt"))?.sync_all()?;
let actual = ModuleRenderer::new("scala")
.cmd("scala-cli version --scala", None)
.path(dir.path())
.collect();
let expected = Some(format!("via {}", Color::Red.bold().paint("🆂 v2.13.5 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_scala_env_file_without_scala_cli() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join(".scalaenv"))?.sync_all()?;
let actual = ModuleRenderer::new("scala")
.cmd("scala-cli version --scala", None)
.path(dir.path())
.collect();
let expected = Some(format!("via {}", Color::Red.bold().paint("🆂 v2.13.5 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_sbt_env_file_without_scala_cli() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join(".sbtenv"))?.sync_all()?;
let actual = ModuleRenderer::new("scala")
.cmd("scala-cli version --scala", None)
.path(dir.path())
.collect();
let expected = Some(format!("via {}", Color::Red.bold().paint("🆂 v2.13.5 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_metals_dir_without_scala_cli() -> io::Result<()> {
let dir = tempfile::tempdir()?;
fs::create_dir_all(dir.path().join(".metals"))?;
let actual = ModuleRenderer::new("scala")
.cmd("scala-cli version --scala", None)
.path(dir.path())
.collect();
let expected = Some(format!("via {}", Color::Red.bold().paint("🆂 v2.13.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/julia.rs | src/modules/julia.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::julia::JuliaConfig;
use crate::formatter::StringFormatter;
use crate::formatter::VersionFormatter;
/// Creates a module with the current Julia version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("julia");
let config = JuliaConfig::try_load(module.config);
let is_julia_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_julia_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 julia_version =
parse_julia_version(&context.exec_cmd("julia", &["--version"])?.stdout)?;
VersionFormatter::format_module_version(
module.get_name(),
&julia_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 `julia`:\n{error}");
return None;
}
});
Some(module)
}
fn parse_julia_version(julia_stdout: &str) -> Option<String> {
// julia version output looks like this:
// julia version 1.4.0
let version = julia_stdout
// split into ("", "1.4.0")
.split_once("julia version")?
// return "1.4.0"
.1
.split_whitespace()
.next()?;
Some(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 folder_without_julia_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("julia").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_julia_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("hello.jl"))?.sync_all()?;
let actual = ModuleRenderer::new("julia").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Purple.bold().paint("ஃ v1.4.0 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_project_toml() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("Project.toml"))?.sync_all()?;
let actual = ModuleRenderer::new("julia").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Purple.bold().paint("ஃ v1.4.0 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_manifest_toml() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("Manifest.toml"))?.sync_all()?;
let actual = ModuleRenderer::new("julia").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Purple.bold().paint("ஃ v1.4.0 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn test_parse_julia_version() {
let input = "julia version 1.4.0";
assert_eq!(parse_julia_version(input), Some("1.4.0".to_string()));
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/vlang.rs | src/modules/vlang.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::v::VConfig;
use crate::formatter::{StringFormatter, VersionFormatter};
/// Creates a module with the current V version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("vlang");
let config = VConfig::try_load(module.config);
let is_v_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_v_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" => context
.exec_cmd("v", &["version"])
.map(|output| parse_v_version(&output.stdout))?
.map(|output| {
VersionFormatter::format_module_version(
module.get_name(),
&output,
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 `vlang`:\n{error}");
return None;
}
});
Some(module)
}
fn parse_v_version(v_version: &str) -> Option<String> {
let version = v_version
// split into ["V", "0.2", "30c0659"]
.split_whitespace()
// return "0.2"
.nth(1)?;
Some(version.to_owned())
}
#[cfg(test)]
mod tests {
use super::parse_v_version;
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
use std::fs::File;
use std::io;
#[test]
fn test_parse_v_version() {
const OUTPUT: &str = "V 0.2 30c0659\n";
assert_eq!(parse_v_version(OUTPUT), Some("0.2".to_string()));
}
#[test]
fn folder_without_v_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("vlang").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_v_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("hello.v"))?.sync_all()?;
let actual = ModuleRenderer::new("vlang").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Blue.bold().paint("V v0.2 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_vmod_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("v.mod"))?.sync_all()?;
let actual = ModuleRenderer::new("vlang").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Blue.bold().paint("V v0.2 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_vpkg_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("vpkg.json"))?.sync_all()?;
let actual = ModuleRenderer::new("vlang").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Blue.bold().paint("V v0.2 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_vpkg_lockfile() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join(".vpkg-lock.json"))?.sync_all()?;
let actual = ModuleRenderer::new("vlang").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Blue.bold().paint("V v0.2 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn version_formatting() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("hello.v"))?.sync_all()?;
let actual = ModuleRenderer::new("vlang")
.path(dir.path())
.config(toml::toml! {
[vlang]
version_format = "${raw}"
})
.collect();
let expected = Some(format!("via {}", Color::Blue.bold().paint("V 0.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/purescript.rs | src/modules/purescript.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::purescript::PureScriptConfig;
use crate::formatter::StringFormatter;
use crate::formatter::VersionFormatter;
/// Creates a module with the current PureScript version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("purescript");
let config: PureScriptConfig = PureScriptConfig::try_load(module.config);
let is_purs_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_folders(&config.detect_folders)
.set_extensions(&config.detect_extensions)
.is_match();
if !is_purs_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 purs_version = context.exec_cmd("purs", &["--version"])?.stdout;
VersionFormatter::format_module_version(
module.get_name(),
purs_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 `purescript`:\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_purescript_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("purescript").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_purescript_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("Main.purs"))?.sync_all()?;
let actual = ModuleRenderer::new("purescript").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::White.bold().paint("<=> v0.13.5 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_spago_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("spago.dhall"))?.sync_all()?;
let actual = ModuleRenderer::new("purescript").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::White.bold().paint("<=> v0.13.5 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_spago_yaml_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("spago.yaml"))?.sync_all()?;
let actual = ModuleRenderer::new("purescript").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::White.bold().paint("<=> v0.13.5 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_spago_lock_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("spago.lock"))?.sync_all()?;
let actual = ModuleRenderer::new("purescript").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::White.bold().paint("<=> v0.13.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/vcsh.rs | src/modules/vcsh.rs | use super::{Context, Module};
use crate::config::ModuleConfig;
use crate::configs::vcsh::VcshConfig;
use crate::formatter::StringFormatter;
/// Creates a module that displays VCSH repository currently in use
///
/// Will display the name of the current VCSH repository if one is active.
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let repo = context.get_env("VCSH_REPO_NAME").unwrap_or_default();
if repo.trim().is_empty() {
return None;
}
let mut module = context.new_module("vcsh");
let config: VcshConfig = VcshConfig::try_load(module.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 {
"repo" => Some(Ok(&repo)),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `vcsh`:\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("vcsh").collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn env_set() {
let actual = ModuleRenderer::new("vcsh")
.env("VCSH_REPO_NAME", "astronauts")
.collect();
let expected = Some(format!(
"vcsh {} ",
Color::Yellow.bold().paint("astronauts")
));
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/red.rs | src/modules/red.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::red::RedConfig;
use crate::formatter::{StringFormatter, VersionFormatter};
/// Creates a module with the current Red version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("red");
let config = RedConfig::try_load(module.config);
let is_red_project = context
.try_begin_scan()?
.set_files(&config.detect_files)
.set_extensions(&config.detect_extensions)
.set_folders(&config.detect_folders)
.is_match();
if !is_red_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" => context
.exec_cmd("red", &["--version"])
.map(|output| {
VersionFormatter::format_module_version(
module.get_name(),
output.stdout.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 `red`:\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_red_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("red").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_red_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("hello.red"))?.sync_all()?;
let actual = ModuleRenderer::new("red").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Red.bold().paint("🔺 v0.6.4 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_reds_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("hello.reds"))?.sync_all()?;
let actual = ModuleRenderer::new("red").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Red.bold().paint("🔺 v0.6.4 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn version_formatting() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("hello.red"))?.sync_all()?;
let actual = ModuleRenderer::new("red")
.path(dir.path())
.config(toml::toml! {
[red]
version_format = "${raw}"
})
.collect();
let expected = Some(format!("via {}", Color::Red.bold().paint("🔺 0.6.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/os.rs | src/modules/os.rs | use super::{Context, Module, ModuleConfig};
use crate::configs::os::OSConfig;
use crate::formatter::StringFormatter;
/// Creates a module with the current operating system
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("os");
let config: OSConfig = OSConfig::try_load(module.config);
if config.disabled {
return None;
}
#[cfg(not(test))]
let os = os_info::get();
#[cfg(test)]
let os = os_info::Info::default();
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|variable, _| match variable {
"symbol" => get_symbol(&config, os.os_type()),
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map(|variable| match variable {
"codename" => get_codename(&os).map(Ok),
"edition" => get_edition(&os).map(Ok),
"name" => get_name(&os).map(Ok),
"type" => get_type(&os).map(Ok),
"version" => get_version(&os).map(Ok),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `os`:\n{error}");
return None;
}
});
Some(module)
}
// Get the operating system symbol from user config, or else default config
// when user has not defined a symbol for the operating system.
fn get_symbol<'a>(config: &'a OSConfig, os_type: os_info::Type) -> Option<&'a str> {
config
.get_symbol(os_type)
.or_else(|| OSConfig::default().get_symbol(os_type))
}
fn get_codename(os: &os_info::Info) -> Option<String> {
os.codename().map(String::from)
}
fn get_edition(os: &os_info::Info) -> Option<String> {
os.edition().map(String::from)
}
fn get_name(os: &os_info::Info) -> Option<String> {
Some(os.os_type().to_string())
}
fn get_type(os: &os_info::Info) -> Option<String> {
// String from os_info::Type
Some(format!("{:?}", os.os_type()))
}
fn get_version(os: &os_info::Info) -> Option<String> {
Some(os.version())
.filter(|&x| x != &os_info::Version::Unknown)
.map(os_info::Version::to_string)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test::ModuleRenderer;
use nu_ansi_term::Color;
use os_info::Type;
#[test]
fn default() {
let actual = ModuleRenderer::new("os").collect();
assert_eq!(actual, None);
}
#[test]
fn default_enabled() {
let actual = ModuleRenderer::new("os")
.config(toml::toml! {
[os]
disabled = false
})
.collect();
let expected = Some(format!("{}", Color::White.bold().paint("❓ ")));
assert_eq!(actual, expected);
}
#[test]
fn all_segments() {
let actual = ModuleRenderer::new("os")
.config(toml::toml! {
[os]
disabled = false
format = "[$symbol($codename )($edition )($name )($type )($version )]($style)"
})
.collect();
let expected = Some(format!(
"{}",
Color::White.bold().paint("❓ Unknown Unknown ")
));
assert_eq!(actual, expected);
}
#[test]
fn get_symbol_default() {
let config = OSConfig::default();
let type_expected_pairs = [
(Type::Alpine, Some("🏔️ ")),
(Type::Amazon, Some("🙂 ")),
(Type::Android, Some("🤖 ")),
(Type::AOSC, Some("🐱 ")),
(Type::Arch, Some("🎗️ ")),
(Type::CentOS, Some("💠 ")),
(Type::Debian, Some("🌀 ")),
(Type::DragonFly, Some("🐉 ")),
(Type::Emscripten, Some("🔗 ")),
(Type::EndeavourOS, Some("🚀 ")),
(Type::Fedora, Some("🎩 ")),
(Type::FreeBSD, Some("😈 ")),
(Type::Garuda, Some("🦅 ")),
(Type::Gentoo, Some("🗜️ ")),
(Type::HardenedBSD, Some("🛡️ ")),
(Type::Illumos, Some("🐦 ")),
(Type::Linux, Some("🐧 ")),
(Type::Macos, Some("🍎 ")),
(Type::Manjaro, Some("🥭 ")),
(Type::Mariner, Some("🌊 ")),
(Type::MidnightBSD, Some("🌘 ")),
(Type::Mint, Some("🌿 ")),
(Type::NetBSD, Some("🚩 ")),
(Type::NixOS, Some("❄️ ")),
(Type::OpenBSD, Some("🐡 ")),
(Type::openSUSE, Some("🦎 ")),
(Type::OracleLinux, Some("🦴 ")),
(Type::Pop, Some("🍭 ")),
(Type::Raspbian, Some("🍓 ")),
(Type::Redhat, Some("🎩 ")),
(Type::RedHatEnterprise, Some("🎩 ")),
(Type::Redox, Some("🧪 ")),
(Type::Solus, Some("⛵ ")),
(Type::SUSE, Some("🦎 ")),
(Type::Ubuntu, Some("🎯 ")),
(Type::Unknown, Some("❓ ")),
(Type::Windows, Some("🪟 ")),
];
for (t, e) in type_expected_pairs {
assert_eq!(get_symbol(&config, t), e);
}
}
#[test]
fn get_symbol_custom() {
let config_toml = toml::toml! {
[symbols]
Alpine = " "
Amazon = " "
Android = " "
AOSC = " "
Arch = " "
CentOS = " "
Debian = " "
DragonFly = " "
Emscripten = " "
EndeavourOS = " "
Fedora = " "
FreeBSD = " "
Garuda = " "
Gentoo = " "
HardenedBSD = " "
Illumos = " "
Linux = " "
Macos = " "
Manjaro = " "
Mariner = " "
MidnightBSD = " "
Mint = " "
NetBSD = " "
NixOS = " "
OpenBSD = " "
SUSE = " "
OracleLinux = " "
Pop = " "
Raspbian = " "
Redhat = " "
RedHatEnterprise = " "
Redox = " "
Solus = " "
openSUSE = " "
Ubuntu = " "
Unknown = " "
Windows = " "
};
let config = OSConfig::load(&config_toml);
let type_expected_pairs = [
(Type::Alpine, Some(" ")),
(Type::Amazon, Some(" ")),
(Type::Android, Some(" ")),
(Type::AOSC, Some(" ")),
(Type::Arch, Some(" ")),
(Type::CentOS, Some(" ")),
(Type::Debian, Some(" ")),
(Type::DragonFly, Some(" ")),
(Type::Emscripten, Some(" ")),
(Type::EndeavourOS, Some(" ")),
(Type::Fedora, Some(" ")),
(Type::FreeBSD, Some(" ")),
(Type::Garuda, Some(" ")),
(Type::Gentoo, Some(" ")),
(Type::HardenedBSD, Some(" ")),
(Type::Illumos, Some(" ")),
(Type::Linux, Some(" ")),
(Type::Macos, Some(" ")),
(Type::Manjaro, Some(" ")),
(Type::Mariner, Some(" ")),
(Type::MidnightBSD, Some(" ")),
(Type::Mint, Some(" ")),
(Type::NetBSD, Some(" ")),
(Type::NixOS, Some(" ")),
(Type::OpenBSD, Some(" ")),
(Type::SUSE, Some(" ")),
(Type::OracleLinux, Some(" ")),
(Type::Pop, Some(" ")),
(Type::Raspbian, Some(" ")),
(Type::Redhat, Some(" ")),
(Type::RedHatEnterprise, Some(" ")),
(Type::Redox, Some(" ")),
(Type::Solus, Some(" ")),
(Type::openSUSE, Some(" ")),
(Type::Ubuntu, Some(" ")),
(Type::Unknown, Some(" ")),
(Type::Windows, Some(" ")),
];
for (t, e) in type_expected_pairs {
assert_eq!(get_symbol(&config, t), e);
}
}
#[test]
fn get_symbol_fallback() {
let config_toml = toml::toml! {
[symbols]
Unknown = ""
Arch = "Arch is the best!"
};
let config = OSConfig::load(&config_toml);
let type_expected_pairs = [
(Type::Alpine, Some("🏔️ ")),
(Type::Amazon, Some("🙂 ")),
(Type::Android, Some("🤖 ")),
(Type::AOSC, Some("🐱 ")),
(Type::Arch, Some("Arch is the best!")),
(Type::CentOS, Some("💠 ")),
(Type::Debian, Some("🌀 ")),
(Type::DragonFly, Some("🐉 ")),
(Type::Emscripten, Some("🔗 ")),
(Type::EndeavourOS, Some("🚀 ")),
(Type::Fedora, Some("🎩 ")),
(Type::FreeBSD, Some("😈 ")),
(Type::Garuda, Some("🦅 ")),
(Type::Gentoo, Some("🗜️ ")),
(Type::HardenedBSD, Some("🛡️ ")),
(Type::Illumos, Some("🐦 ")),
(Type::Linux, Some("🐧 ")),
(Type::Macos, Some("🍎 ")),
(Type::Manjaro, Some("🥭 ")),
(Type::Mariner, Some("🌊 ")),
(Type::MidnightBSD, Some("🌘 ")),
(Type::Mint, Some("🌿 ")),
(Type::NetBSD, Some("🚩 ")),
(Type::NixOS, Some("❄️ ")),
(Type::OpenBSD, Some("🐡 ")),
(Type::openSUSE, Some("🦎 ")),
(Type::OracleLinux, Some("🦴 ")),
(Type::Pop, Some("🍭 ")),
(Type::Raspbian, Some("🍓 ")),
(Type::Redhat, Some("🎩 ")),
(Type::RedHatEnterprise, Some("🎩 ")),
(Type::Redox, Some("🧪 ")),
(Type::Solus, Some("⛵ ")),
(Type::SUSE, Some("🦎 ")),
(Type::Ubuntu, Some("🎯 ")),
(Type::Unknown, Some("")),
(Type::Windows, Some("🪟 ")),
];
for (t, e) in type_expected_pairs {
assert_eq!(get_symbol(&config, t), e);
}
}
#[test]
fn warn_on_os_info_update() {
#[deny(clippy::wildcard_enum_match_arm)]
// This closure is the same as the default config symbols list.
// When this clippy test fails, a new default symbol should be added to
// `config/os.rs` to exhaustively match new possible `os_info::Type` cases.
// Affects:
// - crate::configs::os::OSConfig::default()
// - crate::modules::os::tests
// - docs/config/README.md/#Configuration/#OS/#Options
// - docs/config/README.md/#Configuration/#OS/#Example
// - docs/public/presets/toml/plain-text-symbols.toml
// - dosc/public/presets/toml/nerd-font-symbols.toml
// - .github/config-schema.json
let _ = |t: Type| match t {
Type::AIX => "➿ ",
Type::Alpaquita => "🔔 ",
Type::Alpine => "🏔️ ",
Type::ALTLinux => "Ⓐ ",
Type::Amazon => "🙂 ",
Type::Android => "🤖 ",
Type::AOSC => "🐱 ",
Type::Arch | Type::Artix | Type::CachyOS => "🎗️ ",
Type::Bluefin => "🐟 ",
Type::CentOS | Type::AlmaLinux | Type::RockyLinux => "💠 ",
Type::Cygwin => "",
Type::Debian => "🌀 ",
Type::DragonFly => "🐉 ",
Type::Elementary => "🍏 ",
Type::Emscripten => "🔗 ",
Type::EndeavourOS => "🚀 ",
Type::Fedora | Type::Nobara | Type::Redhat | Type::RedHatEnterprise => "🎩 ",
Type::FreeBSD => "😈 ",
Type::Garuda => "🦅 ",
Type::Gentoo => "🗜️ ",
Type::HardenedBSD => "🛡️ ",
Type::Illumos => "🐦 ",
Type::Ios => "📱 ",
Type::InstantOS => "⏲️ ",
Type::Kali => "🐉 ",
Type::Linux => "🐧 ",
Type::Mabox => "📦 ",
Type::Macos => "🍎 ",
Type::Manjaro => "🥭 ",
Type::Mariner => "🌊 ",
Type::MidnightBSD => "🌘 ",
Type::Mint => "🌿 ",
Type::NetBSD => "🚩 ",
Type::NixOS => "❄️ ",
Type::OpenBSD => "🐡 ",
Type::OpenCloudOS => "☁️ ",
Type::openEuler => "🦉 ",
Type::openSUSE => "🦎 ",
Type::OracleLinux => "🦴 ",
Type::PikaOS => "🐤 ",
Type::Pop => "🍭 ",
Type::Raspbian => "🍓 ",
Type::Redox => "🧪 ",
Type::Solus => "⛵ ",
Type::SUSE => "🦎 ",
Type::Ubuntu => "🎯 ",
Type::Ultramarine => "🔷 ",
Type::Unknown => "❓ ",
Type::Uos => "🐲 ",
Type::Void => " ",
Type::Windows => "🪟 ",
Type::Zorin => "🔹 ",
_ => "",
};
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/c.rs | src/modules/c.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::C)
}
#[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_c_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("c").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_c_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("any.c"))?.sync_all()?;
// What happens when `cc --version` says it's modern gcc?
// The case when it claims to be clang is covered in folder_with_h_file,
// and uses the mock in src/test/mod.rs.
let actual = ModuleRenderer::new("c")
.cmd(
"cc --version",
Some(CommandOutput {
stdout: String::from(
"\
cc (Debian 10.2.1-6) 10.2.1 20210110
Copyright (C) 2020 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 v10.2.1-gcc ")
));
assert_eq!(expected, actual);
// What happens when `cc --version` says it's ancient gcc?
let actual = ModuleRenderer::new("c")
.cmd(
"cc --version",
Some(CommandOutput {
stdout: String::from(
"\
cc (GCC) 3.3.5 (Debian 1:3.3.5-13)
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-gcc ")
));
assert_eq!(expected, actual);
// What happens with an unknown C compiler? Needless to say, we're
// not running on a Z80 so we're never going to see this one in reality!
let actual = ModuleRenderer::new("c")
.cmd(
"cc --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 'cc --version' doesn't work, but 'gcc --version' does?
// This stubs out `cc` but we'll fall back to `gcc --version` as defined in
// src/test/mod.rs.
// Also we don't bother to redefine the config for this one, as we've already
// proved we can parse its version.
let actual = ModuleRenderer::new("c")
.cmd("cc --version", None)
.path(dir.path())
.collect();
let expected = Some(format!(
"via {}",
Color::Fixed(149).bold().paint("C v10.2.1-gcc ")
));
assert_eq!(expected, actual);
// Now with both 'cc' and 'gcc' not working, this should fall back to 'clang --version'
let actual = ModuleRenderer::new("c")
.cmd("cc --version", None)
.cmd("gcc --version", None)
.path(dir.path())
.collect();
let expected = Some(format!(
"via {}",
Color::Fixed(149).bold().paint("C v11.1.0-clang ")
));
assert_eq!(expected, actual);
// What happens when we can't find any of cc, gcc or clang?
let actual = ModuleRenderer::new("c")
.cmd("cc --version", None)
.cmd("gcc --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_h_file() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("any.h"))?.sync_all()?;
let actual = ModuleRenderer::new("c").path(dir.path()).collect();
let expected = Some(format!(
"via {}",
Color::Fixed(149).bold().paint("C v11.0.1-clang ")
));
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/container.rs | src/modules/container.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 super::ModuleConfig;
use crate::configs::container::ContainerConfig;
use crate::formatter::StringFormatter;
use crate::utils::{self, read_file};
pub fn container_name(context: &Context) -> Option<String> {
use crate::utils::context_path;
if context_path(context, "/proc/vz").exists() && !context_path(context, "/proc/bc").exists()
{
// OpenVZ
return Some("OpenVZ".into());
}
if context_path(context, "/run/host/container-manager").exists() {
// OCI
return Some("OCI".into());
}
if context_path(context, "/dev/incus/sock").exists() {
// Incus
return Some("Incus".into());
}
let container_env_path = context_path(context, "/run/.containerenv");
if container_env_path.exists() {
// podman and others
let image_res = read_file(container_env_path)
.map(|s| {
s.lines()
.find_map(|l| {
if let Some(name_val) = l.strip_prefix("name=\"") {
return name_val.strip_suffix('"').map(|n| n.to_string());
}
l.starts_with("image=\"").then(|| {
let r = l.split_at(7).1;
let name = r.rfind('/').map(|n| r.split_at(n + 1).1);
String::from(name.unwrap_or(r).trim_end_matches('"'))
})
})
.unwrap_or_else(|| "podman".into())
})
.unwrap_or_else(|_| "podman".into());
return Some(image_res);
}
// WSL with systemd will set the contents of this file to "wsl"
// Avoid showing the container module in that case
// Honor the contents of this file if "docker" and not running in podman or wsl
let systemd_path = context_path(context, "/run/systemd/container");
if let Ok(s) = utils::read_file(systemd_path) {
match s.trim() {
"docker" => return Some("Docker".into()),
"wsl" => (),
_ => return Some("Systemd".into()),
}
}
if context_path(context, "/.dockerenv").exists() {
// docker
return Some("Docker".into());
}
None
}
let mut module = context.new_module("container");
let config: ContainerConfig = ContainerConfig::try_load(module.config);
if config.disabled {
return None;
}
let container_name = container_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(&container_name)),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `container`: \n{error}");
return None;
}
});
Some(module)
}
#[cfg(test)]
mod tests {
use crate::test::ModuleRenderer;
use crate::utils;
use nu_ansi_term::Color;
use std::fs;
#[test]
fn test_none_if_disabled() {
let expected = None;
let actual = ModuleRenderer::new("container")
// For a custom config
.config(toml::toml! {
[container]
disabled = true
})
// Run the module and collect the output
.collect();
assert_eq!(expected, actual);
}
fn containerenv(
image: Option<&str>,
name: Option<&str>,
) -> std::io::Result<(Option<String>, Option<String>)> {
let renderer = ModuleRenderer::new("container")
// For a custom config
.config(toml::toml! {
[container]
disabled = false
});
let root_path = renderer.root_path();
// simulate file found on ubuntu images to ensure podman containerenv is preferred
let systemd_path = root_path.join("run/systemd/container");
fs::create_dir_all(systemd_path.parent().unwrap())?;
utils::write_file(&systemd_path, "docker\n")?;
let containerenv = root_path.join("run/.containerenv");
fs::create_dir_all(containerenv.parent().unwrap())?;
let contents = name.map(|n| format!("name=\"{n}\"\n")).unwrap_or_default()
+ &image
.map(|i| format!("image=\"{i}\"\n"))
.unwrap_or_default();
utils::write_file(&containerenv, contents)?;
// The output of the module
let actual = renderer
// Run the module and collect the output
.collect();
// The value that should be rendered by the module.
let expected = Some(format!(
"{} ",
Color::Red.bold().dimmed().paint(format!(
"⬢ [{}]",
name.unwrap_or_else(|| image.unwrap_or("podman"))
))
));
Ok((actual, expected))
}
#[test]
#[cfg(target_os = "linux")]
fn test_containerenv() -> std::io::Result<()> {
let (actual, expected) = containerenv(None, None)?;
// Assert that the actual and expected values are the same
assert_eq!(actual, expected);
Ok(())
}
#[test]
#[cfg(target_os = "linux")]
fn test_containerenv_fedora() -> std::io::Result<()> {
let (actual, expected) = containerenv(Some("fedora-toolbox:35"), None)?;
// Assert that the actual and expected values are the same
assert_eq!(actual, expected);
Ok(())
}
#[test]
#[cfg(target_os = "linux")]
fn test_containerenv_fedora_with_name() -> std::io::Result<()> {
let (actual, expected) = containerenv(Some("fedora-toolbox:35"), Some("my-fedora"))?;
// Assert that the actual and expected values are the same
assert_eq!(actual, expected);
Ok(())
}
#[cfg(target_os = "linux")]
fn containerenv_systemd(
name: Option<&str>,
display: Option<&str>,
) -> std::io::Result<(Option<String>, Option<String>)> {
let renderer = ModuleRenderer::new("container")
// For a custom config
.config(toml::toml! {
[container]
disabled = false
});
let root_path = renderer.root_path();
let systemd_path = root_path.join("run/systemd/container");
fs::create_dir_all(systemd_path.parent().unwrap())?;
let contents = match name {
Some(name) => format!("{name}\n"),
None => "systemd-nspawn\n".to_string(),
};
utils::write_file(&systemd_path, contents)?;
// The output of the module
let actual = renderer
// Run the module and collect the output
.collect();
// The value that should be rendered by the module.
let expected = display.map(|_| {
format!(
"{} ",
Color::Red
.bold()
.dimmed()
.paint(format!("⬢ [{}]", display.unwrap_or("Systemd")))
)
});
Ok((actual, expected))
}
#[test]
#[cfg(target_os = "linux")]
fn test_containerenv_systemd() -> std::io::Result<()> {
let (actual, expected) = containerenv_systemd(None, Some("Systemd"))?;
// Assert that the actual and expected values are the same
assert_eq!(actual, expected);
Ok(())
}
#[test]
#[cfg(target_os = "linux")]
fn test_containerenv_docker_in_systemd() -> std::io::Result<()> {
let (actual, expected) = containerenv_systemd(Some("docker"), Some("Docker"))?;
// Assert that the actual and expected values are the same
assert_eq!(actual, expected);
Ok(())
}
#[test]
#[cfg(target_os = "linux")]
fn test_containerenv_wsl_in_systemd() -> std::io::Result<()> {
let (actual, expected) = containerenv_systemd(Some("wsl"), None)?;
// Assert that the actual and expected values are the same
assert_eq!(actual, expected);
Ok(())
}
#[test]
#[cfg(not(target_os = "linux"))]
fn test_containerenv() -> std::io::Result<()> {
let (actual, expected) = containerenv(None, None)?;
// Assert that the actual and expected values are not the same
assert_ne!(actual, expected);
Ok(())
}
#[test]
#[cfg(target_os = "linux")]
fn test_incus_container() -> std::io::Result<()> {
let renderer = ModuleRenderer::new("container").config(toml::toml! {
[container]
disabled = false
});
let root_path = renderer.root_path();
// Create the Incus socket path
let incus_socket_path = root_path.join("dev/incus/sock");
fs::create_dir_all(incus_socket_path.parent().unwrap())?;
fs::File::create(&incus_socket_path)?;
// The output of the module
let actual = renderer.collect();
// The value that should be rendered by the module
let expected = Some(format!(
"{} ",
Color::Red.bold().dimmed().paint("⬢ [Incus]")
));
assert_eq!(actual, expected);
Ok(())
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/azure.rs | src/modules/azure.rs | use serde::{Deserialize, Serialize};
use std::fs;
use std::path::PathBuf;
use super::{Context, Module, ModuleConfig};
use crate::configs::azure::AzureConfig;
use crate::formatter::StringFormatter;
#[derive(Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
struct AzureProfile {
installation_id: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
subscriptions: Vec<Subscription>,
}
#[derive(Serialize, Deserialize, Clone)]
struct User {
name: String,
}
#[derive(Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
struct Subscription {
name: String,
user: User,
is_default: bool,
}
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("azure");
let config = AzureConfig::try_load(module.config);
if config.disabled {
return None;
}
let subscription: Option<Subscription> = get_azure_profile_info(context);
if subscription.is_none() {
log::info!("Could not find Subscriptions in azureProfile.json");
return None;
}
let subscription = subscription.unwrap();
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 {
"subscription" => Some(Ok(config
.subscription_aliases
.get(&subscription.name)
.copied()
.unwrap_or(&subscription.name))),
"username" => Some(Ok(&subscription.user.name)),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `azure`:\n{error}");
return None;
}
});
Some(module)
}
fn get_azure_profile_info(context: &Context) -> Option<Subscription> {
let mut config_path = get_config_file_location(context)?;
config_path.push("azureProfile.json");
let azure_profile = load_azure_profile(&config_path)?;
azure_profile
.subscriptions
.into_iter()
.find(|s| s.is_default)
}
fn load_azure_profile(config_path: &PathBuf) -> Option<AzureProfile> {
let json_data = fs::read_to_string(config_path).ok()?;
let sanitized_json_data = json_data.strip_prefix('\u{feff}').unwrap_or(&json_data);
if let Ok(azure_profile) = serde_json::from_str::<AzureProfile>(sanitized_json_data) {
Some(azure_profile)
} else {
log::info!("Failed to parse azure profile.");
None
}
}
fn get_config_file_location(context: &Context) -> Option<PathBuf> {
context
.get_env("AZURE_CONFIG_DIR")
.map(PathBuf::from)
.or_else(|| {
let mut home = context.get_home()?;
home.push(".azure");
Some(home)
})
}
#[cfg(test)]
mod tests {
use crate::modules::azure::load_azure_profile;
use crate::test::ModuleRenderer;
use ini::Ini;
use nu_ansi_term::Color;
use std::fs::File;
use std::io::{self, Write};
use std::path::PathBuf;
use tempfile::TempDir;
fn generate_test_config(dir: &TempDir, azure_profile_contents: &str) -> io::Result<()> {
save_string_to_file(
dir,
azure_profile_contents,
String::from("azureProfile.json"),
)?;
Ok(())
}
#[test]
fn subscription_set_correctly() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let azure_profile_contents = r#"{
"installationId": "3deacd2a-b9db-77e1-aa42-23e2f8dfffc3",
"subscriptions": [
{
"id": "f568c543-d12e-de0b-3d85-69843598b565",
"name": "Subscription 2",
"state": "Enabled",
"user": {
"name": "user@domain.com",
"type": "user"
},
"isDefault": false,
"tenantId": "0e8a15ec-b0f5-d355-7062-8ece54c59aee",
"environmentName": "AzureCloud",
"homeTenantId": "0e8a15ec-b0f5-d355-7062-8ece54c59aee",
"managedByTenants": []
},
{
"id": "d4442d26-ea6d-46c4-07cb-4f70b8ae5465",
"name": "Subscription 3",
"state": "Enabled",
"user": {
"name": "user@domain.com",
"type": "user"
},
"isDefault": false,
"tenantId": "a4e1bb4b-5330-2d50-339d-b9674d3a87bc",
"environmentName": "AzureCloud",
"homeTenantId": "a4e1bb4b-5330-2d50-339d-b9674d3a87bc",
"managedByTenants": []
},
{
"id": "f3935dc9-92b5-9a93-da7b-42c325d86939",
"name": "Subscription 1",
"state": "Enabled",
"user": {
"name": "user@domain.com",
"type": "user"
},
"isDefault": true,
"tenantId": "f0273a19-7779-e40a-00a1-53b8331b3bb6",
"environmentName": "AzureCloud",
"homeTenantId": "f0273a19-7779-e40a-00a1-53b8331b3bb6",
"managedByTenants": []
}
]
}
"#;
generate_test_config(&dir, azure_profile_contents)?;
let dir_path = &dir.path().to_string_lossy();
let actual = ModuleRenderer::new("azure")
.config(toml::toml! {
[azure]
disabled = false
})
.env("AZURE_CONFIG_DIR", dir_path.as_ref())
.collect();
let expected = Some(format!(
"on {} ",
Color::Blue.bold().paint(" Subscription 1")
));
assert_eq!(actual, expected);
dir.close()
}
#[test]
fn user_name_set_correctly() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let azure_profile_contents = r#"{
"installationId": "3deacd2a-b9db-77e1-aa42-23e2f8dfffc3",
"subscriptions": [
{
"id": "f568c543-d12e-de0b-3d85-69843598b565",
"name": "Subscription 2",
"state": "Enabled",
"user": {
"name": "user@domain.com",
"type": "user"
},
"isDefault": false,
"tenantId": "0e8a15ec-b0f5-d355-7062-8ece54c59aee",
"environmentName": "AzureCloud",
"homeTenantId": "0e8a15ec-b0f5-d355-7062-8ece54c59aee",
"managedByTenants": []
},
{
"id": "d4442d26-ea6d-46c4-07cb-4f70b8ae5465",
"name": "Subscription 3",
"state": "Enabled",
"user": {
"name": "user@domain.com",
"type": "user"
},
"isDefault": false,
"tenantId": "a4e1bb4b-5330-2d50-339d-b9674d3a87bc",
"environmentName": "AzureCloud",
"homeTenantId": "a4e1bb4b-5330-2d50-339d-b9674d3a87bc",
"managedByTenants": []
},
{
"id": "f3935dc9-92b5-9a93-da7b-42c325d86939",
"name": "Subscription 1",
"state": "Enabled",
"user": {
"name": "user@domain.com",
"type": "user"
},
"isDefault": true,
"tenantId": "f0273a19-7779-e40a-00a1-53b8331b3bb6",
"environmentName": "AzureCloud",
"homeTenantId": "f0273a19-7779-e40a-00a1-53b8331b3bb6",
"managedByTenants": []
}
]
}
"#;
generate_test_config(&dir, azure_profile_contents)?;
let dir_path = &dir.path().to_string_lossy();
let actual = ModuleRenderer::new("azure")
.config(toml::toml! {
[azure]
format = "on [$symbol($username)]($style)"
disabled = false
})
.env("AZURE_CONFIG_DIR", dir_path.as_ref())
.collect();
let expected = Some(format!(
"on {}",
Color::Blue.bold().paint(" user@domain.com")
));
assert_eq!(actual, expected);
dir.close()
}
#[test]
fn subscription_name_empty() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let azure_profile_contents = r#"{
"installationId": "3deacd2a-b9db-77e1-aa42-23e2f8dfffc3",
"subscriptions": [
{
"id": "f568c543-d12e-de0b-3d85-69843598b565",
"name": "Subscription 2",
"state": "Enabled",
"user": {
"name": "user@domain.com",
"type": "user"
},
"isDefault": false,
"tenantId": "0e8a15ec-b0f5-d355-7062-8ece54c59aee",
"environmentName": "AzureCloud",
"homeTenantId": "0e8a15ec-b0f5-d355-7062-8ece54c59aee",
"managedByTenants": []
},
{
"id": "d4442d26-ea6d-46c4-07cb-4f70b8ae5465",
"name": "Subscription 3",
"state": "Enabled",
"user": {
"name": "user@domain.com",
"type": "user"
},
"isDefault": false,
"tenantId": "a4e1bb4b-5330-2d50-339d-b9674d3a87bc",
"environmentName": "AzureCloud",
"homeTenantId": "a4e1bb4b-5330-2d50-339d-b9674d3a87bc",
"managedByTenants": []
},
{
"id": "f3935dc9-92b5-9a93-da7b-42c325d86939",
"name": "",
"state": "Enabled",
"user": {
"name": "user@domain.com",
"type": "user"
},
"isDefault": true,
"tenantId": "f0273a19-7779-e40a-00a1-53b8331b3bb6",
"environmentName": "AzureCloud",
"homeTenantId": "f0273a19-7779-e40a-00a1-53b8331b3bb6",
"managedByTenants": []
}
]
}
"#;
generate_test_config(&dir, azure_profile_contents)?;
let dir_path = &dir.path().to_string_lossy();
let actual = ModuleRenderer::new("azure")
.config(toml::toml! {
[azure]
format = "on [$symbol($subscription:$username)]($style)"
disabled = false
})
.env("AZURE_CONFIG_DIR", dir_path.as_ref())
.collect();
let expected = Some(format!(
"on {}",
Color::Blue.bold().paint(" :user@domain.com")
));
assert_eq!(actual, expected);
dir.close()
}
#[test]
fn user_name_empty() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let azure_profile_contents = r#"{
"installationId": "3deacd2a-b9db-77e1-aa42-23e2f8dfffc3",
"subscriptions": [
{
"id": "f568c543-d12e-de0b-3d85-69843598b565",
"name": "Subscription 2",
"state": "Enabled",
"user": {
"name": "user@domain.com",
"type": "user"
},
"isDefault": false,
"tenantId": "0e8a15ec-b0f5-d355-7062-8ece54c59aee",
"environmentName": "AzureCloud",
"homeTenantId": "0e8a15ec-b0f5-d355-7062-8ece54c59aee",
"managedByTenants": []
},
{
"id": "d4442d26-ea6d-46c4-07cb-4f70b8ae5465",
"name": "Subscription 3",
"state": "Enabled",
"user": {
"name": "user@domain.com",
"type": "user"
},
"isDefault": false,
"tenantId": "a4e1bb4b-5330-2d50-339d-b9674d3a87bc",
"environmentName": "AzureCloud",
"homeTenantId": "a4e1bb4b-5330-2d50-339d-b9674d3a87bc",
"managedByTenants": []
},
{
"id": "f3935dc9-92b5-9a93-da7b-42c325d86939",
"name": "Subscription 1",
"state": "Enabled",
"user": {
"name": "",
"type": "user"
},
"isDefault": true,
"tenantId": "f0273a19-7779-e40a-00a1-53b8331b3bb6",
"environmentName": "AzureCloud",
"homeTenantId": "f0273a19-7779-e40a-00a1-53b8331b3bb6",
"managedByTenants": []
}
]
}
"#;
generate_test_config(&dir, azure_profile_contents)?;
let dir_path = &dir.path().to_string_lossy();
let actual = ModuleRenderer::new("azure")
.config(toml::toml! {
[azure]
format = "on [$symbol($subscription:$username)]($style)"
disabled = false
})
.env("AZURE_CONFIG_DIR", dir_path.as_ref())
.collect();
let expected = Some(format!(
"on {}",
Color::Blue.bold().paint(" Subscription 1:")
));
assert_eq!(actual, expected);
dir.close()
}
#[test]
fn user_name_missing_from_profile() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let azure_profile_contents = r#"{
"installationId": "3deacd2a-b9db-77e1-aa42-23e2f8dfffc3",
"subscriptions": [
{
"id": "f568c543-d12e-de0b-3d85-69843598b565",
"name": "Subscription 2",
"state": "Enabled",
"user": {
"type": "user"
},
"isDefault": false,
"tenantId": "0e8a15ec-b0f5-d355-7062-8ece54c59aee",
"environmentName": "AzureCloud",
"homeTenantId": "0e8a15ec-b0f5-d355-7062-8ece54c59aee",
"managedByTenants": []
},
{
"id": "d4442d26-ea6d-46c4-07cb-4f70b8ae5465",
"name": "Subscription 3",
"state": "Enabled",
"user": {
"name": "user@domain.com",
"type": "user"
},
"isDefault": false,
"tenantId": "a4e1bb4b-5330-2d50-339d-b9674d3a87bc",
"environmentName": "AzureCloud",
"homeTenantId": "a4e1bb4b-5330-2d50-339d-b9674d3a87bc",
"managedByTenants": []
},
{
"id": "f3935dc9-92b5-9a93-da7b-42c325d86939",
"name": "Subscription 1",
"state": "Enabled",
"user": {
"name": "",
"type": "user"
},
"isDefault": true,
"tenantId": "f0273a19-7779-e40a-00a1-53b8331b3bb6",
"environmentName": "AzureCloud",
"homeTenantId": "f0273a19-7779-e40a-00a1-53b8331b3bb6",
"managedByTenants": []
}
]
}
"#;
generate_test_config(&dir, azure_profile_contents)?;
let dir_path = &dir.path().to_string_lossy();
let actual = ModuleRenderer::new("azure")
.config(toml::toml! {
[azure]
format = "on [$symbol($subscription:$username)]($style)"
disabled = false
})
.env("AZURE_CONFIG_DIR", dir_path.as_ref())
.collect();
let expected = None;
assert_eq!(actual, expected);
dir.close()
}
#[test]
fn subscription_name_missing_from_profile() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let azure_profile_contents = r#"{
"installationId": "3deacd2a-b9db-77e1-aa42-23e2f8dfffc3",
"subscriptions": [
{
"id": "f568c543-d12e-de0b-3d85-69843598b565",
"name": "Subscription 2",
"state": "Enabled",
"user": {
"name": "user@domain.com",
"type": "user"
},
"isDefault": false,
"tenantId": "0e8a15ec-b0f5-d355-7062-8ece54c59aee",
"environmentName": "AzureCloud",
"homeTenantId": "0e8a15ec-b0f5-d355-7062-8ece54c59aee",
"managedByTenants": []
},
{
"id": "d4442d26-ea6d-46c4-07cb-4f70b8ae5465",
"name": "Subscription 3",
"state": "Enabled",
"user": {
"name": "user@domain.com",
"type": "user"
},
"isDefault": false,
"tenantId": "a4e1bb4b-5330-2d50-339d-b9674d3a87bc",
"environmentName": "AzureCloud",
"homeTenantId": "a4e1bb4b-5330-2d50-339d-b9674d3a87bc",
"managedByTenants": []
},
{
"id": "f3935dc9-92b5-9a93-da7b-42c325d86939",
"state": "Enabled",
"user": {
"name": "user@domain.com",
"type": "user"
},
"isDefault": true,
"tenantId": "f0273a19-7779-e40a-00a1-53b8331b3bb6",
"environmentName": "AzureCloud",
"homeTenantId": "f0273a19-7779-e40a-00a1-53b8331b3bb6",
"managedByTenants": []
}
]
}
"#;
generate_test_config(&dir, azure_profile_contents)?;
let dir_path = &dir.path().to_string_lossy();
let actual = ModuleRenderer::new("azure")
.config(toml::toml! {
[azure]
format = "on [$symbol($subscription:$username)]($style)"
disabled = false
})
.env("AZURE_CONFIG_DIR", dir_path.as_ref())
.collect();
let expected = None;
assert_eq!(actual, expected);
dir.close()
}
#[test]
fn subscription_name_and_username_found() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let azure_profile_contents = r#"{
"installationId": "3deacd2a-b9db-77e1-aa42-23e2f8dfffc3",
"subscriptions": [
{
"id": "f568c543-d12e-de0b-3d85-69843598b565",
"name": "Subscription 2",
"state": "Enabled",
"user": {
"name": "user@domain.com",
"type": "user"
},
"isDefault": false,
"tenantId": "0e8a15ec-b0f5-d355-7062-8ece54c59aee",
"environmentName": "AzureCloud",
"homeTenantId": "0e8a15ec-b0f5-d355-7062-8ece54c59aee",
"managedByTenants": []
},
{
"id": "d4442d26-ea6d-46c4-07cb-4f70b8ae5465",
"name": "Subscription 3",
"state": "Enabled",
"user": {
"name": "user@domain.com",
"type": "user"
},
"isDefault": false,
"tenantId": "a4e1bb4b-5330-2d50-339d-b9674d3a87bc",
"environmentName": "AzureCloud",
"homeTenantId": "a4e1bb4b-5330-2d50-339d-b9674d3a87bc",
"managedByTenants": []
},
{
"id": "f3935dc9-92b5-9a93-da7b-42c325d86939",
"name": "Subscription 1",
"state": "Enabled",
"user": {
"name": "user@domain.com",
"type": "user"
},
"isDefault": true,
"tenantId": "f0273a19-7779-e40a-00a1-53b8331b3bb6",
"environmentName": "AzureCloud",
"homeTenantId": "f0273a19-7779-e40a-00a1-53b8331b3bb6",
"managedByTenants": []
}
]
}
"#;
generate_test_config(&dir, azure_profile_contents)?;
let dir_path = &dir.path().to_string_lossy();
let actual = ModuleRenderer::new("azure")
.config(toml::toml! {
[azure]
format = "on [$symbol($subscription:$username)]($style)"
disabled = false
})
.env("AZURE_CONFIG_DIR", dir_path.as_ref())
.collect();
let expected = Some(format!(
"on {}",
Color::Blue.bold().paint(" Subscription 1:user@domain.com")
));
assert_eq!(actual, expected);
dir.close()
}
#[test]
fn subscription_name_with_alias() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let azure_profile_contents = r#"{
"installationId": "3deacd2a-b9db-77e1-aa42-23e2f8dfffc3",
"subscriptions": [
{
"id": "f568c543-d12e-de0b-3d85-69843598b565",
"name": "VeryLongSubscriptionName",
"state": "Enabled",
"user": {
"name": "user@domain.com",
"type": "user"
},
"isDefault": false,
"tenantId": "0e8a15ec-b0f5-d355-7062-8ece54c59aee",
"environmentName": "AzureCloud",
"homeTenantId": "0e8a15ec-b0f5-d355-7062-8ece54c59aee",
"managedByTenants": []
},
{
"id": "d4442d26-ea6d-46c4-07cb-4f70b8ae5465",
"name": "AnotherLongSubscriptionName",
"state": "Enabled",
"user": {
"name": "user@domain.com",
"type": "user"
},
"isDefault": false,
"tenantId": "a4e1bb4b-5330-2d50-339d-b9674d3a87bc",
"environmentName": "AzureCloud",
"homeTenantId": "a4e1bb4b-5330-2d50-339d-b9674d3a87bc",
"managedByTenants": []
},
{
"id": "f3935dc9-92b5-9a93-da7b-42c325d86939",
"name": "TheLastLongSubscriptionName",
"state": "Enabled",
"user": {
"name": "user@domain.com",
"type": "user"
},
"isDefault": true,
"tenantId": "f0273a19-7779-e40a-00a1-53b8331b3bb6",
"environmentName": "AzureCloud",
"homeTenantId": "f0273a19-7779-e40a-00a1-53b8331b3bb6",
"managedByTenants": []
}
]
}
"#;
generate_test_config(&dir, azure_profile_contents)?;
let dir_path = &dir.path().to_string_lossy();
let actual = ModuleRenderer::new("azure")
.config(toml::toml! {
[azure]
format = "on [$symbol($subscription:$username)]($style)"
disabled = false
[azure.subscription_aliases]
VeryLongSubscriptionName = "vlsn"
AnotherLongSubscriptionName = "alsn"
TheLastLongSubscriptionName = "tllsn"
})
.env("AZURE_CONFIG_DIR", dir_path.as_ref())
.collect();
let expected = Some(format!(
"on {}",
Color::Blue.bold().paint(" tllsn:user@domain.com")
));
assert_eq!(actual, expected);
dir.close()
}
#[test]
fn subscription_azure_profile_empty() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let mut clouds_config_ini = Ini::new();
clouds_config_ini
.with_section(Some("AzureCloud"))
.set("subscription", "f3935dc9-92b5-9a93-da7b-42c325d86939");
//let azure_profile_contents = "\u{feff}{\"installationId\": \"2652263e-40f8-11ed-ae3b-367ddada549c\", \"subscriptions\": []}";
let azure_profile_contents = r#"{
"installationId": "3deacd2a-b9db-77e1-aa42-23e2f8dfffc3",
"subscriptions": []
}
"#;
generate_test_config(&dir, azure_profile_contents)?;
let dir_path = &dir.path().to_string_lossy();
let actual = ModuleRenderer::new("azure")
.config(toml::toml! {
[azure]
disabled = false
})
.env("AZURE_CONFIG_DIR", dir_path.as_ref())
.collect();
let expected = None;
assert_eq!(actual, expected);
dir.close()
}
#[test]
fn azure_profile_with_leading_char() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let bom = vec![239, 187, 191];
let mut bom_str = String::from_utf8(bom).unwrap();
let json_str =
r#"{"installationId": "3deacd2a-b9db-77e1-aa42-23e2f8dfffc3", "subscriptions": []}"#;
bom_str.push_str(json_str);
let dir_path_no_bom = save_string_to_file(&dir, &bom_str, String::from("bom.json"))?;
let sanitized_json = load_azure_profile(&dir_path_no_bom).unwrap();
assert_eq!(
sanitized_json.installation_id,
"3deacd2a-b9db-77e1-aa42-23e2f8dfffc3"
);
assert!(sanitized_json.subscriptions.is_empty());
dir.close()
}
#[test]
fn azure_profile_without_leading_char() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let json_str =
r#"{"installationId": "3deacd2a-b9db-77e1-aa42-23e2f8dfffc3", "subscriptions": []}"#;
let dir_path_no_bom = save_string_to_file(&dir, json_str, String::from("bom.json"))?;
let sanitized_json = load_azure_profile(&dir_path_no_bom).unwrap();
assert_eq!(
sanitized_json.installation_id,
"3deacd2a-b9db-77e1-aa42-23e2f8dfffc3"
);
assert!(sanitized_json.subscriptions.is_empty());
dir.close()
}
#[test]
fn files_missing() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let dir_path = &dir.path().to_string_lossy();
let actual = ModuleRenderer::new("azure")
.env("AZURE_CONFIG_DIR", dir_path.as_ref())
.collect();
let expected = None;
assert_eq!(actual, expected);
dir.close()
}
fn save_string_to_file(
dir: &TempDir,
contents: &str,
file_name: String,
) -> Result<PathBuf, io::Error> {
let bom_file_path = dir.path().join(file_name);
let mut bom_file = File::create(&bom_file_path)?;
bom_file.write_all(contents.as_bytes())?;
bom_file.sync_all()?;
Ok(bom_file_path)
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/status.rs | src/modules/status.rs | use std::string::ToString;
use super::{Context, Module, ModuleConfig};
use crate::configs::status::StatusConfig;
use crate::formatter::{StringFormatter, string_formatter::StringFormatterError};
use crate::segment::Segment;
type ExitCode = i32;
type SignalNumber = u32;
#[derive(PartialEq)]
enum PipeStatusStatus<'a> {
Disabled,
NoPipe,
Pipe(&'a Vec<std::string::String>),
}
/// Creates a module with the status of the last command
///
/// Will display the status
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("status");
let config = StatusConfig::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 exit_code = context.properties.status_code.as_deref().unwrap_or("0");
let pipestatus_status = match &context.properties.pipestatus {
None => PipeStatusStatus::Disabled,
Some(ps) => {
if ps.len() > 1 {
PipeStatusStatus::Pipe(ps)
} else {
PipeStatusStatus::NoPipe
}
}
};
let pipestatus_status = if config.pipestatus {
pipestatus_status
} else {
PipeStatusStatus::Disabled
};
// Exit code is zero while success_symbol and pipestatus are all zero or disabled/missing
if exit_code == "0"
&& config.success_symbol.is_empty()
&& (match pipestatus_status {
PipeStatusStatus::Pipe(ps) => ps.iter().all(|s| s == "0"),
_ => true,
})
{
return None;
}
let segment_format = config.pipestatus_segment_format.unwrap_or(config.format);
let segment_format_with_separator = [segment_format, config.pipestatus_separator].join("");
// Create pipestatus segments
let pipestatus = match pipestatus_status {
PipeStatusStatus::Pipe(ps) => ps
.iter()
.enumerate()
.filter_map(|(i, ec)| {
let formatted = format_exit_code(
ec.as_str(),
if i == ps.len() - 1 {
segment_format
} else {
&segment_format_with_separator
},
None,
&config,
context,
);
match formatted {
Ok(segments) => Some(segments),
Err(e) => {
log::warn!("Error parsing format string in `status.pipestatus_segment_format`: {e:?}");
None
}
}
})
.flatten()
.collect(),
_ => Vec::new(),
};
let main_format = match pipestatus_status {
PipeStatusStatus::Pipe(_) => config.pipestatus_format,
_ => config.format,
};
let parsed = format_exit_code(exit_code, main_format, Some(&pipestatus), &config, context);
module.set_segments(match parsed {
Ok(segments) => segments,
Err(_error) => {
log::warn!("Error parsing format string in `status.format`");
return None;
}
});
Some(module)
}
fn format_exit_code<'a>(
exit_code: &'a str,
format: &'a str,
pipestatus: Option<&Vec<Segment>>,
config: &'a StatusConfig,
context: &'a Context,
) -> Result<Vec<Segment>, StringFormatterError> {
// First, parse as i64 to accept both i32 or u32, then normalize to i32.
let exit_code_int = if let Ok(i) = exit_code.parse::<i64>() {
i as ExitCode
} else {
log::warn!("Error parsing exit_code string to int");
return Ok(Vec::new());
};
let hex_status = format!("0x{exit_code_int:X}");
let common_meaning = status_common_meaning(exit_code_int);
let raw_signal_number = if config.recognize_signal_code {
status_to_signal(exit_code_int)
} else {
None
};
let signal_number = raw_signal_number.map(|sn| sn.to_string());
let signal_name =
raw_signal_number.and_then(|sn| status_signal_name(sn).or(signal_number.as_deref()));
// If not a signal and not a common meaning, it should at least print the raw exit code number
let maybe_exit_code_number = if common_meaning.is_none() && signal_name.is_none() {
Some(exit_code)
} else {
None
};
StringFormatter::new(format).and_then(|formatter| {
formatter
.map_meta(|var, _| match var {
"symbol" => match exit_code_int {
0 => Some(config.success_symbol),
126 if config.map_symbol => Some(config.not_executable_symbol),
127 if config.map_symbol => Some(config.not_found_symbol),
130 if config.recognize_signal_code && config.map_symbol => {
Some(config.sigint_symbol)
}
x if (129..256).contains(&x)
&& config.recognize_signal_code
&& config.map_symbol =>
{
Some(config.signal_symbol)
}
_ => Some(config.symbol),
},
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(if exit_code_int == 0 {
config.success_style
} else {
config.failure_style
}
.unwrap_or(config.style))),
_ => None,
})
.map(|variable| match variable {
"status" => Some(Ok(exit_code)),
"hex_status" => Some(Ok(hex_status.as_ref())),
"int" => Some(Ok(exit_code)),
"maybe_int" => Ok(maybe_exit_code_number).transpose(),
"common_meaning" => Ok(common_meaning).transpose(),
"signal_number" => Ok(signal_number.as_deref()).transpose(),
"signal_name" => Ok(signal_name).transpose(),
_ => None,
})
.map_variables_to_segments(|variable| match variable {
"pipestatus" if pipestatus.is_none() => {
// We might enter this case if pipestatus hasn't
// been processed yet, which means that it has been
// set in format
log::warn!("pipestatus variable is only available in pipestatus_format");
None
}
"pipestatus" => pipestatus.cloned().map(Ok),
_ => None,
})
.parse(None, Some(context))
})
}
fn status_common_meaning(ex: ExitCode) -> Option<&'static str> {
// Over 128 are Signal exit code
if ex > 128 {
return None;
}
match ex {
0 => Some(""), // SUCCESS can be defined by $success_symbol if the user wishes too.
1 => Some("ERROR"),
2 => Some("USAGE"),
// status codes 64-78 from libc
64 => Some("USAGE"),
65 => Some("DATAERR"),
66 => Some("NOINPUT"),
67 => Some("NOUSER"),
68 => Some("NOHOST"),
69 => Some("UNAVAILABLE"),
70 => Some("SOFTWARE"),
71 => Some("OSERR"),
72 => Some("OSFILE"),
73 => Some("CANTCREAT"),
74 => Some("IOERR"),
75 => Some("TEMPFAIL"),
76 => Some("PROTOCOL"),
77 => Some("NOPERM"),
78 => Some("CONFIG"),
126 => Some("NOPERM"),
127 => Some("NOTFOUND"),
_ => None,
}
}
fn status_to_signal(ex: ExitCode) -> Option<SignalNumber> {
if ex < 129 {
return None;
}
let sn = ex - 128;
Some(sn as u32)
}
fn status_signal_name(signal: SignalNumber) -> Option<&'static str> {
match signal {
1 => Some("HUP"), // 128 + 1
2 => Some("INT"), // 128 + 2
3 => Some("QUIT"), // 128 + 3
4 => Some("ILL"), // 128 + 4
5 => Some("TRAP"), // 128 + 5
6 => Some("IOT"), // 128 + 6
7 => Some("BUS"), // 128 + 7
8 => Some("FPE"), // 128 + 8
9 => Some("KILL"), // 128 + 9
10 => Some("USR1"), // 128 + 10
11 => Some("SEGV"), // 128 + 11
12 => Some("USR2"), // 128 + 12
13 => Some("PIPE"), // 128 + 13
14 => Some("ALRM"), // 128 + 14
15 => Some("TERM"), // 128 + 15
16 => Some("STKFLT"), // 128 + 16
17 => Some("CHLD"), // 128 + 17
18 => Some("CONT"), // 128 + 18
19 => Some("STOP"), // 128 + 19
20 => Some("TSTP"), // 128 + 20
21 => Some("TTIN"), // 128 + 21
22 => Some("TTOU"), // 128 + 22
_ => None,
}
}
#[cfg(test)]
mod tests {
use nu_ansi_term::{Color, Style};
use crate::test::ModuleRenderer;
#[test]
fn success_status_success_symbol_empty() {
let expected = None;
// Status code 0 and success_symbol = ""
let actual = ModuleRenderer::new("status")
.config(toml::toml! {
[status]
success_symbol = ""
disabled = false
})
.status(0)
.collect();
assert_eq!(expected, actual);
// Status code 0 and success_symbol is missing
let actual = ModuleRenderer::new("status")
.config(toml::toml! {
[status]
disabled = false
})
.status(0)
.collect();
assert_eq!(expected, actual);
// No status code and success_symbol = ""
let actual = ModuleRenderer::new("status")
.config(toml::toml! {
[status]
success_symbol = ""
disabled = false
})
.collect();
assert_eq!(expected, actual);
// No status code and success_symbol is missing
let actual = ModuleRenderer::new("status")
.config(toml::toml! {
[status]
disabled = false
})
.collect();
assert_eq!(expected, actual);
}
#[test]
fn success_status_success_symbol_filled() {
let expected = Some(format!("{} ", Color::Red.bold().paint("✔️0")));
// Status code 0
let actual = ModuleRenderer::new("status")
.config(toml::toml! {
[status]
success_symbol = "✔️"
disabled = false
})
.status(0)
.collect();
assert_eq!(expected, actual);
// No status code
let actual = ModuleRenderer::new("status")
.config(toml::toml! {
[status]
success_symbol = "✔️"
disabled = false
})
.collect();
assert_eq!(expected, actual);
}
#[test]
fn not_enabled() {
let expected = None;
let actual = ModuleRenderer::new("status").status(1).collect();
assert_eq!(expected, actual);
}
#[test]
fn failure_status() {
let exit_values = [1, 2, 130];
for status in &exit_values {
let expected = Some(format!(
"{} ",
Color::Red.bold().paint(format!("❌{status}"))
));
let actual = ModuleRenderer::new("status")
.config(toml::toml! {
[status]
symbol = "❌"
disabled = false
})
.status(*status)
.collect();
assert_eq!(expected, actual);
}
}
#[test]
fn failure_plaintext_status() {
let exit_values = [1, 2, 130];
for status in &exit_values {
let expected = Some(format!(
"{} ",
Color::Red.bold().paint(format!("x {status}"))
));
let actual = ModuleRenderer::new("status")
.config(toml::toml! {
[status]
symbol = "[x](bold red) "
disabled = false
})
.status(*status)
.collect();
assert_eq!(expected, actual);
}
}
#[test]
fn failure_hex_status() {
let exit_values = [1, 2, 130, -2_147_467_260, 2_147_500_036];
let string_values = ["0x1", "0x2", "0x82", "0x80004004", "0x80004004"];
for (exit_value, string_value) in exit_values.iter().zip(string_values) {
let expected = Some(format!(
"{} ",
Color::Red.bold().paint(format!("❌{string_value}"))
));
let actual = ModuleRenderer::new("status")
.config(toml::toml! {
[status]
symbol = "❌"
disabled = false
format = "[${symbol}${hex_status}]($style) "
})
.status(*exit_value)
.collect();
assert_eq!(expected, actual);
}
}
#[test]
fn signal_name() {
let exit_values = [1, 2, 126, 127, 130, 101];
let exit_values_name = [
Some("ERROR"),
Some("USAGE"),
Some("NOPERM"),
Some("NOTFOUND"),
Some("INT"),
None,
];
for (status, name) in exit_values.iter().zip(&exit_values_name) {
let expected = name.map(std::string::ToString::to_string);
let actual = ModuleRenderer::new("status")
.config(toml::toml! {
[status]
format = "$common_meaning$signal_name"
disabled = false
})
.status(*status)
.collect();
assert_eq!(expected, actual);
}
}
#[test]
fn exit_code_name_no_signal() {
let exit_values = [
1, 2, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 126, 127, 130, 101,
132,
];
let exit_values_name = [
Some("ERROR"),
Some("USAGE"),
Some("USAGE"),
Some("DATAERR"),
Some("NOINPUT"),
Some("NOUSER"),
Some("NOHOST"),
Some("UNAVAILABLE"),
Some("SOFTWARE"),
Some("OSERR"),
Some("OSFILE"),
Some("CANTCREAT"),
Some("IOERR"),
Some("TEMPFAIL"),
Some("PROTOCOL"),
Some("NOPERM"),
Some("CONFIG"),
Some("NOPERM"),
Some("NOTFOUND"),
None,
None,
None,
];
for (status, name) in exit_values.iter().zip(&exit_values_name) {
let expected = name.map(std::string::ToString::to_string);
let actual = ModuleRenderer::new("status")
.config(toml::toml! {
[status]
format = "$common_meaning$signal_name"
recognize_signal_code = false
disabled = false
})
.status(*status)
.collect();
assert_eq!(expected, actual);
}
}
#[test]
fn maybe_exit_code_number() {
let exit_values = [1, 2, 126, 127, 130, 101, 6, -3];
let exit_values_name = [
None,
None,
None,
None,
None,
Some("101"),
Some("6"),
Some("-3"),
];
for (status, name) in exit_values.iter().zip(&exit_values_name) {
let expected = name.map(std::string::ToString::to_string);
let actual = ModuleRenderer::new("status")
.config(toml::toml! {
[status]
format = "$maybe_int"
disabled = false
})
.status(*status)
.collect();
assert_eq!(expected, actual);
}
}
#[test]
fn special_symbols() {
let exit_values = [1, 126, 127, 130, 131];
let exit_values_name = ["🔴", "🚫", "🔍", "🧱", "⚡"];
for (status, name) in exit_values.iter().zip(&exit_values_name) {
let expected = Some((*name).to_string());
let actual = ModuleRenderer::new("status")
.config(toml::toml! {
[status]
format = "$symbol"
symbol = "🔴"
not_executable_symbol = "🚫"
not_found_symbol = "🔍"
sigint_symbol = "🧱"
signal_symbol = "⚡"
recognize_signal_code = true
map_symbol = true
disabled = false
})
.status(*status)
.collect();
assert_eq!(expected, actual);
}
}
#[test]
fn special_symbols_no_signals() {
let exit_values = [1, 126, 127, 130, 131];
let exit_values_name = ["🔴", "🚫", "🔍", "🔴", "🔴"];
for (status, name) in exit_values.iter().zip(&exit_values_name) {
let expected = Some((*name).to_string());
let actual = ModuleRenderer::new("status")
.config(toml::toml! {
[status]
format = "$symbol"
symbol = "🔴"
not_executable_symbol = "🚫"
not_found_symbol = "🔍"
sigint_symbol = "🧱"
signal_symbol = "⚡"
recognize_signal_code = false
map_symbol = true
disabled = false
})
.status(*status)
.collect();
assert_eq!(expected, actual);
}
}
#[test]
fn pipeline_uses_pipestatus_format() {
let exit_values = [
[0, 1, 0, 0],
[0, 1, 2, 3],
[130, 126, 131, 127],
[1, 1, 1, 1],
];
let exit_values_rendered = [
"PSF 🟢=🔴 🟢 🟢",
"PSF 🟢=🔴 🔴 🔴",
"PSF 🧱=🚫 ⚡ 🔍",
"PSF 🔴=🔴 🔴 🔴",
];
for (status, rendered) in exit_values.iter().zip(&exit_values_rendered) {
let main_exit_code = status[0];
let pipe_exit_code = &status[1..];
let expected = Some((*rendered).to_string());
let actual = ModuleRenderer::new("status")
.config(toml::toml! {
[status]
format = "$symbol"
symbol = "🔴"
success_symbol = "🟢"
not_executable_symbol = "🚫"
not_found_symbol = "🔍"
sigint_symbol = "🧱"
signal_symbol = "⚡"
recognize_signal_code = true
map_symbol = true
pipestatus = true
pipestatus_separator = " "
pipestatus_format = "PSF $symbol=$pipestatus"
disabled = false
})
.status(main_exit_code)
.pipestatus(pipe_exit_code)
.collect();
assert_eq!(expected, actual);
}
}
#[test]
fn pipeline_no_map_symbols() {
let exit_values = [
[0, 1, 0, 0],
[0, 1, 2, 3],
[130, 126, 131, 127],
[1, 1, 1, 1],
];
let exit_values_rendered = [
"PSF 🟢=🔴1 🟢0 🟢0",
"PSF 🟢=🔴1 🔴2 🔴3",
"PSF INT🔴=🔴126 🔴1313 🔴127",
"PSF 🔴=🔴1 🔴1 🔴1",
];
for (status, rendered) in exit_values.iter().zip(&exit_values_rendered) {
let main_exit_code = status[0];
let pipe_exit_code = &status[1..];
let expected = Some((*rendered).to_string());
let actual = ModuleRenderer::new("status")
.config(toml::toml! {
[status]
format = "$symbol$int$signal_number"
symbol = "🔴"
success_symbol = "🟢"
not_executable_symbol = "🚫"
not_found_symbol = "🔍"
sigint_symbol = "🧱"
signal_symbol = "⚡"
recognize_signal_code = true
map_symbol = false
pipestatus = true
pipestatus_separator = " "
pipestatus_format = "PSF $signal_name$symbol=$pipestatus"
disabled = false
})
.status(main_exit_code)
.pipestatus(pipe_exit_code)
.collect();
assert_eq!(expected, actual);
}
}
#[test]
fn successful_pipeline() {
let pipe_exit_code = [0, 0, 0];
let main_exit_code = 0;
let expected = None;
let actual = ModuleRenderer::new("status")
.config(toml::toml! {
[status]
disabled = false
})
.status(main_exit_code)
.pipestatus(&pipe_exit_code)
.collect();
assert_eq!(expected, actual);
}
#[test]
fn successful_pipeline_pipestatus_enabled() {
let pipe_exit_code = [0, 0, 0];
let main_exit_code = 0;
let expected = None;
let actual = ModuleRenderer::new("status")
.config(toml::toml! {
[status]
disabled = false
pipestatus = true
})
.status(main_exit_code)
.pipestatus(&pipe_exit_code)
.collect();
assert_eq!(expected, actual);
}
#[test]
fn pipeline_disabled() {
let exit_values = [[130, 126, 131, 127], [1, 1, 1, 1]];
let exit_values_rendered = ["F 🧱", "F 🔴"];
for (status, rendered) in exit_values.iter().zip(&exit_values_rendered) {
let main_exit_code = status[0];
let pipe_exit_code = &status[1..];
let expected = Some((*rendered).to_string());
let actual = ModuleRenderer::new("status")
.config(toml::toml! {
[status]
format = "F $symbol"
symbol = "🔴"
success_symbol = "🟢"
not_executable_symbol = "🚫"
not_found_symbol = "🔍"
sigint_symbol = "🧱"
signal_symbol = "⚡"
recognize_signal_code = true
map_symbol = true
pipestatus = false
pipestatus_separator = " "
pipestatus_format = "PSF $symbol=$pipestatus"
disabled = false
})
.status(main_exit_code)
.pipestatus(pipe_exit_code)
.collect();
assert_eq!(expected, actual);
}
}
#[test]
fn pipeline_long() {
let exit_values = [
[130, 0, 0, 0, 30, 1, 2, 3, 142, 0, 0, 0, 130],
[1, 0, 0, 0, 30, 127, 126, 3, 142, 0, 230, 0, 2],
];
let exit_values_rendered = [
"PSF 130INT=🟢|🟢|🟢|🔴30|🔴|🔴|🔴3|⚡|🟢|🟢|🟢|🧱",
"PSF 1ERROR=🟢|🟢|🟢|🔴30|🔍|🚫|🔴3|⚡|🟢|⚡|🟢|🔴",
];
for (status, rendered) in exit_values.iter().zip(&exit_values_rendered) {
let main_exit_code = status[0];
let pipe_exit_code = &status[1..];
let expected = Some((*rendered).to_string());
let actual = ModuleRenderer::new("status")
.config(toml::toml! {
[status]
format = "$symbol$maybe_int"
symbol = "🔴"
success_symbol = "🟢"
not_executable_symbol = "🚫"
not_found_symbol = "🔍"
sigint_symbol = "🧱"
signal_symbol = "⚡"
recognize_signal_code = true
map_symbol = true
pipestatus = true
pipestatus_separator = "|"
pipestatus_format = "PSF $int$common_meaning$signal_name=$pipestatus"
disabled = false
})
.status(main_exit_code)
.pipestatus(pipe_exit_code)
.collect();
assert_eq!(expected, actual);
}
}
#[test]
fn pipestatus_segment_format() {
let pipe_exit_code = &[0, 1];
let main_exit_code = 1;
let expected = Some("[0]|[1] => <1>".to_string());
let actual = ModuleRenderer::new("status")
.config(toml::toml! {
[status]
format = "\\($status\\)"
pipestatus = true
pipestatus_separator = "|"
pipestatus_format = "$pipestatus => <$status>"
pipestatus_segment_format = "\\[$status\\]"
disabled = false
})
.status(main_exit_code)
.pipestatus(pipe_exit_code)
.collect();
assert_eq!(expected, actual);
}
#[test]
fn pipestatus_separator_format() {
let pipe_exit_code = &[0, 1, 2];
let main_exit_code = 2;
let style = Style::new().on(Color::Red).fg(Color::White).bold();
let sep_style = Style::new().on(Color::Green).fg(Color::White).italic();
let expected = Some(format!(
"{}{}{}{}{}",
style.paint("[0"),
sep_style.paint("|"),
style.paint("1"),
sep_style.paint("|"),
style.paint("2] => <2>"),
));
let actual = ModuleRenderer::new("status")
.config(toml::toml! {
[status]
format = "\\($status\\)"
style = "fg:white bg:red bold"
pipestatus = true
pipestatus_separator = "[|](fg:white bg:green italic)"
pipestatus_format = "[\\[]($style)$pipestatus[\\] => <$status>]($style)"
pipestatus_segment_format = "[$status]($style)"
disabled = false
})
.status(main_exit_code)
.pipestatus(pipe_exit_code)
.collect();
assert_eq!(expected, actual);
}
#[test]
fn pipestatus_width() {
let pipe_exit_code = &[0, 1, 2];
let main_exit_code = 2;
let renderer = ModuleRenderer::new("status")
.config(toml::toml! {
format = "$fill$status"
[status]
style = "fg:white bg:red bold"
pipestatus = true
pipestatus_segment_format = "[$status](bg:blue fg:yellow)"
disabled = false
})
.status(main_exit_code)
.pipestatus(pipe_exit_code)
.width(100);
let context = crate::modules::Context::from(renderer);
let actual = crate::print::get_prompt(&context);
let mut escaping = false;
let mut width = 0;
for c in actual.chars() {
if c == '\x1B' {
escaping = true;
}
if escaping {
escaping = !c.is_ascii_alphabetic();
continue;
}
width += 1;
}
assert_eq!(width, 100);
}
#[test]
fn pipestatus_segment_format_err() {
let pipe_exit_code = &[0, 1, 2];
let main_exit_code = 2;
let expected = Some(format!(
"{}",
Style::new()
.on(Color::Red)
.fg(Color::White)
.bold()
.paint("[] => <2>"),
));
let actual = ModuleRenderer::new("status")
.config(toml::toml! {
[status]
style = "fg:white bg:red bold"
pipestatus = true
pipestatus_format = "[\\[]($style)$pipestatus[\\] => <$status>]($style)"
pipestatus_segment_format = "${"
disabled = false
})
.status(main_exit_code)
.pipestatus(pipe_exit_code)
.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/hostname.rs | src/modules/hostname.rs | use super::{Context, Module};
use crate::config::ModuleConfig;
use crate::configs::hostname::HostnameConfig;
use crate::formatter::StringFormatter;
use whoami::hostname;
/// Creates a module with the system hostname
///
/// Will display the hostname if all of the following criteria are met:
/// - `hostname.disabled` is absent or false
/// - `hostname.ssh_only` is false OR the user is currently connected as an SSH session (`$SSH_CONNECTION`)
/// - `hostname.ssh_only` is false AND `hostname.detect_env_vars` is either empty or contains a defined environment variable
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("hostname");
let config: HostnameConfig = HostnameConfig::try_load(module.config);
let ssh_connection = context.get_env("SSH_CONNECTION");
if (config.ssh_only && ssh_connection.is_none())
|| !context.detect_env_vars(&config.detect_env_vars)
{
return None;
}
let host = hostname()
.inspect_err(|e| log::warn!("Failed to get hostname: {e}"))
.ok()?;
let mut host = if !config.trim_at.is_empty()
&& let Some(index) = host.find(config.trim_at)
{
host.split_at(index).0
} else {
host.as_ref()
};
if let Some(&alias) = config.aliases.get(host) {
host = alias;
}
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|var, _| match var {
"ssh_symbol" => {
if ssh_connection.is_some() {
Some(config.ssh_symbol)
} else {
None
}
}
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map(|variable| match variable {
"hostname" => Some(Ok(host)),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `hostname`:\n{error}");
return None;
}
});
Some(module)
}
#[cfg(test)]
mod tests {
use super::hostname;
use crate::test::ModuleRenderer;
use nu_ansi_term::{Color, Style};
use unicode_segmentation::UnicodeSegmentation;
macro_rules! get_hostname {
() => {
if let Ok(hostname) = hostname() {
hostname
} else {
println!(
"hostname was not tested because gethostname failed! \
This could be caused by your hostname containing invalid UTF."
);
return;
}
};
}
#[test]
fn ssh_only_false_with_empty_detect_env_vars() {
let hostname = get_hostname!();
let actual = ModuleRenderer::new("hostname")
.config(toml::toml! {
[hostname]
ssh_only = false
trim_at = ""
detect_env_vars = []
})
.collect();
let expected = Some(format!("{} in ", style().paint(hostname)));
assert_eq!(expected, actual);
}
#[test]
fn ssh_only_false_with_matching_negated_env_var() {
let actual = ModuleRenderer::new("hostname")
.config(toml::toml! {
[hostname]
ssh_only = false
trim_at = ""
detect_env_vars = ["!NEGATED"]
})
.env("NEGATED", "true")
.collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn ssh_only_false_with_only_negated_env_vars() {
let hostname = get_hostname!();
let actual = ModuleRenderer::new("hostname")
.config(toml::toml! {
[hostname]
ssh_only = false
trim_at = ""
detect_env_vars = ["!NEGATED_ONE", "!NEGATED_TWO", "!NEGATED_THREE"]
})
.collect();
let expected = Some(format!("{} in ", style().paint(hostname)));
assert_eq!(expected, actual);
}
#[test]
fn ssh_only_false_with_matching_env_var() {
let hostname = get_hostname!();
let actual = ModuleRenderer::new("hostname")
.config(toml::toml! {
[hostname]
ssh_only = false
trim_at = ""
detect_env_vars = ["FORCE_HOSTNAME"]
})
.env("FORCE_HOSTNAME", "true")
.collect();
let expected = Some(format!("{} in ", style().paint(hostname)));
assert_eq!(expected, actual);
}
#[test]
fn ssh_only_false_without_matching_env_vars() {
let actual = ModuleRenderer::new("hostname")
.config(toml::toml! {
[hostname]
ssh_only = false
trim_at = ""
detect_env_vars = ["FORCE_HOSTNAME", "!NEGATED"]
})
.collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn ssh_only_false_ssh() {
let hostname = get_hostname!();
let actual = ModuleRenderer::new("hostname")
.config(toml::toml! {
[hostname]
ssh_only = false
trim_at = ""
})
.collect();
let expected = Some(format!("{} in ", style().paint(hostname)));
assert_eq!(expected, actual);
}
#[test]
fn no_ssh() {
let actual = ModuleRenderer::new("hostname")
.config(toml::toml! {
[hostname]
ssh_only = true
})
.collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn ssh() {
let hostname = get_hostname!();
let actual = ModuleRenderer::new("hostname")
.config(toml::toml! {
[hostname]
ssh_only = true
trim_at = ""
})
.env("SSH_CONNECTION", "something")
.collect();
let expected = Some(format!(
"{} in ",
style().paint("🌐 ".to_owned() + hostname.as_str())
));
assert_eq!(expected, actual);
}
#[test]
fn no_trim_at() {
let hostname = get_hostname!();
let actual = ModuleRenderer::new("hostname")
.config(toml::toml! {
[hostname]
ssh_only = false
trim_at = ""
})
.collect();
let expected = Some(format!("{} in ", style().paint(hostname)));
assert_eq!(expected, actual);
}
#[test]
fn trim_at() {
let hostname = get_hostname!();
let mut hostname_iter = hostname.graphemes(true);
let remainder = hostname_iter.next().unwrap_or_default();
let trim_at = hostname_iter.collect::<String>();
let actual = ModuleRenderer::new("hostname")
.config(toml::toml! {
[hostname]
ssh_only = false
trim_at = trim_at
})
.collect();
let expected = Some(format!("{} in ", style().paint(remainder)));
assert_eq!(expected, actual);
}
#[test]
fn test_alias() {
let hostname = get_hostname!();
let mut toml_config = toml::toml!(
[hostname]
ssh_only = false
trim_at = ""
aliases = {}
);
toml_config["hostname"]["aliases"]
.as_table_mut()
.unwrap()
.insert(hostname, toml::Value::String("homeworld".to_string()));
let actual = ModuleRenderer::new("hostname")
.config(toml_config)
.collect();
let expected = Some(format!("{} in ", style().paint("homeworld")));
assert_eq!(expected, actual);
}
#[test]
fn test_alias_with_trim_at() {
let hostname = get_hostname!();
let mut hostname_iter = hostname.graphemes(true);
let remainder = hostname_iter.next().unwrap_or_default();
let trim_at = hostname_iter.collect::<String>();
// Trimmed hostname needs to be non-empty
if remainder.is_empty() {
log::warn!("Skipping test_alias_with_trim_at because hostname is too short");
return;
}
let mut toml_config = toml::toml!(
[hostname]
ssh_only = false
trim_at = trim_at
aliases = {}
);
toml_config["hostname"]["aliases"]
.as_table_mut()
.unwrap()
.insert(remainder.to_string(), toml::Value::String("🌍".to_string()));
let actual = ModuleRenderer::new("hostname")
.config(toml_config)
.collect();
let expected = Some(format!("{} in ", style().paint("🌍")));
assert_eq!(expected, actual);
}
fn style() -> Style {
Color::Green.bold().dimmed()
}
}
| rust | ISC | 8a69666084d248b8fd76b6c54f38aea12abce6e3 | 2026-01-04T15:31:59.388295Z | false |
starship/starship | https://github.com/starship/starship/blob/8a69666084d248b8fd76b6c54f38aea12abce6e3/src/modules/hg_state.rs | src/modules/hg_state.rs | use std::fs::File;
use std::io::{self, Read};
use std::path::Path;
use super::{Context, Module, ModuleConfig};
use crate::configs::hg_state::HgStateConfig;
use crate::formatter::StringFormatter;
/// Creates a module with the state of hg repository at the current directory
///
/// During a mercurial operation it will show: MERGING, REBASING, UPDATING etc.
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("hg_state");
let config: HgStateConfig = HgStateConfig::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_root = context.begin_ancestor_scan().set_folders(&[".hg"]).scan()?;
let state_description = get_state_description(&repo_root, &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,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `hg_state`:\n{error}");
return None;
}
});
Some(module)
}
fn get_state_description<'a>(
hg_root: &Path,
config: &HgStateConfig<'a>,
) -> Option<StateDescription<'a>> {
if hg_root.join(".hg").join("rebasestate").exists() {
Some(StateDescription {
label: config.rebase,
})
} else if hg_root.join(".hg").join("updatestate").exists() {
Some(StateDescription {
label: config.update,
})
} else if hg_root.join(".hg").join("bisect.state").exists() {
Some(StateDescription {
label: config.bisect,
})
} else if hg_root.join(".hg").join("graftstate").exists() {
Some(StateDescription {
label: config.graft,
})
} else if hg_root
.join(".hg")
.join("transplant")
.join("journal")
.exists()
{
Some(StateDescription {
label: config.transplant,
})
} else if hg_root.join(".hg").join("histedit-state").exists() {
Some(StateDescription {
label: config.histedit,
})
} else if is_merge_state(hg_root).is_ok() {
Some(StateDescription {
label: config.merge,
})
} else {
None
}
}
fn is_merge_state(hg_root: &Path) -> io::Result<bool> {
let dirstate_path = hg_root.join(".hg").join("dirstate");
let mut file = File::open(dirstate_path)?;
let mut buffer = [0u8; 40]; // First 40 bytes: 20 for p1, 20 for p2
file.read_exact(&mut buffer)?;
let p2 = &buffer[20..40];
let is_merge = p2.iter().any(|&b| b != 0);
Ok(is_merge)
}
struct StateDescription<'a> {
label: &'a str,
}
#[cfg(test)]
mod tests {
use nu_ansi_term::Color;
use std::fs::{File, create_dir_all};
use std::io;
use std::path::Path;
use crate::test::{FixtureProvider, ModuleRenderer, fixture_repo};
use crate::utils::create_command;
#[test]
fn test_hg_show_nothing_on_empty_dir() -> io::Result<()> {
let repo_dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("hg_state")
.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)?;
let actual = ModuleRenderer::new("hg_state")
.path(repo_dir.to_str().unwrap())
.collect();
let expected = None;
assert_eq!(expected, actual);
tempdir.close()
}
#[test]
#[ignore]
fn test_hg_merging() -> 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,
)?;
run_hg(&["update", "-r", "branch-name-0"], repo_dir)?;
run_hg(&["merge", "-r", "branch-name-101"], repo_dir)?;
expect_hg_state_with_config(
repo_dir,
Some(format!("({}) ", Color::Yellow.bold().paint("MERGING"))),
);
tempdir.close()
}
#[test]
#[ignore]
fn test_hg_rebasing() -> io::Result<()> {
let tempdir = fixture_repo(FixtureProvider::Hg)?;
let repo_dir = tempdir.path();
File::create(repo_dir.join(".hg").join("rebasestate"))?;
expect_hg_state_with_config(
repo_dir,
Some(format!("({}) ", Color::Yellow.bold().paint("REBASING"))),
);
tempdir.close()
}
#[test]
#[ignore]
fn test_hg_updating() -> io::Result<()> {
let tempdir = fixture_repo(FixtureProvider::Hg)?;
let repo_dir = tempdir.path();
File::create(repo_dir.join(".hg").join("updatestate"))?;
expect_hg_state_with_config(
repo_dir,
Some(format!("({}) ", Color::Yellow.bold().paint("UPDATING"))),
);
tempdir.close()
}
#[test]
#[ignore]
fn test_hg_bisecting() -> io::Result<()> {
let tempdir = fixture_repo(FixtureProvider::Hg)?;
let repo_dir = tempdir.path();
run_hg(&["bisect", "--good"], repo_dir)?;
expect_hg_state_with_config(
repo_dir,
Some(format!("({}) ", Color::Yellow.bold().paint("BISECTING"))),
);
tempdir.close()
}
#[test]
#[ignore]
fn test_hg_grafting() -> io::Result<()> {
let tempdir = fixture_repo(FixtureProvider::Hg)?;
let repo_dir = tempdir.path();
File::create(repo_dir.join(".hg").join("graftstate"))?;
expect_hg_state_with_config(
repo_dir,
Some(format!("({}) ", Color::Yellow.bold().paint("GRAFTING"))),
);
tempdir.close()
}
#[test]
#[ignore]
fn test_hg_transplanting() -> io::Result<()> {
let tempdir = fixture_repo(FixtureProvider::Hg)?;
let repo_dir = tempdir.path();
create_dir_all(repo_dir.join(".hg").join("transplant"))?;
File::create(repo_dir.join(".hg").join("transplant").join("journal"))?;
expect_hg_state_with_config(
repo_dir,
Some(format!(
"({}) ",
Color::Yellow.bold().paint("TRANSPLANTING")
)),
);
tempdir.close()
}
#[test]
#[ignore]
fn test_hg_histediting() -> io::Result<()> {
let tempdir = fixture_repo(FixtureProvider::Hg)?;
let repo_dir = tempdir.path();
File::create(repo_dir.join(".hg").join("histedit-state"))?;
expect_hg_state_with_config(
repo_dir,
Some(format!("({}) ", Color::Yellow.bold().paint("HISTEDITING"))),
);
tempdir.close()
}
fn run_hg(args: &[&str], repo_dir: &Path) -> io::Result<()> {
create_command("hg")?
.args(args)
.current_dir(repo_dir)
.output()?;
Ok(())
}
fn expect_hg_state_with_config(repo_dir: &Path, expected: Option<String>) {
let actual = ModuleRenderer::new("hg_state")
.path(repo_dir.to_str().unwrap())
.config({
toml::toml! {
[hg_state]
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/time.rs | src/modules/time.rs | use chrono::{DateTime, FixedOffset, Local, NaiveTime, Utc};
use super::{Context, Module, ModuleConfig};
use crate::configs::time::TimeConfig;
use crate::formatter::StringFormatter;
/// Outputs the current time
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("time");
let config: TimeConfig = TimeConfig::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;
}
// Hide prompt if current time is not inside time_range
let (display_start, display_end) = parse_time_range(config.time_range);
let time_now = Local::now().time();
if !is_inside_time_range(time_now, display_start, display_end) {
return None;
}
let default_format = if config.use_12hr { "%r" } else { "%T" };
let time_format = config.time_format.unwrap_or(default_format);
log::trace!("Timer module is enabled with format string: {time_format}");
let formatted_time_string = if config.utc_time_offset != "local" {
create_offset_time_string(Utc::now(), config.utc_time_offset, time_format).unwrap_or_else(
|_| {
log::warn!(
"Invalid utc_time_offset configuration provided! Falling back to \"local\"."
);
format_time(time_format, Local::now())
},
)
} else {
format_time(time_format, Local::now())
};
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 {
"time" => Some(Ok(&formatted_time_string)),
_ => None,
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `time`: \n{error}");
return None;
}
});
Some(module)
}
fn create_offset_time_string(
utc_time: DateTime<Utc>,
utc_time_offset_str: &str,
time_format: &str,
) -> Result<String, &'static str> {
// Using floats to allow 30/45 minute offsets: https://www.timeanddate.com/time/time-zones-interesting.html
let utc_time_offset_in_hours = utc_time_offset_str.parse::<f32>().unwrap_or(
// Passing out of range value to force falling back to "local"
25_f32,
);
if utc_time_offset_in_hours < 24_f32 && utc_time_offset_in_hours > -24_f32 {
let utc_offset_in_seconds: i32 = (utc_time_offset_in_hours * 3600_f32) as i32;
let Some(timezone_offset) = FixedOffset::east_opt(utc_offset_in_seconds) else {
return Err("Invalid offset");
};
log::trace!("Target timezone offset is {timezone_offset}");
let target_time = utc_time.with_timezone(&timezone_offset);
log::trace!("Time in target timezone now is {target_time}");
Ok(format_time_fixed_offset(time_format, target_time))
} else {
Err("Invalid timezone offset.")
}
}
/// Format a given time into the given string. This function should be referentially
/// transparent, which makes it easy to test (unlike anything involving the actual time)
fn format_time(time_format: &str, local_time: DateTime<Local>) -> String {
local_time.format(time_format).to_string()
}
fn format_time_fixed_offset(time_format: &str, utc_time: DateTime<FixedOffset>) -> String {
utc_time.format(time_format).to_string()
}
/// Returns true if `time_now` is between `time_start` and `time_end`.
/// If one of these values is not given, then it is ignored.
/// It also handles cases where `time_start` and `time_end` have a midnight in between
fn is_inside_time_range(
time_now: NaiveTime,
time_start: Option<NaiveTime>,
time_end: Option<NaiveTime>,
) -> bool {
match (time_start, time_end) {
(None, None) => true,
(Some(i), None) => time_now > i,
(None, Some(i)) => time_now < i,
(Some(i), Some(j)) => {
if i < j {
i < time_now && time_now < j
} else {
time_now > i || time_now < j
}
}
}
}
/// Parses the config's `time_range` field and returns the starting time and ending time.
/// The range is in the format START_TIME-END_TIME, with `START_TIME` and `END_TIME` being optional.
///
/// If one of the ranges is invalid or not provided, then the corresponding field in the output
/// tuple is None
fn parse_time_range(time_range: &str) -> (Option<NaiveTime>, Option<NaiveTime>) {
let value = String::from(time_range);
// Check if there is exactly one hyphen, and fail otherwise
if value.matches('-').count() != 1 {
return (None, None);
}
// Split time_range into the two ranges
let (start, end) = value.split_at(value.find('-').unwrap());
let end = &end[1..];
// Parse the ranges
let start_time = NaiveTime::parse_from_str(start, "%H:%M:%S").ok();
let end_time = NaiveTime::parse_from_str(end, "%H:%M:%S").ok();
(start_time, end_time)
}
/* Because we cannot make acceptance tests for the time module, these unit
tests become extra important */
#[cfg(test)]
mod tests {
use super::*;
use crate::test::ModuleRenderer;
use chrono::offset::TimeZone;
const FMT_12: &str = "%r";
const FMT_24: &str = "%T";
#[test]
fn test_midnight_12hr() {
let time = Local.with_ymd_and_hms(2014, 7, 8, 0, 0, 0).unwrap();
let formatted = format_time(FMT_12, time);
assert_eq!(formatted, "12:00:00 AM");
}
#[test]
fn test_midnight_24hr() {
let time = Local.with_ymd_and_hms(2014, 7, 8, 0, 0, 0).unwrap();
let formatted = format_time(FMT_24, time);
assert_eq!(formatted, "00:00:00");
}
#[test]
fn test_noon_12hr() {
let time = Local.with_ymd_and_hms(2014, 7, 8, 12, 0, 0).unwrap();
let formatted = format_time(FMT_12, time);
assert_eq!(formatted, "12:00:00 PM");
}
#[test]
fn test_noon_24hr() {
let time = Local.with_ymd_and_hms(2014, 7, 8, 12, 0, 0).unwrap();
let formatted = format_time(FMT_24, time);
assert_eq!(formatted, "12:00:00");
}
#[test]
fn test_arbtime_12hr() {
let time = Local.with_ymd_and_hms(2014, 7, 8, 15, 36, 47).unwrap();
let formatted = format_time(FMT_12, time);
assert_eq!(formatted, "03:36:47 PM");
}
#[test]
fn test_arbtime_24hr() {
let time = Local.with_ymd_and_hms(2014, 7, 8, 15, 36, 47).unwrap();
let formatted = format_time(FMT_24, time);
assert_eq!(formatted, "15:36:47");
}
#[test]
fn test_format_with_paren() {
let time = Local.with_ymd_and_hms(2014, 7, 8, 15, 36, 47).unwrap();
let formatted = format_time("[%T]", time);
assert_eq!(formatted, "[15:36:47]");
}
#[test]
fn test_midnight_12hr_fixed_offset() {
let timezone_offset = FixedOffset::east_opt(0).unwrap();
let time = Utc
.with_ymd_and_hms(2014, 7, 8, 0, 0, 0)
.unwrap()
.with_timezone(&timezone_offset);
let formatted = format_time_fixed_offset(FMT_12, time);
assert_eq!(formatted, "12:00:00 AM");
}
#[test]
fn test_midnight_24hr_fixed_offset() {
let timezone_offset = FixedOffset::east_opt(0).unwrap();
let time = Utc
.with_ymd_and_hms(2014, 7, 8, 0, 0, 0)
.unwrap()
.with_timezone(&timezone_offset);
let formatted = format_time_fixed_offset(FMT_24, time);
assert_eq!(formatted, "00:00:00");
}
#[test]
fn test_noon_12hr_fixed_offset() {
let timezone_offset = FixedOffset::east_opt(0).unwrap();
let time = Utc
.with_ymd_and_hms(2014, 7, 8, 12, 0, 0)
.unwrap()
.with_timezone(&timezone_offset);
let formatted = format_time_fixed_offset(FMT_12, time);
assert_eq!(formatted, "12:00:00 PM");
}
#[test]
fn test_noon_24hr_fixed_offset() {
let timezone_offset = FixedOffset::east_opt(0).unwrap();
let time = Utc
.with_ymd_and_hms(2014, 7, 8, 12, 0, 0)
.unwrap()
.with_timezone(&timezone_offset);
let formatted = format_time_fixed_offset(FMT_24, time);
assert_eq!(formatted, "12:00:00");
}
#[test]
fn test_arbtime_12hr_fixed_offset() {
let timezone_offset = FixedOffset::east_opt(0).unwrap();
let time = Utc
.with_ymd_and_hms(2014, 7, 8, 15, 36, 47)
.unwrap()
.with_timezone(&timezone_offset);
let formatted = format_time_fixed_offset(FMT_12, time);
assert_eq!(formatted, "03:36:47 PM");
}
#[test]
fn test_arbtime_24hr_fixed_offset() {
let timezone_offset = FixedOffset::east_opt(0).unwrap();
let time = Utc
.with_ymd_and_hms(2014, 7, 8, 15, 36, 47)
.unwrap()
.with_timezone(&timezone_offset);
let formatted = format_time_fixed_offset(FMT_24, time);
assert_eq!(formatted, "15:36:47");
}
#[test]
fn test_format_with_paren_fixed_offset() {
let timezone_offset = FixedOffset::east_opt(0).unwrap();
let time = Utc
.with_ymd_and_hms(2014, 7, 8, 15, 36, 47)
.unwrap()
.with_timezone(&timezone_offset);
let formatted = format_time_fixed_offset("[%T]", time);
assert_eq!(formatted, "[15:36:47]");
}
#[test]
fn test_create_formatted_time_string_with_minus_3() {
let utc_time: DateTime<Utc> = Utc.with_ymd_and_hms(2014, 7, 8, 15, 36, 47).unwrap();
let utc_time_offset_str = "-3";
let actual = create_offset_time_string(utc_time, utc_time_offset_str, FMT_12).unwrap();
assert_eq!(actual, "12:36:47 PM");
}
#[test]
fn test_create_formatted_time_string_with_plus_5() {
let utc_time: DateTime<Utc> = Utc.with_ymd_and_hms(2014, 7, 8, 15, 36, 47).unwrap();
let utc_time_offset_str = "+5";
let actual = create_offset_time_string(utc_time, utc_time_offset_str, FMT_12).unwrap();
assert_eq!(actual, "08:36:47 PM");
}
#[test]
fn test_create_formatted_time_string_with_plus_9_30() {
let utc_time: DateTime<Utc> = Utc.with_ymd_and_hms(2014, 7, 8, 15, 36, 47).unwrap();
let utc_time_offset_str = "+9.5";
let actual = create_offset_time_string(utc_time, utc_time_offset_str, FMT_12).unwrap();
assert_eq!(actual, "01:06:47 AM");
}
#[test]
fn test_create_formatted_time_string_with_plus_5_45() {
let utc_time: DateTime<Utc> = Utc.with_ymd_and_hms(2014, 7, 8, 15, 36, 47).unwrap();
let utc_time_offset_str = "+5.75";
let actual = create_offset_time_string(utc_time, utc_time_offset_str, FMT_12).unwrap();
assert_eq!(actual, "09:21:47 PM");
}
#[test]
fn test_create_formatted_time_string_with_plus_24() {
let utc_time: DateTime<Utc> = Utc.with_ymd_and_hms(2014, 7, 8, 15, 36, 47).unwrap();
let utc_time_offset_str = "+24";
create_offset_time_string(utc_time, utc_time_offset_str, FMT_12)
.expect_err("Invalid timezone offset.");
}
#[test]
fn test_create_formatted_time_string_with_minus_24() {
let utc_time: DateTime<Utc> = Utc.with_ymd_and_hms(2014, 7, 8, 15, 36, 47).unwrap();
let utc_time_offset_str = "-24";
create_offset_time_string(utc_time, utc_time_offset_str, FMT_12)
.expect_err("Invalid timezone offset.");
}
#[test]
fn test_create_formatted_time_string_with_plus_9001() {
let utc_time: DateTime<Utc> = Utc.with_ymd_and_hms(2014, 7, 8, 15, 36, 47).unwrap();
let utc_time_offset_str = "+9001";
create_offset_time_string(utc_time, utc_time_offset_str, FMT_12)
.expect_err("Invalid timezone offset.");
}
#[test]
fn test_create_formatted_time_string_with_minus_4242() {
let utc_time: DateTime<Utc> = Utc.with_ymd_and_hms(2014, 7, 8, 15, 36, 47).unwrap();
let utc_time_offset_str = "-4242";
create_offset_time_string(utc_time, utc_time_offset_str, FMT_12)
.expect_err("Invalid timezone offset.");
}
#[test]
fn test_create_formatted_time_string_with_invalid_string() {
let utc_time: DateTime<Utc> = Utc.with_ymd_and_hms(2014, 7, 8, 15, 36, 47).unwrap();
let utc_time_offset_str = "completely wrong config";
create_offset_time_string(utc_time, utc_time_offset_str, FMT_12)
.expect_err("Invalid timezone offset.");
}
#[test]
fn test_parse_invalid_time_range() {
let time_range = "10:00:00-12:00:00-13:00:00";
let time_range_2 = "10:00:00";
assert_eq!(parse_time_range(time_range), (None, None));
assert_eq!(parse_time_range(time_range_2), (None, None));
}
#[test]
fn test_parse_start_time_range() {
let time_range = "10:00:00-";
assert_eq!(
parse_time_range(time_range),
(Some(NaiveTime::from_hms_opt(10, 00, 00).unwrap()), None)
);
}
#[test]
fn test_parse_end_time_range() {
let time_range = "-22:00:00";
assert_eq!(
parse_time_range(time_range),
(None, Some(NaiveTime::from_hms_opt(22, 00, 00).unwrap()))
);
}
#[test]
fn test_parse_both_time_ranges() {
let time_range = "10:00:00-16:00:00";
assert_eq!(
parse_time_range(time_range),
(
Some(NaiveTime::from_hms_opt(10, 00, 00).unwrap()),
Some(NaiveTime::from_hms_opt(16, 00, 00).unwrap())
)
);
}
#[test]
fn test_is_inside_time_range_with_no_range() {
let time_start = None;
let time_end = None;
let time_now = NaiveTime::from_hms_opt(10, 00, 00).unwrap();
assert!(is_inside_time_range(time_now, time_start, time_end));
}
#[test]
fn test_is_inside_time_range_with_start_range() {
let time_start = Some(NaiveTime::from_hms_opt(10, 00, 00).unwrap());
let time_now = NaiveTime::from_hms_opt(12, 00, 00).unwrap();
let time_now2 = NaiveTime::from_hms_opt(8, 00, 00).unwrap();
assert!(is_inside_time_range(time_now, time_start, None));
assert!(!is_inside_time_range(time_now2, time_start, None));
}
#[test]
fn test_is_inside_time_range_with_end_range() {
let time_end = Some(NaiveTime::from_hms_opt(16, 00, 00).unwrap());
let time_now = NaiveTime::from_hms_opt(15, 00, 00).unwrap();
let time_now2 = NaiveTime::from_hms_opt(19, 00, 00).unwrap();
assert!(is_inside_time_range(time_now, None, time_end));
assert!(!is_inside_time_range(time_now2, None, time_end));
}
#[test]
fn test_is_inside_time_range_with_complete_range() {
let time_start = Some(NaiveTime::from_hms_opt(9, 00, 00).unwrap());
let time_end = Some(NaiveTime::from_hms_opt(18, 00, 00).unwrap());
let time_now = NaiveTime::from_hms_opt(3, 00, 00).unwrap();
let time_now2 = NaiveTime::from_hms_opt(13, 00, 00).unwrap();
let time_now3 = NaiveTime::from_hms_opt(20, 00, 00).unwrap();
assert!(!is_inside_time_range(time_now, time_start, time_end));
assert!(is_inside_time_range(time_now2, time_start, time_end));
assert!(!is_inside_time_range(time_now3, time_start, time_end));
}
#[test]
fn test_is_inside_time_range_with_complete_range_passing_midnight() {
let time_start = Some(NaiveTime::from_hms_opt(19, 00, 00).unwrap());
let time_end = Some(NaiveTime::from_hms_opt(12, 00, 00).unwrap());
let time_now = NaiveTime::from_hms_opt(3, 00, 00).unwrap();
let time_now2 = NaiveTime::from_hms_opt(13, 00, 00).unwrap();
let time_now3 = NaiveTime::from_hms_opt(20, 00, 00).unwrap();
assert!(is_inside_time_range(time_now, time_start, time_end));
assert!(!is_inside_time_range(time_now2, time_start, time_end));
assert!(is_inside_time_range(time_now3, time_start, time_end));
}
#[test]
fn config_enabled() {
let actual = ModuleRenderer::new("time")
.config(toml::toml! {
[time]
disabled = false
})
.collect();
// We can't test what it actually is...but we can assert that it is something
assert!(actual.is_some());
}
#[test]
fn config_blank() {
let actual = ModuleRenderer::new("time").collect();
let expected = None;
assert_eq!(expected, actual);
}
#[test]
fn config_check_prefix_and_suffix() {
let actual = ModuleRenderer::new("time")
.config(toml::toml! {
[time]
disabled = false
format = "at [\\[$time\\]]($style) "
time_format = "%T"
})
.collect()
.unwrap();
// This is the prefix with "at ", the color code, then the prefix char [
let col_prefix = format!("at {}{}[", '\u{1b}', "[1;33m");
// This is the suffix with suffix char ']', then color codes, then a space
let col_suffix = format!("]{}{} ", '\u{1b}', "[0m");
assert!(actual.starts_with(&col_prefix));
assert!(actual.ends_with(&col_suffix));
}
}
| 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.