def query(ctx, compact, paths): controller = Controller( logger=LOGGER, terminal_size=ctx.obj["terminal_size"], conf_name=ctx.obj["config"], debug=ctx.obj["debug"], ) controller.setup_logging() controller.setup_resource_graph() resource_graph = controller.resource_graph path_parser = st.PathParser() session = st.create_session() for path in paths: head, *tail = path_parser.split(path) if head not in resource_graph.graph.nodes: click.secho(f"{path} does not exist.", fg="red") raise click.Abort node = resource_graph.graph.nodes[head] obj = st.Object(node["value"], node["type"]) for comp in tail: obj = obj[comp] if compact: print(json.dumps(session.resolve(obj))) else: print(json.dumps(session.resolve(obj), indent=2, sort_keys=True))
def get_object(self, value: Any, registry: st.Registry) -> "Object": if isinstance(value, st.Object): return None try: value_type = registry.infer_type(value) except st.exc.NoTypeFound: return None return st.Object(impl.Data(value, value_type), registry=registry)
def __class_getitem__(self, item: Any) -> Object: """ Get an Unknown object with the given type """ import statey as st typ = st.registry.get_type(item) return st.Object(Unknown(return_type=typ), frame=stack.frame_snapshot(1))
def serialize(self, session: session.Session) -> Any: serialized_ns = self.ns_serializer.serialize(session.ns) objects = {} for key, value in session.data.items(): if isinstance(value, st.Object): objects[key] = value else: typ = session.ns.resolve(key) objects[key] = st.Object(impl.Data(value, typ)) dag = nx.DiGraph() for key, obj in objects.items(): session._build_symbol_dag(obj, dag) serialized_dag = nx.DiGraph() for node in dag.nodes: obj = dag.nodes[node]["symbol"] obj_ser = self.registry.get_object_serializer(obj) serialized = obj_ser.serialize(obj) serialized_dag.add_node(node, object=serialized) serialized_dag.add_edges_from(dag.edges) graph_data = nx.to_dict_of_dicts(serialized_dag) node_data = { node: serialized_dag.nodes[node]["object"] for node in serialized_dag.nodes } obj_id_map = {key: obj._impl.id for key, obj in objects.items()} out = { "graph": graph_data, "data": node_data, "keys": obj_id_map, "ns": serialized_ns, } return PythonSessionSchema().dump(out)
def f(template: str, scope: Optional[Dict[str, Any]] = None) -> Object: """ Interpolation operator for objects """ variables = {} if scope is None else scope.copy() frame = sys._getframe(1) # pylint: disable=protected-access variables.update(frame.f_globals) variables.update(frame.f_locals) nodes = Parser(template).parse() _next = partial(next, itertools.count(1)) next_param = lambda: f"param_{_next()}" out_scope = {} out_nodes = [] for node in nodes: if isinstance(node, Expression): # pylint: disable=protected-access,no-member obj = _eval_name(node._name, node._expr, variables) elif isinstance(node, Constant): # pylint: disable=protected-access,no-member obj = _eval_name(node._name, node._name, variables) else: out_nodes.append(node) continue param_name = next_param() # pylint: disable=protected-access out_scope[param_name] = obj out_nodes.append(Constant(param_name, "{" + param_name + "}")) @st.function def render_nodes(scope: Dict[str, Any]) -> str: return generate(out_nodes, scope) return render_nodes(st.Object(out_scope, Dict[str, Any]))
def get_obj(self, registry: Optional["Registry"] = None) -> "Object": if registry is None: registry = st.registry return st.Object(self.data, self.type, registry)
def bind(self, registry: "Registry") -> None: """ Bind input and output objects to the given registry """ self.__dict__["input"] = st.Object(self.input, registry=registry) self.__dict__["output"] = st.Object(self.output, registry=registry)
def __post_init__(self) -> None: input_obj = st.Object(self.input, self.state.input_type) self.__dict__["input"] = input_obj output_impl = impl.Unknown(refs=(input_obj, ), return_type=self.state.output_type) self.__dict__["output"] = st.Object(output_impl)
import pytest import statey as st @pytest.mark.parametrize( "obj, typ, output", [ pytest.param(st.Object(1), st.Integer, 1, id="literal_int_1"), pytest.param(st.Object(True), st.Boolean, True, id="literal_bool_1"), pytest.param(st.Object[str]("92"), st.String, "92", id="literal_str_1"), pytest.param(st.Object[int]("123"), st.Integer, 123, id="literal_int_2"), pytest.param( st.Object({"a": 1, "b": {"c": "d"}}), st.Struct["a":int, "b" : st.Struct["c":str]], {"a": 1, "b": {"c": "d"}}, id="literal_struct_1", ), pytest.param( st.Object([1, 2, 3]), st.Array[int], [1, 2, 3], id="literal_array_1" ), pytest.param( st.Object(["1", "2", "3"]), st.Array[str], ["1", "2", "3"], id="literal_array_2", ), pytest.param( st.Object(["1", 2, True]), st.Array[st.Any], ["1", 2, True], id="literal_array_3",
async def delete(self, current: StateSnapshot, config: StateConfig, session: TaskSession) -> Object: session["delete_file"] << self.remove_file(current.obj.location) return st.Object({})
def ref(path, typ): return st.Object(st.Reference(path, session.ns), typ)
async def delete(self, session: task.TaskSession, current: resource.StateSnapshot) -> "Object": delete_task = self._get_optional_method("delete_task") ref = session["delete"] << task.new(delete_task)(current.obj) return st.join(st.Object({}, st.EmptyType, session.ns.registry), ref)