Skip to content
This repository has been archived by the owner on Aug 19, 2022. It is now read-only.

CLI as a module #1

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .deepsource.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
version = 1

[[analyzers]]
name = "python"
enabled = true

[analyzers.meta]
runtime_version = "3.x.x"
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -145,5 +145,5 @@ cython_debug/


# APX

servers.json
fb8396d910253f82aa01c909b3705493782c4ab2.json
Empty file added __init__.py
Empty file.
90 changes: 58 additions & 32 deletions apx.py
Original file line number Diff line number Diff line change
@@ -1,32 +1,58 @@
from os.path import isfile
from json import load
from os import getcwd
from sys import path, argv

path.append(getcwd())
from args import parser
from commands.commands import SHELL_COMMANDS, CommandFailedException

SERVER_DATA = []

if not isfile("servers.json"):
raise FileNotFoundError("Server config not existing")

with open("servers.json", "r") as read_file:
SERVER_DATA = load(read_file)

parsed_args = parser.parse_args()
if parsed_args.cmd is None:
raise Exception("No cmd given")

for server in parsed_args.server:
config = parsed_args.config
env = {"server_data": SERVER_DATA, "server": None, "server_config": None}
env["server"] = server
if config is not None:
env["server_config"] = config
if parsed_args.cmd not in SHELL_COMMANDS:
raise Exception(f"command {parsed_args.cmd} not found")
result = SHELL_COMMANDS[parsed_args.cmd](env, parsed_args.args)
if not result:
raise Exception(f"Command failed: {argv}")
import logging
from os import path
from sys import argv


if __package__ is None or __package__ == '':
from args import parser
from helpers import get_servers_data
from commands.router import SHELL_COMMANDS
else:
from cli.args import parser
from cli.helpers import get_servers_data
from cli.commands.router import SHELL_COMMANDS


ROOT_PATH = path.dirname(path.realpath(__file__))

logging.basicConfig(filename=path.join(ROOT_PATH, "cli.log"),
encoding='utf-8', level=logging.DEBUG, format='%(asctime)s %(message)s')


def get_args():
parsed_args = parser.parse_args()
if parsed_args.cmd is None:
logging.error("No cmd given")
raise Exception("No cmd given")
return parsed_args


if __name__ == "__main__":

server_data = get_servers_data()
parsed_args = get_args()

env_tpl = {"server_data": server_data,
"server": None, "server_config": None}

for server in parsed_args.server:
config = parsed_args.config

env = env_tpl.copy()
env["server"] = server

if config is not None:
env["server_config"] = config

if parsed_args.cmd not in SHELL_COMMANDS:
raise Exception(f"command {parsed_args.cmd} not found")

cli_command = SHELL_COMMANDS[parsed_args.cmd]

logging.info(
f'Running command "{parsed_args.cmd}" env={env} args={parsed_args.args}')
result = cli_command(env, parsed_args.args)

if not result:
raise Exception(
f"Command failed: {parsed_args.cmd} {argv} result: {result}")
29 changes: 0 additions & 29 deletions commands/__init__.py
Original file line number Diff line number Diff line change
@@ -1,29 +0,0 @@
from typing import Union
from requests import post


def http_api_helper(env: dict, route: str, data: dict, method=post) -> Union[bool, str]:
if "server_data" not in env or env["server"] not in env["server_data"]:
raise Exception("Server.json invalid")
result_ok = False
result_text = None
secret = env["server_data"][env["server"]]["secret"]
url = env["server_data"][env["server"]]["url"]
try:
got = method(
url + f"/{route}",
headers={
"authorization": secret,
"content-type": "application/x-www-form-urlencoded",
},
data=data,
)

result_ok = got.status_code == 200
result_text = got.text
except Exception as err:
print(result_text)
result_ok = False
result_text = str(err)

return result_ok, result_text
36 changes: 20 additions & 16 deletions commands/build.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
from requests import post, get
from os.path import exists, join
from os import listdir, mkdir, unlink
from json import load, loads
from os import listdir
from json import load
import re
from shutil import copyfile, rmtree
import tarfile
from commands import http_api_helper
import io
import zipfile
from .util import http_api_helper
import logging

logger = logging.getLogger(__name__)


team_pattern = r"(?P<name>.+)\s?#(?P<number>.+)\:(?P<pitgroup>\d+)"

Expand Down Expand Up @@ -51,7 +54,7 @@ def get_final_filename(needle: str, short_name: str, number: str) -> str:

def build_track_command(env, *args, **kwargs):
if not env["server"]:
print("no server set")
logger.info("no server set")
else:
server_key = env["server"]
server_data = env["server_data"][server_key]
Expand Down Expand Up @@ -96,15 +99,15 @@ def build_track_command(env, *args, **kwargs):

def build_skin_command(env, *args, **kwargs):
if not env["server"]:
print("no server set")
logger.info("no server set")
else:
server_key = env["server"]
server_data = env["server_data"][server_key]
url = server_data["url"]
secret = server_data["secret"]
file_name = args[0][0]
if not exists(file_name):
print("file not existing")
logger.info(f"file not exists: {file_name}")
else:

# read templates
Expand All @@ -117,6 +120,7 @@ def build_skin_command(env, *args, **kwargs):
if file.endswith(".veh"):
with open(join(templates_path, file)) as file_handle:
templates[file.replace(".veh", "")] = file_handle.read()
logger.info(f"Opening file: {file_name}")
with open(file_name, "r") as file:
data = load(file)
veh_mods = data["cars"]
Expand All @@ -140,12 +144,12 @@ def build_skin_command(env, *args, **kwargs):
tar.add(
join(build_path, mod_name, raw_file), raw_file
)
print(f"Adding {raw_file} to archive")
logger.info(f"Adding {raw_file} to archive")
if ".png" in raw_file:
tar.add(
join(build_path, mod_name, raw_file), raw_file
)
print(f"Adding {raw_file} to archive")
logger.info(f"Adding {raw_file} to archive")
for entry in entries:
match = re.match(team_pattern, entry)
name = match.group("name").strip()
Expand All @@ -164,7 +168,7 @@ def build_skin_command(env, *args, **kwargs):
else None
)
if overwrites:
print(
logger.info(
"Found overwrites for VEH template for entry {}".format(
number
)
Expand All @@ -188,7 +192,7 @@ def build_skin_command(env, *args, **kwargs):
if not use_quotes
else '"{}"'.format(value),
)
print(
logger.info(
"Using value {} (in quotes: {}) for key {} of entry {}".format(
value,
use_quotes,
Expand Down Expand Up @@ -230,10 +234,10 @@ def build_skin_command(env, *args, **kwargs):
final_name = skin_file
had_custom_file = True
tar.add(path, final_name)
print(f"Adding {final_name} to archive")
logger.info(f"Adding {final_name} to archive")

if had_custom_file and mod_name in templates:
print(f"Adding generated {info.name} to archive")
logger.info(f"Adding generated {info.name} to archive")
tar.addfile(info, io.BytesIO(tar_template))

got = post(
Expand All @@ -247,13 +251,13 @@ def build_skin_command(env, *args, **kwargs):

def query_config(env, *args, **kwargs):
got, text = http_api_helper(env, "config", {}, get)
print(text)
logger.info(text)
return got


def get_config_command(env, *args, **kwargs) -> bool:
got = query_config(env, args, kwargs)
print(got)
logger.info(got)
return True


Expand All @@ -266,5 +270,5 @@ def get_ports_command(env, *args, **kwargs) -> bool:
"TCP": [simulation_port, http_port, reciever_port],
"UDP": [simulation_port, http_port + 1, http_port + 2],
}
print(ports)
logger.info(ports)
return True
15 changes: 9 additions & 6 deletions commands/chat.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
from commands import http_api_helper
from .util import http_api_helper
import logging

logger = logging.getLogger(__name__)


def chat_command(env, *args, **kwargs) -> bool:
got, text = http_api_helper(env, "chat", {
"message": ' '.join(args[0])
})
print(text)
logger.info(text)
return got


Expand All @@ -16,7 +19,7 @@ def kick_command(env, *args, **kwargs) -> bool:
got, text = http_api_helper(env, "kick", {
"driver": driver
})
print(text)
logger.info(text)
return got


Expand All @@ -27,14 +30,14 @@ def rejoin_driver_command(env, *args, **kwargs) -> bool:
got_undq, undq_text = http_api_helper(env, "chat", {
"message": "/undq " + ' '.join(args[0])
})
print(dq_text)
print(undq_text)
logger.info(dq_text)
logger.info(undq_text)
return got_dq and got_undq


def action_helper(env, action: str):
got, text = http_api_helper(env, "/action/" + action, {})
print(text)
logger.info(text)
return got


Expand Down
Loading