Last active
February 14, 2019 06:16
-
-
Save satour/16f6d657bb82a5b0f7cf2ad9859724d2 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
#!/usr/bin/ruby | |
require 'fileutils' | |
require 'find' | |
require 'uri' | |
@level1 = /^[#][^#]*[^}]$/ | |
@level2 = /^[#][#][^#]*[^}]$/ | |
@level3 = /^[#][#][#][^#]*[^}]$/ | |
@anchorString = /[{][#].*/ | |
@backup = false | |
Find.find('.') {|fname| | |
if ( File.extname(fname) == '.md' || File.extname(fname) == '.markdown' ) | |
FileUtils.copy_file(fname, fname + ".bak") | |
File.open(fname + ".bak", "r") { |original| | |
File.open(fname, "w") { |dist| | |
original.each_line { |line| | |
buffer = line | |
# 既存行の末尾に Gitbook書式 の anchor があれば、一度削除する | |
if @anchorString.match(buffer.chomp) | |
buffer = buffer.gsub!(@anchorString, "") | |
end | |
# 既存行の末尾に Gitbook書式 の anchor を追加する | |
if @level1.match(buffer) | |
buffer = buffer.chomp.strip | |
new_line = "#{buffer} {##{URI.escape(buffer.slice(2..-1))}}\n" | |
dist.write(new_line) | |
elsif @level2.match(buffer) | |
buffer = buffer.chomp.strip | |
new_line = "#{buffer} {##{URI.escape(buffer.slice(3..-1))}}\n" | |
dist.write(new_line) | |
elsif @level3.match(buffer) | |
buffer = buffer.chomp.strip | |
new_line = "#{buffer} {##{URI.escape(buffer.slice(4..-1))}}\n" | |
dist.write(new_line) | |
else | |
dist.write(buffer) | |
end | |
} | |
} | |
} | |
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
TODO