projm 0.11.0

CLI for projm — project organizer and navigator
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
use anyhow::Result;
use colored::Colorize;

use crate::main_cli::BlueprintSubcommands;
use projm_core::blueprints::{Blueprint, BlueprintsStore};
use projm_core::organize;

pub fn run(sub: Option<BlueprintSubcommands>) -> Result<()> {
    match sub {
        Some(BlueprintSubcommands::Add) => add()?,
        Some(BlueprintSubcommands::List) => list()?,
        Some(BlueprintSubcommands::Run { name }) => run_blueprint(name)?,
        Some(BlueprintSubcommands::Edit { name }) => edit(name)?,
        Some(BlueprintSubcommands::Delete { name }) => delete(name)?,
        None => run_blueprint(None)?,
    }
    Ok(())
}

fn add() -> Result<()> {
    use dialoguer::{theme::ColorfulTheme, Input};

    let theme = ColorfulTheme::default();
    println!();
    println!("{}", "  ✨ Add New Project Blueprint ✨".bold().cyan());
    println!();

    let name: String = Input::with_theme(&theme)
        .with_prompt("Blueprint Name (e.g. better-t-stack)")
        .validate_with(|input: &String| -> Result<(), &str> {
            if input.trim().is_empty() {
                return Err("Name cannot be empty.");
            }
            if !input
                .chars()
                .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
            {
                return Err("Name must be alphanumeric, dashes, or underscores.");
            }
            Ok(())
        })
        .interact()?;

    let mut store = BlueprintsStore::load()?;
    if store.blueprints.iter().any(|b| b.name == name) {
        println!("  {} Blueprint '{}' already exists.", "".red(), name);
        return Ok(());
    }

    let command: String = Input::with_theme(&theme)
        .with_prompt("Command Template (use {name} as optional project name placeholder)")
        .validate_with(|input: &String| -> Result<(), &str> {
            if input.trim().is_empty() {
                return Err("Command cannot be empty.");
            }
            Ok(())
        })
        .interact()?;

    store.blueprints.push(Blueprint {
        name: name.clone(),
        command: command.clone(),
    });
    store.save()?;

    println!();
    println!(
        "  {} Saved blueprint '{}' successfully!",
        "".green(),
        name.bold()
    );
    println!();

    Ok(())
}

fn list() -> Result<()> {
    let store = BlueprintsStore::load()?;
    println!();
    if store.blueprints.is_empty() {
        println!("  No blueprints saved yet. Run `projm blueprint add` to save one.");
        println!();
        return Ok(());
    }

    println!(
        "  {:<20}  {}",
        "blueprint".bold().underline(),
        "command template".bold().underline(),
    );
    println!("  {}", "".repeat(70).dimmed());

    for bp in &store.blueprints {
        println!("  {:<20}  {}", bp.name.cyan().bold(), bp.command);
    }
    println!();
    Ok(())
}

fn run_blueprint(name: Option<String>) -> Result<()> {
    use dialoguer::{theme::ColorfulTheme, Confirm, Input, Select};
    use std::process::Command;

    let theme = ColorfulTheme::default();
    let store = BlueprintsStore::load()?;

    let blueprint = match name {
        Some(ref n) => store.blueprints.iter().find(|b| b.name == *n).cloned(),
        None => {
            if store.blueprints.is_empty() {
                println!();
                println!("  No blueprints saved yet. Run `projm blueprint add` to save one.");
                println!();
                return Ok(());
            }
            let items: Vec<String> = store
                .blueprints
                .iter()
                .map(|b| format!("{}  ({})", b.name.bold(), b.command.dimmed()))
                .collect();

            let selection = Select::with_theme(&theme)
                .with_prompt("Choose a blueprint to run")
                .items(&items)
                .default(0)
                .interact()?;
            Some(store.blueprints[selection].clone())
        }
    };

    let blueprint = match blueprint {
        Some(bp) => bp,
        None => {
            println!("  {} Blueprint not found.", "".red());
            return Ok(());
        }
    };

    println!();
    println!("  Running blueprint: {}", blueprint.name.cyan().bold());
    println!();

    let has_name_placeholder = blueprint.command.contains("{name}");

    let project_name: Option<String> = if has_name_placeholder {
        let name: String = Input::with_theme(&theme)
            .with_prompt("Enter name for your new project")
            .validate_with(|input: &String| -> Result<(), &str> {
                if input.trim().is_empty() {
                    return Err("Project name cannot be empty.");
                }
                if !input
                    .chars()
                    .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
                {
                    return Err("Project name must be alphanumeric, dashes, or underscores.");
                }
                Ok(())
            })
            .interact()?;
        Some(name)
    } else {
        None
    };

    let resolved_command = match &project_name {
        Some(name) => blueprint.command.replace("{name}", name),
        None => blueprint.command.clone(),
    };

    println!();
    println!("  Executing command: {}", resolved_command.bold().yellow());
    println!("  {}", "".repeat(70).dimmed());
    println!();

    // Determine command execution shell
    #[cfg(unix)]
    let mut child = Command::new("sh")
        .arg("-c")
        .arg(&resolved_command)
        .spawn()?;

    #[cfg(windows)]
    let mut child = Command::new("cmd")
        .arg("/C")
        .arg(&resolved_command)
        .spawn()?;

    let status = child.wait()?;

    println!();
    println!("  {}", "".repeat(70).dimmed());

    if !status.success() {
        println!();
        println!(
            "  {} Command failed with exit status: {}",
            "".red(),
            status
        );
        println!();
        return Ok(());
    }

    println!();
    println!("  {} Command finished successfully!", "".green());
    println!();

    // Check if the directory exists in the CWD
    let project_name_str = project_name.clone().unwrap_or_default();
    let new_project_path = std::env::current_dir()?.join(&project_name_str);
    if !project_name_str.is_empty() && new_project_path.exists() && new_project_path.is_dir() {
        let organize = Confirm::with_theme(&theme)
            .with_prompt(format!(
                "Automatically run 'projm organize' on '{}'?",
                project_name_str.cyan()
            ))
            .default(true)
            .interact()?;

        if organize {
            println!();
            println!("  Organising project '{}'...", project_name_str);
            match organize::organize_single(&new_project_path) {
                Ok(dest) => {
                    println!(
                        "  {} Successfully organized! → {}",
                        "".green(),
                        dest.display().to_string().cyan()
                    );
                }
                Err(e) => {
                    println!("  {} Failed to organize project: {}", "".red(), e);
                }
            }
            println!();
        }
    }

    Ok(())
}

fn delete(name: Option<String>) -> Result<()> {
    use dialoguer::{theme::ColorfulTheme, Confirm, Select};

    let theme = ColorfulTheme::default();
    let mut store = BlueprintsStore::load()?;

    if store.blueprints.is_empty() {
        println!();
        println!("  No blueprints saved yet. Run `projm blueprint add` to save one.");
        println!();
        return Ok(());
    }

    // Resolve which blueprint to delete
    let blueprint_name = match name {
        Some(n) => {
            if !store.blueprints.iter().any(|b| b.name == n) {
                println!("  {} Blueprint '{}' not found.", "".red(), n);
                return Ok(());
            }
            n
        }
        None => {
            let items: Vec<String> = store
                .blueprints
                .iter()
                .map(|b| format!("{}  ({})", b.name.bold(), b.command.dimmed()))
                .collect();

            let selection = Select::with_theme(&theme)
                .with_prompt("Choose a blueprint to delete")
                .items(&items)
                .default(0)
                .interact()?;
            store.blueprints[selection].name.clone()
        }
    };

    println!();
    let ok = Confirm::with_theme(&theme)
        .with_prompt(format!(
            "Are you sure you want to delete blueprint '{}'?",
            blueprint_name.cyan()
        ))
        .default(false)
        .interact()?;

    if ok {
        store.blueprints.retain(|b| b.name != blueprint_name);
        store.save()?;
        println!();
        println!(
            "  {} Blueprint '{}' deleted successfully!",
            "".green(),
            blueprint_name.bold()
        );
        println!();
    } else {
        println!();
        println!("  {} Deletion aborted.", "".red());
        println!();
    }

    Ok(())
}

fn edit(name: Option<String>) -> Result<()> {
    use dialoguer::{theme::ColorfulTheme, Input, Select};

    let theme = ColorfulTheme::default();
    let mut store = BlueprintsStore::load()?;

    if store.blueprints.is_empty() {
        println!();
        println!("  No blueprints saved yet. Run `projm blueprint add` to save one.");
        println!();
        return Ok(());
    }

    // Resolve which blueprint to edit
    let index = match name {
        Some(ref n) => match store.blueprints.iter().position(|b| b.name == *n) {
            Some(idx) => idx,
            None => {
                println!("  {} Blueprint '{}' not found.", "".red(), n);
                return Ok(());
            }
        },
        None => {
            let items: Vec<String> = store
                .blueprints
                .iter()
                .map(|b| format!("{}  ({})", b.name.bold(), b.command.dimmed()))
                .collect();

            Select::with_theme(&theme)
                .with_prompt("Choose a blueprint to edit")
                .items(&items)
                .default(0)
                .interact()?
        }
    };

    let old_name = store.blueprints[index].name.clone();
    let old_command = store.blueprints[index].command.clone();

    println!();
    println!(
        "{}",
        format!("  ✨ Edit Blueprint: {}", old_name.bold()).cyan()
    );
    println!();

    let new_name: String = Input::with_theme(&theme)
        .with_prompt("Blueprint Name")
        .with_initial_text(old_name.clone())
        .validate_with(|input: &String| -> Result<(), &str> {
            if input.trim().is_empty() {
                return Err("Name cannot be empty.");
            }
            if !input
                .chars()
                .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
            {
                return Err("Name must be alphanumeric, dashes, or underscores.");
            }
            Ok(())
        })
        .interact()?;

    // Check conflict if name changed
    if new_name != old_name && store.blueprints.iter().any(|b| b.name == new_name) {
        println!("  {} Blueprint '{}' already exists.", "".red(), new_name);
        return Ok(());
    }

    let new_command: String = Input::with_theme(&theme)
        .with_prompt("Command Template")
        .with_initial_text(old_command)
        .validate_with(|input: &String| -> Result<(), &str> {
            if input.trim().is_empty() {
                return Err("Command cannot be empty.");
            }
            Ok(())
        })
        .interact()?;

    store.blueprints[index].name = new_name.clone();
    store.blueprints[index].command = new_command;
    store.save()?;

    println!();
    println!(
        "  {} Blueprint '{}' updated successfully!",
        "".green(),
        new_name.bold()
    );
    println!();

    Ok(())
}