Class: Ast::Merge::Detector::TomlFrontmatter

Inherits:
Base
  • Object
show all
Defined in:
lib/ast/merge/detector/toml_frontmatter.rb

Overview

Detects TOML frontmatter at the beginning of a document.

TOML frontmatter is delimited by +++ at the start and end,
and must begin on the first line of the document (optionally
preceded by a UTF-8 BOM). This format is commonly used by
Hugo and other static site generators.

Examples:

TOML frontmatter

+++
title = "My Document"
author = "Jane Doe"
+++

Usage

detector = TomlFrontmatter.new
regions = detector.detect_all(markdown_source)
# => [#<Region type=:toml_frontmatter content="title = \"My Document\"\n...">]

See Also:

Constant Summary collapse

FRONTMATTER_PATTERN =

Pattern for detecting TOML frontmatter.

  • Must start at beginning of document (or after BOM)
  • Opening delimiter is +++ followed by optional whitespace and newline
  • Content is captured (non-greedy)
  • Closing delimiter is +++ at start of line, followed by optional whitespace and newline/EOF
/\A(?:\xEF\xBB\xBF)?(\+\+\+[ \t]*\r?\n)(.*?)(^\+\+\+[ \t]*(?:\r?\n|\z))/m

Instance Method Summary collapse

Methods inherited from Base

#inspect, #name, #strip_delimiters?

Instance Method Details

#detect_all(source) ⇒ Array<Region>

Detects TOML frontmatter at the beginning of the document.

Parameters:

  • source (String)

    the source document to scan

Returns:

  • (Array<Region>)

    array containing at most one Region for frontmatter



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
# File 'lib/ast/merge/detector/toml_frontmatter.rb', line 50

def detect_all(source)
  return [] if source.nil? || source.empty?

  match = source.match(FRONTMATTER_PATTERN)
  return [] unless match

  opening_delimiter = match[1]
  content = match[2]
  closing_delimiter = match[3]

  # Calculate line numbers
  start_line = 1

  # Count total newlines in the full match to determine end line
  full_match = match[0]
  total_newlines = full_match.count("\n")
  end_line = total_newlines + (full_match.end_with?("\n") ? 0 : 1)

  [
    Region.new(
      type: region_type,
      content: content,
      start_line: start_line,
      end_line: end_line,
      delimiters: [opening_delimiter.strip, closing_delimiter.strip],
      metadata: {format: :toml},
    ),
  ]
end

#region_typeSymbol

Returns the type identifier for TOML frontmatter regions.

Returns:

  • (Symbol)

    the type identifier for TOML frontmatter regions



40
41
42
# File 'lib/ast/merge/detector/toml_frontmatter.rb', line 40

def region_type
  :toml_frontmatter
end