mirror of
https://github.com/starship/starship.git
synced 2026-06-23 02:05:51 +07:00
fix: Lazy load git repo and only run module if not disabled (#306)
A couple of optimizations are done in this PR. One, we now will check config ahead of time to see if a module is disabled before running any module code. Also, we won't try to discover a git repository unless the module requests access to it.
This commit is contained in:
committed by
Matan Kushner
parent
dc8409333e
commit
9f70ffb7a7
+52
-28
@@ -2,11 +2,12 @@ use crate::config::Config;
|
||||
use crate::module::Module;
|
||||
|
||||
use clap::ArgMatches;
|
||||
use git2::Repository;
|
||||
use git2::{Repository, RepositoryState};
|
||||
use once_cell::sync::OnceCell;
|
||||
use std::env;
|
||||
use std::ffi::OsStr;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// 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
|
||||
@@ -24,13 +25,8 @@ pub struct Context<'a> {
|
||||
/// The map of arguments that were passed when starship was called.
|
||||
pub arguments: ArgMatches<'a>,
|
||||
|
||||
/// If `current_dir` is a git repository or is contained within one,
|
||||
/// this is the path to the root of that repo.
|
||||
pub repo_root: Option<PathBuf>,
|
||||
|
||||
/// If `current_dir` is a git repository or is contained within one,
|
||||
/// this is the current branch name of that repo.
|
||||
pub branch_name: Option<String>,
|
||||
/// Private field to store Git information for modules who need it
|
||||
repo: OnceCell<Repo>,
|
||||
}
|
||||
|
||||
impl<'a> Context<'a> {
|
||||
@@ -67,21 +63,12 @@ impl<'a> Context<'a> {
|
||||
.map(|entry| entry.path())
|
||||
.collect::<Vec<PathBuf>>();
|
||||
|
||||
let repository = Repository::discover(¤t_dir).ok();
|
||||
let repo_root = repository
|
||||
.as_ref()
|
||||
.and_then(|repo| repo.workdir().map(std::path::Path::to_path_buf));
|
||||
let branch_name = repository
|
||||
.as_ref()
|
||||
.and_then(|repo| get_current_branch(repo));
|
||||
|
||||
Context {
|
||||
config,
|
||||
arguments,
|
||||
current_dir,
|
||||
dir_files,
|
||||
repo_root,
|
||||
branch_name,
|
||||
repo: OnceCell::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,20 +82,20 @@ impl<'a> Context<'a> {
|
||||
}
|
||||
|
||||
/// Create a new module
|
||||
///
|
||||
/// Will return `None` if the module is disabled by configuration, by setting
|
||||
/// the `disabled` key to `true` in the configuration for that module.
|
||||
pub fn new_module(&self, name: &str) -> Option<Module> {
|
||||
pub fn new_module(&self, name: &str) -> Module {
|
||||
let config = self.config.get_module_config(name);
|
||||
|
||||
Module::new(name, config)
|
||||
}
|
||||
|
||||
/// Check the `disabled` configuration of the module
|
||||
pub fn is_module_enabled(&self, name: &str) -> bool {
|
||||
let config = self.config.get_module_config(name);
|
||||
|
||||
// If the segment has "disabled" set to "true", don't show it
|
||||
let disabled = config.and_then(|table| table.get_as_bool("disabled"));
|
||||
|
||||
if disabled == Some(true) {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(Module::new(name, config))
|
||||
disabled != Some(true)
|
||||
}
|
||||
|
||||
// returns a new ScanDir struct with reference to current dir_files of context
|
||||
@@ -121,6 +108,43 @@ impl<'a> Context<'a> {
|
||||
extensions: &[],
|
||||
}
|
||||
}
|
||||
|
||||
/// Will lazily get repo root and branch when a module requests it.
|
||||
pub fn get_repo(&self) -> Result<&Repo, std::io::Error> {
|
||||
let repo = self
|
||||
.repo
|
||||
.get_or_try_init(|| -> Result<Repo, std::io::Error> {
|
||||
let repository = Repository::discover(&self.current_dir).ok();
|
||||
let branch = repository
|
||||
.as_ref()
|
||||
.and_then(|repo| get_current_branch(repo));
|
||||
let root = repository
|
||||
.as_ref()
|
||||
.and_then(|repo| repo.workdir().map(Path::to_path_buf));
|
||||
let state = repository.as_ref().map(|repo| repo.state());
|
||||
|
||||
Ok(Repo {
|
||||
branch,
|
||||
root,
|
||||
state,
|
||||
})
|
||||
})?;
|
||||
|
||||
Ok(repo)
|
||||
}
|
||||
}
|
||||
|
||||
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.
|
||||
pub root: Option<PathBuf>,
|
||||
|
||||
/// State
|
||||
pub state: Option<RepositoryState>,
|
||||
}
|
||||
|
||||
// A struct of Criteria which will be used to verify current PathBuf is
|
||||
|
||||
@@ -29,7 +29,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
|
||||
}
|
||||
|
||||
// TODO: Set style based on percentage when threshold is modifiable
|
||||
let mut module = context.new_module("battery")?;
|
||||
let mut module = context.new_module("battery");
|
||||
let module_style = module
|
||||
.config_value_style("style")
|
||||
.unwrap_or_else(|| Color::Red.bold());
|
||||
|
||||
@@ -20,7 +20,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
|
||||
const ASSUMED_MODE: ShellEditMode = ShellEditMode::Insert;
|
||||
// TODO: extend config to more modes
|
||||
|
||||
let mut module = context.new_module("character")?;
|
||||
let mut module = context.new_module("character");
|
||||
module.get_prefix().set_value("");
|
||||
|
||||
let style_success = module
|
||||
|
||||
@@ -7,7 +7,7 @@ use super::{Context, Module};
|
||||
/// Will only print if last command took more than a certain amount of time to
|
||||
/// execute. Default is two seconds, but can be set by config option `min_time`.
|
||||
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
|
||||
let mut module = context.new_module("cmd_duration")?;
|
||||
let mut module = context.new_module("cmd_duration");
|
||||
|
||||
let arguments = &context.arguments;
|
||||
let elapsed = arguments
|
||||
|
||||
@@ -18,7 +18,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
|
||||
const DIR_TRUNCATION_LENGTH: i64 = 3;
|
||||
const FISH_STYLE_PWD_DIR_LENGTH: i64 = 0;
|
||||
|
||||
let mut module = context.new_module("directory")?;
|
||||
let mut module = context.new_module("directory");
|
||||
let module_color = module
|
||||
.config_value_style("style")
|
||||
.unwrap_or_else(|| Color::Cyan.bold());
|
||||
@@ -36,7 +36,9 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
|
||||
let current_dir = &context.current_dir;
|
||||
log::debug!("Current directory: {:?}", current_dir);
|
||||
|
||||
let dir_string = match &context.repo_root {
|
||||
let repo = &context.get_repo().ok()?;
|
||||
|
||||
let dir_string = match &repo.root {
|
||||
Some(repo_root) if truncate_to_repo => {
|
||||
let repo_folder_name = repo_root.file_name().unwrap().to_str().unwrap();
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ use super::{Context, Module};
|
||||
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
|
||||
const GIT_BRANCH_CHAR: &str = " ";
|
||||
|
||||
let mut module = context.new_module("git_branch")?;
|
||||
let mut module = context.new_module("git_branch");
|
||||
|
||||
let segment_color = module
|
||||
.config_value_style("style")
|
||||
@@ -38,7 +38,8 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
|
||||
} else {
|
||||
unsafe_truncation_length as usize
|
||||
};
|
||||
let branch_name = context.branch_name.as_ref()?;
|
||||
let repo = context.get_repo().ok()?;
|
||||
let branch_name = repo.branch.as_ref()?;
|
||||
let truncated_graphemes = get_graphemes(&branch_name, len);
|
||||
// The truncation symbol should only be added if we truncated
|
||||
let truncated_and_symbol = if len < graphemes_len(&branch_name) {
|
||||
|
||||
+17
-24
@@ -1,6 +1,6 @@
|
||||
use ansi_term::Color;
|
||||
use git2::{Repository, RepositoryState};
|
||||
use std::path::Path;
|
||||
use git2::RepositoryState;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use super::{Context, Module};
|
||||
|
||||
@@ -9,11 +9,12 @@ use super::{Context, Module};
|
||||
/// During a git operation it will show: REBASING, BISECTING, MERGING, etc.
|
||||
/// If the progress information is available (e.g. rebasing 3/10), it will show that too.
|
||||
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
|
||||
let mut module = context.new_module("git_state")?;
|
||||
let mut module = context.new_module("git_state");
|
||||
|
||||
let repo_root = context.repo_root.as_ref()?;
|
||||
let mut repository = Repository::open(repo_root).ok()?;
|
||||
let state_description = get_state_description(&mut repository);
|
||||
let repo = context.get_repo().ok()?;
|
||||
let repo_root = repo.root.as_ref()?;
|
||||
let repo_state = repo.state?;
|
||||
let state_description = get_state_description(repo_state, repo_root);
|
||||
|
||||
if let StateDescription::Clean = state_description {
|
||||
return None;
|
||||
@@ -79,8 +80,11 @@ static AM_OR_REBASE_LABEL: StateLabel = StateLabel {
|
||||
message_default: "AM/REBASE",
|
||||
};
|
||||
|
||||
fn get_state_description(repository: &mut Repository) -> StateDescription {
|
||||
match repository.state() {
|
||||
/// Returns the state of the current repository
|
||||
///
|
||||
/// During a git operation it will show: REBASING, BISECTING, MERGING, etc.
|
||||
fn get_state_description(state: RepositoryState, root: &PathBuf) -> StateDescription {
|
||||
match state {
|
||||
RepositoryState::Clean => StateDescription::Clean,
|
||||
RepositoryState::Merge => StateDescription::Label(&MERGE_LABEL),
|
||||
RepositoryState::Revert => StateDescription::Label(&REVERT_LABEL),
|
||||
@@ -90,13 +94,13 @@ fn get_state_description(repository: &mut Repository) -> StateDescription {
|
||||
RepositoryState::Bisect => StateDescription::Label(&BISECT_LABEL),
|
||||
RepositoryState::ApplyMailbox => StateDescription::Label(&AM_LABEL),
|
||||
RepositoryState::ApplyMailboxOrRebase => StateDescription::Label(&AM_OR_REBASE_LABEL),
|
||||
RepositoryState::Rebase => describe_rebase(repository),
|
||||
RepositoryState::RebaseInteractive => describe_rebase(repository),
|
||||
RepositoryState::RebaseMerge => describe_rebase(repository),
|
||||
RepositoryState::Rebase => describe_rebase(root),
|
||||
RepositoryState::RebaseInteractive => describe_rebase(root),
|
||||
RepositoryState::RebaseMerge => describe_rebase(root),
|
||||
}
|
||||
}
|
||||
|
||||
fn describe_rebase(repository: &mut Repository) -> StateDescription {
|
||||
fn describe_rebase(root: &PathBuf) -> StateDescription {
|
||||
/*
|
||||
* Sadly, libgit2 seems to have some issues with reading the state of
|
||||
* interactive rebases. So, instead, we'll poke a few of the .git files
|
||||
@@ -107,18 +111,7 @@ fn describe_rebase(repository: &mut Repository) -> StateDescription {
|
||||
|
||||
let just_label = StateDescription::Label(&REBASE_LABEL);
|
||||
|
||||
let dot_git = repository
|
||||
.workdir()
|
||||
.and_then(|d| Some(d.join(Path::new(".git"))));
|
||||
|
||||
let dot_git = match dot_git {
|
||||
None => {
|
||||
// We didn't find the .git directory.
|
||||
// Something very odd is going on. We'll just back away slowly.
|
||||
return just_label;
|
||||
}
|
||||
Some(path) => path,
|
||||
};
|
||||
let dot_git = root.join(".git");
|
||||
|
||||
let has_path = |relative_path: &str| {
|
||||
let path = dot_git.join(Path::new(relative_path));
|
||||
|
||||
@@ -30,11 +30,12 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
|
||||
const GIT_STATUS_RENAMED: &str = "»";
|
||||
const GIT_STATUS_DELETED: &str = "✘";
|
||||
|
||||
let branch_name = context.branch_name.as_ref()?;
|
||||
let repo_root = context.repo_root.as_ref()?;
|
||||
let repo = context.get_repo().ok()?;
|
||||
let branch_name = repo.branch.as_ref()?;
|
||||
let repo_root = repo.root.as_ref()?;
|
||||
let repository = Repository::open(repo_root).ok()?;
|
||||
|
||||
let mut module = context.new_module("git_status")?;
|
||||
let mut module = context.new_module("git_status");
|
||||
let show_sync_count = module.config_value_bool("show_sync_count").unwrap_or(false);
|
||||
let module_style = module
|
||||
.config_value_style("style")
|
||||
@@ -133,10 +134,10 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
|
||||
}
|
||||
|
||||
if module.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(module)
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(module)
|
||||
}
|
||||
|
||||
/// Gets the bitflags associated with the repo's git status
|
||||
|
||||
@@ -29,7 +29,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
|
||||
Some(go_version) => {
|
||||
const GO_CHAR: &str = "🐹 ";
|
||||
|
||||
let mut module = context.new_module("golang")?;
|
||||
let mut module = context.new_module("golang");
|
||||
let module_style = module
|
||||
.config_value_style("style")
|
||||
.unwrap_or_else(|| Color::Cyan.bold());
|
||||
|
||||
@@ -10,7 +10,7 @@ use std::ffi::OsString;
|
||||
/// - hostname.disabled is absent or false
|
||||
/// - hostname.ssh_only is false OR the user is currently connected as an SSH session (`$SSH_CONNECTION`)
|
||||
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
|
||||
let mut module = context.new_module("hostname")?;
|
||||
let mut module = context.new_module("hostname");
|
||||
let module_style = module
|
||||
.config_value_style("style")
|
||||
.unwrap_or_else(|| Color::Green.bold().dimmed());
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ use super::{Context, Module};
|
||||
|
||||
/// Creates a segment to show if there are any active jobs running
|
||||
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
|
||||
let mut module = context.new_module("jobs")?;
|
||||
let mut module = context.new_module("jobs");
|
||||
|
||||
let threshold = module.config_value_i64("threshold").unwrap_or(1);
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ use super::{Context, Module};
|
||||
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
|
||||
const LINE_ENDING: &str = "\n";
|
||||
|
||||
let mut module = context.new_module("line_break")?;
|
||||
let mut module = context.new_module("line_break");
|
||||
|
||||
module.get_prefix().set_value("");
|
||||
module.get_suffix().set_value("");
|
||||
|
||||
@@ -22,7 +22,7 @@ use super::{Context, Module};
|
||||
/// - pure // use_name == false in a pure nix-shell
|
||||
/// - impure // use_name == false in an impure nix-shell
|
||||
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
|
||||
let mut module = context.new_module("nix_shell")?;
|
||||
let mut module = context.new_module("nix_shell");
|
||||
|
||||
env::var("IN_NIX_SHELL")
|
||||
.ok()
|
||||
|
||||
@@ -25,7 +25,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
|
||||
Some(node_version) => {
|
||||
const NODE_CHAR: &str = "⬢ ";
|
||||
|
||||
let mut module = context.new_module("nodejs")?;
|
||||
let mut module = context.new_module("nodejs");
|
||||
let module_style = module
|
||||
.config_value_style("style")
|
||||
.unwrap_or_else(|| Color::Green.bold());
|
||||
|
||||
@@ -13,7 +13,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
|
||||
Some(package_version) => {
|
||||
const PACKAGE_CHAR: &str = "📦 ";
|
||||
|
||||
let mut module = context.new_module("package")?;
|
||||
let mut module = context.new_module("package");
|
||||
let module_style = module
|
||||
.config_value_style("style")
|
||||
.unwrap_or_else(|| Color::Red.bold());
|
||||
|
||||
@@ -30,7 +30,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut module = context.new_module("python")?;
|
||||
let mut module = context.new_module("python");
|
||||
let pyenv_version_name = module
|
||||
.config_value_bool("pyenv_version_name")
|
||||
.unwrap_or(false);
|
||||
|
||||
+1
-1
@@ -23,7 +23,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
|
||||
Some(ruby_version) => {
|
||||
const RUBY_CHAR: &str = "💎 ";
|
||||
|
||||
let mut module = context.new_module("ruby")?;
|
||||
let mut module = context.new_module("ruby");
|
||||
let module_style = module
|
||||
.config_value_style("style")
|
||||
.unwrap_or_else(|| Color::Red.bold());
|
||||
|
||||
+1
-1
@@ -23,7 +23,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
|
||||
Some(rust_version) => {
|
||||
const RUST_CHAR: &str = "🦀 ";
|
||||
|
||||
let mut module = context.new_module("rust")?;
|
||||
let mut module = context.new_module("rust");
|
||||
let module_style = module
|
||||
.config_value_style("style")
|
||||
.unwrap_or_else(|| Color::Red.bold());
|
||||
|
||||
@@ -18,7 +18,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
|
||||
const ROOT_UID: Option<u32> = Some(0);
|
||||
let user_uid = get_uid();
|
||||
if user != logname || ssh_connection.is_some() || user_uid == ROOT_UID {
|
||||
let mut module = context.new_module("username")?;
|
||||
let mut module = context.new_module("username");
|
||||
let module_style = get_mod_style(user_uid, &module);
|
||||
module.set_style(module_style);
|
||||
module.new_segment("username", &user?);
|
||||
|
||||
@@ -81,6 +81,7 @@ pub fn prompt(args: ArgMatches) {
|
||||
|
||||
let modules = &prompt_order
|
||||
.par_iter()
|
||||
.filter(|module| context.is_module_enabled(module))
|
||||
.map(|module| modules::handle(module, &context)) // Compute modules
|
||||
.flatten()
|
||||
.collect::<Vec<Module>>(); // Remove segments set to `None`
|
||||
|
||||
Reference in New Issue
Block a user