cargo_mobile2/config/app/
raw.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
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
use super::{common_email_providers::COMMON_EMAIL_PROVIDERS, identifier, name};
use crate::{
    templating,
    util::{cli::TextWrapper, prompt, Git},
};
use colored::{Color, Colorize as _};
use heck::{ToKebabCase as _, ToTitleCase as _};
use serde::{Deserialize, Serialize};
use std::{
    env,
    fmt::{self, Display},
    io,
    path::PathBuf,
};

#[derive(Debug)]
enum DefaultIdentifierError {
    FailedToGetGitEmailAddr(#[allow(unused)] std::io::Error),
    FailedToParseEmailAddr,
}

fn default_identifier(
    _wrapper: &TextWrapper,
    name: &str,
) -> Result<Option<String>, DefaultIdentifierError> {
    let email = Git::new(".".as_ref())
        .user_email()
        .map_err(DefaultIdentifierError::FailedToGetGitEmailAddr)?;
    let domain = email
        .trim()
        .split('@')
        .last()
        .ok_or(DefaultIdentifierError::FailedToParseEmailAddr)?;
    Ok(
        if !COMMON_EMAIL_PROVIDERS.contains(&domain)
            && identifier::check_identifier_syntax(domain).is_ok()
        {
            #[cfg(not(feature = "brainium"))]
            if domain == "brainiumstudios.com" {
                crate::util::cli::Report::action_request(
                    "You have a Brainium email address, but you're using a non-Brainium installation of cargo-mobile2!",
                    "If that's not intentional, run `cargo install --force --git https://github.com/tauri-apps/cargo-mobile2 --features brainium`",
                ).print(_wrapper);
            }

            let reverse_domain = domain.split('.').rev().collect::<Vec<_>>().join(".");
            Some(format!("{reverse_domain}{name}"))
        } else {
            None
        },
    )
}

#[derive(Debug)]
pub enum DefaultsError {
    CurrentDirFailed(io::Error),
    CurrentDirHasNoName(PathBuf),
    CurrentDirInvalidUtf8(PathBuf),
}

impl Display for DefaultsError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::CurrentDirFailed(err) => {
                write!(f, "Failed to get current working directory: {}", err)
            }
            Self::CurrentDirHasNoName(cwd) => {
                write!(f, "Current working directory has no name: {:?}", cwd)
            }
            Self::CurrentDirInvalidUtf8(cwd) => write!(
                f,
                "Current working directory contained invalid UTF-8: {:?}",
                cwd
            ),
        }
    }
}

#[derive(Debug)]
struct Defaults {
    name: Option<String>,
    stylized_name: String,
    identifier: String,
}

impl Defaults {
    fn new(wrapper: &TextWrapper) -> Result<Self, DefaultsError> {
        let cwd = env::current_dir().map_err(DefaultsError::CurrentDirFailed)?;
        let dir_name = cwd
            .file_name()
            .ok_or_else(|| DefaultsError::CurrentDirHasNoName(cwd.clone()))?;
        let dir_name = dir_name
            .to_str()
            .ok_or_else(|| DefaultsError::CurrentDirInvalidUtf8(cwd.clone()))?;
        let name = name::transliterate(&dir_name.to_kebab_case());
        let dot_name = name
            .as_ref()
            .map(|n| format!(".{n}"))
            .unwrap_or_default()
            .replace("-", "_");
        Ok(Self {
            identifier: default_identifier(wrapper, &dot_name)
                .ok()
                .flatten()
                .unwrap_or_else(|| format!("com.example{dot_name}")),
            name,
            stylized_name: dir_name.to_title_case(),
        })
    }
}

#[derive(Debug)]
pub enum DetectError {
    DefaultsFailed(DefaultsError),
    NameNotDetected,
}

impl Display for DetectError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::DefaultsFailed(err) => write!(f, "Failed to detect default values: {}", err),
            Self::NameNotDetected => write!(f, "No app name was detected."),
        }
    }
}

#[derive(Debug)]
pub enum PromptError {
    DefaultsFailed(DefaultsError),
    NamePromptFailed(io::Error),
    StylizedNamePromptFailed(io::Error),
    IdentifierPromptFailed(io::Error),
    ListTemplatePacksFailed(templating::ListError),
    TemplatePackPromptFailed(io::Error),
}

impl Display for PromptError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::DefaultsFailed(err) => write!(f, "Failed to detect default values: {}", err),
            Self::NamePromptFailed(err) => write!(f, "Failed to prompt for name: {}", err),
            Self::StylizedNamePromptFailed(err) => {
                write!(f, "Failed to prompt for stylized name: {}", err)
            }
            Self::IdentifierPromptFailed(err) => {
                write!(f, "Failed to prompt for identifier: {}", err)
            }
            Self::ListTemplatePacksFailed(err) => write!(f, "{}", err),
            Self::TemplatePackPromptFailed(err) => {
                write!(f, "Failed to prompt for template pack: {}", err)
            }
        }
    }
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct Raw {
    pub name: String,
    pub lib_name: Option<String>,
    pub stylized_name: Option<String>,
    pub identifier: String,
    pub asset_dir: Option<String>,
    pub template_pack: Option<String>,
}

impl Raw {
    pub fn detect(wrapper: &TextWrapper) -> Result<Self, DetectError> {
        let defaults = Defaults::new(wrapper).map_err(DetectError::DefaultsFailed)?;
        Ok(Self {
            name: defaults.name.ok_or_else(|| DetectError::NameNotDetected)?,
            lib_name: None,
            stylized_name: Some(defaults.stylized_name),
            identifier: defaults.identifier,
            asset_dir: None,
            template_pack: Some(super::DEFAULT_TEMPLATE_PACK.to_owned())
                .filter(|pack| pack != super::IMPLIED_TEMPLATE_PACK),
        })
    }

    pub fn prompt(wrapper: &TextWrapper) -> Result<Self, PromptError> {
        let defaults = Defaults::new(wrapper).map_err(PromptError::DefaultsFailed)?;
        let (name, default_stylized) = Self::prompt_name(&defaults)?;
        let stylized_name = Self::prompt_stylized_name(&name, default_stylized)?;
        let identifier = Self::prompt_identifier(wrapper, &defaults)?;
        let template_pack = Some(Self::prompt_template_pack(wrapper)?)
            .filter(|pack| pack != super::IMPLIED_TEMPLATE_PACK);
        Ok(Self {
            name,
            lib_name: None,
            stylized_name: Some(stylized_name),
            identifier,
            asset_dir: None,
            template_pack,
        })
    }
}

impl Raw {
    fn prompt_name(defaults: &Defaults) -> Result<(String, Option<String>), PromptError> {
        let default_name = defaults.name.clone();
        let name = prompt::default("Project name", default_name.as_deref(), None)
            .map_err(PromptError::NamePromptFailed)?;
        let default_stylized = Some(defaults.stylized_name.clone());
        Ok((name, default_stylized))
    }

    fn prompt_stylized_name(
        name: &str,
        default_stylized: Option<String>,
    ) -> Result<String, PromptError> {
        let stylized =
            default_stylized.unwrap_or_else(|| name.replace(['-', '_'], " ").to_title_case());
        prompt::default("Stylized name", Some(&stylized), None)
            .map_err(PromptError::StylizedNamePromptFailed)
    }

    fn prompt_identifier(
        wrapper: &TextWrapper,
        defaults: &Defaults,
    ) -> Result<String, PromptError> {
        Ok(loop {
            let response = prompt::default("Identifier", Some(&defaults.identifier), None)
                .map_err(PromptError::IdentifierPromptFailed)?;
            match identifier::check_identifier_syntax(response.as_str()) {
                Ok(_) => break response,
                Err(err) => {
                    println!(
                        "{}",
                        wrapper.fill(&format!("Sorry! {}", err)).bright_magenta()
                    )
                }
            }
        })
    }

    pub fn prompt_template_pack(wrapper: &TextWrapper) -> Result<String, PromptError> {
        let packs = templating::list_app_packs().map_err(PromptError::ListTemplatePacksFailed)?;
        let mut default_pack = None;
        println!("Detected template packs:");
        for (index, pack) in packs.iter().enumerate() {
            let default = pack == super::DEFAULT_TEMPLATE_PACK;
            if default {
                default_pack = Some(index.to_string());
                println!(
                    "{}",
                    format!("  [{}] {}", index.to_string().bright_green(), pack,)
                        .bright_white()
                        .bold()
                );
            } else {
                println!("  [{}] {}", index.to_string().green(), pack);
            }
        }
        if packs.is_empty() {
            println!("  -- none --");
        }
        loop {
            println!("  Enter an {} for a template pack above.", "index".green(),);
            let pack_input = prompt::default(
                "Template pack",
                default_pack.as_deref(),
                Some(Color::BrightGreen),
            )
            .map_err(PromptError::TemplatePackPromptFailed)?;
            let pack_name = pack_input
                .parse::<usize>()
                .ok()
                .and_then(|index| packs.get(index))
                .cloned();
            if let Some(pack_name) = pack_name {
                break Ok(pack_name);
            } else {
                println!(
                    "{}",
                    wrapper
                        .fill("Uh-oh, you need to specify a template pack.")
                        .bright_magenta()
                );
            }
        }
    }
}