aprender-shell 0.33.0

AI-powered shell completion trained on your history
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
//! Shell history file parsing

use std::fs::File;
use std::io::Read;
use std::path::PathBuf;

/// Parser for shell history files
pub struct HistoryParser;

impl HistoryParser {
    pub fn new() -> Self {
        Self
    }

    /// Auto-detect the shell history file
    pub fn find_history_file() -> Option<PathBuf> {
        let home = dirs::home_dir()?;

        // Try in order of preference
        let candidates = [
            home.join(".zsh_history"),
            home.join(".bash_history"),
            home.join(".local/share/fish/fish_history"),
            home.join(".history"),
        ];

        candidates.into_iter().find(|p| p.exists())
    }

    /// Parse a history file into commands
    pub fn parse_file(&self, path: &PathBuf) -> std::io::Result<Vec<String>> {
        let mut file = File::open(path)?;
        let mut bytes = Vec::new();
        file.read_to_end(&mut bytes)?;

        // Convert to string, replacing invalid UTF-8 with replacement char
        let content = String::from_utf8_lossy(&bytes);

        let mut commands = Vec::new();

        for line in content.lines() {
            if let Some(cmd) = self.parse_line(line) {
                if !cmd.is_empty() && self.is_valid_command(&cmd) {
                    commands.push(cmd);
                }
            }
        }

        Ok(commands)
    }

    /// Parse a single history line (handles zsh extended format)
    ///
    /// Handles:
    /// - ZSH extended format (`: timestamp:0;command`)
    /// - Fish format (`- cmd: command`)
    /// - Plain format (bash)
    /// - Comment stripping
    /// - Shell no-op filtering
    fn parse_line(&self, line: &str) -> Option<String> {
        let line = line.trim();

        if line.is_empty() {
            return None;
        }

        // Skip comment-only lines (issue #91)
        if line.starts_with('#') {
            return None;
        }

        // Skip shell no-ops (issue #91)
        // `: ` is a valid ZSH timestamp prefix, but `: ` followed by non-numeric is a no-op
        if line == ":"
            || (line.starts_with(": ") && !line.chars().nth(2).is_some_and(|c| c.is_ascii_digit()))
        {
            // Check if it's NOT a ZSH timestamp (starts with digit after ": ")
            if !line.starts_with(": ") || !line.chars().nth(2).is_some_and(|c| c.is_ascii_digit()) {
                return None;
            }
        }

        // ZSH extended history format: ": timestamp:0;command"
        if line.starts_with(": ") {
            if let Some(pos) = line.find(';') {
                let cmd = &line[pos + 1..];
                return Some(self.strip_inline_comment(cmd));
            }
        }

        // Fish history format: "- cmd: command"
        if let Some(cmd) = line.strip_prefix("- cmd: ") {
            return Some(self.strip_inline_comment(cmd));
        }

        // Plain format (bash) - strip inline comments
        Some(self.strip_inline_comment(line))
    }

    /// Strip inline comments from commands while preserving quoted strings
    ///
    /// # Examples
    /// - `git status # check` -> `git status`
    /// - `echo "hello #world"` -> `echo "hello #world"` (preserved in quotes)
    /// - `gh issue view #123` -> `gh issue view #123` (preserved - issue number)
    fn strip_inline_comment(&self, cmd: &str) -> String {
        let mut result = String::with_capacity(cmd.len());
        let mut in_single_quote = false;
        let mut in_double_quote = false;
        let chars: Vec<char> = cmd.chars().collect();

        let mut i = 0;
        while i < chars.len() {
            let ch = chars[i];
            let prev_char = if i > 0 { chars[i - 1] } else { '\0' };
            let next_char = chars.get(i + 1).copied();

            // Handle quote state
            if ch == '\'' && !in_double_quote && prev_char != '\\' {
                in_single_quote = !in_single_quote;
            } else if ch == '"' && !in_single_quote && prev_char != '\\' {
                in_double_quote = !in_double_quote;
            }

            // Check for inline comment (# preceded by whitespace, not in quotes)
            // BUT preserve #123 style issue numbers (# followed by digit)
            if ch == '#' && !in_single_quote && !in_double_quote && prev_char.is_whitespace() {
                // Check if # is followed by a digit (issue number like #123)
                if let Some(next) = next_char {
                    if next.is_ascii_digit() {
                        // This is an issue number, preserve it
                        result.push(ch);
                        i += 1;
                        continue;
                    }
                }
                // Found inline comment, stop here and trim trailing whitespace
                return result.trim_end().to_string();
            }

            result.push(ch);
            i += 1;
        }

        result.trim().to_string()
    }

    /// Filter out commands we don't want to learn
    fn is_valid_command(&self, cmd: &str) -> bool {
        // Skip very short commands
        if cmd.len() < 2 {
            return false;
        }

        // Skip malformed/incomplete commands (multiline artifacts)
        if self.is_malformed(cmd) {
            return false;
        }

        // Skip corrupted commands (missing spaces before flags)
        if self.has_corrupted_tokens(cmd) {
            return false;
        }

        // Skip commands with sensitive patterns
        let sensitive = [
            "password",
            "passwd",
            "secret",
            "token",
            "api_key",
            "AWS_SECRET",
            "GITHUB_TOKEN",
            "Authorization:",
        ];

        let cmd_lower = cmd.to_lowercase();
        for pattern in sensitive {
            if cmd_lower.contains(&pattern.to_lowercase()) {
                return false;
            }
        }

        // Skip history manipulation
        if cmd.starts_with("history") || cmd.starts_with("fc ") {
            return false;
        }

        true
    }

    /// Check for malformed commands (incomplete multiline, etc.)
    fn is_malformed(&self, cmd: &str) -> bool {
        let trimmed = cmd.trim();

        // Lone backslash or backslash with whitespace
        if trimmed == "\\" || trimmed.ends_with("\\ ") {
            return true;
        }

        // Incomplete brace/bracket patterns
        if trimmed.starts_with('}') || trimmed.starts_with(')') || trimmed.starts_with(']') {
            return true;
        }

        // Commands starting with flags are multiline continuation artifacts (issue #91)
        // e.g., "--context 3" from "git diff \n  --context 3"
        if trimmed.starts_with("--")
            || trimmed.starts_with('-')
                && trimmed
                    .chars()
                    .nth(1)
                    .is_some_and(|c| c.is_ascii_alphabetic())
        {
            return true;
        }

        false
    }

    /// Check for corrupted tokens like "commit-m" (missing space before flag)
    fn has_corrupted_tokens(&self, cmd: &str) -> bool {
        // Common subcommands that should never have flags directly attached
        let subcommands = [
            "commit", "checkout", "clone", "push", "pull", "merge", "rebase", "status", "add",
            "build", "run", "test", "install",
        ];

        for token in cmd.split_whitespace() {
            if let Some(dash_pos) = token.find('-') {
                if dash_pos > 0 && dash_pos < token.len() - 1 {
                    let before = &token[..dash_pos];
                    let after = &token[dash_pos + 1..];

                    // Pattern: subcommand-flag (e.g., "commit-m", "add-A")
                    if subcommands.contains(&before) && (after.len() <= 2 || after.starts_with('-'))
                    {
                        return true;
                    }
                }
            }
        }

        false
    }
}

impl Default for HistoryParser {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_parse_zsh_extended() {
        let parser = HistoryParser::new();
        let line = ": 1699900000:0;git status";
        assert_eq!(parser.parse_line(line), Some("git status".to_string()));
    }

    #[test]
    fn test_parse_bash() {
        let parser = HistoryParser::new();
        let line = "ls -la";
        assert_eq!(parser.parse_line(line), Some("ls -la".to_string()));
    }

    #[test]
    fn test_filter_sensitive() {
        let parser = HistoryParser::new();
        assert!(!parser.is_valid_command("export API_KEY=secret123"));
        assert!(!parser.is_valid_command("echo $PASSWORD"));
        assert!(parser.is_valid_command("git push origin main"));
    }

    #[test]
    fn test_filter_short() {
        let parser = HistoryParser::new();
        assert!(!parser.is_valid_command("l"));
        assert!(parser.is_valid_command("ls"));
    }

    // ==================== EXTREME TDD: Corrupted Command Filtering ====================

    #[test]
    fn test_filter_corrupted_commands() {
        let parser = HistoryParser::new();

        // Corrupted: missing space before flag
        assert!(
            !parser.is_valid_command("git commit-m test"),
            "Should reject 'commit-m' (missing space)"
        );
        assert!(
            !parser.is_valid_command("git add-A"),
            "Should reject 'add-A' (missing space)"
        );
        assert!(
            !parser.is_valid_command("cargo build-r"),
            "Should reject 'build-r' (missing space)"
        );

        // Valid: proper spacing
        assert!(
            parser.is_valid_command("git commit -m test"),
            "Should accept 'commit -m' (proper spacing)"
        );
        assert!(
            parser.is_valid_command("git add -A"),
            "Should accept 'add -A' (proper spacing)"
        );

        // Valid: legitimate hyphenated words
        assert!(
            parser.is_valid_command("git checkout feature-branch"),
            "Should accept 'feature-branch' (legitimate hyphen)"
        );
        assert!(
            parser.is_valid_command("npm install lodash-es"),
            "Should accept 'lodash-es' (package name)"
        );
    }

    #[test]
    fn test_filter_malformed_multiline() {
        let parser = HistoryParser::new();

        // ZSH sometimes captures incomplete multiline commands
        assert!(
            !parser.is_valid_command("}\\ "),
            "Should reject incomplete multiline"
        );
        assert!(
            !parser.is_valid_command("\\"),
            "Should reject lone backslash"
        );
    }

    // ==================== Issue #91: History Parsing Fixes ====================

    #[test]
    fn test_skip_comment_lines() {
        let parser = HistoryParser::new();
        assert!(parser.parse_line("# this is a comment").is_none());
        assert!(parser.parse_line("  # indented comment").is_none());
        assert!(parser.parse_line("#").is_none());
    }

    #[test]
    fn test_skip_shell_noops() {
        let parser = HistoryParser::new();
        assert!(parser.parse_line(":").is_none());
        assert!(parser.parse_line(": ignored text").is_none());
        assert!(parser.parse_line(":  spaces after").is_none());
    }

    #[test]
    fn test_preserve_zsh_timestamp_format() {
        let parser = HistoryParser::new();
        // ZSH timestamp format should NOT be treated as no-op
        assert_eq!(
            parser.parse_line(": 1699900000:0;git status"),
            Some("git status".to_string())
        );
    }

    #[test]
    fn test_strip_inline_comments() {
        let parser = HistoryParser::new();
        assert_eq!(
            parser.parse_line("git status # check status"),
            Some("git status".to_string())
        );
        assert_eq!(
            parser.parse_line("cargo build --release # optimized"),
            Some("cargo build --release".to_string())
        );
    }

    #[test]
    fn test_preserve_hash_in_arguments() {
        let parser = HistoryParser::new();
        // Issue numbers should be preserved (no space before #)
        assert_eq!(
            parser.parse_line("gh issue view #123"),
            Some("gh issue view #123".to_string())
        );
        // Quoted strings should preserve #
        assert_eq!(
            parser.parse_line(r#"echo "hello #world""#),
            Some(r#"echo "hello #world""#.to_string())
        );
        assert_eq!(
            parser.parse_line("echo '#hashtag'"),
            Some("echo '#hashtag'".to_string())
        );
    }

    #[test]
    fn test_inline_comment_with_quotes() {
        let parser = HistoryParser::new();
        // Comment after quoted string
        assert_eq!(
            parser.parse_line(r#"echo "hello" # comment"#),
            Some(r#"echo "hello""#.to_string())
        );
    }
}