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
use anyhow::Context;
use colored::Colorize;
use dialoguer::Select;
use wasmer_api::backend::BackendClient;
use wasmer_deploy_schema::schema::StringWebcIdent;

pub fn prompt_for_ident(message: &str, default: Option<&str>) -> Result<String, anyhow::Error> {
    loop {
        let mut diag = dialoguer::Input::new();
        diag.with_prompt(message)
            .with_initial_text(default.unwrap_or_default());

        // if let Some(val) = &validator {
        //     diag.validate_with(val);
        // }

        let raw: String = diag.interact()?;
        let val = raw.trim();
        if !val.is_empty() {
            break Ok(val.to_string());
        }
    }
}

/// Ask a user for a package name.
///
/// Will continue looping until the user provides a valid name.
pub fn prompt_for_package_ident(
    message: &str,
    default: Option<&str>,
) -> Result<StringWebcIdent, anyhow::Error> {
    loop {
        let raw: String = dialoguer::Input::new()
            .with_prompt(message)
            .with_initial_text(default.unwrap_or_default())
            .interact_text()
            .context("could not read user input")?;

        match raw.parse::<StringWebcIdent>() {
            Ok(p) => break Ok(p),
            Err(err) => {
                eprintln!("invalid package name: {err}");
            }
        }
    }
}

/// Defines how to check for a package.
pub enum PackageCheckMode {
    /// The package must exist in the registry.
    MustExist,
    /// The package must NOT exist in the registry.
    MustNotExist,
}

/// Ask for a package name.
///
/// Will continue looping until the user provides a valid name.
///
/// If an API is provided, will check if the package exists.
pub async fn prompt_for_package(
    message: &str,
    default: Option<&str>,
    check: Option<PackageCheckMode>,
    client: Option<&BackendClient>,
) -> Result<(StringWebcIdent, Option<wasmer_api::backend::gql::Package>), anyhow::Error> {
    loop {
        let name = prompt_for_package_ident(message, default)?;

        if let Some(check) = &check {
            let api = client.expect("Check mode specified, but no API provided");

            let pkg = wasmer_api::backend::get_package(api, name.to_string())
                .await
                .context("could not query backend for package")?;

            match check {
                PackageCheckMode::MustExist => {
                    if let Some(pkg) = pkg {
                        break Ok((name, Some(pkg)));
                    } else {
                        eprintln!("Package '{name}' does not exist");
                    }
                }
                PackageCheckMode::MustNotExist => {
                    if pkg.is_none() {
                        break Ok((name, None));
                    } else {
                        eprintln!("Package '{name}' already exists");
                    }
                }
            }
        }
    }
}

/// Prompt for a namespace.
///
/// Will either show a select with all available namespaces based on the `user`
/// argument, or present a basic text input.
///
/// The username will be included as an option.
pub fn prompt_for_namespace(
    message: &str,
    default: Option<&str>,
    user: Option<&wasmer_api::backend::gql::UserWithNamespaces>,
) -> Result<String, anyhow::Error> {
    if let Some(user) = user {
        let namespaces = user
            .namespaces
            .edges
            .clone()
            .into_iter()
            .flatten()
            .filter_map(|e| e.node)
            .collect::<Vec<_>>();

        let labels = [user.username.clone()]
            .into_iter()
            .chain(namespaces.iter().map(|ns| ns.global_name.clone()))
            .collect::<Vec<_>>();

        let selection_index = Select::new()
            .with_prompt(message)
            .default(0)
            .items(&labels)
            .interact()
            .context("could not read user input")?;

        Ok(labels[selection_index].clone())
    } else {
        loop {
            let value = dialoguer::Input::<String>::new()
                .with_prompt(message)
                .with_initial_text(default.map(|x| x.trim().to_string()).unwrap_or_default())
                .interact_text()
                .context("could not read user input")?
                .trim()
                .to_string();

            if !value.is_empty() {
                break Ok(value);
            }
        }
    }
}

/// Prompt for an app name.
/// If an api provided, will check if an app with the givne alias already exists.
pub async fn prompt_new_app_name(
    message: &str,
    default: Option<&str>,
    namespace: &str,
    api: Option<&BackendClient>,
) -> Result<String, anyhow::Error> {
    loop {
        let ident = prompt_for_ident(message, default)?;

        if let Some(api) = &api {
            let app =
                wasmer_api::backend::get_app(api, namespace.to_string(), ident.clone()).await?;
            eprintln!("Checking name availability...");
            if app.is_some() {
                eprintln!(
                    "{}: app '{}/{}' already exists - pick a different name",
                    "WARN:".yellow(),
                    namespace,
                    ident
                );
            } else {
                break Ok(ident);
            }
        }
    }
}

/// Prompt for an app name.
/// If an api provided, will check if an app with the givne alias already exists.
pub async fn prompt_new_app_alias(
    message: &str,
    default: Option<&str>,
    api: Option<&BackendClient>,
) -> Result<String, anyhow::Error> {
    loop {
        let ident = prompt_for_ident(message, default)?;

        if let Some(api) = &api {
            let app = wasmer_api::backend::get_app_by_alias(api, ident.clone()).await?;
            eprintln!("Checking name availability...");
            if app.is_some() {
                eprintln!(
                    "{}: alias '{}' already exists - pick a different name",
                    "WARN:".yellow(),
                    ident
                );
            } else {
                break Ok(ident);
            }
        }
    }
}