-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathschema.py
More file actions
115 lines (86 loc) · 4.27 KB
/
schema.py
File metadata and controls
115 lines (86 loc) · 4.27 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
"""
This module contains all functions for schema handling.
"""
"""
The schema definition for that particular JSON is stored with the JSON file's path
as an object, and the JSON storing the cache is an array-type JSON at the topmost
level. Meaning, cache.json is an array that stores multiple JSON objects, each one
containing 2 attributes, "path" and "schema", where "path" stores the file path of
the JSON and "schema" stores the schema definition of the "JSON".
"""
import json, os
def fetcher(filePath:str):
"""
This function fetches the schema of the JSON (i.e, filePath) if it has been cached in 'cache.json'.
NOTE: This function is not a validator or a definer.
"""
try:
with open("cache.json", "r") as cache:
cacheData = json.load(cache)
except json.JSONDecodeError:
print("'cache.json' is corrupted")
return None
except Exception as e:
print("Unexpected error")
return None
for i in cacheData:
if filePath in os.path.normpath(i["path"]):
schema = i["schema"]
return schema
# Variable for indenting nesting
indent = 4
def schemadef():
"""
This function lets user define schema for a JSON file that has not been recorded in
'cache.json'.
When entering the name of a key, the user may end the key name with a pair of curly
braces ("{}") or square bracket ("[]") to define non scalar data type — dictionary
and list respectively.
If the value if a dictionary, the function will recurse. And at the end it returns
a variable named "schemaDefinition"
"""
global indent
schemaDefinition = {}
arg = f'{" " * indent}'
while True:
while True:
key = input(arg)
key = key.strip()
foundWrongChar = False
if key.endswith("{}") or key.endswith("[]"):
temp = key[:-3]
else:
temp = key
for i in temp:
if i.lower() not in "abcdefghijklmnopqrstuvwxyz0123456789_":
foundWrongChar = True
if foundWrongChar == True:
print(f"{arg} Field name can contain only alphanumeric characters and underscore (_)")
else:
break
if "__end__" not in key:
# Strip any type indicators before checking for duplicates
baseKey = key.removesuffix("[]").removesuffix("{}")
if baseKey not in schemaDefinition:
if key.endswith("[]"): # When the value of a key is a list
schemaDefinition[baseKey] = []
elif key.endswith("{}"): # When the value of a key is a dictionary
indent += 4
schemaDefinition[baseKey] = schemadef()
indent -= 4
else:
schemaDefinition[baseKey] = None
else:
if key.endswith("{}"):
confirm = input(f"{arg}Are you sure you want to remove {baseKey}? (y/n): ")
if confirm.lower() != "y":
pass
else:
print(f"\033[A\033[K{arg}\033[A\033[K{baseKey} \"{baseKey}\" removed")
del schemaDefinition[baseKey]
else:
print(f"{arg}\033[A\033[K{baseKey} \"{baseKey}\" removed")
del schemaDefinition[baseKey]
else:
break
return schemaDefinition