From 032009888d0bed4d104d22c12f91d778de507561 Mon Sep 17 00:00:00 2001 From: Josh Nichols Date: Tue, 26 Nov 2024 16:08:43 -0500 Subject: [PATCH] Add support for --json to match ruby codeownership cli --- src/cli.rs | 48 +++++++++++++++++++++++++++++++++++++++--------- src/project.rs | 3 ++- 2 files changed, 41 insertions(+), 10 deletions(-) diff --git a/src/cli.rs b/src/cli.rs index f680b2d..9b78c35 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -16,7 +16,11 @@ use std::{ #[derive(Subcommand, Debug)] enum Command { #[clap(about = "Finds the owner of a given file.", visible_alias = "f")] - ForFile { name: String }, + ForFile { + name: String, + #[arg(long, help = "Output result as JSON")] + json: bool, + }, #[clap(about = "Finds code ownership information for a given team ", visible_alias = "t")] ForTeam { name: String }, @@ -124,15 +128,41 @@ pub fn cli() -> Result<(), Error> { std::fs::write(codeowners_file_path, ownership.generate_file()).change_context(Error::Io)?; ownership.validate().change_context(Error::ValidationFailed)? } - Command::ForFile { name } => { + Command::ForFile { name, json } => { let file_owners = ownership.for_file(&name).change_context(Error::Io)?; - match file_owners.len() { - 0 => println!("{}", FileOwner::default()), - 1 => println!("{}", file_owners[0]), - _ => { - println!("Error: file is owned by multiple teams!"); - for file_owner in file_owners { - println!("\n{}", file_owner); + if json { + let output = match file_owners.len() { + 0 => serde_json::json!({ + "team_name": null, + "team_yml": null + }), + 1 => { + let owner = &file_owners[0]; + serde_json::json!({ + "team_name": owner.team.name, + "team_yml": owner.team_config_file_path + }) + } + _ => serde_json::json!({ + "error": "Multiple owners", + "owners": file_owners.iter().map(|o| { + serde_json::json!({ + "team_name": o.team, + "team_yml": o.team_config_file_path + }) + }).collect::>() + }), + }; + println!("{}", serde_json::to_string(&output).unwrap()); + } else { + match file_owners.len() { + 0 => println!("{}", FileOwner::default()), + 1 => println!("{}", file_owners[0]), + _ => { + println!("Error: file is owned by multiple teams!"); + for file_owner in file_owners { + println!("\n{}", file_owner); + } } } } diff --git a/src/project.rs b/src/project.rs index 0ef1728..659ecd5 100644 --- a/src/project.rs +++ b/src/project.rs @@ -6,6 +6,7 @@ use std::{ }; use error_stack::{Context, Result, ResultExt}; +use serde::Serialize; pub struct Project { pub base_path: PathBuf, @@ -29,7 +30,7 @@ pub struct ProjectFile { pub path: PathBuf, } -#[derive(Clone, Debug, Default)] +#[derive(Clone, Debug, Default, Serialize)] pub struct Team { pub path: PathBuf, pub name: String,