PK MbMl pyfomod/__init__.py# Copyright 2016 Daniel Nunes
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A high-level fomod library written in Python."""
__version__ = "0.4.0"
__all__ = [
"Conditions",
"ConditionType",
"FilePatterns",
"Files",
"FileType",
"Flags",
"Group",
"GroupType",
"Info",
"Option",
"OptionType",
"Order",
"Page",
"Pages",
"Root",
"Type",
"warn",
"parse",
"write",
]
from .base import (
Conditions,
ConditionType,
FilePatterns,
Files,
FileType,
Flags,
Group,
GroupType,
Info,
Option,
OptionType,
Order,
Page,
Pages,
Root,
Type,
warn,
)
from .parser import parse, write
PK ֬M_T pyfomod/base.py# Copyright 2016 Daniel Nunes
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Base classes for pyfomod."""
import warnings
from collections import OrderedDict
from collections.abc import ItemsView, KeysView, Mapping, ValuesView
from enum import Enum
class ValidationWarning(UserWarning):
def __init__(self, title, msg, elem, *args, **kwargs):
self.title = title
self.msg = msg
self.elem = elem
super().__init__("{} - {}".format(title, msg), *args, **kwargs)
class CriticalWarning(ValidationWarning):
def __init__(self, title, msg, elem, *args, **kwargs):
msg += " This may stop users from installing."
super().__init__(title, msg, elem, *args, **kwargs)
def warn(title, msg, elem, critical=False):
if critical:
warning = CriticalWarning(title, msg, elem)
else:
warning = ValidationWarning(title, msg, elem)
warnings.warn(warning, stacklevel=2)
class ConditionType(Enum):
AND = "And"
OR = "Or"
class FileType(Enum):
MISSING = "Missing"
INACTIVE = "Inactive"
ACTIVE = "Active"
class Order(Enum):
ASCENDING = "Ascending"
DESCENDING = "Descending"
EXPLICIT = "Explicit"
class GroupType(Enum):
ATLEASTONE = "SelectAtLeastOne"
ATMOSTONE = "SelectAtMostOne"
EXACTLYONE = "SelectExactlyOne"
ALL = "SelectAll"
ANY = "SelectAny"
class OptionType(Enum):
REQUIRED = "Required"
OPTIONAL = "Optional"
RECOMMENDED = "Recommended"
NOTUSABLE = "NotUsable"
COULDBEUSABLE = "CouldBeUsable"
class HashableSequence(object):
def __getitem__(self, key):
raise NotImplementedError
def __setitem__(self, key, value):
raise NotImplementedError
def __delitem__(self, key):
raise NotImplementedError
def __len__(self):
raise NotImplementedError
def insert(self, index, value):
raise NotImplementedError
def __iter__(self):
i = 0
try:
while True:
v = self[i]
yield v
i += 1
except IndexError:
return
def __contains__(self, value):
for v in self:
if v is value or v == value:
return True
return False
def __reversed__(self):
for i in reversed(range(len(self))):
yield self[i]
def index(self, value, start=0, stop=None):
if start is not None and start < 0:
start = max(len(self) + start, 0)
if stop is not None and stop < 0:
stop += len(self)
i = start
while stop is None or i < stop:
try:
v = self[i]
if v is value or v == value:
return i
except IndexError:
break
i += 1
raise ValueError
def count(self, value):
return sum(1 for v in self if v is value or v == value)
def append(self, value):
self.insert(len(self), value)
def clear(self):
try:
while True:
self.pop()
except IndexError:
pass
def reverse(self):
n = len(self)
for i in range(n // 2):
self[i], self[n - i - 1] = self[n - i - 1], self[i]
def extend(self, values):
if values is self:
values = list(values)
for v in values:
self.append(v)
def pop(self, index=-1):
v = self[index]
del self[index]
return v
def remove(self, value):
del self[self.index(value)]
def __iadd__(self, values):
self.extend(values)
return self
class HashableMapping(object):
def __getitem__(self, key):
raise NotImplementedError
def __setitem__(self, key, value):
raise NotImplementedError
def __delitem__(self, key):
raise NotImplementedError
def __iter__(self):
raise NotImplementedError
def __len__(self):
raise NotImplementedError
def __contains__(self, key):
try:
self[key]
except KeyError:
return False
else:
return True
def keys(self):
return KeysView(self)
def items(self):
return ItemsView(self)
def values(self):
return ValuesView(self)
def get(self, key, default=None):
try:
return self[key]
except KeyError:
return default
__marker = object()
def pop(self, key, default=__marker):
try:
value = self[key]
except KeyError:
if default is self.__marker:
raise
return default
else:
del self[key]
return value
def popitem(self):
try:
key = next(iter(self))
except StopIteration:
raise KeyError from None
value = self[key]
del self[key]
return key, value
def clear(self):
try:
while True:
self.popitem()
except KeyError:
pass
def update(*args, **kwargs):
if not args:
raise TypeError(
"descriptor 'update' of 'HashableMapping' object needs an argument"
)
self, *args = args
if len(args) > 1:
raise TypeError("update expected at most 1 arguments, got %d" % len(args))
if args:
other = args[0]
if isinstance(other, Mapping):
for key in other:
self[key] = other[key]
elif hasattr(other, "keys"):
for key in other.keys():
self[key] = other[key]
else:
for key, value in other:
self[key] = value
for key, value in kwargs.items():
self[key] = value
def setdefault(self, key, default=None):
try:
return self[key]
except KeyError:
self[key] = default
return default
class BaseFomod(object):
def __init__(self, tag, attrib):
self._tag = tag
self._attrib = attrib
self._children = OrderedDict()
def to_string(self):
raise NotImplementedError()
def validate(self, **callbacks):
for key, funcs in callbacks.items():
if isinstance(self, globals()[key]):
for func in funcs:
func(self)
@staticmethod
def _write_attributes(attrib):
result = ""
for attr, value in attrib.items():
result += " "
result += str(attr)
result += "="
result += '"{}"'.format(str(value))
return result
def _write_children(self):
children = ""
for tag, data in self._children.items():
attribs = data[0]
text = data[1]
attribs_str = self._write_attributes(attribs)
if text:
children += "\n" + "<{0}{2}>{1}{0}>".format(tag, text, attribs_str)
else:
children += "\n" + "<{}{}/>".format(tag, attribs_str)
return children
class Root(BaseFomod):
def __init__(self, attrib=None):
if attrib is None:
attrib = {}
super().__init__("config", attrib)
# these attributes are set for max compatibility
schema_url = "http://qconsulting.ca/fo3/ModConfig5.0.xsd"
self._attrib = {
"xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"xsi:noNamespaceSchemaLocation": schema_url,
}
self._info = Info()
self._name = Name()
self._conditions = Conditions()
self._conditions._tag = "moduleDependencies"
self._files = Files()
self._files._tag = "requiredInstallFiles"
self._pages = Pages()
self._file_patterns = FilePatterns()
@property
def name(self):
return self._name.name
@name.setter
def name(self, value):
if not isinstance(value, str):
raise ValueError("Value should be string.")
self._name.name = value
@property
def author(self):
return self._info.get_text("Author")
@author.setter
def author(self, value):
if not isinstance(value, str):
raise ValueError("Value should be string.")
self._info.set_text("Author", value)
@property
def version(self):
return self._info.get_text("Version")
@version.setter
def version(self, value):
if not isinstance(value, str):
raise ValueError("Value should be string.")
self._info.set_text("Version", value)
@property
def description(self):
return self._info.get_text("Description")
@description.setter
def description(self, value):
if not isinstance(value, str):
raise ValueError("Value should be string.")
self._info.set_text("Description", value)
@property
def website(self):
return self._info.get_text("Website")
@website.setter
def website(self, value):
if not isinstance(value, str):
raise ValueError("Value should be string.")
self._info.set_text("Website", value)
@property
def conditions(self):
return self._conditions
@conditions.setter
def conditions(self, value):
if not isinstance(value, Conditions):
raise ValueError("Value should be Conditions.")
self._conditions = value
self._conditions._tag = "moduleDependencies"
@property
def files(self):
return self._files
@files.setter
def files(self, value):
if not isinstance(value, Files):
raise ValueError("Value should be Files.")
self._files = value
self._files._tag = "requiredInstallFiles"
@property
def pages(self):
return self._pages
@pages.setter
def pages(self, value):
if not isinstance(value, Pages):
raise ValueError("Value should be Pages.")
self._pages = value
@property
def file_patterns(self):
return self._file_patterns
@file_patterns.setter
def file_patterns(self, value):
if not isinstance(value, FilePatterns):
raise ValueError("Value should be FilePatterns.")
self._file_patterns = value
def to_string(self):
children = ""
head = "<{}{}>".format(self._tag, self._write_attributes(self._attrib))
children += "\n" + self._name.to_string()
children += self._write_children() # moduleImage
if self._conditions:
children += "\n" + self._conditions.to_string()
if self._files:
children += "\n" + self._files.to_string()
if self._pages:
children += "\n" + self._pages.to_string()
if self._file_patterns:
children += "\n" + self._file_patterns.to_string()
children = children.replace("\n", "\n ")
tail = "{}>".format(self._tag)
return "{}{}\n{}".format(head, children, tail)
def validate(self, **callbacks):
super().validate(**callbacks)
flag_set = []
flag_dep = []
def parse_conditions(conditions):
result = []
for key, value in conditions.items():
if isinstance(key, Conditions):
result.extend(parse_conditions(key))
elif isinstance(key, str) and isinstance(value, str):
result.append((key, conditions))
return result
callbacks.setdefault("Conditions", []).append(
lambda x: flag_dep.extend(parse_conditions(x))
)
callbacks.setdefault("Flags", []).append(lambda x: flag_set.extend(x.keys()))
self._name.validate(**callbacks)
if self._conditions:
self._conditions.validate(**callbacks)
if self._files:
self._files.validate(**callbacks)
if self._pages:
self._pages.validate(**callbacks)
if self._file_patterns:
self._file_patterns.validate(**callbacks)
if not self._files and not self._pages and not self._file_patterns:
title = "Empty Installer"
msg = "This fomod is empty, nothing will be installed."
warn(title, msg, self)
for flag, instance in flag_dep:
if flag not in flag_set:
title = "Impossible Flags"
msg = 'The flag "{}" is never created or set.'.format(flag)
warn(title, msg, instance)
class Info(BaseFomod):
def __init__(self, attrib=None):
if attrib is None:
attrib = {}
super().__init__("fomod", attrib)
def get_text(self, tag):
for key, value in self._children.items():
if key.lower() == tag.lower():
return value[1]
return ""
def set_text(self, tag, text):
for key, value in self._children.items():
if key.lower() == tag.lower():
self._children[key] = (value[0], text)
return
self._children[tag] = ({}, text)
def to_string(self):
head = "<{}{}>".format(self._tag, self._write_attributes(self._attrib))
children = self._write_children()
children = children.replace("\n", "\n ")
tail = "{}>".format(self._tag)
return "{}{}\n{}".format(head, children, tail)
class Name(BaseFomod):
def __init__(self, attrib=None):
if attrib is None:
attrib = {}
super().__init__("moduleName", attrib)
self.name = ""
def to_string(self):
attrib = self._write_attributes(self._attrib)
return "<{0}{1}>{2}{0}>".format(self._tag, attrib, self.name)
def validate(self, **callbacks):
super().validate(**callbacks)
if not self.name:
title = "Missing Installer Name"
msg = "This fomod does not have a name."
warn(title, msg, self)
class Conditions(BaseFomod, HashableMapping):
def __init__(self, attrib=None):
if attrib is None:
attrib = {}
super().__init__("dependencies", attrib)
self._type = ConditionType.AND
self._map = OrderedDict()
@property
def type(self):
return self._type
@type.setter
def type(self, value):
if not isinstance(value, ConditionType):
raise ValueError("Value should be ConditionType.")
self._type = value
def __getitem__(self, key):
return self._map[key]
def __setitem__(self, key, value):
if key is not None and not isinstance(key, (str, Conditions)):
raise TypeError("Key must be either None, string or Conditions.")
if key is None and not isinstance(value, str):
raise TypeError("Value for None key must be string.")
if isinstance(key, str) and not isinstance(value, (str, FileType)):
raise TypeError("Value for string key must be string or FileType.")
if isinstance(key, Conditions):
if value is not None:
raise TypeError("Value for Conditions key must be None.")
key._tag = "dependencies"
self._map[key] = value
def __delitem__(self, key):
del self._map[key]
def __iter__(self):
return iter(self._map)
def __len__(self):
return len(self._map)
def to_string(self):
children = ""
attrib = dict(self._attrib)
attrib["operator"] = self._type.value
head = "<{}{}>".format(self._tag, self._write_attributes(attrib))
for key, value in self._map.items():
if key is None:
child = ''.format(value)
elif isinstance(key, Conditions):
if not key:
continue
child = key.to_string()
elif isinstance(value, str): # string key
tag = "flagDependency"
child = '<{} flag="{}" value="{}"/>'.format(tag, key, value)
elif isinstance(value, FileType): # string key
tag = "fileDependency"
child = '<{} file="{}" state="{}"/>'.format(tag, key, value.value)
children += "\n" + child
children = children.replace("\n", "\n ")
tail = "{}>".format(self._tag)
return "{}{}\n{}".format(head, children, tail)
def validate(self, **callbacks):
super().validate(**callbacks)
if not self:
title = "Empty Conditions"
msg = "This element should have at least one condition present."
warn(title, msg, self, critical=True)
for key, value in self._map.items():
if isinstance(key, Conditions):
if not key:
title = "Empty Conditions"
msg = (
"This element is empty and will not be written to "
"prevent errors."
)
warn(title, msg, key)
else:
key.validate(**callbacks)
elif key is None and not value:
title = "Empty Version Dependency"
msg = "This version dependency is empty " "and may not work correctly."
warn(title, msg, self)
elif isinstance(key, str):
if not key and isinstance(value, FileType):
title = "Empty File Dependency"
msg = (
"This file dependency depends on no file, "
"may not work correctly."
)
warn(title, msg, self)
elif self._tag == "moduleDependencies" and isinstance(value, str):
title = "Useless Flags"
msg = (
"Flag {} shouldn't be used here "
"since it can't have been set.".format(key)
)
warn(title, msg, self)
class Files(BaseFomod, HashableMapping):
def __init__(self, attrib=None):
if attrib is None:
attrib = {}
super().__init__("files", attrib)
self._file_list = []
def __getitem__(self, key):
if not isinstance(key, str):
raise TypeError("Key must be string.")
if key.endswith(("/", "\\")) and key not in self:
key = key[:-1]
try:
return next(a.dst for a in self._file_list if a.src == key)
except StopIteration:
raise KeyError()
# trailing slash -> folder, else file
def __setitem__(self, key, value):
if not isinstance(key, str):
raise TypeError("Key must be string.")
if not isinstance(value, str):
raise TypeError("Value must be string.")
folder = False
if key.endswith(("/", "\\")) and key not in self:
key = key[:-1]
folder = True
try:
next(a for a in self._file_list if a.src == key).dst = value
except StopIteration:
if folder:
new = File(tag="folder")
else:
new = File(tag="file")
new.src = key
new.dst = value
self._file_list.append(new)
def __delitem__(self, key):
if not isinstance(key, str):
raise TypeError("Key must be string.")
if key.endswith(("/", "\\")) and key not in self:
key = key[:-1]
try:
value = next(a for a in self._file_list if a.src == key)
self._file_list.remove(value)
except StopIteration:
raise KeyError()
def __iter__(self):
for item in self._file_list:
source = item.src
if item._tag == "folder" and not source.endswith(("/", "\\")):
source = "{}/".format(source)
yield source
def __len__(self):
return len(self._file_list)
def __contains__(self, key):
try:
next(a for a in self._file_list if a.src == key)
return True
except StopIteration:
return False
def to_string(self):
children = ""
head = "<{}{}>".format(self._tag, self._write_attributes(self._attrib))
for child in self._file_list:
children += "\n" + child.to_string()
children = children.replace("\n", "\n ")
tail = "{}>".format(self._tag)
return "{}{}\n{}".format(head, children, tail)
def validate(self, **callbacks):
super().validate(**callbacks)
for child in self._file_list:
child.validate(**callbacks)
class File(BaseFomod):
def __init__(self, tag="", attrib=None):
if attrib is None:
attrib = {}
super().__init__(tag, attrib)
self.src = ""
self.dst = ""
def to_string(self):
attrib = dict(self._attrib)
attrib["source"] = self.src
if self.dst:
attrib["destination"] = self.dst
elif "destination" in attrib:
del attrib["destination"]
return "<{}{}/>".format(self._tag, self._write_attributes(attrib))
def validate(self, **callbacks):
super().validate(**callbacks)
if not self.src:
title = "Empty Source Field"
msg = "No source specified, nothing will be installed."
warn(title, msg, self)
class Pages(BaseFomod, HashableSequence):
def __init__(self, attrib=None):
if attrib is None:
attrib = {}
super().__init__("installSteps", attrib)
self._page_list = []
self._order = Order.EXPLICIT
@property
def order(self):
return self._order
@order.setter
def order(self, value):
if not isinstance(value, Order):
raise ValueError("Value should be Order.")
self._order = value
def __getitem__(self, key):
return self._page_list[key]
def __setitem__(self, key, value):
if not isinstance(value, Page):
raise ValueError("Value should be Page.")
self._page_list[key] = value
def __delitem__(self, key):
del self._page_list[key]
def __len__(self):
return len(self._page_list)
def insert(self, key, value):
if not isinstance(value, Page):
raise ValueError("Value should be Page.")
self._page_list.insert(key, value)
def to_string(self):
children = ""
attrib = dict(self._attrib)
attrib["order"] = self._order.value
head = "<{}{}>".format(self._tag, self._write_attributes(attrib))
for child in self._page_list:
if child:
children += "\n" + child.to_string()
children = children.replace("\n", "\n ")
tail = "{}>".format(self._tag)
return "{}{}\n{}".format(head, children, tail)
def validate(self, **callbacks):
super().validate(**callbacks)
for page in self._page_list:
if page:
page.validate(**callbacks)
else:
title = "Empty Page"
msg = "This page is empty and will not be written to prevent errors."
warn(title, msg, page)
class Page(BaseFomod, HashableSequence):
def __init__(self, attrib=None):
if attrib is None:
attrib = {}
super().__init__("installStep", attrib)
self._group_list = []
self._name = ""
self._conditions = Conditions()
self._conditions._tag = "visible"
self._order = Order.EXPLICIT
@property
def name(self):
return self._name
@name.setter
def name(self, value):
if not isinstance(value, str):
raise ValueError("Value should be string.")
self._name = value
@property
def conditions(self):
return self._conditions
@conditions.setter
def conditions(self, value):
if not isinstance(value, Conditions):
raise ValueError("Value should be Conditions.")
self._conditions = value
self._conditions._tag = "visible"
@property
def order(self):
return self._order
@order.setter
def order(self, value):
if not isinstance(value, Order):
raise ValueError("Value should be Order.")
self._order = value
def __getitem__(self, key):
return self._group_list[key]
def __setitem__(self, key, value):
if not isinstance(value, Group):
raise ValueError("Value should be Group.")
self._group_list[key] = value
def __delitem__(self, key):
del self._group_list[key]
def __len__(self):
return len(self._group_list)
def insert(self, key, value):
if not isinstance(value, Group):
raise ValueError("Value should be Group.")
self._group_list.insert(key, value)
def to_string(self):
children = ""
grp_tag = "optionalFileGroups"
attrib = dict(self._attrib)
attrib["name"] = self._name
grp_attrib = {"order": self._order.value}
head = "<{}{}>".format(self._tag, self._write_attributes(attrib))
grp_head = "<{}{}>".format(grp_tag, self._write_attributes(grp_attrib))
grp_tail = "{}>".format(grp_tag)
tail = "{}>".format(self._tag)
if self._conditions:
children += "\n" + self._conditions.to_string()
children += "\n" + grp_head
for child in self._group_list:
if child:
children += "\n " + child.to_string().replace("\n", "\n ")
children += "\n" + grp_tail
children = children.replace("\n", "\n ")
return "{}{}\n{}".format(head, children, tail)
def validate(self, **callbacks):
super().validate(**callbacks)
if self._conditions:
self._conditions.validate(**callbacks)
for group in self._group_list:
if group:
group.validate(**callbacks)
else:
title = "Empty Group"
msg = "This group is empty and will not be written to prevent errors."
warn(title, msg, group)
if not self._name:
title = "Empty Page Name"
msg = "This page has no name."
warn(title, msg, self)
class Group(BaseFomod, HashableSequence):
def __init__(self, attrib=None):
if attrib is None:
attrib = {}
super().__init__("group", attrib)
self._option_list = []
self._name = ""
self._order = Order.EXPLICIT
self._type = GroupType.ATLEASTONE
@property
def name(self):
return self._name
@name.setter
def name(self, value):
if not isinstance(value, str):
raise ValueError("Value should be string.")
self._name = value
@property
def order(self):
return self._order
@order.setter
def order(self, value):
if not isinstance(value, Order):
raise ValueError("Value should be Order.")
self._order = value
@property
def type(self):
return self._type
@type.setter
def type(self, value):
if not isinstance(value, GroupType):
raise ValueError("Value should be GroupType.")
self._type = value
def __getitem__(self, key):
return self._option_list[key]
def __setitem__(self, key, value):
if not isinstance(value, Option):
raise ValueError("Value should be Option.")
self._option_list[key] = value
def __delitem__(self, key):
del self._option_list[key]
def __len__(self):
return len(self._option_list)
def insert(self, key, value):
if not isinstance(value, Option):
raise ValueError("Value should be Option.")
self._option_list.insert(key, value)
def to_string(self):
children = ""
opt_tag = "plugins"
attrib = dict(self._attrib)
attrib["name"] = self._name
attrib["type"] = self._type.value
opt_attrib = {"order": self._order.value}
head = "<{}{}>".format(self._tag, self._write_attributes(attrib))
opt_head = "<{}{}>".format(opt_tag, self._write_attributes(opt_attrib))
opt_tail = "{}>".format(opt_tag)
tail = "{}>".format(self._tag)
children += "\n" + opt_head
for child in self._option_list:
children += "\n " + child.to_string().replace("\n", "\n ")
children += "\n" + opt_tail
children = children.replace("\n", "\n ")
return "{}{}\n{}".format(head, children, tail)
def validate(self, **callbacks):
super().validate(**callbacks)
for option in self._option_list:
option.validate(**callbacks)
if not self._name:
title = "Empty Group Name"
msg = "This group has no name."
warn(title, msg, self)
class Option(BaseFomod):
def __init__(self, attrib=None):
if attrib is None:
attrib = {}
super().__init__("plugin", attrib)
self._name = ""
self._description = ""
self._image = ""
self._files = Files()
self._files._tag = "files"
self._flags = Flags()
self._type = OptionType.OPTIONAL
@property
def name(self):
return self._name
@name.setter
def name(self, value):
if not isinstance(value, str):
raise ValueError("Value should be string.")
self._name = value
@property
def description(self):
return self._description
@description.setter
def description(self, value):
if not isinstance(value, str):
raise ValueError("Value should be string.")
self._description = value
@property
def image(self):
return self._image
@image.setter
def image(self, value):
if not isinstance(value, str):
raise ValueError("Value should be string.")
self._image = value
@property
def files(self):
return self._files
@files.setter
def files(self, value):
if not isinstance(value, Files):
raise ValueError("Value should be Files.")
self._files = value
self._files._tag = "files"
@property
def flags(self):
return self._flags
@flags.setter
def flags(self, value):
if not isinstance(value, Flags):
raise ValueError("Value should be Flags.")
self._flags = value
@property
def type(self):
return self._type
@type.setter
def type(self, value):
if not isinstance(value, (Type, OptionType)):
raise ValueError("Value should be OptionType or Type.")
self._type = value
def to_string(self):
children = ""
attrib = dict(self._attrib)
attrib["name"] = self.name
head = "<{}{}>".format(self._tag, self._write_attributes(attrib))
children += "\n"
children += "{}".format(self.description)
if self.image:
children += "\n" + ''.format(self.image)
if self.files:
children += "\n" + self.files.to_string()
if self.flags:
children += "\n" + self.flags.to_string()
children += "\n" + ""
if isinstance(self.type, OptionType):
children += "\n " + ''.format(self.type.value)
else:
children += "\n " + self.type.to_string()
children += "\n" + ""
children = children.replace("\n", "\n ")
tail = "{}>".format(self._tag)
return "{}{}\n{}".format(head, children, tail)
def validate(self, **callbacks):
super().validate(**callbacks)
if not self.name:
title = "Empty Option Name"
msg = "This option has no name."
warn(title, msg, self)
if not self.description:
title = "Empty Option Description"
msg = "This option has no description."
warn(title, msg, self)
if not self.files and not self.flags:
title = "Option Does Nothing"
msg = "This option installs no files and sets no flags."
warn(title, msg, self)
if self.files:
self.files.validate(**callbacks)
if self.flags:
self.flags.validate(**callbacks)
if isinstance(self.type, Type):
self.type.validate(**callbacks)
class Flags(BaseFomod, HashableMapping):
def __init__(self, attrib=None):
if attrib is None:
attrib = {}
super().__init__("conditionFlags", attrib)
self._map = OrderedDict()
def __getitem__(self, key):
return self._map[key]
def __setitem__(self, key, value):
if not isinstance(key, str):
raise TypeError("Key must be string.")
if not isinstance(value, str):
raise TypeError("Value must be string.")
self._map[key] = value
def __delitem__(self, key):
del self._map[key]
def __iter__(self):
return iter(self._map)
def __len__(self):
return len(self._map)
def to_string(self):
children = ""
head = "<{}{}>".format(self._tag, self._write_attributes(self._attrib))
for key, value in self._map.items():
children += "\n" + '{}'.format(key, value)
children = children.replace("\n", "\n ")
tail = "{}>".format(self._tag)
return "{}{}\n{}".format(head, children, tail)
class Type(BaseFomod, HashableMapping):
def __init__(self, attrib=None):
if attrib is None:
attrib = {}
super().__init__("dependencyType", attrib)
self._default = OptionType.OPTIONAL
self._map = OrderedDict()
@property
def default(self):
return self._default
@default.setter
def default(self, value):
if not isinstance(value, OptionType):
raise ValueError("Value should be OptionType.")
self._default = value
def __getitem__(self, key):
return self._map[key]
def __setitem__(self, key, value):
if not isinstance(key, Conditions):
raise TypeError("Key must be Conditions.")
if not isinstance(value, OptionType):
raise TypeError("Value must be OptionType.")
key._tag = "dependencies"
self._map[key] = value
def __delitem__(self, key):
del self._map[key]
def __iter__(self):
return iter(self._map)
def __len__(self):
return len(self._map)
def to_string(self):
children = ""
head = "<{}{}>".format(self._tag, self._write_attributes(self._attrib))
children += "\n"
children += ''.format(self.default.value)
children += "\n" + ""
for key, value in self._map.items():
children += "\n " + ""
children += "\n " + key.to_string().replace("\n", "\n ")
children += "\n " + ''.format(value.value)
children += "\n " + ""
children += "\n" + ""
children = children.replace("\n", "\n ")
tail = "{}>".format(self._tag)
return "{}{}\n{}".format(head, children, tail)
def validate(self, **callbacks):
super().validate(**callbacks)
if not self:
title = "Empty Type Descriptor"
msg = "This type descriptor is empty and will never set a type."
warn(title, msg, self, critical=True)
for key in self._map:
key.validate(**callbacks)
class FilePatterns(BaseFomod, HashableMapping):
def __init__(self, attrib=None):
if attrib is None:
attrib = {}
super().__init__("conditionalFileInstalls", attrib)
self._map = OrderedDict()
def __getitem__(self, key):
return self._map[key]
def __setitem__(self, key, value):
if not isinstance(key, Conditions):
raise TypeError("Key must be Conditions.")
if not isinstance(value, Files):
raise TypeError("Value must be Files.")
key._tag = "dependencies"
value._tag = "files"
self._map[key] = value
def __delitem__(self, key):
del self._map[key]
def __iter__(self):
return iter(self._map)
def __len__(self):
return len(self._map)
def to_string(self):
children = ""
head = "<{}{}>".format(self._tag, self._write_attributes(self._attrib))
children += "\n" + ""
for key, value in self._map.items():
children += "\n " + ""
children += "\n " + key.to_string().replace("\n", "\n ")
children += "\n " + value.to_string().replace("\n", "\n ")
children += "\n " + ""
children += "\n" + ""
children = children.replace("\n", "\n ")
tail = "{}>".format(self._tag)
return "{}{}\n{}".format(head, children, tail)
def validate(self, **callbacks):
super().validate(**callbacks)
for key, value in self._map.items():
key.validate(**callbacks)
value.validate(**callbacks)
PK ֬MR) ) pyfomod/fomod.xsd
PK ֬M9D pyfomod/parser.py# Copyright 2016 Daniel Nunes
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import errno
import os
from collections import OrderedDict
from contextlib import suppress
from pathlib import Path
from lxml import etree
from . import base
SCHEMA_PATH = Path(__file__).parent / "fomod.xsd"
class Placeholder(object):
def __init__(self, tag, attrib):
self._tag = tag
self._attrib = attrib
self._children = OrderedDict()
class PatternPlaceholder(Placeholder):
def __init__(self, attrib):
super().__init__("pattern", attrib)
self.conditions = None
self.value = None
class Target(object):
def __init__(self, quiet=True):
self.quiet = quiet
self._stack = []
self._data = ""
self._last = None
def start(self, tag, attrib):
elem = None
attrib = dict(attrib)
with suppress(IndexError):
parent = self._stack[-1]
with suppress(IndexError):
gparent = self._stack[-2]
if tag == "config":
elem = base.Root(attrib)
elif tag == "fomod":
elem = base.Info(attrib)
elif tag == "moduleName":
elem = base.Name(attrib)
parent._name = elem
elif tag in ("moduleDependencies", "dependencies", "visible"):
elem = base.Conditions(attrib)
elem.type = base.ConditionType(attrib.get("operator", "And"))
if isinstance(parent, base.Conditions): # nested dependencies
parent[elem] = None
else:
parent.conditions = elem
elif tag == "requiredInstallFiles":
elem = base.Files(attrib)
parent.files = elem
elif tag in ("file", "folder"):
elem = base.File(tag, attrib)
elem.src = attrib["source"]
elem.dst = attrib.get("destination", "")
parent._file_list.append(elem)
elif tag == "installSteps":
elem = base.Pages(attrib)
elem.order = base.Order(attrib.get("order", "Ascending"))
parent.pages = elem
elif tag == "installStep":
elem = base.Page(attrib)
elem.name = attrib["name"]
parent._page_list.append(elem)
elif tag == "group":
elem = base.Group(attrib)
elem.name = attrib["name"]
elem.type = base.GroupType(attrib["type"])
gparent._group_list.append(elem)
elif tag == "plugin":
elem = base.Option(attrib)
elem.name = attrib["name"]
gparent._option_list.append(elem)
elif tag == "files":
elem = base.Files(attrib)
if isinstance(parent, base.Option):
parent.files = elem
else: # under pattern tag
parent.value = elem
elif tag == "conditionFlags":
elem = base.Flags(attrib)
parent.flags = elem
elif tag == "dependencyType":
elem = base.Type(attrib)
gparent.type = elem
elif tag == "conditionalFileInstalls":
elem = base.FilePatterns(attrib)
parent.file_patterns = elem
elif tag == "pattern":
elem = PatternPlaceholder(attrib)
else:
elem = Placeholder(tag, attrib)
self._stack.append(elem)
def data(self, data):
self._data = data.strip()
def end(self, tag):
elem = self._stack.pop()
assert tag == elem._tag
with suppress(IndexError):
parent = self._stack[-1]
with suppress(IndexError):
gparent = self._stack[-2]
if isinstance(elem, Placeholder):
parent._children[elem._tag] = (elem._attrib, self._data)
if tag == "moduleName":
elem.name = self._data
elif tag == "fileDependency":
fname = elem._attrib["file"]
ftype = base.FileType(elem._attrib["state"])
parent[fname] = ftype
elif tag == "flagDependency":
fname = elem._attrib["flag"]
fvalue = elem._attrib["value"]
parent[fname] = fvalue
elif tag == "gameDependency":
parent[None] = elem._attrib["version"]
elif tag in ("optionalFileGroups", "plugins"):
order = elem._attrib.get("order", "Ascending")
parent._order = base.Order(order)
elif tag == "description":
parent._description = self._data
elif tag == "image":
parent._image = elem._attrib["path"]
elif tag == "flag":
parent._map[elem._attrib["name"]] = self._data
elif tag == "type":
if isinstance(gparent, base.Option):
gparent._type = base.OptionType(elem._attrib["name"])
else: # under pattern tag
parent.value = base.OptionType(elem._attrib["name"])
elif tag == "defaultType":
parent._default = base.OptionType(elem._attrib["name"])
elif tag == "pattern":
gparent[elem.conditions] = elem.value
self._data = ""
self._last = elem
def comment(self, text):
if text and not self.quiet:
title = "Comment Detected"
msg = "There are comments in this fomod, they will be ignored."
base.warn(title, msg, None)
def close(self):
assert not self._stack
assert isinstance(self._last, (base.Root, base.Info))
return self._last
def parse(source, quiet=True):
if isinstance(source, (tuple, list)):
info, conf = source
else:
path = Path(source) / "fomod"
if not path.is_dir():
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), "fomod")
info = path / "info.xml"
conf = path / "moduleconfig.xml"
if not info.is_file():
info = None
else:
info = str(info)
if not conf.is_file():
raise FileNotFoundError(
errno.ENOENT, os.strerror(errno.ENOENT), "moduleconfig.xml"
)
else:
conf = str(conf)
if not quiet:
schema = etree.XMLSchema(etree.parse(str(SCHEMA_PATH)))
try:
etree.parse(conf, etree.XMLParser(schema=schema))
except etree.XMLSyntaxError as exc:
base.warn("Syntax Error", str(exc), None, critical=True)
parser = etree.XMLParser(target=Target(quiet))
root = etree.parse(conf, parser)
if info is not None:
root._info = etree.parse(info, parser)
return root
def write(root, path):
if isinstance(path, (tuple, list)):
info = path[0]
if info is not None:
info = Path(info)
conf = Path(path[1])
else:
path = Path(path) / "fomod"
path.mkdir(parents=True, exist_ok=True)
info = path / "info.xml"
conf = path / "moduleconfig.xml"
if info is not None:
with info.open("w") as info_f:
info_f.write(root._info.to_string())
info_f.write("\n")
with conf.open("w") as conf_f:
conf_f.write(root.to_string())
conf_f.write("\n")
PK !L;U], ], pyfomod-0.4.0.dist-info/LICENSE Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
PK !H>*R Q pyfomod-0.4.0.dist-info/WHEELHM
K-*ϳR03rOK-J,/RH,rzd&Y)r$[)T&Ur PK !H? pyfomod-0.4.0.dist-info/METADATAV]s6|ǯzm I'3jTWqcy!"Q I}ىNb;-p7ux|NMҋ^k]t؉KV.r.?Ld4i2)T*h|t2`$<9M\=yZsFKsëJ.vv7Y*dp$
ƉnD*mN~!p }Ȭ9֭m`Q&AvPqY
Q;xBfzbcEwm:c26~lh;IV~\6"<<Z&afb_Yזb9
A|W(Ǘ9#F\
'4"u] oH|~W.ݓ .jVFquQZz!ZmT>Izm%(P *-]{)zT[aI:ܶ
ZjsKPE*xYGE=:di\cNw0K&b&@R
M5)F%-qK"Y(+"m ';-пyt1$spi{$HSmJkɫ[ QJ2+`YK5 mm69c;lCge=kнFt⾖v+hq^Oz||LFkG2'5wEǭVKd-VxxCM5W6dABHmOq۞LJx m/.Jp\J
07$Ϗ~fܡc*OP++N(>87
CTh
ݸMO}o!fy=Y8Mlm3.K9m3)E^n%/|;&b/UYA0qՇXҧ[zj%o_5Vqq'uEhWb:w(R~8tS>C1ʵ=@Ty`kz[o5eʋĝ6-72Kr˸ dfiBӽ}PAf7WN+#m PK !H Q pyfomod-0.4.0.dist-info/RECORDuIs@ {~%h &Eɰ٠!\^7m3ip>s2d:7ifülݢTJO7$1@ KJz[ȍOVB(t]HC~K`$Rӟ (AhP=aUՆ b(rlź$(tG@}P_TU!ehI> Dܹ/ͻ88k2FzƬ,ss9K}m5?cTX٘xA}3q<^`%Y,f Տpx|I(Dû6lXo2yH23-!yhaK=ǴNQu:ƴCv MBԖQ~ŚPK MbMl pyfomod/__init__.pyPK ֬M_T pyfomod/base.pyPK ֬MR) ) / pyfomod/fomod.xsdPK ֬M9D pyfomod/parser.pyPK !L;U], ], N pyfomod-0.4.0.dist-info/LICENSEPK !H>*R Q pyfomod-0.4.0.dist-info/WHEELPK !H? u pyfomod-0.4.0.dist-info/METADATAPK !H Q pyfomod-0.4.0.dist-info/RECORDPK .