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
use super::RapidCommand;use crate::{
	cli::{current_directory, logo, rapid_logo, Config},
	constants::BOLT_EMOJI,
};
use clap::{arg, value_parser, ArgAction, ArgMatches, Command};
use colorful::{Color, Colorful};
use std::{
	path::PathBuf,
	fs::remove_dir_all,
	thread, time,
	process::exit
};
use walkdir::WalkDir;
use include_dir::{include_dir, Dir};
use std::{process::Command as StdCommand};
use requestty::{prompt_one, Question};


// We need to get the project directory to extract the template files (this is because include_dir!() is yoinked inside of a workspace)
const PROJECT_DIR: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/src/templates/server");

pub struct New {}

impl RapidCommand for New {
	fn cmd() -> clap::Command {
		Command::new("new")
			.about("Creates a new rapid project at the current working directory!")
			.arg(
				arg!(
					-full --fullstack "Scaffolds a fullstack rapid project!"
				)
				.required(false)
				.action(ArgAction::SetTrue)
				.value_parser(value_parser!(PathBuf)),
			)
			.arg(
				arg!(
					-server --server "Scaffolds a server-side only rapid project!"
				)
				.required(false)
				.action(ArgAction::SetTrue)
				.value_parser(value_parser!(PathBuf)),
			)
	}

	fn execute(_: &Config, args: &ArgMatches) -> Result<(), crate::cli::CliError<'static>> {
		println!("{}", logo());
		parse_new_args(args);
		Ok(())
	}
}


pub fn parse_new_args(args: &ArgMatches) {
	/// NOTE: We can add more args for templates here (ideally we add nextjs asap)
	const NEW_ARGS: [&str; 2] = ["fullstack", "server"];
	// Get the current working directory of the user
	let current_working_directory = current_directory();

	for arg in NEW_ARGS {
		match args.get_one::<PathBuf>(arg) {
			Some(val) => {
				if val == &PathBuf::from("true") {
					match arg {
						"fullstack" => {
							init_fullstack_template(current_working_directory, arg);
							break;
						}
						"server" => {
							init_server_template(current_working_directory, arg);
							break;
						}
						_ => {
							println!("> Invalid argument passed to new command!");
							break;
						}
					}
				}
			}
			None => {
				println!("> No argument passed to new command!");
				break;
			}
		}
	}
}

pub fn init_fullstack_template(current_working_directory: PathBuf, arg: &str) {
	println!("Coming soon...");
}

pub fn init_server_template(current_working_directory: PathBuf, _: &str) {
	// Ask the user what they want to name their project
	let project_name = prompt_one(
        Question::input("project_name")
            .message("What will your project be called?")
            .default("my-app")
            .build(),
    ).expect("Error: Could not scaffold project. Please try again!");

	let project_name = project_name.as_string().unwrap();

	// Validate that the project name does not contain any invalid chars
	if !project_name.chars().all(|x| x.is_alphanumeric() || x == '-' || x == '_') {
		println!("Aborting...your project name may only contain alphanumeric characters along with '-' and '_'...");
		exit(64);
	}

	let path = current_working_directory.join(project_name);

	// Check if the path already exists (if it does we want to ask the user if they want to delete it)
	if path.exists() {
        let force = prompt_one(
            Question::confirm("force_delete")
                .message("Your specified directory is not empty and has files currently in it, do you want to overwrite?")
                .default(false)
                .build(),
        ).expect("Error: Could not scaffold project. Please try again!");

        match !force.as_bool().unwrap() {
            true => {
                exit(64);
            }
            false => {
                remove_dir_all(&path).expect("Error: Could not scaffold project. The specified directory must be empty. Please try again!");
            }
        }
    }


	// Run the cargo commands
	StdCommand::new("sh")
	.current_dir(current_directory())
	.arg("-c")
	.arg(format!("cargo new {} --quiet", project_name))
	.spawn()
	.unwrap()
	.wait()
	.expect("Error: Could not scaffold project. Please try again!");

	StdCommand::new("sh")
	.current_dir(current_directory().join(project_name))
	.arg("-c")
	.arg("cargo add rapid-web rapid-web-codegen futures-util include_dir --quiet")
	.spawn()
	.unwrap()
	.wait()
	.expect("Error: Could not scaffold project. Please try again!");

	// Remove the default src directory
	remove_dir_all(current_working_directory.join(format!("{}/src", project_name))).unwrap();

	// Replace the default source dir with our own template files
	PROJECT_DIR.extract(current_working_directory.join(project_name).clone()).unwrap();

	for entry in WalkDir::new(current_working_directory) {
        let entry = entry.unwrap();
        if entry.file_name().to_str() == Some("Cargo__toml") {
            std::fs::rename(entry.path(), entry.path().with_file_name("Cargo.toml")).expect("Error: could not complete post scaffold scripts. Please try again.");
        }
    }

	println!("{}...", "Initializing a new rapid-web server application".color(Color::Green));

	// Sleep a little to show loading animation, etc (there is a nice one we could use from the "tui" crate)
	let timeout = time::Duration::from_millis(500);
	thread::sleep(timeout);

	println!(
		"\n\n{} {} {} {}",
		format!("{}", rapid_logo()).bold(),
		"Success".bg_blue().color(Color::White).bold(),
		BOLT_EMOJI,
		"Welcome to your new rapid-web server application!"
	);

	println!(
		"{} {} {} {} {}",
		"\n\n🚀".bold(),
		"Next Steps".bg_blue().color(Color::White).bold(),
		BOLT_EMOJI,
		format!("\n\ncd {}", project_name).bold(),
		"\nrapid run".bold()
	);
}