forklaunch 1.15.0

Launch faster with forklaunch
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
use std::{
    collections::HashMap,
    io::{IsTerminal, Write},
};

use anyhow::{Result, bail};
use clap::ArgMatches;
use dialoguer::{FuzzySelect, Input, MultiSelect, theme::ColorfulTheme};
use rustyline::{
    Editor,
    completion::{Completer, Pair},
    history::DefaultHistory,
};
use rustyline_derive::{Helper, Highlighter, Hinter, Validator};
use termcolor::{StandardStream, WriteColor};

#[derive(Helper, Hinter, Validator, Highlighter)]
pub(crate) struct ArrayCompleter {
    options: Vec<String>,
}

impl Completer for ArrayCompleter {
    type Candidate = Pair;

    fn complete(
        &self,
        line: &str,
        pos: usize,
        _ctx: &rustyline::Context<'_>,
    ) -> rustyline::Result<(usize, Vec<Pair>)> {
        let current_line = line.split(',').last().unwrap_or(line).trim();
        let matches: Vec<Pair> = self
            .options
            .iter()
            .filter(|option| option.starts_with(current_line))
            .map(|option| Pair {
                display: option.clone(),
                replacement: option.clone(),
            })
            .collect();
        Ok((pos - current_line.len(), matches))
    }
}

pub(crate) fn prompt_without_validation(
    line_editor: &mut Editor<ArrayCompleter, DefaultHistory>,
    stdout: &mut StandardStream,
    matches_key: &str,
    matches: &ArgMatches,
    prompt: &str,
    valid_options: Option<&[&str]>,
) -> Result<String> {
    prompt_with_validation(
        line_editor,
        stdout,
        matches_key,
        matches,
        prompt,
        valid_options,
        |_| true,
        |_| "".to_string(),
    )
}

pub(crate) fn prompt_for_confirmation(
    line_editor: &mut Editor<ArrayCompleter, DefaultHistory>,
    prompt: &str,
) -> Result<bool> {
    let confirmation = line_editor.readline(prompt)?;
    Ok(confirmation.trim().to_lowercase().starts_with("y"))
}

pub(crate) fn prompt_with_validation<ErrorFunction, ValidatorFunction>(
    line_editor: &mut Editor<ArrayCompleter, DefaultHistory>,
    stdout: &mut StandardStream,
    matches_key: &str,
    matches: &ArgMatches,
    prompt: &str,
    valid_options: Option<&[&str]>,
    validator: ValidatorFunction,
    error_message: ErrorFunction,
) -> Result<String>
where
    ErrorFunction: Fn(&str) -> String,
    ValidatorFunction: Fn(&str) -> bool,
{
    loop {
        let mut continue_loop = true;
        let input = match matches.get_one::<String>(matches_key) {
            Some(val) => {
                continue_loop = false;
                val.to_string()
            }
            None => {
                // Refuse to enter an interactive prompt when stdin is not a TTY (CI, a
                // spawned process with a closed/ignored stdin, etc). dialoguer's
                // `interact()/interact_text()` read EOF instantly on a dead stdin and the
                // validation-retry loop then spins at 100% CPU forever — a single
                // `forklaunch init router` was observed pegging a core for tens of minutes.
                // A required value can't be defaulted, so bail with an actionable message.
                if !std::io::stdin().is_terminal() {
                    bail!(
                        "'{}' was not provided and stdin is not a TTY, so it cannot be \
                         prompted for interactively. Pass it as a flag/argument when running \
                         non-interactively (CI or a spawned process).",
                        matches_key
                    );
                }
                if let Some(options) = valid_options {
                    let completer = ArrayCompleter {
                        options: options.iter().map(|&s| s.to_string()).collect(),
                    };
                    line_editor.set_helper(Some(completer));
                    let prompt = if options.is_empty() {
                        format!("Enter {}: ", prompt)
                    } else {
                        format!("Enter {} [{}]: ", prompt, options.join(", "))
                    };
                    options[FuzzySelect::with_theme(&ColorfulTheme::default())
                        .with_prompt(prompt)
                        .items(options)
                        .default(0)
                        .interact()
                        .unwrap()]
                    .to_string()
                } else {
                    Input::with_theme(&ColorfulTheme::default())
                        .with_prompt(format!("Enter {}: ", prompt))
                        .validate_with({
                            |input: &String| -> Result<(), String> {
                                if validator(input) {
                                    Ok(())
                                } else {
                                    Err(error_message(input))
                                }
                            }
                        })
                        .interact_text()
                        .unwrap()
                }
            }
        };

        if validator(&input) {
            line_editor.set_helper(None);
            break Ok(input);
        }

        log_error!(stdout, "{}", error_message(&input));

        if !continue_loop {
            bail!(error_message(&input));
        }
    }
}

pub(crate) fn prompt_comma_separated_list(
    line_editor: &mut Editor<ArrayCompleter, DefaultHistory>,
    matches_key: &str,
    matches: &ArgMatches,
    valid_options: &[&str],
    active_options: Option<&[&str]>,
    prompt_text: &str,
    is_optional: bool,
) -> Result<Vec<String>> {
    match matches.get_many::<String>(matches_key) {
        Some(values) => Ok(values.cloned().collect()),
        None => {
            // Non-interactive (no TTY): a MultiSelect here would spin at 100% CPU on a dead
            // stdin. An optional list (e.g. a router's infrastructure) simply has no
            // selection in that case — return empty so the command completes headlessly
            // instead of wedging; a required list cannot be defaulted, so bail.
            if !std::io::stdin().is_terminal() {
                if is_optional {
                    return Ok(vec![]);
                }
                bail!(
                    "'{}' was not provided and stdin is not a TTY for an interactive \
                     selection. Pass it as a flag/argument when running non-interactively.",
                    matches_key
                );
            }
            let completer = ArrayCompleter {
                options: valid_options.iter().map(|&s| s.to_string()).collect(),
            };
            line_editor.set_helper(Some(completer));
            let optional_text = if is_optional { " (optional)" } else { "" };
            let prompt = format!(
                "Enter {} (comma-separated, use space to select) [{}]{}: ",
                prompt_text,
                valid_options.join(", "),
                optional_text
            );

            let multi_select_theme = &ColorfulTheme::default();
            let mut multi_select = MultiSelect::with_theme(multi_select_theme).with_prompt(prompt);

            if let Some(active_options) = active_options {
                multi_select = multi_select.items(
                    valid_options
                        .iter()
                        .filter(|s| !active_options.contains(s))
                        .collect::<Vec<&&str>>()
                        .as_slice(),
                );
                // dialoguer 0.12 takes the item iterator by value; passing a
                // reference yields `&(T, bool)` where `(T, bool)` is required.
                multi_select = multi_select.items_checked(
                    active_options
                        .iter()
                        .map(|v| (*v, true))
                        .collect::<Vec<_>>(),
                );
            } else {
                multi_select = multi_select.items(valid_options);
            }

            let input = multi_select
                .interact()
                .unwrap()
                .into_iter()
                .map(|index| valid_options[index].to_string())
                .collect();

            Ok(input)
        }
    }
}

pub(crate) fn prompt_field_from_selections_with_validation(
    field_name: &str,
    current_value: Option<&String>,
    selected_options: &[&str],
    line_editor: &mut Editor<ArrayCompleter, DefaultHistory>,
    stdout: &mut StandardStream,
    matches: &clap::ArgMatches,
    prompt: &str,
    valid_values: Option<&[&str]>,
    validator: impl Fn(&str) -> bool,
    error_msg: impl Fn(&str) -> String,
) -> Result<Option<String>> {
    if selected_options.contains(&field_name) {
        if current_value.is_none() {
            Ok(Some(prompt_with_validation(
                line_editor,
                stdout,
                field_name,
                matches,
                prompt,
                valid_values,
                validator,
                error_msg,
            )?))
        } else {
            Ok(current_value.map(|v| v.to_string()))
        }
    } else {
        Ok(current_value.map(|v| v.to_string()))
    }
}

pub(crate) fn prompt_comma_separated_list_from_selections(
    field_name: &str,
    current_value: Option<Vec<String>>,
    selected_options: &[&str],
    line_editor: &mut Editor<ArrayCompleter, DefaultHistory>,
    matches: &clap::ArgMatches,
    prompt: &str,
    valid_values: &[&str],
    active_values: Option<&[&str]>,
) -> Result<Option<Vec<String>>> {
    if selected_options.contains(&field_name) {
        if current_value.is_none() {
            Ok(Some(prompt_comma_separated_list(
                line_editor,
                field_name,
                matches,
                valid_values,
                active_values,
                prompt,
                false,
            )?))
        } else {
            Ok(current_value.map(|v| v.clone()))
        }
    } else {
        Ok(current_value)
    }
}

// New prompt functions that support pre-provided answers
pub(crate) fn prompt_with_validation_with_answers<ErrorFunction, ValidatorFunction>(
    line_editor: &mut Editor<ArrayCompleter, DefaultHistory>,
    stdout: &mut StandardStream,
    matches_key: &str,
    matches: &ArgMatches,
    prompt: &str,
    valid_options: Option<&[&str]>,
    validator: ValidatorFunction,
    error_message: ErrorFunction,
    project_name: &str,
    prompts_map: &HashMap<String, HashMap<String, String>>,
) -> Result<String>
where
    ErrorFunction: Fn(&str) -> String,
    ValidatorFunction: Fn(&str) -> bool,
{
    if let Some(project_prompts) = prompts_map.get(project_name) {
        if let Some(pre_answer) = project_prompts.get(matches_key) {
            if validator(pre_answer) {
                log_ok!(
                    stdout,
                    "Using pre-provided answer for {}: {}",
                    matches_key, pre_answer
                );
                return Ok(pre_answer.clone());
            } else {
                log_warn!(
                    stdout,
                    "Pre-provided answer '{}' for {} is invalid, prompting for input",
                    pre_answer, matches_key
                );
            }
        }
    }

    prompt_with_validation(
        line_editor,
        stdout,
        matches_key,
        matches,
        prompt,
        valid_options,
        validator,
        error_message,
    )
}

pub(crate) fn prompt_without_validation_with_answers(
    line_editor: &mut Editor<ArrayCompleter, DefaultHistory>,
    stdout: &mut StandardStream,
    matches_key: &str,
    matches: &ArgMatches,
    prompt: &str,
    valid_options: Option<&[&str]>,
    project_name: &str,
    prompts_map: &HashMap<String, HashMap<String, String>>,
) -> Result<String> {
    // Check if we have a pre-provided answer for this project and field
    if let Some(project_prompts) = prompts_map.get(project_name) {
        if let Some(pre_answer) = project_prompts.get(matches_key) {
            log_ok!(
                stdout,
                "Using pre-provided answer for {}: {}",
                matches_key, pre_answer
            );
            return Ok(pre_answer.clone());
        }
    }

    prompt_without_validation(
        line_editor,
        stdout,
        matches_key,
        matches,
        prompt,
        valid_options,
    )
}

pub(crate) fn prompt_comma_separated_list_with_answers(
    line_editor: &mut Editor<ArrayCompleter, DefaultHistory>,
    matches_key: &str,
    matches: &ArgMatches,
    valid_options: &[&str],
    active_options: Option<&[&str]>,
    prompt_text: &str,
    is_optional: bool,
    project_name: &str,
    prompts_map: &HashMap<String, HashMap<String, String>>,
) -> Result<Vec<String>> {
    // Check if we have a pre-provided answer for this project and field
    if let Some(project_prompts) = prompts_map.get(project_name) {
        if let Some(pre_answer) = project_prompts.get(matches_key) {
            let values: Vec<String> = pre_answer
                .split(',')
                .map(|s| s.trim().to_string())
                .filter(|s| !s.is_empty())
                .collect();

            let invalid_values: Vec<&String> = values
                .iter()
                .filter(|v| !valid_options.contains(&v.as_str()))
                .collect();

            if invalid_values.is_empty() {
                return Ok(values);
            }
        }
    }

    prompt_comma_separated_list(
        line_editor,
        matches_key,
        matches,
        valid_options,
        active_options,
        prompt_text,
        is_optional,
    )
}