-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig
More file actions
437 lines (373 loc) · 13.2 KB
/
Copy pathconfig
File metadata and controls
437 lines (373 loc) · 13.2 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
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
use std::env;
use std::fs;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, exit};
struct ProjectPaths {
base_dir: PathBuf,
project_path: PathBuf,
project_name: String,
}
struct ProjectStatus {
has_nextjs: bool,
has_git: bool,
has_github: bool,
has_vercel: bool,
}
fn main() {
let home = env::var("HOME").expect("HOME environment variable not set");
let base_dir = PathBuf::from(home).join("dev/nextjs");
// Ensure base directory exists
fs::create_dir_all(&base_dir).ok();
// Check for required tools
if !command_exists("gh") {
eprintln!("❌ GitHub CLI (gh) not found. Install it first!");
eprintln!(" macOS: brew install gh");
eprintln!(" Ubuntu: sudo apt install gh");
exit(1);
}
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
// No project name provided - enter interactive mode
handle_no_args(&base_dir);
} else {
// Project name provided - full workflow
let project_name = &args[1];
let project_path = base_dir.join(project_name);
let paths = ProjectPaths {
base_dir,
project_path: project_path.clone(),
project_name: project_name.to_string(),
};
run_full_workflow(paths);
}
}
fn handle_no_args(base_dir: &Path) {
// Try to detect current project
if let Ok(current_dir) = env::current_dir() {
if current_dir.starts_with(base_dir) {
if let Some(project_name) = current_dir.file_name() {
let project_name = project_name.to_string_lossy().to_string();
println!("🔍 Detected current project: {}", project_name);
let paths = ProjectPaths {
base_dir: base_dir.to_path_buf(),
project_path: current_dir.clone(),
project_name: project_name.clone(),
};
interactive_mode(paths);
return;
}
}
}
// Not in a project directory
println!("🤔 No project name provided and not in a Next.js project directory.\n");
print!("Enter project name: ");
io::stdout().flush().unwrap();
let mut project_name = String::new();
io::stdin().read_line(&mut project_name).unwrap();
let project_name = project_name.trim().to_string();
if project_name.is_empty() {
eprintln!("❌ Project name cannot be empty.");
exit(1);
}
let project_path = base_dir.join(&project_name);
if project_path.exists() {
println!("📁 Project directory already exists: {}", project_path.display());
} else {
println!("📁 Creating new project directory...");
fs::create_dir_all(&project_path).unwrap();
}
let paths = ProjectPaths {
base_dir: base_dir.to_path_buf(),
project_path,
project_name,
};
interactive_mode(paths);
}
fn interactive_mode(paths: ProjectPaths) {
println!("\n🎯 Interactive Mode");
println!("📁 Current location: {}", paths.project_path.display());
let status = check_project_status(&paths);
println!("\n📊 Current Status:");
println!(" Next.js Project: {}", if status.has_nextjs { "✅" } else { "❌" });
println!(" Git Initialized: {}", if status.has_git { "✅" } else { "❌" });
println!(" GitHub Repo: {}", if status.has_github { "✅" } else { "❌" });
println!(" Vercel Deployed: {}", if status.has_vercel { "✅" } else { "❌" });
println!("\nWhat would you like to do?");
println!("1. Full setup (Next.js + Git + GitHub + Vercel)");
println!("2. Next.js project bootstrapping only");
println!("3. Git initialization only");
println!("4. GitHub repository creation only");
println!("5. Vercel deployment only");
println!("6. Exit");
let choice = get_menu_choice(1, 6);
match choice {
1 => {
if !status.has_nextjs { create_nextjs_project(&paths); }
if !status.has_git { init_git(&paths); }
if !status.has_github { create_github_repo(&paths); }
if command_exists("vercel") && get_yes_no("\nDeploy to Vercel?") {
deploy_to_vercel(&paths);
}
}
2 => {
if status.has_nextjs {
println!("⚠️ Next.js project already exists!");
} else {
create_nextjs_project(&paths);
}
}
3 => {
if status.has_git {
println!("⚠️ Git is already initialized!");
} else {
init_git(&paths);
}
}
4 => {
if status.has_github {
println!("⚠️ GitHub repository already exists!");
} else {
if !status.has_git {
println!("⚠️ Git not initialized. Initializing first...");
init_git(&paths);
}
create_github_repo(&paths);
}
}
5 => {
if !command_exists("vercel") {
println!("❌ Vercel CLI not found. Install it with: npm install -g vercel");
return;
}
if status.has_vercel {
if get_yes_no("⚠️ Project might already be deployed. Deploy again?") {
deploy_to_vercel(&paths);
}
} else {
deploy_to_vercel(&paths);
}
}
6 => {
println!("👋 Goodbye!");
exit(0);
}
_ => unreachable!(),
}
}
fn run_full_workflow(paths: ProjectPaths) {
println!("\n🚀 Initializing project: {}", paths.project_name);
println!("📁 Location: {}\n", paths.project_path.display());
// Check if directory exists
if paths.project_path.exists() {
println!("📁 Project directory already exists.");
} else {
println!("📁 Creating project directory...");
fs::create_dir_all(&paths.project_path).unwrap();
}
let status = check_project_status(&paths);
// Next.js setup
if status.has_nextjs {
println!("⚠️ Next.js project already exists, skipping creation.");
} else if !create_nextjs_project(&paths) {
exit(1);
}
// Git initialization
if status.has_git {
println!("⚠️ Git already initialized, skipping.");
} else if !init_git(&paths) {
exit(1);
}
// GitHub repository
if status.has_github {
println!("⚠️ GitHub repository already exists, skipping creation.");
} else if !create_github_repo(&paths) {
println!("⚠️ Continuing without GitHub repository...");
}
// Vercel deployment
if command_exists("vercel") {
if get_yes_no("\nWould you like to deploy this project to Vercel now?") {
deploy_to_vercel(&paths);
} else {
println!("\n🛑 Skipping Vercel deployment.\n");
}
} else {
println!("\n⚠️ Vercel CLI not found. Skipping deployment.");
println!(" Install with: npm install -g vercel\n");
}
println!("✅ Project '{}' setup complete!\n", paths.project_name);
}
fn check_project_status(paths: &ProjectPaths) -> ProjectStatus {
ProjectStatus {
has_nextjs: check_nextjs_project(&paths.project_path),
has_git: check_git_init(&paths.project_path),
has_github: check_github_repo(&paths.project_name),
has_vercel: check_vercel_deployment(&paths.project_path),
}
}
fn check_nextjs_project(path: &Path) -> bool {
path.join("package.json").exists() && path.join("next.config.js").exists()
}
fn check_git_init(path: &Path) -> bool {
path.join(".git").exists()
}
fn check_github_repo(project_name: &str) -> bool {
let output = Command::new("gh")
.args(&["repo", "view", project_name])
.output();
match output {
Ok(result) => result.status.success(),
Err(_) => false,
}
}
fn check_vercel_deployment(path: &Path) -> bool {
let output = Command::new("vercel")
.args(&["ls"])
.current_dir(path)
.output();
match output {
Ok(result) => {
let stdout = String::from_utf8_lossy(&result.stdout);
if let Some(project_name) = path.file_name() {
stdout.contains(&project_name.to_string_lossy().to_string())
} else {
false
}
}
Err(_) => false,
}
}
fn create_nextjs_project(paths: &ProjectPaths) -> bool {
println!("\n🚀 Creating Next.js project: {}", paths.project_name);
let status = Command::new("npx")
.args(&["create-next-app@latest", "./"])
.current_dir(&paths.project_path)
.status();
match status {
Ok(exit_status) if exit_status.success() => {
println!("✅ Next.js project created successfully!");
true
}
_ => {
println!("❌ Failed to create Next.js project.");
false
}
}
}
fn init_git(paths: &ProjectPaths) -> bool {
println!("\n📦 Initializing Git repository...");
let commands = vec![
vec!["git", "init"],
vec!["git", "add", "."],
vec!["git", "commit", "-m", "Initial Next.js setup"],
];
for cmd in commands {
let status = Command::new(cmd[0])
.args(&cmd[1..])
.current_dir(&paths.project_path)
.status();
if let Ok(exit_status) = status {
if !exit_status.success() {
println!("❌ Failed to initialize Git.");
return false;
}
} else {
println!("❌ Failed to initialize Git.");
return false;
}
}
println!("✅ Git initialized successfully!");
true
}
fn create_github_repo(paths: &ProjectPaths) -> bool {
println!("\n🐙 Creating GitHub repository...");
let is_public = get_yes_no("Should the GitHub repository be public?");
let visibility = if is_public { "--public" } else { "--private" };
let status = Command::new("gh")
.args(&["repo", "create", &paths.project_name, visibility, "--source=.", "--remote=origin", "--push"])
.current_dir(&paths.project_path)
.status();
match status {
Ok(exit_status) if exit_status.success() => {
println!("✅ GitHub repository created and pushed successfully!");
true
}
_ => {
println!("❌ Failed to create GitHub repository.");
false
}
}
}
fn deploy_to_vercel(paths: &ProjectPaths) -> bool {
println!("\n🌍 Deploying to Vercel...");
let output = Command::new("vercel")
.args(&["--yes", "--prod", "--confirm"])
.current_dir(&paths.project_path)
.output();
match output {
Ok(result) => {
let stdout = String::from_utf8_lossy(&result.stdout);
print!("{}", stdout);
// Extract URL
if let Some(url) = extract_vercel_url(&stdout) {
println!("\n✅ Successfully deployed to Vercel!");
println!("🔗 URL: {}", url);
} else {
println!("\n✅ Deployment completed!");
}
true
}
Err(_) => {
println!("❌ Failed to deploy to Vercel.");
false
}
}
}
fn extract_vercel_url(output: &str) -> Option<String> {
for line in output.lines() {
if line.contains("https://") && line.contains(".vercel.app") {
if let Some(start) = line.find("https://") {
let url_part = &line[start..];
if let Some(end) = url_part.find(|c: char| c.is_whitespace()) {
return Some(url_part[..end].to_string());
} else {
return Some(url_part.to_string());
}
}
}
}
None
}
fn command_exists(cmd: &str) -> bool {
Command::new("command")
.args(&["-v", cmd])
.output()
.map(|output| output.status.success())
.unwrap_or(false)
}
fn get_yes_no(prompt: &str) -> bool {
loop {
print!("{} (y/n): ", prompt);
io::stdout().flush().unwrap();
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
let input = input.trim().to_lowercase();
match input.as_str() {
"y" | "yes" => return true,
"n" | "no" => return false,
_ => println!("❌ Invalid input. Please enter 'y' or 'n'."),
}
}
}
fn get_menu_choice(min: u32, max: u32) -> u32 {
loop {
print!("\nEnter your choice ({}-{}): ", min, max);
io::stdout().flush().unwrap();
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
match input.trim().parse::<u32>() {
Ok(choice) if choice >= min && choice <= max => return choice,
_ => println!("❌ Invalid choice. Please enter a number between {} and {}.", min, max),
}
}
}