Skip to content

Instantly share code, notes, and snippets.

@77web
Last active August 29, 2015 14:15
Show Gist options
  • Save 77web/2c24d6d52a71eb792f27 to your computer and use it in GitHub Desktop.
Save 77web/2c24d6d52a71eb792f27 to your computer and use it in GitHub Desktop.
特定のディレクトリ配下にあるプレーンな.md,.markdownファイル全部にfrontmatterをつけるスクリプト
<?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