2022-03-26 09:42:19 +00:00
|
|
|
use crate::config::{ModuleConfig, StarshipConfig};
|
2021-10-27 13:13:17 +00:00
|
|
|
use crate::configs::StarshipRootConfig;
|
2019-06-10 14:56:17 +00:00
|
|
|
use crate::module::Module;
|
2021-12-28 05:56:06 +00:00
|
|
|
use crate::utils::{create_command, exec_timeout, CommandOutput};
|
2019-06-10 14:56:17 +00:00
|
|
|
|
2020-01-02 04:19:08 +00:00
|
|
|
use crate::modules;
|
2021-07-04 19:32:58 +00:00
|
|
|
use crate::utils::{self, home_dir};
|
2022-01-04 09:49:42 +00:00
|
|
|
use clap::Parser;
|
2020-05-06 09:19:53 +00:00
|
|
|
use git2::{ErrorCode::UnbornBranch, Repository, RepositoryState};
|
2019-09-09 23:14:38 +00:00
|
|
|
use once_cell::sync::OnceCell;
|
2022-01-04 09:49:42 +00:00
|
|
|
#[cfg(test)]
|
|
|
|
use std::collections::HashMap;
|
|
|
|
use std::collections::HashSet;
|
2019-04-19 20:57:14 +00:00
|
|
|
use std::env;
|
2021-08-23 16:49:30 +00:00
|
|
|
use std::ffi::{OsStr, OsString};
|
|
|
|
use std::fmt::Debug;
|
2019-04-23 18:51:08 +00:00
|
|
|
use std::fs;
|
2022-01-14 21:12:10 +00:00
|
|
|
use std::marker::PhantomData;
|
2022-01-04 09:49:42 +00:00
|
|
|
use std::num::ParseIntError;
|
2019-09-09 23:14:38 +00:00
|
|
|
use std::path::{Path, PathBuf};
|
2022-02-14 12:12:31 +00:00
|
|
|
use std::str::FromStr;
|
2019-10-20 08:26:27 +00:00
|
|
|
use std::string::String;
|
2020-10-17 19:36:21 +00:00
|
|
|
use std::time::{Duration, Instant};
|
2021-09-23 15:52:51 +00:00
|
|
|
use terminal_size::terminal_size;
|
2019-04-19 20:57:14 +00:00
|
|
|
|
2019-07-15 22:18:19 +00:00
|
|
|
/// 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.
|
2019-04-19 20:57:14 +00:00
|
|
|
pub struct Context<'a> {
|
2019-07-15 22:18:19 +00:00
|
|
|
/// The deserialized configuration map from the user's `starship.toml` file.
|
2019-09-30 12:10:35 +00:00
|
|
|
pub config: StarshipConfig,
|
2019-07-15 22:18:19 +00:00
|
|
|
|
|
|
|
/// The current working directory that starship is being called in.
|
2019-04-19 20:57:14 +00:00
|
|
|
pub current_dir: PathBuf,
|
2019-07-15 22:18:19 +00:00
|
|
|
|
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
|
|
|
/// 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,
|
|
|
|
|
2020-02-03 21:57:48 +00:00
|
|
|
/// A struct containing directory contents in a lookup-optimised format.
|
|
|
|
dir_contents: OnceCell<DirContents>,
|
2019-07-15 22:18:19 +00:00
|
|
|
|
2019-10-20 08:26:27 +00:00
|
|
|
/// Properties to provide to modules.
|
2022-01-04 09:49:42 +00:00
|
|
|
pub properties: Properties,
|
2019-07-15 22:18:19 +00:00
|
|
|
|
2019-09-09 23:14:38 +00:00
|
|
|
/// Private field to store Git information for modules who need it
|
|
|
|
repo: OnceCell<Repo>,
|
2020-01-26 22:37:18 +00:00
|
|
|
|
|
|
|
/// The shell the user is assumed to be running
|
|
|
|
pub shell: Shell,
|
2020-08-07 19:13:12 +00:00
|
|
|
|
2022-01-04 09:49:42 +00:00
|
|
|
/// Which prompt to print (main, right, ...)
|
|
|
|
pub target: Target,
|
2022-01-01 13:12:11 +00:00
|
|
|
|
2021-09-12 23:59:15 +00:00
|
|
|
/// Width of terminal, or zero if width cannot be detected.
|
|
|
|
pub width: usize,
|
|
|
|
|
2020-08-07 19:13:12 +00:00
|
|
|
/// A HashMap of environment variable mocks
|
2021-02-13 18:32:35 +00:00
|
|
|
#[cfg(test)]
|
2020-08-07 19:13:12 +00:00
|
|
|
pub env: HashMap<&'a str, String>,
|
2021-02-11 20:34:47 +00:00
|
|
|
|
2021-02-13 18:32:35 +00:00
|
|
|
/// A HashMap of command mocks
|
|
|
|
#[cfg(test)]
|
|
|
|
pub cmd: HashMap<&'a str, Option<CommandOutput>>,
|
|
|
|
|
2022-01-21 15:44:46 +00:00
|
|
|
/// a mock of the root directory
|
|
|
|
#[cfg(test)]
|
|
|
|
pub root_dir: tempfile::TempDir,
|
|
|
|
|
2021-06-29 23:46:41 +00:00
|
|
|
#[cfg(feature = "battery")]
|
|
|
|
pub battery_info_provider: &'a (dyn crate::modules::BatteryInfoProvider + Send + Sync),
|
|
|
|
|
2021-10-27 13:13:17 +00:00
|
|
|
/// Starship root config
|
|
|
|
pub root_config: StarshipRootConfig,
|
2022-01-14 21:12:10 +00:00
|
|
|
|
|
|
|
/// Avoid issues with unused lifetimes when features are disabled
|
|
|
|
_marker: PhantomData<&'a ()>,
|
2019-04-19 20:57:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a> Context<'a> {
|
2019-07-15 22:18:19 +00:00
|
|
|
/// Identify the current working directory and create an instance of Context
|
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
|
|
|
/// 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).
|
2022-01-04 09:49:42 +00:00
|
|
|
pub fn new(arguments: Properties, target: Target) -> Context<'a> {
|
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
|
|
|
let shell = Context::get_shell();
|
|
|
|
|
|
|
|
// Retrieve the "current directory".
|
|
|
|
// If the path argument is not set fall back to the OS current directory.
|
2019-06-06 12:18:00 +00:00
|
|
|
let path = arguments
|
2022-01-04 09:49:42 +00:00
|
|
|
.path
|
|
|
|
.clone()
|
2021-03-27 15:46:05 +00:00
|
|
|
.or_else(|| env::current_dir().ok())
|
|
|
|
.or_else(|| env::var("PWD").map(PathBuf::from).ok())
|
2022-01-04 09:49:42 +00:00
|
|
|
.or_else(|| arguments.logical_path.clone())
|
2021-03-27 15:46:05 +00:00
|
|
|
.unwrap_or_default();
|
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
|
|
|
|
2021-07-28 16:26:00 +00:00
|
|
|
// Retrieve the "logical directory".
|
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
|
|
|
// 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
|
2022-01-04 09:49:42 +00:00
|
|
|
.logical_path
|
|
|
|
.clone()
|
2021-03-27 15:46:05 +00:00
|
|
|
.or_else(|| env::var("PWD").map(PathBuf::from).ok())
|
|
|
|
.unwrap_or_else(|| path.clone());
|
2019-06-06 12:18:00 +00:00
|
|
|
|
2022-01-04 09:49:42 +00:00
|
|
|
Context::new_with_shell_and_path(arguments, shell, target, path, logical_path)
|
2019-04-19 20:57:14 +00:00
|
|
|
}
|
|
|
|
|
2019-07-15 22:18:19 +00:00
|
|
|
/// Create a new instance of Context for the provided directory
|
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 new_with_shell_and_path(
|
2022-01-15 09:21:38 +00:00
|
|
|
mut properties: Properties,
|
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
|
|
|
shell: Shell,
|
2022-01-04 09:49:42 +00:00
|
|
|
target: Target,
|
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
|
|
|
path: PathBuf,
|
|
|
|
logical_path: PathBuf,
|
2022-01-04 09:49:42 +00:00
|
|
|
) -> Context<'a> {
|
2019-09-30 12:10:35 +00:00
|
|
|
let config = StarshipConfig::initialize();
|
2019-06-10 14:56:17 +00:00
|
|
|
|
2022-01-15 09:21:38 +00:00
|
|
|
// 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
|
2022-01-04 09:49:42 +00:00
|
|
|
.pipestatus
|
|
|
|
.as_deref()
|
2022-01-15 09:21:38 +00:00
|
|
|
.map_or(false, |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;
|
|
|
|
}
|
2021-07-28 16:26:00 +00:00
|
|
|
|
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
|
|
|
// Canonicalize the current path to resolve symlinks, etc.
|
2022-02-23 23:32:35 +00:00
|
|
|
// NOTE: On Windows this may convert the path to extended-path syntax.
|
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
|
|
|
let current_dir = Context::expand_tilde(path);
|
2022-02-23 23:32:35 +00:00
|
|
|
let current_dir = dunce::canonicalize(¤t_dir).unwrap_or(current_dir);
|
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
|
|
|
let logical_dir = logical_path;
|
2020-01-26 22:37:18 +00:00
|
|
|
|
2021-10-27 13:13:17 +00:00
|
|
|
let root_config = config
|
|
|
|
.config
|
|
|
|
.as_ref()
|
|
|
|
.map_or_else(StarshipRootConfig::default, StarshipRootConfig::load);
|
2021-02-11 20:34:47 +00:00
|
|
|
|
2022-01-04 09:49:42 +00:00
|
|
|
let width = properties.terminal_width;
|
2021-10-06 21:36:28 +00:00
|
|
|
|
2019-04-19 20:57:14 +00:00
|
|
|
Context {
|
2019-06-10 14:56:17 +00:00
|
|
|
config,
|
2019-10-20 08:26:27 +00:00
|
|
|
properties,
|
2019-04-27 02:07:07 +00:00
|
|
|
current_dir,
|
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
|
|
|
logical_dir,
|
2020-02-03 21:57:48 +00:00
|
|
|
dir_contents: OnceCell::new(),
|
2019-09-09 23:14:38 +00:00
|
|
|
repo: OnceCell::new(),
|
2020-01-26 22:37:18 +00:00
|
|
|
shell,
|
2022-01-04 09:49:42 +00:00
|
|
|
target,
|
2021-10-06 21:36:28 +00:00
|
|
|
width,
|
2021-02-13 18:32:35 +00:00
|
|
|
#[cfg(test)]
|
2022-01-21 15:44:46 +00:00
|
|
|
root_dir: tempfile::TempDir::new().unwrap(),
|
|
|
|
#[cfg(test)]
|
2020-08-07 19:13:12 +00:00
|
|
|
env: HashMap::new(),
|
2021-02-13 18:32:35 +00:00
|
|
|
#[cfg(test)]
|
|
|
|
cmd: HashMap::new(),
|
2021-06-29 23:46:41 +00:00
|
|
|
#[cfg(feature = "battery")]
|
2021-06-30 01:12:59 +00:00
|
|
|
battery_info_provider: &crate::modules::BatteryInfoProviderImpl,
|
2021-10-27 13:13:17 +00:00
|
|
|
root_config,
|
2022-01-14 21:12:10 +00:00
|
|
|
_marker: PhantomData,
|
2020-08-07 19:13:12 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-19 22:23:27 +00:00
|
|
|
// 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> {
|
|
|
|
if cfg!(test) {
|
|
|
|
return self.get_env("HOME").map(PathBuf::from).or_else(home_dir);
|
|
|
|
}
|
|
|
|
|
|
|
|
home_dir()
|
|
|
|
}
|
|
|
|
|
2020-08-07 19:13:12 +00:00
|
|
|
// Retrives a environment variable from the os or from a table if in testing mode
|
2021-02-13 18:32:35 +00:00
|
|
|
#[cfg(test)]
|
2020-08-07 19:13:12 +00:00
|
|
|
pub fn get_env<K: AsRef<str>>(&self, key: K) -> Option<String> {
|
2021-07-29 18:27:46 +00:00
|
|
|
self.env
|
|
|
|
.get(key.as_ref())
|
|
|
|
.map(std::string::ToString::to_string)
|
2021-02-13 18:32:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(not(test))]
|
|
|
|
#[inline]
|
|
|
|
pub fn get_env<K: AsRef<str>>(&self, key: K) -> Option<String> {
|
|
|
|
env::var(key.as_ref()).ok()
|
2020-08-07 19:13:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Retrives a environment variable from the os or from a table if in testing mode (os version)
|
2021-02-13 18:32:35 +00:00
|
|
|
#[cfg(test)]
|
2020-08-07 19:13:12 +00:00
|
|
|
pub fn get_env_os<K: AsRef<str>>(&self, key: K) -> Option<OsString> {
|
2021-02-13 18:32:35 +00:00
|
|
|
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())
|
2019-04-23 18:51:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Convert a `~` in a path to the home directory
|
2020-08-07 19:13:12 +00:00
|
|
|
pub fn expand_tilde(dir: PathBuf) -> PathBuf {
|
2019-04-23 18:51:08 +00:00
|
|
|
if dir.starts_with("~") {
|
|
|
|
let without_home = dir.strip_prefix("~").unwrap();
|
2021-07-04 19:32:58 +00:00
|
|
|
return utils::home_dir().unwrap().join(without_home);
|
2019-04-19 20:57:14 +00:00
|
|
|
}
|
2019-04-23 18:51:08 +00:00
|
|
|
dir
|
2019-04-19 20:57:14 +00:00
|
|
|
}
|
2019-05-12 17:37:23 +00:00
|
|
|
|
2019-07-02 20:12:53 +00:00
|
|
|
/// Create a new module
|
2019-09-09 23:14:38 +00:00
|
|
|
pub fn new_module(&self, name: &str) -> Module {
|
|
|
|
let config = self.config.get_module_config(name);
|
2020-01-02 04:19:08 +00:00
|
|
|
let desc = modules::description(name);
|
2019-09-09 23:14:38 +00:00
|
|
|
|
2020-01-02 04:19:08 +00:00
|
|
|
Module::new(name, desc, config)
|
2019-09-09 23:14:38 +00:00
|
|
|
}
|
|
|
|
|
2019-10-05 14:10:16 +00:00
|
|
|
/// Check if `disabled` option of the module is true in configuration file.
|
|
|
|
pub fn is_module_disabled_in_config(&self, name: &str) -> bool {
|
2019-07-02 20:12:53 +00:00
|
|
|
let config = self.config.get_module_config(name);
|
|
|
|
|
|
|
|
// If the segment has "disabled" set to "true", don't show it
|
2019-09-30 12:10:35 +00:00
|
|
|
let disabled = config.and_then(|table| table.as_table()?.get("disabled")?.as_bool());
|
2019-07-02 20:12:53 +00:00
|
|
|
|
2019-10-05 14:10:16 +00:00
|
|
|
disabled == Some(true)
|
2019-06-10 14:56:17 +00:00
|
|
|
}
|
|
|
|
|
2020-04-11 16:37:24 +00:00
|
|
|
/// Return whether the specified custom module has a `disabled` option set to true.
|
|
|
|
/// If it doesn't exist, `None` is returned.
|
|
|
|
pub fn is_custom_module_disabled_in_config(&self, name: &str) -> Option<bool> {
|
|
|
|
let config = self.config.get_custom_module_config(name)?;
|
|
|
|
let disabled = Some(config).and_then(|table| table.as_table()?.get("disabled")?.as_bool());
|
|
|
|
|
|
|
|
Some(disabled == Some(true))
|
|
|
|
}
|
|
|
|
|
2019-05-12 17:37:23 +00:00
|
|
|
// returns a new ScanDir struct with reference to current dir_files of context
|
|
|
|
// see ScanDir for methods
|
2019-09-14 14:23:53 +00:00
|
|
|
pub fn try_begin_scan(&'a self) -> Option<ScanDir<'a>> {
|
|
|
|
Some(ScanDir {
|
2020-02-03 21:57:48 +00:00
|
|
|
dir_contents: self.dir_contents().ok()?,
|
2019-05-12 17:37:23 +00:00
|
|
|
files: &[],
|
|
|
|
folders: &[],
|
|
|
|
extensions: &[],
|
2019-09-14 14:23:53 +00:00
|
|
|
})
|
2019-05-12 17:37:23 +00:00
|
|
|
}
|
2019-09-09 23:14:38 +00:00
|
|
|
|
|
|
|
/// Will lazily get repo root and branch when a module requests it.
|
2021-08-14 13:19:43 +00:00
|
|
|
pub fn get_repo(&self) -> Result<&Repo, git2::Error> {
|
|
|
|
self.repo.get_or_try_init(|| -> Result<Repo, git2::Error> {
|
|
|
|
let repository = if env::var("GIT_DIR").is_ok() {
|
|
|
|
Repository::open_from_env()
|
|
|
|
} else {
|
|
|
|
Repository::discover(&self.current_dir)
|
|
|
|
}?;
|
|
|
|
Ok(Repo {
|
|
|
|
branch: get_current_branch(&repository),
|
2021-12-03 20:15:31 +00:00
|
|
|
workdir: repository.workdir().map(Path::to_path_buf),
|
|
|
|
path: Path::to_path_buf(repository.path()),
|
2021-08-14 13:19:43 +00:00
|
|
|
state: repository.state(),
|
|
|
|
remote: get_remote_repository_info(&repository),
|
2019-09-14 14:23:53 +00:00
|
|
|
})
|
2021-08-14 13:19:43 +00:00
|
|
|
})
|
2019-09-14 14:23:53 +00:00
|
|
|
}
|
2019-09-09 23:14:38 +00:00
|
|
|
|
2020-02-03 21:57:48 +00:00
|
|
|
pub fn dir_contents(&self) -> Result<&DirContents, std::io::Error> {
|
|
|
|
self.dir_contents.get_or_try_init(|| {
|
2021-10-27 13:13:17 +00:00
|
|
|
let timeout = self.root_config.scan_timeout;
|
|
|
|
DirContents::from_path_with_timeout(&self.current_dir, Duration::from_millis(timeout))
|
2020-02-03 21:57:48 +00:00
|
|
|
})
|
|
|
|
}
|
2020-02-03 22:01:50 +00:00
|
|
|
|
|
|
|
fn get_shell() -> Shell {
|
2020-08-07 19:13:12 +00:00
|
|
|
let shell = env::var("STARSHIP_SHELL").unwrap_or_default();
|
2020-02-03 22:01:50 +00:00
|
|
|
match shell.as_str() {
|
|
|
|
"bash" => Shell::Bash,
|
|
|
|
"fish" => Shell::Fish,
|
|
|
|
"ion" => Shell::Ion,
|
2022-01-16 19:28:26 +00:00
|
|
|
"powershell" | "pwsh" => Shell::PowerShell,
|
2020-02-03 22:01:50 +00:00
|
|
|
"zsh" => Shell::Zsh,
|
2021-02-02 11:59:55 +00:00
|
|
|
"elvish" => Shell::Elvish,
|
2021-02-27 18:55:27 +00:00
|
|
|
"tcsh" => Shell::Tcsh,
|
2021-07-04 19:32:58 +00:00
|
|
|
"nu" => Shell::Nu,
|
2021-07-16 19:25:01 +00:00
|
|
|
"xonsh" => Shell::Xonsh,
|
2022-01-10 05:47:53 +00:00
|
|
|
"cmd" => Shell::Cmd,
|
2020-02-03 22:01:50 +00:00
|
|
|
_ => Shell::Unknown,
|
|
|
|
}
|
|
|
|
}
|
2020-08-11 16:44:25 +00:00
|
|
|
|
2022-01-04 09:49:42 +00:00
|
|
|
// TODO: This should be used directly by clap parse
|
2020-08-11 16:44:25 +00:00
|
|
|
pub fn get_cmd_duration(&self) -> Option<u128> {
|
2022-01-04 09:49:42 +00:00
|
|
|
self.properties
|
|
|
|
.cmd_duration
|
|
|
|
.as_deref()
|
|
|
|
.and_then(|cd| cd.parse::<u128>().ok())
|
2020-08-11 16:44:25 +00:00
|
|
|
}
|
2021-02-11 20:34:47 +00:00
|
|
|
|
|
|
|
/// Execute a command and return the output on stdout and stderr if successful
|
2021-02-13 18:32:35 +00:00
|
|
|
#[inline]
|
2021-08-23 16:49:30 +00:00
|
|
|
pub fn exec_cmd<T: AsRef<OsStr> + Debug, U: AsRef<OsStr> + Debug>(
|
|
|
|
&self,
|
|
|
|
cmd: T,
|
|
|
|
args: &[U],
|
|
|
|
) -> Option<CommandOutput> {
|
2021-12-28 05:56:06 +00:00
|
|
|
log::trace!(
|
|
|
|
"Executing command {:?} with args {:?} from context",
|
|
|
|
cmd,
|
|
|
|
args
|
|
|
|
);
|
2021-02-13 18:32:35 +00:00
|
|
|
#[cfg(test)]
|
|
|
|
{
|
2021-08-23 16:49:30 +00:00
|
|
|
let command = crate::utils::display_command(&cmd, args);
|
2021-12-28 05:56:06 +00:00
|
|
|
if let Some(output) = self
|
|
|
|
.cmd
|
|
|
|
.get(command.as_str())
|
|
|
|
.cloned()
|
|
|
|
.or_else(|| crate::utils::mock_cmd(&cmd, args))
|
|
|
|
{
|
|
|
|
return output;
|
2021-02-13 18:32:35 +00:00
|
|
|
}
|
|
|
|
}
|
2021-12-28 05:56:06 +00:00
|
|
|
let mut cmd = create_command(cmd).ok()?;
|
|
|
|
cmd.args(args).current_dir(&self.current_dir);
|
|
|
|
exec_timeout(
|
|
|
|
&mut cmd,
|
2021-10-27 13:13:17 +00:00
|
|
|
Duration::from_millis(self.root_config.command_timeout),
|
|
|
|
)
|
2021-02-11 20:34:47 +00:00
|
|
|
}
|
2022-03-25 04:10:19 +00:00
|
|
|
|
|
|
|
/// 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<Vec<&str>>) -> Option<CommandOutput> {
|
|
|
|
commands
|
|
|
|
.iter()
|
|
|
|
.find_map(|attempt| self.exec_cmd(attempt[0], &attempt[1..]))
|
|
|
|
}
|
2020-02-03 21:57:48 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[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 {
|
2020-02-06 04:03:26 +00:00
|
|
|
#[cfg(test)]
|
2021-01-20 18:34:18 +00:00
|
|
|
fn from_path(base: &Path) -> Result<Self, std::io::Error> {
|
2020-02-03 22:13:59 +00:00
|
|
|
Self::from_path_with_timeout(base, Duration::from_secs(30))
|
|
|
|
}
|
|
|
|
|
2021-01-16 12:26:52 +00:00
|
|
|
fn from_path_with_timeout(base: &Path, timeout: Duration) -> Result<Self, std::io::Error> {
|
2020-10-17 19:36:21 +00:00
|
|
|
let start = Instant::now();
|
2020-02-03 21:57:48 +00:00
|
|
|
|
|
|
|
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();
|
|
|
|
|
|
|
|
fs::read_dir(base)?
|
2020-07-28 20:26:00 +00:00
|
|
|
.enumerate()
|
|
|
|
.take_while(|(n, _)| {
|
2021-10-30 08:52:48 +00:00
|
|
|
cfg!(test) // ignore timeout during tests
|
|
|
|
|| n & 0xFF != 0 // only check timeout once every 2^8 entries
|
2020-10-17 19:36:21 +00:00
|
|
|
|| start.elapsed() < timeout
|
2020-07-28 20:26:00 +00:00
|
|
|
})
|
|
|
|
.filter_map(|(_, entry)| entry.ok())
|
2020-02-03 21:57:48 +00:00
|
|
|
.for_each(|entry| {
|
|
|
|
let path = PathBuf::from(entry.path().strip_prefix(base).unwrap());
|
|
|
|
if entry.path().is_dir() {
|
|
|
|
folders.insert(path);
|
|
|
|
} else {
|
|
|
|
if !path.to_string_lossy().starts_with('.') {
|
|
|
|
path.extension()
|
|
|
|
.map(|ext| extensions.insert(ext.to_string_lossy().to_string()));
|
|
|
|
}
|
|
|
|
if let Some(file_name) = path.file_name() {
|
|
|
|
file_names.insert(file_name.to_string_lossy().to_string());
|
|
|
|
}
|
|
|
|
files.insert(path);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
log::trace!(
|
|
|
|
"Building HashSets of directory files, folders and extensions took {:?}",
|
2020-10-17 19:36:21 +00:00
|
|
|
start.elapsed()
|
2020-02-03 21:57:48 +00:00
|
|
|
);
|
|
|
|
|
2021-07-29 18:27:46 +00:00
|
|
|
Ok(Self {
|
2020-02-03 21:57:48 +00:00
|
|
|
files,
|
|
|
|
file_names,
|
2021-03-25 20:03:19 +00:00
|
|
|
folders,
|
2020-02-03 21:57:48 +00:00
|
|
|
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_any_file_name(&self, names: &[&str]) -> bool {
|
|
|
|
names.iter().any(|name| self.has_file_name(name))
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn has_folder(&self, path: &str) -> bool {
|
|
|
|
self.folders.contains(Path::new(path))
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn has_any_folder(&self, paths: &[&str]) -> bool {
|
|
|
|
paths.iter().any(|path| self.has_folder(path))
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn has_extension(&self, ext: &str) -> bool {
|
|
|
|
self.extensions.contains(ext)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn has_any_extension(&self, exts: &[&str]) -> bool {
|
|
|
|
exts.iter().any(|ext| self.has_extension(ext))
|
2019-09-09 23:14:38 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct Repo {
|
|
|
|
/// If `current_dir` is a git repository or is contained within one,
|
|
|
|
/// this is the current branch name of that repo.
|
|
|
|
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.
|
2021-12-03 20:15:31 +00:00
|
|
|
pub workdir: Option<PathBuf>,
|
|
|
|
|
|
|
|
/// The path of the repository's `.git` directory.
|
|
|
|
pub path: PathBuf,
|
2019-09-09 23:14:38 +00:00
|
|
|
|
|
|
|
/// State
|
2021-08-14 13:19:43 +00:00
|
|
|
pub state: RepositoryState,
|
2020-11-23 21:07:16 +00:00
|
|
|
|
2020-12-08 10:12:53 +00:00
|
|
|
/// Remote repository
|
|
|
|
pub remote: Option<Remote>,
|
|
|
|
}
|
|
|
|
|
2021-12-03 20:15:31 +00:00
|
|
|
impl Repo {
|
|
|
|
/// Opens the associated git repository.
|
|
|
|
pub fn open(&self) -> Result<Repository, git2::Error> {
|
|
|
|
Repository::open(&self.path)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-08 10:12:53 +00:00
|
|
|
/// Remote repository
|
|
|
|
pub struct Remote {
|
|
|
|
pub branch: Option<String>,
|
|
|
|
pub name: Option<String>,
|
2019-05-12 17:37:23 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// 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> {
|
2020-02-03 21:57:48 +00:00
|
|
|
dir_contents: &'a DirContents,
|
2019-05-12 17:37:23 +00:00
|
|
|
files: &'a [&'a str],
|
|
|
|
folders: &'a [&'a str],
|
|
|
|
extensions: &'a [&'a str],
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a> ScanDir<'a> {
|
2022-02-25 04:31:01 +00:00
|
|
|
#[must_use]
|
2019-07-31 23:48:51 +00:00
|
|
|
pub const fn set_files(mut self, files: &'a [&'a str]) -> Self {
|
2019-05-12 17:37:23 +00:00
|
|
|
self.files = files;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2022-02-25 04:31:01 +00:00
|
|
|
#[must_use]
|
2019-07-31 23:48:51 +00:00
|
|
|
pub const fn set_extensions(mut self, extensions: &'a [&'a str]) -> Self {
|
2019-05-12 17:37:23 +00:00
|
|
|
self.extensions = extensions;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2022-02-25 04:31:01 +00:00
|
|
|
#[must_use]
|
2019-07-31 23:48:51 +00:00
|
|
|
pub const fn set_folders(mut self, folders: &'a [&'a str]) -> Self {
|
2019-05-12 17:37:23 +00:00
|
|
|
self.folders = folders;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2020-08-07 19:13:12 +00:00
|
|
|
/// based on the current PathBuf check to see
|
2019-05-12 17:37:23 +00:00
|
|
|
/// if any of this criteria match or exist and returning a boolean
|
2019-09-14 14:23:53 +00:00
|
|
|
pub fn is_match(&self) -> bool {
|
2020-02-03 21:57:48 +00:00
|
|
|
self.dir_contents.has_any_extension(self.extensions)
|
|
|
|
|| self.dir_contents.has_any_folder(self.folders)
|
|
|
|
|| self.dir_contents.has_any_file_name(self.files)
|
2019-05-12 17:37:23 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-05-22 16:04:51 +00:00
|
|
|
fn get_current_branch(repository: &Repository) -> Option<String> {
|
2020-05-06 09:19:53 +00:00
|
|
|
let head = match repository.head() {
|
|
|
|
Ok(reference) => reference,
|
|
|
|
Err(e) => {
|
|
|
|
return if e.code() == UnbornBranch {
|
|
|
|
// HEAD should only be an unborn branch if the repository is fresh,
|
2020-07-05 17:22:14 +00:00
|
|
|
// in that case read directly from `.git/HEAD`
|
|
|
|
let mut head_path = repository.path().to_path_buf();
|
|
|
|
head_path.push("HEAD");
|
|
|
|
|
|
|
|
// get first line, then last path segment
|
|
|
|
fs::read_to_string(&head_path)
|
|
|
|
.ok()?
|
|
|
|
.lines()
|
|
|
|
.next()?
|
|
|
|
.trim()
|
|
|
|
.split('/')
|
|
|
|
.last()
|
2021-07-29 18:27:46 +00:00
|
|
|
.map(std::borrow::ToOwned::to_owned)
|
2020-05-06 09:19:53 +00:00
|
|
|
} else {
|
|
|
|
None
|
|
|
|
};
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2019-05-22 16:04:51 +00:00
|
|
|
let shorthand = head.shorthand();
|
|
|
|
|
2019-07-31 23:48:51 +00:00
|
|
|
shorthand.map(std::string::ToString::to_string)
|
2019-05-22 16:04:51 +00:00
|
|
|
}
|
|
|
|
|
2020-12-08 10:12:53 +00:00
|
|
|
fn get_remote_repository_info(repository: &Repository) -> Option<Remote> {
|
2020-11-23 21:07:16 +00:00
|
|
|
if let Ok(head) = repository.head() {
|
|
|
|
if let Some(local_branch_ref) = head.name() {
|
|
|
|
let remote_ref = match repository.branch_upstream_name(local_branch_ref) {
|
|
|
|
Ok(remote_ref) => remote_ref.as_str()?.to_owned(),
|
|
|
|
Err(_) => return None,
|
|
|
|
};
|
|
|
|
|
2020-12-08 10:12:53 +00:00
|
|
|
let mut v = remote_ref.splitn(4, '/');
|
|
|
|
let remote_name = v.nth(2)?.to_owned();
|
|
|
|
let remote_branch = v.last()?.to_owned();
|
|
|
|
|
|
|
|
return Some(Remote {
|
|
|
|
branch: Some(remote_branch),
|
|
|
|
name: Some(remote_name),
|
|
|
|
});
|
2020-11-23 21:07:16 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
None
|
|
|
|
}
|
|
|
|
|
2020-02-06 16:10:59 +00:00
|
|
|
#[derive(Debug, Clone, Copy, PartialEq)]
|
2020-01-26 22:37:18 +00:00
|
|
|
pub enum Shell {
|
|
|
|
Bash,
|
|
|
|
Fish,
|
|
|
|
Ion,
|
|
|
|
PowerShell,
|
|
|
|
Zsh,
|
2021-02-02 11:59:55 +00:00
|
|
|
Elvish,
|
2021-02-27 18:55:27 +00:00
|
|
|
Tcsh,
|
2021-07-04 19:32:58 +00:00
|
|
|
Nu,
|
2021-07-16 19:25:01 +00:00
|
|
|
Xonsh,
|
2022-01-10 05:47:53 +00:00
|
|
|
Cmd,
|
2020-01-26 22:37:18 +00:00
|
|
|
Unknown,
|
|
|
|
}
|
|
|
|
|
2022-01-04 09:49:42 +00:00
|
|
|
/// Which kind of prompt target to print (main prompt, rprompt, ...)
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq)]
|
|
|
|
pub enum Target {
|
|
|
|
Main,
|
|
|
|
Right,
|
|
|
|
Continuation,
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Properties as passed on from the shell as arguments
|
|
|
|
#[derive(Parser, Debug)]
|
|
|
|
pub struct Properties {
|
2022-02-05 20:13:42 +00:00
|
|
|
/// The status code of the previously run command as an unsigned or signed 32bit integer
|
2022-01-04 09:49:42 +00:00
|
|
|
#[clap(short = 's', long = "status")]
|
2022-01-15 09:21:38 +00:00
|
|
|
pub status_code: Option<String>,
|
2022-01-10 05:47:53 +00:00
|
|
|
/// Bash, Fish and Zsh support returning codes for each process in a pipeline.
|
2022-01-15 09:21:38 +00:00
|
|
|
#[clap(long, value_delimiter = ' ')]
|
|
|
|
pub pipestatus: Option<Vec<String>>,
|
2022-01-04 09:49:42 +00:00
|
|
|
/// The width of the current interactive terminal.
|
2022-01-15 09:21:38 +00:00
|
|
|
#[clap(short = 'w', long, default_value_t=default_width(), parse(try_from_str=parse_width))]
|
2022-01-04 09:49:42 +00:00
|
|
|
terminal_width: usize,
|
|
|
|
/// The path that the prompt should render for.
|
|
|
|
#[clap(short, long)]
|
|
|
|
path: Option<PathBuf>,
|
|
|
|
/// The logical path that the prompt should render for.
|
|
|
|
/// This path should be a virtual/logical representation of the PATH argument.
|
|
|
|
#[clap(short = 'P', long)]
|
|
|
|
logical_path: Option<PathBuf>,
|
|
|
|
/// The execution duration of the last command, in milliseconds
|
|
|
|
#[clap(short = 'd', long)]
|
|
|
|
pub cmd_duration: Option<String>,
|
2022-01-10 05:47:53 +00:00
|
|
|
/// The keymap of fish/zsh/cmd
|
2022-01-04 09:49:42 +00:00
|
|
|
#[clap(short = 'k', long, default_value = "viins")]
|
|
|
|
pub keymap: String,
|
|
|
|
/// The number of currently running jobs
|
|
|
|
#[clap(short, long, default_value_t, parse(try_from_str=parse_jobs))]
|
|
|
|
pub jobs: i64,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Default for Properties {
|
|
|
|
fn default() -> Self {
|
|
|
|
Properties {
|
|
|
|
status_code: None,
|
|
|
|
pipestatus: None,
|
|
|
|
terminal_width: default_width(),
|
|
|
|
path: None,
|
|
|
|
logical_path: None,
|
|
|
|
cmd_duration: None,
|
|
|
|
keymap: "viins".to_string(),
|
|
|
|
jobs: 0,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-02-14 12:12:31 +00:00
|
|
|
/// Parse String, but treat empty strings as `None`
|
|
|
|
fn parse_trim<F: FromStr>(value: &str) -> Option<Result<F, F::Err>> {
|
|
|
|
let value = value.trim();
|
|
|
|
if value.is_empty() {
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
Some(F::from_str(value))
|
|
|
|
}
|
|
|
|
|
2022-01-04 09:49:42 +00:00
|
|
|
fn parse_jobs(jobs: &str) -> Result<i64, ParseIntError> {
|
2022-02-14 12:12:31 +00:00
|
|
|
parse_trim(jobs).unwrap_or(Ok(0))
|
2022-01-04 09:49:42 +00:00
|
|
|
}
|
|
|
|
|
2022-01-15 09:21:38 +00:00
|
|
|
fn default_width() -> usize {
|
|
|
|
terminal_size().map_or(80, |(w, _)| w.0 as usize)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn parse_width(width: &str) -> Result<usize, ParseIntError> {
|
2022-02-14 12:12:31 +00:00
|
|
|
parse_trim(width).unwrap_or_else(|| Ok(default_width()))
|
2022-01-15 09:21:38 +00:00
|
|
|
}
|
|
|
|
|
2019-05-12 17:37:23 +00:00
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
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
|
|
|
use std::io;
|
2019-05-12 17:37:23 +00:00
|
|
|
|
2020-02-03 21:57:48 +00:00
|
|
|
fn testdir(paths: &[&str]) -> Result<tempfile::TempDir, std::io::Error> {
|
|
|
|
let dir = tempfile::tempdir()?;
|
|
|
|
for path in paths {
|
|
|
|
let p = dir.path().join(Path::new(path));
|
|
|
|
if let Some(parent) = p.parent() {
|
|
|
|
fs::create_dir_all(parent)?;
|
|
|
|
}
|
|
|
|
fs::File::create(p)?.sync_all()?;
|
|
|
|
}
|
|
|
|
Ok(dir)
|
2019-05-12 17:37:23 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
2020-02-03 21:57:48 +00:00
|
|
|
fn test_scan_dir() -> Result<(), Box<dyn std::error::Error>> {
|
|
|
|
let empty = testdir(&[])?;
|
2021-01-20 18:34:18 +00:00
|
|
|
let empty_dc = DirContents::from_path(empty.path())?;
|
2020-02-03 21:57:48 +00:00
|
|
|
|
2021-06-21 18:13:10 +00:00
|
|
|
assert!(!ScanDir {
|
|
|
|
dir_contents: &empty_dc,
|
|
|
|
files: &["package.json"],
|
|
|
|
extensions: &["js"],
|
|
|
|
folders: &["node_modules"],
|
|
|
|
}
|
|
|
|
.is_match());
|
2020-03-15 17:12:25 +00:00
|
|
|
empty.close()?;
|
2020-02-03 21:57:48 +00:00
|
|
|
|
|
|
|
let rust = testdir(&["README.md", "Cargo.toml", "src/main.rs"])?;
|
2021-01-20 18:34:18 +00:00
|
|
|
let rust_dc = DirContents::from_path(rust.path())?;
|
2021-06-21 18:13:10 +00:00
|
|
|
assert!(!ScanDir {
|
|
|
|
dir_contents: &rust_dc,
|
|
|
|
files: &["package.json"],
|
|
|
|
extensions: &["js"],
|
|
|
|
folders: &["node_modules"],
|
|
|
|
}
|
|
|
|
.is_match());
|
2020-03-15 17:12:25 +00:00
|
|
|
rust.close()?;
|
2020-02-03 21:57:48 +00:00
|
|
|
|
|
|
|
let java = testdir(&["README.md", "src/com/test/Main.java", "pom.xml"])?;
|
2021-01-20 18:34:18 +00:00
|
|
|
let java_dc = DirContents::from_path(java.path())?;
|
2021-06-21 18:13:10 +00:00
|
|
|
assert!(!ScanDir {
|
|
|
|
dir_contents: &java_dc,
|
|
|
|
files: &["package.json"],
|
|
|
|
extensions: &["js"],
|
|
|
|
folders: &["node_modules"],
|
|
|
|
}
|
|
|
|
.is_match());
|
2020-03-15 17:12:25 +00:00
|
|
|
java.close()?;
|
2020-02-03 21:57:48 +00:00
|
|
|
|
|
|
|
let node = testdir(&["README.md", "node_modules/lodash/main.js", "package.json"])?;
|
2021-01-20 18:34:18 +00:00
|
|
|
let node_dc = DirContents::from_path(node.path())?;
|
2021-06-21 18:13:10 +00:00
|
|
|
assert!(ScanDir {
|
|
|
|
dir_contents: &node_dc,
|
|
|
|
files: &["package.json"],
|
|
|
|
extensions: &["js"],
|
|
|
|
folders: &["node_modules"],
|
|
|
|
}
|
|
|
|
.is_match());
|
2020-03-15 17:12:25 +00:00
|
|
|
node.close()?;
|
2019-05-22 16:04:51 +00:00
|
|
|
|
2020-02-03 21:57:48 +00:00
|
|
|
Ok(())
|
2019-05-12 17:37:23 +00:00
|
|
|
}
|
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
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn context_constructor_should_canonicalize_current_dir() -> io::Result<()> {
|
|
|
|
#[cfg(not(windows))]
|
|
|
|
use std::os::unix::fs::symlink as symlink_dir;
|
|
|
|
#[cfg(windows)]
|
|
|
|
use std::os::windows::fs::symlink_dir;
|
|
|
|
|
|
|
|
let tmp_dir = tempfile::TempDir::new()?;
|
|
|
|
let path = tmp_dir.path().join("a/xxx/yyy");
|
|
|
|
fs::create_dir_all(&path)?;
|
|
|
|
|
|
|
|
// Set up a mock symlink
|
|
|
|
let path_actual = tmp_dir.path().join("a/xxx");
|
|
|
|
let path_symlink = tmp_dir.path().join("a/symlink");
|
|
|
|
symlink_dir(&path_actual, &path_symlink).expect("create symlink");
|
|
|
|
|
|
|
|
// Mock navigation into the symlink path
|
|
|
|
let test_path = path_symlink.join("yyy");
|
|
|
|
let context = Context::new_with_shell_and_path(
|
2022-01-04 09:49:42 +00:00
|
|
|
Default::default(),
|
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
|
|
|
Shell::Unknown,
|
2022-01-04 09:49:42 +00:00
|
|
|
Target::Main,
|
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
|
|
|
test_path.clone(),
|
|
|
|
test_path.clone(),
|
|
|
|
);
|
|
|
|
|
|
|
|
assert_ne!(context.current_dir, context.logical_dir);
|
|
|
|
|
2022-02-23 23:32:35 +00:00
|
|
|
let expected_current_dir =
|
|
|
|
dunce::canonicalize(path_actual.join("yyy")).expect("canonicalize");
|
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
|
|
|
assert_eq!(expected_current_dir, context.current_dir);
|
|
|
|
|
|
|
|
let expected_logical_dir = test_path;
|
|
|
|
assert_eq!(expected_logical_dir, context.logical_dir);
|
|
|
|
|
|
|
|
tmp_dir.close()
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn context_constructor_should_fail_gracefully_when_canonicalization_fails() {
|
|
|
|
// Mock navigation to a directory which does not exist on disk
|
|
|
|
let test_path = Path::new("/path_which_does_not_exist").to_path_buf();
|
|
|
|
let context = Context::new_with_shell_and_path(
|
2022-01-04 09:49:42 +00:00
|
|
|
Default::default(),
|
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
|
|
|
Shell::Unknown,
|
2022-01-04 09:49:42 +00:00
|
|
|
Target::Main,
|
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
|
|
|
test_path.clone(),
|
|
|
|
test_path.clone(),
|
|
|
|
);
|
|
|
|
|
|
|
|
let expected_current_dir = &test_path;
|
|
|
|
assert_eq!(expected_current_dir, &context.current_dir);
|
|
|
|
|
|
|
|
let expected_logical_dir = &test_path;
|
|
|
|
assert_eq!(expected_logical_dir, &context.logical_dir);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn context_constructor_should_fall_back_to_tilde_replacement_when_canonicalization_fails() {
|
2021-07-04 19:32:58 +00:00
|
|
|
use utils::home_dir;
|
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
|
|
|
|
|
|
|
// Mock navigation to a directory which does not exist on disk
|
|
|
|
let test_path = Path::new("~/path_which_does_not_exist").to_path_buf();
|
|
|
|
let context = Context::new_with_shell_and_path(
|
2022-01-04 09:49:42 +00:00
|
|
|
Default::default(),
|
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
|
|
|
Shell::Unknown,
|
2022-01-04 09:49:42 +00:00
|
|
|
Target::Main,
|
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
|
|
|
test_path.clone(),
|
|
|
|
test_path.clone(),
|
|
|
|
);
|
|
|
|
|
|
|
|
let expected_current_dir = home_dir()
|
|
|
|
.expect("home_dir")
|
|
|
|
.join("path_which_does_not_exist");
|
|
|
|
assert_eq!(expected_current_dir, context.current_dir);
|
|
|
|
|
|
|
|
let expected_logical_dir = test_path;
|
|
|
|
assert_eq!(expected_logical_dir, context.logical_dir);
|
|
|
|
}
|
2022-02-23 23:32:35 +00:00
|
|
|
|
|
|
|
#[cfg(windows)]
|
|
|
|
#[test]
|
|
|
|
fn strip_extended_path_prefix() {
|
|
|
|
let test_path = Path::new(r"\\?\C:\").to_path_buf();
|
|
|
|
let context = Context::new_with_shell_and_path(
|
|
|
|
Properties::default(),
|
|
|
|
Shell::Unknown,
|
|
|
|
Target::Main,
|
|
|
|
test_path.clone(),
|
|
|
|
test_path,
|
|
|
|
);
|
|
|
|
|
|
|
|
let expected_path = Path::new(r"C:\");
|
|
|
|
|
|
|
|
assert_eq!(&context.current_dir, expected_path);
|
|
|
|
}
|
2019-04-19 20:57:14 +00:00
|
|
|
}
|