1
0
mirror of https://github.com/Llewellynvdm/starship.git synced 2024-12-01 09:13:54 +00:00

feat(vlang): create module (#2577)

* Add V module

* Format

* Fix tests

* fix typo

* Update src/configs/v.rs

Co-authored-by: Dario Vladović <d.vladimyr@gmail.com>

* Update docs/config/README.md

Co-authored-by: Dario Vladović <d.vladimyr@gmail.com>

* Update docs/config/README.md

Co-authored-by: Dario Vladović <d.vladimyr@gmail.com>

* Update docs/config/README.md

Co-authored-by: Dario Vladović <d.vladimyr@gmail.com>

* Use blue bold

* v -> vlang

* change docs

* More vlang fixes

* add package support for v

* Update docs/config/README.md

Co-authored-by: Dario Vladović <d.vladimyr@gmail.com>

* use regex

* Update src/configs/mod.rs

Co-authored-by: David Knaack <davidkna@users.noreply.github.com>

* apply patch

* fix

Co-authored-by: Dario Vladović <d.vladimyr@gmail.com>
Co-authored-by: David Knaack <davidkna@users.noreply.github.com>
This commit is contained in:
Milo 2021-05-03 20:50:29 +01:00 committed by GitHub
parent dead06ba14
commit 48f913ec23
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 194 additions and 0 deletions

View File

@ -223,6 +223,7 @@ $rust\
$scala\ $scala\
$swift\ $swift\
$terraform\ $terraform\
$vlang\
$vagrant\ $vagrant\
$zig\ $zig\
$nix_shell\ $nix_shell\
@ -2022,6 +2023,7 @@ package, and shows its current version. The module currently supports `npm`, `ca
- [**helm**](https://helm.sh/docs/helm/helm_package/) - The `helm` chart version is extracted from the `Chart.yaml` present - [**helm**](https://helm.sh/docs/helm/helm_package/) - The `helm` chart version is extracted from the `Chart.yaml` present
- [**maven**](https://maven.apache.org/) - The `maven` package version is extracted from the `pom.xml` present - [**maven**](https://maven.apache.org/) - The `maven` package version is extracted from the `pom.xml` present
- [**meson**](https://mesonbuild.com/) - The `meson` package version is extracted from the `meson.build` present - [**meson**](https://mesonbuild.com/) - The `meson` package version is extracted from the `meson.build` present
- [**vlang**](https://vlang.io) - The `vlang` package version is extracted from the `v.mod` present
> ⚠️ The version being shown is that of the package whose source code is in your > ⚠️ The version being shown is that of the package whose source code is in your
> current directory, not your package manager. > current directory, not your package manager.
@ -2839,6 +2841,41 @@ By default the module will be shown if any of the following conditions are met:
format = "via [⍱ $version](bold white) " format = "via [⍱ $version](bold white) "
``` ```
## VLang
The `vlang` module shows you your currently installed version of V.
By default the module will be shown if any of the following conditions are met:
- The current directory contains a file with `.v` extension
- The current directory contains a `v.mod` file
### Options
| Option | Default | Description |
| ------------------- | ------------------------------------------------- | ----------------------------------------------- |
| `format` | `"via [$symbol($version )]($style)"` | The format for the module. |
| `symbol` | `"V "` | A format string representing the symbol of V |
| `detect_extensions` | `["v"]` | Which extensions should trigger this module. |
| `detect_files` | `["v.mod"]` | Which filenames should trigger this module. |
| `detect_folders` | `[]` | Which folders should trigger this module. |
| `style` | `"blue bold"` | The style for the module. |
| `disabled` | `false` | Disables the `vlang` module. |
### Variables
| Variable | Example | Description |
| -------- | -------- | ------------------------------------ |
| version | `v0.2` | The version of `v` |
| symbol | | Mirrors the value of option `symbol` |
| style\* | | Mirrors the value of option `style` |
### Example
```toml
# ~/.config/starship.toml
[v]
format = "via [V $version](blue bold) "
```
## VCSH ## VCSH
The `vcsh` module displays the current active [VCSH](https://github.com/RichiH/vcsh) repository. The `vcsh` module displays the current active [VCSH](https://github.com/RichiH/vcsh) repository.

View File

@ -59,6 +59,7 @@ pub mod swift;
pub mod terraform; pub mod terraform;
pub mod time; pub mod time;
pub mod username; pub mod username;
pub mod v;
pub mod vagrant; pub mod vagrant;
pub mod vcsh; pub mod vcsh;
pub mod zig; pub mod zig;
@ -128,6 +129,7 @@ pub struct FullConfig<'a> {
terraform: terraform::TerraformConfig<'a>, terraform: terraform::TerraformConfig<'a>,
time: time::TimeConfig<'a>, time: time::TimeConfig<'a>,
username: username::UsernameConfig<'a>, username: username::UsernameConfig<'a>,
vlang: v::VLangConfig<'a>,
vagrant: vagrant::VagrantConfig<'a>, vagrant: vagrant::VagrantConfig<'a>,
zig: zig::ZigConfig<'a>, zig: zig::ZigConfig<'a>,
custom: IndexMap<String, custom::CustomConfig<'a>>, custom: IndexMap<String, custom::CustomConfig<'a>>,
@ -196,6 +198,7 @@ impl<'a> Default for FullConfig<'a> {
time: Default::default(), time: Default::default(),
username: Default::default(), username: Default::default(),
vagrant: Default::default(), vagrant: Default::default(),
vlang: Default::default(),
zig: Default::default(), zig: Default::default(),
custom: Default::default(), custom: Default::default(),
} }

View File

@ -58,6 +58,7 @@ pub const PROMPT_ORDER: &[&str] = &[
"scala", "scala",
"swift", "swift",
"terraform", "terraform",
"vlang",
"vagrant", "vagrant",
"zig", "zig",
// ↑ Toolchain version modules ↑ // ↑ Toolchain version modules ↑

29
src/configs/v.rs Normal file
View File

@ -0,0 +1,29 @@
use crate::config::ModuleConfig;
use serde::Serialize;
use starship_module_config_derive::ModuleConfig;
#[derive(Clone, ModuleConfig, Serialize)]
pub struct VLangConfig<'a> {
pub format: &'a str,
pub symbol: &'a str,
pub style: &'a str,
pub disabled: bool,
pub detect_extensions: Vec<&'a str>,
pub detect_files: Vec<&'a str>,
pub detect_folders: Vec<&'a str>,
}
impl<'a> Default for VLangConfig<'a> {
fn default() -> Self {
VLangConfig {
format: "via [$symbol($version )]($style)",
symbol: "V ",
style: "blue bold",
disabled: false,
detect_extensions: vec!["v"],
detect_files: vec!["v.mod"],
detect_folders: vec![],
}
}
}

View File

@ -67,6 +67,7 @@ pub const ALL_MODULES: &[&str] = &[
"username", "username",
"vcsh", "vcsh",
"vagrant", "vagrant",
"vlang",
"zig", "zig",
]; ];

View File

@ -57,6 +57,7 @@ mod username;
mod utils; mod utils;
mod vagrant; mod vagrant;
mod vcsh; mod vcsh;
mod vlang;
mod zig; mod zig;
#[cfg(feature = "battery")] #[cfg(feature = "battery")]
@ -130,6 +131,7 @@ pub fn handle<'a>(module: &str, context: &'a Context) -> Option<Module<'a>> {
"time" => time::module(context), "time" => time::module(context),
"crystal" => crystal::module(context), "crystal" => crystal::module(context),
"username" => username::module(context), "username" => username::module(context),
"vlang" => vlang::module(context),
"vagrant" => vagrant::module(context), "vagrant" => vagrant::module(context),
"vcsh" => vcsh::module(context), "vcsh" => vcsh::module(context),
"zig" => zig::module(context), "zig" => zig::module(context),
@ -210,6 +212,7 @@ pub fn description(module: &str) -> &'static str {
"terraform" => "The currently selected terraform workspace and version", "terraform" => "The currently selected terraform workspace and version",
"time" => "The current local time", "time" => "The current local time",
"username" => "The active user's username", "username" => "The active user's username",
"vlang" => "The currently installed version of V",
"vagrant" => "The currently installed version of Vagrant", "vagrant" => "The currently installed version of Vagrant",
"vcsh" => "The currently active VCSH repository", "vcsh" => "The currently active VCSH repository",
"zig" => "The currently installed version of Zig", "zig" => "The currently installed version of Zig",

View File

@ -54,6 +54,13 @@ fn extract_cargo_version(file_contents: &str) -> Option<String> {
Some(formatted_version) Some(formatted_version)
} }
fn extract_vlang_version(file_contents: &str) -> Option<String> {
let re = Regex::new(r"(?m)^\s*version\s*:\s*'(?P<version>[^']+)'").unwrap();
let caps = re.captures(file_contents)?;
let formatted_version = format_version(&caps["version"]);
Some(formatted_version)
}
fn extract_package_version(file_contents: &str, display_private: bool) -> Option<String> { fn extract_package_version(file_contents: &str, display_private: bool) -> Option<String> {
let package_json: json::Value = json::from_str(file_contents).ok()?; let package_json: json::Value = json::from_str(file_contents).ok()?;
@ -198,6 +205,8 @@ fn get_package_version(base_dir: &Path, config: &PackageConfig) -> Option<String
extract_maven_version(&pom_file) extract_maven_version(&pom_file)
} else if let Ok(meson_build) = utils::read_file(base_dir.join("meson.build")) { } else if let Ok(meson_build) = utils::read_file(base_dir.join("meson.build")) {
extract_meson_version(&meson_build) extract_meson_version(&meson_build)
} else if let Ok(vlang_mod) = utils::read_file(base_dir.join("v.mod")) {
extract_vlang_version(&vlang_mod)
} else { } else {
None None
} }
@ -818,6 +827,21 @@ end";
project_dir.close() project_dir.close()
} }
#[test]
fn test_extract_vlang_version() -> io::Result<()> {
let config_name = "v.mod";
let config_content = "
Module {
name: 'starship',
author: 'matchai',
version: '1.2.3'
}";
let project_dir = create_project_dir()?;
fill_config(&project_dir, config_name, Some(&config_content))?;
expect_output(&project_dir, Some("v1.2.3"), None);
project_dir.close()
}
fn create_project_dir() -> io::Result<TempDir> { fn create_project_dir() -> io::Result<TempDir> {
tempfile::tempdir() tempfile::tempdir()
} }

92
src/modules/vlang.rs Normal file
View File

@ -0,0 +1,92 @@
use super::{Context, Module, RootModuleConfig};
use crate::configs::v::VLangConfig;
use crate::formatter::StringFormatter;
/// Creates a module with the current V version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("vlang");
let config = VLangConfig::try_load(module.config);
let is_v_project = context
.try_begin_scan()?
.set_extensions(&config.detect_extensions)
.is_match();
if !is_v_project {
return None;
}
let parsed = StringFormatter::new(config.format).and_then(|formatter| {
formatter
.map_meta(|var, _| match var {
"symbol" => Some(config.symbol),
_ => None,
})
.map_style(|variable| match variable {
"style" => Some(Ok(config.style)),
_ => None,
})
.map(|variable| match variable {
"version" => context
.exec_cmd("v", &["version"])
.and_then(|output| parse_v_version(output.stdout.trim()))
.map(Ok),
_ => None,
})
.parse(None)
});
module.set_segments(match parsed {
Ok(segments) => segments,
Err(error) => {
log::warn!("Error in module `vlang`:\n{}", error);
return None;
}
});
Some(module)
}
fn parse_v_version(v_version: &str) -> Option<String> {
let version = v_version
// split into ["V", "0.2", "30c0659"]
.split_whitespace()
// return "0.2"
.nth(1)?;
Some(format!("v{}", version))
}
#[cfg(test)]
mod tests {
use super::parse_v_version;
use crate::test::ModuleRenderer;
use ansi_term::Color;
use std::fs::File;
use std::io;
#[test]
fn test_parse_v_version() {
const OUTPUT: &str = "V 0.2 30c0659\n";
assert_eq!(parse_v_version(OUTPUT.trim()), Some("v0.2".to_string()))
}
#[test]
fn folder_without_v_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
let actual = ModuleRenderer::new("vlang").path(dir.path()).collect();
let expected = None;
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn folder_with_v_files() -> io::Result<()> {
let dir = tempfile::tempdir()?;
File::create(dir.path().join("hello.v"))?.sync_all()?;
let actual = ModuleRenderer::new("vlang").path(dir.path()).collect();
let expected = Some(format!("via {}", Color::Blue.bold().paint("V v0.2 ")));
assert_eq!(expected, actual);
dir.close()
}
}

View File

@ -188,6 +188,10 @@ Target: x86_64-apple-darwin19.4.0\n",
stdout: String::from("Vagrant 2.2.10\n"), stdout: String::from("Vagrant 2.2.10\n"),
stderr: String::default(), stderr: String::default(),
}), }),
"v version" => Some(CommandOutput {
stdout: String::from("V 0.2 30c0659"),
stderr: String::default()
}),
"zig version" => Some(CommandOutput { "zig version" => Some(CommandOutput {
stdout: String::from("0.6.0\n"), stdout: String::from("0.6.0\n"),
stderr: String::default(), stderr: String::default(),