1
0
mirror of https://github.com/Llewellynvdm/starship.git synced 2024-06-17 15:52:47 +00:00
starship/src/test/mod.rs

251 lines
7.3 KiB
Rust
Raw Normal View History

2022-01-04 09:49:42 +00:00
use crate::context::{Context, Shell, Target};
use crate::logger::StarshipLogger;
use crate::{
config::StarshipConfig,
utils::{create_command, CommandOutput},
};
use log::{Level, LevelFilter};
use once_cell::sync::Lazy;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::Once;
use tempfile::TempDir;
static FIXTURE_DIR: Lazy<PathBuf> =
Lazy::new(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("src/test/fixtures/"));
static GIT_FIXTURE: Lazy<PathBuf> = Lazy::new(|| FIXTURE_DIR.join("git-repo.bundle"));
static HG_FIXTURE: Lazy<PathBuf> = Lazy::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(
2022-01-04 09:49:42 +00:00
Default::default(),
Shell::Unknown,
2022-01-04 09:49:42 +00:00
Target::Main,
PathBuf::new(),
PathBuf::new(),
Default::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> {
2022-05-23 10:58:27 +00:00
/// 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 }
}
pub fn path<T>(mut self, path: T) -> Self
where
T: Into<PathBuf>,
{
self.context.current_dir = path.into();
refactor(directory): Introduce `logical-path` argument which allows a shell to explicitly specify both a logical and physical filesystem path (#2104) * refactor(directory): Introduce `logical-path` argument which allows a shell to explicitly specify both a logical and physical filesystem path Fix `directory::module` to consume both path and logical-path (if provided). The "logical" path is preferred when rendering the "display path", while the "physical" path is used to resolve the "read only" flag. Repo- and home-directory contraction behavior is maintained, based on the logical path if it is set, or the physical path if it is not. The custom "get_current_dir" logic has been removed entirely, and the `directory` module now relies on `context.current_dir` / `context.logical_dir` entirely. Changes have been made to `init/starship.ps1` to work with this new flag: - Calculate and pass "physical" and "logical" paths explicitly (as other shells do not pass `--logical-path` that they fall back to rendering the physical path) - Moved the "powershell provider prefix" cleanup code to the PowerShell script - this code _should_ now support any kind of powershell path prefix. * fix(powershell): Fix an issue with trailing backslashes on file paths causing command line parsing issues. This is a bit of a footgun! The work-around chosen is to append a trailing space when a path string ends with a backslash, and then trim any extra whitespace away in the Context constructor. Other alternatives considered and rejected: 1. Always trim trailing backslashes as the filesystem generally doesn't need them. 2. Escape trailing backslashes with another backslash. This proved complex as PS only quotes string args when the string includes some whitespace, and other backslashes within the string apparently don't need to be escaped. * fix(powershell): Use Invoke-Native pattern for safely invoking native executables with strings which may contain characters which need to be escaped carefully. * fix(context): Remove superfluous argument trims These were in place to clean up extra whitespace sometimes injected by starship.ps1::prompt, and are no longer required with the new Invoke-Native helper in place. * refactor(directory): Clean up the semantics of `logical_dir` defaulting it to `current_dir` but overridable by the `--logical-dir` flag. - Restore `use_logical_path` config flag. - Always attempt to contract repo paths from the `current_dir`. * fix(directory) :Use logical_dir for contracting the home directory This keeps the two calls to contract_path in sync. * fix(directory): Remove test script * refactor(directory): Convert current_dir to canonical filesystem path when use_logical_path = false - This requires some clean-up to remove the extended-path prefix on Windows - The configured logical_dir is ignored entirely in this mode - we calculate a new logical_dir by cleaning up the physical_dir path for display. - Test coverage * fix(directory): Use AsRef style for passing Path arguments * fix(directory): Strip the windows extended-path prefix from the display string later in the render process * fix(docs): Update docs/config/README.md for use_logical_path * refactor(context): Populate `current_dir` from `--path` or `std::env::current_dir`, populate `logical_dir` from `--logical-path` or the `PWD` env var - `current_dir` is always canonicalized - On Windows, `current_dir` will have an extended-path prefix - `logical_dir` is now always set - `directory::module` now just selects between `current_dir` and `logical_dir` when picking which path to render - Test coverage * fix(directory): Fix path comparison operations in directory to ignore differences between path prefixes - Added PathExt extension trait which adds `normalised_equals`, `normalised_starts_with` and `without_prefix` * fix(path): Add test coverage for PathExt on *nix * fix(directory): Test coverage for `contract_repo_path`, `contract_path` with variations of verbatim and non-verbatim paths * fix(directory): Update path-slash to latest This fixes the issue with the trailing character of some Windows paths being truncated, e.g. `\\server\share` and `C:` * fix(powershell): Improve UTF8 output handling, argument encoding - Use `ProcessStartInfo` to launch native executable, replacing manual UTF8 output encoding handling - If we detect we're on PWSH6+ use the new `System.Diagnostics.ProcessStartInfo.ArgumentList` parameter, otherwise manually escape the argument string - Move `Get-Cwd` and `Invoke-Native` into the prompt function scope so that they don't leak into the user's shell scope * fix(path): Make PathExt methods no-ops on *nix * fix(path): Cargo fmt * fix(powershell): Remove typo ';'. Fix variable assignment lint.
2021-02-08 14:14:59 +00:00
self.context.logical_dir = self.context.current_dir.clone();
self
}
pub fn root_path(&self) -> &Path {
self.context.root_dir.path()
}
refactor(directory): Introduce `logical-path` argument which allows a shell to explicitly specify both a logical and physical filesystem path (#2104) * refactor(directory): Introduce `logical-path` argument which allows a shell to explicitly specify both a logical and physical filesystem path Fix `directory::module` to consume both path and logical-path (if provided). The "logical" path is preferred when rendering the "display path", while the "physical" path is used to resolve the "read only" flag. Repo- and home-directory contraction behavior is maintained, based on the logical path if it is set, or the physical path if it is not. The custom "get_current_dir" logic has been removed entirely, and the `directory` module now relies on `context.current_dir` / `context.logical_dir` entirely. Changes have been made to `init/starship.ps1` to work with this new flag: - Calculate and pass "physical" and "logical" paths explicitly (as other shells do not pass `--logical-path` that they fall back to rendering the physical path) - Moved the "powershell provider prefix" cleanup code to the PowerShell script - this code _should_ now support any kind of powershell path prefix. * fix(powershell): Fix an issue with trailing backslashes on file paths causing command line parsing issues. This is a bit of a footgun! The work-around chosen is to append a trailing space when a path string ends with a backslash, and then trim any extra whitespace away in the Context constructor. Other alternatives considered and rejected: 1. Always trim trailing backslashes as the filesystem generally doesn't need them. 2. Escape trailing backslashes with another backslash. This proved complex as PS only quotes string args when the string includes some whitespace, and other backslashes within the string apparently don't need to be escaped. * fix(powershell): Use Invoke-Native pattern for safely invoking native executables with strings which may contain characters which need to be escaped carefully. * fix(context): Remove superfluous argument trims These were in place to clean up extra whitespace sometimes injected by starship.ps1::prompt, and are no longer required with the new Invoke-Native helper in place. * refactor(directory): Clean up the semantics of `logical_dir` defaulting it to `current_dir` but overridable by the `--logical-dir` flag. - Restore `use_logical_path` config flag. - Always attempt to contract repo paths from the `current_dir`. * fix(directory) :Use logical_dir for contracting the home directory This keeps the two calls to contract_path in sync. * fix(directory): Remove test script * refactor(directory): Convert current_dir to canonical filesystem path when use_logical_path = false - This requires some clean-up to remove the extended-path prefix on Windows - The configured logical_dir is ignored entirely in this mode - we calculate a new logical_dir by cleaning up the physical_dir path for display. - Test coverage * fix(directory): Use AsRef style for passing Path arguments * fix(directory): Strip the windows extended-path prefix from the display string later in the render process * fix(docs): Update docs/config/README.md for use_logical_path * refactor(context): Populate `current_dir` from `--path` or `std::env::current_dir`, populate `logical_dir` from `--logical-path` or the `PWD` env var - `current_dir` is always canonicalized - On Windows, `current_dir` will have an extended-path prefix - `logical_dir` is now always set - `directory::module` now just selects between `current_dir` and `logical_dir` when picking which path to render - Test coverage * fix(directory): Fix path comparison operations in directory to ignore differences between path prefixes - Added PathExt extension trait which adds `normalised_equals`, `normalised_starts_with` and `without_prefix` * fix(path): Add test coverage for PathExt on *nix * fix(directory): Test coverage for `contract_repo_path`, `contract_path` with variations of verbatim and non-verbatim paths * fix(directory): Update path-slash to latest This fixes the issue with the trailing character of some Windows paths being truncated, e.g. `\\server\share` and `C:` * fix(powershell): Improve UTF8 output handling, argument encoding - Use `ProcessStartInfo` to launch native executable, replacing manual UTF8 output encoding handling - If we detect we're on PWSH6+ use the new `System.Diagnostics.ProcessStartInfo.ArgumentList` parameter, otherwise manually escape the argument string - Move `Get-Cwd` and `Invoke-Native` into the prompt function scope so that they don't leak into the user's shell scope * fix(path): Make PathExt methods no-ops on *nix * fix(path): Cargo fmt * fix(powershell): Remove typo ';'. Fix variable assignment lint.
2021-02-08 14:14:59 +00:00
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
}
2022-05-23 10:58:27 +00:00
/// 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
}
2022-05-23 10:58:27 +00:00
/// 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
}
2022-01-04 09:49:42 +00:00
pub fn jobs(mut self, jobs: i64) -> Self {
self.context.properties.jobs = jobs;
self
}
pub fn cmd_duration(mut self, duration: u64) -> Self {
2022-01-04 09:49:42 +00:00
self.context.properties.cmd_duration = Some(duration.to_string());
self
}
pub fn keymap<T>(mut self, keymap: T) -> Self
where
T: Into<String>,
{
2022-01-04 09:49:42 +00:00
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
}
#[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())
}
}
2022-05-23 10:58:27 +00:00
#[derive(Clone, Copy)]
pub enum FixtureProvider {
Fossil,
2021-03-25 20:03:19 +00:00
Git,
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)
.open(path.path().join(checkout_db))?
.sync_all()?;
Ok(path)
}
2021-03-25 20:03:19 +00:00
FixtureProvider::Git => {
let path = tempfile::tempdir()?;
create_command("git")?
.current_dir(path.path())
2022-11-05 11:40:46 +00:00
.args(["clone", "-b", "master"])
.arg(GIT_FIXTURE.as_os_str())
2022-11-05 11:40:46 +00:00
.arg(path.path())
.output()?;
create_command("git")?
2022-11-05 11:40:46 +00:00
.args(["config", "--local", "user.email", "starship@example.com"])
.current_dir(path.path())
.output()?;
create_command("git")?
2022-11-05 11:40:46 +00:00
.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")?
2022-11-05 11:40:46 +00:00
.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")?
2022-11-05 11:40:46 +00:00
.args(["config", "--local", "core.fsyncObjectFiles", "true"])
.current_dir(path.path())
.output()?;
create_command("git")?
2022-11-05 11:40:46 +00:00
.args(["reset", "--hard", "HEAD"])
.current_dir(path.path())
.output()?;
Ok(path)
}
2021-03-25 20:03:19 +00:00
FixtureProvider::Hg => {
let path = tempfile::tempdir()?;
create_command("hg")?
.current_dir(path.path())
.arg("clone")
.arg(HG_FIXTURE.as_os_str())
2022-11-05 11:40:46 +00:00
.arg(path.path())
.output()?;
Ok(path)
}
FixtureProvider::Pijul => {
let path = tempfile::tempdir()?;
fs::create_dir(path.path().join(".pijul"))?;
Ok(path)
}
}
}