Class: Philiprehberger::ChangelogParser::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/philiprehberger/changelog_parser/parser.rb

Overview

Parses Keep a Changelog formatted markdown

Constant Summary collapse

VERSION_HEADER =
/^##\s+\[(.+?)\](?:\s+-\s+(.+))?$/
CATEGORY_HEADER =
/^###\s+(.+)$/
LIST_ITEM =
/^-\s+(.+)$/
TITLE_HEADER =
/^#\s+(.+)$/

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.call(input) ⇒ Changelog

Parse a changelog from a file path or string

Parameters:

  • input (String)

    file path or markdown string

Returns:



19
20
21
22
# File 'lib/philiprehberger/changelog_parser/parser.rb', line 19

def self.call(input)
  content = File.exist?(input) ? File.read(input) : input
  new.parse(content)
end

Instance Method Details

#parse(content) ⇒ Changelog

Parse changelog content

Parameters:

  • content (String)

    the markdown content

Returns:



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
# File 'lib/philiprehberger/changelog_parser/parser.rb', line 28

def parse(content)
  lines = content.lines.map(&:chomp)
  title = ''
  preamble_lines = []
  entries = []
  current_entry = nil
  current_category = nil
  in_preamble = true

  lines.each do |line|
    case line
    when TITLE_HEADER
      title = Regexp.last_match(1)
    when VERSION_HEADER
      in_preamble = false
      current_entry = VersionEntry.new(
        version: Regexp.last_match(1),
        date: Regexp.last_match(2)
      )
      entries << current_entry
      current_category = nil
    when CATEGORY_HEADER
      current_category = Regexp.last_match(1) if current_entry
    when LIST_ITEM
      current_entry.add_entry(current_category, Regexp.last_match(1)) if current_entry && current_category
    else
      preamble_lines << line if in_preamble && !line.match?(TITLE_HEADER)
    end
  end

  preamble = preamble_lines.join("\n").strip
  preamble += "\n" unless preamble.empty?

  Changelog.new(title: title, preamble: preamble, entries: entries)
end