summaryrefslogtreecommitdiff
path: root/bin/yamlbrowser
blob: 7b5e9a99355e5091ebea19544fbd5abc91148fb6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#!/usr/bin/env python3

import sys
import yaml
from qtpy import QtGui, QtWidgets, QtCore
from qtpy.QtWidgets import QApplication, QTreeWidget, QTreeWidgetItem, QLabel
from datetime import datetime

def _make_children (parent:QTreeWidgetItem, d) -> QTreeWidgetItem:
	"""
	If the item is a container item, i.e. list or dict,
	its contents are added as children to the parent.

	If the item is not a container item,
	it becomes the value to its parent.
	"""
	def transform_l (p:QTreeWidgetItem, d:list) -> QTreeWidgetItem:
		p.addChildren (_make_children (QTreeWidgetItem (), x) for x in d)
		return p
	def transform_d (p:QTreeWidgetItem, d:dict) -> QTreeWidgetItem:
		p.addChildren (_make_children (QTreeWidgetItem ([key]), value) for key, value in d.items ())
		return p
	return {
		list:	lambda p, d : transform_l (p, d)
	,	dict:	lambda p, d : transform_d (p, d)
	,	str:	lambda p, d : QTreeWidgetItem ([p.text (0), d])
	,	int:	lambda p, d : QTreeWidgetItem ([p.text (0), str(d)])
	,	float:	lambda p, d : QTreeWidgetItem ([p.text (0), str(d)])
	,	bool:	lambda p, d : QTreeWidgetItem ([p.text (0), str(d)])
	,	datetime:	lambda p, d : QTreeWidgetItem ([p.text (0), str(d)])
	,	type(None):	lambda p, d : QTreeWidgetItem ([p.text (0), str(d)])
	}[type (d)] (parent, d)

def main ():
	app = QApplication (sys.argv)
	# TODO: Check for suitable arguments first.
	# Parameter may be a Qt option.
	if len (sys.argv) == 1:
		print ("Usage:", sys.argv[0], "[file …]", file=sys.stderr)
		return
	try:
		items = []
		for arg in sys.argv[1:]:
			with open (arg) as file:
				data = list (yaml.safe_load_all (file))
			items.append (_make_children (QTreeWidgetItem ([arg]), data[0] if len (data) == 1 else data))

		tree = QTreeWidget ()
		tree.setColumnCount (2)
		tree.setHeaderLabels (["Key", "Value"])
		tree.insertTopLevelItems(0, items)
		tree.show ()
	except Exception as x:
		print (x, file=sys.stderr)
		label = QtWidgets.QLabel (str(x))
		label.show ()	# Opens window.
	sys.exit (app.exec_())	# Main loop.  Display the label.

if __name__=='__main__':
	main ()