Skip to content

Commit

Permalink
run black
Browse files Browse the repository at this point in the history
  • Loading branch information
ITJamie committed Jun 9, 2024
1 parent cb948af commit e06e02f
Show file tree
Hide file tree
Showing 8 changed files with 53 additions and 63 deletions.
2 changes: 1 addition & 1 deletion netbox_changelog_diff_plugin/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class ChangeLogDiffConfig(PluginConfig):
version = "version"
base_url = "netbox_changelog_diff_plugin"
default_settings = {
'change_log_format': 'yaml',
"change_log_format": "yaml",
}


Expand Down
3 changes: 0 additions & 3 deletions netbox_changelog_diff_plugin/forms.py
Original file line number Diff line number Diff line change
@@ -1,4 +1 @@
from django import forms



1 change: 0 additions & 1 deletion netbox_changelog_diff_plugin/models.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from django.db import models
from django.urls import reverse
from netbox.models import NetBoxModel

1 change: 0 additions & 1 deletion netbox_changelog_diff_plugin/tables.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
import django_tables2 as tables
from netbox.tables import NetBoxTable, ChoiceFieldColumn

18 changes: 9 additions & 9 deletions netbox_changelog_diff_plugin/template_content.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
from netbox.plugins import PluginTemplateExtension
from .utilities.html_differ import styled_diff

class ChangeLogDiffTemplateExtension(PluginTemplateExtension):
model = 'extras.objectchange'

class ChangeLogDiffTemplateExtension(PluginTemplateExtension):
model = "extras.objectchange"

def full_width_page(self):
prechange_data = self.context['object'].prechange_data
postchange_data = self.context['object'].postchange_data
prechange_data = self.context["object"].prechange_data
postchange_data = self.context["object"].postchange_data

leftrightdiffhtml = styled_diff(
prechange_data or dict(),
prechange_data or dict(),
postchange_data or dict(),
)
return self.render('netbox_changelog_diff_plugin/changelogdiff.html',
extra_context={
'leftrightdiffhtml': leftrightdiffhtml
})
return self.render(
"netbox_changelog_diff_plugin/changelogdiff.html", extra_context={"leftrightdiffhtml": leftrightdiffhtml}
)


template_extensions = [ChangeLogDiffTemplateExtension]
2 changes: 1 addition & 1 deletion netbox_changelog_diff_plugin/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
from netbox.views.generic import ObjectChangeLogView


urlpatterns = []
urlpatterns = []
82 changes: 38 additions & 44 deletions netbox_changelog_diff_plugin/utilities/html_differ.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,22 +17,23 @@ class DefaultLexer(RegexLexer):
Simply lex each line as a token.
"""

name = 'Default'
aliases = ['default']
filenames = ['*']
name = "Default"
aliases = ["default"]
filenames = ["*"]

tokens = {
'root': [
(r'.*\n', Text),
"root": [
(r".*\n", Text),
]
}


class DiffHtmlFormatter(HtmlFormatter):
"""
Formats a single source file with pygments and adds diff highlights based on the
Formats a single source file with pygments and adds diff highlights based on the
diff details given.
"""

isLeft = False
diffs = None

Expand All @@ -51,25 +52,21 @@ def getDiffLineNos(self):
if self.isLeft:
if change:
if isinstance(left_no, int) and isinstance(right_no, int):
no = '<span class="lineno_q lineno_leftchange">' + \
str(left_no) + "</span>"
no = '<span class="lineno_q lineno_leftchange">' + str(left_no) + "</span>"
elif isinstance(left_no, int) and not isinstance(right_no, int):
no = '<span class="lineno_q lineno_leftdel">' + \
str(left_no) + "</span>"
no = '<span class="lineno_q lineno_leftdel">' + str(left_no) + "</span>"
elif not isinstance(left_no, int) and isinstance(right_no, int):
no = '<span class="lineno_q lineno_leftadd"> </span>'
else:
no = '<span class="lineno_q">' + str(left_no) + "</span>"
else:
if change:
if isinstance(left_no, int) and isinstance(right_no, int):
no = '<span class="lineno_q lineno_rightchange">' + \
str(right_no) + "</span>"
no = '<span class="lineno_q lineno_rightchange">' + str(right_no) + "</span>"
elif isinstance(left_no, int) and not isinstance(right_no, int):
no = '<span class="lineno_q lineno_rightdel"> </span>'
elif not isinstance(left_no, int) and isinstance(right_no, int):
no = '<span class="lineno_q lineno_rightadd">' + \
str(right_no) + "</span>"
no = '<span class="lineno_q lineno_rightadd">' + str(right_no) + "</span>"
else:
no = '<span class="lineno_q">' + str(right_no) + "</span>"

Expand All @@ -79,7 +76,7 @@ def getDiffLineNos(self):

def _wrap_code(self, source):
source = list(source)
yield 0, ''
yield 0, ""

for idx, ((left_no, left_line), (right_no, right_line), change) in enumerate(self.diffs):
# print idx, ((left_no, left_line),(right_no, right_line),change)
Expand Down Expand Up @@ -132,7 +129,7 @@ def _wrap_code(self, source):
except:
# print "WARNING! failed to enumerate diffs fully!"
pass # this is expected sometimes
yield 0, '\n'
yield 0, "\n"

def _wrap_tablelinenos(self, inner):
dummyoutfile = io.StringIO()
Expand All @@ -150,11 +147,9 @@ def _wrap_tablelinenos(self, inner):
aln = self.anchorlinenos
nocls = self.noclasses



yield 0, (f'<table width="100%" class="{self.cssclass}"><tr></div></td><td class="code">')
yield 0, dummyoutfile.getvalue()
yield 0, '</td></tr></table>'
yield 0, "</td></tr></table>"


class CodeDiff(object):
Expand All @@ -164,26 +159,24 @@ class CodeDiff(object):
"""

def __init__(self, fromtxt, totxt, name=None):

self.fromlines = [n + "\n" for n in fromtxt.split("\n")]
self.leftcode = "".join(self.fromlines)


self.tolines = [n + "\n" for n in totxt.split("\n")]
self.rightcode = "".join(self.tolines)

def getDiffDetails(self, fromdesc='', todesc='', context=False, numlines=5, tabSize=8):
def getDiffDetails(self, fromdesc="", todesc="", context=False, numlines=5, tabSize=8):
# change tabs to spaces before it gets more difficult after we insert
# markkup
def expand_tabs(line):
# hide real spaces
line = line.replace(' ', '\0')
line = line.replace(" ", "\0")
# expand tabs into spaces
line = line.expandtabs(tabSize)
# replace spaces from expanded tabs back into tab characters
# (we'll replace them with markup after we do differencing)
line = line.replace(' ', '\t')
return line.replace('\0', ' ').rstrip('\n')
line = line.replace(" ", "\t")
return line.replace("\0", " ").rstrip("\n")

self.fromlines = [expand_tabs(line) for line in self.fromlines]
self.tolines = [expand_tabs(line) for line in self.tolines]
Expand All @@ -194,29 +187,29 @@ def expand_tabs(line):
else:
context_lines = None

diffs = difflib._mdiff(self.fromlines, self.tolines, context_lines,
linejunk=None, charjunk=difflib.IS_CHARACTER_JUNK)
diffs = difflib._mdiff(
self.fromlines, self.tolines, context_lines, linejunk=None, charjunk=difflib.IS_CHARACTER_JUNK
)
return list(diffs)

def format(self, verbose=False):
self.diffs = self.getDiffDetails('a', 'b')
self.diffs = self.getDiffDetails("a", "b")

if verbose:
for diff in self.diffs:
print("%-6s %-80s %-80s" % (diff[2], diff[0], diff[1]))

fields = ((self.leftcode, True),
(self.rightcode, False))
fields = ((self.leftcode, True), (self.rightcode, False))

codeContents = []
for (code, isLeft) in fields:

inst = DiffHtmlFormatter(isLeft,
self.diffs,
nobackground=False,
linenos=True,
#style=options.syntax_css
)
for code, isLeft in fields:
inst = DiffHtmlFormatter(
isLeft,
self.diffs,
nobackground=False,
linenos=True,
# style=options.syntax_css
)

self.lexer = DefaultLexer()

Expand All @@ -225,27 +218,28 @@ def format(self, verbose=False):
codeContents.append(formatted)

answers = {
"left": codeContents[0],
"right": codeContents[1],
"left": codeContents[0],
"right": codeContents[1],
}

return answers


def styled_diff(old, new):
"""
returns styled output
"""

if "last_updated" in old:
old.pop("last_updated")
old.pop("last_updated")
if "last_updated" in new:
new.pop("last_updated")

if get_plugin_setting('change_log_format') == 'yaml':
if get_plugin_setting("change_log_format") == "yaml":
# old['output_format'] = 'yaml'
old = yaml.dump(old, sort_keys=False)
new = yaml.dump(new, sort_keys=False)
elif get_plugin_setting('change_log_format') == 'json':
elif get_plugin_setting("change_log_format") == "json":
# old['output_format'] = 'json'
old = json.dumps(old, indent=2)
new = json.dumps(new, indent=2)
Expand All @@ -255,4 +249,4 @@ def styled_diff(old, new):
new = yaml.dump(new, sort_keys=False)

codeDiff = CodeDiff(old, new)
return codeDiff.format()
return codeDiff.format()
7 changes: 4 additions & 3 deletions netbox_changelog_diff_plugin/utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from django.conf import settings


def get_plugin_setting(setting_name):
plugin_settings = settings.PLUGINS_CONFIG['netbox_changelog_diff_plugin']
assert setting_name in plugin_settings, f'Setting {setting_name} not supported'
return plugin_settings[setting_name]
plugin_settings = settings.PLUGINS_CONFIG["netbox_changelog_diff_plugin"]
assert setting_name in plugin_settings, f"Setting {setting_name} not supported"
return plugin_settings[setting_name]

0 comments on commit e06e02f

Please sign in to comment.