git-ignore-tool 1.0.2

A command-line tool to add patterns to git ignore files
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
//! Core ignore file management functionality

use crate::{PatternIssue, PatternSeverity, PatternValidationLevel};
use anyhow::{bail, Context};
use std::{
    collections::HashSet,
    fs::{File, OpenOptions},
    io::{BufRead, BufReader, BufWriter, Write},
    path::Path,
};

/// Sanitize a pattern to prevent file corruption
fn sanitize_pattern(pattern: &str) -> String {
    // Remove newlines and carriage returns that could break file format
    pattern.replace(['\n', '\r'], "").trim().to_string()
}

/// Normalize a pattern for duplicate comparison.
///
/// A trailing slash only restricts a gitignore pattern to matching
/// directories; it doesn't change what directory it matches. Patterns that
/// differ solely by a trailing slash (e.g. "build" and "build/") are treated
/// as the same entry so one doesn't get added alongside the other.
fn normalize_pattern_for_dedup(pattern: &str) -> &str {
    if pattern == "/" {
        pattern
    } else {
        pattern.strip_suffix('/').unwrap_or(pattern)
    }
}

/// Validate that file path is safe to write to
fn validate_file_path(file_path: &Path, base_dir: Option<&Path>) -> anyhow::Result<()> {
    let resolved = if file_path.exists() {
        file_path.canonicalize()
    } else if let Some(parent) = file_path.parent() {
        parent.canonicalize().and_then(|p| {
            file_path
                .file_name()
                .ok_or_else(|| {
                    std::io::Error::new(std::io::ErrorKind::InvalidInput, "Invalid file path")
                })
                .map(|name| p.join(name))
        })
    } else {
        Err(std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            "Invalid file path",
        ))
    }
    .with_context(|| format!("Invalid file path: {}", file_path.display()))?;

    if let Some(base) = base_dir {
        let base_resolved = base
            .canonicalize()
            .with_context(|| format!("Invalid base directory: {}", base.display()))?;

        if !resolved.starts_with(base_resolved) {
            bail!(
                "File path {} is outside allowed directory",
                file_path.display()
            );
        }
    }

    Ok(())
}

/// Read patterns from ignore file
pub fn read_ignore_patterns(file_path: &Path) -> anyhow::Result<HashSet<String>> {
    if !file_path.exists() {
        return Ok(HashSet::new());
    }

    let file = File::open(file_path)
        .with_context(|| format!("Failed to open ignore file: {}", file_path.display()))?;

    let reader = BufReader::new(file);
    let mut patterns = HashSet::new();

    for line in reader.lines() {
        let line =
            line.with_context(|| format!("Failed to read line from: {}", file_path.display()))?;

        let trimmed = line.trim();

        // Skip empty lines and comments
        if !trimmed.is_empty() && !trimmed.starts_with('#') {
            patterns.insert(trimmed.to_string());
        }
    }

    Ok(patterns)
}

/// Write patterns to ignore file
pub fn write_ignore_patterns(
    file_path: &Path,
    patterns: &[String],
    append: bool,
) -> anyhow::Result<()> {
    if patterns.is_empty() {
        return Ok(());
    }

    validate_file_path(file_path, None)?;

    // Sanitize all patterns before writing
    let sanitized_patterns: Vec<String> = patterns
        .iter()
        .map(|p| sanitize_pattern(p))
        .filter(|p| !p.is_empty())
        .collect();

    if sanitized_patterns.is_empty() {
        return Ok(());
    }

    // Ensure parent directory exists
    if let Some(parent) = file_path.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("Failed to create directory: {}", parent.display()))?;
    }

    let mut file = if append {
        OpenOptions::new()
            .create(true)
            .append(true)
            .read(true)
            .open(file_path)
    } else {
        OpenOptions::new()
            .create(true)
            .write(true)
            .truncate(true)
            .open(file_path)
    }
    .with_context(|| format!("Failed to write to: {}", file_path.display()))?;

    // Handle newline for append mode
    if append && file.metadata().map(|m| m.len()).unwrap_or(0) > 0 {
        writeln!(file)
            .with_context(|| format!("Failed to write newline to: {}", file_path.display()))?;
    }

    let mut writer = BufWriter::new(&mut file);
    for pattern in sanitized_patterns {
        writeln!(writer, "{pattern}")
            .with_context(|| format!("Failed to write pattern to: {}", file_path.display()))?;
    }

    writer
        .flush()
        .with_context(|| format!("Failed to flush writes to: {}", file_path.display()))?;

    Ok(())
}

/// Add patterns to an ignore file, optionally avoiding duplicates
pub fn add_patterns_to_ignore_file(
    file_path: &Path,
    new_patterns: &[String],
    avoid_duplicates: bool,
    _validation_level: PatternValidationLevel,
) -> anyhow::Result<Vec<String>> {
    if new_patterns.is_empty() {
        return Ok(Vec::new());
    }

    // Skip validation - patterns should be pre-validated by caller
    // The validation_level parameter is kept for API compatibility

    let mut seen: HashSet<String> = if avoid_duplicates {
        read_ignore_patterns(file_path)?
            .into_iter()
            .map(|p| normalize_pattern_for_dedup(&p).to_string())
            .collect()
    } else {
        HashSet::new()
    };

    let mut patterns_to_add = Vec::new();
    for pattern in new_patterns {
        let sanitized = sanitize_pattern(pattern);
        if sanitized.is_empty() {
            continue;
        }
        if avoid_duplicates {
            let normalized = normalize_pattern_for_dedup(&sanitized).to_string();
            if !seen.insert(normalized) {
                continue;
            }
        }
        patterns_to_add.push(sanitized);
    }

    if !patterns_to_add.is_empty() {
        write_ignore_patterns(file_path, &patterns_to_add, true)?;
    }

    Ok(patterns_to_add)
}

/// Validate ignore patterns
pub fn validate_ignore_patterns(patterns: &[String]) -> Vec<PatternIssue> {
    let mut issues = Vec::new();

    for original_pattern in patterns {
        let pattern = sanitize_pattern(original_pattern);

        // Skip empty patterns after sanitization
        if pattern.is_empty() {
            continue;
        }

        // Check for newline characters in original pattern
        if original_pattern.contains(['\n', '\r']) {
            issues.push(PatternIssue {
                pattern: original_pattern.clone(),
                severity: PatternSeverity::Error,
                message: "Pattern contains newline characters which will corrupt the ignore file"
                    .to_string(),
            });
        }

        // Check for common issues
        if pattern.starts_with('/') && pattern.ends_with('/') && pattern.len() > 2 {
            issues.push(PatternIssue {
                pattern: pattern.clone(),
                severity: PatternSeverity::Info,
                message: "Pattern has leading and trailing slashes - might be too restrictive"
                    .to_string(),
            });
        }

        if pattern.starts_with("./") {
            issues.push(PatternIssue {
                pattern: pattern.clone(),
                severity: PatternSeverity::Info,
                message: "Pattern starts with './' which is redundant".to_string(),
            });
        }

        if pattern.matches("**").count() > 1 {
            issues.push(PatternIssue {
                pattern: pattern.clone(),
                severity: PatternSeverity::Warning,
                message: "Pattern contains multiple '**' which may not work as expected"
                    .to_string(),
            });
        }

        // Check for very broad patterns
        if matches!(pattern.as_str(), "*" | "**" | "/") {
            issues.push(PatternIssue {
                pattern: pattern.clone(),
                severity: PatternSeverity::Warning,
                message: "Pattern is very broad and may ignore more than intended".to_string(),
            });
        }

        // Check for patterns that might ignore important files
        if matches!(
            pattern.as_str(),
            ".git" | ".gitignore" | "README*" | "LICENSE*"
        ) {
            issues.push(PatternIssue {
                pattern: pattern.clone(),
                severity: PatternSeverity::Warning,
                message: "Pattern might ignore important project files".to_string(),
            });
        }
    }

    issues
}

/// Ensure the .git/info/exclude file exists and has proper structure
pub fn ensure_info_exclude_exists(exclude_file_path: &Path) -> anyhow::Result<()> {
    if exclude_file_path.exists() {
        return Ok(());
    }

    // Create the info directory if it doesn't exist
    if let Some(parent) = exclude_file_path.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("Failed to create directory: {}", parent.display()))?;
    }

    // Create the exclude file with default template
    let template = r#"# git ls-files --others --exclude-from=.git/info/exclude
# Lines that start with '#' are comments.
# For a project mostly in C, the following would be a good set of
# exclude patterns (uncomment them if you want to use them):
# *.[oa]
# *~
"#;

    std::fs::write(exclude_file_path, template).with_context(|| {
        format!(
            "Failed to initialize exclude file: {}",
            exclude_file_path.display()
        )
    })?;

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::{io::Write, path::PathBuf};
    use tempfile::{NamedTempFile, TempDir};

    #[test]
    fn test_sanitize_pattern() {
        assert_eq!(sanitize_pattern("*.pyc"), "*.pyc");
        assert_eq!(sanitize_pattern("  *.pyc  "), "*.pyc");
        assert_eq!(sanitize_pattern("*.pyc\n"), "*.pyc");
        assert_eq!(sanitize_pattern("*.pyc\r\n"), "*.pyc");
        assert_eq!(sanitize_pattern(""), "");
    }

    #[test]
    fn test_read_ignore_patterns_nonexistent() {
        let result = read_ignore_patterns(&PathBuf::from("/nonexistent/file"));
        assert!(result.is_ok());
        assert_eq!(result.unwrap().len(), 0);
    }

    #[test]
    fn test_read_ignore_patterns() {
        let mut temp_file = NamedTempFile::new().unwrap();
        writeln!(temp_file, "*.pyc").unwrap();
        writeln!(temp_file, "# comment").unwrap();
        writeln!(temp_file).unwrap();
        writeln!(temp_file, "__pycache__/").unwrap();

        let patterns = read_ignore_patterns(temp_file.path()).unwrap();
        assert_eq!(patterns.len(), 2);
        assert!(patterns.contains("*.pyc"));
        assert!(patterns.contains("__pycache__/"));
    }

    #[test]
    fn test_validate_ignore_patterns() {
        let patterns = vec!["*.pyc".to_string(), "build".to_string()];
        let issues = validate_ignore_patterns(&patterns);
        assert_eq!(issues.len(), 0);

        let patterns = vec!["*.pyc\n".to_string()];
        let issues = validate_ignore_patterns(&patterns);
        assert_eq!(issues.len(), 1);
        assert_eq!(issues[0].severity, PatternSeverity::Error);
    }

    #[test]
    fn test_write_ignore_patterns() {
        let temp_dir = TempDir::new().unwrap();
        let temp_file = temp_dir.path().join("test_ignore");

        let patterns = vec!["*.pyc".to_string(), "__pycache__/".to_string()];
        write_ignore_patterns(&temp_file, &patterns, false).unwrap();

        let content = std::fs::read_to_string(&temp_file).unwrap();
        assert!(content.contains("*.pyc\n"));
        assert!(content.contains("__pycache__/\n"));
    }

    #[test]
    fn test_normalize_pattern_for_dedup() {
        assert_eq!(normalize_pattern_for_dedup("planning"), "planning");
        assert_eq!(normalize_pattern_for_dedup("planning/"), "planning");
        assert_eq!(normalize_pattern_for_dedup("/"), "/");
        assert_eq!(normalize_pattern_for_dedup("/build/"), "/build");
    }

    #[test]
    fn test_add_patterns_skips_trailing_slash_duplicate() {
        let temp_dir = TempDir::new().unwrap();
        let temp_file = temp_dir.path().join("test_ignore");

        let added = add_patterns_to_ignore_file(
            &temp_file,
            &["planning".to_string()],
            true,
            PatternValidationLevel::Warn,
        )
        .unwrap();
        assert_eq!(added, vec!["planning".to_string()]);

        // "planning/" only differs from the already-present "planning" by a
        // trailing slash, so it must be treated as a duplicate.
        let added = add_patterns_to_ignore_file(
            &temp_file,
            &["planning/".to_string()],
            true,
            PatternValidationLevel::Warn,
        )
        .unwrap();
        assert!(added.is_empty());

        let content = std::fs::read_to_string(&temp_file).unwrap();
        assert_eq!(content.matches("planning").count(), 1);
    }

    #[test]
    fn test_add_patterns_skips_trailing_slash_duplicate_within_same_batch() {
        let temp_dir = TempDir::new().unwrap();
        let temp_file = temp_dir.path().join("test_ignore");

        let added = add_patterns_to_ignore_file(
            &temp_file,
            &["planning".to_string(), "planning/".to_string()],
            true,
            PatternValidationLevel::Warn,
        )
        .unwrap();
        assert_eq!(added, vec!["planning".to_string()]);
    }
}