1use std::path::{Path, PathBuf};
2
3use clap::builder::PossibleValuesParser;
4
5use crate::serde::args::{ArgType, CliArgsSet};
6
7#[derive(Debug, Clone, Copy)]
8pub enum OutputLocation<'a> {
9 File(&'a Path),
10 Folder(&'a Path),
11}
12
13#[derive(clap::Args, Debug)]
14#[group(multiple = false, required = true)]
15pub struct Output {
16 #[arg(short = 'o', long = "output-file")]
19 pub file: Option<PathBuf>,
20
21 #[arg(short = 'd', long = "output-folder")]
24 pub directory: Option<PathBuf>,
25}
26
27impl Output {
28 pub fn location(&self) -> OutputLocation<'_> {
29 match (&self.directory, &self.file) {
30 (Some(dir), None) => OutputLocation::Folder(dir),
31 (None, Some(file)) => OutputLocation::File(file),
32 (None, None) => panic!("got neither a file nor a directory; clap should prevent this"),
33 (Some(dir), Some(file)) => {
34 panic!("got both file '{file:?}' and directory '{dir:?}'; clap should prevent this")
35 }
36 }
37 }
38}
39
40#[derive(clap::Parser, Debug)]
41#[command(args_conflicts_with_subcommands = true, subcommand_negates_reqs = true)]
42pub struct StandardArgs {
43 #[command(subcommand)]
44 pub subcommand: Option<Command>,
45
46 #[arg(short, long, visible_alias("config-file"))]
48 pub config: Option<PathBuf>,
49
50 #[arg(num_args(1..), required=true)]
52 pub directories: Vec<PathBuf>,
53
54 #[arg(long, exclusive(true))]
55 pub completions: Option<String>,
56
57 #[command(flatten)]
58 pub output: Output,
59
60 #[arg(long, num_args=1..)]
72 pub target_os: Option<Vec<String>>,
73}
74
75#[derive(Debug, Clone, Copy, clap::Subcommand)]
76pub enum Command {
77 Completions {
79 shell: clap_complete::Shell,
81 },
82}
83
84pub fn add_lang_argument(command: clap::Command, languages: &[&'static str]) -> clap::Command {
87 let arg = clap::Arg::new("language")
88 .short('l')
89 .long("lang")
90 .value_name("LANGUAGE")
91 .value_parser(PossibleValuesParser::new(languages))
92 .action(clap::ArgAction::Set)
93 .help("the output language of generated types");
94
95 command.arg(match languages {
96 [] => panic!("need at least one language"),
97 [lang] => arg.required(false).default_value(lang),
98 _ => arg.required(true),
99 })
100}
101
102pub fn add_language_params_to_clap(
106 command: clap::Command,
107 language: &'static str,
108 args: &CliArgsSet,
109) -> clap::Command {
110 if let Some(arg) = command
111 .get_arguments()
112 .find(|arg| arg.get_id().as_str().starts_with(language))
113 {
114 panic!(
115 "existing argument {id:?} conflicts with language {language}",
116 id = arg.get_id().as_str(),
117 )
118 }
119
120 args.iter().fold(command, |command, spec| {
121 let arg = clap::Arg::new(spec.full_key.to_owned())
122 .long(spec.full_key.to_owned())
123 .required(false);
124
125 command.arg(match spec.arg_type {
126 ArgType::Bool => arg.action(clap::ArgAction::SetTrue),
127 ArgType::Value => arg.action(clap::ArgAction::Set).value_name(spec.key),
128 })
129 })
130}