gign 0.3.0

A smart command line tool to generate .gitignore 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
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
use std::collections::HashMap;
use std::error::Error;
use std::fs;
use std::hash::{Hash, Hasher};
use std::io::Write;
use std::path::PathBuf;

use clap::parser::ValuesRef;
use colored::Colorize;
use triple_accel::levenshtein_exp;
use walkdir::WalkDir;

const TEMPLATES_ROOT_DIR: &str = "gign";
const TEMPLATES_REPO: &str = "https://github.com/github/gitignore.git";
const TEMPLATES_REPO_DIR: &str = "default";

/// A struct that represents a template in the templates database.
pub struct TemplateEntry {
    prefix: String,
    name: String,
    template: Option<String>,
    path: PathBuf,
}

impl TemplateEntry {
    /// Creates a new TemplateEntry.
    pub fn new(prefix: String, name: String, path: PathBuf) -> TemplateEntry {
        TemplateEntry {
            prefix,
            name,
            template: None,
            path,
        }
    }

    /// Returns the name of the template.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the prefix of the template.
    pub fn prefix(&self) -> &str {
        &self.prefix
    }

    /// Creates a new template with initialized template content.
    pub fn with_template(&self) -> Result<Self, Box<dyn Error>> {
        let template = fs::read_to_string(&self.path)?;
        Ok(TemplateEntry {
            prefix: self.prefix.clone(),
            name: self.name.clone(),
            template: Some(template),
            path: self.path.clone(),
        })
    }

    /// Returns the content of the template.
    pub fn template(&self) -> Option<&String> {
        match &self.template {
            Some(template) => Some(template),
            None => None,
        }
    }

    /// Returns a title of the template.
    /// Title is generated by combining the prefix and name of the template with colon.
    pub fn title(&self) -> String {
        if self.prefix.is_empty() {
            self.name.clone()
        } else {
            format!("{}:{}", self.prefix(), self.name())
        }
    }

    /// Same as title() but with colored text.
    pub fn title_colored(&self) -> String {
        if self.prefix.is_empty() {
            self.name.clone()
        } else {
            let colored_prefix = {
                let prefix = self.prefix();
                // get hash of the prefix
                let mut hasher = std::collections::hash_map::DefaultHasher::new();
                prefix.hash(&mut hasher);
                let hash = hasher.finish();

                if hash % 5 == 0 {
                    prefix.green()
                } else if hash % 4 == 0 {
                    prefix.yellow()
                } else if hash % 3 == 0 {
                    prefix.cyan()
                } else if hash % 2 == 0 {
                    prefix.magenta()
                } else {
                    prefix.blue()
                }
            };
            format!("{}{}{}", colored_prefix, ":".magenta(), self.name())
        }
    }

    /// Returns a string representation of the template.
    /// This is how template will look like in the generated gitignore file.
    pub fn to_string(&self) -> String {
        let hashes = "#".repeat(self.name().len() + 4);
        let name = self.name();
        let template = self.template().unwrap();

        format!("
{hashes}
# {} #
{hashes}

{}



", name, template)
    }
}


/// Get the default templates database
pub fn get_templates() -> Result<HashMap<String, TemplateEntry>, Box<dyn Error>> {
    match get_app_dir() {
        Some(path) => {
            // check if path exists
            if !path.exists() {
                return Err(Box::new(std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    "templates path does not exist",
                )));
            }

            let entries: Vec<TemplateEntry> = WalkDir::new(path)
                .into_iter()
                .filter_entry(|e| {
                    // filter only files that has .gitignore extension
                    if e.file_type().is_file() || e.file_type().is_symlink() {
                        return e.path().extension() == Some("gitignore".as_ref());
                    }

                    // ignore non-related directories
                    !e.path().ends_with(".git") &&
                        !e.path().ends_with(".github")
                })
                .filter_map(|e| match e {
                    Ok(e) => if e.file_type().is_file() { Some(e) } else { None },
                    Err(_) => None
                }
                )
                .map(|e| {
                    let name = e.file_name().to_string_lossy().trim_end_matches(".gitignore").to_string();
                    let prefix = e.path().parent().unwrap().file_name().unwrap().to_string_lossy().to_string();

                    if prefix == TEMPLATES_ROOT_DIR {
                        TemplateEntry::new("".to_string(), name, e.path().to_path_buf())
                    } else {
                        TemplateEntry::new(prefix.to_lowercase(), name, e.path().to_path_buf())
                    }
                })
                .collect();

            let mut hash_map = HashMap::new();
            for entry in entries {
                if hash_map.contains_key(entry.title().as_str()) {
                    return Err(Box::new(std::io::Error::new(
                        std::io::ErrorKind::AlreadyExists,
                        format!("duplicate template name: {}", entry.name()),
                    )));
                }

                hash_map.insert(entry.title(), entry);
            }

            Ok(hash_map)
        }
        None => {
            Err(Box::new(std::io::Error::new(
                std::io::ErrorKind::NotFound,
                "could not find the application directory",
            )))
        }
    }
}

/// Find the closest template to the given name
/// Returns None if no suggestion is found.
pub fn find_closest<'a>(target: &str, templates: Vec<&'a TemplateEntry>) -> Option<&'a TemplateEntry> {
    let mut closest_distance = u32::MAX;
    let mut closest_template = None;

    let target = if target.contains(":") {
        target.split(":").last().unwrap()
    } else {
        target
    };


    for template in templates {
        let distance = levenshtein_exp(target.to_lowercase().as_ref(), template.name().to_lowercase().as_ref());
        if distance < closest_distance && distance < 10 {
            closest_distance = distance;
            closest_template = Some(template);
        }
    }

    if let Some(entry) = closest_template {
        return Some(entry);
    }

    None
}


/// Generate a gitignore file from the given template names.
pub fn generate_gitignore(mut templates: ValuesRef<String>, strict: bool) -> Result<String, Box<dyn Error>> {
    match get_templates() {
        Ok(available_templates) => {
            let res = templates.try_fold(
                "".to_string(),
                |acc, name| {
                    if available_templates.contains_key(name) {
                        let template = available_templates.get(name).unwrap();
                        return Ok(format!("{}{}", acc, template.with_template().unwrap().to_string()));
                    }

                    let available_templates: Vec<&TemplateEntry> = available_templates
                        .values()
                        .collect();

                    let closest = find_closest(name, available_templates);
                    if let Some(closest) = closest {
                        // use closest template if no exact match is found and auto is enabled
                        if !strict {
                            return Ok(format!("{}{}", acc, closest.with_template().unwrap().to_string()));
                        }

                        return {
                            let message = format!(
                                "template '{}' not found, did you mean '{}'?",
                                name,
                                closest.title_colored(),
                            );

                            Err(Box::new(std::io::Error::new(
                                std::io::ErrorKind::InvalidInput,
                                message,
                            )))
                        };
                    }
                    // ignore non-existing templates when using auto mode
                    if !strict {
                        return Ok(acc);
                    }

                    Err(Box::new(std::io::Error::new(
                        std::io::ErrorKind::InvalidInput,
                        format!("template '{}' not found", name),
                    )))
                },
            )?;

            // trim trailing newlines
            Ok(res.trim_matches('\n').to_string())
        }
        Err(err) => Err(err)
    }
}

/// Get the application directory
pub fn get_app_dir() -> Option<PathBuf> {
    match dirs::config_dir() {
        Some(path) => Some(path.join(TEMPLATES_ROOT_DIR)),
        None => None
    }
}


/// Clones the templates repository into the default directory
pub fn clone_templates_repo() -> Result<PathBuf, Box<dyn Error>> {
    match get_app_dir() {
        Some(path) => {
            // check if git is installed
            if !command_is_available("git") {
                return Err(Box::new(std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    "Git is not installed",
                )));
            }

            let target_path = path.join(TEMPLATES_REPO_DIR);

            // run git clone
            let output = std::process::Command::new("git")
                .arg("clone")
                .arg(TEMPLATES_REPO)
                .arg(target_path.to_str().unwrap())
                .output()?;

            // check if clone was successful
            if !output.status.success() {
                return Err(Box::new(std::io::Error::new(
                    std::io::ErrorKind::Other,
                    "failed to clone templates repository",
                )));
            }

            Ok(target_path)
        }
        None => Err(Box::new(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            "could not find app directory",
        )))
    }
}

/// Update the default templates database
/// This will download the latest patterns database from the GitHub repository.
pub fn pull_templates_repo() -> Result<PathBuf, Box<dyn Error>> {
    match get_app_dir() {
        Some(path) => {
            let target_path = path.join(TEMPLATES_REPO_DIR);

            // clone repository if it doesn't exist yet instead of pulling it
            if !target_path.exists() {
                clone_templates_repo()?;
                return Ok(target_path);
            }

            // run git pull
            let output = std::process::Command::new("git")
                .arg("-C")
                .arg(target_path.to_str().unwrap())
                .arg("pull")
                .arg("origin")
                .arg("main")
                .output()?;

            // check if pull was successful
            if !output.status.success() {
                return Err(Box::new(std::io::Error::new(
                    std::io::ErrorKind::Other,
                    "failed to pull templates repository",
                )));
            }

            Ok(target_path)
        }
        None => Err(Box::new(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            "could not find app directory",
        )))
    }
}

/// Initialize the default templates database
pub fn init_default_templates() -> Result<(), Box<dyn Error>> {
    match get_app_dir() {
        Some(path) => {
            if !path.exists() {
                fs::create_dir_all(path)?;
                if let Err(err) = clone_templates_repo() {
                    warning(err.to_string().as_str());
                }
            }

            Ok(())
        }
        None => Err(Box::new(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            "could not find app directory",
        )))
    }
}

/// Checks if the given command is available in the system path.
pub fn command_is_available(name: &str) -> bool {
    let output = std::process::Command::new("which")
        .arg(name)
        .output()
        .ok();

    output.is_some()
}

/// Helper function to print error message and exit with code 1
pub fn error(msg: &str) {
    eprintln!("{}: {}", "error".red().bold(), msg);
    std::process::exit(1);
}

fn warning(msg: &str) {
    eprintln!("{}: {}", "warning".yellow().bold(), msg);
}

/// Checks if the given path is inside git repository.
fn is_git_repo(path: &PathBuf) -> Result<bool, Box<dyn Error>> {
    let output = std::process::Command::new("git")
        .arg("-C")
        .arg(path.to_str().unwrap())
        .arg("rev-parse")
        .arg("--is-inside-work-tree")
        .output()?;

    Ok(output.status.success())
}

/// Gets git root directory (i.e. top-level directory of the repository)
fn get_git_root(path: &PathBuf) -> Result<PathBuf, Box<dyn Error>> {
    let output = std::process::Command::new("git")
        .arg("-C")
        .arg(path.to_str().unwrap())
        .arg("rev-parse")
        .arg("--show-toplevel")
        .output()?;

    if !output.status.success() {
        return Err(Box::new(std::io::Error::new(
            std::io::ErrorKind::Other,
            "failed to get git root",
        )));
    }

    let root = String::from_utf8(output.stdout)?;
    Ok(PathBuf::from(root.trim()))
}

/// Appends to the root level .gitignore of the repository from path
/// If the file doesn't exist it will be created.
/// It will return the path to the .gitignore file.
pub fn append_to_gitignore(path: &PathBuf, template: &str) -> Result<PathBuf, Box<dyn Error>> {
    if !is_git_repo(path)? {
        return Err(Box::new(std::io::Error::new(
            std::io::ErrorKind::Other,
            "not a git repository",
        )));
    }

    let root = get_git_root(path)?;
    let gitignore = root.join(".gitignore");

    // Either append to the existing file or create a new one
    let file = {
        if gitignore.exists() {
            fs::OpenOptions::new()
                .append(true)
                .open(&gitignore)
        } else {
            fs::OpenOptions::new()
                .write(true)
                .create(true)
                .open(&gitignore)
        }
    };

    match file {
        Ok(mut f) => {
            if let Err(e) = writeln!(f, "\n{}", template) {
                return Err(Box::new(std::io::Error::new(
                    e.kind(),
                    e.to_string(),
                )));
            }

            Ok(gitignore)
        }
        Err(err) => Err(Box::new(err)),
    }
}