Skip to content

Commit bc69e83

Browse files
committed
Refactoring: Move all report renderers to grafana_wtf.report
1 parent 33f6da7 commit bc69e83

File tree

5 files changed

+72
-66
lines changed

5 files changed

+72
-66
lines changed

CHANGES.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ in progress
99
- Caching: Increase default cache TTL to five minutes again
1010
- Caching: Optionally configure TTL using environment variable ``CACHE_TTL``
1111
- History: Stop ``grafana-wtf log <UID>`` acquiring *all* dashboards
12+
- Refactoring: Move all report renderers to ``grafana_wtf.report``
1213

1314
2023-03-05 0.14.1
1415
=================

grafana_wtf/commands.py

Lines changed: 6 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,16 @@
44
import json
55
import logging
66
import os
7-
from collections import OrderedDict
87
from functools import partial
98
from operator import itemgetter
109
from typing import List
1110

1211
from docopt import DocoptExit, docopt
13-
from tabulate import tabulate
1412

1513
from grafana_wtf import __appname__, __version__
1614
from grafana_wtf.core import GrafanaWtf
17-
from grafana_wtf.report import WtfReport
18-
from grafana_wtf.tabular_report import TabularReport
15+
from grafana_wtf.report.textual import TextualSearchReport
16+
from grafana_wtf.report.tabular import TabularSearchReport, get_table_format, TabularEditHistoryReport
1917
from grafana_wtf.util import (
2018
configure_http_logging,
2119
normalize_options,
@@ -212,9 +210,9 @@ def run():
212210

213211
if output_format.startswith("tabular"):
214212
table_format = get_table_format(output_format)
215-
generator = partial(TabularReport, tblfmt=table_format)
213+
generator = partial(TabularSearchReport, tblfmt=table_format)
216214
else:
217-
generator = WtfReport
215+
generator = TextualSearchReport
218216

219217
report = generator(grafana_url, verbose=options.verbose)
220218
report.display(options.search_expression, result)
@@ -231,15 +229,12 @@ def run():
231229
count = int(options.number)
232230
entries = entries[:count]
233231

234-
# TODO: Refactor tabular formatting to WtfTabularReport class.
235-
# https://bitbucket.org/astanin/python-tabulate
236232
if output_format == "json":
237233
output = json.dumps(entries, indent=4)
238234

239235
elif output_format.startswith("tabular"):
240-
table_format = get_table_format(output_format)
241-
entries = compact_table(to_table(entries), output_format)
242-
output = tabulate(entries, headers="keys", tablefmt=table_format)
236+
report = TabularEditHistoryReport(data=entries)
237+
output = report.render(output_format)
243238

244239
else:
245240
raise ValueError(f'Unknown output format "{output_format}"')
@@ -275,53 +270,3 @@ def output_results(output_format: str, results: List):
275270
raise ValueError(f'Unknown output format "{output_format}"')
276271

277272
print(output)
278-
279-
280-
def get_table_format(output_format):
281-
tablefmt = None
282-
if output_format is not None and output_format.startswith("tabular"):
283-
try:
284-
tablefmt = output_format.split(":")[1]
285-
except:
286-
tablefmt = "psql"
287-
288-
return tablefmt
289-
290-
291-
def to_table(entries):
292-
for entry in entries:
293-
item = entry
294-
name = item["title"]
295-
if item["folder"]:
296-
name = item["folder"].strip() + " » " + name.strip()
297-
item["name"] = name.strip(" 🤓")
298-
# del item['url']
299-
del item["folder"]
300-
del item["title"]
301-
del item["version"]
302-
yield item
303-
304-
305-
def compact_table(entries, format):
306-
seperator = "\n"
307-
if format.endswith("pipe"):
308-
seperator = "<br/>"
309-
for entry in entries:
310-
item = OrderedDict()
311-
if format.endswith("pipe"):
312-
link = "[{}]({})".format(entry["name"], entry["url"])
313-
else:
314-
link = "Name: {}\nURL: {}".format(entry["name"], entry["url"])
315-
item["Dashboard"] = seperator.join(
316-
[
317-
"Notes: {}".format(entry["message"].capitalize() or "n/a"),
318-
link,
319-
]
320-
)
321-
item["Update"] = seperator.join(
322-
[
323-
"User: {}".format(entry["user"]),
324-
"Date: {}".format(entry["datetime"]),
325-
]
326-
)
327-
yield item

grafana_wtf/report/__init__.py

Whitespace-only changes.

grafana_wtf/tabular_report.py renamed to grafana_wtf/report/tabular.py

Lines changed: 64 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,21 @@
55
from munch import Munch
66
from tabulate import tabulate
77

8-
from grafana_wtf.report import WtfReport
8+
from grafana_wtf.report.textual import TextualSearchReport
99

1010

11-
class TabularReport(WtfReport):
11+
def get_table_format(output_format):
12+
tablefmt = None
13+
if output_format is not None and output_format.startswith("tabular"):
14+
try:
15+
tablefmt = output_format.split(":")[1]
16+
except:
17+
tablefmt = "psql"
18+
19+
return tablefmt
20+
21+
22+
class TabularSearchReport(TextualSearchReport):
1223
def __init__(self, grafana_url, tblfmt="psql", verbose=False):
1324
self.format = tblfmt
1425
super().__init__(grafana_url, verbose=verbose)
@@ -63,3 +74,54 @@ def get_datasources(self, item):
6374
datasources.append(value)
6475

6576
return datasources
77+
78+
79+
class TabularEditHistoryReport:
80+
81+
def __init__(self, data):
82+
self.data = data
83+
84+
def render(self, output_format: str):
85+
table_format = get_table_format(output_format)
86+
entries = self.compact_table(self.to_table(self.data), output_format)
87+
output = tabulate(entries, headers="keys", tablefmt=table_format)
88+
return output
89+
90+
@staticmethod
91+
def to_table(entries):
92+
for entry in entries:
93+
item = entry
94+
name = item["title"]
95+
if item["folder"]:
96+
name = item["folder"].strip() + " » " + name.strip()
97+
item["name"] = name.strip(" 🤓")
98+
# del item['url']
99+
del item["folder"]
100+
del item["title"]
101+
del item["version"]
102+
yield item
103+
104+
@staticmethod
105+
def compact_table(entries, format):
106+
seperator = "\n"
107+
if format.endswith("pipe"):
108+
seperator = "<br/>"
109+
for entry in entries:
110+
item = OrderedDict()
111+
if format.endswith("pipe"):
112+
link = "[{}]({})".format(entry["name"], entry["url"])
113+
else:
114+
link = "Name: {}\nURL: {}".format(entry["name"], entry["url"])
115+
item["Dashboard"] = seperator.join(
116+
[
117+
"Notes: {}".format(entry["message"].capitalize() or "n/a"),
118+
link,
119+
]
120+
)
121+
item["Update"] = seperator.join(
122+
[
123+
"User: {}".format(entry["user"]),
124+
"Date: {}".format(entry["datetime"]),
125+
]
126+
)
127+
yield item

grafana_wtf/report.py renamed to grafana_wtf/report/textual.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,16 @@
44
import logging
55
import textwrap
66
from collections import OrderedDict
7-
from pprint import pprint
87
from urllib.parse import urljoin
98

109
import colored
11-
from six import StringIO
1210

1311
from grafana_wtf.util import format_dict, prettify_json
1412

1513
log = logging.getLogger(__name__)
1614

1715

18-
class WtfReport:
16+
class TextualSearchReport:
1917
def __init__(self, grafana_url, verbose=False):
2018
self.grafana_url = grafana_url
2119
self.verbose = verbose

0 commit comments

Comments
 (0)