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
use anyhow::Result;
use err_derive::Error;
use changelog::{Change, Changelog, ChangelogBuilder, Release, ReleaseBuilder};
use chrono::NaiveDate;
use pulldown_cmark::{Event, LinkType, Parser, Tag};
use semver::Version;
use std::fs::File;
use std::io::prelude::*;
use std::path::PathBuf;

pub mod changelog;

#[derive(Clone, Debug)]
enum ChangelogFormat {
    Markdown,
    Json,
    Yaml,
}

#[derive(Clone, Debug)]
enum ChangelogSection {
    None,
    Title,
    Description,
    ReleaseHeader,
    ChangesetHeader,
    Changeset(String),
}

#[derive(Debug, Error)]
pub enum ChangelogParserError {
    #[error(display = "unable to determine file format from contents")]
    UnableToDetermineFormat,
    #[error(display = "error building release")]
    ErrorBuildingRelease(String),
}

pub struct ChangelogParser;
impl ChangelogParser {
    pub fn parse(path: PathBuf) -> Result<Changelog> {
        let mut document = String::new();
        File::open(path.clone())?.read_to_string(&mut document)?;
        Self::parse_buffer(document)
    }

    pub fn parse_buffer(buffer: String) -> Result<Changelog> {
        match Self::get_format_from_buffer(buffer.clone()) {
            Ok(format) => match format {
                ChangelogFormat::Markdown => Self::parse_markdown(buffer),
                ChangelogFormat::Json => Self::parse_json(buffer),
                ChangelogFormat::Yaml => Self::parse_yaml(buffer),
            },
            _ => Err(ChangelogParserError::UnableToDetermineFormat.into()),
        }
    }

    fn parse_markdown(markdown: String) -> Result<Changelog> {
        let parser = Parser::new(&markdown);

        let mut section = ChangelogSection::None;

        let mut title = String::new();
        let mut description = String::new();
        let mut description_links = String::new();
        let mut releases: Vec<Release> = Vec::new();

        let mut release = ReleaseBuilder::default();
        let mut changeset: Vec<Change> = Vec::new();
        let mut accumulator = String::new();
        let mut link_accumulator = String::new();

        for event in parser {
            match event {
                // Headings.
                Event::Start(Tag::Header(1)) => section = ChangelogSection::Title,
                Event::End(Tag::Header(1)) => section = ChangelogSection::Description,
                Event::Start(Tag::Header(2)) => {
                    match section {
                        ChangelogSection::Description => {
                            description = accumulator.clone();
                            accumulator = String::new();
                        }
                        ChangelogSection::Changeset(_) | ChangelogSection::ReleaseHeader => {
                            release.changes(changeset.clone());
                            releases.push(release.build().map_err(ChangelogParserError::ErrorBuildingRelease)?);

                            changeset = Vec::new();
                            release = ReleaseBuilder::default();
                        }
                        _ => (),
                    }

                    section = ChangelogSection::ReleaseHeader;
                }
                Event::Start(Tag::Header(3)) => section = ChangelogSection::ChangesetHeader,

                // Links.
                Event::Start(Tag::Link(LinkType::Inline, _, _)) => accumulator.push_str("["),
                Event::Start(Tag::Link(LinkType::Collapsed, _, _)) => {
                    accumulator.push_str("[");
                    link_accumulator = String::from("[");
                }
                Event::End(Tag::Link(LinkType::Inline, href, _)) => {
                    accumulator.push_str(&format!("]({})", href));
                }
                Event::End(Tag::Link(LinkType::Collapsed, href, _)) => {
                    accumulator.push_str("][]");
                    link_accumulator.push_str(&format!("]: {}\n", href));
                    description_links.push_str(&link_accumulator);
                    link_accumulator = String::new();
                }
                Event::Start(Tag::Link(LinkType::Shortcut, href, _)) => {
                    release.link(href.to_string());
                }

                // Items.
                Event::End(Tag::Item) => {
                    if let ChangelogSection::Changeset(name) = section.clone() {
                        changeset.push(Change::new(&name, accumulator)?);

                        accumulator = String::new();
                    }
                }

                // Line breaks.
                Event::SoftBreak => accumulator.push_str("\n"),
                Event::End(Tag::Paragraph) => accumulator.push_str("\n\n"),

                // Inline code.
                Event::Code(text) => accumulator.push_str(&format!("`{}`", text)),

                // Text formatting.
                Event::Start(Tag::Strong) | Event::End(Tag::Strong) => accumulator.push_str("**"),
                Event::Start(Tag::Emphasis) | Event::End(Tag::Emphasis) => {
                    accumulator.push_str("_")
                }
                Event::Start(Tag::Strikethrough) | Event::End(Tag::Strikethrough) => {
                    accumulator.push_str("~~")
                }

                // Text.
                Event::Text(text) => match section {
                    ChangelogSection::Title => title = text.to_string(),
                    ChangelogSection::Description => {
                        accumulator.push_str(&text);

                        if !link_accumulator.is_empty() {
                            link_accumulator.push_str(&text);
                        }
                    }
                    ChangelogSection::ReleaseHeader => {
                        let text = text.trim();

                        if text == "YANKED" {
                            release.yanked(true);
                        }

                        let mut date_format = "- %Y-%m-%d";
                        let split: Vec<&str> = text.split(" - ").collect();

                        if split.iter().count() > 1 {
                            date_format = "%Y-%m-%d";
                        }

                        for string in split {
                            if let Ok(date) = NaiveDate::parse_from_str(&string, date_format) {
                                release.date(date);
                            }

                            if let Ok(version) = Version::parse(&string) {
                                release.version(version);
                            }
                        }
                    }
                    ChangelogSection::ChangesetHeader => {
                        section = ChangelogSection::Changeset(text.to_string())
                    }
                    ChangelogSection::Changeset(_) => accumulator.push_str(&text),
                    _ => (),
                },
                _ => (),
            };
        }

        release.changes(changeset.clone());
        releases.push(release.build().map_err(ChangelogParserError::ErrorBuildingRelease)?);

        if !description_links.is_empty() {
            description = format!("{}{}\n", description, description_links);
        }

        let changelog = ChangelogBuilder::default()
            .title(title)
            .description(description)
            .releases(releases)
            .build()
            .map_err(ChangelogParserError::ErrorBuildingRelease)?;

        Ok(changelog)
    }

    fn parse_json(json: String) -> Result<Changelog> {
        let changelog: Changelog = serde_json::from_str(&json)?;

        Ok(changelog)
    }

    fn parse_yaml(yaml: String) -> Result<Changelog> {
        let changelog: Changelog = serde_yaml::from_str(&yaml)?;

        Ok(changelog)
    }

    fn get_format_from_buffer(buffer: String) -> Result<ChangelogFormat> {
        let first_char = match buffer.chars().next() {
            Some(first_char) => first_char,
            _ => {
                return Err(ChangelogParserError::UnableToDetermineFormat.into());
            }
        };

        let first_line: String = buffer.chars().take_while(|&c| c != '\n').collect();
        let mut format: Option<ChangelogFormat> = match first_char {
            '{' => Some(ChangelogFormat::Json),
            '#' => Some(ChangelogFormat::Markdown),
            _ => None,
        };

        if format.is_none() && (first_line == "---" || first_line.contains("title:")) {
            format = Some(ChangelogFormat::Yaml);
        }

        if let Some(format) = format {
            Ok(format)
        } else {
            Err(ChangelogParserError::UnableToDetermineFormat.into())
        }
    }
}