feat: add username to Pulumi module (#3428)

* feat: add username to Pulumi module

* run dprint fmt
This commit is contained in:
Aaron Friel 2022-01-25 08:40:44 -08:00 committed by GitHub
parent f4ddaa0d60
commit 568d057032
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 130 additions and 13 deletions

View File

@ -2424,7 +2424,7 @@ format = "via [🔹 $version](147 bold) "
## Pulumi ## Pulumi
The `pulumi` module shows the currently selected [Pulumi Stack](https://www.pulumi.com/docs/intro/concepts/stack/) and version. The `pulumi` module shows the current username, selected [Pulumi Stack](https://www.pulumi.com/docs/intro/concepts/stack/), and version.
::: tip ::: tip
@ -2441,8 +2441,8 @@ By default the module will be shown if any of the following conditions are met:
### Options ### Options
| Option | Default | Description | | Option | Default | Description |
| ---------------- | -------------------------------- | ------------------------------------------------------------------------- | | ---------------- | -------------------------------------------- | ------------------------------------------------------------------------- |
| `format` | `"via [$symbol$stack]($style) "` | The format string for the module. | | `format` | `"via [$symbol($username@)$stack]($style) "` | The format string for the module. |
| `version_format` | `"v${raw}"` | The version format. Available vars are `raw`, `major`, `minor`, & `patch` | | `version_format` | `"v${raw}"` | The version format. Available vars are `raw`, `major`, `minor`, & `patch` |
| `symbol` | `" "` | A format string shown before the Pulumi stack. | | `symbol` | `" "` | A format string shown before the Pulumi stack. |
| `style` | `"bold 5"` | The style for the module. | | `style` | `"bold 5"` | The style for the module. |
@ -2454,6 +2454,7 @@ By default the module will be shown if any of the following conditions are met:
| -------- | ---------- | ------------------------------------ | | -------- | ---------- | ------------------------------------ |
| version | `v0.12.24` | The version of `pulumi` | | version | `v0.12.24` | The version of `pulumi` |
| stack | `dev` | The current Pulumi stack | | stack | `dev` | The current Pulumi stack |
| username | `alice` | The current Pulumi username |
| symbol | | Mirrors the value of option `symbol` | | symbol | | Mirrors the value of option `symbol` |
| style\* | | Mirrors the value of option `style` | | style\* | | Mirrors the value of option `style` |

View File

@ -15,7 +15,7 @@ pub struct PulumiConfig<'a> {
impl<'a> Default for PulumiConfig<'a> { impl<'a> Default for PulumiConfig<'a> {
fn default() -> Self { fn default() -> Self {
PulumiConfig { PulumiConfig {
format: "via [$symbol$stack]($style) ", format: "via [$symbol($username@)$stack]($style) ",
version_format: "v${raw}", version_format: "v${raw}",
symbol: "", symbol: "",
style: "bold 5", style: "bold 5",

View File

@ -222,7 +222,7 @@ pub fn description(module: &str) -> &'static str {
"package" => "The package version of the current directory's project", "package" => "The package version of the current directory's project",
"perl" => "The currently installed version of Perl", "perl" => "The currently installed version of Perl",
"php" => "The currently installed version of PHP", "php" => "The currently installed version of PHP",
"pulumi" => "The current stack and installed version of Pulumi", "pulumi" => "The current username, stack, and installed version of Pulumi",
"purescript" => "The currently installed version of PureScript", "purescript" => "The currently installed version of PureScript",
"python" => "The currently installed version of Python", "python" => "The currently installed version of Python",
"red" => "The currently installed version of Red", "red" => "The currently installed version of Red",

View File

@ -1,8 +1,10 @@
#![warn(missing_docs)] #![warn(missing_docs)]
use serde::Deserialize;
use sha1::{Digest, Sha1}; use sha1::{Digest, Sha1};
use std::collections::HashMap;
use std::ffi::OsStr; use std::ffi::OsStr;
use std::fs::File; use std::fs::File;
use std::io::Read; use std::io::{BufReader, Read};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::str::FromStr; use std::str::FromStr;
use yaml_rust::{Yaml, YamlLoader}; use yaml_rust::{Yaml, YamlLoader};
@ -13,6 +15,17 @@ use crate::formatter::{StringFormatter, VersionFormatter};
static PULUMI_HOME: &str = "PULUMI_HOME"; static PULUMI_HOME: &str = "PULUMI_HOME";
#[derive(Deserialize)]
struct Credentials {
current: Option<String>,
accounts: Option<HashMap<String, Account>>,
}
#[derive(Deserialize)]
struct Account {
username: Option<String>,
}
/// Creates a module with the current Pulumi version and stack name. /// Creates a module with the current Pulumi version and stack name.
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> { pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("pulumi"); let mut module = context.new_module("pulumi");
@ -40,6 +53,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
) )
} }
.map(Ok), .map(Ok),
"username" => get_pulumi_username(context).map(Ok),
"stack" => stack_name(&project_file, context).map(Ok), "stack" => stack_name(&project_file, context).map(Ok),
_ => None, _ => None,
}) })
@ -163,6 +177,21 @@ fn pulumi_home_dir(context: &Context) -> Option<PathBuf> {
} }
} }
fn get_pulumi_username(context: &Context) -> Option<String> {
let home_dir = pulumi_home_dir(context)?;
let creds_path = home_dir.join("credentials.json");
let file = File::open(creds_path).ok()?;
let reader = BufReader::new(file);
// Read the JSON contents of the file as an instance of `User`.
let creds: Credentials = serde_json::from_reader(reader).ok()?;
let current_api_provider = creds.current?;
creds.accounts?.remove(&current_api_provider)?.username
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use std::io; use std::io;
@ -259,16 +288,103 @@ mod tests {
), ),
)?; )?;
workspace.sync_all()?; workspace.sync_all()?;
let credential_path = root.join(".pulumi");
let _ = std::fs::create_dir_all(&credential_path)?;
let credential_path = &credential_path.join("credentials.json");
let mut credential = File::create(&credential_path)?;
serde_json::to_writer_pretty(
&mut credential,
&serde_json::json!(
{
"current": "https://api.example.com",
"accessTokens": {
"https://api.example.com": "redacted",
"https://api.pulumi.com": "redacted"
},
"accounts": {
"https://api.example.com": {
"accessToken": "redacted",
"username": "test-user",
"lastValidatedAt": "2022-01-12T00:00:00.000000000-08:00"
}
}
}
),
)?;
credential.sync_all()?;
let rendered = ModuleRenderer::new("pulumi") let rendered = ModuleRenderer::new("pulumi")
.path(root.clone()) .path(root.clone())
.logical_path(root.clone()) .logical_path(root.clone())
.config(toml::toml! { .config(toml::toml! {
[pulumi] [pulumi]
format = "in [$symbol($stack)]($style) " format = "via [$symbol($username@)$stack]($style) "
}) })
.env("HOME", root.to_str().unwrap()) .env("HOME", root.to_str().unwrap())
.collect(); .collect();
let expected = format!("in {} ", Color::Fixed(5).bold().paint(" launch")); let expected = format!(
"via {} ",
Color::Fixed(5).bold().paint(" test-user@launch")
);
assert_eq!(expected, rendered.expect("a result"));
dir.close()?;
Ok(())
}
#[test]
/// This test confirms a render when the account information incomplete, i.e.: no username for
/// the current API.
fn partial_login() -> io::Result<()> {
use io::Write;
let dir = tempfile::tempdir()?;
let root = std::fs::canonicalize(dir.path())?;
let mut yaml = File::create(root.join("Pulumi.yml"))?;
yaml.write_all("name: starship\nruntime: nodejs\ndescription: A thing\n".as_bytes())?;
yaml.sync_all()?;
let workspace_path = root.join(".pulumi").join("workspaces");
let _ = std::fs::create_dir_all(&workspace_path)?;
let workspace_path = &workspace_path.join("starship-test-workspace.json");
let mut workspace = File::create(&workspace_path)?;
serde_json::to_writer_pretty(
&mut workspace,
&serde_json::json!(
{
"stack": "launch"
}
),
)?;
workspace.sync_all()?;
let credential_path = root.join(".pulumi");
let _ = std::fs::create_dir_all(&credential_path)?;
let credential_path = &credential_path.join("starship-test-credential.json");
let mut credential = File::create(&credential_path)?;
serde_json::to_writer_pretty(
&mut credential,
&serde_json::json!(
{
"current": "https://api.example.com",
"accessTokens": {
"https://api.example.com": "redacted",
"https://api.pulumi.com": "redacted"
},
"accounts": {
}
}
),
)?;
credential.sync_all()?;
let rendered = ModuleRenderer::new("pulumi")
.path(root.clone())
.logical_path(root.clone())
.config(toml::toml! {
[pulumi]
format = "via [$symbol($username@)$stack]($style) "
})
.env("HOME", root.to_str().unwrap())
.collect();
let expected = format!("via {} ", Color::Fixed(5).bold().paint(" launch"));
assert_eq!(expected, rendered.expect("a result")); assert_eq!(expected, rendered.expect("a result"));
dir.close()?; dir.close()?;
Ok(()) Ok(())