Compare commits

..

No commits in common. "c91b3a3f931874d2580194ccbff3e36255ed1f18" and "39d7471dc8bd2bf437400ccbccd969d7b4ffd28e" have entirely different histories.

5 changed files with 31 additions and 33 deletions

View File

@ -42,9 +42,6 @@ python3 -m pip install .
## Changelog
### 1.2
#### 1.2.1
- Refactored configuration management
#### 1.2.0
- Support ueberzugpp
- Added option to open file with `xdg-open`
- 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.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
"""
# get configs
if len(self._configs) == 0:
info(f"No config valid file found in '{self._config_dir}'")
return self.create_config(root_directory)
return False
print("0: create new configuration")
for i, c in enumerate(self._configs):
@ -54,8 +54,8 @@ class ConfigManager():
continue
if choice == 0:
return self.create_config(root_directory)
return self.load_config(self._configs[choice-1], root_directory)
return False
return self._configs[choice-1]
def _make_name(self, config_name: str):
@ -64,12 +64,12 @@ class ConfigManager():
def write_config(self, config_name: str, keys: dict[str,str]):
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() :
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
"""
@ -89,13 +89,13 @@ class ConfigManager():
match = re.fullmatch(r". = [^*?<>|]+", line)
if match:
key, value = line.split(" = ")
keys[key] = value
keys[key] = path.normpath(root_directory + "/" + value)
elif not line[0] == "#":
warning(f"In config file '{config_file}': Invalid line ({i+1}): '{line}'")
self.validate_config(keys, root_directory)
self.validate_dirs(keys)
return keys
def create_config(self, root_directory="."):
def create_config(self):
keys: dict[str, str] = {}
print(
f"""
@ -103,7 +103,7 @@ f"""
Creating a new config
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 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.
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)
INVALID_PATH_CHARS = r":*?<>|"
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
keys[key] = directory
print(f"Added: {key}: '{directory}'\n")
self.validate_config(keys, root_directory)
self.validate_dirs(keys)
return keys
def validate_config(self, keys, root_directory):
def validate_dirs(self, keys):
"""
Create the directories that dont exist.
"""
missing = []
for k, d in keys.items():
d = path.expanduser(d)
if not path.isabs(d):
d = path.normpath(root_directory + "/" + d)
keys[k] = d
for d in keys.values():
if not path.isdir(d):
missing.append(d)
if len(missing) == 0: return

View File

@ -1,5 +1,4 @@
version = "1.2.1"
fullversion = f"{version}-legacy"
version = "1.2"
settings_map = {
"q": "quit",
@ -14,8 +13,9 @@ def error(*args, exitcode=1, **kwargs):
print("\033[31mError: \033[0m", *args, **kwargs)
exit(exitcode)
def user_error(*args, **kwargs):
def user_error(*args, exitcode=1, **kwargs):
print("\033[31mError: \033[0m", *args, **kwargs)
exit(exitcode)
def warning(*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
from .ueberzug import UeberzugLayer
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
# Size settings
@ -229,14 +229,14 @@ class Sorter:
def main():
# 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")
# 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.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 +253,15 @@ Image Sorter {fullversion}
confman = ConfigManager(config_dir)
# configuration
if type(args.config) == str:
config = confman.load_config(args.config, args.sort_dir)
if not args.config:
args.config = confman.present_config_selection()
# if create config was selected
if args.config is False:
config = confman.create_config()
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)
sorter = Sorter(wd, config)
sorter.get_images()

View File

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