Compare commits

...

2 Commits

Author SHA1 Message Date
378ebcebf6 second revision, logging output polished 2024-04-01 00:49:03 +02:00
5cd56f5f97 foo 2024-04-01 00:48:33 +02:00
5 changed files with 160 additions and 46 deletions

2
.idea/misc.xml generated
View File

@ -3,5 +3,5 @@
<component name="Black">
<option name="sdkName" value="Python 3.6 (pyuserconfig)" />
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.6 (pyuserconfig) (2)" project-jdk-type="Python SDK" />
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.12 (userconfig)" project-jdk-type="Python SDK" />
</project>

View File

@ -4,7 +4,7 @@
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/venv" />
</content>
<orderEntry type="jdk" jdkName="Python 3.6 (pyuserconfig) (2)" jdkType="Python SDK" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="TestRunnerService">

98
.idea/workspace.xml generated Normal file
View File

@ -0,0 +1,98 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AutoImportSettings">
<option name="autoReloadType" value="SELECTIVE" />
</component>
<component name="ChangeListManager">
<list default="true" id="cee80f0e-cafd-4941-b7a7-08488f062272" name="Changes" comment="">
<change beforePath="$PROJECT_DIR$/.idea/misc.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/misc.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/pyuserconfig.iml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/pyuserconfig.iml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/cli/__init__.py" beforeDir="false" afterPath="$PROJECT_DIR$/cli/__init__.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/userconfig/__init__.py" beforeDir="false" afterPath="$PROJECT_DIR$/userconfig/__init__.py" afterDir="false" />
</list>
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="Git.Settings">
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
</component>
<component name="ProjectColorInfo">{
&quot;associatedIndex&quot;: 2
}</component>
<component name="ProjectId" id="2eKxRWG4LxyRkMlusUvbQX9b4Vc" />
<component name="ProjectViewState">
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent"><![CDATA[{
"keyToString": {
"ASKED_ADD_EXTERNAL_FILES": "true",
"Python.__init__.executor": "Run",
"Python.cli.executor": "Run",
"Python.test.executor": "Run",
"Python.tools.executor": "Run",
"RunOnceActivity.OpenProjectViewOnStart": "true",
"RunOnceActivity.ShowReadmeOnStart": "true",
"SHARE_PROJECT_CONFIGURATION_FILES": "true",
"git-widget-placeholder": "reorg__checks",
"last_opened_file_path": "/Users/lysis/Documents/Repositories/lys.is/pyuserconfig",
"settings.editor.selected.configurable": "com.jetbrains.python.configuration.PyActiveSdkModuleConfigurable"
}
}]]></component>
<component name="RunManager">
<configuration name="test" type="PythonConfigurationType" factoryName="Python" nameIsGenerated="true">
<module name="pyuserconfig" />
<option name="ENV_FILES" value="" />
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs>
<env name="PYTHONUNBUFFERED" value="1" />
</envs>
<option name="SDK_HOME" value="" />
<option name="SDK_NAME" value="Python 3.12 (userconfig)" />
<option name="WORKING_DIRECTORY" value="$Sourcepath$" />
<option name="IS_MODULE_SDK" value="false" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<option name="SCRIPT_NAME" value="$PROJECT_DIR$/test.py" />
<option name="PARAMETERS" value="" />
<option name="SHOW_COMMAND_LINE" value="false" />
<option name="EMULATE_TERMINAL" value="false" />
<option name="MODULE_MODE" value="false" />
<option name="REDIRECT_INPUT" value="false" />
<option name="INPUT_FILE" value="" />
<method v="2" />
</configuration>
</component>
<component name="SharedIndexes">
<attachedChunks>
<set>
<option value="bundled-python-sdk-09665e90c3a7-d3b881c8e49f-com.jetbrains.pycharm.community.sharedIndexes.bundled-PC-233.15026.15" />
</set>
</attachedChunks>
</component>
<component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<changelist id="cee80f0e-cafd-4941-b7a7-08488f062272" name="Changes" comment="" />
<created>1711667063738</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1711667063738</updated>
</task>
<servers />
</component>
<component name="Vcs.Log.Tabs.Properties">
<option name="TAB_STATES">
<map>
<entry key="MAIN">
<value>
<State />
</value>
</entry>
</map>
</option>
</component>
</project>

View File

@ -15,7 +15,7 @@ class Debug:
_COLOR_YELLOW = '\033[93m'
_COLOR_END = '\33[0m'
_FORMAT = {'STANDARD': '',
_FORMAT = {'STANDARD': 'INFO: ',
'ERROR': f'{_COLOR_RED}ERROR:{_COLOR_END} ',
'NOTICE': f'{_COLOR_BLUE}NOTICE:{_COLOR_END} ',
'WARNING': f'{_COLOR_YELLOW}WARNING:{_COLOR_END} ',
@ -35,11 +35,15 @@ class Debug:
return self._verbose
def stdout(self, out, verbose_level=0, category='STANDARD'):
spaces = ''
if verbose_level > 1:
spaces = ' '*(verbose_level-1)
if self._verbose >= verbose_level:
if category in self._FORMAT:
print(f'{self._FORMAT[category]}{out}')
print(f'{spaces}{self._FORMAT[category]}{out}')
else:
print(f'[category {category} unknown]:{out}')
print(f'{spaces}[category {category} unknown]:{out}')
def stderr(self, out, verbose_level=0, category='STANDARD'):
if self._verbose >= verbose_level:
@ -74,11 +78,11 @@ def main():
debug = Debug()
# debug.set_verbose(cmdline.verbose)
# cfg = Conf(filename=cmdline.file, debug=debug)
debug.set_verbose(1)
cfg = Conf(filename='/home/lysis/userconfig2-test.conf', debug=debug)
debug.set_verbose(3)
cfg = Conf(filename='/Users/lysis/userconfig2-test.conf', debug=debug)
uc = Userconfig(cfg)
cfg.debug.stdout(f'Verbose level: {cfg.debug.get_verbose()}', 1, 'STANDARD')
cfg.debug.stdout(f'Verbose level: {cfg.debug.get_verbose()}', 1)
configdir = cfg.get('configdir')
# configdir is the root of the userconfig files
# Directory structure:
@ -107,6 +111,7 @@ def main():
cfg.debug.stdout(f'configdir: {configdir}', 1)
for package in os.scandir(configdir):
# Skip on non-production files
if not package.is_dir():
cfg.debug.stdout(f'{package.path} is not a directory, skipping', 2, 'WARNING')
continue
@ -115,12 +120,13 @@ def main():
if os.path.isfile(f'{package.path}/.ignore'):
cfg.debug.stdout(f'{package.path} contains .ignore, skipping', 2, 'WARNING')
continue
cfg.debug.stdout(f'Package: {package.path}', 1, 'NOTICE')
cfg.debug.stdout(f'============ start {cfg.debug.green(package.path)} ============', 2)
# Start processing
cfg.debug.stdout(f'Start Package {cfg.debug.green(package.path)}', 1, 'NOTICE')
# Get all category directories for package
(category_dirs, dir_config) = uc.process_package_dir(package.path)
cfg.debug.stdout(f'Got categories: {category_dirs}', 2)
host_category_dirs = uc.filter_categories(category_dirs)
cfg.debug.stdout(f'Filtered categories for host: {host_category_dirs}', 2)
cfg.debug.stdout(f'Host uses categories: {", ".join([f'{v[1]}_{v[2]}' for v in host_category_dirs])}', 2)
file_list = dict()
for c in host_category_dirs:
file_list = uc.process_category_dir(c, file_list)
@ -130,16 +136,26 @@ def main():
subprocess.call([f'{package.path}/install.sh'])
for file in file_list:
dest = f'{dir_config.get(section="Main", option="dest")}/{file}'
cfg.debug.stdout(f'Generating {dest} from:\n {"\n ".join(file_list[file])}', 1)
try:
comment_string = dir_config.get(section="Main", option="commentstring")
except ValueError:
cfg.debug.stdout(f'commentstring does not exist in config file {dir_config._cfgfiles}', 0, 'ERROR')
sys.exit(1)
# Make sure all directories for destination file exist
uc.create_destination_directories(dir_config.get(section="Main", option="dest"))
if uc.create_destination_directories(dir_config.get(section="Main", option="dest")):
cfg.debug.stdout(f'Created target directories {cfg.debug.green(dir_config.get(section="Main", option="dest"))}',
0, 'SUCCESS')
else:
cfg.debug.stdout(f'All target directories exist', 2)
temp_filename = uc.build_file(file_list[file], dest, comment_string)
uc.diff_and_copy_file(temp_filename, dest, comment_string)
cfg.debug.stdout(f'============ end {cfg.debug.green(package.path)} ============\n\n', 2)
if uc.diff_and_copy_file(temp_filename, dest, comment_string):
cfg.debug.stdout(f'Copy {temp_filename} -> {cfg.debug.green(dest)} (changed)\n', 0, 'SUCCESS')
else:
cfg.debug.stdout(f'Generated file and destination are the same.\n', 1)
cfg.debug.stdout(f'End Package {cfg.debug.green(package.path)}\n\n', 1, 'NOTICE')
if __name__ == '__main__':

View File

@ -23,24 +23,24 @@ class Userconfig:
:param package_dir: root of package directory
:return: list of tuples (prio, category, value, path), sorted with prio
"""
self._cfg.debug.stdout(f'*** process package {package_dir}', 3)
self._cfg.debug.stdout(f'process package_dir {package_dir}', 3)
package_config_file = f'{package_dir}/{self._cfg.get("configfile")}'
if not os.path.isfile(package_config_file):
self._cfg.debug.stdout(f'No config file {self._cfg.get("configfile")} in {package_dir}, skipping',
1, 'ERROR')
0, 'ERROR')
return None
dir_config = self.get_config(package_config_file)
if not dir_config:
self._cfg.debug.stdout(f'Cannot read config file {package_config_file}, skipping', 1, 'ERROR')
self._cfg.debug.stdout(f'Cannot read config file {package_config_file}, skipping', 0, 'ERROR')
return None
classes = []
for category in os.scandir(package_dir):
if category.path == package_config_file:
continue
if not category.is_dir():
self._cfg.debug.stdout(f'{category.path} is not a directory, skipping', 3, 'WARNING')
self._cfg.debug.stdout(f'{category.path} is not a directory, skipping', 3)
continue
self._cfg.debug.stdout(f'****** process category {category.path}', 3)
self._cfg.debug.stdout(f'process category {category.path}', 3)
content = category.name.split('_')
# Format: <number>_<category>_<value>
if len(content) == 3:
@ -52,14 +52,14 @@ class Userconfig:
category_name = content[1]
value = ''
else:
self._cfg.debug.stdout(f'Format of package directory {category.path} wrong, skipping', 1, 'ERROR')
self._cfg.debug.stdout(f'Format of package directory {category.path} wrong, skipping', 0, 'ERROR')
continue
try:
prio = int(prio_string)
except ValueError:
self._cfg.debug.stdout(f'Cannot convert prio to integer ({category.path}, skipping', 1, 'ERROR')
self._cfg.debug.stdout(f'Cannot convert prio to integer ({category.path}, skipping', 0, 'ERROR')
continue
# self._cfg.debug.stdout(f'****** Got class: {(prio, category_name, value)}', 3)
# self._cfg.debug.stdout(f'Got class: {(prio, category_name, value)}', 3)
classes.append((prio, category_name, value, category.path))
classes.sort(key=lambda k: k[0])
return classes, dir_config
@ -74,7 +74,7 @@ class Userconfig:
ret = []
for c in categories:
if not c[1]:
self._cfg.debug.stdout(f'category not set for {c[3]}, skipping', 3, 'WARNING')
self._cfg.debug.stdout(f'category not set for {c[3]}, skipping', 0, 'ERROR')
continue
if check_class(c):
ret.append(c)
@ -89,7 +89,7 @@ class Userconfig:
:return:
"""
(prio, category, value, category_dir) = category_dir_tuple
self._cfg.debug.stdout(f'*** process category {category_dir}', 3)
self._cfg.debug.stdout(f'process category {category_dir}', 3)
for file in os.scandir(category_dir):
if file.name not in file_list:
file_list[file.name] = []
@ -107,7 +107,7 @@ class Userconfig:
"""
content = []
self._cfg.debug.stdout(f'*** building file for {dest_file}', 3)
self._cfg.debug.stdout(f'building file for {dest_file}', 3)
if comment_string:
content.append(f'{comment_string} {self._cfg.get("stamp")} {time.strftime("%+")}\n')
for file in files:
@ -124,7 +124,7 @@ class Userconfig:
try:
fp = os.fdopen(temp_fd, "w")
except Exception as e:
self._cfg.debug.stderr(f"Cannot write to temporary file {temp_filename}: {e}", 0, 'ERROR')
self._cfg.debug.stderr(f'Cannot write to temporary file {temp_filename}: {e}', 0, 'ERROR')
os.remove(temp_filename)
return False
self._cfg.debug.stdout(f'Writing merged files into temporary file {temp_filename}', 3)
@ -135,32 +135,35 @@ class Userconfig:
return temp_filename
def diff_and_copy_file(self, temp_filename, dest_filename, comment_string):
ret = False
if self.diff(dest_filename, temp_filename, comment_string):
self._cfg.debug.stdout(f"File {dest_filename} has changed", 0, 'NOTICE')
if not self.user_config_generated(dest_filename):
self._cfg.debug.stdout(f"{dest_filename} not generated by userconfig, backing up.", 3)
self._cfg.debug.stdout(f'{dest_filename} not generated by userconfig, running back_up.', 3)
self.backup_file(dest_filename)
self._cfg.debug.stdout(f"Copy {temp_filename} to {dest_filename}", 0, 'NOTICE')
self.copy_file(temp_filename, dest_filename)
self._cfg.debug.stdout(f"Removing temporary file {temp_filename}", 3)
ret = True
os.remove(temp_filename)
self._cfg.debug.stdout(f'Removed temporary file {temp_filename}', 3, 'SUCCESS')
return ret
def create_destination_directories(self, dest_directory):
self._cfg.debug.stdout(f'*** Creating {dest_directory} if needed', 3)
path = Path(dest_directory)
if not path.exists():
path.mkdir(parents=True)
return True
else:
return False
def get_config(self, filename):
"""reads filename as config, checks for DEST parameter and returns cfgfile object"""
try:
ret = Conf(filename=filename, debug=self._cfg.debug, force_filename=True)
except ValueError:
self._cfg.debug.stderr("Error reading config file %s" % filename)
self._cfg.debug.stderr(f'Error reading config file {filename}', 0, 'ERROR')
return False
# check for DEST parameter
if not ret.check(section="Main", option="dest"):
self._cfg.debug.stderr("No dest in config file %s" % filename)
self._cfg.debug.stderr(f'No dest in config file {filename}', 0, 'ERROR')
return False
# make sure DEST ends with /
if not ret.get(section="Main", option="dest").endswith("/"):
@ -179,14 +182,12 @@ class Userconfig:
def diff(self, dest_file, temp_file, comment_string):
"""diff dest_file and temp_file, returns True if files differ, False if they are the same"""
self._cfg.debug.stdout("Diffing %s and %s, comment: %s" % (dest_file, temp_file, comment_string), 3)
self._cfg.debug.stdout(f'Diffing {dest_file} and {temp_file}, comment: {comment_string}', 3)
if not os.path.isfile(dest_file):
self._cfg.debug.stdout("Destination file %s does not exist, returning True." % dest_file, 3)
# dest_file does not exist -> copy temp_file over
self._cfg.debug.stdout(f'dest_file {dest_file} does not exist.', 3)
return True
if not os.path.isfile(temp_file):
# temp_file does not exist, this should never happen
self._cfg.debug.stderr("Temporary file %s does not exist, this should not happen." % temp_file)
self._cfg.debug.stderr(f'Temporary file {temp_file} does not exist, this should not happen.', 0, 'ERROR')
sys.exit(1)
fp1 = open(temp_file)
@ -196,11 +197,11 @@ class Userconfig:
if line1 != line2:
fp1.close()
fp2.close()
self._cfg.debug.stdout("%s differs, return true" % dest_file, 3)
self._cfg.debug.stdout(f'{dest_file} differs from generated config', 3)
return True
fp1.close()
fp2.close()
self._cfg.debug.stdout("%s is the same, return false" % dest_file, 3)
self._cfg.debug.stdout(f'{dest_file} is the same as generated config', 3)
return False
def user_config_generated(self, filename):
@ -224,18 +225,18 @@ class Userconfig:
def backup_file(self, filename):
"""make backup of filename, returns True if backup is successful, False else"""
if os.path.isfile(filename):
self._cfg.debug.stdout("%s exists, finding backup name." % filename, 3)
self._cfg.debug.stdout(f'{filename} exists, finding backup name.', 3)
backup_name = filename+".userconfig."+time.strftime("%F")
test_backup_name = backup_name
counter = 0
while os.path.isfile(test_backup_name):
counter += 1
test_backup_name = backup_name+"."+str(counter)
self._cfg.debug.stdout("Renaming %s to %s" % (filename, test_backup_name), 1)
os.rename(filename, test_backup_name)
self._cfg.debug.stdout(f'Renamed {filename} to {test_backup_name}', 1, 'SUCCESS')
return True
else:
self._cfg.debug.stdout("%s does not exist, do not need backup." % filename, 3)
self._cfg.debug.stdout(f'{filename} does not exist, do not need backup.', 3)
return False
def copy_file(self, sourcefile, dest_file):
@ -243,11 +244,10 @@ class Userconfig:
if os.path.isfile(sourcefile):
# sourcefile exists
self._cfg.debug.stdout("Source file %s exists, proceeding with copy." % sourcefile, 3)
self._cfg.debug.stdout(f'Source file {sourcefile} exists, proceeding with copy.', 3)
if not os.path.isfile(dest_file) or os.access(dest_file, os.W_OK):
self._cfg.debug.stdout("Copying %s to %s" % (sourcefile, dest_file), 1)
shutil.copy(sourcefile, dest_file)
return True
else:
self._cfg.debug.stdout("Destination file %s does not exist or is not writable." % dest_file, 3)
self._cfg.debug.stdout('Destination {dest_file} is not a file or not writable.', 0, 'ERROR')
return False