Compare commits
No commits in common. "f5344f606e4e9eb91e4450bf0c7336d7c2e2ceba" and "fdf3e0fb50e6ea699efa268cb72094f0ca1aabc3" have entirely different histories.
f5344f606e
...
fdf3e0fb50
@ -1,165 +1,100 @@
|
|||||||
import enum
|
from os import path, getcwd, listdir, mkdir, makedirs, rename
|
||||||
from os import EX_CANTCREAT, path, getcwd, listdir, rename
|
|
||||||
from sys import exit
|
|
||||||
import re
|
import re
|
||||||
|
|
||||||
from .globals import version, settings_map
|
def read_config(filepath, root_directory="."):
|
||||||
from .globals import warning, error, user_error, info, create_dir
|
if not path.isfile(filepath): return False
|
||||||
|
|
||||||
class ConfigManager():
|
file = open(filepath, 'r')
|
||||||
"""Manage config files for imgsort"""
|
keys = {}
|
||||||
def __init__(self, config_dir: str):
|
for line in file.readlines():
|
||||||
"""TODO: to be defined.
|
line = line.replace("\n", "")
|
||||||
|
match = re.match(r". = /?([a-z-A-ZöÖäÄüÜ0-9/: _-]+/)*[a-zA-ZöÖäÄüÜ0-9/: _-]+/?", line)
|
||||||
|
if match:
|
||||||
|
key, value = line.split(" = ")
|
||||||
|
keys[key] = root_directory + "/" + value
|
||||||
|
return keys
|
||||||
|
|
||||||
@param config_path TODO
|
def write_config(filepath, keys):
|
||||||
|
file = open(filepath, 'w')
|
||||||
"""
|
file.write("Config written by imgsort.\n")
|
||||||
self._config_dir = config_dir
|
|
||||||
if not path.isdir(self._config_dir):
|
|
||||||
if path.exists(self._config_dir):
|
|
||||||
error(f"Config '{self._config_dir}' exists but is not a directory.")
|
|
||||||
info(f"Creating config dir '{self._config_dir}' since it does not exist")
|
|
||||||
try:
|
|
||||||
create_dir(self._config_dir)
|
|
||||||
except PermissionError as e:
|
|
||||||
error(f"Could not create '{self._config_dir}': PermissionError: {e}")
|
|
||||||
except Exception as e:
|
|
||||||
error(f"Could not create '{self._config_dir}': {e}")
|
|
||||||
|
|
||||||
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):
|
|
||||||
"""
|
|
||||||
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 False
|
|
||||||
|
|
||||||
print("0: create new configuration")
|
|
||||||
for i, c in enumerate(self._configs):
|
|
||||||
print(f"{i+1:2}: {c}")
|
|
||||||
|
|
||||||
while True:
|
|
||||||
choice = input("Please select a config: ")
|
|
||||||
try:
|
|
||||||
choice = int(choice)
|
|
||||||
except ValueError:
|
|
||||||
user_error(f"Invalid choice: '{choice}'. Choice must be a number between 0 and {len(self._configs)}")
|
|
||||||
continue
|
|
||||||
if not 0 <= choice <= len(self._configs):
|
|
||||||
user_error(f"Invalid choice: '{choice}'. Choice must be a number between 0 and {len(self._configs)}")
|
|
||||||
continue
|
|
||||||
|
|
||||||
if choice == 0:
|
|
||||||
return False
|
|
||||||
return self._configs[choice-1]
|
|
||||||
|
|
||||||
|
|
||||||
def _make_name(self, config_name: str):
|
|
||||||
return path.normpath(self._config_dir + "/" + config_name.removesuffix(".conf") + ".conf")
|
|
||||||
|
|
||||||
|
|
||||||
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")
|
|
||||||
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 create_config():
|
||||||
def read_config(self, config_name: str, root_directory="."):
|
keys = {}
|
||||||
"""
|
|
||||||
@param root_directory Make all relative paths relative to this one
|
|
||||||
"""
|
|
||||||
if type(config_name) != str:
|
|
||||||
error(f"load config got wrong type: '{type(config_name)}'")
|
|
||||||
config_file = self._make_name(config_name)
|
|
||||||
if not path.isfile(config_file):
|
|
||||||
error(f"File '{config_file}' does not exist")
|
|
||||||
try:
|
|
||||||
file = open(config_file, 'r')
|
|
||||||
except Exception as e:
|
|
||||||
error(f"Could not open file '{config_file}': {e}")
|
|
||||||
|
|
||||||
keys: dict[str, str] = {}
|
|
||||||
for i, line in enumerate(file.readlines()):
|
|
||||||
line = line.replace("\n", "")
|
|
||||||
match = re.fullmatch(r". = [^*?<>|]+", line)
|
|
||||||
if match:
|
|
||||||
key, value = line.split(" = ")
|
|
||||||
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_dirs(keys)
|
|
||||||
return keys
|
|
||||||
|
|
||||||
def create_config(self):
|
|
||||||
keys: dict[str, str] = {}
|
|
||||||
print(
|
print(
|
||||||
f"""
|
"""
|
||||||
===================================================================================================
|
===================================================================================================
|
||||||
Creating a new config
|
Creating a new config
|
||||||
You can now map keys to directories.
|
Please enter at least one key and one directory.
|
||||||
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 'q', 's', 'o' or 'u'.
|
||||||
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).
|
||||||
===================================================================================================
|
===================================================================================================
|
||||||
"""
|
"""
|
||||||
)
|
)
|
||||||
|
|
||||||
while True:
|
done = False
|
||||||
|
while not done:
|
||||||
|
|
||||||
# ask for key
|
# ask for key
|
||||||
key = input("Please enter a key or 'q' when you are done: ")
|
key = input("Please enter a key or 'q' when you are done: ")
|
||||||
if (len(key) != 1):
|
if (len(key) != 1):
|
||||||
user_error(f"Invalid key: '{key}' has a length other than 1")
|
print("Invalid key: " + key)
|
||||||
continue
|
continue
|
||||||
# if done
|
# if done
|
||||||
elif key == 'q':
|
elif key == 'q':
|
||||||
if len(keys) == 0:
|
save = input("\nDo you want to save the config to ~/.config/imgsort/<name>.conf?\nType a name to save the config or type 'q' to not save the config: ")
|
||||||
warning(f"No keys were mapped - exiting")
|
if not save == 'q':
|
||||||
exit(0)
|
config_path = path.expanduser("~") + "/.config/imgsort"
|
||||||
save = input(f"\nDo you want to save the config to {self._config_dir}/<name>.conf?\nType a name to save the config or type 'q' to not save the config: ")
|
if not path.isdir(config_path):
|
||||||
if save != 'q':
|
mkdir(config_path)
|
||||||
self.write_config(save + ".conf", keys)
|
|
||||||
break
|
write_config(path.normpath(config_path + "/" + save + ".conf"), keys)
|
||||||
elif key in settings_map.keys():
|
done = True
|
||||||
user_error(f"Invalid key: '{key}' is reserved and can not be mapped")
|
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# ask for directory
|
# ask for directory
|
||||||
directory = input("Please enter the directory/path: ")
|
directory = input("Please enter the directory path: ")
|
||||||
# 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":*?<>|"
|
if not match:
|
||||||
if any(c in INVALID_PATH_CHARS for c in directory):
|
print("Invalid directory path: " + directory)
|
||||||
user_error(f"Invalid directory path: '{directory}' contains at least one if '{INVALID_PATH_CHARS}'")
|
|
||||||
continue
|
continue
|
||||||
keys[key] = directory
|
|
||||||
print(f"Added: {key}: '{directory}'\n")
|
|
||||||
|
|
||||||
self.validate_dirs(keys)
|
keys[key] = directory
|
||||||
|
print(f"Added: ({key}: {directory})\n")
|
||||||
|
|
||||||
return keys
|
return keys
|
||||||
|
|
||||||
|
|
||||||
def validate_dirs(self, keys):
|
def select_config():
|
||||||
"""
|
"""
|
||||||
Create the directories that dont exist.
|
Returns to path to an existing config or False if a new config should be created
|
||||||
"""
|
"""
|
||||||
missing = []
|
# get configs
|
||||||
for d in keys.values():
|
config_path = path.expanduser("~") + "/.config/imgsort"
|
||||||
if not path.isdir(d):
|
if not path.isdir(config_path) or len(listdir(config_path)) == 0:
|
||||||
missing.append(d)
|
return False
|
||||||
if len(missing) == 0: return
|
|
||||||
print(f"The following directories do not exist:")
|
configs = {}
|
||||||
for d in missing: print(f"\t{d}")
|
|
||||||
decision = input(f"Create the ({len(missing)}) missing directories? y/*: ")
|
i = 1
|
||||||
if (decision == "y"):
|
for file in listdir(config_path):
|
||||||
for d in missing:
|
if not re.match(r"[a-zA-ZöÖäÄüÜ0-9_\- ]+\.conf", file): continue
|
||||||
create_dir(d)
|
|
||||||
|
configs[str(i)] = file
|
||||||
|
i += 1
|
||||||
|
|
||||||
|
# print configs
|
||||||
|
print("0: Create new config")
|
||||||
|
for n, conf in configs.items():
|
||||||
|
print(f"{n}: {conf}")
|
||||||
|
|
||||||
|
choice = input("Please select a config: ")
|
||||||
|
if choice == "0": return None
|
||||||
|
elif choice in configs:
|
||||||
|
return path.normpath(config_path + "/" + configs[choice])
|
||||||
else:
|
else:
|
||||||
error("Exiting - can not use non-existing directories.")
|
print("Invalid choice - creating new config")
|
||||||
|
return None
|
||||||
|
|
||||||
|
@ -1,32 +0,0 @@
|
|||||||
version = "1.2"
|
|
||||||
|
|
||||||
settings_map = {
|
|
||||||
"q": "quit",
|
|
||||||
"s": "skip",
|
|
||||||
"u": "undo",
|
|
||||||
"o": "open"
|
|
||||||
}
|
|
||||||
|
|
||||||
from os import makedirs
|
|
||||||
|
|
||||||
def error(*args, exitcode=1, **kwargs):
|
|
||||||
print("\033[31mError: \033[0m", *args, **kwargs)
|
|
||||||
exit(exitcode)
|
|
||||||
|
|
||||||
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)
|
|
||||||
|
|
||||||
def info(*args, **kwargs):
|
|
||||||
print("\033[34mInfo: \033[0m", *args, **kwargs)
|
|
||||||
|
|
||||||
def create_dir(d):
|
|
||||||
try:
|
|
||||||
makedirs(d)
|
|
||||||
except PermissionError as e:
|
|
||||||
error(f"Could not create '{d}': PermissionError: {e}")
|
|
||||||
except Exception as e:
|
|
||||||
error(f"Could not create '{d}': {e}")
|
|
@ -13,10 +13,16 @@ if __name__ == "__main__": # make relative imports work as described here: http
|
|||||||
filepath = path.realpath(path.abspath(__file__))
|
filepath = path.realpath(path.abspath(__file__))
|
||||||
sys.path.insert(0, path.dirname(path.dirname(filepath)))
|
sys.path.insert(0, path.dirname(path.dirname(filepath)))
|
||||||
|
|
||||||
from .configs import ConfigManager
|
from .configs import read_config, select_config
|
||||||
from .ueberzug import UeberzugLayer
|
from .ueberzug import UeberzugLayer
|
||||||
from .globals import version, settings_map
|
|
||||||
from .globals import warning, error, user_error, info, create_dir
|
|
||||||
|
settings = {
|
||||||
|
"q": "quit",
|
||||||
|
"s": "skip",
|
||||||
|
"u": "undo",
|
||||||
|
"o": "open"
|
||||||
|
}
|
||||||
|
|
||||||
# Size settings
|
# Size settings
|
||||||
FOOTER_LEFT = 0
|
FOOTER_LEFT = 0
|
||||||
@ -29,6 +35,8 @@ CURSOR_Y = 2
|
|||||||
|
|
||||||
KEYS_BEGIN = 5
|
KEYS_BEGIN = 5
|
||||||
|
|
||||||
|
version = "1.2"
|
||||||
|
|
||||||
class Sorter:
|
class Sorter:
|
||||||
def __init__(self, wdir, config):
|
def __init__(self, wdir, config):
|
||||||
self.wd = wdir
|
self.wd = wdir
|
||||||
@ -40,7 +48,9 @@ class Sorter:
|
|||||||
|
|
||||||
self.keys = config
|
self.keys = config
|
||||||
|
|
||||||
self.settings = settings_map
|
self.settings = settings
|
||||||
|
|
||||||
|
self.validate_dirs()
|
||||||
|
|
||||||
# info about last action
|
# info about last action
|
||||||
self.last_dir = ""
|
self.last_dir = ""
|
||||||
@ -67,6 +77,21 @@ class Sorter:
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def validate_dirs(self):
|
||||||
|
"""
|
||||||
|
Create the directories that dont exist.
|
||||||
|
"""
|
||||||
|
for d in self.keys.values():
|
||||||
|
if not path.isdir(d):
|
||||||
|
print(f"Directory '{d}' does not exist.")
|
||||||
|
decision = input(f"Create directory '{path.abspath(d)}'? y/n: ")
|
||||||
|
if (decision == "y"):
|
||||||
|
makedirs(d)
|
||||||
|
else:
|
||||||
|
print("Exiting - can not use non-existing directory.")
|
||||||
|
exit(1)
|
||||||
|
|
||||||
|
|
||||||
def get_images(self):
|
def get_images(self):
|
||||||
"""
|
"""
|
||||||
Put all image-paths from wd in images dictionary.
|
Put all image-paths from wd in images dictionary.
|
||||||
@ -108,7 +133,7 @@ class Sorter:
|
|||||||
self.image_iter += 1
|
self.image_iter += 1
|
||||||
self.message = "Skipped image"
|
self.message = "Skipped image"
|
||||||
continue
|
continue
|
||||||
elif settings_map[self.pressed_key] == "undo":
|
elif settings[self.pressed_key] == "undo":
|
||||||
if self.image_iter > 0:
|
if self.image_iter > 0:
|
||||||
self.image_iter -= 1 # using last image
|
self.image_iter -= 1 # using last image
|
||||||
rename(self.images_new[self.image_iter], self.images[self.image_iter])
|
rename(self.images_new[self.image_iter], self.images[self.image_iter])
|
||||||
@ -118,7 +143,7 @@ class Sorter:
|
|||||||
else:
|
else:
|
||||||
self.message = "Nothing to undo!"
|
self.message = "Nothing to undo!"
|
||||||
continue
|
continue
|
||||||
elif settings_map[self.pressed_key] == "open":
|
elif settings[self.pressed_key] == "open":
|
||||||
try:
|
try:
|
||||||
subprocess.run(['xdg-open', self.image], stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL)
|
subprocess.run(['xdg-open', self.image], stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL)
|
||||||
self.message = "Opening with xdg-open"
|
self.message = "Opening with xdg-open"
|
||||||
@ -238,7 +263,7 @@ Image Sorter
|
|||||||
if 'IMGSOSRT_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)")
|
||||||
parser.add_argument("-i", "--sort-dir", action="store", help="the directory where the folders from the config will be created")
|
parser.add_argument("-i", "--sort-dir", action="store", help="the directory where the folders from the config will be created")
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
@ -249,18 +274,23 @@ Image Sorter
|
|||||||
else:
|
else:
|
||||||
args.sort_dir = getcwd()
|
args.sort_dir = getcwd()
|
||||||
|
|
||||||
confman = ConfigManager(config_dir)
|
|
||||||
|
|
||||||
# configuration
|
# configuration
|
||||||
if not args.config:
|
if args.config:
|
||||||
args.config = confman.present_config_selection()
|
config_path = args.config_file
|
||||||
# if create config was selected
|
# search locally
|
||||||
if args.config is False:
|
if not path.isfile(config_path):
|
||||||
config = confman.create_config()
|
config_path = path.join(config_dir, args.config)
|
||||||
|
if not path.isfile(config_path):
|
||||||
|
parser.error(f"invalid configuration path/name:'{config_path}'/'{args.config}'")
|
||||||
else:
|
else:
|
||||||
if type(args.config) != str:
|
args.config = select_config()
|
||||||
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)
|
config = read_config(args.config, root_directory=args.sort_dir)
|
||||||
|
if not config:
|
||||||
|
print("Error reading the config:")
|
||||||
|
print(" Config Name:", args.config)
|
||||||
|
print(" Config:", config)
|
||||||
|
exit(1)
|
||||||
|
|
||||||
sorter = Sorter(wd, config)
|
sorter = Sorter(wd, config)
|
||||||
sorter.get_images()
|
sorter.get_images()
|
||||||
|
Loading…
Reference in New Issue
Block a user