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
// Copyright 2019-2022 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

use dialoguer::{Confirm, Input, Select};
use std::{ffi::OsString, fs, process::exit};

use crate::{category::Category, colors::*, package_manager::PackageManager, theme::ColorfulTheme};

mod category;
mod cli;
mod colors;
mod manifest;
mod package_manager;
mod template;
mod theme;

pub mod internal {
    //! Re-export of create-tauri-app internals
    //!
    //! ## Warning
    //!
    //! This is meant to be used internally only so use at your own risk
    //! and expect APIs to break without a prior notice.
    pub mod package_manager {
        pub use crate::package_manager::*;
    }

    pub mod template {
        pub use crate::template::*;
    }
}

pub fn run<I, A>(args: I, bin_name: Option<String>)
where
    I: IntoIterator<Item = A>,
    A: Into<OsString> + Clone,
{
    if let Err(e) = try_run(args, bin_name) {
        eprintln!("{BOLD}{RED}error{RESET}: {e:#}");
        exit(1);
    }
}

fn try_run<I, A>(args: I, bin_name: Option<String>) -> anyhow::Result<()>
where
    I: IntoIterator<Item = A>,
    A: Into<OsString> + Clone,
{
    let args = cli::parse(args.into_iter().map(Into::into).collect(), bin_name)?;
    let defaults = cli::Args::default();
    let cli::Args {
        skip,
        mobile,
        alpha,
        ..
    } = args;
    let cwd = std::env::current_dir()?;

    // Allow `--mobile` to only be used with `--alpha` for now
    // TODO: remove this limitation once tauri@v2 is stable
    if let Some(mobile) = mobile {
        if mobile && !alpha {
            eprintln!(
                "{BOLD}{RED}error{RESET}: `{GREEN}--mobile{RESET}` option is only available if `{GREEN}--alpha{RESET}` option is also used"
            );
            exit(1);
        }
    }

    // Project name used for the project directory name
    // and if valid, it will also be used in Cargo.toml, Package.json ...etc
    let project_name = args.project_name.unwrap_or_else(|| {
        if skip {
            defaults.project_name.unwrap()
        } else {
            Input::<String>::with_theme(&ColorfulTheme::default())
                .with_prompt("Project name")
                .default("tauri-app".into())
                .interact_text()
                .unwrap()
                .trim()
                .to_string()
        }
    });

    let target_dir = cwd.join(&project_name);

    // Package name used in Cargo.toml, Package.json ...etc
    let package_name = if is_valid_pkg_name(&project_name) {
        project_name.clone()
    } else {
        let valid_name = to_valid_pkg_name(&project_name);
        if skip {
            valid_name
        } else {
            Input::<String>::with_theme(&ColorfulTheme::default())
            .with_prompt("Package name")
            .default(valid_name.clone())
            .with_initial_text(valid_name)
            .validate_with(|input: &String| {
                if is_valid_pkg_name(input) {
                    Ok(())
                } else {
                    Err("Package name should only include alphanumeric character and hyphens \"-\" and doesn't start with numbers")
                }
            })
            .interact_text()?
            .trim().to_string()
        }
    };

    // Confirm deleting the target project directory if not empty
    if target_dir.exists() && target_dir.read_dir()?.next().is_some() {
        let overrwite = if skip {
            false
        } else {
            Confirm::with_theme(&ColorfulTheme::default())
                .with_prompt(format!(
                    "{} directory is not empty, do you want to overwrite?",
                    if target_dir == cwd {
                        "Current directory".to_string()
                    } else {
                        target_dir
                            .file_name()
                            .unwrap()
                            .to_string_lossy()
                            .to_string()
                    }
                ))
                .default(false)
                .interact()?
        };
        if !overrwite {
            eprintln!("{BOLD}{RED}✘{RESET} Operation Cancelled");
            exit(1);
        }
    };

    // Prompt for category if a package manger is not passed on the command line
    let category = if args.manager.is_none() && !skip {
        // Filter managers if a template is passed on the command line
        let managers = PackageManager::ALL.to_vec();
        let managers = args
            .template
            .map(|t| {
                managers
                    .iter()
                    .copied()
                    .filter(|p| p.templates().contains(&t))
                    .collect::<Vec<_>>()
            })
            .unwrap_or(managers);

        // Filter categories based on the detected package mangers
        let categories = Category::ALL.to_vec();
        let categories = categories
            .into_iter()
            .filter(|c| c.package_managers().iter().any(|p| managers.contains(p)))
            .collect::<Vec<_>>();

        // If only one category is detected, skip prompt
        if categories.len() == 1 {
            Some(categories[0])
        } else {
            let index = Select::with_theme(&ColorfulTheme::default())
                .with_prompt("Choose which language to use for your frontend")
                .items(&categories)
                .default(0)
                .interact()
                .unwrap();
            Some(categories[index])
        }
    } else {
        None
    };

    // Package manager which will be used for rendering the template
    // and the after-render instructions
    let pkg_manager = args.manager.unwrap_or_else(|| {
        if skip {
            defaults.manager.unwrap()
        } else {
            let category = category.unwrap();
            let managers = category.package_managers();

            // If only one package manager is detected, skip prompt
            if managers.len() == 1 {
                managers[0]
            } else {
                let index = Select::with_theme(&ColorfulTheme::default())
                    .with_prompt("Choose your package manager")
                    .items(managers)
                    .default(0)
                    .interact()
                    .unwrap();
                managers[index]
            }
        }
    });

    let templates = pkg_manager.templates();

    // Template to render
    let template = args.template.unwrap_or_else(|| {
        if skip {
            defaults.template.unwrap()
        } else {
            let index = Select::with_theme(&ColorfulTheme::default())
                .with_prompt("Choose your UI template")
                .items(
                    &templates
                        .iter()
                        .map(|t| t.select_text())
                        .collect::<Vec<_>>(),
                )
                .default(0)
                .interact()
                .unwrap();
            let template = templates[index];

            // Prompt for flavors if the template has more than one flavor
            let flavors = template.flavors(pkg_manager);
            if let Some(flavors) = flavors {
                let index = Select::with_theme(&ColorfulTheme::default())
                    .with_prompt("Choose your UI flavor")
                    .items(flavors)
                    .default(0)
                    .interact()
                    .unwrap();
                template.from_flavor(flavors[index])
            } else {
                template
            }
        }
    });

    // Prompt for wether to bootstrap a mobile-friendly tauri project
    // This should only be prompted if `--alpha` is used on the command line and `--mobile` wasn't.
    // TODO: remove this limitation once tauri@v2 is stable
    let mobile = mobile.unwrap_or_else(|| {
        if skip || !alpha {
            defaults.mobile.unwrap()
        } else {
            Confirm::with_theme(&ColorfulTheme::default())
                .with_prompt("Would you like to setup the project for mobile as well?")
                .default(false)
                .interact()
                .unwrap()
        }
    });

    // If the package manager and the template are specified on the command line
    // then almost all prompts are skipped so we need to make sure that the combination
    // is valid, otherwise, we error and exit
    if !pkg_manager.templates_all().contains(&template) {
        eprintln!(
            "{BOLD}{RED}error{RESET}: the {GREEN}{}{RESET} template is not suppported for the {GREEN}{pkg_manager}{RESET} package manager\n       possible templates for {GREEN}{pkg_manager}{RESET} are: [{}]",
            template,
            templates.iter().map(|e|format!("{GREEN}{}{RESET}", e, GREEN = GREEN, RESET = RESET)).collect::<Vec<_>>().join(", ")
        );
        exit(1);
    }

    // Remove the target dir contents before rendering the template
    // SAFETY: Upon reaching this line, the user already accepted to overwrite
    if target_dir.exists() {
        for file in fs::read_dir(&target_dir)?.flatten() {
            let _ = fs::remove_file(file.path());
        }
    } else {
        let _ = fs::create_dir_all(&target_dir);
    }

    // Render the template
    template.render(&target_dir, pkg_manager, &package_name, alpha, mobile)?;

    // Print post-render instructions
    println!();
    println!(
        "{ITALIC}{DIM}Please follow{DIMRESET} {BLUE}https://tauri.app/v1/guides/getting-started/prerequisites{WHITE} {DIM}to install the needed prerequisites, if you haven't already.{DIMRESET}{RESET}",
    );
    if let Some(info) = template.post_init_info(pkg_manager, alpha) {
        println!("{}", info);
    }
    println!();
    println!("Done, Now run:");
    if target_dir != cwd {
        println!(
            "  cd {}",
            if project_name.contains(' ') {
                format!("\"{}\"", project_name)
            } else {
                project_name
            }
        );
    }
    if let Some(cmd) = pkg_manager.install_cmd() {
        println!("  {}", cmd);
    }
    println!("  {} tauri dev", pkg_manager.run_cmd());
    println!();
    Ok(())
}

fn is_valid_pkg_name(project_name: &str) -> bool {
    !project_name
        .chars()
        .next()
        .map(|c| c.is_ascii_digit())
        .unwrap_or_default()
        && !project_name
            .chars()
            .any(|ch| !(ch.is_alphanumeric() || ch == '-' || ch == '_'))
        && !project_name.is_empty()
}

fn to_valid_pkg_name(project_name: &str) -> String {
    #[allow(clippy::collapsible_str_replace)]
    let ret = project_name
        .trim()
        .to_lowercase()
        .replace(':', "-")
        .replace(';', "-")
        .replace(' ', "-")
        .replace('~', "-")
        .replace('.', "")
        .replace('\\', "")
        .replace('/', "");

    let ret = ret
        .chars()
        .skip_while(|ch| ch.is_ascii_digit() || *ch == '-')
        .collect::<String>();

    if ret.is_empty() {
        "tauri-app".to_string()
    } else {
        ret
    }
}

#[cfg(test)]
mod test {
    use super::*;
    #[test]
    fn valiadtes_pkg_name() {
        assert!(is_valid_pkg_name("tauri-app"));
        assert!(is_valid_pkg_name("tauri_app"));
        assert!(is_valid_pkg_name("t2auriapp"));
        assert!(!is_valid_pkg_name("1tauriapp"));
        assert!(!is_valid_pkg_name("tauri app"));
        assert!(!is_valid_pkg_name("tauri:app"));
        assert!(!is_valid_pkg_name("tauri.app"));
        assert!(!is_valid_pkg_name("tauri/app"));
        assert!(!is_valid_pkg_name("tauri\\app"));
        assert!(!is_valid_pkg_name("tauri~app"));
    }

    #[test]
    fn converts_to_valid_pkg_name() {
        assert_eq!(to_valid_pkg_name("tauri-app"), "tauri-app");
        assert_eq!(to_valid_pkg_name("tauri_app"), "tauri_app");
        assert_eq!(to_valid_pkg_name("t2auriapp"), "t2auriapp");
        assert_eq!(to_valid_pkg_name("1tauriapp"), "tauriapp");
        assert_eq!(to_valid_pkg_name("123tauriapp"), "tauriapp");
        assert_eq!(to_valid_pkg_name("123-tauriapp"), "tauriapp");
        assert_eq!(to_valid_pkg_name("tauri app"), "tauri-app");
        assert_eq!(to_valid_pkg_name("tauri:app"), "tauri-app");
        assert_eq!(to_valid_pkg_name("tauri;app"), "tauri-app");
        assert_eq!(to_valid_pkg_name("tauri.app"), "tauriapp");
        assert_eq!(to_valid_pkg_name("tauri/app"), "tauriapp");
        assert_eq!(to_valid_pkg_name("tauri\\app"), "tauriapp");
        assert_eq!(to_valid_pkg_name("tauri~app"), "tauri-app");
        assert_eq!(to_valid_pkg_name("-tauri.app"), "tauriapp");
        assert_eq!(to_valid_pkg_name("-123tauri.app"), "tauriapp");
        assert_eq!(to_valid_pkg_name("-2-123tau2ri-app-2"), "tau2ri-app-2");
        assert_eq!(to_valid_pkg_name("1-2-3tau2ri-app2-"), "tau2ri-app2-");
    }
}