-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.py
More file actions
136 lines (108 loc) · 4.79 KB
/
app.py
File metadata and controls
136 lines (108 loc) · 4.79 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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
import argparse
import json
import logging
import sys
from collections import defaultdict
from datetime import UTC, datetime
from operator import attrgetter
from pathlib import Path
from pydantic import ValidationError
from rules_validation_api.decorators.tracker import VALIDATORS_CALLED
from rules_validation_api.validators.rules_validator import RulesValidation
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
force=True,
)
GREEN = "\033[92m"
RESET = "\033[0m"
YELLOW = "\033[93m"
RED = "\033[91m"
BLUE = "\033[34m"
def refine_error(e: ValidationError) -> str:
"""Return a very short, single-line error message."""
lines = [f"❌Validation Error: {len(e.errors())} validation error(s)"]
for err in e.errors():
loc = ".".join(str(x) for x in err["loc"])
msg = err["msg"]
type_ = err["type"]
lines.append(f"{loc} : {msg} [type={type_}]")
return "\n".join(lines)
def main() -> None: # pragma: no cover
parser = argparse.ArgumentParser(description="Validate campaign configuration.")
parser.add_argument("--config_path", required=True, help="Path to the campaign config JSON file")
args = parser.parse_args()
try:
with Path(args.config_path).open() as file:
json_data = json.load(file)
result = RulesValidation(**json_data)
sys.stdout.write(f"{GREEN}Valid Config{RESET}\n")
display_current_iteration(result)
# Group by class
grouped = defaultdict(list)
for v in VALIDATORS_CALLED:
cls, method = v.split(":", 1)
grouped[cls].append(method.strip())
# Print grouped
for cls_name in sorted(grouped.keys(), reverse=True):
methods = sorted(grouped[cls_name])
# First method prints class name
first = methods[0]
colored = f"{BLUE}{cls_name}{RESET}{YELLOW}:{RESET}{GREEN}{first}{RESET}\n"
sys.stdout.write(colored)
# Rest methods indented
for method_name in methods[1:]:
colored = f"{' ' * len(cls_name)}{YELLOW}:{RESET}{GREEN}{method_name}{RESET}\n"
sys.stdout.write(colored)
except ValidationError as e:
clean = refine_error(e)
sys.stderr.write(f"{YELLOW}{clean}{RESET}\n")
def display_current_iteration(result: RulesValidation) -> None:
config = result.campaign_config
iterations = config.iterations
is_campaign_live = config.campaign_live
today = datetime.now(tz=UTC).date()
no_of_iterations = len(iterations)
is_campaign_expired = config.end_date < today
# ---- Current Iteration ----
if is_campaign_live:
sys.stdout.write(f"{YELLOW}Campaign is {RESET}{GREEN}LIVE{RESET}\n")
try:
current = config.current_iteration
if current:
sys.stdout.write(
f"{YELLOW}Current active Iteration Number: {RESET}{GREEN}{current.iteration_number}{RESET}\n"
)
tz = current.iteration_datetime.tzinfo
sys.stdout.write(
f"{YELLOW}Current active Iteration's date&time: "
f"{RESET}{GREEN}{current.iteration_datetime} ({tz}){RESET}\n"
)
except StopIteration:
sys.stdout.write(f"{YELLOW}No active iteration could be determined{RESET}\n")
else:
sys.stdout.write(f"{YELLOW}Campaign is {RESET}{GREEN}NOT LIVE{RESET} ")
if is_campaign_expired:
sys.stdout.write(f"{YELLOW}[EXPIRED on {config.end_date}]{RESET}\n")
else:
sys.stdout.write(f"{YELLOW}[To be STARTED on {RESET}{GREEN}{config.start_date}{RESET}{YELLOW}]{RESET}\n")
# ---- Next Iteration ----
if not is_campaign_expired:
sorted_iterations = sorted(iterations, key=attrgetter("iteration_date"))
try:
next_iteration = next((i for i in sorted_iterations if i.iteration_date > today), None)
if next_iteration:
sys.stdout.write(
f"{YELLOW}Next active Iteration Number: {RESET}{GREEN}{next_iteration.iteration_number}{RESET}\n"
)
tz = next_iteration.iteration_datetime.tzinfo
sys.stdout.write(
f"{YELLOW}Next active Iteration's date&time: "
f"{RESET}{GREEN}{next_iteration.iteration_datetime} ({tz}){RESET}\n"
)
except StopIteration:
sys.stdout.write(f"{YELLOW}No next active iteration could be determined{RESET}\n")
# ---- Total Iterations ----
sys.stdout.write(f"{YELLOW}Total iterations configured: {RESET}{GREEN}{no_of_iterations}{RESET}\n")
if __name__ == "__main__": # pragma: no cover
main()