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
use std::fmt;
use std::fs;
use std::fs::File;
use std::io::{BufRead,BufReader};

pub(crate) struct Step {
    comments: Vec<String>,
    code: Vec<String>,
    format: String,
}

#[allow(dead_code)]
pub(crate) struct Script {
    shebang: Option<String>,
    steps: Vec<Step>,
}

impl fmt::Display for Script {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = self.steps
            .iter()
            .map(|s| s.to_string())
            .collect::<Vec<String>>()
            .join("");

        // match &self.shebang {
        //     Some(sb) => write!(f, "{}\n{}", sb, s),
        //     None => write!(f, "{}", s),
        // }
        write!(f, "{}", s)
    }
}

impl fmt::Display for Step {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let comments = self.comments
            .iter()
            .map(|x| x
                 .trim_start_matches('#')
                 .trim_start()
                 .to_string())
            .collect::<Vec<String>>()
            .join("");
        let code = self.code.join("\t");

        write!(f, "1. {}\t```{}\n\t{}\t```\n", comments, self.format, code)
    }
}

fn read_file(file_path: &str) -> BufReader<File>
{
    let file = match fs::File::open(file_path) {
        Ok(file) => file,
        Err(_) => panic!("Unable to read file from {}", file_path)
    };

    let buffer = BufReader::new(file);
    return buffer
}

pub(crate) fn parse(file_path: &str) -> Script {
    let mut file_reader = read_file(file_path);
    let shebang  = skip_shebang(&mut file_reader).expect("error looking for Shebang ");

    let mut steps = vec![];
    loop {
        match read_step(&mut file_reader) {
            Ok(x) => {
                match x {
                    Some(step) => steps.push(step),
                    None => break,
                }
            },
            Err(_) => panic!("error parsing step"),
        }
    }

    return Script {
        shebang,
        steps,
    }
}

fn skip_shebang(script: &mut BufReader<File>) -> Result<Option<String>, std::io::Error>
{
    let mut first_line = String::new();
    script.read_line(&mut first_line).expect("Unable to read first line");

    if first_line.starts_with("#!") {
        return Ok(Some(first_line.to_string()));
    }

    let l = first_line.len() as i64;
    script.seek_relative(-1 * l)?;
    return Ok(None)
}

fn read_step(script: &mut BufReader<File>) -> Result<Option<Step>, std::io::Error>
{
    let mut comments = vec![];
    let mut code = vec![];

    loop {
        let mut l = String::new();
        let r = script.read_line(&mut l)?;
        if r == 0 {
            if comments.is_empty() {
                return Ok(None);
            }

            let s = Step{
                comments,
                code,
                format: "bash".to_string(),
            };
            return Ok(Some(s));
        }

        if l
            .trim_end_matches('\r')
            .trim_end_matches('\n')
            .is_empty() {
            continue
        }

        let is_comment = l.starts_with("#");
        if !comments.is_empty() && is_comment {
            match script.seek_relative(-1 * l.len() as i64) {
                Ok(x) => x,
                Err(_) => panic!("error resetting file reader"),
            }
            break
        }

        if l
            .trim_end_matches('\r')
            .trim_end_matches('\n')
            .ends_with("# mdbash: skip-line") {
            continue
        }

        if is_comment {
            comments.push(l);
        } else {
            code.push(l);
        }
    }

    if comments.is_empty() {
        return Ok(None)
    }

    let s = Step{
        comments,
        code,
        format: "bash".to_string(),
    };
    return Ok(Some(s));
}