dos2unix/
lib.rs

1/*
2    rust-dos2unix
3    Copyright 2016 Sam Saint-Pettersen.
4
5    Released under the MIT license;
6    see LICENSE.
7*/
8
9//! Rust library to convert DOS to Unix line endings.
10
11use std::fs::File;
12use std::io::prelude::*;
13
14pub struct Dos2Unix;
15
16impl Dos2Unix {
17    fn is_ascii(contents: String) -> bool {
18        let mut ascii = true;
19        for c in contents.chars() {
20            let code = c as i32;
21            if code > 127 {
22                ascii = false;
23                break;
24            }
25        }
26        ascii
27    }
28
29    fn is_dos_eol(contents: String) -> bool {
30        let mut dos_eol = false;
31        for c in contents.chars() {
32            if c == '\r' {
33                dos_eol = true;
34                break;
35            }
36        }
37        dos_eol
38    }
39
40    fn to_unix_line_endings(contents: String) -> Vec<String> {
41        let mut ucontents = Vec::new();
42        for c in contents.chars() {
43            if c != '\r' {
44                ucontents.push(format!("{}", c));
45            }
46        }
47        ucontents
48    }
49
50    ///
51    /// Convert a file to have Unix line endings.
52    ///
53    /// * `filename` - Filename to open and change line endings for.
54    /// * `feedback` - Display feedback when file already has Unix line endings or is binary.
55    pub fn convert(filename: &str, feedback: bool) -> bool {
56        let mut input = File::open(filename).unwrap();
57        let mut contents = String::new();
58        let _ = input.read_to_string(&mut contents);
59        let ascii = Dos2Unix::is_ascii(contents.clone());
60        let dos_eol = Dos2Unix::is_dos_eol(contents.clone());
61
62        let message = "dos2unix: File already has Unix line endings or is binary.";
63        let mut success = false;
64
65        if ascii && dos_eol {
66            let converted = Dos2Unix::to_unix_line_endings(contents.clone());
67            let mut w = File::create(filename).unwrap();
68            let _ = w.write_all(converted.join("").as_bytes());
69            success = true;
70        } else if feedback {
71            println!("{}", message);
72        }
73        success
74    }
75}
76
77#[cfg(test)]
78#[test]
79fn convert() {
80    Dos2Unix::convert("README.md", true);
81    let mut input = File::open("README.md").unwrap();
82    let mut contents = String::new();
83    let _ = input.read_to_string(&mut contents);
84    let mut has_dos_eol = false;
85    for c in contents.chars() {
86        if c == '\r' {
87            has_dos_eol = true;
88            break;
89        }
90    }
91    assert_eq!(has_dos_eol, false);
92}