feat(vcs): Introduce the VCS module (#6388)

Co-authored-by: David Knaack <davidkna@users.noreply.github.com>
This commit is contained in:
Poliorcetics
2026-01-04 17:44:03 +01:00
committed by GitHub
parent 8a69666084
commit 0dd5a4f402
11 changed files with 426 additions and 34 deletions
+73
View File
@@ -1749,6 +1749,26 @@
"detect_folders": []
}
},
"vcs": {
"default": {
"disabled": false,
"fossil_modules": "$fossil_branch$fossil_metrics",
"git_modules": "$git_branch$git_commit$git_state$git_metrics$git_status",
"hg_modules": "$hg_branch$hg_state",
"order": [
"git",
"hg",
"pijul",
"fossil"
],
"pijul_modules": "$pijul_channel"
},
"allOf": [
{
"$ref": "#/definitions/VcsConfig"
}
]
},
"vcsh": {
"$ref": "#/$defs/VcshConfig",
"default": {
@@ -6518,6 +6538,59 @@
},
"additionalProperties": false
},
"VcsConfig": {
"type": "object",
"properties": {
"order": {
"description": "Order in which to discover VCSes. The first one found is the one used.",
"default": [
"git",
"hg",
"pijul",
"fossil"
],
"type": "array",
"items": {
"$ref": "#/definitions/Vcs"
}
},
"disabled": {
"description": "Disables the VCS module.",
"default": false,
"type": "boolean"
},
"fossil_modules": {
"description": "Modules to use when Fossil is matched.\n\nThey are configured separately at the top level.",
"default": "$fossil_branch$fossil_metrics",
"type": "string"
},
"git_modules": {
"description": "Modules to use when Git is matched.\n\nThey are configured separately at the top level.",
"default": "$git_branch$git_commit$git_state$git_metrics$git_status",
"type": "string"
},
"hg_modules": {
"description": "Modules to use when Mercurial is matched.\n\nThey are configured separately at the top level.",
"default": "$hg_branch$hg_state",
"type": "string"
},
"pijul_modules": {
"description": "Modules to use when Pijul is matched.\n\nThey are configured separately at the top level.",
"default": "$pijul_channel",
"type": "string"
}
},
"additionalProperties": false
},
"Vcs": {
"type": "string",
"enum": [
"fossil",
"git",
"hg",
"pijul"
]
},
"VcshConfig": {
"type": "object",
"properties": {
+41
View File
@@ -4909,6 +4909,47 @@ By default the module will be shown if any of the following conditions are met:
format = 'via [V $version](blue bold) '
```
## VCS
> Note the module is enabled by default but **not** included in the default list because that would be a breaking change.
> Additionally, the exact format of the module may change in the future, for example to handle right-aligned prompt.
The `vcs` module displays the current active Version Control System (VCS).
The module will be shown only if a configured VCS is currently in use.
### Options
| Option | Default | Description |
| ---------------- | ----------------------------------------------------------- | ----------------------------------------------------- |
| `order` | `["git", "hg", "pijul", "fossil"]` | The order in which to search VCSes. |
| `fossil_modules` | `"$fossil_branch$fossil_metrics"` | Modules to show when a Fossil repository is found. |
| `git_modules` | `"$git_branch$git_commit$git_state$git_metrics$git_status"` | Modules to show when a Git repository is found. |
| `hg_modules` | `"$hg_branch$hg_state"` | Modules to show when a Mercurial repository is found. |
| `pijul_modules` | `"$pijul_channel"` | Modules to show when a Pijul repository is found. |
| `disabled` | `false` | Disables the `vcs` module. |
### Example
```toml
# ~/.config/starship.toml
[vcs]
# Will look for Git then Pijul if not found but not for other VCSes at all
order = [
"git",
"pijul",
]
# Any module (except `$vcs` itself to avoid infinite loops) can be included here
git_modules = "$git_branch${custom.foo}"
# See documentation for custom modules
[custom.foo]
command = 'echo foo'
detect_files = ['foo']
when = ''' test "$HOME" = "$PWD" '''
format = ' transcending [$output]($style)'
```
## VCSH
The `vcsh` module displays the current active [VCSH](https://github.com/RichiH/vcsh) repository.
+3
View File
@@ -101,6 +101,7 @@ pub mod typst;
pub mod username;
pub mod v;
pub mod vagrant;
pub mod vcs;
pub mod vcsh;
pub mod xmake;
pub mod zig;
@@ -314,6 +315,8 @@ pub struct FullConfig<'a> {
#[serde(borrow)]
vagrant: vagrant::VagrantConfig<'a>,
#[serde(borrow)]
vcs: vcs::VcsConfig<'a>,
#[serde(borrow)]
vcsh: vcsh::VcshConfig<'a>,
#[serde(borrow)]
vlang: v::VConfig<'a>,
+56
View File
@@ -0,0 +1,56 @@
//! The VCS module is a gathering of other Version Control System modules.
//!
//! It offers the option to order VCSes in a "discovery" order and will then use the `<vcs>.format`
//! option for it.
//!
//! Notably, this module is only a dispatcher: it offers nothing beyond "try these VCSes in this
//! order and use these modules for the first one found".
//!
//! Individual VCS modules are still configured at the toplevel starship configuration, they are
//! not included as subconfigurations of the current module.
use serde::{Deserialize, Serialize};
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(
feature = "config-schema",
derive(schemars::JsonSchema),
schemars(deny_unknown_fields)
)]
#[serde(default)]
pub struct VcsConfig<'a> {
/// Order in which to discover VCSes.
/// The first one found is the one used.
pub order: Vec<&'a str>,
/// Disables the VCS module.
pub disabled: bool,
/// Modules to use when Fossil is matched.
///
/// They are configured separately at the top level.
pub fossil_modules: &'a str,
/// Modules to use when Git is matched.
///
/// They are configured separately at the top level.
pub git_modules: &'a str,
/// Modules to use when Mercurial is matched.
///
/// They are configured separately at the top level.
pub hg_modules: &'a str, // NOTE: uses `hg` to correspond to existing `hg_branch` module
/// Modules to use when Pijul is matched.
///
/// They are configured separately at the top level.
pub pijul_modules: &'a str,
}
impl Default for VcsConfig<'_> {
fn default() -> Self {
VcsConfig {
order: vec!["git", "hg", "pijul", "fossil"],
disabled: false,
fossil_modules: "$fossil_branch$fossil_metrics",
git_modules: "$git_branch$git_commit$git_state$git_metrics$git_status",
hg_modules: "$hg_branch$hg_state",
pijul_modules: "$pijul_channel",
}
}
}
+1
View File
@@ -103,6 +103,7 @@ pub const ALL_MODULES: &[&str] = &[
"typst",
"username",
"vagrant",
"vcs",
"vcsh",
"vlang",
"xmake",
+2 -11
View File
@@ -1,4 +1,4 @@
use super::{Context, Module, ModuleConfig};
use super::{Context, Module, ModuleConfig, vcs};
use crate::configs::fossil_branch::FossilBranchConfig;
use crate::formatter::StringFormatter;
@@ -17,16 +17,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
return None;
}
let checkout_db = if cfg!(windows) {
"_FOSSIL_"
} else {
".fslckout"
};
// See if we're in a check-out by scanning upwards for a directory containing the checkout_db file
context
.begin_ancestor_scan()
.set_files(&[checkout_db])
.scan()?;
vcs::discover_repo_root(context, vcs::Vcs::Fossil)?;
let len = if config.truncation_length <= 0 {
log::warn!(
+2 -11
View File
@@ -1,6 +1,6 @@
use regex::Regex;
use super::{Context, Module, ModuleConfig};
use super::{Context, Module, ModuleConfig, vcs};
use crate::configs::fossil_metrics::FossilMetricsConfig;
use crate::formatter::StringFormatter;
@@ -17,16 +17,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
return None;
}
let checkout_db = if cfg!(windows) {
"_FOSSIL_"
} else {
".fslckout"
};
// See if we're in a check-out by scanning upwards for a directory containing the checkout_db file
context
.begin_ancestor_scan()
.set_files(&[checkout_db])
.scan()?;
vcs::discover_repo_root(context, vcs::Vcs::Fossil)?;
// Read the total number of added and deleted lines from "fossil diff -i --numstat"
let output = context
+2 -2
View File
@@ -2,7 +2,7 @@ use std::io::Error;
use std::path::Path;
use super::utils::truncate::truncate_text;
use super::{Context, Module, ModuleConfig};
use super::{Context, Module, ModuleConfig, vcs};
use crate::configs::hg_branch::HgBranchConfig;
use crate::formatter::StringFormatter;
@@ -31,7 +31,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
config.truncation_length as usize
};
let repo_root = context.begin_ancestor_scan().set_folders(&[".hg"]).scan()?;
let repo_root = vcs::discover_repo_root(context, vcs::Vcs::Hg)?;
let branch_name = get_hg_current_bookmark(&repo_root).unwrap_or_else(|_| {
get_hg_branch_name(&repo_root).unwrap_or_else(|_| String::from("default"))
});
+3
View File
@@ -96,6 +96,7 @@ mod time;
mod username;
mod utils;
mod vagrant;
mod vcs;
mod vcsh;
mod vlang;
mod xmake;
@@ -217,6 +218,7 @@ pub fn handle<'a>(module: &str, context: &'a Context) -> Option<Module<'a>> {
"username" => username::module(context),
"vlang" => vlang::module(context),
"vagrant" => vagrant::module(context),
"vcs" => vcs::module(context),
"vcsh" => vcsh::module(context),
"xmake" => xmake::module(context),
"zig" => zig::module(context),
@@ -351,6 +353,7 @@ pub fn description(module: &str) -> &'static str {
"typst" => "The current installed version of typst",
"username" => "The active user's username",
"vagrant" => "The currently installed version of Vagrant",
"vcs" => "The currently active VCS repository (first one matching)",
"vcsh" => "The currently active VCSH repository",
"vlang" => "The currently installed version of V",
"xmake" => "The currently installed version of XMake",
+3 -10
View File
@@ -1,5 +1,5 @@
use super::utils::truncate::truncate_text;
use super::{Context, Module, ModuleConfig};
use super::{Context, Module, ModuleConfig, vcs};
use crate::configs::pijul_channel::PijulConfig;
use crate::formatter::StringFormatter;
@@ -8,15 +8,6 @@ use crate::formatter::StringFormatter;
///
/// Will display the channel lame if the current directory is a pijul repo
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let is_repo = context
.try_begin_scan()?
.set_folders(&[".pijul"])
.is_match();
if !is_repo {
return None;
}
let mut module = context.new_module("pijul_channel");
let config: PijulConfig = PijulConfig::try_load(module.config);
@@ -25,6 +16,8 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
return None;
}
vcs::discover_repo_root(context, vcs::Vcs::Pijul)?;
let channel_name = get_pijul_current_channel(context)?;
let truncated_text = truncate_text(
+240
View File
@@ -0,0 +1,240 @@
use std::borrow::Cow;
use std::path::Path;
use super::{Context, Module, ModuleConfig};
use crate::configs::vcs::VcsConfig;
use crate::formatter::StringFormatter;
use crate::formatter::string_formatter::StringFormatterError;
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("vcs");
let config = VcsConfig::try_load(module.config);
if config.disabled || config.order.is_empty() {
return None;
}
let vcs = config
.order
.into_iter()
.filter_map(|vcs| Vcs::try_from(vcs).ok())
.find(|vcs| discover_repo_root(context, *vcs).is_some())?;
let modules = match vcs {
Vcs::Fossil => config.fossil_modules,
Vcs::Git => config.git_modules,
Vcs::Hg => config.hg_modules,
Vcs::Pijul => config.pijul_modules,
};
if modules.is_empty() {
return None;
}
let parsed = StringFormatter::new(modules).and_then(|formatter| {
formatter
.map_variables_to_segments(|variable| match variable {
"vcs" => Some(Err(StringFormatterError::Custom(
"cannot recursively include the `vcs` module in itself".into(),
))),
module => super::handle(module, context).map(|m| Ok(m.segments)),
})
.parse(None, Some(context))
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `vcs`:\n{}", error);
return None;
}
});
Some(module)
}
pub fn discover_repo_root<'a>(context: &'a Context, vcs: Vcs) -> Option<Cow<'a, Path>> {
let scan = context.begin_ancestor_scan();
let scan = match vcs {
Vcs::Fossil => scan.set_files(if cfg!(windows) {
&["_FOSSIL_"]
} else {
&[".fslckout"]
}),
Vcs::Hg => scan.set_folders(&[".hg"]),
Vcs::Pijul => scan.set_folders(&[".pijul"]),
Vcs::Git => return context.get_repo().ok().map(|r| r.repo.path().into()),
};
scan.scan().map(Into::into)
}
#[derive(Debug, Copy, Clone)]
pub enum Vcs {
Fossil,
Git,
// NOTE: uses `hg` to correspond to existing `hg_branch` module
Hg,
Pijul,
}
impl<'a> TryFrom<&'a str> for Vcs {
type Error = &'a str;
fn try_from(value: &'a str) -> Result<Self, Self::Error> {
match value {
"fossil" => Ok(Self::Fossil),
"git" => Ok(Self::Git),
"hg" | "mercurial" => Ok(Self::Hg),
"pijul" => Ok(Self::Pijul),
_ => Err(value),
}
}
}
#[cfg(test)]
mod tests {
use std::io;
use nu_ansi_term::Color;
use crate::test::{FixtureProvider, ModuleRenderer, fixture_repo};
#[test]
fn empty_order_disables() {
let actual = ModuleRenderer::new("vcs")
.config(toml::toml! {
[vcs]
order = []
})
.collect();
assert_eq!(actual, None);
}
#[test]
fn empty_modules_disables() -> io::Result<()> {
let repo_dir = fixture_repo(FixtureProvider::Fossil)?;
let actual = ModuleRenderer::new("vcs")
.config(toml::toml! {
[vcs]
order = ["fossil"]
fossil_modules = ""
})
.path(repo_dir.path())
.collect();
assert_eq!(actual, None);
repo_dir.close()
}
#[test]
fn recursive_vcs_include_fails() -> io::Result<()> {
let repo_dir = fixture_repo(FixtureProvider::Fossil)?;
let actual = ModuleRenderer::new("vcs")
.config(toml::toml! {
[vcs]
order = ["fossil"]
fossil_modules = "$vcs"
})
.path(repo_dir.path())
.collect();
assert_eq!(actual, None);
repo_dir.close()
}
#[test]
fn detect_fossil() -> io::Result<()> {
with_marker(
"fossil",
FixtureProvider::Fossil,
Some(format!("{}", Color::Green.bold().paint("test "))),
)
}
#[test]
fn detect_git() -> io::Result<()> {
with_marker(
"git",
FixtureProvider::Git,
Some(format!("{}", Color::Green.bold().paint("test "))),
)
}
#[test]
fn detect_hg() -> io::Result<()> {
with_marker(
"hg",
FixtureProvider::Hg,
Some(format!("{}", Color::Green.bold().paint("test "))),
)
}
#[test]
fn detect_hg_alias_mercurial() -> io::Result<()> {
with_marker(
"mercurial",
FixtureProvider::Hg,
Some(format!("{}", Color::Green.bold().paint("test "))),
)
}
#[test]
fn detect_pijul() -> io::Result<()> {
with_marker(
"pijul",
FixtureProvider::Pijul,
Some(format!("{}", Color::Green.bold().paint("test "))),
)
}
#[test]
fn invalid_vcs_is_none() -> io::Result<()> {
with_marker("does_not_exists", FixtureProvider::Fossil, None)
}
#[track_caller]
fn with_marker(
vcs_name: &'static str,
fixture: FixtureProvider,
expected: Option<String>,
) -> io::Result<()> {
let repo_dir = match fixture {
// Custom handling of Mercurial because we only care to detect the repo root, not run `hg` commands
FixtureProvider::Hg => {
let repo_dir = tempfile::tempdir()?;
std::fs::create_dir(repo_dir.path().join(".hg"))?;
repo_dir
}
_ => fixture_repo(fixture)?,
};
let config = toml::toml! {
[vcs]
order = [vcs_name]
// Use `custom.test` for VCSes
fossil_modules = "${custom.test}"
git_modules = "${custom.test}"
hg_modules = "${custom.test}"
pijul_modules = "${custom.test}"
// Inserting the `custom.test` module to have something printed that we control
[custom.test]
command = "echo test"
when = true
};
let actual = ModuleRenderer::new("vcs")
.config(config)
.path(repo_dir.path())
.collect();
assert_eq!(actual, expected);
repo_dir.close()
}
}