typeshare_engine/
args.rs

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    /// File to write output to. mtime will be preserved if the file contents
17    /// don't change
18    #[arg(short = 'o', long = "output-file")]
19    pub file: Option<PathBuf>,
20
21    /// Folder to write output to. mtime will be preserved if the file contents
22    /// don't change
23    #[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    /// Path to the config file for this typeshare
47    #[arg(short, long, visible_alias("config-file"))]
48    pub config: Option<PathBuf>,
49
50    /// The directories within which to recursively find and process rust files
51    #[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    /// If given, only fields / types / variants matching at least one of these
61    /// OSes (per `cfg(target_os)`) will be emitted. If any `--target-os`
62    /// arguments are passed, they will override ALL target OSes passed via
63    /// a config file.
64    ///
65    /// Generally, typeshare will err on the side of generating things. For
66    /// instance, given `--target-os=ios` and `cfg(any(target_os="android", test))`,
67    /// it WILL generate a type, because that type does exist on iOS in test
68    /// mode: there exists a configuration where that type exists on iOS.
69    ///
70    /// In the future typeshare may be able to consider other cfgs.
71    #[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    /// Generate shell completions
78    Completions {
79        /// The shell to generate the completions for
80        shell: clap_complete::Shell,
81    },
82}
83
84/// Add a `--lang` argument to the command. This argument will be optional if
85/// there is only one language
86pub 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
102/// Given a CliArgsSet for a language, use the name of the language and
103/// information about its configuration to populate a clap command with
104/// args specific to that language
105pub 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}