rich-prompt 0.2.0

A Rust CLI tool for rich prompts with file and directory selection.
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
use log::{debug, info, warn};
use std::collections::{HashMap, HashSet};
use std::fs;
use std::io::{BufRead, Read};
use std::path::{Path, PathBuf};

fn parse_gitignore(root: &str) -> anyhow::Result<HashSet<String>> {
    let gitignore_path = Path::new(root).join(".gitignore");
    let mut patterns = HashSet::new();

    if gitignore_path.exists() && gitignore_path.is_file() {
        debug!("Parsing .gitignore file at: {}", gitignore_path.display());
        let file = fs::File::open(gitignore_path)?;
        let reader = std::io::BufReader::new(file);

        for line in reader.lines() {
            let line = line?;
            let trimmed = line.trim();

            if !trimmed.is_empty() && !trimmed.starts_with('#') {
                if trimmed.starts_with('!') && trimmed.len() > 1 {
                    patterns.insert(format!("!{}", trimmed[1..].trim()));
                } else {
                    patterns.insert(trimmed.to_string());
                }
            }
        }

        info!("Loaded {} patterns from .gitignore", patterns.len());
    } else {
        debug!("No .gitignore file found at: {}", gitignore_path.display());
    }

    Ok(patterns)
}

fn should_ignore_by_gitignore(
    path: &Path,
    root: &Path,
    gitignore_patterns: &HashSet<String>,
) -> bool {
    if gitignore_patterns.is_empty() {
        return false;
    }

    let rel_path = path.strip_prefix(root).unwrap_or(path);
    let path_str = rel_path.to_string_lossy();
    let is_dir = path.is_dir();

    let mut matched_negated = false;
    let mut should_ignore = false;

    for pattern in gitignore_patterns {
        let is_negated = pattern.starts_with('!');

        if is_negated {
            let negated_pattern = &pattern[1..]; // Remove the '!' prefix
            if matches_gitignore_pattern(path_str.as_ref(), negated_pattern, is_dir) {
                debug!(
                    "Path {} matches negated gitignore pattern: {}",
                    path_str, pattern
                );
                matched_negated = true;
            }
            continue;
        }

        if !matched_negated && matches_gitignore_pattern(path_str.as_ref(), pattern, is_dir) {
            debug!("Path {} matches gitignore pattern: {}", path_str, pattern);
            should_ignore = true;
        }
    }

    if matched_negated {
        return false;
    }

    should_ignore
}

fn matches_gitignore_pattern(path: &str, pattern: &str, is_dir: bool) -> bool {
    if pattern.ends_with('/') && !is_dir {
        return false;
    }

    let clean_pattern = pattern.trim_end_matches('/');

    if !clean_pattern.contains('*') {
        if path == clean_pattern
            || path.starts_with(&format!("{}/", clean_pattern))
            || path.ends_with(&format!("/{}", clean_pattern))
        {
            return true;
        }
    }

    if clean_pattern.contains('*') {
        if clean_pattern.starts_with('*') && clean_pattern.ends_with('*') {
            let inner = clean_pattern.trim_matches('*');
            return path.contains(inner);
        } else if clean_pattern.starts_with('*') {
            let suffix = clean_pattern.trim_start_matches('*');
            return path.ends_with(suffix);
        } else if clean_pattern.ends_with('*') {
            let prefix = clean_pattern.trim_end_matches('*');
            return path.starts_with(prefix);
        } else if clean_pattern.contains('*') {
            let parts: Vec<&str> = clean_pattern.split('*').collect();
            if parts.len() >= 2 {
                return path.starts_with(parts[0])
                    && path.ends_with(parts[parts.len() - 1])
                    && parts[1..parts.len() - 1]
                        .iter()
                        .all(|part| path.contains(part));
            }
        }
    }

    if clean_pattern.starts_with('/') {
        let pattern_without_slash = clean_pattern.trim_start_matches('/');
        return path == pattern_without_slash
            || path.starts_with(&format!("{}/", pattern_without_slash));
    }

    path.contains(clean_pattern)
}

pub fn list_code_files(
    root: &str,
    extensions: &[&str],
    exclude_patterns: &[&str],
) -> anyhow::Result<Vec<PathBuf>> {
    info!("Listing code files in: {}", root);
    debug!("Extensions: {:?}", extensions);
    debug!("Exclude patterns: {:?}", exclude_patterns);

    let mut result = Vec::new();

    for entry in walkdir::WalkDir::new(root)
        .into_iter()
        .filter_entry(|e| {
            let path = e.path().to_string_lossy();
            let exclude_match = exclude_patterns.is_empty()
                || !exclude_patterns.iter().any(|pat| path.contains(pat));

            exclude_match
        })
        .filter_map(Result::ok)
    {
        if entry.file_type().is_dir() || entry.file_type().is_symlink() {
            continue;
        }

        let path = entry.path();

        let ext_matches = if extensions.is_empty() {
            true
        } else {
            path.extension()
                .and_then(|e| e.to_str())
                .map(|e| {
                    extensions
                        .iter()
                        .any(|ext| ext.trim_start_matches('.') == e)
                })
                .unwrap_or(false)
        };

        let excluded = !exclude_patterns.is_empty()
            && exclude_patterns
                .iter()
                .any(|pattern| path.to_string_lossy().contains(pattern));

        if ext_matches && !excluded {
            debug!("Found matching file: {}", path.display());
            result.push(path.to_path_buf());
        }
    }

    info!("Found {} matching files", result.len());
    Ok(result)
}

pub fn list_code_files_with_gitignore(
    root: &str,
    extensions: &[&str],
    exclude_patterns: &[&str],
    exclude_version_control_dir: &str,
    apply_dot_git_ignore: bool,
) -> anyhow::Result<Vec<PathBuf>> {
    info!("Listing code files in: {} with gitignore support", root);
    debug!("Extensions: {:?}", extensions);
    debug!("Exclude patterns: {:?}", exclude_patterns);
    debug!("Exclude VCS dir: {}", exclude_version_control_dir);
    debug!("Apply .gitignore: {}", apply_dot_git_ignore);

    let mut result = Vec::new();
    let mut all_exclude_patterns = exclude_patterns.to_vec();

    // Add version control directory to exclude patterns
    if !exclude_version_control_dir.is_empty() {
        all_exclude_patterns.push(exclude_version_control_dir);
    }

    // Parse .gitignore if needed
    let gitignore_patterns = if apply_dot_git_ignore {
        parse_gitignore(root)?
    } else {
        HashSet::new()
    };

    let root_path = Path::new(root);

    for entry in walkdir::WalkDir::new(root)
        .into_iter()
        .filter_entry(|e| {
            let path = e.path().to_string_lossy();
            let exclude_match = all_exclude_patterns.is_empty()
                || !all_exclude_patterns.iter().any(|pat| path.contains(pat));

            let gitignore_match = if apply_dot_git_ignore {
                !should_ignore_by_gitignore(e.path(), root_path, &gitignore_patterns)
            } else {
                true
            };

            exclude_match && gitignore_match
        })
        .filter_map(Result::ok)
    {
        if entry.file_type().is_dir() || entry.file_type().is_symlink() {
            continue;
        }

        let path = entry.path();

        let ext_matches = if extensions.is_empty() {
            true
        } else {
            path.extension()
                .and_then(|e| e.to_str())
                .map(|e| {
                    extensions
                        .iter()
                        .any(|ext| ext.trim_start_matches('.') == e)
                })
                .unwrap_or(false)
        };

        if ext_matches {
            debug!("Found matching file: {}", path.display());
            result.push(path.to_path_buf());
        }
    }

    info!("Found {} matching files", result.len());
    Ok(result)
}

pub fn read_file_contents(path: &Path) -> anyhow::Result<String> {
    if !path.exists() {
        warn!("File does not exist: {}", path.display());
        return Ok(String::new());
    }
    if !path.is_file() {
        warn!("Not a file: {}", path.display());
        return Ok(String::new());
    }
    if path.metadata()?.len() == 0 {
        debug!("File is empty: {}", path.display());
        return Ok(String::new());
    }

    debug!("Reading file contents: {}", path.display());
    let mut file = fs::File::open(path)?;
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;
    debug!("Read {} bytes from file", contents.len());
    Ok(contents)
}

pub fn generate_file_map(
    root: &str,
    exclude_patterns: &[&str],
    exclude_version_control_dir: &str,
    apply_dot_git_ignore: bool,
) -> anyhow::Result<String> {
    info!("Generating file map for: {}", root);
    let mut output = String::new();

    let mut all_exclude_patterns = exclude_patterns.to_vec();

    if !exclude_version_control_dir.is_empty() {
        all_exclude_patterns.push(exclude_version_control_dir);
    }

    let gitignore_patterns = if apply_dot_git_ignore {
        parse_gitignore(root)?
    } else {
        HashSet::new()
    };

    let dir_map = list_dir_structure_with_gitignore(
        root,
        &all_exclude_patterns,
        &gitignore_patterns,
        apply_dot_git_ignore,
    )?;

    for (dir, files) in &dir_map {
        output.push_str(&format!("{}\n", dir));
        for file in files {
            output.push_str(&format!("├── {}\n", file));
        }
    }

    debug!("Generated file map with {} directories", dir_map.len());
    Ok(output)
}

pub fn list_dir_structure_with_gitignore(
    root: &str,
    exclude_patterns: &[&str],
    gitignore_patterns: &HashSet<String>,
    apply_dot_git_ignore: bool,
) -> anyhow::Result<HashMap<String, Vec<String>>> {
    debug!(
        "Listing directory structure in: {} with gitignore support",
        root
    );
    let mut dir_map = HashMap::new();
    let root_path = Path::new(root);

    for entry in walkdir::WalkDir::new(root)
        .into_iter()
        .filter_entry(|e| {
            let path = e.path().to_string_lossy();
            let exclude_match = exclude_patterns.is_empty()
                || !exclude_patterns.iter().any(|pat| path.contains(pat));

            let gitignore_match = if apply_dot_git_ignore {
                !should_ignore_by_gitignore(e.path(), root_path, gitignore_patterns)
            } else {
                true
            };

            exclude_match && gitignore_match
        })
        .filter_map(Result::ok)
    {
        if entry.file_type().is_dir() {
            let path = entry.path().to_string_lossy().to_string();
            dir_map.entry(path).or_insert_with(Vec::new);
        } else if entry.file_type().is_file() {
            let path = entry.path().to_string_lossy().to_string();
            let parent = entry.path().parent().unwrap_or_else(|| Path::new(""));
            dir_map
                .entry(parent.to_string_lossy().to_string())
                .or_insert_with(Vec::new)
                .push(path);
        }
    }

    debug!("Found {} directories in structure", dir_map.len());
    Ok(dir_map)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs::File;
    use std::io::Write;
    use tempfile::TempDir;

    #[test]
    fn test_read_file_contents() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("test.txt");

        {
            let mut file = File::create(&file_path).unwrap();
            writeln!(file, "Test content").unwrap();
        }

        let contents = read_file_contents(&file_path).unwrap();
        assert_eq!(contents, "Test content\n");
    }

    #[test]
    fn test_read_nonexistent_file() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("nonexistent.txt");

        let contents = read_file_contents(&file_path).unwrap();
        assert_eq!(contents, "");
    }

    #[test]
    fn test_parse_gitignore() {
        let temp_dir = TempDir::new().unwrap();
        let root = temp_dir.path().to_string_lossy().to_string();
        let gitignore_path = temp_dir.path().join(".gitignore");

        {
            let mut file = File::create(&gitignore_path).unwrap();
            writeln!(file, "# Comment line").unwrap();
            writeln!(file, "node_modules/").unwrap();
            writeln!(file, "*.log").unwrap();
            writeln!(file, "build").unwrap();
            writeln!(file, "").unwrap();
            writeln!(file, "/dist").unwrap();
            writeln!(file, "temp*").unwrap();
            writeln!(file, "!important.log").unwrap();
            writeln!(file, "**/coverage").unwrap();
        }

        let patterns = parse_gitignore(&root).unwrap();

        assert_eq!(patterns.len(), 7);
        assert!(patterns.contains("node_modules/"));
        assert!(patterns.contains("*.log"));
        assert!(patterns.contains("build"));
        assert!(patterns.contains("/dist"));
        assert!(patterns.contains("temp*"));
        assert!(patterns.contains("!important.log"));
        assert!(patterns.contains("**/coverage"));
    }

    #[test]
    fn test_matches_gitignore_pattern() {
        assert!(matches_gitignore_pattern("test.log", "*.log", false));
        assert!(matches_gitignore_pattern("logs/test.log", "*.log", false));
        assert!(matches_gitignore_pattern(
            "node_modules/package.json",
            "node_modules/",
            true
        ));
        assert!(!matches_gitignore_pattern(
            "node_modules.txt",
            "node_modules/",
            false
        ));
        assert!(matches_gitignore_pattern("dist/main.js", "/dist", false));
        assert!(matches_gitignore_pattern("temp", "temp*", false));
        assert!(matches_gitignore_pattern("temporary.txt", "temp*", false));
        assert!(matches_gitignore_pattern(
            "src/coverage/report.html",
            "**/coverage",
            false
        ));
        assert!(matches_gitignore_pattern("abc.xyz", "*.xy*", false));
        assert!(matches_gitignore_pattern("a/b/c.txt", "**/c.txt", false));

        assert!(!matches_gitignore_pattern(
            "node_modules.txt",
            "node_modules/",
            false
        ));
        assert!(matches_gitignore_pattern(
            "node_modules",
            "node_modules/",
            true
        ));
    }

    #[test]
    fn test_should_ignore_by_gitignore() {
        let root = Path::new("/test");
        let mut patterns = HashSet::new();

        patterns.insert("node_modules/".to_string());
        patterns.insert("*.log".to_string());
        patterns.insert("build".to_string());
        patterns.insert("/dist".to_string());
        patterns.insert("temp*".to_string());
        patterns.insert("!important.log".to_string());

        assert!(should_ignore_by_gitignore(
            &Path::new("/test/node_modules/file.js"),
            root,
            &patterns
        ));
        assert!(should_ignore_by_gitignore(
            &Path::new("/test/logs/server.log"),
            root,
            &patterns
        ));
        assert!(should_ignore_by_gitignore(
            &Path::new("/test/build/index.js"),
            root,
            &patterns
        ));
        assert!(should_ignore_by_gitignore(
            &Path::new("/test/dist/main.js"),
            root,
            &patterns
        ));
        assert!(should_ignore_by_gitignore(
            &Path::new("/test/temporary.txt"),
            root,
            &patterns
        ));

        assert!(!should_ignore_by_gitignore(
            &Path::new("/test/logs/important.log"),
            root,
            &patterns
        ));

        assert!(!should_ignore_by_gitignore(
            &Path::new("/test/src/index.js"),
            root,
            &patterns
        ));
        assert!(!should_ignore_by_gitignore(
            &Path::new("/test/package.json"),
            root,
            &patterns
        ));
    }
}