1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
use serde::{Deserialize, Serialize};
pub mod output;
mod common;

#[cfg(feature = "target")]
pub mod tls;

#[cfg(feature = "installation")]
pub mod installation;

pub use common::*;
pub use crate::output::Terminal;
use fluvio_index::{PackageId, MaybeVersion};

pub const COMMAND_TEMPLATE: &str = "{about}

{usage}

{all-args}
";

#[macro_export]
macro_rules! t_print {
    ($out:expr,$($arg:tt)*) => ( $out.print(&format!($($arg)*)))
}

#[macro_export]
macro_rules! t_println {
    ($out:expr,$($arg:tt)*) => ( $out.println(&format!($($arg)*)))
}

#[macro_export]
macro_rules! t_print_cli_err {
    ($out:expr,$x:expr) => {
        t_println!($out, "\x1B[1;31merror:\x1B[0m {}", $x);
    };
}

/// Metadata that plugins may provide to Fluvio at runtime.
///
/// This allows `fluvio` to include external plugins in the help
/// menu, version printouts, and automatic updates.
#[derive(Debug, Serialize, Deserialize)]
pub struct FluvioExtensionMetadata {
    /// The title is a human-readable pretty name
    #[serde(alias = "command")]
    pub title: String,
    /// Identifies the plugin on the package index
    ///
    /// Example: `fluvio/fluvio-cloud`
    #[serde(default)]
    pub package: Option<PackageId<MaybeVersion>>,
    /// A brief description of what this plugin does
    pub description: String,
    /// The version of this plugin
    pub version: semver::Version,
}

#[derive(Debug)]
pub struct PrintTerminal {}

impl PrintTerminal {
    pub fn new() -> Self {
        Self {}
    }
}

impl Default for PrintTerminal {
    fn default() -> Self {
        Self::new()
    }
}

impl Terminal for PrintTerminal {
    fn print(&self, msg: &str) {
        print!("{msg}");
    }

    fn println(&self, msg: &str) {
        println!("{msg}");
    }
}

#[cfg(feature = "target")]
pub mod target {
    use std::io::{ErrorKind, Error as IoError};
    use std::convert::TryInto;
    use clap::Parser;

    use anyhow::Result;

    use fluvio::FluvioConfig;
    use fluvio::FluvioError;
    use fluvio::Fluvio;
    use fluvio::config::ConfigFile;
    use crate::tls::TlsClientOpt;

    #[derive(thiserror::Error, Debug)]
    pub enum TargetError {
        #[error(transparent)]
        IoError(#[from] IoError),
        #[error("Fluvio client error")]
        ClientError(#[from] FluvioError),
        #[error("Invalid argument: {0}")]
        InvalidArg(String),
        #[error("Unknown error: {0}")]
        Other(String),
    }

    impl TargetError {
        pub fn invalid_arg(reason: impl Into<String>) -> Self {
            Self::InvalidArg(reason.into())
        }
    }

    /// server configuration
    #[derive(Debug, Parser, Default, Clone)]
    pub struct ClusterTarget {
        /// Address of cluster
        #[arg(short = 'c', long, value_name = "host:port")]
        pub cluster: Option<String>,

        #[clap(flatten)]
        pub tls: TlsClientOpt,

        #[arg(short = 'P', long, value_name = "profile")]
        pub profile: Option<String>,
    }

    impl ClusterTarget {
        /// helper method to connect to fluvio
        pub async fn connect(self) -> Result<Fluvio> {
            let fluvio_config = self.load()?;
            Fluvio::connect_with_config(&fluvio_config).await
        }

        /// try to create sc config
        pub fn load(self) -> Result<FluvioConfig> {
            let tls = self.tls.try_into()?;

            use fluvio::config::TlsPolicy::*;
            match (self.profile, self.cluster) {
                // Profile and Cluster together is illegal
                (Some(_profile), Some(_cluster)) => Err(TargetError::invalid_arg(
                    "cluster addr is not valid when profile is used",
                )
                .into()),
                (Some(profile), _) => {
                    // Specifying TLS is illegal when also giving a profile
                    if let Anonymous | Verified(_) = tls {
                        return Err(TargetError::invalid_arg(
                            "tls is not valid when profile is is used",
                        )
                        .into());
                    }

                    let config_file = ConfigFile::load(None)?;
                    let cluster = config_file
                        .config()
                        // NOTE: This will not fallback to current cluster like it did before
                        // Current cluster will be used when no profile is given.
                        .cluster_with_profile(&profile)
                        .ok_or_else(|| {
                            IoError::new(ErrorKind::Other, "Cluster not found for profile")
                        })?;
                    Ok(cluster.clone())
                }
                (None, Some(cluster)) => {
                    let cluster = FluvioConfig::new(cluster).with_tls(tls);
                    Ok(cluster)
                }
                (None, None) => {
                    // TLS specification is illegal without Cluster
                    if let Anonymous | Verified(_) = tls {
                        return Err(TargetError::invalid_arg(
                            "tls is only valid if cluster addr is used",
                        )
                        .into());
                    }

                    // Try to use the default cluster from saved config
                    let config_file = ConfigFile::load(None)?;
                    let cluster = config_file.config().current_cluster()?;
                    Ok(cluster.clone())
                }
            }
        }
    }
}