Skip to main content

ggen_core/domain/shell/
completion.rs

1//! Shell completion generation and installation - Domain layer
2//!
3//! This module provides pure business logic for generating and installing shell
4//! completion scripts. It's independent of CLI presentation concerns.
5
6use crate::utils::error::Result;
7use std::path::PathBuf;
8
9/// Supported shell types
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum ShellType {
12    Bash,
13    Zsh,
14    Fish,
15    PowerShell,
16}
17
18impl std::str::FromStr for ShellType {
19    type Err = String;
20
21    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
22        match s.to_lowercase().as_str() {
23            "bash" => Ok(Self::Bash),
24            "zsh" => Ok(Self::Zsh),
25            "fish" => Ok(Self::Fish),
26            "powershell" | "pwsh" => Ok(Self::PowerShell),
27            _ => Err(format!("Invalid shell type: {}", s)),
28        }
29    }
30}
31
32impl ShellType {
33    /// Get shell name as string
34    pub fn as_str(&self) -> &'static str {
35        match self {
36            Self::Bash => "bash",
37            Self::Zsh => "zsh",
38            Self::Fish => "fish",
39            Self::PowerShell => "powershell",
40        }
41    }
42
43    /// Get default completion directory for the shell
44    pub fn default_completion_dir(&self) -> Option<PathBuf> {
45        match self {
46            Self::Bash => {
47                // Try XDG_DATA_HOME first, then fallback to ~/.bash_completion.d
48                if let Ok(xdg_data) = std::env::var("XDG_DATA_HOME") {
49                    Some(PathBuf::from(xdg_data).join("bash-completion/completions"))
50                } else if let Ok(home) = std::env::var("HOME") {
51                    Some(PathBuf::from(home).join(".bash_completion.d"))
52                } else {
53                    None
54                }
55            }
56            Self::Zsh => {
57                // Try XDG_DATA_HOME first, then fallback to ~/.zfunc
58                if let Ok(xdg_data) = std::env::var("XDG_DATA_HOME") {
59                    Some(PathBuf::from(xdg_data).join("zsh/site-functions"))
60                } else if let Ok(home) = std::env::var("HOME") {
61                    Some(PathBuf::from(home).join(".zfunc"))
62                } else {
63                    None
64                }
65            }
66            Self::Fish => {
67                // Try XDG_CONFIG_HOME first, then fallback to ~/.config/fish
68                if let Ok(xdg_config) = std::env::var("XDG_CONFIG_HOME") {
69                    Some(PathBuf::from(xdg_config).join("fish").join("completions"))
70                } else if let Ok(home) = std::env::var("HOME") {
71                    Some(
72                        PathBuf::from(home)
73                            .join(".config")
74                            .join("fish")
75                            .join("completions"),
76                    )
77                } else {
78                    None
79                }
80            }
81            Self::PowerShell => {
82                // PowerShell completion is typically in profile directory
83                if let Ok(profile) = std::env::var("PROFILE") {
84                    Some(PathBuf::from(profile).parent()?.to_path_buf())
85                } else {
86                    None
87                }
88            }
89        }
90    }
91}
92
93/// Result of completion generation
94#[derive(Debug, Clone)]
95pub struct CompletionResult {
96    pub script: String,
97    pub shell: ShellType,
98}
99
100/// Trait for generating shell completions
101pub trait CompletionGenerator {
102    /// Generate completion script for the specified shell
103    fn generate(&self, shell: ShellType) -> Result<CompletionResult>;
104}
105
106/// Trait for installing shell completions
107pub trait CompletionInstaller {
108    /// Install completion script to default location
109    fn install(&self, result: &CompletionResult, force: bool) -> Result<PathBuf>;
110
111    /// Install completion script to custom location
112    fn install_to(&self, result: &CompletionResult, path: PathBuf, force: bool) -> Result<PathBuf>;
113}
114
115/// Trait for listing available shells
116pub trait ShellLister {
117    /// List all supported shells
118    fn list_supported(&self) -> Vec<ShellType>;
119
120    /// Check if a shell is installed on the system
121    fn is_installed(&self, shell: ShellType) -> bool;
122}
123
124// NOTE: Completion generation is delegated to the CLI layer
125// This domain layer only defines the contracts/traits.
126// The actual implementation using clap_complete lives in the CLI layer.
127
128/// Default implementation for installing completions
129pub struct FileSystemCompletionInstaller;
130
131impl CompletionInstaller for FileSystemCompletionInstaller {
132    fn install(&self, result: &CompletionResult, force: bool) -> Result<PathBuf> {
133        let dir = result.shell.default_completion_dir().ok_or_else(|| {
134            crate::utils::error::Error::new("Could not determine completion directory")
135        })?;
136
137        let filename = format!("ggen.{}", result.shell.as_str());
138        let path = dir.join(filename);
139
140        self.install_to(result, path, force)
141    }
142
143    fn install_to(&self, result: &CompletionResult, path: PathBuf, force: bool) -> Result<PathBuf> {
144        // Check if file exists and force is not set
145        if path.exists() && !force {
146            return Err(crate::utils::error::Error::new(&format!(
147                "Completion file already exists: {}. Use --force to overwrite",
148                path.display()
149            )));
150        }
151
152        // Create parent directory if it doesn't exist
153        if let Some(parent) = path.parent() {
154            std::fs::create_dir_all(parent)?;
155        }
156
157        // Write completion script
158        std::fs::write(&path, &result.script)?;
159
160        Ok(path)
161    }
162}
163
164/// Default implementation for listing shells
165pub struct SystemShellLister;
166
167impl ShellLister for SystemShellLister {
168    fn list_supported(&self) -> Vec<ShellType> {
169        vec![
170            ShellType::Bash,
171            ShellType::Zsh,
172            ShellType::Fish,
173            ShellType::PowerShell,
174        ]
175    }
176
177    fn is_installed(&self, shell: ShellType) -> bool {
178        // Try to find shell executable
179        let shell_cmd = match shell {
180            ShellType::Bash => "bash",
181            ShellType::Zsh => "zsh",
182            ShellType::Fish => "fish",
183            ShellType::PowerShell => {
184                if cfg!(windows) {
185                    "pwsh.exe"
186                } else {
187                    "pwsh"
188                }
189            }
190        };
191
192        // Use which/where to check if shell exists
193        std::process::Command::new(if cfg!(windows) { "where" } else { "which" })
194            .arg(shell_cmd)
195            .output()
196            .map(|output| output.status.success())
197            .unwrap_or(false)
198    }
199}
200
201#[cfg(test)]
202mod tests {
203    use super::*;
204    use std::str::FromStr;
205
206    #[test]
207    fn test_shell_type_from_str() {
208        assert_eq!(ShellType::from_str("bash"), Ok(ShellType::Bash));
209        assert_eq!(ShellType::from_str("BASH"), Ok(ShellType::Bash));
210        assert_eq!(ShellType::from_str("zsh"), Ok(ShellType::Zsh));
211        assert_eq!(ShellType::from_str("fish"), Ok(ShellType::Fish));
212        assert_eq!(ShellType::from_str("powershell"), Ok(ShellType::PowerShell));
213        assert_eq!(ShellType::from_str("pwsh"), Ok(ShellType::PowerShell));
214        assert!(ShellType::from_str("invalid").is_err());
215    }
216
217    #[test]
218    fn test_shell_type_as_str() {
219        assert_eq!(ShellType::Bash.as_str(), "bash");
220        assert_eq!(ShellType::Zsh.as_str(), "zsh");
221        assert_eq!(ShellType::Fish.as_str(), "fish");
222        assert_eq!(ShellType::PowerShell.as_str(), "powershell");
223    }
224
225    #[test]
226    fn test_system_shell_lister_lists_all() {
227        let lister = SystemShellLister;
228        let shells = lister.list_supported();
229        assert_eq!(shells.len(), 4);
230        assert!(shells.contains(&ShellType::Bash));
231        assert!(shells.contains(&ShellType::Zsh));
232        assert!(shells.contains(&ShellType::Fish));
233        assert!(shells.contains(&ShellType::PowerShell));
234    }
235}