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
//! # File utils
//!
//! Provides various utilities to work with files.

use crate::utils;
use log::error;
use std::cmp::Ordering;
use std::fs::{read_to_string, File};
use std::io::{BufRead, BufReader};
use std::path::Path;

/// Verifies that files have headers matching one of the templates.
pub fn check_headers(files: &[&Path], templates: &[&Path]) -> bool {
    if !verify_files(&files) {
        return false;
    }

    if !verify_files(&templates) {
        return false;
    }

    let result: bool = files
        .iter()
        .all(|file| compare_file_headers(file, &templates));

    result
}

fn compare_file_headers(file: &Path, templates: &[&Path]) -> bool {
    for template in templates {
        let template_lines = get_lines(&template);
        let file_lines = get_top_lines(file, template_lines.len());

        if Ordering::Equal == utils::compare(&template_lines, &file_lines) {
            return true;
        }
    }

    error!("Invalid header: {}", file.display());
    false
}

/// Verifies that all files exist
pub fn verify_files(paths: &[&Path]) -> bool {
    paths.iter().all(|path| {
        let exists = path.exists();
        if !exists {
            error!("`{}` not found", path.display());
        }
        exists
    })
}

/// Returns certain amount of lines from the top of the file
pub fn get_top_lines(path: &Path, size: usize) -> Vec<String> {
    let input = match File::open(path) {
        Ok(file) => file,
        Err(_) => {
            error!("Error opening file {}", path.display());
            return vec![];
        }
    };
    BufReader::new(input)
        .lines()
        .take(size)
        .map(|item| item.unwrap())
        .collect()
}

/// Returns the content of the file as a collection of lines
pub fn get_lines(path: &Path) -> Vec<String> {
    match read_to_string(&path) {
        Ok(content) => content.lines().map(|line| line.to_string()).collect(),
        Err(err) => {
            error!("Error loading `{}`. {}", path.display(), err);
            vec![]
        }
    }
}