Skip to main content

purple_ssh/ssh_config/
model.rs

1use std::path::PathBuf;
2
3/// Represents the entire SSH config file as a sequence of elements.
4/// Preserves the original structure for round-trip fidelity.
5#[derive(Debug, Clone)]
6pub struct SshConfigFile {
7    pub elements: Vec<ConfigElement>,
8    pub path: PathBuf,
9    /// Whether the original file used CRLF line endings.
10    pub crlf: bool,
11}
12
13/// An Include directive that references other config files.
14#[derive(Debug, Clone)]
15#[allow(dead_code)]
16pub struct IncludeDirective {
17    pub raw_line: String,
18    pub pattern: String,
19    pub resolved_files: Vec<IncludedFile>,
20}
21
22/// A file resolved from an Include directive.
23#[derive(Debug, Clone)]
24pub struct IncludedFile {
25    pub path: PathBuf,
26    pub elements: Vec<ConfigElement>,
27}
28
29/// A single element in the config file.
30#[derive(Debug, Clone)]
31pub enum ConfigElement {
32    /// A Host block: the "Host <pattern>" line plus all indented directives.
33    HostBlock(HostBlock),
34    /// A comment, blank line, or global directive not inside a Host block.
35    GlobalLine(String),
36    /// An Include directive referencing other config files (read-only).
37    Include(IncludeDirective),
38}
39
40/// A parsed Host block with its directives.
41#[derive(Debug, Clone)]
42pub struct HostBlock {
43    /// The host alias/pattern (the value after "Host").
44    pub host_pattern: String,
45    /// The original raw "Host ..." line for faithful reproduction.
46    pub raw_host_line: String,
47    /// Parsed directives inside this block.
48    pub directives: Vec<Directive>,
49}
50
51/// A directive line inside a Host block.
52#[derive(Debug, Clone)]
53pub struct Directive {
54    /// The directive key (e.g., "HostName", "User", "Port").
55    pub key: String,
56    /// The directive value.
57    pub value: String,
58    /// The original raw line (preserves indentation, inline comments).
59    pub raw_line: String,
60    /// Whether this is a comment-only or blank line inside a host block.
61    pub is_non_directive: bool,
62}
63
64/// Convenience view for the TUI — extracted from a HostBlock.
65#[derive(Debug, Clone, Default)]
66pub struct HostEntry {
67    pub alias: String,
68    pub hostname: String,
69    pub user: String,
70    pub port: u16,
71    pub identity_file: String,
72    pub proxy_jump: String,
73    /// If this host comes from an included file, the file path.
74    pub source_file: Option<PathBuf>,
75    /// Tags from purple:tags comment.
76    pub tags: Vec<String>,
77}
78
79impl HostEntry {
80    /// Build the SSH command string for this host (e.g. "ssh myserver").
81    pub fn ssh_command(&self) -> String {
82        format!("ssh {}", self.alias)
83    }
84}
85
86impl HostBlock {
87    /// Index of the first trailing blank line (for inserting content before separators).
88    fn content_end(&self) -> usize {
89        let mut pos = self.directives.len();
90        while pos > 0 {
91            if self.directives[pos - 1].is_non_directive
92                && self.directives[pos - 1].raw_line.trim().is_empty()
93            {
94                pos -= 1;
95            } else {
96                break;
97            }
98        }
99        pos
100    }
101
102    /// Remove and return trailing blank lines.
103    fn pop_trailing_blanks(&mut self) -> Vec<Directive> {
104        let end = self.content_end();
105        self.directives.drain(end..).collect()
106    }
107
108    /// Ensure exactly one trailing blank line.
109    fn ensure_trailing_blank(&mut self) {
110        self.pop_trailing_blanks();
111        self.directives.push(Directive {
112            key: String::new(),
113            value: String::new(),
114            raw_line: String::new(),
115            is_non_directive: true,
116        });
117    }
118
119    /// Detect indentation used by existing directives (falls back to "  ").
120    fn detect_indent(&self) -> String {
121        for d in &self.directives {
122            if !d.is_non_directive && !d.raw_line.is_empty() {
123                let trimmed = d.raw_line.trim_start();
124                let indent_len = d.raw_line.len() - trimmed.len();
125                if indent_len > 0 {
126                    return d.raw_line[..indent_len].to_string();
127                }
128            }
129        }
130        "  ".to_string()
131    }
132
133    /// Extract tags from purple:tags comment in directives.
134    pub fn tags(&self) -> Vec<String> {
135        for d in &self.directives {
136            if d.is_non_directive {
137                let trimmed = d.raw_line.trim();
138                if let Some(rest) = trimmed.strip_prefix("# purple:tags ") {
139                    return rest
140                        .split(',')
141                        .map(|t| t.trim().to_string())
142                        .filter(|t| !t.is_empty())
143                        .collect();
144                }
145            }
146        }
147        Vec::new()
148    }
149
150    /// Set tags on a host block. Replaces existing purple:tags comment or adds one.
151    pub fn set_tags(&mut self, tags: &[String]) {
152        let indent = self.detect_indent();
153        self.directives.retain(|d| {
154            !(d.is_non_directive && d.raw_line.trim().starts_with("# purple:tags"))
155        });
156        if !tags.is_empty() {
157            let pos = self.content_end();
158            self.directives.insert(
159                pos,
160                Directive {
161                    key: String::new(),
162                    value: String::new(),
163                    raw_line: format!("{}# purple:tags {}", indent, tags.join(",")),
164                    is_non_directive: true,
165                },
166            );
167        }
168    }
169
170    /// Extract a convenience HostEntry view from this block.
171    pub fn to_host_entry(&self) -> HostEntry {
172        let mut entry = HostEntry {
173            alias: self.host_pattern.clone(),
174            port: 22,
175            ..Default::default()
176        };
177        for d in &self.directives {
178            if d.is_non_directive {
179                continue;
180            }
181            match d.key.to_lowercase().as_str() {
182                "hostname" => entry.hostname = d.value.clone(),
183                "user" => entry.user = d.value.clone(),
184                "port" => entry.port = d.value.parse().unwrap_or(22),
185                "identityfile" => entry.identity_file = d.value.clone(),
186                "proxyjump" => entry.proxy_jump = d.value.clone(),
187                _ => {}
188            }
189        }
190        entry.tags = self.tags();
191        entry
192    }
193}
194
195impl SshConfigFile {
196    /// Get all host entries as convenience views (including from Include files).
197    pub fn host_entries(&self) -> Vec<HostEntry> {
198        Self::collect_host_entries(&self.elements)
199    }
200
201    /// Collect all resolved Include file paths (recursively).
202    pub fn include_paths(&self) -> Vec<PathBuf> {
203        let mut paths = Vec::new();
204        Self::collect_include_paths(&self.elements, &mut paths);
205        paths
206    }
207
208    fn collect_include_paths(elements: &[ConfigElement], paths: &mut Vec<PathBuf>) {
209        for e in elements {
210            if let ConfigElement::Include(include) = e {
211                for file in &include.resolved_files {
212                    paths.push(file.path.clone());
213                    Self::collect_include_paths(&file.elements, paths);
214                }
215            }
216        }
217    }
218
219    /// Recursively collect host entries from a list of elements.
220    fn collect_host_entries(elements: &[ConfigElement]) -> Vec<HostEntry> {
221        let mut entries = Vec::new();
222        for e in elements {
223            match e {
224                ConfigElement::HostBlock(block) => {
225                    // Skip wildcard/multi patterns (*, ?, space-separated)
226                    if block.host_pattern.contains('*')
227                        || block.host_pattern.contains('?')
228                        || block.host_pattern.contains(' ')
229                    {
230                        continue;
231                    }
232                    entries.push(block.to_host_entry());
233                }
234                ConfigElement::Include(include) => {
235                    for file in &include.resolved_files {
236                        let mut file_entries = Self::collect_host_entries(&file.elements);
237                        for entry in &mut file_entries {
238                            if entry.source_file.is_none() {
239                                entry.source_file = Some(file.path.clone());
240                            }
241                        }
242                        entries.extend(file_entries);
243                    }
244                }
245                ConfigElement::GlobalLine(_) => {}
246            }
247        }
248        entries
249    }
250
251    /// Check if a host alias already exists (including in Include files).
252    /// Walks the element tree directly without building HostEntry structs.
253    pub fn has_host(&self, alias: &str) -> bool {
254        Self::has_host_in_elements(&self.elements, alias)
255    }
256
257    fn has_host_in_elements(elements: &[ConfigElement], alias: &str) -> bool {
258        for e in elements {
259            match e {
260                ConfigElement::HostBlock(block) => {
261                    if block.host_pattern == alias {
262                        return true;
263                    }
264                }
265                ConfigElement::Include(include) => {
266                    for file in &include.resolved_files {
267                        if Self::has_host_in_elements(&file.elements, alias) {
268                            return true;
269                        }
270                    }
271                }
272                ConfigElement::GlobalLine(_) => {}
273            }
274        }
275        false
276    }
277
278    /// Add a new host entry to the config.
279    pub fn add_host(&mut self, entry: &HostEntry) {
280        let block = Self::entry_to_block(entry);
281        // Add a blank line separator if the file isn't empty and doesn't already end with one
282        if !self.elements.is_empty() && !self.last_element_has_trailing_blank() {
283            self.elements
284                .push(ConfigElement::GlobalLine(String::new()));
285        }
286        self.elements.push(ConfigElement::HostBlock(block));
287    }
288
289    /// Check if the last element already ends with a blank line.
290    fn last_element_has_trailing_blank(&self) -> bool {
291        match self.elements.last() {
292            Some(ConfigElement::HostBlock(block)) => block
293                .directives
294                .last()
295                .is_some_and(|d| d.is_non_directive && d.raw_line.trim().is_empty()),
296            Some(ConfigElement::GlobalLine(line)) => line.trim().is_empty(),
297            _ => false,
298        }
299    }
300
301    /// Update an existing host entry by alias.
302    /// Merges changes into the existing block, preserving unknown directives.
303    pub fn update_host(&mut self, old_alias: &str, entry: &HostEntry) {
304        for element in &mut self.elements {
305            if let ConfigElement::HostBlock(block) = element {
306                if block.host_pattern == old_alias {
307                    // Update host pattern
308                    block.host_pattern = entry.alias.clone();
309                    block.raw_host_line = format!("Host {}", entry.alias);
310
311                    // Merge known directives (update existing, add missing, remove empty)
312                    Self::upsert_directive(block, "HostName", &entry.hostname);
313                    Self::upsert_directive(block, "User", &entry.user);
314                    if entry.port != 22 {
315                        Self::upsert_directive(block, "Port", &entry.port.to_string());
316                    } else {
317                        // Remove explicit Port 22 (it's the default)
318                        block
319                            .directives
320                            .retain(|d| d.is_non_directive || d.key.to_lowercase() != "port");
321                    }
322                    Self::upsert_directive(block, "IdentityFile", &entry.identity_file);
323                    Self::upsert_directive(block, "ProxyJump", &entry.proxy_jump);
324                    return;
325                }
326            }
327        }
328    }
329
330    /// Update a directive in-place, add it if missing, or remove it if value is empty.
331    fn upsert_directive(block: &mut HostBlock, key: &str, value: &str) {
332        if value.is_empty() {
333            block
334                .directives
335                .retain(|d| d.is_non_directive || d.key.to_lowercase() != key.to_lowercase());
336            return;
337        }
338        let indent = block.detect_indent();
339        for d in &mut block.directives {
340            if !d.is_non_directive && d.key.to_lowercase() == key.to_lowercase() {
341                d.value = value.to_string();
342                // Preserve original key casing for round-trip fidelity
343                d.raw_line = format!("{}{} {}", indent, d.key, value);
344                return;
345            }
346        }
347        // Not found — insert before trailing blanks
348        let pos = block.content_end();
349        block.directives.insert(
350            pos,
351            Directive {
352                key: key.to_string(),
353                value: value.to_string(),
354                raw_line: format!("{}{} {}", indent, key, value),
355                is_non_directive: false,
356            },
357        );
358    }
359
360    /// Set tags on a host block by alias.
361    pub fn set_host_tags(&mut self, alias: &str, tags: &[String]) {
362        for element in &mut self.elements {
363            if let ConfigElement::HostBlock(block) = element {
364                if block.host_pattern == alias {
365                    block.set_tags(tags);
366                    return;
367                }
368            }
369        }
370    }
371
372    /// Delete a host entry by alias.
373    #[allow(dead_code)]
374    pub fn delete_host(&mut self, alias: &str) {
375        self.elements.retain(|e| match e {
376            ConfigElement::HostBlock(block) => block.host_pattern != alias,
377            _ => true,
378        });
379        // Collapse consecutive blank lines left by deletion
380        self.elements.dedup_by(|a, b| {
381            matches!(
382                (&*a, &*b),
383                (ConfigElement::GlobalLine(x), ConfigElement::GlobalLine(y))
384                if x.trim().is_empty() && y.trim().is_empty()
385            )
386        });
387    }
388
389    /// Delete a host and return the removed element and its position for undo.
390    /// Does NOT collapse blank lines so the position stays valid for re-insertion.
391    pub fn delete_host_undoable(&mut self, alias: &str) -> Option<(ConfigElement, usize)> {
392        let pos = self.elements.iter().position(|e| {
393            matches!(e, ConfigElement::HostBlock(b) if b.host_pattern == alias)
394        })?;
395        let element = self.elements.remove(pos);
396        Some((element, pos))
397    }
398
399    /// Insert a host block at a specific position (for undo).
400    pub fn insert_host_at(&mut self, element: ConfigElement, position: usize) {
401        let pos = position.min(self.elements.len());
402        self.elements.insert(pos, element);
403    }
404
405    /// Swap two host blocks in the config by alias. Returns true if swap was performed.
406    #[allow(dead_code)]
407    pub fn swap_hosts(&mut self, alias_a: &str, alias_b: &str) -> bool {
408        let pos_a = self.elements.iter().position(|e| {
409            matches!(e, ConfigElement::HostBlock(b) if b.host_pattern == alias_a)
410        });
411        let pos_b = self.elements.iter().position(|e| {
412            matches!(e, ConfigElement::HostBlock(b) if b.host_pattern == alias_b)
413        });
414        if let (Some(a), Some(b)) = (pos_a, pos_b) {
415            let (first, second) = (a.min(b), a.max(b));
416
417            // Strip trailing blanks from both blocks before swap
418            if let ConfigElement::HostBlock(block) = &mut self.elements[first] {
419                block.pop_trailing_blanks();
420            }
421            if let ConfigElement::HostBlock(block) = &mut self.elements[second] {
422                block.pop_trailing_blanks();
423            }
424
425            // Swap
426            self.elements.swap(first, second);
427
428            // Add trailing blank to first block (separator between the two)
429            if let ConfigElement::HostBlock(block) = &mut self.elements[first] {
430                block.ensure_trailing_blank();
431            }
432
433            // Add trailing blank to second only if not the last element
434            if second < self.elements.len() - 1 {
435                if let ConfigElement::HostBlock(block) = &mut self.elements[second] {
436                    block.ensure_trailing_blank();
437                }
438            }
439
440            return true;
441        }
442        false
443    }
444
445    /// Convert a HostEntry into a new HostBlock with clean formatting.
446    fn entry_to_block(entry: &HostEntry) -> HostBlock {
447        let mut directives = Vec::new();
448
449        if !entry.hostname.is_empty() {
450            directives.push(Directive {
451                key: "HostName".to_string(),
452                value: entry.hostname.clone(),
453                raw_line: format!("  HostName {}", entry.hostname),
454                is_non_directive: false,
455            });
456        }
457        if !entry.user.is_empty() {
458            directives.push(Directive {
459                key: "User".to_string(),
460                value: entry.user.clone(),
461                raw_line: format!("  User {}", entry.user),
462                is_non_directive: false,
463            });
464        }
465        if entry.port != 22 {
466            directives.push(Directive {
467                key: "Port".to_string(),
468                value: entry.port.to_string(),
469                raw_line: format!("  Port {}", entry.port),
470                is_non_directive: false,
471            });
472        }
473        if !entry.identity_file.is_empty() {
474            directives.push(Directive {
475                key: "IdentityFile".to_string(),
476                value: entry.identity_file.clone(),
477                raw_line: format!("  IdentityFile {}", entry.identity_file),
478                is_non_directive: false,
479            });
480        }
481        if !entry.proxy_jump.is_empty() {
482            directives.push(Directive {
483                key: "ProxyJump".to_string(),
484                value: entry.proxy_jump.clone(),
485                raw_line: format!("  ProxyJump {}", entry.proxy_jump),
486                is_non_directive: false,
487            });
488        }
489
490        HostBlock {
491            host_pattern: entry.alias.clone(),
492            raw_host_line: format!("Host {}", entry.alias),
493            directives,
494        }
495    }
496}