angreal 2.8.6

Angreal is a tool for templating projects and associated processes to provide a consistent developer experience across multiple projects.
Documentation
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
//! Shell completion support for Angreal
//!
//! Provides auto-installing shell completion for bash and zsh with:
//! - Real-time task discovery
//! - Template suggestions from GitHub
//! - Automatic setup on first run

use anyhow::{Context, Result};
use std::env;
use std::fs;
use std::path::PathBuf;
use std::process::Command;

pub mod bash;
pub mod templates;
pub mod zsh;

/// Supported shells for completion
#[derive(Debug, Clone, PartialEq)]
pub enum Shell {
    Bash,
    Zsh,
    Unknown(String),
}

impl Shell {
    /// Detect the current shell from environment
    pub fn detect() -> Self {
        // Check SHELL environment variable
        if let Ok(shell_path) = env::var("SHELL") {
            if shell_path.contains("bash") {
                return Shell::Bash;
            } else if shell_path.contains("zsh") {
                return Shell::Zsh;
            }
        }

        // Fallback: check parent process name
        if let Ok(output) = Command::new("ps")
            .args(["-p", &std::process::id().to_string(), "-o", "comm="])
            .output()
        {
            let comm = String::from_utf8_lossy(&output.stdout);
            if comm.contains("bash") {
                return Shell::Bash;
            } else if comm.contains("zsh") {
                return Shell::Zsh;
            }
        }

        Shell::Unknown("unknown".to_string())
    }

    /// Get the name of this shell
    pub fn name(&self) -> &str {
        match self {
            Shell::Bash => "bash",
            Shell::Zsh => "zsh",
            Shell::Unknown(name) => name,
        }
    }
}

/// Configuration for shell completion
pub struct CompletionConfig {
    pub shell: Shell,
    pub install_path: PathBuf,
    pub completion_script: String,
}

impl CompletionConfig {
    /// Create completion config for detected shell
    pub fn for_current_shell() -> Result<Self> {
        let shell = Shell::detect();
        let home = env::var("HOME").context("HOME environment variable not set")?;

        let (install_path, completion_script) = match shell {
            Shell::Bash => {
                let path = PathBuf::from(&home)
                    .join(".bash_completion.d")
                    .join("angreal");
                let script = bash::generate_completion_script();
                (path, script)
            }
            Shell::Zsh => {
                // Try to find zsh completion directory
                let zsh_dir = find_zsh_completion_dir(&home)?;
                let path = zsh_dir.join("_angreal");
                let script = zsh::generate_completion_script();
                (path, script)
            }
            Shell::Unknown(_) => {
                anyhow::bail!("Unsupported shell for completion: {}", shell.name());
            }
        };

        Ok(CompletionConfig {
            shell,
            install_path,
            completion_script,
        })
    }

    /// Check if completion is already installed
    pub fn is_installed(&self) -> bool {
        self.install_path.exists()
    }

    /// Install completion script
    pub fn install(&self) -> Result<()> {
        // Create parent directory if it doesn't exist
        if let Some(parent) = self.install_path.parent() {
            fs::create_dir_all(parent)
                .with_context(|| format!("Failed to create directory: {}", parent.display()))?;
        }

        // Write completion script
        fs::write(&self.install_path, &self.completion_script).with_context(|| {
            format!(
                "Failed to write completion script to: {}",
                self.install_path.display()
            )
        })?;

        // Add source line to shell rc file if needed
        self.ensure_sourced()?;

        Ok(())
    }

    /// Ensure completion script is sourced in shell rc file
    fn ensure_sourced(&self) -> Result<()> {
        let home = env::var("HOME").context("HOME environment variable not set")?;

        let rc_file = match self.shell {
            Shell::Bash => {
                // Try .bashrc first, then .bash_profile
                let bashrc = PathBuf::from(&home).join(".bashrc");
                if bashrc.exists() {
                    bashrc
                } else {
                    PathBuf::from(&home).join(".bash_profile")
                }
            }
            Shell::Zsh => PathBuf::from(&home).join(".zshrc"),
            Shell::Unknown(_) => return Ok(()), // Skip for unknown shells
        };

        // Check if sourcing is already present
        if rc_file.exists() {
            let content = fs::read_to_string(&rc_file)?;

            match self.shell {
                Shell::Bash => {
                    let source_line = format!("source {}", self.install_path.display());
                    if !content.contains(&source_line) {
                        // Add source line for bash
                        let mut new_content = content;
                        new_content.push('\n');
                        new_content
                            .push_str(&format!("# Angreal shell completion\n{}\n", source_line));
                        fs::write(&rc_file, new_content)?;
                    }
                }
                Shell::Zsh => {
                    // Check if we need to add custom completion directory to fpath
                    let completion_dir = self.install_path.parent().unwrap();
                    let is_custom_dir = !completion_dir.to_str().unwrap().contains("/usr/")
                        && !completion_dir.to_str().unwrap().contains("/etc/");

                    if is_custom_dir {
                        let fpath_line = format!("fpath=({} $fpath)", completion_dir.display());
                        if !content.contains(&fpath_line) {
                            let mut new_content = content;
                            new_content.push('\n');
                            new_content
                                .push_str(&format!("# Angreal shell completion\n{}\n", fpath_line));

                            // Also ensure compinit is called
                            if !new_content.contains("autoload -U compinit")
                                || !new_content.contains("compinit")
                            {
                                new_content.push_str("autoload -U compinit && compinit\n");
                            }

                            fs::write(&rc_file, new_content)?;
                        }
                    }
                }
                Shell::Unknown(_) => return Ok(()),
            }
        }

        Ok(())
    }
}

/// Find zsh completion directory
fn find_zsh_completion_dir(home: &str) -> Result<PathBuf> {
    // Common zsh completion directories in order of preference
    let candidates = vec![
        PathBuf::from(home).join(".zsh").join("completions"),
        PathBuf::from(home).join(".oh-my-zsh").join("completions"),
        PathBuf::from("/usr/local/share/zsh/site-functions"),
        PathBuf::from("/usr/share/zsh/site-functions"),
        // Fallback: create in home directory
        PathBuf::from(home).join(".zsh_completions"),
    ];

    for candidate in &candidates {
        if candidate.exists() && candidate.is_dir() {
            // Check if we can write to this directory
            let test_file = candidate.join(".angreal_test_write");
            if fs::write(&test_file, "test").is_ok() {
                // Clean up test file
                let _ = fs::remove_file(&test_file);
                return Ok(candidate.clone());
            }
        }
    }

    // Create the fallback directory
    let fallback = &candidates[candidates.len() - 1];
    fs::create_dir_all(fallback).with_context(|| {
        format!(
            "Failed to create zsh completion directory: {}",
            fallback.display()
        )
    })?;

    Ok(fallback.clone())
}

/// Check if completion should be auto-installed
pub fn should_auto_install() -> bool {
    // Check if user has explicitly disabled auto-install
    if env::var("ANGREAL_NO_AUTO_COMPLETION").is_ok() {
        return false;
    }

    // Check if completion is already installed
    if let Ok(config) = CompletionConfig::for_current_shell() {
        !config.is_installed()
    } else {
        false
    }
}

/// Auto-install completion if appropriate
pub fn auto_install_completion() -> Result<()> {
    if !should_auto_install() {
        return Ok(());
    }

    let config = CompletionConfig::for_current_shell()
        .context("Failed to detect shell for completion setup")?;

    println!(
        "🚀 Setting up shell completion for {}...",
        config.shell.name()
    );

    config
        .install()
        .with_context(|| format!("Failed to install {} completion", config.shell.name()))?;

    println!("✅ Shell completion installed! Restart your shell or run:");
    match config.shell {
        Shell::Bash => println!("   source ~/.bashrc"),
        Shell::Zsh => println!("   source ~/.zshrc"),
        Shell::Unknown(_) => {}
    }

    Ok(())
}

/// Force install completion for specific shell or detected shell
pub fn force_install_completion(shell: Option<&str>) -> Result<()> {
    let config = if let Some(shell_name) = shell {
        // Create config for specific shell
        let shell_type = match shell_name {
            "bash" => Shell::Bash,
            "zsh" => Shell::Zsh,
            _ => anyhow::bail!("Unsupported shell: {}. Use 'bash' or 'zsh'", shell_name),
        };

        let home = env::var("HOME").context("HOME environment variable not set")?;
        let (install_path, completion_script) = match shell_type {
            Shell::Bash => {
                let path = PathBuf::from(&home)
                    .join(".bash_completion.d")
                    .join("angreal");
                let script = bash::generate_completion_script();
                (path, script)
            }
            Shell::Zsh => {
                let zsh_dir = find_zsh_completion_dir(&home)?;
                let path = zsh_dir.join("_angreal");
                let script = zsh::generate_completion_script();
                (path, script)
            }
            Shell::Unknown(_) => unreachable!(),
        };

        CompletionConfig {
            shell: shell_type,
            install_path,
            completion_script,
        }
    } else {
        // Use detected shell
        CompletionConfig::for_current_shell()
            .context("Failed to detect shell for completion setup")?
    };

    println!(
        "Installing {} completion{}...",
        config.shell.name(),
        if config.is_installed() {
            " (reinstalling)"
        } else {
            ""
        }
    );

    config
        .install()
        .with_context(|| format!("Failed to install {} completion", config.shell.name()))?;

    println!("{} completion installed!", config.shell.name());
    println!("Restart your shell or run:");
    match config.shell {
        Shell::Bash => println!("   source ~/.bashrc"),
        Shell::Zsh => println!("   source ~/.zshrc"),
        Shell::Unknown(_) => {}
    }

    Ok(())
}

/// Uninstall completion for specific shell or detected shell
pub fn uninstall_completion(shell: Option<&str>) -> Result<()> {
    let configs = if let Some(shell_name) = shell {
        // Uninstall specific shell
        let shell_type = match shell_name {
            "bash" => Shell::Bash,
            "zsh" => Shell::Zsh,
            _ => anyhow::bail!("Unsupported shell: {}. Use 'bash' or 'zsh'", shell_name),
        };

        let home = env::var("HOME").context("HOME environment variable not set")?;
        let install_path = match shell_type {
            Shell::Bash => PathBuf::from(&home)
                .join(".bash_completion.d")
                .join("angreal"),
            Shell::Zsh => {
                let zsh_dir = find_zsh_completion_dir(&home)?;
                zsh_dir.join("_angreal")
            }
            Shell::Unknown(_) => unreachable!(),
        };

        vec![(shell_type, install_path)]
    } else {
        // Uninstall from all common locations
        let home = env::var("HOME").context("HOME environment variable not set")?;
        vec![
            (
                Shell::Bash,
                PathBuf::from(&home)
                    .join(".bash_completion.d")
                    .join("angreal"),
            ),
            (
                Shell::Zsh,
                PathBuf::from(&home)
                    .join(".zsh_completions")
                    .join("_angreal"),
            ),
            (
                Shell::Zsh,
                PathBuf::from(&home)
                    .join(".zsh")
                    .join("completions")
                    .join("_angreal"),
            ),
        ]
    };

    let mut removed_any = false;
    for (shell_type, path) in configs {
        if path.exists() {
            fs::remove_file(&path)
                .with_context(|| format!("Failed to remove completion file: {}", path.display()))?;
            println!("✅ Removed {} completion", shell_type.name());
            removed_any = true;
        }
    }

    if !removed_any {
        println!("No completion files found to remove.");
    }

    Ok(())
}

/// Show completion installation status
pub fn show_completion_status() -> Result<()> {
    let home = env::var("HOME").context("HOME environment variable not set")?;

    // Check common completion locations
    let locations = vec![
        (
            "Bash",
            PathBuf::from(&home)
                .join(".bash_completion.d")
                .join("angreal"),
        ),
        (
            "Zsh (local)",
            PathBuf::from(&home)
                .join(".zsh_completions")
                .join("_angreal"),
        ),
        (
            "Zsh (oh-my-zsh)",
            PathBuf::from(&home)
                .join(".oh-my-zsh")
                .join("completions")
                .join("_angreal"),
        ),
        (
            "Zsh (system)",
            PathBuf::from("/usr/local/share/zsh/site-functions").join("_angreal"),
        ),
    ];

    println!("Shell completion status:");
    let mut found_any = false;

    for (name, path) in locations {
        if path.exists() {
            println!("{} - installed at {}", name, path.display());
            found_any = true;
        } else {
            println!("{} - not found", name);
        }
    }

    if !found_any {
        println!(
            "\nNo completion files found. Run 'angreal completion install' to set up completion."
        );
    }

    // Show current shell
    let current_shell = Shell::detect();
    println!("\nCurrent shell: {}", current_shell.name());

    Ok(())
}

/// Generate completions for current command line
pub fn generate_completions(args: &[String]) -> Result<Vec<String>> {
    let mut completions = Vec::new();

    // Filter out empty strings from args (shell completion often adds them)
    let filtered_args: Vec<String> = args.iter().filter(|s| !s.is_empty()).cloned().collect();

    // If we're completing the first argument after 'angreal'
    if filtered_args.is_empty() {
        // Always add built-in commands
        completions.push("alias".to_string());
        completions.push("tree".to_string());

        // Add 'init' command if not in angreal project
        if crate::utils::is_angreal_project().is_err() {
            completions.push("init".to_string());
        } else {
            // Add discovered tasks (top-level commands and groups)
            completions.extend(get_available_tasks()?);
        }
        return Ok(completions);
    }

    // Handle 'init' command completion
    if filtered_args.len() == 1 && filtered_args[0] == "init" {
        // Complete template names
        completions.extend(templates::get_template_suggestions()?);
        return Ok(completions);
    }

    // Handle 'alias' command completion
    if !filtered_args.is_empty() && filtered_args[0] == "alias" {
        if filtered_args.len() == 1 {
            // Complete subcommands for 'alias'
            completions.extend(vec![
                "create".to_string(),
                "remove".to_string(),
                "list".to_string(),
            ]);
            return Ok(completions);
        } else if filtered_args.len() == 2 && filtered_args[1] == "remove" {
            // Complete with existing aliases for 'alias remove'
            if let Ok(aliases) = crate::list_entrypoints() {
                completions.extend(aliases);
            }
            return Ok(completions);
        } else if filtered_args.len() >= 2 {
            // For 'alias create' or 'alias list', no further completion needed
            return Ok(completions);
        }
    }

    // Handle 'completion' command completion
    if !filtered_args.is_empty() && filtered_args[0] == "completion" {
        if filtered_args.len() == 1 {
            // Complete subcommands for 'completion'
            completions.extend(vec![
                "install".to_string(),
                "uninstall".to_string(),
                "status".to_string(),
            ]);
            return Ok(completions);
        } else if filtered_args.len() == 2
            && (filtered_args[1] == "install" || filtered_args[1] == "uninstall")
        {
            // Complete with shell options for 'completion install/uninstall'
            completions.extend(vec!["bash".to_string(), "zsh".to_string()]);
            return Ok(completions);
        } else if filtered_args.len() >= 2 {
            // For 'completion status' or other completed commands, no further completion needed
            return Ok(completions);
        }
    }

    // Handle nested command completion for angreal projects
    if crate::utils::is_angreal_project().is_ok() {
        // For any args, try to get nested completions
        // This will handle cases like "angreal test <TAB>" or "angreal group subgroup <TAB>"
        completions.extend(get_nested_command_completions(&filtered_args)?);
    }

    Ok(completions)
}

/// Get available tasks in current project
fn get_available_tasks() -> Result<Vec<String>> {
    let mut tasks = Vec::new();

    // Load tasks (this triggers the same discovery as normal angreal execution)
    let angreal_path = crate::utils::is_angreal_project()?;
    let task_files = crate::utils::get_task_files(angreal_path)?;

    // Load task files to register commands
    for task_file in task_files {
        let _ = crate::utils::load_python(task_file); // Ignore errors for completion
    }

    // Get registered tasks
    for (_, task) in crate::task::ANGREAL_TASKS.lock().unwrap().iter() {
        if task.group.is_none() || task.group.as_ref().unwrap().is_empty() {
            // Top-level task - add the task name directly
            tasks.push(task.name.clone());
        } else {
            // Grouped task - add only the top-level group name for initial completion
            // The nested completion will handle deeper levels
            if let Some(groups) = &task.group {
                if let Some(first_group) = groups.first() {
                    tasks.push(first_group.name.clone());
                }
            }
        }
    }

    // Remove duplicates and sort
    tasks.sort();
    tasks.dedup();

    Ok(tasks)
}

/// Get completions for nested commands
fn get_nested_command_completions(args: &[String]) -> Result<Vec<String>> {
    use crate::builder::command_tree::CommandNode;

    let mut completions = Vec::new();

    // Build command tree from registered tasks
    let mut root = CommandNode::new_group("root".to_string(), None);

    // Load tasks
    let angreal_path = crate::utils::is_angreal_project()?;
    let task_files = crate::utils::get_task_files(angreal_path)?;

    // Load task files to register commands
    for task_file in task_files {
        let _ = crate::utils::load_python(task_file); // Ignore errors for completion
    }

    // Add all registered tasks to the command tree
    for (_, task) in crate::task::ANGREAL_TASKS.lock().unwrap().iter() {
        root.add_command(task.clone());
    }

    // Navigate the command tree based on the current args
    let mut current_node = &root;
    for arg in args {
        if let Some(child) = current_node.children.get(arg) {
            current_node = child;
        } else {
            // If we can't find this path, return empty completions
            return Ok(completions);
        }
    }

    // Return the names of all children at the current level
    for (name, child) in &current_node.children {
        // Only suggest groups if they have children, or commands if they're leaf nodes
        if !child.children.is_empty() || child.command.is_some() {
            completions.push(name.clone());
        }
    }

    // Sort for consistent output
    completions.sort();

    Ok(completions)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_shell_detection() {
        let shell = Shell::detect();
        // Should detect some shell or unknown
        match shell {
            Shell::Bash | Shell::Zsh | Shell::Unknown(_) => {}
        }
    }

    #[test]
    fn test_should_auto_install() {
        // Should not crash
        let _ = should_auto_install();
    }
}