Compare commits

..

No commits in common. "ef48a089cf71e793f0586d727dd61d83c7d871e5" and "8f8e6bdbc587678e74bd66f0a0e40d92de011703" have entirely different histories.

5 changed files with 33 additions and 33 deletions

View File

@ -42,9 +42,6 @@ python3 -m pip install .
## Changelog ## Changelog
### 1.2 ### 1.2
#### 1.2.1
- Refactored configuration management
#### 1.2.0
- Support ueberzugpp - Support ueberzugpp
- Added option to open file with `xdg-open` - Added option to open file with `xdg-open`
- Use pyproject.toml for installation - Use pyproject.toml for installation

View File

@ -29,14 +29,14 @@ class ConfigManager():
self._configs = [ e for e in listdir(self._config_dir) if path.isfile(path.normpath(self._config_dir + "/" + e)) and e.endswith(".conf") ] self._configs = [ e for e in listdir(self._config_dir) if path.isfile(path.normpath(self._config_dir + "/" + e)) and e.endswith(".conf") ]
self._configs.sort() self._configs.sort()
def present_config_selection(self, root_directory="."): def present_config_selection(self):
""" """
Returns to path to an existing config or False if a new config should be created Returns to path to an existing config or False if a new config should be created
""" """
# get configs # get configs
if len(self._configs) == 0: if len(self._configs) == 0:
info(f"No config valid file found in '{self._config_dir}'") info(f"No config valid file found in '{self._config_dir}'")
return self.create_config(root_directory) return False
print("0: create new configuration") print("0: create new configuration")
for i, c in enumerate(self._configs): for i, c in enumerate(self._configs):
@ -54,8 +54,8 @@ class ConfigManager():
continue continue
if choice == 0: if choice == 0:
return self.create_config(root_directory) return False
return self.load_config(self._configs[choice-1], root_directory) return self._configs[choice-1]
def _make_name(self, config_name: str): def _make_name(self, config_name: str):
@ -64,12 +64,12 @@ class ConfigManager():
def write_config(self, config_name: str, keys: dict[str,str]): def write_config(self, config_name: str, keys: dict[str,str]):
file = open(path.normpath(self._config_dir + "/" + config_name), 'w') file = open(path.normpath(self._config_dir + "/" + config_name), 'w')
file.write(f"# Config written by imgsort {version}\n") file.write(f"# Config written by imgsort {version}.\n")
for k, v in keys.items() : for k, v in keys.items() :
file.write(f"{k} = {v}\n") file.write(f"{k} = {v}\n")
def load_config(self, config_name: str, root_directory="."): def read_config(self, config_name: str, root_directory="."):
""" """
@param root_directory Make all relative paths relative to this one @param root_directory Make all relative paths relative to this one
""" """
@ -89,13 +89,13 @@ class ConfigManager():
match = re.fullmatch(r". = [^*?<>|]+", line) match = re.fullmatch(r". = [^*?<>|]+", line)
if match: if match:
key, value = line.split(" = ") key, value = line.split(" = ")
keys[key] = value keys[key] = path.normpath(root_directory + "/" + value)
elif not line[0] == "#": elif not line[0] == "#":
warning(f"In config file '{config_file}': Invalid line ({i+1}): '{line}'") warning(f"In config file '{config_file}': Invalid line ({i+1}): '{line}'")
self.validate_config(keys, root_directory) self.validate_dirs(keys)
return keys return keys
def create_config(self, root_directory="."): def create_config(self):
keys: dict[str, str] = {} keys: dict[str, str] = {}
print( print(
f""" f"""
@ -103,7 +103,7 @@ f"""
Creating a new config Creating a new config
You can now map keys to directories. You can now map keys to directories.
The key must be one single letter, a single digit number or some other keyboard key like .-#+&/ ... The key must be one single letter, a single digit number or some other keyboard key like .-#+&/ ...
The key can not be one of '{' '.join(settings_map.keys())}'. The key can not be one of {' '.join(settings_map.keys())}.
The directory must be a valid path to a directory, but is does not have to exist. The directory must be a valid path to a directory, but is does not have to exist.
You can use an absolute path (starting with '/', not '~') or a relative path (from here). You can use an absolute path (starting with '/', not '~') or a relative path (from here).
=================================================================================================== ===================================================================================================
@ -134,26 +134,22 @@ Creating a new config
# match = re.match(r"/?([a-z-A-ZöÖäÄüÜ0-9/: _\-]+/)*[a-z-A-ZöÖäÄüÜ0-9/: _\-]+/?", directory) # match = re.match(r"/?([a-z-A-ZöÖäÄüÜ0-9/: _\-]+/)*[a-z-A-ZöÖäÄüÜ0-9/: _\-]+/?", directory)
INVALID_PATH_CHARS = r":*?<>|" INVALID_PATH_CHARS = r":*?<>|"
if any(c in INVALID_PATH_CHARS for c in directory): if any(c in INVALID_PATH_CHARS for c in directory):
user_error(f"Invalid directory path: '{directory}' contains at least one of '{INVALID_PATH_CHARS}'") user_error(f"Invalid directory path: '{directory}' contains at least one if '{INVALID_PATH_CHARS}'")
continue continue
keys[key] = directory keys[key] = directory
print(f"Added: {key}: '{directory}'\n") print(f"Added: {key}: '{directory}'\n")
self.validate_config(keys, root_directory) self.validate_dirs(keys)
return keys return keys
def validate_config(self, keys, root_directory): def validate_dirs(self, keys):
""" """
Create the directories that dont exist. Create the directories that dont exist.
""" """
missing = [] missing = []
for k, d in keys.items(): for d in keys.values():
d = path.expanduser(d)
if not path.isabs(d):
d = path.normpath(root_directory + "/" + d)
keys[k] = d
if not path.isdir(d): if not path.isdir(d):
missing.append(d) missing.append(d)
if len(missing) == 0: return if len(missing) == 0: return

View File

@ -1,5 +1,4 @@
version = "1.2.1" version = "1.2"
fullversion = f"{version}-legacy"
settings_map = { settings_map = {
"q": "quit", "q": "quit",
@ -14,8 +13,9 @@ def error(*args, exitcode=1, **kwargs):
print("\033[31mError: \033[0m", *args, **kwargs) print("\033[31mError: \033[0m", *args, **kwargs)
exit(exitcode) exit(exitcode)
def user_error(*args, **kwargs): def user_error(*args, exitcode=1, **kwargs):
print("\033[31mError: \033[0m", *args, **kwargs) print("\033[31mError: \033[0m", *args, **kwargs)
exit(exitcode)
def warning(*args, **kwargs): def warning(*args, **kwargs):
print("\033[33mWarning: \033[0m", *args, **kwargs) print("\033[33mWarning: \033[0m", *args, **kwargs)

View File

@ -16,7 +16,7 @@ if __name__ == "__main__": # make relative imports work as described here: http
import ueberzug.lib.v0 as uz import ueberzug.lib.v0 as uz
from .configs import ConfigManager from .configs import ConfigManager
from .globals import version, fullversion, settings_map from .globals import version, settings_map
from .globals import warning, error, user_error, info, create_dir from .globals import warning, error, user_error, info, create_dir
# Size settings # Size settings
@ -30,6 +30,8 @@ CURSOR_Y = 2
KEYS_BEGIN = 5 KEYS_BEGIN = 5
version = "1.2-legacy"
class Sorter: class Sorter:
def __init__(self, wdir, canvas, config): def __init__(self, wdir, canvas, config):
self.wd = wdir self.wd = wdir
@ -229,14 +231,14 @@ class Sorter:
def main(): def main():
# set working directory # set working directory
print(f""" print("""
=================================================================================================== ===================================================================================================
Image Sorter {fullversion} Image Sorter
=================================================================================================== ===================================================================================================
""") """)
config_dir = os.path.join(os.environ.get("XDG_CONFIG_HOME", os.path.expanduser("~/.config")), "imgsort") config_dir = os.path.join(os.environ.get("XDG_CONFIG_HOME", os.path.expanduser("~/.config")), "imgsort")
# check if environment variables are set and use them if they are # check if environment variables are set and use them if they are
if 'IMGSORT_CONFIG_DIR' in os.environ: config_dir = os.environ['IMGSORT_CONFIG_DIR'] if 'IMGSOSRT_CONFIG_DIR' in os.environ: config_dir = os.environ['IMGSORT_CONFIG_DIR']
parser = argparse.ArgumentParser("imgsort") parser = argparse.ArgumentParser("imgsort")
parser.add_argument("-c", "--config", action="store", help="name of the config file in ($IMGSORT_CONFIG_DIR > $XDG_CONFIG_HOME/imgsort > ~/.config/imgsort)", default=None) parser.add_argument("-c", "--config", action="store", help="name of the config file in ($IMGSORT_CONFIG_DIR > $XDG_CONFIG_HOME/imgsort > ~/.config/imgsort)", default=None)
@ -253,10 +255,15 @@ Image Sorter {fullversion}
confman = ConfigManager(config_dir) confman = ConfigManager(config_dir)
# configuration # configuration
if type(args.config) == str: if not args.config:
config = confman.load_config(args.config, args.sort_dir) args.config = confman.present_config_selection()
# if create config was selected
if args.config is False:
config = confman.create_config()
else: else:
config = confman.present_config_selection() if type(args.config) != str:
error(f"Could not determine condig file to load ('{args.config}' is of type '{type(args.config)}' not ")
config = confman.read_config(args.config, args.sort_dir)
with uz.Canvas() as canvas: with uz.Canvas() as canvas:
sorter = Sorter(wd, canvas, config) sorter = Sorter(wd, canvas, config)

View File

@ -3,7 +3,7 @@ requires = ["setuptools"]
[project] [project]
name = "imgsort" name = "imgsort"
version = "1.2.1" version = "1.2.0"
description = "A program that lets you easily sort images into different folders." description = "A program that lets you easily sort images into different folders."
requires-python = ">=3.10" requires-python = ">=3.10"
readme = "README.md" readme = "README.md"