Created
July 26, 2020 10:51
-
-
Save zhaoyibo/049a82a68a671d5b38f231a3b2ff65cd to your computer and use it in GitHub Desktop.
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
package com.haoyizebo; | |
import org.yaml.snakeyaml.DumperOptions; | |
import org.yaml.snakeyaml.Yaml; | |
import java.io.File; | |
import java.io.IOException; | |
import java.nio.charset.StandardCharsets; | |
import java.nio.file.Files; | |
import java.text.SimpleDateFormat; | |
import java.util.*; | |
/** | |
* <p> | |
* 去除 hexo front matter 里无用的 permalink 和 id | |
* <p> | |
* 并根据文件名添加 addrlink | |
* <p> | |
* dependency: <a href="https://mvnrepository.com/artifact/org.yaml/snakeyaml">SnakeYAML</a> | |
* | |
* @author yibo | |
*/ | |
public class HexoFrontMatterBatchProcess { | |
public static void main(String[] args) throws IOException { | |
// 设置 yaml 输出格式 | |
DumperOptions options = new DumperOptions(); | |
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); | |
options.setPrettyFlow(true); | |
options.setIndent(4); | |
options.setIndicatorIndent(2); | |
options.setTimeZone(TimeZone.getTimeZone("+8")); | |
Yaml yaml = new Yaml(options); | |
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); | |
File postDir = new File("/Users/yibo/hexo-blog/source/_posts"); | |
for (File file : Objects.requireNonNull(postDir.listFiles())) { | |
String fileName = file.getName(); | |
if (fileName.equals(".DS_Store")) { | |
continue; | |
} | |
// 文件名示例 2016-01-03-golang-note-1.md | |
String title = fileName.substring(11, fileName.length() - 3); | |
List<String> lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); | |
// 第一行是 --- 忽略 | |
int lineNum = 1; | |
// 获取 front matter | |
StringBuilder frontMatterBuilder = new StringBuilder(); | |
while (true) { | |
String line = lines.get(lineNum); | |
if (line.trim().equals("---")) { | |
break; | |
} | |
lineNum++; | |
frontMatterBuilder.append(line).append("\n"); | |
} | |
// 处理 front matter | |
Map<String, Object> frontMatterMap = yaml.load(frontMatterBuilder.toString()); | |
frontMatterMap.remove("id"); | |
frontMatterMap.remove("permalink"); | |
frontMatterMap.put("addrlink", title); | |
// 需要将 Date 转为 String,否则默认的格式不对 | |
Object date = frontMatterMap.get("date"); | |
if (date instanceof Date) { | |
frontMatterMap.put("date", sdf.format(date)); | |
} | |
String frontMatter = yaml.dump(frontMatterMap); | |
// 正文内容 | |
String content = String.join("\n", lines.subList(lineNum + 1, lines.size())); | |
// | |
String post = "---\n" + | |
frontMatter + | |
"---\n" + | |
content; | |
Files.write(file.toPath(), post.getBytes()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment