ircthing/ircthing_utils.py
2024-02-11 09:05:43 +02:00

106 lines
3.0 KiB
Python

"""
ircthing_utils
Some functions that make life nicer.
"""
import configparser
import argparse
import os
import sys
from typing import Union, List, Tuple
def base_path() -> str:
"""
Returns location that the script will use as root for its dir structure
Returns:
str: path for run time files
"""
my_name = sys.argv[0]
my_name_pyless, _ = os.path.splitext(my_name)
return f"/tmp/{my_name_pyless}"
def cli_args() -> Union[str, None]:
"""
Parse arguments and provide small usage message
Returns:
str or None: path to config file
"""
parser = argparse.ArgumentParser(
description="Usage: python3.11 ircthing.py /myconfig.ini"
)
parser.add_argument("config", help="Path to the configuration file.")
args = parser.parse_args()
if args.config:
return args.config
return None
def read_config(config_path: str) -> List[dict]:
"""
Read configuration file and return list of dicts.
Dictionaries hold information about irc networks/server to connecto to.
args:
str: Path to the configuration file.
Returns:
list[{}, {}]: List of dictionaries.
"""
config = configparser.ConfigParser()
config.read(config_path)
network_configs = []
try:
# Collect information from each topic / network
for topic in config.sections():
network = config[topic]
server = network.get("server")
port = network.getint("port")
channels = network.get("channels", fallback=None)
nickname = network.get("nickname")
password = network.get("password", fallback=None)
network_config = {
"net_name": network.name,
"server": server,
"port": port,
"channels": channels,
"nickname": nickname,
"password": password,
}
network_configs.append(network_config)
return network_configs
except Exception as config_read_error:
print(f"Failure while reading configuration file. {config_read_error}")
sys.exit(1)
def make_files(path: str, net_name: str) -> Tuple[List[str], str]:
"""
Make directories and fifo files need to make irc server connection.
Args:
str: The root path for run time files.
str: The network name of the irc server we are joining
Returns:
list: List containing the fio files created.
str: Path to the directory created for the network connection.
"""
os.makedirs(path, exist_ok=True)
server_dir = os.path.join(path, net_name)
os.makedirs(server_dir, exist_ok=True)
try:
os.mkfifo(f"{server_dir}/in")
except FileExistsError:
pass
try:
os.mkfifo(f"{server_dir}/out")
except FileExistsError:
pass
fifo_files = []
fifo_files.append(f"{server_dir}/in")
fifo_files.append(f"{server_dir}/out")
return fifo_files, server_dir