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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
use crate::{
    config::{UpdateRegistry, WasmerConfig, WasmerEnv},
    VERSION,
};
use anyhow::{Context, Result};
use clap::Parser;
use std::str::ParseBoolError;

use super::AsyncCliCommand;

#[derive(Debug, Parser)]
/// The options for the `wasmer config` subcommand: `wasmer config get --OPTION` or `wasmer config set [FLAG]`
pub struct Config {
    #[clap(flatten)]
    env: WasmerEnv,

    #[clap(flatten)]
    flags: Flags,
    /// Subcommand for `wasmer config get | set`
    #[clap(subcommand)]
    set: Option<GetOrSet>,
}

/// Normal configuration
#[derive(Debug, Parser)]
pub struct Flags {
    /// Print the installation prefix.
    #[clap(long, conflicts_with = "pkg_config")]
    prefix: bool,

    /// Directory containing Wasmer executables.
    #[clap(long, conflicts_with = "pkg_config")]
    bindir: bool,

    /// Directory containing Wasmer headers.
    #[clap(long, conflicts_with = "pkg_config")]
    includedir: bool,

    /// Directory containing Wasmer libraries.
    #[clap(long, conflicts_with = "pkg_config")]
    libdir: bool,

    /// Libraries needed to link against Wasmer components.
    #[clap(long, conflicts_with = "pkg_config")]
    libs: bool,

    /// C compiler flags for files that include Wasmer headers.
    #[clap(long, conflicts_with = "pkg_config")]
    cflags: bool,

    /// Print the path to the wasmer configuration file where all settings are stored
    #[clap(long, conflicts_with = "pkg_config")]
    config_path: bool,

    /// Outputs the necessary details for compiling
    /// and linking a program to Wasmer, using the `pkg-config` format.
    #[clap(long)]
    pkg_config: bool,
}

/// Subcommand for `wasmer config set`
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Parser)]
pub enum GetOrSet {
    /// `wasmer config get $KEY`
    #[clap(subcommand)]
    Get(RetrievableConfigField),
    /// `wasmer config set $KEY $VALUE`
    #[clap(subcommand)]
    Set(StorableConfigField),
}

/// Subcommand for `wasmer config get`
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Parser)]
pub enum RetrievableConfigField {
    /// Print the registry URL of the currently active registry
    #[clap(name = "registry.url")]
    RegistryUrl,
    /// Print the token for the currently active registry or nothing if not logged in
    #[clap(name = "registry.token")]
    RegistryToken,
    /// Print whether telemetry is currently enabled
    #[clap(name = "telemetry.enabled")]
    TelemetryEnabled,
    /// Print whether update notifications are enabled
    #[clap(name = "update-notifications.enabled")]
    UpdateNotificationsEnabled,
    /// Print the proxy URL
    #[clap(name = "proxy.url")]
    ProxyUrl,
}

/// Setting that can be stored in the wasmer config
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Parser)]
pub enum StorableConfigField {
    /// Set the registry URL of the currently active registry
    #[clap(name = "registry.url")]
    RegistryUrl(SetRegistryUrl),
    /// Set the token for the currently active registry or nothing if not logged in
    #[clap(name = "registry.token")]
    RegistryToken(SetRegistryToken),
    /// Set whether telemetry is currently enabled
    #[clap(name = "telemetry.enabled")]
    TelemetryEnabled(SetTelemetryEnabled),
    /// Set whether update notifications are enabled
    #[clap(name = "update-notifications.enabled")]
    UpdateNotificationsEnabled(SetUpdateNotificationsEnabled),
    /// Set the active proxy URL
    #[clap(name = "proxy.url")]
    ProxyUrl(SetProxyUrl),
}

/// Set the current active registry URL
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Parser)]
pub struct SetRegistryUrl {
    /// Url of the registry
    #[clap(name = "URL")]
    pub url: String,
}

/// Set or change the token for the current active registry
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Parser)]
pub struct SetRegistryToken {
    /// Token to set
    #[clap(name = "TOKEN")]
    pub token: String,
}

/// Set if update notifications are enabled
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Parser)]
pub struct SetUpdateNotificationsEnabled {
    /// Whether to enable update notifications
    ///
    /// ("true" | "false")
    #[clap(name = "ENABLED")]
    pub enabled: BoolString,
}

/// "true" or "false" for handling input in the CLI
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct BoolString(pub bool);

impl std::str::FromStr for BoolString {
    type Err = ParseBoolError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self(bool::from_str(s)?))
    }
}

/// Set if telemetry is enabled
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Parser)]
pub struct SetTelemetryEnabled {
    /// Whether to enable telemetry
    ///
    /// ("true" | "false")
    #[clap(name = "ENABLED")]
    pub enabled: BoolString,
}

/// Set if a proxy URL should be used
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Parser)]
pub struct SetProxyUrl {
    /// Set if a proxy URL should be used (empty = unset proxy)
    #[clap(name = "URL")]
    pub url: String,
}

#[async_trait::async_trait]
impl AsyncCliCommand for Config {
    type Output = ();

    /// Runs logic for the `config` subcommand
    async fn run_async(self) -> Result<Self::Output, anyhow::Error> {
        self.inner_execute()
            .await
            .context("failed to retrieve the wasmer config".to_string())
    }
}

impl Config {
    async fn inner_execute(&self) -> Result<()> {
        if let Some(s) = self.set.as_ref() {
            return s.execute(&self.env).await;
        }

        let flags = &self.flags;

        let prefix = self.env.dir();

        let prefixdir = prefix.display().to_string();
        let bindir = prefix.join("bin").display().to_string();
        let includedir = prefix.join("include").display().to_string();
        let libdir = prefix.join("lib").display().to_string();
        let cflags = format!("-I{includedir}");
        let libs = format!("-L{libdir} -lwasmer");

        if flags.pkg_config {
            println!("prefix={prefixdir}");
            println!("exec_prefix={bindir}");
            println!("includedir={includedir}");
            println!("libdir={libdir}");
            println!();
            println!("Name: wasmer");
            println!("Description: The Wasmer library for running WebAssembly");
            println!("Version: {VERSION}");
            println!("Cflags: {cflags}");
            println!("Libs: {libs}");
            return Ok(());
        }

        if flags.prefix {
            println!("{prefixdir}");
        }
        if flags.bindir {
            println!("{bindir}");
        }
        if flags.includedir {
            println!("{includedir}");
        }
        if flags.libdir {
            println!("{libdir}");
        }
        if flags.libs {
            println!("{libs}");
        }
        if flags.cflags {
            println!("{cflags}");
        }

        if flags.config_path {
            let path = WasmerConfig::get_file_location(self.env.dir());
            println!("{}", path.display());
        }

        Ok(())
    }
}

impl GetOrSet {
    async fn execute(&self, env: &WasmerEnv) -> Result<()> {
        let config_file = WasmerConfig::get_file_location(env.dir());
        let mut config = env.config()?;

        match self {
            GetOrSet::Get(g) => match g {
                RetrievableConfigField::RegistryUrl => {
                    println!("{}", config.registry.get_current_registry());
                }
                RetrievableConfigField::RegistryToken => {
                    if let Some(s) = config
                        .registry
                        .get_login_token_for_registry(&config.registry.get_current_registry())
                    {
                        println!("{s}");
                    }
                }
                RetrievableConfigField::TelemetryEnabled => {
                    println!("{:?}", config.telemetry_enabled);
                }
                RetrievableConfigField::UpdateNotificationsEnabled => {
                    println!("{:?}", config.update_notifications_enabled);
                }
                RetrievableConfigField::ProxyUrl => {
                    if let Some(s) = config.proxy.url.as_ref() {
                        println!("{s}");
                    } else {
                        println!("none");
                    }
                }
            },
            GetOrSet::Set(s) => {
                match s {
                    StorableConfigField::RegistryUrl(s) => {
                        config.registry.set_current_registry(&s.url).await;
                        let current_registry = config.registry.get_current_registry();
                        if let Ok(client) = env.client() {
                            if let Some(u) =
                                wasmer_backend_api::query::current_user(&client).await?
                            {
                                println!(
                                "Successfully logged into registry {current_registry:?} as user {u:?}"
                            );
                            }
                        }
                    }
                    StorableConfigField::RegistryToken(t) => {
                        config.registry.set_login_token_for_registry(
                            &config.registry.get_current_registry(),
                            &t.token,
                            UpdateRegistry::LeaveAsIs,
                        );
                    }
                    StorableConfigField::TelemetryEnabled(t) => {
                        config.telemetry_enabled = t.enabled.0;
                    }
                    StorableConfigField::ProxyUrl(p) => {
                        if p.url == "none" || p.url.is_empty() {
                            config.proxy.url = None;
                        } else {
                            config.proxy.url = Some(p.url.clone());
                        }
                    }
                    StorableConfigField::UpdateNotificationsEnabled(u) => {
                        config.update_notifications_enabled = u.enabled.0;
                    }
                }
                config
                    .save(config_file)
                    .with_context(|| anyhow::anyhow!("could not save config file"))?;
            }
        }
        Ok(())
    }
}