all repos

olexsmir.xyz @ main

my site, yes, i like lua

olexsmir.xyz/lua/lego/frontmatter.lua(view raw)

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
local frontmatter = {}

---@param lines string[]
---@return table
function frontmatter.extract(lines)
  if lines[1] ~= "---" then
    return {}
  end

  for i = 2, #lines do
    if lines[i] == "---" then
      local frontmatter_lines = { unpack(lines, 2, i - 1) }

      local result = {}
      for _, line in ipairs(frontmatter_lines) do
        local key, value = line:match "^%s*(.-)%s*=%s*(.-)%s*$"
        if key and value then
          result[key] = value
        end
      end

      return result
    end
  end

  return {}
end

---@param lines string[]
---@return string[]|nil
function frontmatter.content(lines)
  if lines[1] ~= "---" then
    return lines
  end

  return vim
    .iter(lines)
    :skip(1)
    :skip(function(el)
      return el ~= "---"
    end)
    :skip(1)
    :totable()
end

return frontmatter