Last active
August 29, 2015 14:27
-
-
Save trevor-vaughan/91905753c5514cc706cc to your computer and use it in GitHub Desktop.
A script to convert RestructuredText Tables to list-tables
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 | |
# Test your changes using rst2pdf | |
require 'fileutils' | |
input = ARGV[0] | |
tmpfile = %(#{input}.tmp) | |
File.exist?(input) || fail("'#{input}' is not a valid filename") | |
begin | |
output = [] | |
widths = [] | |
headers = 0 | |
table = [] | |
in_row = false | |
File.readlines(input).each do |line| | |
line.chomp! | |
if line =~ /^\s*((\+(-|=))|(\|))/ | |
line_match = $1.nil? ? $2 : $1 | |
row_type = nil | |
case line_match | |
when '+=' then row_type = 'header' | |
when '+-' then row_type = 'plain' | |
when '|' then row_type = 'body' | |
end | |
# Chop of the leading and trailing delimiters for splitting | |
line[0] = '' | |
line[-1] = '' | |
if row_type == 'body' | |
table << %( * - #{line.split(/\s\|\s/).map(&:strip).join("\n - ")}) | |
else | |
in_row = !in_row | |
if widths.empty? | |
widths = line.split('+').map{|x| x.size} | |
end | |
if row_type == 'header' | |
headers += 1 | |
end | |
end | |
elsif !in_row | |
unless table.empty? | |
# Write out the table | |
output << '.. list-table::' | |
output << " :widths: #{widths.join(' ')}" | |
unless headers == 0 | |
output << " :header-rows: #{headers}" | |
end | |
# Add a blank line | |
output << '' | |
output << table.join("\n") | |
output << '' | |
table = [] | |
headers = 0 | |
widths = [] | |
else | |
output << line | |
end | |
else | |
output << line | |
end | |
end | |
tmpfh = File.open(tmpfile,'w') | |
tmpfh.puts(output.join("\n")) | |
tmpfh.flush | |
tmpfh.close | |
FileUtils.mv(tmpfh,input) | |
puts("Updated: #{input}") | |
rescue Exception => e | |
puts("Failed: #{input} => #{e}") | |
exit 1 | |
ensure | |
FileUtlis.rm(tmpfile) if File.exist?(tmpfile) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment