comment + refactor renumber
This commit is contained in:
31
bin/renumber
31
bin/renumber
@@ -6,33 +6,40 @@ files = Array(ARGV.shift || Dir.glob("./**/*.md"))
|
|||||||
files.each do |file|
|
files.each do |file|
|
||||||
content = File.read(file)
|
content = File.read(file)
|
||||||
|
|
||||||
|
# First, scan for all references ([#]: at beginning of line)
|
||||||
|
# and look for duplicates
|
||||||
refs = content.scan(/^\[\d+\]:/)
|
refs = content.scan(/^\[\d+\]:/)
|
||||||
|
dups = refs.combination(2).filter_map { |i, j| i if i == j }
|
||||||
|
|
||||||
unless refs == refs.uniq
|
# If duplicate refs detected, this won't work, so bail out
|
||||||
warn "Error in #{file}: duplicate refs detected"
|
if dups.any?
|
||||||
|
warn "Duplicate refs detected in #{file} (#{dups * ", "})"
|
||||||
exit 1
|
exit 1
|
||||||
end
|
end
|
||||||
|
|
||||||
idx = 0
|
idx = 0
|
||||||
code_block = false
|
code_block = false
|
||||||
refs = {}
|
cache = {}
|
||||||
|
|
||||||
updated = content.gsub(/\[\d+\]|```|`/) do |token|
|
# Find all numbered links (in text + references) + code delimeters
|
||||||
|
# (for fenced code blocks, "`" suffices because "```" is an odd number)
|
||||||
|
updated = content.gsub(/\[\d+\]|`/) do |token|
|
||||||
case token
|
case token
|
||||||
when "```", "`"
|
when "`"
|
||||||
|
# We don't want to do substitution inside code blocks
|
||||||
|
# (where `[#]` sometimes occurs) but we do want to toggle
|
||||||
|
# whether or not we're in a code block
|
||||||
code_block = !code_block
|
code_block = !code_block
|
||||||
token
|
token
|
||||||
else
|
else
|
||||||
if code_block
|
# If we're in a code block, just return the token
|
||||||
token
|
# Otherwise, check if the reference has already been assigned
|
||||||
else
|
# - If so, return the cached value
|
||||||
refs[token] ||= "[$$#{idx += 1}]"
|
# - If not, bump the index, cache the value, and return it
|
||||||
end
|
code_block ? token : cache[token] ||= "[#{idx += 1}]"
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
updated.gsub!("$$", "")
|
|
||||||
|
|
||||||
if fix
|
if fix
|
||||||
File.write(file, updated)
|
File.write(file, updated)
|
||||||
elsif content != updated
|
elsif content != updated
|
||||||
|
|||||||
Reference in New Issue
Block a user