1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
|
# SPDX-FileCopyrightText: © 2008-2022 Oprea Dan
# SPDX-FileCopyrightText: © 2008-2022 Bart de Koning
# SPDX-FileCopyrightText: © 2008-2022 Richard Bailey
# SPDX-FileCopyrightText: © 2008-2022 Germar Reitze
#
# SPDX-License-Identifier: GPL-2.0-or-later
#
# This file is part of the program "Back In Time" which is released under GNU
# General Public License v2 (GPLv2). See LICENSES directory or go to
# <https://spdx.org/licenses/GPL-2.0-or-later.html>.
import os
import collections
import re
import logger
class ConfigFile:
"""Store options in a plain text file in form of: key=value
"""
def __init__(self):
self.dict = {}
self.errorHandler = None
self.questionHandler = None
def setErrorHandler(self, handler):
"""
Register a function that should be called for notifying errors.
handler (method): callable function
"""
self.errorHandler = handler
def setQuestionHandler(self, handler):
"""
Register a function that should be called for asking questions.
handler (method): callable function
"""
self.questionHandler = handler
def clearHandlers(self):
"""
Reset error and question handlers.
"""
self.errorHandler = None
self.questionHandler = None
def notifyError(self, message):
"""
Call previously registered function to show an error.
Args:
message (str): error message that should be shown
"""
if self.errorHandler is None:
return
self.errorHandler(message)
def askQuestion(self, message):
"""
Call previously registered function to ask a question.
Args:
message (str): question that should be shown
"""
if self.questionHandler is None:
return False
return self.questionHandler(message)
def save(self, filename):
"""
Save all options to file.
Args:
filename (str): full path
Returns:
bool: ``True`` if successful
"""
def numsort(key):
"""
Sort int in keys in numeric order instead of alphabetical by adding
leading zeros to int's
"""
return re.sub(r'\d+', lambda m: m.group(0).zfill(6), key)
try:
with open(filename, mode='wt', encoding='utf-8') as f:
keys = list(self.dict.keys())
keys.sort(key=numsort)
for key in keys:
f.write("%s=%s\n" % (key, self.dict[key]))
except OSError as e:
logger.error('Failed to save config: %s' % str(e), self)
self.notifyError(
'{}: {}'.format(_('Failed to save config'), str(e)))
return False
return True
def load(self, filename, **kwargs):
"""
Reset current options and load new options from file.
Args:
filename (str): full path
"""
self.dict = {}
self.append(filename, **kwargs)
def append(self, filename, maxsplit=1):
"""
Load options from file and append them to current options.
Args:
filename (str): full path
maxsplit (int): split lines only n times on '='
"""
lines = []
if not os.path.isfile(filename):
return
try:
with open(filename, mode='rt', encoding='utf-8') as f:
lines = f.readlines()
except OSError as e:
logger.error('Failed to load config: %s' % str(e), self)
self.notifyError(
'{}: {}'.format(_('Failed to load config'), str(e)))
for line in lines:
items = line.strip('\n').split('=', maxsplit)
if len(items) == 2:
self.dict[items[0]] = items[1]
def remapKey(self, old_key, new_key):
"""
Remap keys to a new key name.
Args:
old_key (str): old key name
new_key (str): new key name
"""
if old_key != new_key:
if old_key in self.dict:
if new_key not in self.dict:
self.dict[new_key] = self.dict[old_key]
del self.dict[old_key]
def remapKeyRegex(self, pattern, replace):
"""
Remap keys to a new key name using :py:func:`re.sub`.
Args:
pattern (str): part of key name that should be replaced
replace (:py:class:`str`, method):
string or a callable function which will be used
to replace all matches of ``pattern``.
"""
c = re.compile(pattern)
for key in list(self.dict):
newKey = c.sub(replace, key)
if key != newKey:
self.remapKey(key, newKey)
def hasKey(self, key):
"""
``True`` if key is set.
Args:
key (str): string used as key
Returns:
bool: ``True`` if the ``key`` is set
"""
return key in self.dict
def strValue(self, key, default=''):
"""
Return a 'str' instance of key's value.
Args:
key (str): Key identifying the value in the config file.
default (str): Default value if ``key`` is not present.
Returns:
str: Value of ``key`` or ``default``.
"""
if key in self.dict:
return self.dict[key]
else:
return default
def setStrValue(self, key, value):
"""
Set a string value for key.
Args:
key (str): string used as key
value (str): store this value
"""
self.dict[key] = value
def intValue(self, key, default=0):
"""
Return a 'int' instance of key's value.
Args:
key (str): string used as key
default (int): return this if ``key`` is not set
Returns:
int: value of ``key`` or ``default``
if ``key`` is not set.
"""
try:
return int(self.dict[key])
except Exception:
return default
def setIntValue(self, key, value):
"""
Set an integer value for key.
Args:
key (str): string used as key
value (int): store this option
"""
self.setStrValue(key, str(value))
def boolValue(self, key, default=False):
"""
Return a 'bool' instance of key's value.
Args:
key (str): string used as key
default (bool): return this if key is not set
Returns:
bool: value of 'key' or 'default'
if 'key' is not set.
"""
try:
val = self.dict[key]
if "1" == val or "TRUE" == val.upper():
return True
return False
except Exception:
return default
def setBoolValue(self, key, value):
"""
Set a bool value for key.
Args:
key (str): string used as key
value (bool): store this option
"""
if value:
self.setStrValue(key, 'true')
else:
self.setStrValue(key, 'false')
def listValue(self, key, type_key='str:value', default=[]):
"""
Return a list of values
Size of the list must be stored in key.size
Args:
key (str): used base-key
type_key (str): pattern of 'value-type:value-name'.
See examples below.
default (list): default value
Returns:
list: value of ``key`` or ``default``
if ``key`` is not set.
``type_key`` pattern examples::
'str:value' => return str values from key.value
'int:type' => return int values from key.type
'bool:enabled' => return bool values from key.enabled
('str:value', 'int:type') => return tuple of values
"""
def typeKeySplit(tk):
t, k = '', ''
if isinstance(tk, str):
t, k = tk.split(':', maxsplit=1)
return (t, k)
def value(key, tk):
t, k = typeKeySplit(tk)
if t in ('str', 'int', 'bool'):
func = getattr(self, '%sValue' % t)
return func('%s.%s' % (key, k))
raise TypeError('Invalid type_key: %s' % tk)
size = self.intValue('%s.size' % key, -1)
if size < 0:
return default
ret = []
for i in range(1, size + 1):
if isinstance(type_key, str):
if not self.hasKey('%s.%s.%s' %
(key, i, typeKeySplit(type_key)[1])):
continue
ret.append(value('%s.%s' % (key, i), type_key))
elif isinstance(type_key, tuple):
if not self.hasKey('%s.%s.%s' %
(key, i, typeKeySplit(type_key[0])[1])):
continue
items = []
for tk in type_key:
items.append(value('%s.%s' % (key, i), tk))
ret.append(tuple(items))
else:
raise TypeError('Invalid type_key: %s' % type_key)
return ret
def setListValue(self, key, type_key, value):
"""
Set a list of values.
Size of the list will be stored in key.size
Args:
key (str): used base-key
type_key (str): pattern of 'value-type:value-name'.
See examples below.
value (list): that should be stored
``type_key`` pattern examples::
'str:value' => return str values from key.value
'int:type' => return int values from key.type
'bool:enabled' => return bool values from key.enabled
('str:value', 'int:type') => return tuple of values
"""
def setValue(key, tk, v):
t = ''
if isinstance(tk, str):
t, k = tk.split(':', maxsplit=1)
if t in ('str', 'int', 'bool'):
func = getattr(self, 'set%sValue' % t.capitalize())
return func('%s.%s' % (key, k), v)
raise TypeError('Invalid type_key: %s' % tk)
if not isinstance(value, (list, tuple)):
raise TypeError('value has wrong type: %s' % value)
old_size = self.intValue('%s.size' % key, -1)
self.setIntValue('%s.size' % key, len(value))
for i, v in enumerate(value, start=1):
if isinstance(type_key, str):
setValue('%s.%s' % (key, i), type_key, v)
elif isinstance(type_key, tuple):
for iv, tk in enumerate(type_key):
if len(v) > iv:
setValue('%s.%s' % (key, i), tk, v[iv])
else:
self.removeKey('%s.%s.%s' % (key, i, tk.split(':')[1]))
else:
raise TypeError('Invalid type_key: %s' % type_key)
if len(value) < old_size:
for i in range(len(value) + 1, old_size + 1):
if isinstance(type_key, str):
self.removeKey(
'%s.%s.%s' % (key, i, type_key.split(':')[1]))
elif isinstance(type_key, tuple):
for tk in type_key:
self.removeKey(
'%s.%s.%s' % (key, i, tk.split(':')[1]))
def removeKey(self, key):
"""
Remove key from options.
Args:
key (str): string used as key
"""
if key in self.dict:
del self.dict[key]
def removeKeysStartsWith(self, prefix):
"""
Remove key from options which start with given prefix.
Args:
prefix (str): prefix for keys (key starts with this string)
that should be removed
"""
removeKeys = []
for key in self.dict.keys():
if key.startswith(prefix):
removeKeys.append(key)
for key in removeKeys:
del self.dict[key]
def keys(self):
return list(self.dict.keys())
class ConfigFileWithProfiles(ConfigFile):
"""
Store options in profiles as 'profileX.key=value'
Args:
default_profile_name (str): default name of the first profile.
"""
def __init__(self, default_profile_name=''):
ConfigFile.__init__(self)
self.default_profile_name = default_profile_name
self.current_profile_id = '1'
self.setCurrentProfile(self.current_profile_id)
def load(self, filename):
"""
Reset current options and load new options from file.
Args:
filename (str): full path
"""
self.current_profile_id = '1'
super(ConfigFileWithProfiles, self).load(filename)
def append(self, filename):
"""Load options from file and append them to current options.
Args:
filename (str): full path
"""
super(ConfigFileWithProfiles, self).append(filename)
found = False
profiles = self.profiles()
for profile_id in profiles:
if profile_id == self.current_profile_id:
found = True
break
if not found and profiles:
self.current_profile_id = profiles[0]
if self.intValue('profiles.version') <= 0:
rename_keys = []
for key in self.dict.keys():
if key.startswith('profile.0.'):
rename_keys.append(key)
for old_key in rename_keys:
new_key = 'profile1.' + old_key[10:]
self.dict[new_key] = self.dict[old_key]
del self.dict[old_key]
if self.intValue('profiles.version') != 1:
self.setIntValue('profiles.version', 1)
def profiles(self):
"""
List of all available profile IDs. Profile IDs are strings!
Returns:
list: List with strings of profile IDs as strings.
"""
return self.strValue(key='profiles', default='1').split(':')
def profilesSortedByName(self):
"""
List of available profile IDs alphabetically sorted by their names.
Profile IDs are strings!
Returns:
list: all available profile IDs as strings
"""
profiles_unsorted = self.profiles()
if len(profiles_unsorted) <= 1:
return profiles_unsorted
profiles_dict = {}
for profile_id in profiles_unsorted:
profiles_dict[self.profileName(profile_id).upper()] = profile_id
# sort the dictionary by key (the profile name)
profiles_sorted = collections.OrderedDict(
sorted(profiles_dict.items()))
# return the names as a list
return list(profiles_sorted.values())
def currentProfile(self):
"""
Currently selected profile ID. Profile IDs are strings!
Returns:
str: profile ID
"""
return self.current_profile_id
def setCurrentProfile(self, profile_id):
"""
Change the current profile.
Args:
profile_id (str, int): valid profile ID
Returns:
bool: ``True`` if successful
"""
if isinstance(profile_id, int):
profile_id = str(profile_id)
profiles = self.profiles()
for i in profiles:
if i == profile_id:
profile_name = self.profileName(profile_id)
self.current_profile_id = profile_id
logger.changeProfile(profile_id, profile_name)
logger.debug(
f'Change current profile to {profile_name}({profile_id})',
self)
return True
return False
def setCurrentProfileByName(self, name):
"""
Change the current profile by a given name.
Args:
name (str): valid profile name
Returns:
bool: ``True`` if successful
"""
# Find the profile_id to this name...
for profile_id in self.profiles():
if self.profileName(profile_id) == name:
# ...and set current profile by this id.
return self.setCurrentProfile(profile_id)
return False
def profileExists(self, profile_id):
"""
``True`` if the profile exists.
Args:
profile_id (str, int): profile ID
Returns:
bool: ``True`` if ``profile_id`` exists.
"""
if isinstance(profile_id, int):
profile_id = str(profile_id)
return profile_id in self.profiles()
def profileExistsByName(self, name) -> bool:
"""
``True`` if the profile exists.
Args:
name (str): profile name
Returns:
bool: ``True`` if ``name`` exists.
"""
profiles = self.profiles()
for profile_id in profiles:
if self.profileName(profile_id) == name:
return True
return False
def profileName(self, profile_id=None):
"""Name of the profile.
Args:
profile_id (str, int): Valid profile ID
Returns:
str: Name of profile.
"""
if isinstance(profile_id, int):
profile_id = str(profile_id)
if profile_id is None:
profile_id = self.current_profile_id
if profile_id == '1':
default = self.default_profile_name
else:
default = 'Profile %s' % profile_id
return self.profileStrValue('name', default, profile_id)
def addProfile(self, name: str) -> str | None:
"""Add a new profile if the name is not already in use.
Args:
name (str): Profile name.
Returns:
str: The new profile ID or None if profile with same name
already exists.
"""
if self.profileExistsByName(name):
self.notifyError(
_('Profile "{name}" already exists.').format(name=name))
return None
profiles = self.profiles()
pid = self._next_unused_id()
profiles.append(self._next_unused_id())
self.setStrValue('profiles', ':'.join(profiles))
self.setProfileStrValue('name', name, pid)
return pid
def _next_unused_id(self):
pid = 1
existing_pids = self.profiles()
while True:
if str(pid) in existing_pids:
pid += 1
else:
break
return str(pid)
def removeProfile(self, profile_id=None):
"""
Remove profile and all its keys and values.
Args:
profile_id (str, int): valid profile ID
Returns:
bool: ``True`` if successful
"""
if isinstance(profile_id, int):
profile_id = str(profile_id)
if profile_id is None:
profile_id = self.current_profile_id
profiles = self.profiles()
if len(profiles) <= 1:
self.notifyError(_("The last profile cannot be removed."))
return False
found = False
index = 0
for profile in profiles:
if profile == profile_id:
self.removeKeysStartsWith(self.profileKey('', profile_id))
del profiles[index]
self.setStrValue('profiles', ':'.join(profiles))
found = True
break
index = index + 1
if not found:
return False
if self.current_profile_id == profile_id:
self.current_profile_id = '1'
return True
def setProfileName(self, name, profile_id=None):
"""
Change the name of the profile.
Args:
name (str): new profile name
profile_id (str, int): valid profile ID
Returns:
bool: ``True`` if successful.
"""
if isinstance(profile_id, int):
profile_id = str(profile_id)
if profile_id is None:
profile_id = self.current_profile_id
profiles = self.profiles()
for profile in profiles:
if self.profileName(profile) == name:
if profile[0] != profile_id:
self.notifyError(_(
'Profile "{name}" already exists.').format(name=name))
return False
self.setProfileStrValue('name', name, profile_id)
return True
def profileKey(self, key, profile_id=None):
"""
Prefix for keys with profile. e.g. 'profile1.key'
Args:
key (str): Key identifier.
profile_id (str, int): Valid profile ID.
Returns:
str: Key with prefix 'profile1.key'
"""
if isinstance(profile_id, int):
profile_id = str(profile_id)
if profile_id is None:
profile_id = self.current_profile_id
return 'profile' + profile_id + '.' + key
def removeProfileKey(self, key, profile_id=None):
"""
Remove the key from profile.
Args:
key (str): key name
profile_id (str, int): valid profile ID
"""
self.removeKey(self.profileKey(key, profile_id))
def removeProfileKeysStartsWith(self, prefix, profile_id=None):
"""
Remove the keys starting with prefix from profile.
Args:
prefix (str): prefix for keys (key starts with this
string) that should be removed.
profile_id (str, int): valid profile ID
"""
self.removeKeysStartsWith(self.profileKey(prefix, profile_id))
def remapProfileKey(self, oldKey, newKey, profileId=None):
"""
Remap profile keys to a new key name.
Args:
oldKey (str): old key name
newKey (str): new key name
profileId (str, int): valid profile ID
"""
self.remapKey(self.profileKey(oldKey, profileId),
self.profileKey(newKey, profileId))
def hasProfileKey(self, key, profile_id=None):
"""
``True`` if key is set in profile.
Args:
key (str): string used as key
profile_id (str, int): valid profile ID
Returns:
bool: ``True`` if ``key`` is set.
"""
return self.profileKey(key, profile_id) in self.dict
def profileStrValue(self, key, default='', profile_id=None):
"""Return the value of ``key`` related to ``profile_id``.
Returns:
str: The value.
"""
return self.strValue(self.profileKey(key, profile_id), default)
def setProfileStrValue(self, key, value, profile_id=None):
self.setStrValue(self.profileKey(key, profile_id), value)
def profileIntValue(self, key, default=0, profile_id=None):
return self.intValue(self.profileKey(key, profile_id), default)
def setProfileIntValue(self, key, value, profile_id=None):
self.setIntValue(self.profileKey(key, profile_id), value)
def profileBoolValue(self, key, default=False, profile_id=None):
return self.boolValue(self.profileKey(key, profile_id), default)
def setProfileBoolValue(self, key, value, profile_id=None):
self.setBoolValue(self.profileKey(key, profile_id), value)
def profileListValue(self,
key,
type_key='str:value',
default=[],
profile_id=None):
return self.listValue(
self.profileKey(key, profile_id), type_key, default)
def setProfileListValue(self, key, type_key, value, profile_id=None):
self.setListValue(self.profileKey(key, profile_id), type_key, value)
|