-
Notifications
You must be signed in to change notification settings - Fork 40
/
handle_files.py
87 lines (72 loc) · 3 KB
/
handle_files.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
"""
Copyright (C) 2017-2018 Team Kodi
This file is part of Kodi - kodi.tv
SPDX-License-Identifier: GPL-3.0-only
See LICENSES/README.md for more information.
"""
import os
import pathlib
import re
from .common import relative_path
from .record import PROBLEM, Record
from .report import Report
def find_file(name: str, path: str):
"""Looks for a file in a given path.
:name: name of the file to look for
:path: path of the directory.
:return: full path for the file.
"""
for file_name in os.listdir(path):
match = re.match(name, file_name, re.IGNORECASE)
if match is not None:
return os.path.join(path, match.string)
return None
def find_files_recursive(name: str, path: str):
"""This looks for a file but only returns the first occurrence
:name: name of the file to look for
:path: path of directory to look for the file
"""
for root, _, files in os.walk(path):
for file in files:
if name in file:
yield os.path.join(root, file)
def create_file_index(path: str):
"""Creates a list having multiple dictionaries in following format:
[{'name':<file_name>, 'path': '<path_to_file>'}]
:path: path for the directory
"""
file_index = []
for root, folders, files in os.walk(path, topdown=True):
if ".git" in folders:
folders.remove(".git")
for file_name in files:
file_index.append({"path": root, "name": file_name})
return file_index
def find_in_file(path: str, search_terms: list, whitelisted_file_types: list):
"""Finds for particular terms in whitelisted file type i.e .py or .xml
:path: path of a directory
:search_term: list of all the terms to be searched
:whitelisted_file_type: list of all the whitelisted file types
"""
results = []
if search_terms:
for directory in os.walk(path):
for file_name in directory[2]:
if pathlib.Path(file_name).suffix in whitelisted_file_types or not whitelisted_file_types:
file_path = os.path.join(directory[0], file_name)
with open(file_path, "r", encoding="utf8") as searchfile:
linenumber = 0
for line in searchfile:
linenumber = linenumber + 1
for term in search_terms:
if term in line:
results.append({"term": term, "line": line.strip(
), "searchfile": file_path, "linenumber": linenumber})
return results
def addon_file_exists(report: Report, addon_path: str, file_name: str):
"""check whether addon file exists or not
:addon_path: path to the addon
:file_name: name of the addon file
"""
if find_file(file_name, addon_path) is None:
report.add(Record(PROBLEM, f"Not found {file_name} in folder {relative_path(addon_path)}"))