Skip to content

Commit

Permalink
Add docstrings
Browse files Browse the repository at this point in the history
Minor name changes
  • Loading branch information
mzfr authored and mzfr committed Mar 19, 2019
1 parent 8ab6f49 commit 0501426
Show file tree
Hide file tree
Showing 17 changed files with 117 additions and 40 deletions.
13 changes: 13 additions & 0 deletions kodi_addon_checker/addons/Addon.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@


class Addon():
"""Report all the dependencies of an addon
"""
def __init__(self, addon_xml: ET.Element):
super(Addon, self).__init__()
self.id = addon_xml.get('id')
Expand All @@ -21,9 +23,20 @@ def __init__(self, addon_xml: ET.Element):
self.dependencies.append(AddonDependency(dependency))

def __eq__(self, other):
"""Check if the addon and it version is equivalent or not.
This comparision is done between the version of in the main
repository and the version present in the addon.xml of the addon
"""
return self.id == other.id and self.version == other.version

def dependsOn(self, addonId):
"""Check if addon is dependent on any other addon.
Arguments:
addonId {str} -- Id of addon whose dependencies
are to be looked
"""
for dependency in self.dependencies:
if dependency.id == addonId:
return True
Expand Down
2 changes: 2 additions & 0 deletions kodi_addon_checker/addons/AddonDependency.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@


class AddonDependency():
"""Get the version of the current addon
"""
def __init__(self, import_xml: ET.Element):
super(AddonDependency, self).__init__()
self.id = import_xml.get('addon')
Expand Down
18 changes: 18 additions & 0 deletions kodi_addon_checker/addons/Repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@


class Repository():
"""Get information of all the addon under specific branch
"""
def __init__(self, version, path):
super(Repository, self).__init__()
self.version = version
Expand All @@ -29,18 +31,34 @@ def __init__(self, version, path):
self.addons.append(Addon(addon))

def __contains__(self, addonId):
"""Check if addon is present in the list or not
Arguments:
addonId {str} -- Id of addon that is to be looked for
"""
for addon in self.addons:
if addon.id == addonId:
return True
return False

def find(self, addonId):
"""If the addon exists in the list then return it
Arguments:
addonId {str} -- Id of addon that is to be looked for
"""
for addon in self.addons:
if addon.id == addonId:
return addon
return None

def rdepends(self, addonId):
"""Check if addon is dependent on any other addon.
Arguments:
addonId {str} -- Id of addon whose dependencies
are to be looked
"""
rdepends = []
for addon in self.addons:
if addon.dependsOn(addonId):
Expand Down
20 changes: 10 additions & 10 deletions kodi_addon_checker/check_dependencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from .record import INFORMATION, PROBLEM, WARNING, Record
from .report import Report

common_ignore_deps = ['xbmc.metadata.scraper.albums', 'xbmc.metadata.scraper.movies',
COMMON_IGNORE_DEPS = ['xbmc.metadata.scraper.albums', 'xbmc.metadata.scraper.movies',
'xbmc.metadata.scraper.musicvideos', 'xbmc.metadata.scraper.tvshows',
'xbmc.metadata.scraper.library', 'xbmc.ui.screensaver', 'xbmc.player.musicviz',
'xbmc.python.pluginsource', 'xbmc.python.script', 'xbmc.python.weather', 'xbmc.python.lyrics',
Expand All @@ -26,7 +26,7 @@
'kodi.resource.font', 'kodi.inputstream', 'kodi.vfs', 'kodi.imagedecoder', 'xbmc.addon',
'xbmc.gui', 'xbmc.json', 'xbmc.metadata', 'xbmc.python', 'script.module.pil']

extensions = {"kodi.gameclient": "kodi.binary.instance.game",
EXTENSIONS = {"kodi.gameclient": "kodi.binary.instance.game",
"xbmc.gui.skin": "xbmc.gui",
"kodi.vfs": "kodi.binary.instance.vfs",
"xbmc.metadata.scraper.albums": "xbmc.metadata",
Expand Down Expand Up @@ -145,15 +145,15 @@ def _get_ignore_list(branch_name):
"""

if branch_name == "leia":
common_ignore_deps.extend(["script.module.pycryptodome"])
return common_ignore_deps
COMMON_IGNORE_DEPS.extend(["script.module.pycryptodome"])
return COMMON_IGNORE_DEPS

elif branch_name == "krypton":
common_ignore_deps.extend(["inputstream.adaptive", "inputstream.rtmp"])
return common_ignore_deps
COMMON_IGNORE_DEPS.extend(["inputstream.adaptive", "inputstream.rtmp"])
return COMMON_IGNORE_DEPS

else:
return common_ignore_deps
return COMMON_IGNORE_DEPS


def _check_extensions(report: Report, parsed_xml, addon):
Expand All @@ -166,6 +166,6 @@ def _check_extensions(report: Report, parsed_xml, addon):

for extension in parsed_xml.findall("extension"):
point = extension.get("point")
if point in extensions and extensions[point] not in deps:
report.add(Record(PROBLEM, "{} dependency is required for {} extensions"
.format(extensions[point], point)))
if point in EXTENSIONS and EXTENSIONS[point] not in deps:
report.add(Record(PROBLEM, "{} dependency is required for {} extension"
.format(EXTENSIONS[point], point)))
4 changes: 2 additions & 2 deletions kodi_addon_checker/check_entrypoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,8 @@ def _number_of_lines(report: Report, filepath: str, library: str, max_entrypoint
report.add(Record(WARNING,
"Complex entry point. Check: %s | Counted lines: %d | Lines allowed: %d"
% (library, lineno, max_entrypoint_count)))
except SyntaxError as e:
if e.msg == 'SyntaxError at line: 1':
except SyntaxError as err:
if err.msg == 'SyntaxError at line: 1':
report.add(Record(PROBLEM,
("Error parsing file, is your file saved with UTF-8 encoding? "
"Make sure it has no BOM. Check: %s")
Expand Down
21 changes: 13 additions & 8 deletions kodi_addon_checker/check_py3_compatibility.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@


class KodiRefactoringTool(refactor.RefactoringTool):
"""Report possible refactoring error detected by lib2to3
Extends:
refactor.RefactoringTool
"""

def __init__(self, report, log_level, *args, **kwargs):
self.report = report
Expand Down Expand Up @@ -60,11 +65,11 @@ def check_py3_compatibility(report: Report, path: str, branch_name: str):

fixer_names = ['lib2to3.fixes.fix_' + fix for fix in list_of_fixes]

rt = KodiRefactoringTool(report, PROBLEM, fixer_names, options=None, explicit=None)
refactoring_tool = KodiRefactoringTool(report, PROBLEM, fixer_names, options=None, explicit=None)
try:
rt.refactor([path])
except pgen2.parse.ParseError as e:
report.add(Record(PROBLEM, "ParseError: {}".format(e)))
refactoring_tool.refactor([path])
except pgen2.parse.ParseError as err:
report.add(Record(PROBLEM, "ParseError: {}".format(err)))

if branch_name not in ['gotham', 'helix', 'isengard', 'jarvis']:
list_of_fixes = [
Expand All @@ -85,8 +90,8 @@ def check_py3_compatibility(report: Report, path: str, branch_name: str):

fixer_names = ['lib2to3.fixes.fix_' + fix for fix in list_of_fixes]

rt = KodiRefactoringTool(report, INFORMATION, fixer_names, options=None, explicit=None)
refactoring_tool = KodiRefactoringTool(report, INFORMATION, fixer_names, options=None, explicit=None)
try:
rt.refactor([path])
except pgen2.parse.ParseError as e:
report.add(Record(INFORMATION, "ParseError: {}".format(e)))
refactoring_tool.refactor([path])
except pgen2.parse.ParseError as err:
report.add(Record(INFORMATION, "ParseError: {}".format(err)))
4 changes: 2 additions & 2 deletions kodi_addon_checker/check_string.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,9 @@ def check_for_invalid_strings_po(report: Report, file_index: list):
for po_file in po_file_index:
full_path = os.path.join(po_file["path"], po_file["name"])

with open(full_path, "r", encoding="utf-8") as f:
with open(full_path, "r", encoding="utf-8") as file:
try:
contents = f.read()
contents = file.read()
except UnicodeDecodeError:
report_made = True
report.add(Record(PROBLEM, "Invalid PO file %s: File is not saved with UTF-8 encoding"
Expand Down
15 changes: 8 additions & 7 deletions kodi_addon_checker/check_url.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,14 @@ def check_url(report: Report, parsed_xml):
scheme = False

try:
r = requests.head(url, allow_redirects=True, timeout=5)
host = urllib3.util.parse_url(r.url).host
response = requests.head(url, allow_redirects=True, timeout=5)
host = urllib3.util.parse_url(response.url).host
if not scheme and not host.endswith(source.text):
report.add(Record(WARNING, "{} redirects to {}".format(source.text, host)))
elif scheme and r.url.rstrip('/') != url.rstrip('/'):
report.add(Record(WARNING, "{} redirects to {}".format(source.text, r.url)))
r.raise_for_status()
elif scheme and response.url.rstrip('/') != url.rstrip('/'):
report.add(Record(WARNING, "{} redirects to {}".format(source.text, response.url)))
response.raise_for_status()
except (requests.exceptions.ConnectionError, requests.exceptions.ConnectTimeout, requests.exceptions.HTTPError,
requests.exceptions.MissingSchema, requests.exceptions.ReadTimeout, requests.exceptions.SSLError) as e:
report.add(Record(WARNING, e))
requests.exceptions.MissingSchema, requests.exceptions.ReadTimeout, requests.exceptions.SSLError
) as err:
report.add(Record(WARNING, err))
8 changes: 4 additions & 4 deletions kodi_addon_checker/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,14 @@
REL_PATH = ""


def has_transparency(im):
def has_transparency(image):
"""Check the transparency(aplha layer) in the given image
:im: PIL.Image object
:image: PIL.Image object
"""
try:
if im.mode == "RGBA":
alpha = im.split()[-1]
if image.mode == "RGBA":
alpha = image.split()[-1]
listdata = list(alpha.getdata())
first_transparent_pixel = next(x[0]
for x in enumerate(listdata) if x[1] < 255)
Expand Down
8 changes: 8 additions & 0 deletions kodi_addon_checker/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ def __init__(self, repo_path, cmd_args=None):
self._load_config(repo_path)

def _load_config(self, repo_path):
"""Load the config file
Arguments:
repo_path {str} -- the repo path which contains .tests-config.json.
"""
if repo_path is None:
return
config_path = os.path.join(repo_path, '.tests-config.json')
Expand All @@ -37,6 +42,9 @@ def _load_config(self, repo_path):
self.configs = file_config

def is_enabled(self, value):
"""Check if the certain value in the
config file in enabled or not
"""
return self.configs.get(value, False)

def __getitem__(self, item):
Expand Down
2 changes: 2 additions & 0 deletions kodi_addon_checker/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@


class Logger:
"""Logger class the provokes the create_logger function.
"""

@staticmethod
def create_logger(debug_filename, logger_name):
Expand Down
5 changes: 5 additions & 0 deletions kodi_addon_checker/plugins/array_reporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@

@reporter(name="array", enabled=False)
class ArrayReporter(Reporter):
"""Setup array report for Reporter class
Extends:
Reporter
"""
def __init__(self):
self.reports = []

Expand Down
5 changes: 5 additions & 0 deletions kodi_addon_checker/plugins/log_reporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@

@reporter(name="log", enabled=False)
class LogReporter(Reporter):
"""Report logs to the log file
Extends:
Reporter
"""

def __init__(self):
log_file_name = os.path.join(os.getcwd(), "kodi-addon-checker-report.log")
Expand Down
3 changes: 2 additions & 1 deletion kodi_addon_checker/record.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,11 @@


class Record():
"""Create a record which is the low level entry in Report to represent logs.
"""
def __init__(self, log_level, message, start_line=-1, end_line=-1, start_char_position=-1,
end_char_position=-1):
"""
Create a record which is the low level entry in Report to represent logs.
:param log_level: "ERROR", "WARN" or "INFO"
:param message: the actual log message
:param start_line: for text files, provide the start line of issue
Expand Down
6 changes: 2 additions & 4 deletions kodi_addon_checker/report.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,9 @@


class Report():
"""Create a new report for the given artifact. The artifact can be a repo, add-on or file.
"""
def __init__(self, artifact_name):
"""
Create a new report for the given artifact. The artifact can be a repo, add-on or file.
:param artifact_name: the artifact name
"""
self.artifact_name = artifact_name
self.problem_count = 0
self.warning_count = 0
Expand Down
8 changes: 8 additions & 0 deletions kodi_addon_checker/reporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,14 @@ def report(self, report):


class ReportManager():
"""Manage all the reporters
"""
reporters = {}

@classmethod
def register(cls, reporter_clazz: Reporter, name, enabled):
"""Register the reporters
"""
cls.reporters[name] = [reporter_clazz(), enabled]

@classmethod
Expand All @@ -35,10 +39,14 @@ def enable(cls, names):

@classmethod
def getEnabledReporters(cls):
"""Get all the reporters that are enabled
"""
return [reporter[0] for reporter in cls.reporters.values() if reporter[1]]


def reporter(name, enabled=False):
"""Report all the enabled reporters to ReportManager
"""
def _reporter(clazz):
if inspect.isclass(clazz):
if not hasattr(clazz, "report") or len(inspect.signature(getattr(clazz, "report")).parameters.items()) != 2:
Expand Down
15 changes: 13 additions & 2 deletions kodi_addon_checker/schema_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,11 @@
LOGGER = logging.getLogger(__name__)


def schemas(report: Report, CONST_parsed_xml, branch_name):
def schemas(report: Report, const_parsed_xml, branch_name):
"""validates XML file with existing schemas
:parsed_xml: parsed data from an XML file
"""
parsed_xml = copy.copy(CONST_parsed_xml)
parsed_xml = copy.copy(const_parsed_xml)
failed, metadatacount, valid = _validation_checks(report, parsed_xml, branch_name)

root_schema = join(XML_SCHEMA, 'addon.xsd')
Expand Down Expand Up @@ -115,6 +115,17 @@ def _validate(xml, schemapath):


def check_version(branch_name, schema_file):
"""Check whether the schema files for the specific
branch exists or not
Arguments:
branch_name {str} -- Name of the branch the schema
is being validated of
schema_file {str} -- Schema file to look for.
Returns:
[str] -- full path to the schema file.
"""
all_branches = ['leia', 'krypton', 'jarvis', 'isengard', 'helix', 'gotham']
branches = all_branches[all_branches.index(branch_name)::1]
for branch in branches:
Expand Down

0 comments on commit 0501426

Please sign in to comment.