Skip to content

Instantly share code, notes, and snippets.

@mimoo
Created May 2, 2017 14:56
Show Gist options
  • Save mimoo/02f6e181bbf8f16f768d23079a1732ef to your computer and use it in GitHub Desktop.
Save mimoo/02f6e181bbf8f16f768d23079a1732ef to your computer and use it in GitHub Desktop.
Parse a porcelain output from git diff
import re
css_add = """
.add{
background-color:rgba(0, 255, 0, .2);
}
.remove{
background-color:rgba(255, 0, 0, .2);
color:black;
}
"""
def am_I_inside_a_tag(line):
match = re.match( r'^[^<]*>', line)
match2 = re.match( r'<[^>]*$', line)
if match or match2:
return True
else:
return False
def main():
# read file
with open("diff.html") as f:
content = f.readlines()
# output
output_html = ""
# detect head
still_in_head = True
# line by line
for line in content:
# parse porcelain output
if line[0] == "~":
output_html += "\n"
elif line[0] == " ":
output_html += line[1:-1]
if line[1:7] == "<style":
output_html += css_add
elif line[0] == "+":
if not still_in_head and not am_I_inside_a_tag(line):
output_html += "<span class=\"add\">" + line[1:-1] + "</span>"
else:
output_html += line[1:-1]
elif line[0] == "-":
if not still_in_head and not am_I_inside_a_tag(line):
output_html += "<span class=\"remove\">" + line[1:-1] + "</span>"
else:
print "error"
break
# am I inside a tag?
if line[1:8] == "</head>":
still_in_head = False
# print output
print output_html
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment