Skip to main content

rocketmq_admin_cli/
rocketmq_cli.rs

1// Copyright 2023 The RocketMQ Rust Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::ffi::OsString;
16
17use clap::CommandFactory;
18use clap::Parser;
19use clap_complete::generate;
20use clap_complete::shells::Bash;
21use clap_complete::shells::Fish;
22use clap_complete::shells::Zsh;
23
24use crate::commands::CommandExecute;
25use crate::commands::Commands;
26
27#[derive(Parser)]
28#[command(name = "rocketmq-admin-cli")]
29#[command(about = "Rocketmq Rust admin commands", long_about = None, author="mxsm")]
30pub struct RocketMQCli {
31    #[arg(
32        long = "generate-completion",
33        value_name = "SHELL",
34        help = "Generate shell completion script (bash, zsh, fish)"
35    )]
36    completion: Option<String>,
37
38    #[command(subcommand)]
39    commands: Option<Commands>,
40}
41
42impl RocketMQCli {
43    pub fn parse_from_java_compatible_args() -> Self {
44        Self::parse_from(normalize_java_compatible_args(std::env::args_os()))
45    }
46
47    pub async fn handle(&self) {
48        if let Some(shell) = &self.completion {
49            let mut cmd = RocketMQCli::command();
50            let bin_name = "rocketmq-admin-cli";
51
52            match shell.to_lowercase().as_str() {
53                "bash" => {
54                    generate(Bash, &mut cmd, bin_name, &mut std::io::stdout());
55                }
56                "zsh" => {
57                    generate(Zsh, &mut cmd, bin_name, &mut std::io::stdout());
58                }
59                "fish" => {
60                    generate(Fish, &mut cmd, bin_name, &mut std::io::stdout());
61                }
62                _ => {
63                    eprintln!("Unsupported shell: {}", shell);
64                    eprintln!("Supported shells: bash, zsh, fish");
65                    std::process::exit(1);
66                }
67            }
68            return;
69        }
70
71        if let Some(ref commands) = self.commands {
72            if let Err(e) = commands.execute(None).await {
73                eprintln!("Error: {e}");
74            }
75        } else {
76            eprintln!("No command specified. Use --help for usage information.");
77        }
78    }
79}
80
81fn normalize_java_compatible_args<I>(args: I) -> Vec<OsString>
82where
83    I: IntoIterator<Item = OsString>,
84{
85    args.into_iter()
86        .map(|arg| {
87            if arg == "-bn" {
88                OsString::from("--brokerName")
89            } else {
90                arg
91            }
92        })
93        .collect()
94}
95
96#[cfg(test)]
97mod tests {
98    use super::normalize_java_compatible_args;
99    use std::ffi::OsString;
100
101    #[test]
102    fn normalizes_java_multi_character_short_broker_name_option() {
103        let args = normalize_java_compatible_args([
104            OsString::from("rocketmq-admin-cli"),
105            OsString::from("controller"),
106            OsString::from("electMaster"),
107            OsString::from("-bn"),
108            OsString::from("broker-a"),
109        ]);
110
111        assert_eq!(args[3], OsString::from("--brokerName"));
112    }
113}