cjnfuncs 3.2.2__tar.gz → 3.2.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cjnfuncs
3
- Version: 3.2.2
3
+ Version: 3.2.4
4
4
  Summary: A collection of core functions for tool script writing
5
5
  Author-email: Chris Nelson <github@cjnaz.com>
6
6
  License-Expression: MIT
@@ -35,7 +35,7 @@ module | Description/Purpose
35
35
  [resourcelock](https://github.com/cjnaz/cjnfuncs/blob/main/resourcelock.md) | Inter-process resource lock mechanism
36
36
  [SMTP](https://github.com/cjnaz/cjnfuncs/blob/main/SMTP.md) | Send notification and email messages
37
37
 
38
- Developed and tested on Python 3.9.21 and supported on all higher Python versions.
38
+ Developed and tested on Python 3.9, 3.11, and 3.13. Supported on all higher Python versions.
39
39
  Developed on Linux. Supported on Windows, except for the resourcelock module (posix-ipc module dependency).
40
40
 
41
41
  In this documentation, "tool script" refers to a Python project that imports and uses cjnfuncs. Some may be simple scripts, and others may themselves be installed packages.
@@ -58,7 +58,20 @@ Project repo: https://github.com/cjnaz/cjnfuncs
58
58
 
59
59
  <br/>
60
60
 
61
- ## Key changes since the prior major public release (version 3.0)
61
+ ## Key changes since the prior major public release (version 3.1)
62
+
63
+ 3.2.4 changes
64
+ - Minor, isolated changes
65
+ - core - trap/warning for attempting to open logging to file owned by root
66
+ - resourcelock - added /dev/shm deleted files note
67
+
68
+ 3.2.3 changes
69
+ - Minor, isolated changes
70
+ - configman.write() - the target directory tree is created if not existing, oneliner comment at top of written file
71
+ - configman.write() - config_timestamp only updated when written by persistent_config.save()
72
+ - configman.loadconfig() - remap_logdirbase is disabled for secondary configs
73
+ - configman tuned up debug logging
74
+ - resource lock moved signal traps inside of cli(), else they become global to the entire application -->
62
75
 
63
76
  3.2.2 change
64
77
  - periodic_log output now includes `[category - <package>.<module>.<function>(<line number>)]` for debug traceability of where the log event came from.
@@ -73,31 +86,15 @@ script restarts and system reboots.
73
86
  - Shared memory block handling - Extending resourcelock's features, read/write access is provided to the shared memory block associated with
74
87
  a user-defined lock.
75
88
 
76
-
77
- 3.1 changes
78
- - Several issues with Windows support were fixed.
79
-
80
- - `configman.config_item()` now supports a safe_mode switch, which will speed up Windows usage of loadconfig() at some risk. See the note on `config_item()`.
81
-
82
- - Named child loggers are now implemented on several cjnfuncs modules. By default, logging from cjnfuncs modules is disabled (internal logging events are usually at the INFO or DEBUG
83
- level, while the default logging level is set to WARNING). For example, logging from configman may be enabled by `logging.getLogger('cjnfuncs.configman').setLevel(logging.INFO)`,
84
- or using `core.set_logging_level(logging.INFO, 'cjnfuncs.configman')`.
85
-
86
- - Changed mungePath set_attributes from default True to default False to avoid long processing time on Windows by default.
87
-
88
- - deployfiles can now create an empty target directory.
89
-
90
- 3.1.1 changes
91
- - get_next_dt now supports a days or weeks offset for the days arg
92
- - Added separate child logger `cjnfuncs.resourcelock_islocked` so that `is_locked()` may be called in a loop without flooding the log while `cjnfuncs.resourcelock` is set to debug
93
-
94
89
  <br/>
95
90
 
96
91
  ## Revision history
97
92
 
98
- - 3.2.2 - 261002 - periodic_log output now includes `[category - <package>.<module>.<function>(<line number>)]` for debug traceability of where the log event came from.
99
- - 3.2.1 - 260526 - periodic_log now returns True/False whether the the call was logged. Minor changes in resourcelock.
100
- - 3.2 - 260506 - New features: persistent_config and shared memory block handling
93
+ - 3.2.4 261124 - core: trap/warning for attempting to open logging to file owned by root, added resourcelock /dev/shm deleted files note
94
+ - 3.2.3 261022 - Minor, isolated features tuning to configman and resource_lock
95
+ - 3.2.2 261002 - periodic_log output now includes `[category - <package>.<module>.<function>(<line number>)]` for debug traceability of where the log event came from.
96
+ - 3.2.1 260526 - periodic_log now returns True/False whether the the call was logged. Minor changes in resourcelock.
97
+ - 3.2 260506 - New features: persistent_config and shared memory block handling
101
98
  - 3.1.1 260207 - separate resourcelock_islocked logger, get_next_dt days/weeks offset
102
99
  - 3.1 251109
103
100
  Support for and use of child loggers,
@@ -15,7 +15,7 @@ module | Description/Purpose
15
15
  [resourcelock](https://github.com/cjnaz/cjnfuncs/blob/main/resourcelock.md) | Inter-process resource lock mechanism
16
16
  [SMTP](https://github.com/cjnaz/cjnfuncs/blob/main/SMTP.md) | Send notification and email messages
17
17
 
18
- Developed and tested on Python 3.9.21 and supported on all higher Python versions.
18
+ Developed and tested on Python 3.9, 3.11, and 3.13. Supported on all higher Python versions.
19
19
  Developed on Linux. Supported on Windows, except for the resourcelock module (posix-ipc module dependency).
20
20
 
21
21
  In this documentation, "tool script" refers to a Python project that imports and uses cjnfuncs. Some may be simple scripts, and others may themselves be installed packages.
@@ -38,7 +38,20 @@ Project repo: https://github.com/cjnaz/cjnfuncs
38
38
 
39
39
  <br/>
40
40
 
41
- ## Key changes since the prior major public release (version 3.0)
41
+ ## Key changes since the prior major public release (version 3.1)
42
+
43
+ 3.2.4 changes
44
+ - Minor, isolated changes
45
+ - core - trap/warning for attempting to open logging to file owned by root
46
+ - resourcelock - added /dev/shm deleted files note
47
+
48
+ 3.2.3 changes
49
+ - Minor, isolated changes
50
+ - configman.write() - the target directory tree is created if not existing, oneliner comment at top of written file
51
+ - configman.write() - config_timestamp only updated when written by persistent_config.save()
52
+ - configman.loadconfig() - remap_logdirbase is disabled for secondary configs
53
+ - configman tuned up debug logging
54
+ - resource lock moved signal traps inside of cli(), else they become global to the entire application -->
42
55
 
43
56
  3.2.2 change
44
57
  - periodic_log output now includes `[category - <package>.<module>.<function>(<line number>)]` for debug traceability of where the log event came from.
@@ -53,31 +66,15 @@ script restarts and system reboots.
53
66
  - Shared memory block handling - Extending resourcelock's features, read/write access is provided to the shared memory block associated with
54
67
  a user-defined lock.
55
68
 
56
-
57
- 3.1 changes
58
- - Several issues with Windows support were fixed.
59
-
60
- - `configman.config_item()` now supports a safe_mode switch, which will speed up Windows usage of loadconfig() at some risk. See the note on `config_item()`.
61
-
62
- - Named child loggers are now implemented on several cjnfuncs modules. By default, logging from cjnfuncs modules is disabled (internal logging events are usually at the INFO or DEBUG
63
- level, while the default logging level is set to WARNING). For example, logging from configman may be enabled by `logging.getLogger('cjnfuncs.configman').setLevel(logging.INFO)`,
64
- or using `core.set_logging_level(logging.INFO, 'cjnfuncs.configman')`.
65
-
66
- - Changed mungePath set_attributes from default True to default False to avoid long processing time on Windows by default.
67
-
68
- - deployfiles can now create an empty target directory.
69
-
70
- 3.1.1 changes
71
- - get_next_dt now supports a days or weeks offset for the days arg
72
- - Added separate child logger `cjnfuncs.resourcelock_islocked` so that `is_locked()` may be called in a loop without flooding the log while `cjnfuncs.resourcelock` is set to debug
73
-
74
69
  <br/>
75
70
 
76
71
  ## Revision history
77
72
 
78
- - 3.2.2 - 261002 - periodic_log output now includes `[category - <package>.<module>.<function>(<line number>)]` for debug traceability of where the log event came from.
79
- - 3.2.1 - 260526 - periodic_log now returns True/False whether the the call was logged. Minor changes in resourcelock.
80
- - 3.2 - 260506 - New features: persistent_config and shared memory block handling
73
+ - 3.2.4 261124 - core: trap/warning for attempting to open logging to file owned by root, added resourcelock /dev/shm deleted files note
74
+ - 3.2.3 261022 - Minor, isolated features tuning to configman and resource_lock
75
+ - 3.2.2 261002 - periodic_log output now includes `[category - <package>.<module>.<function>(<line number>)]` for debug traceability of where the log event came from.
76
+ - 3.2.1 260526 - periodic_log now returns True/False whether the the call was logged. Minor changes in resourcelock.
77
+ - 3.2 260506 - New features: persistent_config and shared memory block handling
81
78
  - 3.1.1 260207 - separate resourcelock_islocked logger, get_next_dt days/weeks offset
82
79
  - 3.1 251109
83
80
  Support for and use of child loggers,
@@ -1,6 +1,13 @@
1
1
  [project]
2
2
  name = 'cjnfuncs'
3
- version = '3.2.2'
3
+ version = '3.2.4'
4
+ # 3.2.4 261124 Release - core: trap/warning for attempting to open logging to file owned by root, added resourcelock /dev/shm deleted files note
5
+ # 3.2.3 261022 Release
6
+ # configman.write() - the target directory tree is created if not existing, oneliner comment at top of written file
7
+ # configman.write() - config_timestamp only updated when written by persistent_config.save()
8
+ # configman.loadconfig() - remap_logdirbase is disabled for secondary configs
9
+ # configman tuned up debug logging
10
+ # resource lock moved signal traps inside of cli(), else they become global to the entire application
4
11
  # 3.2.2 261002 Release - periodic_log [category - <package>.<module>.<function>(<line number>)]
5
12
  # 3.2.1 - Release
6
13
  # resourcelock info level log on lock unget request ignored if lock not owned by current process and not forced
@@ -58,7 +58,7 @@ See the loadconfig() documentation for details on config file syntax and rules.
58
58
  ### Instantiation args
59
59
  `config_file` (Path or str, default None)
60
60
  - Path to the configuration file, relative to the `core.tool.config_dir` directory, or an absolute path.
61
- - `None` may be used if the config will be loaded programmatically via `read_string()` or `read_dict()`.
61
+ - `None` may be used if the config will be loaded programmatically, for example via `read_string()` or `set_cfg()`.
62
62
 
63
63
  `remap_logdirbase` (bool, default True)
64
64
  - If `remap_logdirbase=True` and the tool script is running in _user_ mode (not site mode)
@@ -184,7 +184,7 @@ produces no logging events from this module), eg:
184
184
  else:
185
185
  raise ConfigError (f"Config file <{config_file}> not found.")
186
186
 
187
- if remap_logdirbase and core.tool.log_dir_base == core.tool.user_data_dir:
187
+ if not secondary_config and remap_logdirbase and core.tool.log_dir_base == core.tool.user_data_dir:
188
188
  core.tool.log_dir_base = core.tool.config_dir
189
189
 
190
190
 
@@ -382,14 +382,10 @@ cannot be accessed.
382
382
 
383
383
  if force_reload:
384
384
  if not flush_on_reload:
385
- configman_logger.info(f"Config <{self.config_file}> Force reload, not flushed")
385
+ configman_logger.info(f"Load config <{self.config_file}> - Force reload, not flushed")
386
386
  else:
387
387
  self.clear()
388
- configman_logger.info(f"Config <{self.config_file}> Force reload, flushed first")
389
- # configman_logger.info(f"Config <{self.config_file}> force reloaded (force_reload)")
390
- # if flush_on_reload:
391
- # self.clear()
392
- # configman_logger.info(f"Config <{self.config_file}> flushed (flush_on_reload)")
388
+ configman_logger.info(f"Load config <{self.config_file}> - Force reload, flushed first")
393
389
  self.config_timestamp = 0 # Force reload of the config file
394
390
 
395
391
  # Check if config file is available and has changed
@@ -403,7 +399,7 @@ cannot be accessed.
403
399
 
404
400
  if not _exists:
405
401
  if tolerate_missing:
406
- configman_logger.info (f"Config <{self.config_file}> file not currently accessible. Skipping (re)load.")
402
+ configman_logger.info (f"Config <{self.config_file}> file not currently accessible - Skipping (re)load.")
407
403
  return -1 # -1 indicates that the config file cannot currently be found
408
404
  else:
409
405
  raise ConfigError (f"Could not find <{self.config_file}>")
@@ -417,23 +413,18 @@ cannot be accessed.
417
413
  if prereload_callback:
418
414
  configman_logger.debug("Pre-reload callback user function called")
419
415
  prereload_callback()
420
- configman_logger.info (f"Config <{self.config_file}> file timestamp: {current_timestamp}")
416
+ configman_logger.debug (f"Config <{self.config_file}> file timestamp: {current_timestamp}")
421
417
 
422
418
  if not force_reload:
423
419
  if not self.loaded:
424
- configman_logger.info(f"Config <{self.config_file}> Initial load")
420
+ configman_logger.info(f"Load config <{self.config_file}> - Initial load")
425
421
  # self.loaded = True
426
422
  else:
427
423
  if not flush_on_reload:
428
- configman_logger.info(f"Config <{self.config_file}> Reload due to changed file, not flushed")
424
+ configman_logger.info(f"Load config <{self.config_file}> - Reload due to changed file, not flushed")
429
425
  else:
430
426
  self.clear()
431
- configman_logger.info(f"Config <{self.config_file}> Reload due to changed file, flushed first")
432
-
433
- # if flush_on_reload:
434
- # if not force_reload:
435
- # configman_logger.info (f"Config <{self.config_file}> flushed due to changed file (flush_on_reload)")
436
- # self.clear()
427
+ configman_logger.info(f"Load config <{self.config_file}> - Reload due to changed file, flushed first")
437
428
 
438
429
 
439
430
  # Load the config
@@ -441,7 +432,8 @@ cannot be accessed.
441
432
  # An exception raised within read_string() while processing an imported config lands at this except clause, and is re-raised
442
433
  # to be handled at the next higher level, until we reach the top-level loadconfig() call, and the exception is passed to the
443
434
  # tool script code.
444
- configman_logger.info (f"Loading <{config}>")
435
+ if not isimport:
436
+ configman_logger.debug (f"Loading <{config}>")
445
437
  try:
446
438
  string_blob = config.read_text() # Minor hang risk - above exists check should protect
447
439
  self.read_string (string_blob, isimport=isimport)
@@ -524,7 +516,6 @@ flush_on_reload, force_reload, and tolerate_missing.
524
516
  find_comment_re = re.compile(xx, re.VERBOSE) # Find unquoted '#'
525
517
  section_name_re = re.compile(r'\[([^\]]*)\]') # Get section name
526
518
 
527
-
528
519
  for line in str_blob.split('\n'):
529
520
 
530
521
  if line.strip().startswith('['): # Section
@@ -535,6 +526,7 @@ flush_on_reload, force_reload, and tolerate_missing.
535
526
  if section_name != '' and section_name not in self.sections_list and section_name != 'DEFAULT':
536
527
  self.cfg[section_name] = {}
537
528
  self.sections_list.append(section_name)
529
+ configman_logger.debug (f"Opened section [{section_name}]")
538
530
  if section_name is None:
539
531
  raise ConfigError (f"Malformed section line <{line}>")
540
532
  else:
@@ -568,14 +560,17 @@ flush_on_reload, force_reload, and tolerate_missing.
568
560
  if param_name != '':
569
561
  if param_name.lower().startswith('import'): # import line
570
562
  target = mungePath(value_portion, self.config_dir).full_path
563
+ configman_logger.debug (f"Importing <{target}>")
571
564
  imported_config = config_item(target, secondary_config=True)
572
565
  imported_config.loadconfig(isimport=True) # May raise exception, caught by higher level
573
566
  for key in imported_config.cfg:
574
567
  if self.current_section_name == '':
575
568
  self.cfg[key] = imported_config.cfg[key]
576
569
  elif self.current_section_name == 'DEFAULT':
570
+ configman_logger.debug (f"param <{key}> placed in section [DEFAULT]")
577
571
  self.defaults[key] = imported_config.cfg[key]
578
572
  else:
573
+ configman_logger.debug (f"param <{key}> placed in section [{self.current_section_name}]")
579
574
  self.cfg[self.current_section_name][key] = imported_config.cfg[key]
580
575
  else: # param - value line
581
576
  if value_portion.lower() == 'true':
@@ -590,7 +585,8 @@ flush_on_reload, force_reload, and tolerate_missing.
590
585
  except:
591
586
  pass # default to str
592
587
  self._add_key(param_name, value_portion, self.current_section_name)
593
- configman_logger.debug (f"Loaded {param_name} = <{value_portion}> ({type(value_portion)})")
588
+ configman_logger.debug(f"Loaded <[{self.current_section_name}] {param_name}>: <{value_portion}> ({type(value_portion)})")
589
+
594
590
  self.loaded = True
595
591
 
596
592
 
@@ -649,6 +645,7 @@ Loaded content is added to and/or modifies any previously loaded content.
649
645
  ```
650
646
  """
651
647
 
648
+ configman_logger.debug(f"Loading config from dict to section <{section}>")
652
649
  try:
653
650
  if section == '':
654
651
  for key in param_dict:
@@ -735,7 +732,8 @@ This can lead to cleaner tool script code. Either access method may be used, al
735
732
 
736
733
  if _value == '__nonevalue__':
737
734
  if fallback != '_nofallback':
738
- return fallback
735
+ _value = fallback
736
+ # return fallback
739
737
  else:
740
738
  raise ConfigError (f"Param <[{section}] {param}> not in <{self.config_file}> and no default or fallback.")
741
739
  else:
@@ -743,13 +741,18 @@ This can lead to cleaner tool script code. Either access method may be used, al
743
741
  if isinstance(types, type):
744
742
  types = [types]
745
743
 
746
- if types == []:
747
- return _value
748
- else:
749
- if type(_value) in types:
750
- return _value
751
- else:
752
- raise ConfigError (f"Config parameter <[{section}] {param}> value <{_value}> type {type(_value)} not of expected type(s): {types}")
744
+ if types != [] and type(_value) not in types:
745
+ raise ConfigError (f"Config parameter <[{section}] {param}> value <{_value}> type {type(_value)} not of expected type(s): {types}")
746
+ # if types == []:
747
+ # return _value
748
+ # else:
749
+ # if type(_value) in types:
750
+ # return _value
751
+ # else:
752
+ # raise ConfigError (f"Config parameter <[{section}] {param}> value <{_value}> type {type(_value)} not of expected type(s): {types}")
753
+
754
+ configman_logger.debug(f"Retrieved <[{section}] {param}> (fallback <{fallback}>, expected types <{types}>): <{_value}> ")
755
+ return _value
753
756
 
754
757
 
755
758
  #=====================================================================================
@@ -800,7 +803,7 @@ This can lead to cleaner tool script code. Either access method may be used, al
800
803
  self.sections_list.append(section)
801
804
 
802
805
  self.cfg[section][param] = value
803
- configman_logger.debug (f"Set [{section}] {param} = <{value}> ({type(value)})")
806
+ configman_logger.debug (f"Set <[{section}] {param}> = <{value}> ({type(value)})")
804
807
 
805
808
 
806
809
  #=====================================================================================
@@ -837,7 +840,7 @@ This can lead to cleaner tool script code. Either access method may be used, al
837
840
  if section == '': # Top-level case
838
841
  if param in self.cfg:
839
842
  del self.cfg[param]
840
- configman_logger.debug (f"Removed [{section}] {param}")
843
+ configman_logger.debug (f"Removed <[{section}] {param}>")
841
844
  return
842
845
  elif missing_ok:
843
846
  return
@@ -846,7 +849,8 @@ This can lead to cleaner tool script code. Either access method may be used, al
846
849
  elif section == 'DEFAULT': # DEFAULT case
847
850
  if param in self.defaults:
848
851
  del self.defaults[param]
849
- configman_logger.debug (f"Removed [{section}] {param}")
852
+ configman_logger.debug (f"Removed <[{section}] {param}>")
853
+ # configman_logger.debug (f"Removed [{section}] {param}")
850
854
  return
851
855
  elif missing_ok:
852
856
  return
@@ -857,7 +861,8 @@ This can lead to cleaner tool script code. Either access method may be used, al
857
861
  raise ConfigError (f"Section <{section}> not found in config {self.config_file}")
858
862
  if param in self.cfg[section]:
859
863
  del self.cfg[section][param]
860
- configman_logger.debug (f"Removed [{section}] {param}")
864
+ configman_logger.debug (f"Removed <[{section}] {param}>")
865
+ # configman_logger.debug (f"Removed [{section}] {param}")
861
866
  return
862
867
  elif missing_ok:
863
868
  return
@@ -957,6 +962,7 @@ reload call to avoid multiple config reloads.
957
962
  else:
958
963
  found_param = True
959
964
  if remove == True:
965
+ configman_logger.debug (f"Removed <{param}>")
960
966
  continue # just don't save the line
961
967
 
962
968
  # Update value for the current line
@@ -967,16 +973,18 @@ reload call to avoid multiple config reloads.
967
973
  if len_current_whitespace == 0:
968
974
  len_new_whitespace = 0
969
975
  updated_content += out.group(1) + out.group(2) + out.group(3) + value + ' '*len_new_whitespace + out.group(5) + '\n'
976
+ configman_logger.debug (f"Modified <{param}> to new value <{value}>")
970
977
  else:
971
978
  updated_content += line + '\n'
972
979
 
973
- if found_param == False:
974
- if add_if_not_existing == True:
980
+ if not found_param:
981
+ if add_if_not_existing:
975
982
  updated_content += f"{param} {value}\n"
983
+ configman_logger.debug (f"Added new <{param}>: <{value}>")
976
984
  elif param=='' and value=='' and save==True: # Save-only call
977
985
  pass
978
986
  else:
979
- configman_logger.warning (f"Modification of param <{param}> failed - not found in config file. Modification skipped.")
987
+ configman_logger.warning (f"Modify of param <{param}> failed - not found in config file. Modification skipped.")
980
988
 
981
989
  self.config_content = updated_content[:-1] # Avoid adding extra \n at end of file
982
990
 
@@ -986,6 +994,7 @@ reload call to avoid multiple config reloads.
986
994
  else:
987
995
  self.config_full_path.write_text(self.config_content)
988
996
  self.config_content = ''
997
+ configman_logger.debug (f"Saved modified config to <{self.config_full_path}>")
989
998
 
990
999
 
991
1000
  #=====================================================================================
@@ -994,18 +1003,27 @@ reload call to avoid multiple config reloads.
994
1003
  #=====================================================================================
995
1004
  #=====================================================================================
996
1005
 
997
- def write(self, savefile):
1006
+ def write(self, savefile, oneliner=None, update_timestamp=False):
998
1007
  """
999
1008
  ## write (savefile) - Write config data to a file
1000
1009
 
1001
1010
  ***config_item() class member function***
1002
1011
 
1003
1012
 
1004
- ### Arg
1013
+ ### Args
1005
1014
  `savefile` (Path or str)
1006
1015
  - Path to the output file.
1007
1016
  - The config data will be written to an absolute path, or relative to the `core.tool.config_dir`
1017
+ - The target directory tree is created, as needed.
1018
+
1019
+ `oneliner` (str or None, default None)
1020
+ - A header comment line placed as the first line in the `savefile`
1021
+ - The `oneliner` text is prefixed with '# '
1008
1022
 
1023
+ `update_timestamp` (bool, default False)
1024
+ - Generally, this is for internal use.
1025
+ - If True, forces the config_item loaded config timestamp to be updated when write() is called.
1026
+ Used by the persistent_config class save() method to force the underlying config_item config timestamp to updated on save.
1009
1027
 
1010
1028
  ### Returns
1011
1029
  - None on success
@@ -1013,38 +1031,65 @@ reload call to avoid multiple config reloads.
1013
1031
 
1014
1032
 
1015
1033
  ### Behaviors and rules
1016
- - The created config file is as loaded in memory. Any imports in the originally loaded config file
1017
- are merged into the top-level.
1034
+ - The written file is as loaded in memory.
1035
+ - Any imported params in the originally loaded config file are effectively merged into the top-level.
1036
+ - Any comments in the originally loaded config file are lost.
1037
+ - While `savefile` and the instantiation `config_file` may reference the same file, they are treated independently.
1038
+ - By default, the class attribute `config_timestamp` is not updated by `write()` (`config_timestamp` is only updated by a call to loadconfig).
1039
+ - The class attribute `config_file` is not updated by `write().`
1040
+ - The class instantiation `safe_mode` setting is honored/followed.
1041
+ - The `[DEFAULTS]` section is only written out if there are defaults defined in the loaded config.
1018
1042
  """
1019
1043
 
1020
1044
  cfg_list = ''
1045
+
1046
+ if oneliner:
1047
+ cfg_list += f"# {oneliner}\n"
1048
+
1021
1049
  for key in self.cfg:
1022
1050
  if key not in self.sections_list:
1023
1051
  if type(self.cfg[key]) is str and '#' in self.cfg[key]:
1024
1052
  cfg_list += f"{key:20} = '''{self.cfg[key]}'''\n"
1025
1053
  else:
1026
1054
  cfg_list += f"{key:20} = {self.cfg[key]}\n"
1027
- cfg_list += '\n[DEFAULT]\n'
1055
+
1056
+ first_default = True
1028
1057
  for key in self.defaults:
1058
+ if first_default:
1059
+ cfg_list += '\n[DEFAULT]\n'
1060
+ first_default = False
1029
1061
  cfg_list += f"{key:20} = {self.defaults[key]}\n"
1062
+
1030
1063
  for section in self.sections_list:
1031
1064
  cfg_list += f'\n[{section}]\n'
1032
1065
  for key in self.cfg[section]:
1033
1066
  cfg_list += f"{key:20} = {self.cfg[section][key]}\n"
1034
1067
 
1035
- outfile = mungePath(savefile, core.tool.config_dir).full_path
1068
+ outfile_mp = mungePath(savefile, core.tool.config_dir)
1069
+ configman_logger.debug (f"Writing config to <{outfile_mp.full_path}>")
1070
+
1036
1071
 
1037
1072
  try:
1038
1073
  if self.safe_mode:
1039
- run_with_timeout(outfile.write_text, cfg_list, rwt_ntries=RWT_NTRIES, rwt_timeout=RWT_TIMEOUT)
1040
- stat = run_with_timeout(self.config_full_path.stat, rwt_ntries=RWT_NTRIES, rwt_timeout=RWT_TIMEOUT)
1074
+ run_with_timeout(outfile_mp.parent.mkdir, exist_ok=True, parents=True, rwt_ntries=RWT_NTRIES, rwt_timeout=RWT_TIMEOUT)
1041
1075
  else:
1042
- outfile.write_text(cfg_list)
1043
- stat = self.config_full_path.stat()
1076
+ outfile_mp.parent.mkdir(exist_ok=True, parents=True)
1044
1077
  except Exception as e:
1045
- raise ConfigError (f"Failed to write config {self.config_file} to file {outfile}\n {type(e).__name__}: {e}")
1078
+ raise ConfigError (f"Failed to create directory tree {outfile_mp.parent}\n {type(e).__name__}: {e}")
1079
+
1046
1080
 
1047
- self.config_timestamp = int(stat.st_mtime)
1081
+ try:
1082
+ if self.safe_mode:
1083
+ run_with_timeout(outfile_mp.full_path.write_text, cfg_list, rwt_ntries=RWT_NTRIES, rwt_timeout=RWT_TIMEOUT)
1084
+ stat = run_with_timeout(outfile_mp.full_path.stat, rwt_ntries=RWT_NTRIES, rwt_timeout=RWT_TIMEOUT)
1085
+ else:
1086
+ outfile_mp.full_path.write_text(cfg_list)
1087
+ stat = outfile_mp.full_path.stat()
1088
+ except Exception as e:
1089
+ raise ConfigError (f"Failed to write config {outfile_mp.full_path}\n {type(e).__name__}: {e}")
1090
+
1091
+ if update_timestamp:
1092
+ self.config_timestamp = int(stat.st_mtime)
1048
1093
 
1049
1094
 
1050
1095
  #=====================================================================================
@@ -1098,6 +1143,8 @@ output:
1098
1143
  - A ConfigError is raised if attempting to remove a non-existing section
1099
1144
  """
1100
1145
 
1146
+ configman_logger.debug (f"Clearing section [{section}]")
1147
+
1101
1148
  if section == '':
1102
1149
  self.cfg.clear()
1103
1150
  self.sections_list = []
@@ -1255,9 +1302,9 @@ save after critical data has been written to the config.
1255
1302
 
1256
1303
  # Make the target directory
1257
1304
  if self.safe_mode:
1258
- run_with_timeout(conf_file_mp.parent.mkdir, exist_ok=True, rwt_ntries=RWT_NTRIES, rwt_timeout=RWT_TIMEOUT)
1305
+ run_with_timeout(conf_file_mp.parent.mkdir, exist_ok=True, parents=True, rwt_ntries=RWT_NTRIES, rwt_timeout=RWT_TIMEOUT)
1259
1306
  else:
1260
- conf_file_mp.parent.mkdir(exist_ok=True)
1307
+ conf_file_mp.parent.mkdir(exist_ok=True, parents=True)
1261
1308
 
1262
1309
  # Delete any existing file if force_new
1263
1310
  if force_new:
@@ -1281,12 +1328,13 @@ save after critical data has been written to the config.
1281
1328
 
1282
1329
  # Set up scheduled saves
1283
1330
  if self.save_schedule:
1284
- self.periodic_save_exit = False
1285
- self.save_thread = Thread(target=self._scheduled_save, name=f'{config_file} scheduled save')
1331
+ self.next_save_dt = None
1332
+ self.periodic_save_exit = False
1333
+ self.save_thread = Thread(target=self._scheduled_save, name=f'{config_file} scheduled save')
1286
1334
  self.save_thread.start()
1287
1335
  else:
1288
- self.next_save_dt = None
1289
- self.save_thread = None
1336
+ self.next_save_dt = None
1337
+ self.save_thread = None
1290
1338
 
1291
1339
 
1292
1340
  #=====================================================================================
@@ -1312,6 +1360,10 @@ save after critical data has been written to the config.
1312
1360
  - None on successful save and scheduled save thread exit (if enabled)
1313
1361
  - Raises ConfigError if the schedule save thread does not terminate within 5 seconds. The config data has not been saved.
1314
1362
  - Raises other exceptions, such as `PermissionError` and `OSError`, as appropriate
1363
+
1364
+
1365
+ ### Behaviors and rules
1366
+ - The persistent config's class attribute `config_timestamp` is updated when save() is called
1315
1367
  """
1316
1368
  if exit and self.save_thread:
1317
1369
  self.periodic_save_exit = True # _scheduled_save saves on exit
@@ -1321,7 +1373,7 @@ save after critical data has been written to the config.
1321
1373
  return
1322
1374
 
1323
1375
  configman_logger.info (f"Saving <{self.config_file}> data")
1324
- super().write(self.config_full_path)
1376
+ super().write(self.config_full_path, update_timestamp=True)
1325
1377
  return True
1326
1378
 
1327
1379
 
@@ -285,11 +285,14 @@ These modules support setting child logger levels: configman, deployfiles, reso
285
285
  mungePath(_lfp.parent, mkdir=True) # Force make the target dir TODO Hang risk if not on local drive. rwt?
286
286
  _fmt = FILE_LOGGING_FORMAT if FileLogFormat == None else FileLogFormat
287
287
  log_format = logging.Formatter(_fmt, style='{')
288
- handler = logging.FileHandler(_lfp.full_path, "a")
289
- handler.setLevel(logging.DEBUG)
290
- handler.setFormatter(log_format)
291
- logger.handlers.clear()
292
- logger.addHandler(handler)
288
+ try:
289
+ handler = logging.FileHandler(_lfp.full_path, "a")
290
+ handler.setLevel(logging.DEBUG)
291
+ handler.setFormatter(log_format)
292
+ logger.handlers.clear()
293
+ logger.addHandler(handler)
294
+ except Exception as e:
295
+ logging.warning (f"Error attempting to open logging to <{_lfp.full_path}> - Continuing\n {type(e).__name__}: {e}")
293
296
 
294
297
  tool.log_dir = _lfp.parent
295
298
  tool.log_file = _lfp.name
@@ -370,8 +370,8 @@ def int_handler(sig, frame):
370
370
  resourcelock_logger.warning(f"Signal {sig} received")
371
371
  sys.exit(0)
372
372
 
373
- signal.signal(signal.SIGINT, int_handler) # Ctrl-C
374
- signal.signal(signal.SIGTERM, int_handler) # kill
373
+ # signal.signal(signal.SIGINT, int_handler) # Ctrl-C
374
+ # signal.signal(signal.SIGTERM, int_handler) # kill
375
375
 
376
376
 
377
377
  def cli():
@@ -387,6 +387,8 @@ Commands:
387
387
  from time import sleep
388
388
 
389
389
  TOOLNAME = 'resourcelock'
390
+ signal.signal(signal.SIGINT, int_handler) # Ctrl-C
391
+ signal.signal(signal.SIGTERM, int_handler) # kill
390
392
 
391
393
  set_toolname (TOOLNAME)
392
394
  setuplogging()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cjnfuncs
3
- Version: 3.2.2
3
+ Version: 3.2.4
4
4
  Summary: A collection of core functions for tool script writing
5
5
  Author-email: Chris Nelson <github@cjnaz.com>
6
6
  License-Expression: MIT
@@ -35,7 +35,7 @@ module | Description/Purpose
35
35
  [resourcelock](https://github.com/cjnaz/cjnfuncs/blob/main/resourcelock.md) | Inter-process resource lock mechanism
36
36
  [SMTP](https://github.com/cjnaz/cjnfuncs/blob/main/SMTP.md) | Send notification and email messages
37
37
 
38
- Developed and tested on Python 3.9.21 and supported on all higher Python versions.
38
+ Developed and tested on Python 3.9, 3.11, and 3.13. Supported on all higher Python versions.
39
39
  Developed on Linux. Supported on Windows, except for the resourcelock module (posix-ipc module dependency).
40
40
 
41
41
  In this documentation, "tool script" refers to a Python project that imports and uses cjnfuncs. Some may be simple scripts, and others may themselves be installed packages.
@@ -58,7 +58,20 @@ Project repo: https://github.com/cjnaz/cjnfuncs
58
58
 
59
59
  <br/>
60
60
 
61
- ## Key changes since the prior major public release (version 3.0)
61
+ ## Key changes since the prior major public release (version 3.1)
62
+
63
+ 3.2.4 changes
64
+ - Minor, isolated changes
65
+ - core - trap/warning for attempting to open logging to file owned by root
66
+ - resourcelock - added /dev/shm deleted files note
67
+
68
+ 3.2.3 changes
69
+ - Minor, isolated changes
70
+ - configman.write() - the target directory tree is created if not existing, oneliner comment at top of written file
71
+ - configman.write() - config_timestamp only updated when written by persistent_config.save()
72
+ - configman.loadconfig() - remap_logdirbase is disabled for secondary configs
73
+ - configman tuned up debug logging
74
+ - resource lock moved signal traps inside of cli(), else they become global to the entire application -->
62
75
 
63
76
  3.2.2 change
64
77
  - periodic_log output now includes `[category - <package>.<module>.<function>(<line number>)]` for debug traceability of where the log event came from.
@@ -73,31 +86,15 @@ script restarts and system reboots.
73
86
  - Shared memory block handling - Extending resourcelock's features, read/write access is provided to the shared memory block associated with
74
87
  a user-defined lock.
75
88
 
76
-
77
- 3.1 changes
78
- - Several issues with Windows support were fixed.
79
-
80
- - `configman.config_item()` now supports a safe_mode switch, which will speed up Windows usage of loadconfig() at some risk. See the note on `config_item()`.
81
-
82
- - Named child loggers are now implemented on several cjnfuncs modules. By default, logging from cjnfuncs modules is disabled (internal logging events are usually at the INFO or DEBUG
83
- level, while the default logging level is set to WARNING). For example, logging from configman may be enabled by `logging.getLogger('cjnfuncs.configman').setLevel(logging.INFO)`,
84
- or using `core.set_logging_level(logging.INFO, 'cjnfuncs.configman')`.
85
-
86
- - Changed mungePath set_attributes from default True to default False to avoid long processing time on Windows by default.
87
-
88
- - deployfiles can now create an empty target directory.
89
-
90
- 3.1.1 changes
91
- - get_next_dt now supports a days or weeks offset for the days arg
92
- - Added separate child logger `cjnfuncs.resourcelock_islocked` so that `is_locked()` may be called in a loop without flooding the log while `cjnfuncs.resourcelock` is set to debug
93
-
94
89
  <br/>
95
90
 
96
91
  ## Revision history
97
92
 
98
- - 3.2.2 - 261002 - periodic_log output now includes `[category - <package>.<module>.<function>(<line number>)]` for debug traceability of where the log event came from.
99
- - 3.2.1 - 260526 - periodic_log now returns True/False whether the the call was logged. Minor changes in resourcelock.
100
- - 3.2 - 260506 - New features: persistent_config and shared memory block handling
93
+ - 3.2.4 261124 - core: trap/warning for attempting to open logging to file owned by root, added resourcelock /dev/shm deleted files note
94
+ - 3.2.3 261022 - Minor, isolated features tuning to configman and resource_lock
95
+ - 3.2.2 261002 - periodic_log output now includes `[category - <package>.<module>.<function>(<line number>)]` for debug traceability of where the log event came from.
96
+ - 3.2.1 260526 - periodic_log now returns True/False whether the the call was logged. Minor changes in resourcelock.
97
+ - 3.2 260506 - New features: persistent_config and shared memory block handling
101
98
  - 3.1.1 260207 - separate resourcelock_islocked logger, get_next_dt days/weeks offset
102
99
  - 3.1 251109
103
100
  Support for and use of child loggers,
File without changes
File without changes
File without changes
File without changes