spm_swift_package/
fields_results.rs

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
use demand::{DemandOption, Input, MultiSelect, Spinner, SpinnerStyle};
use std::process::{exit, Command};
use std::{thread::sleep, time::Duration};

use crate::spm::*;

pub struct FieldsResults;

impl FieldsResults {
    pub fn result() {
        let project_name = match Self::project_name_input() {
            Ok(value) => value,
            Err(_) => {
                exit(0);
            }
        };

        let selected = Self::multi_select_input();

        Self::loading();
        Spm::create_spm(&project_name, selected);
        Self::command_open_xcode(project_name);
    }

    fn project_name_input() -> Result<String, String> {
        let validation_empty = |s: &str| {
            if s.is_empty() {
                return Err("Library name cannot be empty");
            }
            Ok(())
        };

        let input = Input::new("Library name")
            .placeholder("Enter the library name")
            .prompt("Library: ")
            .validation(validation_empty);

        match input.run() {
            Ok(library) => Ok(library),
            Err(error) => {
                if error.to_string().contains("Interrupted") {
                    exit(0)
                } else {
                    exit(0)
                }
            }
        }
    }

    fn multi_select_input() -> Vec<&'static str> {
        let multi_select = MultiSelect::new("Add files")
            .description("Do you want to add some of these files?")
            .filterable(true)
            .option(DemandOption::new("Changelog"))
            .option(DemandOption::new("Swift Package Index"))
            .option(DemandOption::new("Readme"));

        let result = multi_select.run().expect("error running multi select");

        let selected: Vec<&str> = result
            .iter()
            .filter(|opt| !opt.is_empty())
            .copied()
            .collect();

        selected
    }

    fn loading() {
        Spinner::new("Building the Package...")
            .style(&SpinnerStyle::line())
            .run(|_| {
                sleep(Duration::from_secs(5));
            })
            .expect("error running spinner");
    }

    fn command_open_xcode(project_name: String) {
        let command = format!("cd {} && open Package.swift", project_name);
        let mut child = Command::new("sh")
            .arg("-c")
            .arg(&command)
            .spawn()
            .expect("Failed to open Xcode");
        
        child.wait().expect("Failed to wait on child");
    }    
}