Skip to content

Commit

Permalink
feat: allow config ls to return JSON (#2775)
Browse files Browse the repository at this point in the history
  • Loading branch information
roele authored Oct 17, 2024
1 parent 6996e33 commit 1bd50a8
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 0 deletions.
45 changes: 45 additions & 0 deletions src/cli/config/ls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,23 @@ pub struct ConfigLs {
/// Do not print table header
#[clap(long, alias = "no-headers", verbatim_doc_comment)]
pub no_header: bool,

/// Output in JSON format
#[clap(short = 'J', long, verbatim_doc_comment)]
pub json: bool,
}

impl ConfigLs {
pub fn run(self) -> Result<()> {
if self.json {
self.display_json()?;
} else {
self.display()?;
}
Ok(())
}

fn display(&self) -> Result<()> {
let rows = CONFIG
.config_files
.values()
Expand All @@ -30,7 +43,33 @@ impl ConfigLs {
table::default_style(&mut table, self.no_header);
table.with(Modify::new(Columns::last()).with(Width::truncate(40).suffix("…")));
miseprintln!("{table}");
Ok(())
}

fn display_json(&self) -> Result<()> {
let array_items = CONFIG
.config_files
.values()
.map(|cf| {
let c: &dyn ConfigFile = cf.as_ref();
let mut item = serde_json::Map::new();
item.insert(
"path".to_string(),
serde_json::Value::String(c.get_path().to_string_lossy().to_string()),
);
let plugins = c
.to_tool_request_set()
.unwrap()
.list_plugins()
.into_iter()
.map(|s| serde_json::Value::String(s.to_string()))
.collect::<Vec<serde_json::Value>>();
item.insert("plugins".to_string(), serde_json::Value::Array(plugins));

item
})
.collect::<serde_json::Value>();
miseprintln!("{}", serde_json::to_string_pretty(&array_items)?);
Ok(())
}
}
Expand Down Expand Up @@ -80,4 +119,10 @@ mod tests {
~/config/config.toml (none)
"###);
}

#[test]
fn test_config_ls_json() {
reset();
assert_cli_snapshot!("cfg", "--json");
}
}
5 changes: 5 additions & 0 deletions src/cli/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ pub struct Config {
/// Do not print table header
#[clap(long, alias = "no-headers", verbatim_doc_comment)]
no_header: bool,

/// Output in JSON format
#[clap(short = 'J', long, verbatim_doc_comment)]
pub json: bool,
}

#[derive(Debug, Subcommand)]
Expand All @@ -44,6 +48,7 @@ impl Config {
pub fn run(self) -> Result<()> {
let cmd = self.command.unwrap_or(Commands::Ls(ls::ConfigLs {
no_header: self.no_header,
json: self.json,
}));

cmd.run()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
---
source: src/cli/config/ls.rs
expression: output
---
[
{
"path": "~/cwd/.test-tool-versions",
"plugins": [
"tiny"
]
},
{
"path": "~/.test-tool-versions",
"plugins": [
"tiny",
"dummy"
]
},
{
"path": "~/config/config.toml",
"plugins": []
}
]

0 comments on commit 1bd50a8

Please sign in to comment.