Skip to content

Commit

Permalink
Repostats action only on main repo, sys.exit(), ConfiguratorIO error …
Browse files Browse the repository at this point in the history
…handling, utf-8 configuration file (#93)

* Repostats action only on main repo

* Use sys.exit() everywhere

* Error handling in ConfiguratorIO
  • Loading branch information
infeeeee authored Jan 12, 2024
1 parent f3ce160 commit 650e2f4
Show file tree
Hide file tree
Showing 5 changed files with 57 additions and 37 deletions.
1 change: 1 addition & 0 deletions .github/workflows/repostats.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ on:
jobs:
j1:
name: repostats-for-nice-project
if: github.repository == 'richibrics/IoTuring'
runs-on: ubuntu-latest
steps:
- name: run-ghrs
Expand Down
3 changes: 2 additions & 1 deletion IoTuring/Configurator/Configurator.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import os
import subprocess
import shutil
import sys

from IoTuring.Logger.LogObject import LogObject
from IoTuring.Exceptions.Exceptions import UserCancelledException
Expand Down Expand Up @@ -180,7 +181,7 @@ def DisplayHelp(self) -> None:
def Quit(self) -> None:
""" Save configurations and quit """
self.WriteConfigurations()
exit(0)
sys.exit(0)

def LoadConfigurations(self) -> dict:
""" Reads the configuration file and returns configuration dictionary.
Expand Down
67 changes: 41 additions & 26 deletions IoTuring/Configurator/ConfiguratorIO.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import json
from pathlib import Path
import inspect
import sys

from IoTuring.Logger.LogObject import LogObject
from IoTuring.MyApp.App import App # App name
Expand Down Expand Up @@ -30,24 +31,34 @@ def readConfigurations(self):
""" Returns configurations dictionary. If does not exist the file where it should be stored, return None. """
config = None
try:
with open(self.getFilePath(), "r") as f:
with open(self.getFilePath(), "r", encoding="utf-8") as f:
config = json.loads(f.read())
self.Log(self.LOG_MESSAGE, f"Loaded \"{self.getFilePath()}\"")
except:
except FileNotFoundError:
self.Log(self.LOG_WARNING, f"It seems you don't have a configuration yet. Use configuration mode (-c) to enable your favourite entities and warehouses.\
\nConfigurations will be saved in \"{str(self.getFolderPath())}\"")
except Exception as e:
self.Log(self.LOG_ERROR, f"Error opening configuration file: {str(e)}")
sys.exit(str(e))
return config

def writeConfigurations(self, data):
""" Writes configuration data in its file """
self.createFolderPathIfDoesNotExist()
with open(self.getFilePath(), "w") as f:
f.write(json.dumps(data, indent=4))
self.Log(self.LOG_MESSAGE, f"Saved \"{str(self.getFilePath())}\"")
try:
self.createFolderPathIfDoesNotExist()
with open(self.getFilePath(), "w", encoding="utf-8") as f:
f.write(json.dumps(data, indent=4, ensure_ascii=False))
self.Log(self.LOG_MESSAGE, f"Saved \"{str(self.getFilePath())}\"")
except Exception as e:
self.Log(self.LOG_ERROR, f"Error saving configuration file: {str(e)}")
sys.exit(str(e))

def checkConfigurationFileExists(self) -> bool:
""" Returns True if the configuration file exists in the correct folder, False otherwise. """
return self.getFilePath().exists() and self.getFilePath().is_file()
try:
return self.getFilePath().exists() and self.getFilePath().is_file()
except:
return False

def getFilePath(self) -> Path:
""" Returns the path to the configurations file. """
Expand All @@ -56,7 +67,7 @@ def getFilePath(self) -> Path:
def createFolderPathIfDoesNotExist(self):
""" Check if file exists, if not check if path exists: if not create both folder and file otherwise just the file """
if not self.getFolderPath().exists():
self.getFolderPath().mkdir()
self.getFolderPath().mkdir(parents=True)

def getFolderPath(self) -> Path:
""" Returns the path to the configurations file. If the directory where the file
Expand Down Expand Up @@ -135,22 +146,26 @@ def manageOldConfig(self, moveFile: bool) -> None:
moveFile (bool): True: move the file. False: Create dontmove file
"""

if moveFile:
# create folder if not exists
self.createFolderPathIfDoesNotExist()
# copy file from old to new location
self.oldFolderPath().joinpath(CONFIGURATION_FILE_NAME).rename(self.getFilePath())
self.Log(self.LOG_MESSAGE,
f"Copied to \"{str(self.getFilePath())}\"")
else:
# create dont move file
with open(self.oldFolderPath().joinpath(DONT_MOVE_FILE_FILENAME), "w") as f:
f.write(" ".join([
"This file is here to remember you that you don't want to move the configuration file into the new location.",
"If you want to move it, delete this file and run the script in -c mode."
try:
if moveFile:
# create folder if not exists
self.createFolderPathIfDoesNotExist()
# copy file from old to new location
self.oldFolderPath().joinpath(CONFIGURATION_FILE_NAME).rename(self.getFilePath())
self.Log(self.LOG_MESSAGE,
f"Copied to \"{str(self.getFilePath())}\"")
else:
# create dont move file
with open(self.oldFolderPath().joinpath(DONT_MOVE_FILE_FILENAME), "w") as f:
f.write(" ".join([
"This file is here to remember you that you don't want to move the configuration file into the new location.",
"If you want to move it, delete this file and run the script in -c mode."
]))
self.Log(self.LOG_MESSAGE, " ".join([
"You won't be asked again. A new blank configuration will be used;",
f"if you want to move the existing configuration file, delete \"{self.oldFolderPath().joinpath(DONT_MOVE_FILE_FILENAME)}",
"and run the script in -c mode."
]))
self.Log(self.LOG_MESSAGE, " ".join([
"You won't be asked again. A new blank configuration will be used;",
f"if you want to move the existing configuration file, delete \"{self.oldFolderPath().joinpath(DONT_MOVE_FILE_FILENAME)}",
"and run the script in -c mode."
]))
except Exception as e:
self.Log(self.LOG_ERROR, f"Error saving file: {str(e)}")
sys.exit(str(e))
6 changes: 4 additions & 2 deletions IoTuring/Configurator/ConfiguratorLoader.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from __future__ import annotations
import sys

from IoTuring.Entity.Entity import Entity
from IoTuring.Logger.LogObject import LogObject
from IoTuring.Configurator.Configurator import KEY_ENTITY_TYPE, Configurator, KEY_ACTIVE_ENTITIES, KEY_ACTIVE_WAREHOUSES, KEY_WAREHOUSE_TYPE
Expand All @@ -20,7 +22,7 @@ def LoadWarehouses(self) -> list[Warehouse]:
if not KEY_ACTIVE_WAREHOUSES in self.configurations:
self.Log(
self.LOG_ERROR, "You have to enable at least one warehouse: configure it using -c argument")
exit(1)
sys.exit("No warehouse enabled")
for activeWarehouse in self.configurations[KEY_ACTIVE_WAREHOUSES]:
# Get WareHouse named like in config type field, then init it with configs and add it to warehouses list
whClass = wcm.GetClassFromName(
Expand All @@ -43,7 +45,7 @@ def LoadEntities(self) -> list[Entity]:
if not KEY_ACTIVE_ENTITIES in self.configurations:
self.Log(
self.LOG_ERROR, "You have to enable at least one entity: configure it using -c argument")
exit(1)
sys.exit("No entity enabled")
for activeEntity in self.configurations[KEY_ACTIVE_ENTITIES]:
entityClass = ecm.GetClassFromName(activeEntity[KEY_ENTITY_TYPE])
if entityClass is None:
Expand Down
17 changes: 9 additions & 8 deletions IoTuring/__init__.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
#!/usr/bin/env python3

import signal
import sys
import time
import argparse

from IoTuring.MyApp.App import App
from IoTuring.Configurator.Configurator import Configurator
from IoTuring.Configurator.ConfiguratorLoader import ConfiguratorLoader
from IoTuring.Entity.EntityManager import EntityManager
from IoTuring.Logger.Logger import Logger
from IoTuring.Logger.Colors import Colors
import signal
import os
import time
import argparse

warehouses = []
entities = []
Expand Down Expand Up @@ -40,9 +41,9 @@ def loop():

# Only one argument should be used:
if all(vars(args).values()):
print("error: use only one option!", end="\n\n")
parser.print_help()
os._exit(0)
print()
sys.exit("Error: Invalid arguments!")

# Clear the terminal
Configurator.ClearTerminal()
Expand All @@ -66,7 +67,7 @@ def loop():

elif args.open_config:
configurator.OpenConfigInEditor()
os._exit(0)
sys.exit(0)

# This have to start after configurator.Menu(), otherwise won't work starting from the menu
signal.signal(signal.SIGINT, Exit_SIGINT_handler)
Expand Down Expand Up @@ -121,4 +122,4 @@ def Exit_SIGINT_handler(sig=None, frame=None):
writeToFile=False) # to terminal

logger.CloseFile()
os._exit(0)
sys.exit(0)

0 comments on commit 650e2f4

Please sign in to comment.