Skip to content

Commit 217da5f

Browse files
committed
refactor util functions; update tests; bump version
1 parent 5c075a6 commit 217da5f

File tree

4 files changed

+87
-69
lines changed

4 files changed

+87
-69
lines changed

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,6 @@
6565
setup_requires=setup_requires,
6666
install_requires=requirements,
6767
package_dir={'tdtax': 'tdtax'},
68-
package_data={'tdtax': ['viz_template.html']}
68+
package_data={'tdtax': ['viz_template.html']},
6969
url='https://github.com/profjsb/timedomain-taxonomy'
7070
)

tdtax/__init__.py

Lines changed: 7 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -7,87 +7,29 @@
77
import os
88
from os.path import join as pjoin
99
import json
10-
import pkgutil
11-
import datetime
1210

1311
import yaml
1412
from yaml import Loader
1513
from jsonschema import validate
1614

15+
from .util import write_viz, merge_yamls
1716

1817
_basedir = os.path.dirname(__file__)
1918
schema = json.load(open(pjoin(_basedir, "schema.json"), "r"))
2019

21-
22-
def write_viz(vega_taxonomy, outname="viz.html"):
23-
"""
24-
Use the current taxonomy to vizualize the tree
25-
with d3.
26-
27-
>> import tdtax
28-
>> tdtax.write_viz(tdtax.vega_taxonomy)
29-
30-
"""
31-
text = pkgutil.get_data(__name__, "viz_template.html").decode()
32-
text = text.replace("%%JSON%%", json.dumps(vega_taxonomy))
33-
text = text.replace("%%VERSION%%", __version__)
34-
text = text.replace("%%DATE%%", str(datetime.datetime.utcnow()))
35-
f = open(outname, "w")
36-
f.write(text)
37-
f.close()
38-
print(f"wrote {outname}")
39-
40-
41-
def walk_and_replace(d, path="./", verbose=False):
42-
"""
43-
recursively replace references to YAMLs
44-
"""
45-
if not isinstance(d, dict):
46-
return
47-
48-
for key, value in d.items():
49-
if isinstance(value, dict):
50-
walk_and_replace(value, path=path, verbose=verbose)
51-
elif isinstance(value, list):
52-
for i in range(len(value)):
53-
if isinstance(value[i], dict):
54-
if value[i].get("ref") is not None:
55-
ref = path + value[i].get("ref")
56-
if os.path.exists(ref):
57-
replacement = yaml.load(open(ref), Loader=Loader)
58-
value[i] = replacement
59-
else:
60-
if verbose:
61-
print(
62-
f"Did not find file {ref}."
63-
"Adding placeholder."
64-
)
65-
basename = os.path.basename(ref).split(".")[0]
66-
value[i] = {"class": basename + "-placeholder"}
67-
walk_and_replace(value[i], path=path, verbose=verbose)
68-
69-
70-
def merge_yamls(fname):
71-
taxonomy = yaml.load(open(fname), Loader=Loader)
72-
path = os.path.dirname(fname) + "/"
73-
walk_and_replace(taxonomy, path)
74-
return taxonomy
75-
76-
77-
# get the taxonomy and validate
20+
# get the taxonomy and validate - raise an error if this does
21+
# not validate against the schema
7822
taxonomy = merge_yamls(pjoin(_basedir, "top.yaml"))
7923
validate(instance=taxonomy, schema=schema)
8024

8125
# get a version of the taxonomy suitable for vega/d3 viz
8226
taxstr = json.dumps(taxonomy)
8327
taxstr = taxstr.replace('"class":', '"name":') \
84-
.replace('"subclasses":', '"children":')
28+
.replace('"subclasses":', '"children":')
8529
vega_taxonomy = json.loads(taxstr)
8630

31+
__version__ = '0.0.4'
8732

88-
__all__ = ["taxonomy", "schema", "merge_yamls", "vega_taxonomy", "write_viz"]
89-
90-
__version__ = '0.0.2'
33+
__all__ = ["taxonomy", "schema", "vega_taxonomy", "write_viz", "__version__"]
9134

92-
del (taxstr, walk_and_replace, merge_yamls,
93-
os, json, pkgutil, datetime, yaml, Loader, pjoin)
35+
del (taxstr, merge_yamls, os, json, yaml, Loader, pjoin)

tdtax/test/test_validate.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,12 @@
1-
import tdtax
1+
from tdtax import schema
2+
from tdtax.validate import is_valid
23

34

4-
def test():
5-
tdtax.validate(tdtax.taxonomy, tdtax.taxonomy)
5+
def test_validate_bad_yaml():
6+
ret = is_valid("tdtax/test/bad.yaml", schema)
7+
assert ret.find("not against") != -1
8+
9+
10+
def test_validate_top_yaml():
11+
ret = is_valid("tdtax/top.yaml", schema)
12+
assert ret.find("valid") != -1

tdtax/util.py

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
import os
2+
import json
3+
import pkgutil
4+
import datetime
5+
import ast
6+
7+
import yaml
8+
from yaml import Loader
9+
10+
# Get version without importing module
11+
mod = ast.parse(pkgutil.get_data(__name__, "__init__.py").decode())
12+
assignments = [node for node in mod.body if isinstance(node, ast.Assign)]
13+
__version__ = [node.value.s for node in assignments
14+
if node.targets[0].id == '__version__'][0]
15+
16+
17+
def write_viz(vega_taxonomy, outname="viz.html"):
18+
"""
19+
Use the current taxonomy to vizualize the tree
20+
with d3.
21+
22+
>> import tdtax
23+
>> tdtax.write_viz(tdtax.vega_taxonomy)
24+
25+
"""
26+
text = pkgutil.get_data(__name__, "viz_template.html").decode()
27+
text = text.replace("%%JSON%%", json.dumps(vega_taxonomy))
28+
text = text.replace("%%VERSION%%", __version__)
29+
text = text.replace("%%DATE%%", str(datetime.datetime.utcnow()))
30+
f = open(outname, "w")
31+
f.write(text)
32+
f.close()
33+
print(f"wrote {outname}")
34+
35+
36+
def walk_and_replace(d, path="./", verbose=False):
37+
"""
38+
recursively replace references to YAMLs
39+
"""
40+
if not isinstance(d, dict):
41+
return
42+
43+
for key, value in d.items():
44+
if isinstance(value, dict):
45+
walk_and_replace(value, path=path, verbose=verbose)
46+
elif isinstance(value, list):
47+
for i in range(len(value)):
48+
if isinstance(value[i], dict):
49+
if value[i].get("ref") is not None:
50+
ref = path + value[i].get("ref")
51+
if os.path.exists(ref):
52+
replacement = yaml.load(open(ref), Loader=Loader)
53+
value[i] = replacement
54+
else:
55+
if verbose:
56+
print(
57+
f"Did not find file {ref}."
58+
"Adding placeholder."
59+
)
60+
basename = os.path.basename(ref).split(".")[0]
61+
value[i] = {"class": basename + "-placeholder"}
62+
walk_and_replace(value[i], path=path, verbose=verbose)
63+
64+
65+
def merge_yamls(fname):
66+
taxonomy = yaml.load(open(fname), Loader=Loader)
67+
path = os.path.dirname(fname) + "/"
68+
walk_and_replace(taxonomy, path)
69+
return taxonomy

0 commit comments

Comments
 (0)