-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathnew.rs
More file actions
235 lines (201 loc) · 6.21 KB
/
new.rs
File metadata and controls
235 lines (201 loc) · 6.21 KB
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
//! New project command
use anyhow::{Context, Result};
use clap::Args;
use console::style;
use dialoguer::{theme::ColorfulTheme, Confirm, Input, Select};
use indicatif::{ProgressBar, ProgressStyle};
use std::path::Path;
use std::time::Duration;
use tokio::fs;
use crate::templates::{self, ProjectTemplate};
/// Arguments for the `new` command
#[derive(Args, Debug)]
pub struct NewArgs {
/// Project name (positional argument)
pub name: Option<String>,
/// Project template
#[arg(short, long, value_enum)]
pub template: Option<ProjectTemplate>,
/// Features to enable
#[arg(short, long, value_delimiter = ',')]
pub features: Option<Vec<String>>,
/// Skip interactive prompts
#[arg(long)]
pub yes: bool,
/// Initialize git repository
#[arg(long, default_value = "true")]
pub git: bool,
}
/// Create a new RustAPI project
pub async fn new_project(mut args: NewArgs) -> Result<()> {
let theme = ColorfulTheme::default();
// Get project name
let name = if let Some(name) = args.name.take() {
name
} else {
Input::with_theme(&theme)
.with_prompt("Project name")
.default("my-rustapi-app".to_string())
.interact_text()?
};
// Validate project name
validate_project_name(&name)?;
// Check if directory exists
let project_path = Path::new(&name);
if project_path.exists() {
anyhow::bail!("Directory '{}' already exists", name);
}
// Get template
let template = if let Some(template) = args.template {
template
} else if args.yes {
ProjectTemplate::Minimal
} else {
let templates = [
"minimal - Bare minimum app",
"api - REST API with CRUD",
"web - Web app with templates",
"full - Full-featured app",
];
let selection = Select::with_theme(&theme)
.with_prompt("Select a template")
.items(&templates)
.default(0)
.interact()?;
match selection {
0 => ProjectTemplate::Minimal,
1 => ProjectTemplate::Api,
2 => ProjectTemplate::Web,
3 => ProjectTemplate::Full,
_ => ProjectTemplate::Minimal,
}
};
// Get features
let features = if let Some(features) = args.features {
features
} else if args.yes {
vec![]
} else {
let available = [
"extras-jwt",
"extras-cors",
"extras-rate-limit",
"extras-config",
"protocol-toon",
"protocol-ws",
"protocol-view",
"protocol-grpc",
];
let defaults = match template {
ProjectTemplate::Full => vec![true, true, true, true, false, false, false, false],
ProjectTemplate::Web => vec![false, false, false, false, false, false, true, false],
_ => vec![false; available.len()],
};
let selections = dialoguer::MultiSelect::with_theme(&theme)
.with_prompt("Select features (space to toggle)")
.items(&available)
.defaults(&defaults)
.interact()?;
selections
.iter()
.map(|&i| available[i].to_string())
.collect()
};
// Confirm
if !args.yes {
println!();
println!("{}", style("Project configuration:").bold());
println!(" Name: {}", style(&name).cyan());
println!(" Template: {}", style(format!("{:?}", template)).cyan());
println!(
" Features: {}",
style(if features.is_empty() {
"none".to_string()
} else {
features.join(", ")
})
.cyan()
);
println!();
if !Confirm::with_theme(&theme)
.with_prompt("Create project?")
.default(true)
.interact()?
{
println!("{}", style("Aborted").yellow());
return Ok(());
}
}
// Create project
let pb = ProgressBar::new_spinner();
pb.set_style(
ProgressStyle::default_spinner()
.template("{spinner:.green} {msg}")
.unwrap(),
);
pb.enable_steady_tick(Duration::from_millis(80));
pb.set_message("Creating project directory...");
fs::create_dir_all(&name).await?;
pb.set_message("Generating project files...");
templates::generate_project(&name, template, &features).await?;
if args.git {
pb.set_message("Initializing git repository...");
init_git(&name).await.ok(); // Don't fail if git isn't available
}
pb.finish_and_clear();
// Success message
println!();
println!(
"{}",
style("✨ Project created successfully!").green().bold()
);
println!();
println!("Next steps:");
println!(" {} {}", style("cd").cyan(), name);
println!(" {} run", style("cargo").cyan());
println!();
println!(
"Then open {} in your browser.",
style("http://localhost:8080").cyan()
);
println!(
"API docs available at {}",
style("http://localhost:8080/docs").cyan()
);
Ok(())
}
/// Validate project name
fn validate_project_name(name: &str) -> Result<()> {
if name.is_empty() {
anyhow::bail!("Project name cannot be empty");
}
if name.contains('/') || name.contains('\\') {
anyhow::bail!("Project name cannot contain path separators");
}
// Check for valid Rust crate name characters
if !name
.chars()
.all(|c| c.is_alphanumeric() || c == '-' || c == '_')
{
anyhow::bail!(
"Project name can only contain alphanumeric characters, hyphens, and underscores"
);
}
if name.starts_with('-') || name.starts_with('_') {
anyhow::bail!("Project name cannot start with a hyphen or underscore");
}
Ok(())
}
/// Initialize a git repository
async fn init_git(path: &str) -> Result<()> {
let output = tokio::process::Command::new("git")
.args(["init"])
.current_dir(path)
.output()
.await
.context("Failed to run git init")?;
if !output.status.success() {
anyhow::bail!("git init failed");
}
Ok(())
}