|
| 1 | +use clap::{Parser, Subcommand}; |
| 2 | +use colored_json::ToColoredJson; |
| 3 | +use iab_gpp::sections::SectionId; |
| 4 | +use iab_gpp::v1::GPPString; |
| 5 | +use num_traits::cast::FromPrimitive; |
| 6 | +use num_traits::ToPrimitive; |
| 7 | +use std::str::FromStr; |
| 8 | + |
| 9 | +#[derive(Parser)] |
| 10 | +#[command(version, about, long_about = None)] |
| 11 | +struct Cli { |
| 12 | + #[command(subcommand)] |
| 13 | + cmd: Commands, |
| 14 | +} |
| 15 | + |
| 16 | +#[derive(Subcommand)] |
| 17 | +enum Commands { |
| 18 | + /// Parse a GPP string and display it in the console |
| 19 | + Parse { |
| 20 | + /// GPP string to parse |
| 21 | + gpp_string: String, |
| 22 | + /// Section ID to parse |
| 23 | + #[arg(short, long)] |
| 24 | + section_id: Option<u32>, |
| 25 | + }, |
| 26 | + /// List all sections |
| 27 | + List { |
| 28 | + /// GPP string to parse |
| 29 | + gpp_string: String, |
| 30 | + }, |
| 31 | +} |
| 32 | + |
| 33 | +fn main() { |
| 34 | + let args = Cli::parse(); |
| 35 | + |
| 36 | + let e = match args.cmd { |
| 37 | + Commands::Parse { |
| 38 | + gpp_string, |
| 39 | + section_id: None, |
| 40 | + } => parse_gpp_string(&gpp_string), |
| 41 | + Commands::Parse { |
| 42 | + gpp_string, |
| 43 | + section_id: Some(id), |
| 44 | + } => parse_gpp_string_section(&gpp_string, id), |
| 45 | + Commands::List { gpp_string } => list_sections(&gpp_string), |
| 46 | + }; |
| 47 | + |
| 48 | + if let Err(e) = e { |
| 49 | + eprintln!("{}", e); |
| 50 | + std::process::exit(1); |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +fn parse_gpp_string(s: &str) -> Result<(), Box<dyn std::error::Error>> { |
| 55 | + let gpp_str = GPPString::from_str(s)?; |
| 56 | + |
| 57 | + let sections = gpp_str |
| 58 | + .decode_all_sections() |
| 59 | + .into_iter() |
| 60 | + .collect::<Result<Vec<_>, _>>()?; |
| 61 | + |
| 62 | + println!( |
| 63 | + "{}", |
| 64 | + serde_json::to_string_pretty(§ions)?.to_colored_json_auto()? |
| 65 | + ); |
| 66 | + |
| 67 | + Ok(()) |
| 68 | +} |
| 69 | + |
| 70 | +fn parse_gpp_string_section(s: &str, id: u32) -> Result<(), Box<dyn std::error::Error>> { |
| 71 | + let gpp_str = GPPString::from_str(s)?; |
| 72 | + |
| 73 | + let section = gpp_str.decode_section(SectionId::from_u32(id).ok_or("Invalid ID")?)?; |
| 74 | + |
| 75 | + println!( |
| 76 | + "{}", |
| 77 | + serde_json::to_string_pretty(§ion)?.to_colored_json_auto()? |
| 78 | + ); |
| 79 | + |
| 80 | + Ok(()) |
| 81 | +} |
| 82 | + |
| 83 | +fn list_sections(s: &str) -> Result<(), Box<dyn std::error::Error>> { |
| 84 | + let gpp_str = GPPString::from_str(s)?; |
| 85 | + |
| 86 | + for s in gpp_str.section_ids() { |
| 87 | + println!("{}\t{:?}", s.to_u32().unwrap_or_default(), s); |
| 88 | + } |
| 89 | + |
| 90 | + Ok(()) |
| 91 | +} |
0 commit comments