Skip to content

Commit 01b310f

Browse files
committed
adjust regex to match top of document
1 parent 696b3aa commit 01b310f

2 files changed

Lines changed: 44 additions & 5 deletions

File tree

src/public/Get-MarkdownFrontMatter.ps1

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,18 +17,15 @@ Function Get-MarkdownFrontMatter
1717

1818
$Content = Get-Content $File -Raw
1919

20-
$yamlRegex = '(?smi)(---.*?)(?:---)'
20+
$yamlRegex = '(?smi)\A(---.*?)(?:---)'
2121

2222
try {
2323

24-
$result = $null
24+
$result = [ordered]@{}
2525

2626
if ($Content -match $yamlRegex) {
2727
$yamlBlock = ($Content | Select-String $yamlRegex -AllMatches).Matches[0].Groups[1].Value
28-
2928
$result = $yamlBlock | ConvertFrom-Yaml -Ordered
30-
} else {
31-
$result = [ordered]@{}
3229
}
3330

3431
if (!$result['title']) {

src/tests/Get-MarkdownFrontMatter.Tests.ps1

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,48 @@ postid: 1234
3030
$result.postId | Should -Be "1234"
3131
}
3232

33+
It "Should only find front matter at the top of the file" {
34+
# arrange
35+
# create content with two --- sections
36+
$content = @(
37+
"---"
38+
"title: First Title"
39+
"---"
40+
"# Heading"
41+
"An example with a page break or hr"
42+
"---"
43+
"# Second Title"
44+
) -join "`n"
45+
$path = Get-TestFilePath 'front-matter-top-only.md'
46+
Set-MarkdownFile -Path $path -Content $content
47+
48+
# act
49+
$result = Get-MarkdownFrontMatter -File $path
50+
51+
# assert
52+
$result.title | Should -Be "First Title"
53+
}
54+
55+
It "Should not complain if content has --- but not intended as front matter" {
56+
# arrange
57+
$content = @(
58+
"An example with a page break or hr"
59+
"````"
60+
"---"
61+
"Some content in a block"
62+
"---"
63+
"````"
64+
) -join "`n"
65+
$path = Get-TestFilePath 'no-front-matter.md'
66+
Set-MarkdownFile -Path $path -Content $content
67+
68+
# act
69+
$result = Get-MarkdownFrontMatter -File $path
70+
71+
# assert
72+
$result.title | Should -Be "no front matter" # from file name
73+
}
74+
3375
Context "Front Matter does not contain title" {
3476
It "Should create default title from first heading when available" {
3577

0 commit comments

Comments
 (0)