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
use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
use std::path::PathBuf;

use crate::types::{BlockType, DocItem};

#[derive(PartialEq)]
enum Directive {
    Continue,
    Stop,
}

pub fn parse_hcl(filename: PathBuf) -> std::io::Result<Vec<DocItem>> {
    let file = File::open(filename)?;
    let buf_reader = BufReader::new(file);
    let mut result = vec![DocItem::new()];
    for line in buf_reader.lines() {
        let state = parse_line(line?, result.pop().unwrap());
        result.push(state.0);
        if state.1 == Directive::Stop {
            result.push(DocItem::new());
        }
    }
    result.pop(); // Remove the last DocItem from the collection since it's empty
    result = result
        .into_iter()
        .filter(|i| {
            if i.category == BlockType::Comment {
                if let Some(line) = i.description.first() {
                    return line.starts_with("Title: ");
                }
            }
            true
        })
        .collect();
    Ok(result)
}

fn parse_line(line: String, mut result: DocItem) -> (DocItem, Directive) {
    match get_line_variant(&line) {
        BlockType::Resource => parse_regular(line, result, BlockType::Resource, &parse_resource),
        BlockType::Output => parse_regular(line, result, BlockType::Output, &parse_interface),
        BlockType::Variable => parse_regular(line, result, BlockType::Variable, &parse_interface),
        BlockType::Comment => (parse_comment(line, result), Directive::Continue),
        BlockType::None => {
            // Determine if it should stop parsing this block
            if (line.starts_with('}') && result.category != BlockType::None)
                || (line.trim().len() == 0 && result.category == BlockType::Comment)
            {
                return (result, Directive::Stop);
            }
            // Parse description if relevant
            if (result.category == BlockType::Variable || result.category == BlockType::Output)
                && line.trim().starts_with("description")
            {
                if let Some(description) = parse_description(&line) {
                    result.description.push(String::from(description));
                }
            }
            (result, Directive::Continue)
        }
    }
}

fn get_line_variant(line: &str) -> BlockType {
    let variants = vec![
        ("resource ", BlockType::Resource),
        ("variable ", BlockType::Variable),
        ("output ", BlockType::Output),
        ("#", BlockType::Comment),
    ];
    for variant in variants {
        if line.starts_with(variant.0) {
            return variant.1;
        }
    }
    BlockType::None
}

fn parse_regular(
    line: String,
    mut result: DocItem,
    category: BlockType,
    parser_function: &Fn(&str) -> String,
) -> (DocItem, Directive) {
    result.category = category;
    result.name = parser_function(&line);
    match line.trim().ends_with('}') {
        true => (result, Directive::Stop),
        false => (result, Directive::Continue),
    }
}

fn parse_resource(line: &str) -> String {
    line.split_whitespace()
        .skip(1)
        .take(2)
        .map(|s| s.trim_matches('"'))
        .collect::<Vec<&str>>()
        .join(".")
}

fn parse_interface(line: &str) -> String {
    // Parse variable and output blocks
    let result = line
        .split_whitespace()
        .skip(1)
        .take(1)
        .map(|s| s.trim_matches('"'))
        .collect::<Vec<&str>>()[0];
    String::from(result)
}

fn parse_description(line: &str) -> Option<&str> {
    let start = line.find('"')?;
    let substring = line.get(start..)?;
    Some(substring.trim_matches('"'))
}

fn parse_comment(line: String, mut result: DocItem) -> DocItem {
    let parsed = line.trim_start_matches('#').trim();
    if parsed.len() > 0 {
        result.category = BlockType::Comment;
        result.description.push(String::from(parsed));
    }
    result
}

//
// Unit tests
//

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn get_line_variant_resource() {
        let line = r#"resource "foo" "bar" {"#;
        match get_line_variant(line) {
            BlockType::Resource => {}
            _ => panic!("Type error!"),
        }
    }

    #[test]
    fn get_line_variant_output() {
        let line = r#"output "foo" {"#;
        match get_line_variant(line) {
            BlockType::Output => {}
            _ => panic!("Type error!"),
        }
    }

    #[test]
    fn get_line_variant_variable() {
        let line = r#"variable "foo" {"#;
        match get_line_variant(line) {
            BlockType::Variable => {}
            _ => panic!("Type error!"),
        }
    }

    #[test]
    fn get_line_variant_comment() {
        let line = r#"# foo"#;
        match get_line_variant(line) {
            BlockType::Comment => {}
            _ => panic!("Type error!"),
        }
    }

    #[test]
    fn get_line_variant_comment2() {
        let line = r#"#foo"#;
        match get_line_variant(line) {
            BlockType::Comment => {}
            _ => panic!("Type error!"),
        }
    }

    #[test]
    fn get_line_variant_none() {
        let line = r#"  foo"#;
        match get_line_variant(line) {
            BlockType::None => {}
            _ => panic!("Type error!"),
        }
    }

    #[test]
    fn test_parse_resource() {
        let line = r#"resource "foo" "bar" {"#;
        assert_eq!(parse_resource(line), "foo.bar".to_string());
    }

    #[test]
    fn test_parse_output() {
        let line = r#"output "foo" {"#;
        assert_eq!(parse_interface(line), "foo");
    }

    #[test]
    fn test_parse_variable() {
        let line = r#"variable "foo" {"#;
        assert_eq!(parse_interface(line), "foo");
    }

    #[test]
    fn test_parse_description() {
        let line = r#"  description = "foo bar""#;
        assert_eq!(parse_description(line), Some("foo bar"));
    }

    #[test]
    fn test_parse_comment() {
        let line = String::from(r#"# foo bar"#);
        let result = DocItem::new();
        assert_eq!(parse_comment(line, result).description[0], "foo bar");
    }

    #[test]
    fn test_parse_comment2() {
        let line = String::from(r#"#foo bar"#);
        let result = DocItem::new();
        assert_eq!(parse_comment(line, result).description[0], "foo bar");
    }
}