Skip to content

Instantly share code, notes, and snippets.

@Stautob
Last active December 2, 2019 10:21
Show Gist options
  • Save Stautob/f7dda73dfac93492222a42908cf575b1 to your computer and use it in GitHub Desktop.
Save Stautob/f7dda73dfac93492222a42908cf575b1 to your computer and use it in GitHub Desktop.
A python script to convert the output of cloc into a Latex longtable
#!/usr/bin/env python3
import re
import sys
indentation = " "
latexHline = "\\hline"
latexLineBreak = "\\\\"
spacer = "\\hspace{3mm}"
beginTabular = "\\begin{tabular}{lrrrr}"
beginTabularx = "\\begin{tabularx}{\\textwidth}{Xrrrr}"
beginLongtable = "\\begin{longtable}{lrrrr}"
endTabular = "\\end{tabular}"
endTabularx = "\\end{tabularx}"
endLongtable = "\\end{longtable}"
files = sys.argv[1:]
if not files:
files = ["/dev/stdin"]
dataStarted = False
added = (0,0,0,0)
for file in files:
with open(file, 'r') as pse:
print(beginLongtable)
print(f"{indentation}\hiderowcolors")
print(f"{indentation}\caption{{}}\label{{tab:}}")
print(f"{indentation}\endfirsthead\endhead")
print(f"{indentation}\showrowcolors")
for line in pse:
if re.search("^-+$", line):
dataStarted = True
print(f"{indentation}{latexHline}")
elif dataStarted:
match = re.search("^(\s?)(\S+(?:\s\S+)*)\s+([\w|\d]+)\s+([\w|\d]+)\s+([\w|\d]+)\s+([\w|\d]+)$", line)
if match:
if "added" in match.group(2):
added = (int(match.group(3)), int(match.group(4)), int(match.group(5)), int(match.group(6)))
print(
f"{indentation}{spacer if ' ' in match.group(1) else ''}{match.group(2)} & {match.group(3)} & {match.group(4)} & {match.group(5)} & {match.group(6)} {latexLineBreak}")
if "removed" in match.group(2):
print(f"{indentation}{spacer if ' ' in match.group(1) else ''}diff & {added[0]-int(match.group(3)):+d} & {added[1]-int(match.group(4)):+d} & {added[2]-int(match.group(5)):+d} & {added[3]-int(match.group(6)):+d} {latexLineBreak}")
else:
match = re.search("^(.+)$", line)
if match:
print(f"{indentation}{match.group(1)} & & & & {latexLineBreak}")
print(endLongtable)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment