Last active
August 29, 2015 14:15
-
-
Save 77web/2c24d6d52a71eb792f27 to your computer and use it in GitHub Desktop.
特定のディレクトリ配下にあるプレーンな.md,.markdownファイル全部にfrontmatterをつけるスクリプト
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$targetDir = __DIR__.'/awos'; | |
$dir = dir($targetDir); | |
$mdFiles = []; | |
while ($file = $dir->read()) { | |
if (false !== strpos($file, '.md') || false !== strpos($file, '.markdown')) { | |
$mdFiles[] = $file; | |
} | |
} | |
$dir->close(); | |
$frontmatterWithoutTitle = "---\nlayout: default\n---\n\n"; | |
$frontmatterWithTitle = "---\nlayout: default\ntitle: \"%s\"\n---\n\n"; | |
foreach ($mdFiles as $mdFile) { | |
$content = file_get_contents($targetDir.'/'.$mdFile); | |
if (false === strpos($content, '---')) { | |
// 既にfrontmatterが入っていない場合のみ追加 | |
$title = detectTitle($content); | |
$frontmatter = $title ? sprintf($frontmatterWithTitle, $title) : $frontmatterWithoutTitle; | |
file_put_contents($targetDir.'/'.$mdFile, $frontmatter.$content); | |
} | |
} | |
function detectTitle($content) | |
{ | |
$title = null; | |
if (false !== strpos($content, '===')) { | |
list($title,) = explode('===', $content); | |
$title = str_replace(["\n", "\r"], '', $title); | |
} elseif (false !== strpos($content, '# ')) { | |
foreach (explode("\r", $content) as $line) { | |
if ('#' === $line[0]) { | |
$title = ltrim($title, '#'); | |
break; | |
} | |
} | |
} | |
return $title; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment