能讓程序做的事情堅決不用人來做——批量修復markdownlint MD034警告
阿新 • • 發佈:2018-03-04
lin .get == AI iter -a ins except pil
歡迎和大家交流技術相關問題:
郵箱: [email protected]
博客園地址: http://www.cnblogs.com/jiangxinnju
GitHub地址: https://github.com/jiangxincode
知乎地址: https://www.zhihu.com/people/jiangxinnju
現在各種編程語言都有自己的lint工具來做靜態檢查,防止一些低級錯誤並維持統一的風格。Markdown這樣的樣式標記語言也不例外,現在大家用的比較多的是markdownlint。該項目開源在github:https://github.com/markdownlint/markdownlint,當前很多實用markdown語言的項目都使用該工具。
markdownlint的檢查規則目前有41項https://github.com/markdownlint/markdownlint/blob/master/docs/RULES.md,其中"MD034 - Bare URL used"是大家經常遇到的問題,如果你在Markdown文檔中使用URL,但是沒有在URL周圍使用<>的話就會產生警告,我維護了一個類似於awesome的項目https://github.com/jiangxincode/cnblogs,其中報了1000多個類似的警告,如果全部手工來修改估計手都回廢掉,因此寫了個小程序在所有的.md文檔中的所有url兩遍加上了<>。
程序使用Java編寫,比較簡單,主要使用了正則表達式的替換,程序如下:
package edu.jiangxin.tools;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Solve the problem of MD034. <p>
* {@link https://github.com/markdownlint/markdownlint/blob/master/docs/RULES.md}
* This program doesn‘t process any exception!
* @author aloys
*
*/
public class MD034Solver {
public static final String regex = "\\b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|$!:,.;]*[A-Z0-9+&@#/%=~_|$]";
public static final String sourceDirStr = "D:\\temp\\cnblogs";
public static final String targetDirStr = "D:\\temp\\cnblogsbak";
public static void main(String[] args) throws IOException {
// Source directory must be a valid directory which contains the text files to be processed.
File sourceDir = new File(sourceDirStr);
// Target directory must be a valid directory which will save the proecessed files.
File targetDir = new File(targetDirStr);
for (File file : sourceDir.listFiles()) {
// take off the .git directory and .gitignore file
if (file.getName().startsWith(".")) {
continue;
}
BufferedReader reader = new BufferedReader(new FileReader(file));
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(targetDir, file.getName())));
String temp = null;
while ((temp = reader.readLine()) != null) {
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
Matcher regexMatcher = pattern.matcher(temp);
StringBuffer sb = new StringBuffer();
while (regexMatcher.find()) {
String group = regexMatcher.group();
int start = regexMatcher.start();
if (start >= 1 && (temp.charAt(start - 1) == ‘<‘ || temp.charAt(start - 1) == ‘(‘)) {
regexMatcher.appendReplacement(sb, group);
} else {
regexMatcher.appendReplacement(sb, "<" + group + ">");
}
}
regexMatcher.appendTail(sb);
writer.write(sb.toString());
writer.newLine();
}
reader.close();
writer.close();
}
}
}
能讓程序做的事情堅決不用人來做——批量修復markdownlint MD034警告