configman always return keys
This commit is contained in:
parent
d78f522743
commit
ef48a089cf
@ -29,16 +29,16 @@ 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):
|
def present_config_selection(self, root_directory="."):
|
||||||
"""
|
"""
|
||||||
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 False
|
return self.create_config(root_directory)
|
||||||
|
|
||||||
print("0: create new configuration")
|
print(" 0: create new configuration")
|
||||||
for i, c in enumerate(self._configs):
|
for i, c in enumerate(self._configs):
|
||||||
print(f"{i+1:2}: {c}")
|
print(f"{i+1:2}: {c}")
|
||||||
|
|
||||||
@ -54,8 +54,8 @@ class ConfigManager():
|
|||||||
continue
|
continue
|
||||||
|
|
||||||
if choice == 0:
|
if choice == 0:
|
||||||
return False
|
return self.create_config(root_directory)
|
||||||
return self._configs[choice-1]
|
return self.load_config(self._configs[choice-1], root_directory)
|
||||||
|
|
||||||
|
|
||||||
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 read_config(self, config_name: str, root_directory="."):
|
def load_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] = path.normpath(root_directory + "/" + value)
|
keys[key] = 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_dirs(keys)
|
self.validate_config(keys, root_directory)
|
||||||
return keys
|
return keys
|
||||||
|
|
||||||
def create_config(self):
|
def create_config(self, root_directory="."):
|
||||||
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,22 +134,26 @@ 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 if '{INVALID_PATH_CHARS}'")
|
user_error(f"Invalid directory path: '{directory}' contains at least one of '{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_dirs(keys)
|
self.validate_config(keys, root_directory)
|
||||||
|
|
||||||
return keys
|
return keys
|
||||||
|
|
||||||
|
|
||||||
def validate_dirs(self, keys):
|
def validate_config(self, keys, root_directory):
|
||||||
"""
|
"""
|
||||||
Create the directories that dont exist.
|
Create the directories that dont exist.
|
||||||
"""
|
"""
|
||||||
missing = []
|
missing = []
|
||||||
for d in keys.values():
|
for k, d in keys.items():
|
||||||
|
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
|
||||||
|
@ -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, settings_map
|
from .globals import version, fullversion, 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,8 +30,6 @@ 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
|
||||||
@ -231,14 +229,14 @@ class Sorter:
|
|||||||
|
|
||||||
def main():
|
def main():
|
||||||
# set working directory
|
# set working directory
|
||||||
print("""
|
print(f"""
|
||||||
===================================================================================================
|
===================================================================================================
|
||||||
Image Sorter
|
Image Sorter {fullversion}
|
||||||
===================================================================================================
|
===================================================================================================
|
||||||
""")
|
""")
|
||||||
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 'IMGSOSRT_CONFIG_DIR' in os.environ: config_dir = os.environ['IMGSORT_CONFIG_DIR']
|
if 'IMGSORT_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)
|
||||||
@ -255,15 +253,10 @@ Image Sorter
|
|||||||
confman = ConfigManager(config_dir)
|
confman = ConfigManager(config_dir)
|
||||||
|
|
||||||
# configuration
|
# configuration
|
||||||
if not args.config:
|
if type(args.config) == str:
|
||||||
args.config = confman.present_config_selection()
|
config = confman.load_config(args.config, args.sort_dir)
|
||||||
# if create config was selected
|
|
||||||
if args.config is False:
|
|
||||||
config = confman.create_config()
|
|
||||||
else:
|
else:
|
||||||
if type(args.config) != str:
|
config = confman.present_config_selection()
|
||||||
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)
|
||||||
|
Loading…
Reference in New Issue
Block a user