Coverage for farmbot_sidecar_starter_pack/state.py: 100%
54 statements
« prev ^ index » next coverage.py v7.4.4, created at 2024-08-30 13:00 -0700
« prev ^ index » next coverage.py v7.4.4, created at 2024-08-30 13:00 -0700
1"""State management."""
3import json
4import inspect
5from datetime import datetime
7def get_call_stack_depth():
8 """Return the depth of the current call stack."""
9 depth = 0
10 frame = inspect.currentframe()
11 while frame:
12 depth += 1
13 frame = frame.f_back
14 return depth
16def get_function_call_info():
17 """Return the name and given arguments of the function where this is called."""
18 # back to print_status then back to the function that called print_status
19 frame = inspect.currentframe().f_back.f_back
20 func_name = frame.f_code.co_name
21 args, _, _, values = inspect.getargvalues(frame)
22 arg_strings = [f"{arg}={repr(values[arg])}" for arg in args if arg != "self"]
23 arg_str = ", ".join(arg_strings)
24 return f"{func_name}({arg_str})"
27class State():
28 """State class."""
30 NO_TOKEN_ERROR = "ERROR: You have no token, please call `get_token` using your login credentials and the server you wish to connect to."
32 def __init__(self):
33 self.token = None
34 self.error = None
35 self.last_messages = {}
36 self.verbosity = 2
37 self.broker_listen_duration = 15
38 self.test_env = False
39 self.ssl = True
40 self.min_call_stack_depth = 100
41 self.dry_run = False
43 def print_status(self, endpoint_json=None, description=None, update_only=False, end="\n"):
44 """Handle changes to output based on user-defined verbosity."""
45 depth = get_call_stack_depth()
46 if depth < self.min_call_stack_depth:
47 self.min_call_stack_depth = depth
48 top = depth == self.min_call_stack_depth
49 indent = "" if top else " " * 4
51 if self.verbosity >= 2 and not update_only:
52 if top:
53 print()
54 function = get_function_call_info()
55 print(f"{indent}`{function}` called at {datetime.now()}")
56 if self.verbosity >= 1:
57 if self.verbosity == 1 and not update_only and top:
58 print()
59 if description:
60 print(indent + description, end=end, flush=(end == ""))
61 if endpoint_json:
62 json_str = json.dumps(endpoint_json, indent=4)
63 indented_str = indent + json_str.replace("\n", "\n" + indent)
64 print(indented_str)
66 def check_token(self):
67 """Ensure the token persists throughout sidecar."""
69 if self.token is None:
70 self.print_status(description=self.NO_TOKEN_ERROR)
71 self.error = self.NO_TOKEN_ERROR
72 raise ValueError(self.NO_TOKEN_ERROR)