Ciasto piekarz Ciasto piekarz - 1 month ago 14
Git Question

How to output git diff result side by side with code line numbers to embed in webpage?

I have figured out how to display line numbers and coloured diff using html to embed in email or for a web page, but I am not sure how to go about going for a diff side by side.

Here is my piece of cake to get colour HTML based git diff with line numbers:

openTag = """<span style='font-size:1.0em; color: """
openTagEnd = ";font-family: courier, arial, helvetica, sans-serif;'>"
nbsp = '&nbsp;&nbsp;&nbsp;&nbsp;'

def _traditional_diff(linesfromDiff, openTag, openTagEnd, nbsp):
lines = []
line_num = 0

def updateLine(line_num, color, line):
tabs = line.count('\t')
lines.append("%s:%s#%s%s%s%s</span><br>" %
((repr(line_num), openTag, color, openTagEnd, nbsp*tabs, line)))
return lines

for line in linesfromDiff:
if (line.startswith('diff ') or
line.startswith('index ') or
line.startswith('--- ')):
color = "10EDF5"
updateLine(line_num, color, line)
continue

if line.startswith('-'):
color = "ff0000"
updateLine(line_num, color, line)
continue


if line.startswith('+++ '):
color = "07CB14"
updateLine(line_num, color, line)
continue

if line.startswith('@@ '):
_, old_nr, new_nr, _ = line.split(' ', 3)
line_num = int(new_nr.split(',')[0])
color = "5753BE"
updateLine(line_num, color, line)
continue

if line.startswith('+'):
color = "007900"
updateLine(line_num, color, line)

if line.startswith('+') or line.startswith(' '):
line_num += 1

return ''.join(lines)


Any help will be greatly appreciated. thanks.

Answer

Use the following process:

  • Wrap the openTag in a table column:

    <td>
    
  • Replace nbsp with an end tag for the column:

    </td>
    
  • Put the result of the loop in a table

    <table><tr>%s</tr></table>
    
  • Wrap each line in an ol tag

  • Each line number would be a li tag

References