gitignore-in 0.2.1

A command line tool for managing .gitignore files with gitignore.in
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
use clap::{Parser, Subcommand};
use std::{io::Read, path::Path};
mod build;
mod edit;
mod gi;
mod gibo;
mod infer;
mod parser;
mod restore;
mod script;

const AFTER_HELP: &str =
    "Official site: https://gitignore.in/\nRepository: https://github.com/gitignore-in/gitignore-in";
const GITIGNORE_IN_HEADER_LINES: [&str; 2] = [
    "# See https://gitignore.in/",
    "# Edit this file and run `gitignore.in` to rebuild .gitignore",
];

fn main() -> std::io::Result<()> {
    let cli = Cli::parse();
    run(cli)
}

#[derive(Debug, Parser)]
#[command(
    name = "gitignore.in",
    version,
    about = "Manage .gitignore files with .gitignore.in",
    long_about = None,
    after_help = AFTER_HELP
)]
struct Cli {
    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Debug, Subcommand)]
enum Commands {
    /// Search templates available from gibo and gitignore.io
    Search {
        /// Search terms matched case-insensitively against template names
        queries: Vec<String>,
    },
    /// Add templates to .gitignore.in and rebuild .gitignore
    Add {
        /// Template names such as Rust, macOS, or node
        templates: Vec<String>,
    },
    /// Remove templates from .gitignore.in and rebuild .gitignore
    Remove {
        /// Template names such as Rust, macOS, or node
        templates: Vec<String>,
    },
    /// Restore .gitignore.in from a generated .gitignore
    Restore,
    /// Infer .gitignore.in from an existing .gitignore
    Infer {
        /// Comma-separated gibo targets to consider
        #[arg(long, value_delimiter = ',')]
        gibo: Vec<String>,
        /// Comma-separated gitignore.io targets to consider
        #[arg(long, value_delimiter = ',')]
        gi: Vec<String>,
        /// Minimum number of matching lines required for a template
        #[arg(long, default_value_t = 2)]
        min_overlap: usize,
    },
}

fn run(cli: Cli) -> std::io::Result<()> {
    match cli.command {
        Some(Commands::Search { queries }) => search_templates(queries),
        Some(Commands::Add { templates }) => {
            update_gitignore_in_file(UpdateMode::Add, templates)?;
            println!("Updated .gitignore.in");
            build_gitignore()
        }
        Some(Commands::Remove { templates }) => {
            update_gitignore_in_file(UpdateMode::Remove, templates)?;
            println!("Updated .gitignore.in");
            build_gitignore()
        }
        Some(Commands::Restore) => {
            restore_gitignore_in_file()?;
            println!("Restored .gitignore.in");
            Ok(())
        }
        Some(Commands::Infer {
            gibo,
            gi,
            min_overlap,
        }) => {
            infer_gitignore_in_file(gibo, gi, min_overlap)?;
            println!("Inferred .gitignore.in");
            Ok(())
        }
        None => build_gitignore(),
    }
}

enum UpdateMode {
    Add,
    Remove,
}

fn build_gitignore() -> std::io::Result<()> {
    match bootstrap_gitignore_in_file() {
        Ok(BootstrapStatus::Initialized) => {
            println!("Initialized .gitignore.in");
        }
        Ok(BootstrapStatus::Inferred) => {
            println!("Inferred .gitignore.in from .gitignore");
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            println!("Tried to create .gitignore.in, but failed.");
        }
        Err(e) => {
            println!("Error: {e}");
            return Err(e);
        }
        _ => {}
    }
    let statements = parse_gitignore_in_file()?;
    let result = build::build(statements)?;
    // write to .gitignore
    ensure_gitignore_file()?;
    let path = Path::new(".gitignore");
    std::fs::write(path, result)?;
    println!("Generated .gitignore");
    Ok(())
}

fn search_templates(queries: Vec<String>) -> std::io::Result<()> {
    let catalog = edit::Catalog::load()?;
    let results = catalog.search(&queries);
    if results.is_empty() {
        let message = if queries.is_empty() {
            "No templates are available from gibo or gitignore.io".to_string()
        } else {
            format!("No templates matched: {}", queries.join(", "))
        };
        return Err(std::io::Error::other(message));
    }

    for template in results {
        println!(
            "{}\t{}",
            edit::provider_label(template.provider),
            template.target
        );
    }

    Ok(())
}

enum BootstrapStatus {
    AlreadyPresent,
    Initialized,
    Inferred,
}

fn bootstrap_gitignore_in_file() -> std::io::Result<BootstrapStatus> {
    let path = Path::new(".gitignore.in");
    if path.exists() {
        return Ok(BootstrapStatus::AlreadyPresent);
    }

    if Path::new(".gitignore").exists() {
        infer_gitignore_in_file(Vec::new(), Vec::new(), 2)?;
        return Ok(BootstrapStatus::Inferred);
    }

    std::fs::File::create(path)?;
    std::fs::write(path, gitignore_in_template_header())?;

    Ok(BootstrapStatus::Initialized)
}

fn ensure_gitignore_file() -> std::io::Result<()> {
    let path = Path::new(".gitignore");
    if let Err(e) = std::fs::metadata(path) {
        if e.kind() == std::io::ErrorKind::NotFound {
            match std::fs::File::create(path) {
                Ok(_) => return Ok(()),
                Err(_) => return Err(e),
            }
        }
    }
    Ok(())
}

fn restore_gitignore_in_file() -> std::io::Result<()> {
    let path = std::path::Path::new(".gitignore");
    let mut file = std::fs::File::open(path)?;
    let mut content = String::new();
    file.read_to_string(&mut content)?;
    let restored = add_gitignore_in_header(&restore::restore(&content));
    std::fs::write(".gitignore.in", restored)?;
    Ok(())
}

fn infer_gitignore_in_file(
    gibo_targets: Vec<String>,
    gi_targets: Vec<String>,
    min_overlap: usize,
) -> std::io::Result<()> {
    let path = std::path::Path::new(".gitignore");
    let mut file = std::fs::File::open(path)?;
    let mut content = String::new();
    file.read_to_string(&mut content)?;

    let inferred = infer::infer_with_options(
        &content,
        &infer::InferOptions {
            gibo_targets,
            gi_targets,
            min_overlap,
        },
    )?;
    std::fs::write(".gitignore.in", add_gitignore_in_header(&inferred))?;
    Ok(())
}

fn update_gitignore_in_file(mode: UpdateMode, templates: Vec<String>) -> std::io::Result<()> {
    if templates.is_empty() {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            "At least one template name is required",
        ));
    }

    match bootstrap_gitignore_in_file() {
        Ok(BootstrapStatus::Initialized) => {
            println!("Initialized .gitignore.in");
        }
        Ok(BootstrapStatus::Inferred) => {
            println!("Inferred .gitignore.in from .gitignore");
        }
        Ok(BootstrapStatus::AlreadyPresent) => {}
        Err(e) => return Err(e),
    }

    let mut script = parse_gitignore_in_file()?;
    match mode {
        UpdateMode::Add => {
            let catalog = edit::Catalog::load()?;
            edit::add_templates(&mut script, &catalog, &templates)?;
        }
        UpdateMode::Remove => {
            edit::remove_templates(&mut script, &templates)?;
        }
    }
    std::fs::write(".gitignore.in", edit::render(&script))?;
    Ok(())
}

fn parse_gitignore_in_file() -> std::io::Result<script::GitIgnoreIn> {
    let path = std::path::Path::new(".gitignore.in");
    parse_path(path)
}

fn parse_path(path: &Path) -> std::io::Result<script::GitIgnoreIn> {
    let mut file = std::fs::File::open(path)?;
    let mut content = String::new();
    file.read_to_string(&mut content)?;
    let result = parser::parse_text(&content);
    Ok(result)
}

fn gitignore_in_template_header() -> String {
    GITIGNORE_IN_HEADER_LINES.join("\n") + "\n"
}

fn add_gitignore_in_header(content: &str) -> String {
    if GITIGNORE_IN_HEADER_LINES
        .iter()
        .all(|line| content.contains(line))
    {
        return content.to_string();
    }

    if content.is_empty() {
        return gitignore_in_template_header();
    }

    format!("{}\n{}", gitignore_in_template_header(), content)
}

#[cfg(test)]
mod tests {
    use super::*;
    use mktemp::Temp;
    use std::sync::{Mutex, OnceLock};

    fn cwd_lock() -> &'static Mutex<()> {
        static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
        LOCK.get_or_init(|| Mutex::new(()))
    }

    #[test]
    fn test_main() {
        let _guard = cwd_lock().lock().expect("failed to lock cwd");
        let current_dir = std::env::current_dir().expect("failed to get current dir");
        let temp_dir = Temp::new_dir().expect("failed to create temp dir");
        std::env::set_current_dir(temp_dir.as_path()).expect("failed to change current dir");
        let result = run(Cli { command: None });
        assert!(result.is_ok());
        // check if the .gitignore.in file is in current directory
        let path = Path::new(".gitignore.in");
        assert!(path.exists());
        let content = std::fs::read_to_string(path).expect("failed to read .gitignore.in");
        assert!(content.contains("# See https://gitignore.in/"));

        // try again
        let result = run(Cli { command: None });
        assert!(result.is_ok());
        assert!(path.exists());
        std::env::set_current_dir(current_dir).expect("failed to restore current dir");
    }

    #[test]
    fn test_bootstrap_infers_from_existing_gitignore() {
        let _guard = cwd_lock().lock().expect("failed to lock cwd");
        let current_dir = std::env::current_dir().expect("failed to get current dir");
        let temp_dir = Temp::new_dir().expect("failed to create temp dir");
        std::env::set_current_dir(temp_dir.as_path()).expect("failed to change current dir");
        std::fs::write(
            ".gitignore",
            "# DO NOT EDIT THIS FILE\n# Generated by gitignore.in\n# See https://gitignore.in/\n# Edit .gitignore.in instead of this file\n# Run `gitignore.in` to build .gitignore\n# -----------------------------------------------------------------------------\nplain-entry\n# -----------------------------------------------------------------------------\n!important.txt\n",
        )
        .expect("failed to write .gitignore");

        let result = run(Cli { command: None });
        assert!(result.is_ok());

        let restored =
            std::fs::read_to_string(".gitignore.in").expect("failed to read .gitignore.in");
        assert_eq!(
            restored,
            "# See https://gitignore.in/\n# Edit this file and run `gitignore.in` to rebuild .gitignore\n\necho 'plain-entry'\necho '!important.txt'\n"
        );
        std::env::set_current_dir(current_dir).expect("failed to restore current dir");
    }

    #[test]
    fn test_parse_restore_command() {
        let cli = Cli::parse_from(["gitignore.in", "restore"]);
        assert!(matches!(cli.command, Some(Commands::Restore)));
    }

    #[test]
    fn test_parse_add_command() {
        let cli = Cli::parse_from(["gitignore.in", "add", "Rust", "node"]);
        match cli.command {
            Some(Commands::Add { templates }) => {
                assert_eq!(templates, vec!["Rust".to_string(), "node".to_string()]);
            }
            _ => unreachable!(),
        }
    }

    #[test]
    fn test_parse_search_command() {
        let cli = Cli::parse_from(["gitignore.in", "search", "rust", "node"]);
        match cli.command {
            Some(Commands::Search { queries }) => {
                assert_eq!(queries, vec!["rust".to_string(), "node".to_string()]);
            }
            _ => unreachable!(),
        }
    }

    #[test]
    fn test_parse_remove_command() {
        let cli = Cli::parse_from(["gitignore.in", "remove", "Rust"]);
        match cli.command {
            Some(Commands::Remove { templates }) => {
                assert_eq!(templates, vec!["Rust".to_string()]);
            }
            _ => unreachable!(),
        }
    }

    #[test]
    fn test_parse_infer_command() {
        let cli = Cli::parse_from([
            "gitignore.in",
            "infer",
            "--gibo",
            "Rust,macOS",
            "--gi",
            "node",
            "--min-overlap",
            "3",
        ]);

        match cli.command {
            Some(Commands::Infer {
                gibo,
                gi,
                min_overlap,
            }) => {
                assert_eq!(gibo, vec!["Rust".to_string(), "macOS".to_string()]);
                assert_eq!(gi, vec!["node".to_string()]);
                assert_eq!(min_overlap, 3);
            }
            _ => unreachable!(),
        }
    }

    #[test]
    fn add_gitignore_in_header_keeps_existing_header() {
        let content = "# See https://gitignore.in/\n# Edit this file and run `gitignore.in` to rebuild .gitignore\n";
        assert_eq!(add_gitignore_in_header(content), content);
    }
}