Last active
February 14, 2019 07:50
-
-
Save satour/d2c50341e83a20bc0cef2383107c391c 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
#requires ruby 2.4.0p0 | |
require 'find' | |
require 'fileutils' | |
require 'tempfile' | |
require 'uri' | |
=begin | |
1. なにをするスクリプトか? | |
- Markdown ファイルの中を読み取り、その中に記述されているH行を表として Markdown ファイルの先頭に追記します。 | |
- Gitbook 形式で書かれた Markdown ファイルを想定しています。 | |
- このスクリプトを実行したディレクトリ以下にあるすべての *md および *.markdown ファイルが変更対象になります。 | |
2. 挙動 | |
- 各記事のみだしは、一番最初のみだしは Headline level1, それ以降は Headline Level2 で書かれている想定です。 | |
- 各記事の Headline Level1 および Level2 を Numbered List として一覧化し、Gitbook の"最終更新日"アノテーションの下の行に追加します。 | |
--- | |
lastUpdated: 2019-01-16 | |
--- | |
=end | |
@h1 = /^[#][^#]/ | |
@h2 = /^[#][#][^#]/ | |
@anchorString = /[{][#].*[}]/ | |
@devider = "---\n" | |
@backup = false | |
Find.find('.') {|fname| | |
if ( File.extname(fname) == '.md' || File.extname(fname) == '.markdown' ) | |
FileUtils.copy_file(fname, fname + ".bak") | |
list_headlines = [] | |
count_devider = 0 | |
File.open(fname, "r") { |original_file| | |
original_file.each_with_index { |line, i| | |
buffer = line; title = ""; href = "" | |
if anchor = @anchorString.match(buffer.chomp) | |
href = anchor[0].gsub(/{/, "(").gsub(/}/, ")").strip | |
end | |
if @h1.match(buffer.chomp) | |
title = buffer.chomp[2..-1].gsub(@anchorString, "").strip | |
list_headlines << "1. [#{title}]#{href}\n" | |
end | |
if @h2.match(buffer.chomp) | |
title = buffer.chomp[3..-1].gsub(@anchorString, "").strip | |
list_headlines << "1. [#{title}]#{href}\n" | |
end | |
} | |
} | |
tf = Tempfile.open | |
File.open(fname, "r") {|original_file| | |
original_file.each {|line| | |
if line == @devider | |
count_devider += 1 | |
if count_devider == 2 | |
unless list_headlines.empty? | |
line = line + "\n----\n" + list_headlines.join('') + "----\n" | |
end | |
end | |
end | |
tf.print(line) | |
} | |
} | |
tf.close | |
FileUtils.copy_file(tf, fname) | |
FileUtils.rm(fname + ".bak") unless @backup | |
end | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment