Merge branch 'master' into conditional-style

This commit is contained in:
Filip Bachul 2023-06-02 19:58:39 +02:00
commit 54b0092f9f
9 changed files with 246 additions and 36 deletions

View File

@ -656,6 +656,7 @@
],
"disabled": false,
"format": "via [$symbol($version )]($style)",
"not_capable_style": "bold red",
"style": "bold cyan",
"symbol": "🐹 ",
"version_format": "v${raw}"
@ -3454,6 +3455,10 @@
"default": false,
"type": "boolean"
},
"not_capable_style": {
"default": "bold red",
"type": "string"
},
"detect_extensions": {
"default": [
"go"

View File

@ -7,4 +7,4 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: crate-ci/typos@v1.14.11
- uses: crate-ci/typos@v1.14.12

4
Cargo.lock generated
View File

@ -337,9 +337,9 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "chrono"
version = "0.4.25"
version = "0.4.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fdbc37d37da9e5bce8173f3a41b71d9bf3c674deebbaceacd0ebdabde76efb03"
checksum = "ec837a71355b28f6556dbd569b37b3f363091c0bd4b2e735674521b4c5fd9bc5"
dependencies = [
"android-tzdata",
"iana-time-zone",

View File

@ -42,7 +42,7 @@ gix-max-perf = ["gix-features/zlib-ng", "gix/fast-sha1"]
gix-faster = ["gix-features/zlib-stock", "gix/fast-sha1"]
[dependencies]
chrono = { version = "0.4.25", default-features = false, features = ["clock", "std", "wasmbind"] }
chrono = { version = "0.4.26", default-features = false, features = ["clock", "std", "wasmbind"] }
clap = { version = "4.3.0", features = ["derive", "cargo", "unicode"] }
clap_complete = "4.3.0"
dirs-next = "2.0.0"

View File

@ -4,7 +4,6 @@ use std::io::Write;
use shadow_rs::SdResult;
fn main() -> SdResult<()> {
shadow_rs::new().map_err(|err| err.to_string())?;
shadow_rs::new_hook(gen_presets_hook)?;
#[cfg(windows)]

View File

@ -1973,7 +1973,7 @@ By default the module will be shown if any of the following conditions are met:
### Options
| Option | Default | Description |
| ------------------- | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- |
| ------------------- | ----------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| `format` | `'via [$symbol($version )]($style)'` | The format for the module. |
| `version_format` | `'v${raw}'` | The version format. Available vars are `raw`, `major`, `minor`, & `patch` |
| `symbol` | `'🐹 '` | A format string representing the symbol of Go. |
@ -1981,13 +1981,15 @@ By default the module will be shown if any of the following conditions are met:
| `detect_files` | `['go.mod', 'go.sum', 'go.work', 'glide.yaml', 'Gopkg.yml', 'Gopkg.lock', '.go-version']` | Which filenames should trigger this module. |
| `detect_folders` | `['Godeps']` | Which folders should trigger this module. |
| `style` | `'bold cyan'` | The style for the module. |
| `not_capable_style` | `'bold red'` | The style for the module when the go directive in the go.mod file does not match the installed Go version. |
| `disabled` | `false` | Disables the `golang` module. |
### Variables
| Variable | Example | Description |
| -------- | --------- | ------------------------------------ |
| ----------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| version | `v1.12.1` | The version of `go` |
| mod_version | `1.16` | `go` version requirement as set in the go directive of `go.mod`. Will only show if the version requirement does not match the `go` version. |
| symbol | | Mirrors the value of option `symbol` |
| style\* | | Mirrors the value of option `style` |
@ -2002,6 +2004,15 @@ By default the module will be shown if any of the following conditions are met:
format = 'via [🏎💨 $version](bold cyan) '
```
### Using `mod_version`
```toml
# ~/.config/starship.toml
[golang]
format = 'via [$symbol($version )($mod_version )]($style)'
```
## Guix-shell
The `guix_shell` module shows the [guix-shell](https://guix.gnu.org/manual/devel/en/html_node/Invoking-guix-shell.html) environment.
@ -2849,8 +2860,9 @@ By default the module will be shown if any of the following conditions are met:
### Variables
| Variable | Example | Description |
| -------- | ---------- | ------------------------------------ |
| --------------- | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| version | `v13.12.0` | The version of `node` |
| engines_version | `>=12.0.0` | `node` version requirement as set in the engines property of `package.json`. Will only show if the version requirement does not match the `node` version. |
| symbol | | Mirrors the value of option `symbol` |
| style\* | | Mirrors the value of option `style` |

View File

@ -13,6 +13,7 @@ pub struct GoConfig<'a> {
pub symbol: &'a str,
pub style: &'a str,
pub disabled: bool,
pub not_capable_style: &'a str,
pub detect_extensions: Vec<&'a str>,
pub detect_files: Vec<&'a str>,
pub detect_folders: Vec<&'a str>,
@ -26,6 +27,7 @@ impl<'a> Default for GoConfig<'a> {
symbol: "🐹 ",
style: "bold cyan",
disabled: false,
not_capable_style: "bold red",
detect_extensions: vec!["go"],
detect_files: vec![
"go.mod",

View File

@ -4,6 +4,12 @@ use crate::configs::go::GoConfig;
use crate::formatter::StringFormatter;
use crate::formatter::VersionFormatter;
use once_cell::sync::Lazy;
use regex::Regex;
use semver::Version;
use semver::VersionReq;
use std::ops::Deref;
/// Creates a module with the current Go version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("golang");
@ -19,6 +25,10 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
return None;
}
let golang_version =
Lazy::new(|| parse_go_version(&context.exec_cmd("go", &["version"])?.stdout));
let mod_version = Lazy::new(|| get_go_mod_version(context));
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|var, _| match var {
@ -26,21 +36,36 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
"style" => {
let in_mod_range =
check_go_version(golang_version.as_deref(), mod_version.as_deref());
if in_mod_range {
Some(Ok(config.style))
} else {
Some(Ok(config.not_capable_style))
}
}
_ => None,
})
.map(|variable| match variable {
"version" => {
let golang_version =
parse_go_version(&context.exec_cmd("go", &["version"])?.stdout)?;
let go_ver = golang_version.deref().as_ref()?;
VersionFormatter::format_module_version(
module.get_name(),
&golang_version,
go_ver,
config.version_format,
)
.map(Ok)
}
"mod_version" => {
let in_mod_range =
check_go_version(golang_version.as_deref(), mod_version.as_deref());
let mod_ver = mod_version.as_deref()?.to_string();
(!in_mod_range).then_some(Ok(mod_ver))
}
_ => None,
})
.parse(None, Some(context))
@ -74,6 +99,32 @@ fn parse_go_version(go_stdout: &str) -> Option<String> {
Some(version.to_string())
}
fn get_go_mod_version(context: &Context) -> Option<String> {
let mod_str = context.read_file_from_pwd("go.mod")?;
let re = Regex::new(r"(?:go\s)(\d+(\.\d+)+)").unwrap();
if let Some(cap) = re.captures(&mod_str) {
let mod_ver = cap.get(1)?.as_str();
Some(mod_ver.to_string())
} else {
None
}
}
fn check_go_version(go_version: Option<&str>, mod_version: Option<&str>) -> bool {
let (Some(go_version), Some(mod_version)) = (go_version, mod_version) else {
return true;
};
let Ok(r) = VersionReq::parse(mod_version) else {
return true;
};
let Ok(v) = Version::parse(go_version) else {
return true;
};
r.matches(&v)
}
#[cfg(test)]
mod tests {
use super::*;
@ -81,6 +132,7 @@ mod tests {
use nu_ansi_term::Color;
use std::fs::{self, File};
use std::io;
use std::io::Write;
#[test]
fn folder_without_go_files() -> io::Result<()> {
@ -203,4 +255,53 @@ mod tests {
let input = "go version go1.12 darwin/amd64";
assert_eq!(parse_go_version(input), Some("1.12".to_string()));
}
#[test]
fn show_mod_version_if_not_matching_go_version() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let mut file = File::create(dir.path().join("go.mod"))?;
file.write_all(
b"package test\n\n
go 1.16",
)?;
file.sync_all()?;
let actual = ModuleRenderer::new("golang")
.path(dir.path())
.config(toml::toml! {
[golang]
format = "via [$symbol($version )($mod_version )]($style)"
})
.collect();
let expected = Some(format!(
"via {}",
Color::Red.bold().paint("🐹 v1.12.1 1.16 ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn hide_mod_version_when_it_matches_go_version() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let mut file = File::create(dir.path().join("go.mod"))?;
file.write_all(
b"package test\n\n
go 1.12",
)?;
file.sync_all()?;
let actual = ModuleRenderer::new("golang")
.path(dir.path())
.config(toml::toml! {
[golang]
format = "via [$symbol($version )($mod_version )]($style)"
})
.collect();
let expected = Some(format!("via {}", Color::Cyan.bold().paint("🐹 v1.12.1 ")));
assert_eq!(expected, actual);
dir.close()
}
}

View File

@ -35,6 +35,8 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
.exec_cmd("node", &["--version"])
.map(|cmd| cmd.stdout)
});
let engines_version = Lazy::new(|| get_engines_version(context));
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|var, _| match var {
@ -43,9 +45,11 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
})
.map_style(|variable| match variable {
"style" => {
let engines_version = get_engines_version(context);
let in_engines_range =
check_engines_version(nodejs_version.as_deref(), engines_version);
let in_engines_range = check_engines_version(
nodejs_version.as_deref(),
engines_version.as_deref(),
);
if in_engines_range {
Some(Ok(config.style))
} else {
@ -56,7 +60,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
})
.map(|variable| match variable {
"version" => {
let version = nodejs_version
let node_ver = nodejs_version
.deref()
.as_ref()?
.trim_start_matches('v')
@ -64,11 +68,20 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
VersionFormatter::format_module_version(
module.get_name(),
version,
node_ver,
config.version_format,
)
.map(Ok)
}
"engines_version" => {
let in_engines_range = check_engines_version(
nodejs_version.as_deref(),
engines_version.as_deref(),
);
let eng_ver = engines_version.as_deref()?.to_string();
(!in_engines_range).then_some(Ok(eng_ver))
}
_ => None,
})
.parse(None, Some(context))
@ -89,16 +102,19 @@ fn get_engines_version(context: &Context) -> Option<String> {
let json_str = context.read_file_from_pwd("package.json")?;
let package_json: json::Value = json::from_str(&json_str).ok()?;
let raw_version = package_json.get("engines")?.get("node")?.as_str()?;
Some(raw_version.to_string())
}
fn check_engines_version(nodejs_version: Option<&str>, engines_version: Option<String>) -> bool {
fn check_engines_version(nodejs_version: Option<&str>, engines_version: Option<&str>) -> bool {
let (Some(nodejs_version), Some(engines_version)) = (nodejs_version, engines_version) else {
return true;
};
let Ok(r) = VersionReq::parse(&engines_version) else {
let Ok(r) = VersionReq::parse(engines_version) else {
return true;
};
let re = Regex::new(r"\d+\.\d+\.\d+").unwrap();
let version = re
.captures(nodejs_version)
@ -106,6 +122,7 @@ fn check_engines_version(nodejs_version: Option<&str>, engines_version: Option<S
.get(0)
.unwrap()
.as_str();
let v = match Version::parse(version) {
Ok(v) => v,
Err(_e) => return true,
@ -269,6 +286,80 @@ mod tests {
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn show_expected_version_when_engines_does_not_match() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let mut file = File::create(dir.path().join("package.json"))?;
file.write_all(
b"{
\"engines\":{
\"node\":\"<=11.0.0\"
}
}",
)?;
file.sync_all()?;
let actual = ModuleRenderer::new("nodejs")
.path(dir.path())
.config(toml::toml! {
[nodejs]
format = "via [$symbol($version )($engines_version )]($style)"
})
.collect();
let expected = Some(format!(
"via {}",
Color::Red.bold().paint(" v12.0.0 <=11.0.0 ")
));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn do_not_show_expected_version_if_engines_match() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let mut file = File::create(dir.path().join("package.json"))?;
file.write_all(
b"{
\"engines\":{
\"node\":\">=12.0.0\"
}
}",
)?;
file.sync_all()?;
let actual = ModuleRenderer::new("nodejs")
.path(dir.path())
.config(toml::toml! [
[nodejs]
format = "via [$symbol($version )($engines_version )]($style)"
])
.collect();
let expected = Some(format!("via {}", Color::Green.bold().paint(" v12.0.0 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn do_not_show_expected_version_if_no_set_engines_version() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("package.json"))?.sync_all()?;
let actual = ModuleRenderer::new("nodejs")
.path(dir.path())
.config(toml::toml! {
[nodejs]
format = "via [$symbol($version )($engines_version )]($style)"
})
.collect();
let expected = Some(format!("via {}", Color::Green.bold().paint(" v12.0.0 ")));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn no_node_installed() -> io::Result<()> {
let dir = tempfile::tempdir()?;