Skip to content

Commit 009ac83

Browse files
committed
refactor: follow pep8 function naming
1 parent f88b858 commit 009ac83

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

49 files changed

+370
-378
lines changed

docs/src/dev/index.md

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -24,14 +24,8 @@ The principle is to **Keep this project simple and maintainable**:
2424
## Naming convention
2525
**Python**
2626

27-
Alough [PEP-8](https://peps.python.org/pep-0008/#function-and-variable-names) suggests use `lower_case_with_underscores` for methods and functions...
28-
29-
By my personal preference, I use the following naming rules:
30-
- `snake_case` (Lowercase / Lower case with underscore) for variables, properties
31-
- `lowerCamelCase` (Mixed case) for functions, methods
32-
- `UpperCamelCase` (Pascal case) for classes
33-
34-
**Please follow this style if you are working on this repository**, these naming makes it very clear to distinguish between different types of code.
27+
Follow [PEP-8](https://peps.python.org/pep-0008/#function-and-variable-names) for python code style.
28+
Use `snake_case` for command line arguments.
3529

3630
**Javascript**
3731

lires/cmd/cluster.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ class ClusterConfigT(TypedDict):
2525
allowed_entries = ['log', 'ai', 'feed', 'server']
2626
exec_order = allowed_entries
2727

28-
def __getDefaultConfig()->ClusterConfigT:
28+
def __default_config()->ClusterConfigT:
2929
ssl_certfile = os.environ.get("LRS_SSL_CERTFILE", "")
3030
ssl_keyfile = os.environ.get("LRS_SSL_KEYFILE", "")
3131
return {
@@ -60,8 +60,8 @@ def __getDefaultConfig()->ClusterConfigT:
6060
]
6161
}
6262

63-
def generateConfigFile(path:str):
64-
config = __getDefaultConfig()
63+
def generate_config_file(path:str):
64+
config = __default_config()
6565

6666
# use yaml
6767
with open(path, "w") as f:
@@ -97,7 +97,7 @@ def generateConfigFile(path:str):
9797
with open(path, "w") as f:
9898
f.write("# " + "\n# ".join(comments) + "\n" + content)
9999

100-
def loadConfigFile(path:str)->ClusterConfigT:
100+
def load_config_file(path:str)->ClusterConfigT:
101101
with open(path, "r") as f:
102102
config: ClusterConfigT = yaml.safe_load(f)
103103

@@ -137,7 +137,7 @@ def cprint(*args):
137137
print(BCOLORS.LIGHTMAGENTA + "[cluster] " + " ".join(map(str, args)) + BCOLORS.ENDC)
138138

139139
## Multi-processes
140-
def initProcesses(config: ClusterConfigT):
140+
def init_processes(config: ClusterConfigT):
141141
""" Execute the config file """
142142
ps: list[subprocess.Popen] = []
143143
g_env = os.environ.copy()
@@ -190,15 +190,15 @@ def main():
190190
if os.path.exists(args.path) and not args.overwrite:
191191
cprint("Config file already exists, use --overwrite to overwrite")
192192
exit(1)
193-
generateConfigFile(args.path)
193+
generate_config_file(args.path)
194194
exit(0)
195195

196196
if args.overwrite and not args.generate:
197197
cprint("--overwrite can only be used with --generate")
198198
exit(1)
199199

200200
if not os.path.exists(args.path) and args.init_if_not_exist:
201-
generateConfigFile(args.path)
201+
generate_config_file(args.path)
202202

203203
if not os.path.exists(args.path):
204204
cprint("Config file does not exist, use --generate to generate one")
@@ -220,11 +220,11 @@ def main():
220220
time.sleep(0.1)
221221

222222
## Start servers -------------------------------
223-
config = loadConfigFile(args.path)
224-
procs = initProcesses(config)
223+
config = load_config_file(args.path)
224+
procs = init_processes(config)
225225

226226
# handle SIGINT
227-
def sigintHandler(sig, frame):
227+
def sigint_handler(sig, frame):
228228
print("") # print a newline
229229
cprint("{} received, terminating...".format(signal.Signals(sig).name))
230230

@@ -242,8 +242,8 @@ def sigintHandler(sig, frame):
242242
cprint("All processes terminated, exit.")
243243
exit(0)
244244

245-
signal.signal(signal.SIGINT, sigintHandler)
246-
signal.signal(signal.SIGTERM, sigintHandler)
245+
signal.signal(signal.SIGINT, sigint_handler)
246+
signal.signal(signal.SIGTERM, sigint_handler)
247247

248248
while True:
249249
time.sleep(1)

lires/cmd/config.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from ..config import generateDefaultConf, CONF_FILE_PATH
1+
from ..config import generate_default_conf, CONF_FILE_PATH
22
import argparse, json
33

44
def run():
@@ -13,7 +13,7 @@ def run():
1313

1414
args = parser.parse_args()
1515
if args.subparser == "reset":
16-
generateDefaultConf(args.group)
16+
generate_default_conf(args.group)
1717

1818
elif args.subparser == "show":
1919
print("Configuration file: ", CONF_FILE_PATH)

lires/cmd/index.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
from lires.api import IServerConn
88
from lires.loader import init_resources
99

10-
def parseArgs() -> argparse.Namespace:
10+
def parse_arguments() -> argparse.Namespace:
1111
parser = argparse.ArgumentParser(description="Build search index for the database")
1212
parser.add_argument("user", action="store", type=str, help="user name")
1313
subparsers = parser.add_subparsers(dest="subparser", help="sub-command help")
@@ -82,7 +82,7 @@ async def entry(args):
8282

8383
def main():
8484
import asyncio
85-
args = parseArgs()
85+
args = parse_arguments()
8686
asyncio.run(entry(args))
8787

8888
if __name__ == "__main__":

lires/cmd/log.py

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -22,15 +22,15 @@ def __init__(self, db_file: str) -> None:
2222
self.conn = sqlite3.connect(db_file)
2323
self.cur = self.conn.cursor()
2424

25-
def getTableNames(self) -> list[str]:
25+
def get_table_names(self) -> list[str]:
2626
self.cur.execute("SELECT name FROM sqlite_master WHERE type='table';")
2727
return [x[0] for x in self.cur.fetchall()]
2828

29-
def hasTable(self, table_name: str) -> bool:
29+
def has_table(self, table_name: str) -> bool:
3030
self.cur.execute(f"SELECT name FROM sqlite_master WHERE type='table' AND name='{table_name}';")
3131
return len(self.cur.fetchall()) > 0
3232

33-
def getMessagesFromTable(
33+
def get_messages_from(
3434
self,
3535
table_name: str,
3636
level_name: Optional[str] = None,
@@ -41,7 +41,7 @@ def getMessagesFromTable(
4141
self.cur.execute(f"SELECT * FROM {table_name} WHERE level_name='{level_name}' ORDER BY time DESC LIMIT {limit}")
4242
return self.cur.fetchall()
4343

44-
def getCountFromTable(
44+
def get_count_from(
4545
self,
4646
table_name: str,
4747
level_name: Optional[str] = None) -> int:
@@ -58,16 +58,16 @@ def getCountFromTable(
5858
"ERROR": BCOLORS.FAIL,
5959
"CRITICAL": BCOLORS.FAIL,
6060
}
61-
def formatLine(line: tuple) -> str:
61+
def format_line(line: tuple) -> str:
6262
time = line[1]
6363
level_name = line[3]
6464
message = line[4]
6565
return f"{BCOLORS.OKCYAN}{time}{BCOLORS.ENDC} {__color_level[level_name]}{level_name}{BCOLORS.ENDC}: {message}"
66-
def formatLines(lines: list[tuple]) -> Generator[str, None, None]:
66+
def format_lines(lines: list[tuple]) -> Generator[str, None, None]:
6767
for i in range(0, len(lines)):
68-
yield formatLine(lines[i])
68+
yield format_line(lines[i])
6969

70-
def sortLines(lines: list[tuple]) -> list[tuple]:
70+
def sort_lines(lines: list[tuple]) -> list[tuple]:
7171
# in the order of time
7272
return sorted(lines, key=lambda x: x[0], reverse=False)
7373

@@ -102,17 +102,17 @@ def main():
102102
parser.print_help()
103103
return
104104

105-
def getAllTableNames(files) -> list[str]:
105+
def get_all_table_names(files) -> list[str]:
106106
__all_table_names = []
107107
for file in files:
108108
reader = LogDBReader(file)
109-
__all_table_names.extend(reader.getTableNames())
109+
__all_table_names.extend(reader.get_table_names())
110110
return sorted(list(set(__all_table_names)))
111111

112112
if args.subparser_name == 'view':
113113
__all_lines = []
114114
table_name = args.table
115-
__all_table_names = getAllTableNames(args.files)
115+
__all_table_names = get_all_table_names(args.files)
116116
if table_name is None or table_name == "":
117117
for idx, table_name in enumerate(__all_table_names):
118118
print(f"[{idx}] {table_name}")
@@ -143,13 +143,13 @@ def getAllTableNames(files) -> list[str]:
143143

144144
for file in args.files:
145145
reader = LogDBReader(file)
146-
if not reader.hasTable(table_name):
146+
if not reader.has_table(table_name):
147147
continue
148-
lines = reader.getMessagesFromTable(table_name, args.level, limit=args.limit)
148+
lines = reader.get_messages_from(table_name, args.level, limit=args.limit)
149149
__all_lines.extend(lines)
150-
__all_lines = sortLines(__all_lines)
150+
__all_lines = sort_lines(__all_lines)
151151
try:
152-
for line in formatLines(__all_lines):
152+
for line in format_lines(__all_lines):
153153
print(line)
154154
print('\n'+'-' * 80)
155155
print(f"Total {len(__all_lines)} lines, from table {table_name}")
@@ -164,14 +164,14 @@ def getAllTableNames(files) -> list[str]:
164164

165165
elif args.subparser_name == 'check':
166166
# get size of each table
167-
all_tables = getAllTableNames(args.files)
167+
all_tables = get_all_table_names(args.files)
168168
count = {}
169169
for file in args.files:
170170
reader = LogDBReader(file)
171171
for table_name in all_tables:
172-
if not reader.hasTable(table_name):
172+
if not reader.has_table(table_name):
173173
continue
174-
lines = reader.getCountFromTable(table_name, level_name=args.level)
174+
lines = reader.get_count_from(table_name, level_name=args.level)
175175
count[table_name] = count.setdefault(table_name, 0) + lines
176176
# print
177177
max_len = max([len(x) for x in all_tables])
@@ -191,8 +191,8 @@ async def ensureNotLogging():
191191
from lires.core.error import LiresError
192192
from lires.utils import BCOLORS
193193
from lires.api import RegistryConn
194-
from lires.config import getConf
195-
group_id = getConf()['group']
194+
from lires.config import get_conf
195+
group_id = get_conf()['group']
196196
rconn = RegistryConn()
197197
try:
198198
log_service = await rconn.get('log', group_id)
@@ -211,7 +211,7 @@ def unifyPath(path: str) -> str:
211211
if unifyPath(all_files[i]) == unifyPath(args.output):
212212
all_files.pop(i)
213213
break
214-
all_tables = getAllTableNames(all_files)
214+
all_tables = get_all_table_names(all_files)
215215
conn = sqlite3.connect(args.output)
216216
cur = conn.cursor()
217217

@@ -232,9 +232,9 @@ def unifyPath(path: str) -> str:
232232
sql_create = sql_create[:-2] + ")"
233233
cur.execute(sql_create)
234234

235-
if not reader.hasTable(table_name):
235+
if not reader.has_table(table_name):
236236
continue
237-
lines = reader.getMessagesFromTable(table_name)
237+
lines = reader.get_messages_from(table_name)
238238
for line in lines:
239239
cur.execute(f"INSERT INTO {table_name} VALUES (?,?,?,?,?)", line)
240240
conn.commit()

lires/cmd/userManage.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ async def _run():
4545
parser_list.add_argument('-r', "--reverse", help = "Reverse order", action="store_true")
4646
parser_list.add_argument('--ascii', help = "Only print ascii characters, work only with table", action="store_true")
4747

48-
def parseStorage(s: str) -> int:
48+
def parse_storage(s: str) -> int:
4949
assert s[:-1].isdigit(), "Invalid storage size"
5050
assert s[-1].lower() in ["m", "g", "t"], "Invalid storage unit"
5151
if s[-1].lower() == "m":
@@ -66,7 +66,7 @@ def parseStorage(s: str) -> int:
6666
await user_db_conn.insert_user(
6767
username=args.username, password=generate_hex_hash(args.password), name=args.name,
6868
is_admin=args.admin, mandatory_tags=DataTags(args.tags).to_ordered_list(),
69-
max_storage=parseStorage(args.max_storage) if args.max_storage is not None else None
69+
max_storage=parse_storage(args.max_storage) if args.max_storage is not None else None
7070
)
7171

7272
elif args.subparser == "update":
@@ -81,7 +81,7 @@ def parseStorage(s: str) -> int:
8181
if args.admin is not None:
8282
await user_db_conn.update_user(user_id, is_admin=args.admin)
8383
if args.max_storage is not None:
84-
await user_db_conn.update_user(user_id, max_storage=parseStorage(args.max_storage))
84+
await user_db_conn.update_user(user_id, max_storage=parse_storage(args.max_storage))
8585

8686
elif args.subparser == "delete":
8787
assert args.username is not None or args.id is not None, "Username or id is required"

lires/config.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -56,28 +56,28 @@
5656
# the new fields will be added on top of the old config file on getConf()
5757
import uuid
5858
import platform
59-
def __staticConfigToken(prefix = uuid.NAMESPACE_DNS):
59+
def __static_config_token(prefix = uuid.NAMESPACE_DNS):
6060
# Create a static token for the configuration file,
6161
# based on the $LRS_HOME directory and node id
6262
return uuid.uuid5(prefix, platform.node() + LRS_HOME).hex
6363
__default_config: LiresConfT = {
64-
'group': __staticConfigToken(uuid.NAMESPACE_DNS)[:8],
64+
'group': __static_config_token(uuid.NAMESPACE_DNS)[:8],
6565
'max_users': 1000,
6666
'default_user_max_storage': '512m',
6767
'service_port_range': [21000, 22000],
6868
'allow_public_query': True,
6969
}
7070
__essential_config_keys = [] # keys that must be in the configuration file
7171
__g_config: Optional[LiresConfT] = None # buffer
72-
def getConf() -> LiresConfT:
72+
def get_conf() -> LiresConfT:
7373
global __g_config, CONF_FILE_PATH
7474
if __g_config is None:
7575
with open(CONF_FILE_PATH, "r", encoding="utf-8") as conf_file:
7676
read_conf = json.load(conf_file)
7777

7878
# compare the keys and value types recursively
7979
# TODO: may be replaced by a more elegant solution
80-
def compareObject(d1, d2):
80+
def compare_object(d1, d2):
8181
if not type(d1) == type(d2):
8282
__logger.debug(f"Type mismatch: {type(d1)} != {type(d2)}")
8383
return False
@@ -91,14 +91,14 @@ def compareObject(d1, d2):
9191
__logger.debug(f"Key mismatch: {d1.keys()} != {d2.keys()}")
9292
return False
9393
for k in d1:
94-
if not compareObject(d1[k], d2[k]):
94+
if not compare_object(d1[k], d2[k]):
9595
return False
9696
return True
9797
# check if the essential keys are in the configuration file
9898
if not all([k in read_conf for k in __essential_config_keys]):
9999
raise KeyError(f"Essential keys ({__essential_config_keys}) are missing in the configuration file")
100100
# warn if the configuration file is outdated
101-
if not compareObject(read_conf, __default_config):
101+
if not compare_object(read_conf, __default_config):
102102
__logger.warn("Configuration file outdated, "
103103
"default configuration will be used as fallback, if errors occur, "
104104
"please run `lrs-config reset` to update the configuration file")
@@ -121,7 +121,7 @@ def compareObject(d1, d2):
121121
# To not repeatedly reading/parsing configuration file
122122
return __g_config
123123

124-
def saveToConf(**kwargs):
124+
def save_conf(**kwargs):
125125
global __g_config
126126
try:
127127
with open(CONF_FILE_PATH, "r", encoding="utf-8") as conf_file:
@@ -137,7 +137,7 @@ def saveToConf(**kwargs):
137137
# So that next time the configuration will be read from file by getConf
138138
__g_config = None
139139

140-
def generateDefaultConf(group: Optional[str] = None):
140+
def generate_default_conf(group: Optional[str] = None):
141141
"""
142142
Generate default configuration file at CONF_FILE_PATH
143143
"""

0 commit comments

Comments
 (0)