Make scripts/objects lists use EvMore. Change EvMore to not justify by default.

This commit is contained in:
Griatch 2020-01-11 15:49:12 +01:00
parent b5aee2c41e
commit 69d85bd184
221 changed files with 2190 additions and 6810 deletions

View file

@ -53,9 +53,9 @@ def _get_flat_menu_prototype(caller, refresh=False, validate=False):
flat_prototype = caller.ndb._menutree.olc_flat_prototype
if not flat_prototype:
prot = _get_menu_prototype(caller)
caller.ndb._menutree.olc_flat_prototype = (
flat_prototype
) = spawner.flatten_prototype(prot, validate=validate)
caller.ndb._menutree.olc_flat_prototype = flat_prototype = spawner.flatten_prototype(
prot, validate=validate
)
return flat_prototype
@ -110,9 +110,7 @@ def _format_option_value(prop, required=False, prototype=None, cropper=None):
if not out and required:
out = "|runset"
if out:
return " ({}|n)".format(
cropper(out) if cropper else utils.crop(out, _MENU_CROP_WIDTH)
)
return " ({}|n)".format(cropper(out) if cropper else utils.crop(out, _MENU_CROP_WIDTH))
return ""
@ -155,9 +153,7 @@ def _set_property(caller, raw_string, **kwargs):
except Exception as err:
caller.msg(
"Could not set {prop} to {value} ({err})".format(
prop=prop.replace("_", "-").capitalize(),
value=raw_string,
err=str(err),
prop=prop.replace("_", "-").capitalize(), value=raw_string, err=str(err)
)
)
# this means we'll re-run the current node.
@ -177,11 +173,7 @@ def _set_property(caller, raw_string, **kwargs):
except Exception:
repr_value = value
out = [
" Set {prop} to {value} ({typ}).".format(
prop=prop, value=repr_value, typ=type(value)
)
]
out = [" Set {prop} to {value} ({typ}).".format(prop=prop, value=repr_value, typ=type(value))]
if kwargs.get("test_parse", True):
out.append(" Simulating prototype-func parsing ...")
@ -190,9 +182,7 @@ def _set_property(caller, raw_string, **kwargs):
out.append(" |yPython `literal_eval` warning: {}|n".format(err))
if parsed_value != value:
out.append(
" |g(Example-)value when parsed ({}):|n {}".format(
type(parsed_value), parsed_value
)
" |g(Example-)value when parsed ({}):|n {}".format(type(parsed_value), parsed_value)
)
else:
out.append(" |gNo change when parsed.")
@ -209,9 +199,7 @@ def _wizard_options(curr_node, prev_node, next_node, color="|W", search=False):
options.append(
{
"key": ("|wB|Wack", "b"),
"desc": "{color}({node})|n".format(
color=color, node=prev_node.replace("_", "-")
),
"desc": "{color}({node})|n".format(color=color, node=prev_node.replace("_", "-")),
"goto": "node_{}".format(prev_node),
}
)
@ -219,9 +207,7 @@ def _wizard_options(curr_node, prev_node, next_node, color="|W", search=False):
options.append(
{
"key": ("|wF|Worward", "f"),
"desc": "{color}({node})|n".format(
color=color, node=next_node.replace("_", "-")
),
"desc": "{color}({node})|n".format(color=color, node=next_node.replace("_", "-")),
"goto": "node_{}".format(next_node),
}
)
@ -278,16 +264,13 @@ def _validate_prototype(prototype):
def _format_protfuncs():
out = []
sorted_funcs = [
(key, func)
for key, func in sorted(protlib.PROT_FUNCS.items(), key=lambda tup: tup[0])
(key, func) for key, func in sorted(protlib.PROT_FUNCS.items(), key=lambda tup: tup[0])
]
for protfunc_name, protfunc in sorted_funcs:
out.append(
"- |c${name}|n - |W{docs}".format(
name=protfunc_name,
docs=utils.justify(
protfunc.__doc__.strip(), align="l", indent=10
).strip(),
docs=utils.justify(protfunc.__doc__.strip(), align="l", indent=10).strip(),
)
)
return "\n ".join(out)
@ -296,15 +279,13 @@ def _format_protfuncs():
def _format_lockfuncs():
out = []
sorted_funcs = [
(key, func)
for key, func in sorted(get_all_lockfuncs().items(), key=lambda tup: tup[0])
(key, func) for key, func in sorted(get_all_lockfuncs().items(), key=lambda tup: tup[0])
]
for lockfunc_name, lockfunc in sorted_funcs:
doc = (lockfunc.__doc__ or "").strip()
out.append(
"- |c${name}|n - |W{docs}".format(
name=lockfunc_name,
docs=utils.justify(doc, align="l", indent=10).strip(),
name=lockfunc_name, docs=utils.justify(doc, align="l", indent=10).strip()
)
)
return "\n".join(out)
@ -329,9 +310,7 @@ def _format_list_actions(*args, **kwargs):
return prefix + " |W|||n ".join(actions)
def _get_current_value(
caller, keyname, comparer=None, formatter=str, only_inherit=False
):
def _get_current_value(caller, keyname, comparer=None, formatter=str, only_inherit=False):
"""
Return current value, marking if value comes from parent or set in this prototype.
@ -494,8 +473,7 @@ def _search_object(caller):
else:
keyquery = Q(db_key__istartswith=searchstring)
aliasquery = Q(
db_tags__db_key__istartswith=searchstring,
db_tags__db_tagtype__iexact="alias",
db_tags__db_key__istartswith=searchstring, db_tags__db_tagtype__iexact="alias"
)
results = ObjectDB.objects.filter(keyquery | aliasquery).distinct()
@ -524,10 +502,7 @@ def _object_search_actions(caller, raw_inp, **kwargs):
"All this does is to queue a search query"
choices = kwargs["available_choices"]
obj_entry, action = _default_parse(
raw_inp,
choices,
("examine", "e"),
("create prototype from object", "create", "c"),
raw_inp, choices, ("examine", "e"), ("create prototype from object", "create", "c")
)
raw_inp = raw_inp.strip()
@ -589,9 +564,7 @@ def node_search_object(caller, raw_inp, **kwargs):
)
_set_actioninfo(
caller,
_format_list_actions(
"examine", "create prototype from object", prefix="Actions: "
),
_format_list_actions("examine", "create prototype from object", prefix="Actions: "),
)
else:
text = "Enter search criterion."
@ -609,9 +582,7 @@ def node_search_object(caller, raw_inp, **kwargs):
text = (text, helptext)
options = _wizard_options(None, prev_node, None)
options.append(
{"key": "_default", "goto": (_object_search_actions, {"back": prev_node})}
)
options.append({"key": "_default", "goto": (_object_search_actions, {"back": prev_node})})
return text, options
@ -679,9 +650,7 @@ def node_index(caller):
options.append(
{
"desc": "|WPrototype-Key|n|n{}".format(
_format_option_value(
"Key", "prototype_key" not in prototype, prototype, None
)
_format_option_value("Key", "prototype_key" not in prototype, prototype, None)
),
"goto": "node_prototype_key",
}
@ -702,9 +671,7 @@ def node_index(caller):
required = False
cropper = None
if key in ("Prototype_Parent", "Typeclass"):
required = ("prototype_parent" not in prototype) and (
"typeclass" not in prototype
)
required = ("prototype_parent" not in prototype) and ("typeclass" not in prototype)
if key == "Typeclass":
cropper = _path_cropper
options.append(
@ -730,26 +697,11 @@ def node_index(caller):
options.extend(
(
{
"key": ("|wV|Walidate prototype", "validate", "v"),
"goto": "node_validate_prototype",
},
{
"key": ("|wSA|Wve prototype", "save", "sa"),
"goto": "node_prototype_save",
},
{
"key": ("|wSP|Wawn prototype", "spawn", "sp"),
"goto": "node_prototype_spawn",
},
{
"key": ("|wLO|Wad prototype", "load", "lo"),
"goto": "node_prototype_load",
},
{
"key": ("|wSE|Warch objects|n", "search", "se"),
"goto": "node_search_object",
},
{"key": ("|wV|Walidate prototype", "validate", "v"), "goto": "node_validate_prototype"},
{"key": ("|wSA|Wve prototype", "save", "sa"), "goto": "node_prototype_save"},
{"key": ("|wSP|Wawn prototype", "spawn", "sp"), "goto": "node_prototype_spawn"},
{"key": ("|wLO|Wad prototype", "load", "lo"), "goto": "node_prototype_load"},
{"key": ("|wSE|Warch objects|n", "search", "se"), "goto": "node_search_object"},
)
)
@ -827,11 +779,7 @@ def _prototype_parent_actions(caller, raw_inp, **kwargs):
"""Parse the default Convert prototype to a string representation for closer inspection"""
choices = kwargs.get("available_choices", [])
prototype_parent, action = _default_parse(
raw_inp,
choices,
("examine", "e", "l"),
("add", "a"),
("remove", "r", "delete", "d"),
raw_inp, choices, ("examine", "e", "l"), ("add", "a"), ("remove", "r", "delete", "d")
)
if prototype_parent:
@ -853,11 +801,7 @@ def _prototype_parent_actions(caller, raw_inp, **kwargs):
if current_prot_parent:
current_prot_parent = utils.make_iter(current_prot_parent)
if prototype_parent_key in current_prot_parent:
caller.msg(
"Prototype_parent {} is already used.".format(
prototype_parent_key
)
)
caller.msg("Prototype_parent {} is already used.".format(prototype_parent_key))
return "node_prototype_parent"
else:
current_prot_parent.append(prototype_parent_key)
@ -885,18 +829,12 @@ def _prototype_parent_actions(caller, raw_inp, **kwargs):
current_prot_parent = utils.make_iter(current_prot_parent)
try:
current_prot_parent.remove(prototype_parent_key)
_set_prototype_value(
caller, "prototype_parent", current_prot_parent
)
_set_prototype_value(caller, "prototype_parent", current_prot_parent)
_get_flat_menu_prototype(caller, refresh=True)
caller.msg(
"Removed prototype parent {}.".format(prototype_parent_key)
)
caller.msg("Removed prototype parent {}.".format(prototype_parent_key))
except ValueError:
caller.msg(
"|rPrototype-parent {} could not be removed.".format(
prototype_parent_key
)
"|rPrototype-parent {} could not be removed.".format(prototype_parent_key)
)
return "node_prototype_parent"
@ -912,8 +850,7 @@ def _prototype_parent_select(caller, new_parent):
raise RuntimeError("Not found.")
except RuntimeError as err:
caller.msg(
"Selected prototype-parent {} "
"caused Error(s):\n|r{}|n".format(new_parent, err)
"Selected prototype-parent {} " "caused Error(s):\n|r{}|n".format(new_parent, err)
)
else:
ret = _set_property(
@ -964,9 +901,7 @@ def node_prototype_parent(caller):
)
)
else:
ptexts.append(
"Prototype parent |r{pkey} was not found.".format(pkey=pkey)
)
ptexts.append("Prototype parent |r{pkey} was not found.".format(pkey=pkey))
if not ptexts:
ptexts.append("[No prototype_parent set]")
@ -975,9 +910,7 @@ def node_prototype_parent(caller):
text = (text, helptext)
options = _wizard_options(
"prototype_parent", "prototype_key", "typeclass", color="|W"
)
options = _wizard_options("prototype_parent", "prototype_key", "typeclass", color="|W")
options.append({"key": "_default", "goto": _prototype_parent_actions})
return text, options
@ -990,9 +923,7 @@ def _all_typeclasses(caller):
"""Get name of available typeclasses."""
return list(
name
for name in sorted(
utils.get_all_typeclasses("evennia.objects.models.ObjectDB").keys()
)
for name in sorted(utils.get_all_typeclasses("evennia.objects.models.ObjectDB").keys())
if name != "evennia.objects.models.ObjectDB"
)
@ -1169,18 +1100,13 @@ def node_aliases(caller):
current=_get_current_value(
caller,
"aliases",
comparer=lambda propval, flatval: [
al for al in flatval if al not in propval
],
comparer=lambda propval, flatval: [al for al in flatval if al not in propval],
formatter=lambda lst: "\n" + ", ".join(lst),
only_inherit=True,
)
)
_set_actioninfo(
caller,
_format_list_actions(
"remove", prefix="|w<text>|W to add new alias. Other action: "
),
caller, _format_list_actions("remove", prefix="|w<text>|W to add new alias. Other action: ")
)
helptext = """
@ -1309,10 +1235,7 @@ def _attr_select(caller, attrstr):
attr_tup = _get_tup_by_attrname(caller, attrname)
if attr_tup:
return (
"node_examine_entity",
{"text": _display_attribute(attr_tup), "back": "attrs"},
)
return ("node_examine_entity", {"text": _display_attribute(attr_tup), "back": "attrs"})
else:
caller.msg("Attribute not found.")
return "node_attrs"
@ -1337,10 +1260,7 @@ def _attrs_actions(caller, raw_inp, **kwargs):
if action and attr_tup:
if action == "examine":
return (
"node_examine_entity",
{"text": _display_attribute(attr_tup), "back": "attrs"},
)
return ("node_examine_entity", {"text": _display_attribute(attr_tup), "back": "attrs"})
elif action == "remove":
res = _add_attr(caller, attrname, delete=True)
caller.msg(res)
@ -1377,14 +1297,11 @@ def node_attrs(caller):
caller,
"attrs",
comparer=_currentcmp,
formatter=lambda lst: "\n"
+ "\n".join(_display_attribute(tup) for tup in lst),
formatter=lambda lst: "\n" + "\n".join(_display_attribute(tup) for tup in lst),
only_inherit=True,
)
)
_set_actioninfo(
caller, _format_list_actions("examine", "remove", prefix="Actions: ")
)
_set_actioninfo(caller, _format_list_actions("examine", "remove", prefix="Actions: "))
helptext = """
Most commonly, Attributes don't need any categories or locks. If using locks, the lock-types
@ -1522,10 +1439,7 @@ def _tags_actions(caller, raw_inp, **kwargs):
if tag_tup:
if action == "examine":
return (
"node_examine_entity",
{"text": _display_tag(tag_tup), "back": "tags"},
)
return ("node_examine_entity", {"text": _display_tag(tag_tup), "back": "tags"})
elif action == "remove":
res = _add_tag(caller, tagname, delete=True)
caller.msg(res)
@ -1563,9 +1477,7 @@ def node_tags(caller):
only_inherit=True,
)
)
_set_actioninfo(
caller, _format_list_actions("examine", "remove", prefix="Actions: ")
)
_set_actioninfo(caller, _format_list_actions("examine", "remove", prefix="Actions: "))
helptext = """
Tags are shared between all objects with that tag. So the 'data' field (which is not
@ -1598,10 +1510,7 @@ def _locks_display(caller, lock):
def _lock_select(caller, lockstr):
return (
"node_examine_entity",
{"text": _locks_display(caller, lockstr), "back": "locks"},
)
return ("node_examine_entity", {"text": _locks_display(caller, lockstr), "back": "locks"})
def _lock_add(caller, lock, **kwargs):
@ -1643,10 +1552,7 @@ def _locks_actions(caller, raw_inp, **kwargs):
if lock:
if action == "examine":
return (
"node_examine_entity",
{"text": _locks_display(caller, lock), "back": "locks"},
)
return ("node_examine_entity", {"text": _locks_display(caller, lock), "back": "locks"})
elif action == "remove":
ret = _lock_add(caller, lock, delete=True)
caller.msg(ret)
@ -1662,9 +1568,7 @@ def node_locks(caller):
def _currentcmp(propval, flatval):
"match by locktype"
cmp1 = [lck.split(":", 1)[0] for lck in propval.split(";")]
return ";".join(
lstr for lstr in flatval.split(";") if lstr.split(":", 1)[0] not in cmp1
)
return ";".join(lstr for lstr in flatval.split(";") if lstr.split(":", 1)[0] not in cmp1)
text = """
The |cLock string|n defines limitations for accessing various properties of the object once
@ -1730,9 +1634,7 @@ def _display_perm(caller, permission, only_hierarchy=False):
txt = "Permission (in hieararchy): {}".format(
", ".join(
[
"|w[{}]|n".format(prm)
if prm.lower() == perm_low
else "|W{}|n".format(prm)
"|w[{}]|n".format(prm) if prm.lower() == perm_low else "|W{}|n".format(prm)
for prm in hierarchy
]
)
@ -1815,9 +1717,7 @@ def node_permissions(caller):
only_inherit=True,
)
)
_set_actioninfo(
caller, _format_list_actions("examine", "remove", prefix="Actions: ")
)
_set_actioninfo(caller, _format_list_actions("examine", "remove", prefix="Actions: "))
helptext = """
Any string can act as a permission as long as a lock is set to look for it. Depending on the
@ -1872,10 +1772,7 @@ def node_location(caller):
options.append(
{
"key": "_default",
"goto": (
_set_property,
dict(prop="location", processor=lambda s: s.strip()),
),
"goto": (_set_property, dict(prop="location", processor=lambda s: s.strip())),
}
)
return text, options
@ -1952,10 +1849,7 @@ def node_destination(caller):
options.append(
{
"key": "_default",
"goto": (
_set_property,
dict(prop="destination", processor=lambda s: s.strip()),
),
"goto": (_set_property, dict(prop="destination", processor=lambda s: s.strip())),
}
)
return text, options
@ -2088,10 +1982,7 @@ def node_prototype_tags(caller):
)
)
_set_actioninfo(
caller,
_format_list_actions(
"remove", prefix="|w<text>|n|W to add Tag. Other Action:|n "
),
caller, _format_list_actions("remove", prefix="|w<text>|n|W to add Tag. Other Action:|n ")
)
helptext = """
Using prototype-tags is a good way to organize and group large numbers of prototypes by
@ -2138,9 +2029,7 @@ def _prototype_lock_add(caller, lock, **kwargs):
try:
ind = locks.index(lock)
locks.pop(ind)
_set_prototype_value(
caller, "prototype_locks", ";".join(locks), parse=False
)
_set_prototype_value(caller, "prototype_locks", ";".join(locks), parse=False)
ret = "Prototype-lock {} deleted.".format(lock)
except ValueError:
ret = "No Prototype-lock found to delete."
@ -2165,10 +2054,7 @@ def _prototype_locks_actions(caller, raw_inp, **kwargs):
if lock:
if action == "examine":
return (
"node_examine_entity",
{"text": _locks_display(caller, lock), "back": "locks"},
)
return ("node_examine_entity", {"text": _locks_display(caller, lock), "back": "locks"})
elif action == "remove":
ret = _prototype_lock_add(caller, lock.strip(), delete=True)
caller.msg(ret)
@ -2204,9 +2090,7 @@ def node_prototype_locks(caller):
only_inherit=True,
)
)
_set_actioninfo(
caller, _format_list_actions("examine", "remove", prefix="Actions: ")
)
_set_actioninfo(caller, _format_list_actions("examine", "remove", prefix="Actions: "))
helptext = """
Prototype locks can be used to vary access for different tiers of builders. It also allows
@ -2231,9 +2115,7 @@ def _apply_diff(caller, **kwargs):
objects = kwargs["objects"]
back_node = kwargs["back_node"]
diff = kwargs.get("diff", None)
num_changed = spawner.batch_update_objects_with_prototype(
prototype, diff=diff, objects=objects
)
num_changed = spawner.batch_update_objects_with_prototype(prototype, diff=diff, objects=objects)
caller.msg("|g{num} objects were updated successfully.|n".format(num=num_changed))
return back_node
@ -2284,18 +2166,12 @@ def _format_diff_text_and_options(diff, **kwargs):
rootname = args[0]
old, new, instruction = diffpart
if instruction == "KEEP":
texts.append(
" |gKEEP|W:|n {old}".format(old=_visualize(old, rootname))
)
texts.append(" |gKEEP|W:|n {old}".format(old=_visualize(old, rootname)))
else:
vold = _visualize(old, rootname)
vnew = _visualize(new, rootname)
vsep = "" if len(vold) < 78 else "\n"
vinst = (
"|rREMOVE|n"
if instruction == "REMOVE"
else "|y{}|n".format(instruction)
)
vinst = "|rREMOVE|n" if instruction == "REMOVE" else "|y{}|n".format(instruction)
texts.append(
" |c[{num}] {inst}|W:|n {old} |W->|n{sep} {new}".format(
inst=vinst, num=optnum, old=vold, sep=vsep, new=vnew
@ -2307,19 +2183,14 @@ def _format_diff_text_and_options(diff, **kwargs):
"desc": "|gKEEP|n ({}) {}".format(
rootname, _visualize(old, args[-1], get_name=True)
),
"goto": (
_keep_diff,
dict((("path", args), ("diff", diff)), **kwargs),
),
"goto": (_keep_diff, dict((("path", args), ("diff", diff)), **kwargs)),
}
)
optnum += 1
else:
for key in sorted(list(diffpart.keys())):
subdiffpart = diffpart[key]
text, option, optnum = _parse_diffpart(
subdiffpart, optnum, *(args + (key,))
)
text, option, optnum = _parse_diffpart(subdiffpart, optnum, *(args + (key,)))
texts.extend(text)
options.extend(option)
return texts, options, optnum
@ -2350,9 +2221,7 @@ def _format_diff_text_and_options(diff, **kwargs):
def node_apply_diff(caller, **kwargs):
"""Offer options for updating objects"""
def _keep_option(
keyname, prototype, base_obj, obj_prototype, diff, objects, back_node
):
def _keep_option(keyname, prototype, base_obj, obj_prototype, diff, objects, back_node):
"""helper returning an option dict"""
options = {
"desc": "Keep {} as-is".format(keyname),
@ -2408,9 +2277,7 @@ def node_apply_diff(caller, **kwargs):
if not custom_location:
diff.pop("location", None)
txt, options = _format_diff_text_and_options(
diff, objects=update_objects, base_obj=base_obj
)
txt, options = _format_diff_text_and_options(diff, objects=update_objects, base_obj=base_obj)
if options:
text = [
@ -2422,11 +2289,7 @@ def node_apply_diff(caller, **kwargs):
options.extend(
[
{
"key": (
"|wu|Wpdate {} objects".format(len(update_objects)),
"update",
"u",
),
"key": ("|wu|Wpdate {} objects".format(len(update_objects)), "update", "u"),
"desc": "Update {} objects".format(len(update_objects)),
"goto": (
_apply_diff,
@ -2443,11 +2306,7 @@ def node_apply_diff(caller, **kwargs):
"key": ("|wr|Weset changes", "reset", "r"),
"goto": (
"node_apply_diff",
{
"prototype": prototype,
"back_node": back_node,
"objects": update_objects,
},
{"prototype": prototype, "back_node": back_node, "objects": update_objects},
),
},
]
@ -2512,11 +2371,7 @@ def node_prototype_save(caller, **kwargs):
},
),
},
{
"key": ("[|wN|Wo|n]", "n"),
"desc": "Return to index",
"goto": "node_index",
},
{"key": ("[|wN|Wo|n]", "n"), "desc": "Return to index", "goto": "node_index"},
{"key": "_default", "goto": "node_index"},
)
else:
@ -2561,11 +2416,7 @@ def node_prototype_save(caller, **kwargs):
)
)
else:
text.append(
"\nDo you want to save the prototype as '{name}'?".format(
name=prototype_key
)
)
text.append("\nDo you want to save the prototype as '{name}'?".format(name=prototype_key))
text = "\n".join(text)
@ -2583,22 +2434,12 @@ def node_prototype_save(caller, **kwargs):
{
"key": ("[|wY|Wes|n]", "yes", "y"),
"desc": "Save prototype",
"goto": (
"node_prototype_save",
{"accept_save": True, "prototype": prototype},
),
},
{
"key": ("|wN|Wo|n", "n"),
"desc": "Abort and return to Index",
"goto": "node_index",
"goto": ("node_prototype_save", {"accept_save": True, "prototype": prototype}),
},
{"key": ("|wN|Wo|n", "n"), "desc": "Abort and return to Index", "goto": "node_index"},
{
"key": "_default",
"goto": (
"node_prototype_save",
{"accept_save": True, "prototype": prototype},
),
"goto": ("node_prototype_save", {"accept_save": True, "prototype": prototype}),
},
)
@ -2642,9 +2483,7 @@ def node_prototype_spawn(caller, **kwargs):
text = [text]
if error:
text.append(
"\n|rPrototype validation failed. Correct the errors before spawning.|n"
)
text.append("\n|rPrototype validation failed. Correct the errors before spawning.|n")
options = _wizard_options("prototype_spawn", "index", None)
return "\n".join(text), options
@ -2667,9 +2506,7 @@ def node_prototype_spawn(caller, **kwargs):
if location:
options.append(
{
"desc": "Spawn in prototype's defined location ({loc})".format(
loc=location
),
"desc": "Spawn in prototype's defined location ({loc})".format(loc=location),
"goto": (
_spawn,
dict(prototype=prototype, location=location, custom_location=True),
@ -2699,9 +2536,7 @@ def node_prototype_spawn(caller, **kwargs):
if spawned_objects:
options.append(
{
"desc": "Update {num} existing objects with this prototype".format(
num=nspawned
),
"desc": "Update {num} existing objects with this prototype".format(num=nspawned),
"goto": (
"node_apply_diff",
{

View file

@ -300,9 +300,7 @@ def _obj_search(*args, **kwargs):
if len(targets) > 1:
raise ValueError(
"$obj: Query '{query}' gave {nmatches} matches. Limit your "
"query or use $objlist instead.".format(
query=query, nmatches=len(targets)
)
"query or use $objlist instead.".format(query=query, nmatches=len(targets))
)
target = targets[0]
if account:
@ -334,9 +332,7 @@ def objlist(*args, **kwargs):
Returns list with one or more Objects searched globally by key, alias or #dbref.
"""
return [
"#{}".format(obj.id) for obj in _obj_search(return_list=True, *args, **kwargs)
]
return ["#{}".format(obj.id) for obj in _obj_search(return_list=True, *args, **kwargs)]
def dbref(*args, **kwargs):

View file

@ -135,26 +135,20 @@ for mod in settings.PROTOTYPE_MODULES:
prot["prototype_key"] = variable_name.lower()
prots.append((prot["prototype_key"], homogenize_prototype(prot)))
# assign module path to each prototype_key for easy reference
_MODULE_PROTOTYPE_MODULES.update(
{prototype_key.lower(): mod for prototype_key, _ in prots}
)
_MODULE_PROTOTYPE_MODULES.update({prototype_key.lower(): mod for prototype_key, _ in prots})
# make sure the prototype contains all meta info
for prototype_key, prot in prots:
actual_prot_key = prot.get("prototype_key", prototype_key).lower()
prot.update(
{
"prototype_key": actual_prot_key,
"prototype_desc": prot["prototype_desc"]
if "prototype_desc" in prot
else mod,
"prototype_desc": prot["prototype_desc"] if "prototype_desc" in prot else mod,
"prototype_locks": (
prot["prototype_locks"]
if "prototype_locks" in prot
else "use:all();edit:false()"
),
"prototype_tags": list(
set(make_iter(prot.get("prototype_tags", [])) + ["module"])
),
"prototype_tags": list(set(make_iter(prot.get("prototype_tags", [])) + ["module"])),
}
)
_MODULE_PROTOTYPES[actual_prot_key] = prot
@ -225,8 +219,7 @@ def save_prototype(prototype):
if prototype_key in _MODULE_PROTOTYPES:
mod = _MODULE_PROTOTYPE_MODULES.get(prototype_key, "N/A")
raise PermissionError(
"{} is a read-only prototype "
"(defined as code in {}).".format(prototype_key, mod)
"{} is a read-only prototype " "(defined as code in {}).".format(prototype_key, mod)
)
# make sure meta properties are included with defaults
@ -237,8 +230,7 @@ def save_prototype(prototype):
"prototype_desc", prototype.get("prototype_desc", "")
)
prototype_locks = in_prototype.get(
"prototype_locks",
prototype.get("prototype_locks", "spawn:all();edit:perm(Admin)"),
"prototype_locks", prototype.get("prototype_locks", "spawn:all();edit:perm(Admin)")
)
is_valid, err = validate_lockstring(prototype_locks)
if not is_valid:
@ -298,8 +290,7 @@ def delete_prototype(prototype_key, caller=None):
if prototype_key in _MODULE_PROTOTYPES:
mod = _MODULE_PROTOTYPE_MODULES.get(prototype_key.lower(), "N/A")
raise PermissionError(
"{} is a read-only prototype "
"(defined as code in {}).".format(prototype_key, mod)
"{} is a read-only prototype " "(defined as code in {}).".format(prototype_key, mod)
)
stored_prototype = DbPrototype.objects.filter(db_key__iexact=prototype_key)
@ -396,9 +387,7 @@ def search_prototype(key=None, tags=None, require_single=False):
key = key.lower()
# avoid duplicates if an exact match exist between the two types
filter_matches = [
mta
for mta in matches
if mta.get("prototype_key") and mta["prototype_key"] == key
mta for mta in matches if mta.get("prototype_key") and mta["prototype_key"] == key
]
if filter_matches and len(filter_matches) < nmatches:
matches = filter_matches
@ -421,14 +410,10 @@ def search_objects_with_prototype(prototype_key):
matches (Queryset): All matching objects spawned from this prototype.
"""
return ObjectDB.objects.get_by_tag(
key=prototype_key, category=_PROTOTYPE_TAG_CATEGORY
)
return ObjectDB.objects.get_by_tag(key=prototype_key, category=_PROTOTYPE_TAG_CATEGORY)
def list_prototypes(
caller, key=None, tags=None, show_non_use=False, show_non_edit=True
):
def list_prototypes(caller, key=None, tags=None, show_non_use=False, show_non_edit=True):
"""
Collate a list of found prototypes based on search criteria and access.
@ -453,10 +438,7 @@ def list_prototypes(
display_tuples = []
for prototype in sorted(prototypes, key=lambda d: d.get("prototype_key", "")):
lock_use = caller.locks.check_lockstring(
caller,
prototype.get("prototype_locks", ""),
access_type="spawn",
default=True,
caller, prototype.get("prototype_locks", ""), access_type="spawn", default=True
)
if not show_non_use and not lock_use:
continue
@ -464,10 +446,7 @@ def list_prototypes(
lock_edit = False
else:
lock_edit = caller.locks.check_lockstring(
caller,
prototype.get("prototype_locks", ""),
access_type="edit",
default=True,
caller, prototype.get("prototype_locks", ""), access_type="edit", default=True
)
if not show_non_edit and not lock_edit:
continue
@ -497,9 +476,7 @@ def list_prototypes(
width = 78
for i in range(len(display_tuples[0])):
table.append([str(display_tuple[i]) for display_tuple in display_tuples])
table = EvTable(
"Key", "Desc", "Spawn/Edit", "Tags", table=table, crop=True, width=width
)
table = EvTable("Key", "Desc", "Spawn/Edit", "Tags", table=table, crop=True, width=width)
table.reformat_column(0, width=22)
table.reformat_column(1, width=29)
table.reformat_column(2, width=11, align="c")
@ -508,12 +485,7 @@ def list_prototypes(
def validate_prototype(
prototype,
protkey=None,
protparents=None,
is_prototype_base=True,
strict=True,
_flags=None,
prototype, protkey=None, protparents=None, is_prototype_base=True, strict=True, _flags=None
):
"""
Run validation on a prototype, checking for inifinite regress.
@ -539,13 +511,7 @@ def validate_prototype(
assert isinstance(prototype, dict)
if _flags is None:
_flags = {
"visited": [],
"depth": 0,
"typeclass": False,
"errors": [],
"warnings": [],
}
_flags = {"visited": [], "depth": 0, "typeclass": False, "errors": [], "warnings": []}
if not protparents:
protparents = {
@ -565,8 +531,7 @@ def validate_prototype(
if strict and not (typeclass or prototype_parent):
if is_prototype_base:
_flags["errors"].append(
"Prototype {} requires `typeclass` "
"or 'prototype_parent'.".format(protkey)
"Prototype {} requires `typeclass` " "or 'prototype_parent'.".format(protkey)
)
else:
_flags["warnings"].append(
@ -589,15 +554,11 @@ def validate_prototype(
for protstring in make_iter(prototype_parent):
protstring = protstring.lower()
if protkey is not None and protstring == protkey:
_flags["errors"].append(
"Prototype {} tries to parent itself.".format(protkey)
)
_flags["errors"].append("Prototype {} tries to parent itself.".format(protkey))
protparent = protparents.get(protstring)
if not protparent:
_flags["errors"].append(
"Prototype {}'s prototype_parent '{}' was not found.".format(
(protkey, protstring)
)
"Prototype {}'s prototype_parent '{}' was not found.".format((protkey, protstring))
)
if id(prototype) in _flags["visited"]:
_flags["errors"].append(
@ -609,11 +570,7 @@ def validate_prototype(
_flags["visited"].append(id(prototype))
_flags["depth"] += 1
validate_prototype(
protparent,
protstring,
protparents,
is_prototype_base=is_prototype_base,
_flags=_flags,
protparent, protstring, protparents, is_prototype_base=is_prototype_base, _flags=_flags
)
_flags["visited"].pop()
_flags["depth"] -= 1
@ -622,12 +579,7 @@ def validate_prototype(
_flags["typeclass"] = typeclass
# if we get back to the current level without a typeclass it's an error.
if (
strict
and is_prototype_base
and _flags["depth"] <= 0
and not _flags["typeclass"]
):
if strict and is_prototype_base and _flags["depth"] <= 0 and not _flags["typeclass"]:
_flags["errors"].append(
"Prototype {} has no `typeclass` defined anywhere in its parent\n "
"chain. Add `typeclass`, or a `prototype_parent` pointing to a "
@ -666,9 +618,7 @@ for mod in settings.PROT_FUNC_MODULES:
raise
def protfunc_parser(
value, available_functions=None, testing=False, stacktrace=False, **kwargs
):
def protfunc_parser(value, available_functions=None, testing=False, stacktrace=False, **kwargs):
"""
Parse a prototype value string for a protfunc and process it.
@ -704,16 +654,10 @@ def protfunc_parser(
if not isinstance(value, str):
return value
available_functions = (
PROT_FUNCS if available_functions is None else available_functions
)
available_functions = PROT_FUNCS if available_functions is None else available_functions
result = inlinefuncs.parse_inlinefunc(
value,
available_funcs=available_functions,
stacktrace=stacktrace,
testing=testing,
**kwargs
value, available_funcs=available_functions, stacktrace=stacktrace, testing=testing, **kwargs
)
err = None
@ -802,9 +746,7 @@ def prototype_to_str(prototype):
for (tagkey, category, data) in tags:
out.append(
"{tagkey} (category: {category}{dat})".format(
tagkey=tagkey,
category=category,
dat=", data: {}".format(data) if data else "",
tagkey=tagkey, category=category, dat=", data: {}".format(data) if data else ""
)
)
tags = "|ctags:|n\n {tags}".format(tags=", ".join(out))
@ -826,17 +768,7 @@ def prototype_to_str(prototype):
body = "\n".join(
part
for part in (
key,
aliases,
attrs,
tags,
locks,
permissions,
location,
home,
destination,
)
for part in (key, aliases, attrs, tags, locks, permissions, location, home, destination)
if part
)
@ -860,8 +792,7 @@ def check_permission(prototype_key, action, default=True):
if prototype_key in _MODULE_PROTOTYPES:
mod = _MODULE_PROTOTYPE_MODULES.get(prototype_key, "N/A")
logger.log_err(
"{} is a read-only prototype "
"(defined as code in {}).".format(prototype_key, mod)
"{} is a read-only prototype " "(defined as code in {}).".format(prototype_key, mod)
)
return False
@ -911,8 +842,7 @@ def value_to_obj_or_any(value):
if is_iter(value):
if stype == dict:
return {
value_to_obj_or_any(key): value_to_obj_or_any(val)
for key, val in value.items()
value_to_obj_or_any(key): value_to_obj_or_any(val) for key, val in value.items()
}
else:
return stype([value_to_obj_or_any(val) for val in value])
@ -925,10 +855,7 @@ def value_to_obj(value, force=True):
stype = type(value)
if is_iter(value):
if stype == dict:
return {
value_to_obj_or_any(key): value_to_obj_or_any(val)
for key, val in value.iter()
}
return {value_to_obj_or_any(key): value_to_obj_or_any(val) for key, val in value.iter()}
else:
return stype([value_to_obj_or_any(val) for val in value])
return dbid_to_obj(value, ObjectDB)

View file

@ -149,12 +149,7 @@ from evennia.prototypes.prototypes import (
_CREATE_OBJECT_KWARGS = ("key", "location", "home", "destination")
_PROTOTYPE_META_NAMES = (
"prototype_key",
"prototype_desc",
"prototype_tags",
"prototype_locks",
)
_PROTOTYPE_META_NAMES = ("prototype_key", "prototype_desc", "prototype_tags", "prototype_locks")
_PROTOTYPE_ROOT_NAMES = (
"typeclass",
"key",
@ -216,16 +211,12 @@ def _get_prototype(inprot, protparents, uninherited=None, _workprot=None):
new_prot["attrs"] = _inherit_attrs(
_workprot.get("attrs", {}), new_prot.get("attrs", {})
)
new_prot["tags"] = _inherit_tags(
_workprot.get("tags", {}), new_prot.get("tags", {})
)
new_prot["tags"] = _inherit_tags(_workprot.get("tags", {}), new_prot.get("tags", {}))
_workprot.update(new_prot)
# the inprot represents a higher level (a child prot), which should override parents
inprot["attrs"] = _inherit_attrs(
_workprot.get("attrs", {}), inprot.get("attrs", {})
)
inprot["attrs"] = _inherit_attrs(_workprot.get("attrs", {}), inprot.get("attrs", {}))
inprot["tags"] = _inherit_tags(_workprot.get("tags", {}), inprot.get("tags", {}))
_workprot.update(inprot)
if uninherited:
@ -251,16 +242,12 @@ def flatten_prototype(prototype, validate=False):
if prototype:
prototype = protlib.homogenize_prototype(prototype)
protparents = {
prot["prototype_key"].lower(): prot for prot in protlib.search_prototype()
}
protparents = {prot["prototype_key"].lower(): prot for prot in protlib.search_prototype()}
protlib.validate_prototype(
prototype, None, protparents, is_prototype_base=validate, strict=validate
)
return _get_prototype(
prototype,
protparents,
uninherited={"prototype_key": prototype.get("prototype_key")},
prototype, protparents, uninherited={"prototype_key": prototype.get("prototype_key")}
)
return {}
@ -297,9 +284,7 @@ def prototype_from_object(obj):
else:
prot = prot[0]
prot["key"] = (
obj.db_key or hashlib.md5(bytes(str(time.time()), "utf-8")).hexdigest()[:6]
)
prot["key"] = obj.db_key or hashlib.md5(bytes(str(time.time()), "utf-8")).hexdigest()[:6]
prot["typeclass"] = obj.db_typeclass_path
location = obj.db_location
@ -321,10 +306,7 @@ def prototype_from_object(obj):
if aliases:
prot["aliases"] = aliases
tags = sorted(
[
(tag.db_key, tag.db_category, tag.db_data)
for tag in obj.tags.all(return_objs=True)
]
[(tag.db_key, tag.db_category, tag.db_data) for tag in obj.tags.all(return_objs=True)]
)
if tags:
prot["tags"] = tags
@ -374,18 +356,14 @@ def prototype_diff(prototype1, prototype2, maxdepth=2):
return {key: (part, None, "REMOVE") for key, part in old.items()}
elif depth < maxdepth and is_iter(old):
return {
part[0] if is_iter(part) else part: (part, None, "REMOVE")
for part in old
part[0] if is_iter(part) else part: (part, None, "REMOVE") for part in old
}
return (old, new, "REMOVE")
elif not old and new:
if depth < maxdepth and new_type == dict:
return {key: (None, part, "ADD") for key, part in new.items()}
elif depth < maxdepth and is_iter(new):
return {
part[0] if is_iter(part) else part: (None, part, "ADD")
for part in new
}
return {part[0] if is_iter(part) else part: (None, part, "ADD") for part in new}
return (old, new, "ADD")
else:
# this condition should not occur in a standard diff
@ -401,9 +379,7 @@ def prototype_diff(prototype1, prototype2, maxdepth=2):
new_map = {part[0] if is_iter(part) else part: part for part in new}
all_keys = set(list(old_map.keys()) + list(new_map.keys()))
return {
key: _recursive_diff(
old_map.get(key), new_map.get(key), depth=depth + 1
)
key: _recursive_diff(old_map.get(key), new_map.get(key), depth=depth + 1)
for key in all_keys
}
elif old != new:
@ -539,9 +515,7 @@ def batch_update_objects_with_prototype(prototype, diff=None, objects=None):
prototype_key = new_prototype["prototype_key"]
if not objects:
objects = ObjectDB.objects.get_by_tag(
prototype_key, category=_PROTOTYPE_TAG_CATEGORY
)
objects = ObjectDB.objects.get_by_tag(prototype_key, category=_PROTOTYPE_TAG_CATEGORY)
if not objects:
return 0
@ -588,15 +562,11 @@ def batch_update_objects_with_prototype(prototype, diff=None, objects=None):
elif key == "permissions":
if directive == "REPLACE":
obj.permissions.clear()
obj.permissions.batch_add(
*(init_spawn_value(perm, str) for perm in val)
)
obj.permissions.batch_add(*(init_spawn_value(perm, str) for perm in val))
elif key == "aliases":
if directive == "REPLACE":
obj.aliases.clear()
obj.aliases.batch_add(
*(init_spawn_value(alias, str) for alias in val)
)
obj.aliases.batch_add(*(init_spawn_value(alias, str) for alias in val))
elif key == "tags":
if directive == "REPLACE":
obj.tags.clear()
@ -762,16 +732,12 @@ def spawn(*prototypes, **kwargs):
"""
# search string (=prototype_key) from input
prototypes = [
protlib.search_prototype(prot, require_single=True)[0]
if isinstance(prot, str)
else prot
protlib.search_prototype(prot, require_single=True)[0] if isinstance(prot, str) else prot
for prot in prototypes
]
# get available protparents
protparents = {
prot["prototype_key"].lower(): prot for prot in protlib.search_prototype()
}
protparents = {prot["prototype_key"].lower(): prot for prot in protlib.search_prototype()}
if not kwargs.get("only_validate"):
# homogenization to be more lenient about prototype format when entering the prototype manually
@ -794,9 +760,7 @@ def spawn(*prototypes, **kwargs):
protlib.validate_prototype(prototype, None, protparents, is_prototype_base=True)
prot = _get_prototype(
prototype,
protparents,
uninherited={"prototype_key": prototype.get("prototype_key")},
prototype, protparents, uninherited={"prototype_key": prototype.get("prototype_key")}
)
if not prot:
continue
@ -808,9 +772,7 @@ def spawn(*prototypes, **kwargs):
# chance this is not unique but it should usually not be a problem.
val = prot.pop(
"key",
"Spawned-{}".format(
hashlib.md5(bytes(str(time.time()), "utf-8")).hexdigest()[:6]
),
"Spawned-{}".format(hashlib.md5(bytes(str(time.time()), "utf-8")).hexdigest()[:6]),
)
create_kwargs["db_key"] = init_spawn_value(val, str)

View file

@ -55,9 +55,7 @@ class TestSpawner(EvenniaTest):
def test_spawn_from_prot(self):
obj1 = spawner.spawn(self.prot1)
# check spawned objects have the right tag
self.assertEqual(
list(protlib.search_objects_with_prototype("testprototype")), obj1
)
self.assertEqual(list(protlib.search_objects_with_prototype("testprototype")), obj1)
self.assertEqual(
[
o.key
@ -73,9 +71,7 @@ class TestSpawner(EvenniaTest):
def test_spawn_from_str(self):
protlib.save_prototype(self.prot1)
obj1 = spawner.spawn(self.prot1["prototype_key"])
self.assertEqual(
list(protlib.search_objects_with_prototype("testprototype")), obj1
)
self.assertEqual(list(protlib.search_objects_with_prototype("testprototype")), obj1)
self.assertEqual(
[
o.key
@ -181,10 +177,7 @@ class TestUtils(EvenniaTest):
self.assertEqual(
old_prot,
{
"attrs": [
("oldtest", "to_keep", None, ""),
("fooattr", "fooattrval", None, ""),
],
"attrs": [("oldtest", "to_keep", None, ""), ("fooattr", "fooattrval", None, "")],
"home": Something,
"key": "Obj",
"location": Something,
@ -207,11 +200,7 @@ class TestUtils(EvenniaTest):
pdiff,
{
"home": (Something, Something, "KEEP"),
"prototype_locks": (
"spawn:all();edit:all()",
"spawn:all();edit:all()",
"KEEP",
),
"prototype_locks": ("spawn:all();edit:all()", "spawn:all();edit:all()", "KEEP"),
"prototype_key": (Something, Something, "UPDATE"),
"location": (Something, Something, "KEEP"),
"locks": (
@ -248,11 +237,7 @@ class TestUtils(EvenniaTest):
),
"aliases": {"foo": ("foo", None, "REMOVE")},
"tags": {"footag": (("footag", "foocategory", None), None, "REMOVE")},
"prototype_desc": (
"Built from Obj",
"New version of prototype",
"UPDATE",
),
"prototype_desc": ("Built from Obj", "New version of prototype", "UPDATE"),
"permissions": {"Builder": (None, "Builder", "ADD")},
},
)
@ -349,9 +334,7 @@ class TestProtLib(EvenniaTest):
self.assertEqual(match, [self.prot])
@override_settings(
PROT_FUNC_MODULES=["evennia.prototypes.protfuncs"], CLIENT_DEFAULT_WIDTH=20
)
@override_settings(PROT_FUNC_MODULES=["evennia.prototypes.protfuncs"], CLIENT_DEFAULT_WIDTH=20)
class TestProtFuncs(EvenniaTest):
def setUp(self):
super(TestProtFuncs, self).setUp()
@ -361,27 +344,16 @@ class TestProtFuncs(EvenniaTest):
"key": "ExampleObj",
}
@mock.patch(
"evennia.prototypes.protfuncs.base_random", new=mock.MagicMock(return_value=0.5)
)
@mock.patch(
"evennia.prototypes.protfuncs.base_randint", new=mock.MagicMock(return_value=5)
)
@mock.patch("evennia.prototypes.protfuncs.base_random", new=mock.MagicMock(return_value=0.5))
@mock.patch("evennia.prototypes.protfuncs.base_randint", new=mock.MagicMock(return_value=5))
def test_protfuncs(self):
self.assertEqual(protlib.protfunc_parser("$random()"), 0.5)
self.assertEqual(protlib.protfunc_parser("$randint(1, 10)"), 5)
self.assertEqual(protlib.protfunc_parser("$left_justify( foo )"), "foo ")
self.assertEqual(protlib.protfunc_parser("$right_justify( foo )"), " foo")
self.assertEqual(protlib.protfunc_parser("$center_justify(foo )"), " foo ")
self.assertEqual(
protlib.protfunc_parser("$left_justify( foo )"), "foo "
)
self.assertEqual(
protlib.protfunc_parser("$right_justify( foo )"), " foo"
)
self.assertEqual(
protlib.protfunc_parser("$center_justify(foo )"), " foo "
)
self.assertEqual(
protlib.protfunc_parser("$full_justify(foo bar moo too)"),
"foo bar moo too",
protlib.protfunc_parser("$full_justify(foo bar moo too)"), "foo bar moo too"
)
self.assertEqual(
protlib.protfunc_parser("$right_justify( foo )", testing=True),
@ -391,23 +363,17 @@ class TestProtFuncs(EvenniaTest):
test_prot = {"key1": "value1", "key2": 2}
self.assertEqual(
protlib.protfunc_parser(
"$protkey(key1)", testing=True, prototype=test_prot
),
protlib.protfunc_parser("$protkey(key1)", testing=True, prototype=test_prot),
(None, "value1"),
)
self.assertEqual(
protlib.protfunc_parser(
"$protkey(key2)", testing=True, prototype=test_prot
),
(None, 2),
protlib.protfunc_parser("$protkey(key2)", testing=True, prototype=test_prot), (None, 2)
)
self.assertEqual(protlib.protfunc_parser("$add(1, 2)"), 3)
self.assertEqual(protlib.protfunc_parser("$add(10, 25)"), 35)
self.assertEqual(
protlib.protfunc_parser("$add('''[1,2,3]''', '''[4,5,6]''')"),
[1, 2, 3, 4, 5, 6],
protlib.protfunc_parser("$add('''[1,2,3]''', '''[4,5,6]''')"), [1, 2, 3, 4, 5, 6]
)
self.assertEqual(protlib.protfunc_parser("$add(foo, bar)"), "foo bar")
@ -453,9 +419,7 @@ class TestProtFuncs(EvenniaTest):
"evennia.prototypes.protfuncs._obj_search", wraps=protofuncs._obj_search
) as mocked__obj_search:
self.assertEqual(
protlib.protfunc_parser(
"dbref({})".format(odbref), session=self.session
),
protlib.protfunc_parser("dbref({})".format(odbref), session=self.session),
"dbref({})".format(odbref),
)
mocked__obj_search.assert_not_called()
@ -464,34 +428,27 @@ class TestProtFuncs(EvenniaTest):
"evennia.prototypes.protfuncs._obj_search", wraps=protofuncs._obj_search
) as mocked__obj_search:
self.assertEqual(
protlib.protfunc_parser("stone(#12345)", session=self.session),
"stone(#12345)",
protlib.protfunc_parser("stone(#12345)", session=self.session), "stone(#12345)"
)
mocked__obj_search.assert_not_called()
with mock.patch(
"evennia.prototypes.protfuncs._obj_search", wraps=protofuncs._obj_search
) as mocked__obj_search:
self.assertEqual(
protlib.protfunc_parser(odbref, session=self.session), odbref
)
self.assertEqual(protlib.protfunc_parser(odbref, session=self.session), odbref)
mocked__obj_search.assert_not_called()
with mock.patch(
"evennia.prototypes.protfuncs._obj_search", wraps=protofuncs._obj_search
) as mocked__obj_search:
self.assertEqual(protlib.protfunc_parser("#12345", session=self.session), "#12345")
mocked__obj_search.assert_not_called()
with mock.patch(
"evennia.prototypes.protfuncs._obj_search", wraps=protofuncs._obj_search
) as mocked__obj_search:
self.assertEqual(
protlib.protfunc_parser("#12345", session=self.session), "#12345"
)
mocked__obj_search.assert_not_called()
with mock.patch(
"evennia.prototypes.protfuncs._obj_search", wraps=protofuncs._obj_search
) as mocked__obj_search:
self.assertEqual(
protlib.protfunc_parser(
"nothing({})".format(odbref), session=self.session
),
protlib.protfunc_parser("nothing({})".format(odbref), session=self.session),
"nothing({})".format(odbref),
)
mocked__obj_search.assert_not_called()
@ -499,9 +456,7 @@ class TestProtFuncs(EvenniaTest):
with mock.patch(
"evennia.prototypes.protfuncs._obj_search", wraps=protofuncs._obj_search
) as mocked__obj_search:
self.assertEqual(
protlib.protfunc_parser("(#12345)", session=self.session), "(#12345)"
)
self.assertEqual(protlib.protfunc_parser("(#12345)", session=self.session), "(#12345)")
mocked__obj_search.assert_not_called()
with mock.patch(
@ -516,9 +471,7 @@ class TestProtFuncs(EvenniaTest):
"evennia.prototypes.protfuncs._obj_search", wraps=protofuncs._obj_search
) as mocked__obj_search:
self.assertEqual(
protlib.protfunc_parser(
"objlist({})".format(odbref), session=self.session
),
protlib.protfunc_parser("objlist({})".format(odbref), session=self.session),
"objlist({})".format(odbref),
)
mocked__obj_search.assert_not_called()
@ -527,8 +480,7 @@ class TestProtFuncs(EvenniaTest):
"evennia.prototypes.protfuncs._obj_search", wraps=protofuncs._obj_search
) as mocked__obj_search:
self.assertEqual(
protlib.protfunc_parser("dbref(Char)", session=self.session),
"dbref(Char)",
protlib.protfunc_parser("dbref(Char)", session=self.session), "dbref(Char)"
)
mocked__obj_search.assert_not_called()
@ -538,9 +490,7 @@ class TestProtFuncs(EvenniaTest):
"evennia.prototypes.protfuncs._obj_search", wraps=protofuncs._obj_search
) as mocked__obj_search:
self.assertEqual(
protlib.protfunc_parser(
"$objlist({})".format(odbref), session=self.session
),
protlib.protfunc_parser("$objlist({})".format(odbref), session=self.session),
[odbref],
)
mocked__obj_search.assert_called_once()
@ -550,10 +500,7 @@ class TestProtFuncs(EvenniaTest):
"evennia.prototypes.protfuncs._obj_search", wraps=protofuncs._obj_search
) as mocked__obj_search:
self.assertEqual(
protlib.protfunc_parser(
"$obj({})".format(odbref), session=self.session
),
odbref,
protlib.protfunc_parser("$obj({})".format(odbref), session=self.session), odbref
)
mocked__obj_search.assert_called_once()
assert (odbref,) == mocked__obj_search.call_args[0]
@ -562,10 +509,7 @@ class TestProtFuncs(EvenniaTest):
"evennia.prototypes.protfuncs._obj_search", wraps=protofuncs._obj_search
) as mocked__obj_search:
self.assertEqual(
protlib.protfunc_parser(
"$dbref({})".format(odbref), session=self.session
),
odbref,
protlib.protfunc_parser("$dbref({})".format(odbref), session=self.session), odbref
)
mocked__obj_search.assert_called_once()
assert (odbref,) == mocked__obj_search.call_args[0]
@ -575,9 +519,7 @@ class TestProtFuncs(EvenniaTest):
with mock.patch(
"evennia.prototypes.protfuncs._obj_search", wraps=protofuncs._obj_search
) as mocked__obj_search:
self.assertEqual(
protlib.protfunc_parser("$obj(Char)", session=self.session), cdbref
)
self.assertEqual(protlib.protfunc_parser("$obj(Char)", session=self.session), cdbref)
mocked__obj_search.assert_called_once()
assert ("Char",) == mocked__obj_search.call_args[0]
@ -587,8 +529,7 @@ class TestProtFuncs(EvenniaTest):
"evennia.prototypes.protfuncs._obj_search", wraps=protofuncs._obj_search
) as mocked__obj_search:
self.assertEqual(
protlib.protfunc_parser("$badfunc(#112345)", session=self.session),
"<UNKNOWN>",
protlib.protfunc_parser("$badfunc(#112345)", session=self.session), "<UNKNOWN>"
)
mocked__obj_search.assert_not_called()
@ -599,20 +540,15 @@ class TestProtFuncs(EvenniaTest):
mocked__obj_search.assert_not_called()
self.assertEqual(
protlib.value_to_obj(protlib.protfunc_parser(cdbref, session=self.session)),
protlib.value_to_obj(protlib.protfunc_parser(cdbref, session=self.session)), self.char1
)
self.assertEqual(
protlib.value_to_obj_or_any(protlib.protfunc_parser(cdbref, session=self.session)),
self.char1,
)
self.assertEqual(
protlib.value_to_obj_or_any(
protlib.protfunc_parser(cdbref, session=self.session)
),
self.char1,
)
self.assertEqual(
protlib.value_to_obj_or_any(
protlib.protfunc_parser(
"[1,2,3,'{}',5]".format(cdbref), session=self.session
)
protlib.protfunc_parser("[1,2,3,'{}',5]".format(cdbref), session=self.session)
),
[1, 2, 3, self.char1, 5],
)
@ -648,13 +584,11 @@ class TestPrototypeStorage(EvenniaTest):
self.assertEqual(prot1["prototype_desc"], "testdesc1")
self.assertEqual(prot1["prototype_tags"], [("foo1", _PROTOTYPE_TAG_META_CATEGORY)])
self.assertEqual(
prot1["prototype_tags"], [("foo1", _PROTOTYPE_TAG_META_CATEGORY)]
)
self.assertEqual(
protlib.DbPrototype.objects.get_by_tag(
"foo1", _PROTOTYPE_TAG_META_CATEGORY
)[0].db.prototype,
protlib.DbPrototype.objects.get_by_tag("foo1", _PROTOTYPE_TAG_META_CATEGORY)[
0
].db.prototype,
prot1,
)
@ -671,11 +605,7 @@ class TestPrototypeStorage(EvenniaTest):
# add to existing prototype
prot1b = protlib.create_prototype(
{
"prototype_key": "testprototype1",
"foo": "bar",
"prototype_tags": ["foo2"],
}
{"prototype_key": "testprototype1", "foo": "bar", "prototype_tags": ["foo2"]}
)
self.assertEqual(
@ -696,12 +626,8 @@ class TestPrototypeStorage(EvenniaTest):
# partial match
with mock.patch("evennia.prototypes.prototypes._MODULE_PROTOTYPES", {}):
self.assertEqual(
list(protlib.search_prototype("prot")), [prot1b, prot2, prot3]
)
self.assertEqual(
list(protlib.search_prototype(tags="foo1")), [prot1b, prot2, prot3]
)
self.assertEqual(list(protlib.search_prototype("prot")), [prot1b, prot2, prot3])
self.assertEqual(list(protlib.search_prototype(tags="foo1")), [prot1b, prot2, prot3])
self.assertTrue(str(str(protlib.list_prototypes(self.char1))))
@ -751,8 +677,7 @@ class TestMenuModule(EvenniaTest):
" (TestKey|n)",
)
self.assertEqual(
olc_menus._format_option_value([1, 2, 3, "foo"], required=True),
" (1, 2, 3, foo|n)",
olc_menus._format_option_value([1, 2, 3, "foo"], required=True), " (1, 2, 3, foo|n)"
)
self.assertEqual(
@ -766,16 +691,8 @@ class TestMenuModule(EvenniaTest):
self.assertEqual(
olc_menus._wizard_options("ThisNode", "PrevNode", "NextNode"),
[
{
"goto": "node_PrevNode",
"key": ("|wB|Wack", "b"),
"desc": "|W(PrevNode)|n",
},
{
"goto": "node_NextNode",
"key": ("|wF|Worward", "f"),
"desc": "|W(NextNode)|n",
},
{"goto": "node_PrevNode", "key": ("|wB|Wack", "b"), "desc": "|W(PrevNode)|n"},
{"goto": "node_NextNode", "key": ("|wF|Worward", "f"), "desc": "|W(NextNode)|n"},
{"goto": "node_index", "key": ("|wI|Wndex", "i")},
{
"goto": ("node_validate_prototype", {"back": "ThisNode"}),
@ -784,33 +701,19 @@ class TestMenuModule(EvenniaTest):
],
)
self.assertEqual(olc_menus._validate_prototype(self.test_prot), (False, Something))
self.assertEqual(
olc_menus._validate_prototype(self.test_prot), (False, Something)
)
self.assertEqual(
olc_menus._validate_prototype(
{"prototype_key": "testthing", "key": "mytest"}
),
olc_menus._validate_prototype({"prototype_key": "testthing", "key": "mytest"}),
(True, Something),
)
choices = ["test1", "test2", "test3", "test4"]
actions = (("examine", "e", "l"), ("add", "a"), ("foo", "f"))
self.assertEqual(
olc_menus._default_parse("l4", choices, *actions), ("test4", "examine")
)
self.assertEqual(
olc_menus._default_parse("add 2", choices, *actions), ("test2", "add")
)
self.assertEqual(
olc_menus._default_parse("foo3", choices, *actions), ("test3", "foo")
)
self.assertEqual(
olc_menus._default_parse("f3", choices, *actions), ("test3", "foo")
)
self.assertEqual(
olc_menus._default_parse("f5", choices, *actions), (None, None)
)
self.assertEqual(olc_menus._default_parse("l4", choices, *actions), ("test4", "examine"))
self.assertEqual(olc_menus._default_parse("add 2", choices, *actions), ("test2", "add"))
self.assertEqual(olc_menus._default_parse("foo3", choices, *actions), ("test3", "foo"))
self.assertEqual(olc_menus._default_parse("f3", choices, *actions), ("test3", "foo"))
self.assertEqual(olc_menus._default_parse("f5", choices, *actions), (None, None))
def test_node_helpers(self):
@ -823,9 +726,7 @@ class TestMenuModule(EvenniaTest):
# prototype_key helpers
self.assertEqual(olc_menus._check_prototype_key(caller, "test_prot"), None)
caller.ndb._menutree.olc_new = True
self.assertEqual(
olc_menus._check_prototype_key(caller, "test_prot"), "node_index"
)
self.assertEqual(olc_menus._check_prototype_key(caller, "test_prot"), "node_index")
# prototype_parent helpers
self.assertEqual(olc_menus._all_prototype_parents(caller), ["test_prot"])
@ -840,8 +741,7 @@ class TestMenuModule(EvenniaTest):
new=mock.MagicMock(return_value=[_PROTPARENTS["GOBLIN"]]),
):
self.assertEqual(
olc_menus._prototype_parent_select(caller, "goblin"),
"node_prototype_parent",
olc_menus._prototype_parent_select(caller, "goblin"), "node_prototype_parent"
)
self.assertEqual(
@ -862,10 +762,7 @@ class TestMenuModule(EvenniaTest):
self.assertEqual(olc_menus._all_typeclasses(caller), ["bar", "foo"])
self.assertEqual(
olc_menus._typeclass_select(
caller, "evennia.objects.objects.DefaultObject"
),
None,
olc_menus._typeclass_select(caller, "evennia.objects.objects.DefaultObject"), None
)
# prototype_parent should be popped off here
self.assertEqual(
@ -882,16 +779,12 @@ class TestMenuModule(EvenniaTest):
self.assertEqual(olc_menus._caller_attrs(caller), [])
self.assertEqual(olc_menus._add_attr(caller, "test1=foo1"), Something)
self.assertEqual(olc_menus._add_attr(caller, "test2;cat1=foo2"), Something)
self.assertEqual(olc_menus._add_attr(caller, "test3;cat2;edit:false()=foo3"), Something)
self.assertEqual(
olc_menus._add_attr(caller, "test3;cat2;edit:false()=foo3"), Something
olc_menus._add_attr(caller, "test4;cat3;set:true();edit:false()=foo4"), Something
)
self.assertEqual(
olc_menus._add_attr(caller, "test4;cat3;set:true();edit:false()=foo4"),
Something,
)
self.assertEqual(
olc_menus._add_attr(caller, "test5;cat4;set:true();edit:false()=123"),
Something,
olc_menus._add_attr(caller, "test5;cat4;set:true();edit:false()=123"), Something
)
self.assertEqual(olc_menus._add_attr(caller, "test1=foo1_changed"), Something)
self.assertEqual(
@ -915,93 +808,67 @@ class TestMenuModule(EvenniaTest):
olc_menus._get_menu_prototype(caller)["tags"],
[("foo1", None, ""), ("foo2", "cat1", ""), ("foo3", "cat2", "dat1")],
)
self.assertEqual(
olc_menus._add_tag(caller, "foo1", delete=True), "Removed Tag 'foo1'."
)
self.assertEqual(olc_menus._add_tag(caller, "foo1", delete=True), "Removed Tag 'foo1'.")
self.assertEqual(
olc_menus._get_menu_prototype(caller)["tags"],
[("foo2", "cat1", ""), ("foo3", "cat2", "dat1")],
)
self.assertEqual(
olc_menus._display_tag(olc_menus._get_menu_prototype(caller)["tags"][0]),
Something,
olc_menus._display_tag(olc_menus._get_menu_prototype(caller)["tags"][0]), Something
)
self.assertEqual(olc_menus._caller_tags(caller), ["foo2", "foo3"])
protlib.save_prototype(self.test_prot)
# locks helpers
self.assertEqual(olc_menus._lock_add(caller, "foo:false()"), "Added lock 'foo:false()'.")
self.assertEqual(olc_menus._lock_add(caller, "foo2:false()"), "Added lock 'foo2:false()'.")
self.assertEqual(
olc_menus._lock_add(caller, "foo:false()"), "Added lock 'foo:false()'."
)
self.assertEqual(
olc_menus._lock_add(caller, "foo2:false()"), "Added lock 'foo2:false()'."
)
self.assertEqual(
olc_menus._lock_add(caller, "foo2:true()"),
"Lock with locktype 'foo2' updated.",
)
self.assertEqual(
olc_menus._get_menu_prototype(caller)["locks"], "foo:false();foo2:true()"
olc_menus._lock_add(caller, "foo2:true()"), "Lock with locktype 'foo2' updated."
)
self.assertEqual(olc_menus._get_menu_prototype(caller)["locks"], "foo:false();foo2:true()")
# perm helpers
self.assertEqual(olc_menus._add_perm(caller, "foo"), "Added Permission 'foo'")
self.assertEqual(olc_menus._add_perm(caller, "foo2"), "Added Permission 'foo2'")
self.assertEqual(
olc_menus._get_menu_prototype(caller)["permissions"], ["foo", "foo2"]
)
self.assertEqual(olc_menus._get_menu_prototype(caller)["permissions"], ["foo", "foo2"])
# prototype_tags helpers
self.assertEqual(
olc_menus._add_prototype_tag(caller, "foo"), "Added Prototype-Tag 'foo'."
)
self.assertEqual(olc_menus._add_prototype_tag(caller, "foo"), "Added Prototype-Tag 'foo'.")
self.assertEqual(
olc_menus._add_prototype_tag(caller, "foo2"), "Added Prototype-Tag 'foo2'."
)
self.assertEqual(
olc_menus._get_menu_prototype(caller)["prototype_tags"], ["foo", "foo2"]
)
self.assertEqual(olc_menus._get_menu_prototype(caller)["prototype_tags"], ["foo", "foo2"])
# spawn helpers
with mock.patch(
"evennia.prototypes.menus.protlib.search_prototype",
new=mock.MagicMock(return_value=[_PROTPARENTS["GOBLIN"]]),
):
self.assertEqual(
olc_menus._spawn(caller, prototype=self.test_prot), Something
)
self.assertEqual(olc_menus._spawn(caller, prototype=self.test_prot), Something)
obj = caller.contents[0]
self.assertEqual(obj.typeclass_path, "evennia.objects.objects.DefaultObject")
self.assertEqual(
obj.tags.get(category=spawner._PROTOTYPE_TAG_CATEGORY),
self.test_prot["prototype_key"],
obj.tags.get(category=spawner._PROTOTYPE_TAG_CATEGORY), self.test_prot["prototype_key"]
)
# update helpers
self.assertEqual(
olc_menus._apply_diff(
caller, prototype=self.test_prot, back_node="foo", objects=[obj]
),
olc_menus._apply_diff(caller, prototype=self.test_prot, back_node="foo", objects=[obj]),
"foo",
) # no changes to apply
self.test_prot["key"] = "updated key" # change prototype
self.assertEqual(
olc_menus._apply_diff(
caller, prototype=self.test_prot, objects=[obj], back_node="foo"
),
olc_menus._apply_diff(caller, prototype=self.test_prot, objects=[obj], back_node="foo"),
"foo",
) # apply change to the one obj
# load helpers
self.assertEqual(
olc_menus._prototype_load_select(caller, self.test_prot["prototype_key"]),
(
"node_examine_entity",
{"text": "|gLoaded prototype test_prot.|n", "back": "index"},
),
("node_examine_entity", {"text": "|gLoaded prototype test_prot.|n", "back": "index"}),
)
# diff helpers
@ -1033,11 +900,7 @@ class TestMenuModule(EvenniaTest):
"permissions": {"developer": ("developer", "developer", "KEEP")},
"prototype_desc": ("Testobject build", None, "REMOVE"),
"prototype_key": ("TestDiffKey", "TestDiffKey", "KEEP"),
"prototype_locks": (
"spawn:all();edit:all()",
"spawn:all();edit:all()",
"KEEP",
),
"prototype_locks": ("spawn:all();edit:all()", "spawn:all();edit:all()", "KEEP"),
"prototype_tags": {},
"tags": {"foo": (None, ("foo", None, ""), "ADD")},
"typeclass": (
@ -1070,21 +933,13 @@ class TestMenuModule(EvenniaTest):
self.assertEqual(
options,
[
{
"goto": (Something, Something),
"key": "1",
"desc": "|gKEEP|n (attrs) None",
},
{"goto": (Something, Something), "key": "1", "desc": "|gKEEP|n (attrs) None"},
{
"goto": (Something, Something),
"key": "2",
"desc": "|gKEEP|n (prototype_desc) Testobject build",
},
{
"goto": (Something, Something),
"key": "3",
"desc": "|gKEEP|n (tags) None",
},
{"goto": (Something, Something), "key": "3", "desc": "|gKEEP|n (tags) None"},
],
)
@ -1093,11 +948,7 @@ class TestMenuModule(EvenniaTest):
"evennia.prototypes.menus.protlib.search_prototype",
new=mock.MagicMock(
return_value=[
{
"prototype_key": "TestPrototype",
"typeclass": "TypeClassTest",
"key": "TestObj",
}
{"prototype_key": "TestPrototype", "typeclass": "TypeClassTest", "key": "TestObj"}
]
),
)
@ -1147,45 +998,15 @@ class TestOLCMenu(TestEvMenu):
"node_index",
],
"node_key",
[
"node_typeclass",
"node_key",
"node_index",
"node_validate_prototype",
"node_index",
],
["node_typeclass", "node_key", "node_index", "node_validate_prototype", "node_index"],
"node_aliases",
[
"node_key",
"node_aliases",
"node_index",
"node_validate_prototype",
"node_index",
],
["node_key", "node_aliases", "node_index", "node_validate_prototype", "node_index"],
"node_attrs",
[
"node_aliases",
"node_attrs",
"node_index",
"node_validate_prototype",
"node_index",
],
["node_aliases", "node_attrs", "node_index", "node_validate_prototype", "node_index"],
"node_tags",
[
"node_attrs",
"node_tags",
"node_index",
"node_validate_prototype",
"node_index",
],
["node_attrs", "node_tags", "node_index", "node_validate_prototype", "node_index"],
"node_locks",
[
"node_tags",
"node_locks",
"node_index",
"node_validate_prototype",
"node_index",
],
["node_tags", "node_locks", "node_index", "node_validate_prototype", "node_index"],
"node_permissions",
[
"node_locks",