xenoslib 0.1.29.15__py3-none-any.whl → 0.1.29.17__py3-none-any.whl

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.
xenoslib/about.py CHANGED
@@ -4,4 +4,4 @@ __url__ = "https://github.com/XenosLu/xenoslib.git"
4
4
  __author__ = "Xenocider"
5
5
  __author_email__ = "xenos.lu@gmail.com"
6
6
  __license__ = "MIT License"
7
- __version__ = "0.1.29.15"
7
+ __version__ = "0.1.29.17"
xenoslib/extend.py CHANGED
@@ -7,6 +7,8 @@ import logging
7
7
  import yaml
8
8
  import requests
9
9
 
10
+ from xenoslib.base import SingletonWithArgs
11
+
10
12
 
11
13
  logger = logging.getLogger(__name__)
12
14
 
@@ -192,5 +194,177 @@ class DingTalkLogHandler(logging.Handler):
192
194
  print(exc)
193
195
 
194
196
 
197
+ class ConfigLoader(SingletonWithArgs):
198
+ """Centralized configuration management with optional Vault integration.
199
+
200
+ Args:
201
+ config_file_path (str): Path to the YAML configuration file. Defaults to "config.yml".
202
+ vault_secret_id (str, optional): Secret ID for Vault authentication.
203
+ If provided, enables Vault functionality and imports hvac module.
204
+
205
+ Attributes:
206
+ cache (dict): Cache storage for frequently accessed configuration values.
207
+
208
+ Example:
209
+ # Without Vault (hvac not imported)
210
+ >>> config = ConfigLoader("config.yml")
211
+
212
+ # With Vault (hvac imported on demand)
213
+ >>> config = ConfigLoader("config.yml", vault_secret_id="my-secret-id")
214
+ """
215
+
216
+ def __init__(self, config_file_path="config.yml", vault_secret_id=None):
217
+ """Initialize the ConfigLoader with a configuration file and optional Vault secret."""
218
+ with open(config_file_path, "r") as f:
219
+ self._raw_config = yaml.safe_load(f) or {}
220
+
221
+ self.cache = {}
222
+ self.vault_client = None
223
+
224
+ if vault_secret_id is not None:
225
+ self._init_vault_client(vault_secret_id)
226
+
227
+ def _init_vault_client(self, vault_secret_id):
228
+ """Initialize and authenticate the Vault client (imports hvac on demand).
229
+
230
+ Args:
231
+ vault_secret_id (str): Secret ID for Vault authentication.
232
+
233
+ Raises:
234
+ ImportError: If hvac package is not installed.
235
+ KeyError: If required Vault configuration is missing.
236
+ Exception: If Vault authentication fails.
237
+ """
238
+ try:
239
+ import hvac # Lazy import
240
+ except ImportError as e:
241
+ raise ImportError(
242
+ "hvac package is required for Vault integration. " "Install with: pip install hvac"
243
+ ) from e
244
+
245
+ try:
246
+ vault_config = self._raw_config.get("vault", {})
247
+ vault_url = vault_config.get("url")
248
+ vault_space = vault_config.get("space")
249
+ vault_role_id = vault_config.get("role_id")
250
+
251
+ if not all([vault_url, vault_space, vault_role_id]):
252
+ raise KeyError("Missing required Vault configuration in config.yml")
253
+
254
+ self.vault_client = hvac.Client(url=vault_url, namespace=vault_space)
255
+ self.vault_client.auth.approle.login(role_id=vault_role_id, secret_id=vault_secret_id)
256
+ except Exception as e:
257
+ self.vault_client = None
258
+ raise Exception(f"Failed to initialize Vault client: {str(e)}")
259
+
260
+ def get(self, section, key_name, use_cache=True):
261
+ """Retrieve a configuration value.
262
+
263
+ Args:
264
+ section (str): The configuration section name.
265
+ key_name (str): The key name within the section.
266
+ use_cache (bool): Whether to use cached values. Defaults to True.
267
+
268
+ Returns:
269
+ The configuration value, which may come from:
270
+ - Direct configuration value
271
+ - Vault secret (if Vault is initialized)
272
+ - Cache (if enabled)
273
+
274
+ Raises:
275
+ KeyError: If the section or key is not found.
276
+ Exception: If Vault access is required but not available.
277
+ """
278
+ if section not in self._raw_config:
279
+ raise KeyError(f"Section '{section}' not found")
280
+
281
+ # Check for direct value first
282
+ if key_name in self._raw_config[section]:
283
+ return self._raw_config[section][key_name]
284
+
285
+ # Handle Vault reference if Vault is enabled
286
+ vault_key = f"{key_name}@vault"
287
+ if vault_key in self._raw_config[section]:
288
+ if self.vault_client is None:
289
+ raise Exception(
290
+ f"Vault access required for {key_name} but Vault is not initialized"
291
+ )
292
+
293
+ cache_key = f"{section}_{key_name}"
294
+ if use_cache and cache_key in self.cache:
295
+ return self.cache[cache_key]
296
+
297
+ value = self._get_value_from_vault(section, key_name)
298
+ self.cache[cache_key] = value
299
+ return value
300
+
301
+ raise KeyError(f"Key '{key_name}' or '{vault_key}' not found in section '{section}'")
302
+
303
+ def _get_value_from_vault(self, section, key_name):
304
+ """Retrieve a secret value from Vault.
305
+
306
+ Args:
307
+ section (str): The configuration section name.
308
+ key_name (str): The key name within the section.
309
+
310
+ Returns:
311
+ The secret value from Vault.
312
+
313
+ Raises:
314
+ Exception: If Vault access fails.
315
+ """
316
+ try:
317
+ vault_path = self._raw_config[section]["vault_path"]
318
+ vault_key = self._raw_config[section][f"{key_name}@vault"]
319
+ data = self.vault_client.secrets.kv.read_secret_version(
320
+ path=vault_path, mount_point="kv", raise_on_deleted_version=True
321
+ )
322
+ return data["data"]["data"][vault_key]
323
+ except Exception as e:
324
+ raise Exception(f"Failed to fetch {key_name} from Vault: {str(e)}")
325
+
326
+ def __getitem__(self, section):
327
+ """Dictionary-style access to configuration sections."""
328
+ if section not in self._raw_config:
329
+ raise KeyError(f"Section '{section}' not found")
330
+ return SectionProxy(self, section)
331
+
332
+ def __getattr__(self, section):
333
+ """Attribute-style access to configuration sections."""
334
+ try:
335
+ return self[section]
336
+ except KeyError as e:
337
+ raise AttributeError(str(e))
338
+
339
+
340
+ class SectionProxy:
341
+ """Proxy class for configuration section access."""
342
+
343
+ def __init__(self, config_loader, section):
344
+ self._loader = config_loader
345
+ self._section = section
346
+
347
+ def __getitem__(self, key):
348
+ """Dictionary-style access to configuration values."""
349
+ return self._loader.get(self._section, key)
350
+
351
+ def __getattr__(self, key):
352
+ """Attribute-style access to configuration values."""
353
+ try:
354
+ return self[key]
355
+ except KeyError as e:
356
+ raise AttributeError(str(e))
357
+
358
+ def __repr__(self):
359
+ """String representation of the section's configuration."""
360
+ return yaml.dump(self._loader._raw_config[self._section])
361
+
362
+
195
363
  if __name__ == "__main__":
196
- pass
364
+ config_without_vault = ConfigLoader("config.yml")
365
+ print("Without Vault:", config_without_vault.get("jira", "url"))
366
+
367
+ # This will only work if you provide a valid Vault secret ID
368
+ # and hvac package is installed
369
+ config_with_vault = ConfigLoader("config.yml", vault_secret_id="your-secret-id")
370
+ print("With Vault:", config_with_vault.get("cis", "cis_client_id"))
xenoslib/mail.py CHANGED
@@ -40,14 +40,22 @@ class MailFetcher:
40
40
  """
41
41
 
42
42
  def __new__(
43
- cls, imap_server, mail_addr, mail_pwd, interval=30, days=1, timeout=30, skip_current=True, endless=True
43
+ cls,
44
+ imap_server,
45
+ mail_addr,
46
+ mail_pwd,
47
+ interval=30,
48
+ days=1,
49
+ timeout=30,
50
+ skip_current=True,
51
+ endless=True,
44
52
  ):
45
53
  self = super().__new__(cls)
46
54
  self.imap_server = imap_server
47
55
  self.mail_addr = mail_addr
48
56
  self.mail_pwd = mail_pwd
49
57
  self.days = days
50
- self.timeout=timeout
58
+ self.timeout = timeout
51
59
 
52
60
  self.msg_ids = deque(maxlen=999)
53
61
  if not endless:
@@ -105,7 +113,9 @@ class MailFetcher:
105
113
  except Exception as exc:
106
114
  logger.warning(exc)
107
115
  sleep(30)
108
- raise Exception("Reached maximum retry attempts when connect IMAP server. Giving up connection.")
116
+ raise Exception(
117
+ "Reached maximum retry attempts when connect IMAP server. Giving up connection."
118
+ )
109
119
 
110
120
 
111
121
  class SMTPMail:
@@ -0,0 +1,30 @@
1
+ Metadata-Version: 2.4
2
+ Name: xenoslib
3
+ Version: 0.1.29.17
4
+ Summary: Xenos' common lib
5
+ Home-page: https://github.com/XenosLu/xenoslib.git
6
+ Author: Xenocider
7
+ Author-email: xenos.lu@gmail.com
8
+ License: MIT License
9
+ Requires-Python: >=3.7
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: PyYAML>=5.4
13
+ Requires-Dist: IMAPClient>=2.3.1
14
+ Requires-Dist: pywin32>=225; sys_platform == "win32"
15
+ Requires-Dist: requests>=2.19; python_version >= "3.10"
16
+ Requires-Dist: requests>=2.0.0; python_version <= "3.9"
17
+ Provides-Extra: colorful
18
+ Requires-Dist: colorama>=0.4.4; sys_platform == "win32" and extra == "colorful"
19
+ Provides-Extra: mock
20
+ Requires-Dist: requests_mock>=1.9.3; extra == "mock"
21
+ Dynamic: author
22
+ Dynamic: author-email
23
+ Dynamic: description-content-type
24
+ Dynamic: home-page
25
+ Dynamic: license
26
+ Dynamic: license-file
27
+ Dynamic: provides-extra
28
+ Dynamic: requires-dist
29
+ Dynamic: requires-python
30
+ Dynamic: summary
@@ -1,17 +1,17 @@
1
1
  xenoslib/__init__.py,sha256=vlMWwdD2gTb9ztpm_orYAm_Y0Be0Es64ifvMQwrE1jU,310
2
2
  xenoslib/__main__.py,sha256=UpD3pl4l5ZUFxK6FzNMWRb1AZpEnwerulSFoPb_Pdgw,307
3
- xenoslib/about.py,sha256=QdU3Wbq1HwaSgxPN7c14DtEgkaDgxCLBAToKX-hkQqE,232
3
+ xenoslib/about.py,sha256=bCHEaNZtyjL7Bkwok4krX155G-dVugCI2mNLMzY4djA,232
4
4
  xenoslib/base.py,sha256=yylMYrF5F-bY4ncdo5bCyImjy7OkBAz5YWMGdZNV3rY,12377
5
5
  xenoslib/dev.py,sha256=R6iwKuu-xvaYiBOUyP2gpePyvXss17TOZaCmQEihPCw,1236
6
- xenoslib/extend.py,sha256=LSzcBafyyLn1H_rwyLqGtTPqL18EDHC01_YxCsyCPLY,5887
6
+ xenoslib/extend.py,sha256=z6wZu70w4yv8d7q7tWdc08GdGr8jJwc8gH9FR_Nmi7c,12477
7
7
  xenoslib/linux.py,sha256=EFCQBq_JsmNJc3wGlJlzH9W0tjOA7sSwx0u62R5Ut2k,1318
8
- xenoslib/mail.py,sha256=olgvOxpZGxVYXK313A3GixkbvJ2ldyWw--PdLt32luc,7197
8
+ xenoslib/mail.py,sha256=pkC4gpMSxKbuvNR-0CdwbJQEJNbBCp5oEYAJS-uxq9s,7286
9
9
  xenoslib/mock.py,sha256=iNIplO7clejqLWfpY4r0WQH5BULy9dCoolDenZEci0c,3572
10
10
  xenoslib/onedrive.py,sha256=-bJJ8Cd_RjJSlDynYqKoZlFKE1HHM34l6NXOQrWOwtg,7783
11
11
  xenoslib/win_trayicon.py,sha256=7GJwX3c2CS1XWQjsyDK5EfM-MmEHdzPJCTX2sGpWmuU,13115
12
12
  xenoslib/windows.py,sha256=lUTD7TowaPqYHgIL6b-GM9PLd-VyJNNGzkzC3K9vOxo,4080
13
- xenoslib-0.1.29.15.dist-info/LICENSE,sha256=lF6hjufhiR-xAje_Wo7ogxV5phz2d5TgkfL5SGshujg,1066
14
- xenoslib-0.1.29.15.dist-info/METADATA,sha256=v-mplstVhD1G9vDgsd7L4STgEJ98_HZQCPUWsI76OaE,710
15
- xenoslib-0.1.29.15.dist-info/WHEEL,sha256=R06PA3UVYHThwHvxuRWMqaGcr-PuniXahwjmQRFMEkY,91
16
- xenoslib-0.1.29.15.dist-info/top_level.txt,sha256=Rfm4GdW0NyA2AHDNUF2wFQOfAo53mAPibddSHGd3X60,9
17
- xenoslib-0.1.29.15.dist-info/RECORD,,
13
+ xenoslib-0.1.29.17.dist-info/licenses/LICENSE,sha256=lF6hjufhiR-xAje_Wo7ogxV5phz2d5TgkfL5SGshujg,1066
14
+ xenoslib-0.1.29.17.dist-info/METADATA,sha256=Wbk4ENgu87_xfcFOwZThy3p_iJhybUxexanO5d2KbNI,914
15
+ xenoslib-0.1.29.17.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
16
+ xenoslib-0.1.29.17.dist-info/top_level.txt,sha256=Rfm4GdW0NyA2AHDNUF2wFQOfAo53mAPibddSHGd3X60,9
17
+ xenoslib-0.1.29.17.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (75.5.0)
2
+ Generator: setuptools (80.9.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,21 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: xenoslib
3
- Version: 0.1.29.15
4
- Summary: Xenos' common lib
5
- Home-page: https://github.com/XenosLu/xenoslib.git
6
- Author: Xenocider
7
- Author-email: xenos.lu@gmail.com
8
- License: MIT License
9
- Requires-Python: >=3.7
10
- Description-Content-Type: text/markdown
11
- License-File: LICENSE
12
- Requires-Dist: PyYAML >=5.4
13
- Requires-Dist: IMAPClient >=2.3.1
14
- Requires-Dist: requests >=2.0.0 ; python_version <= "3.9"
15
- Requires-Dist: requests >=2.19 ; python_version >= "3.10"
16
- Requires-Dist: pywin32 >=225 ; sys_platform == "win32"
17
- Provides-Extra: colorful
18
- Requires-Dist: colorama >=0.4.4 ; (sys_platform == "win32") and extra == 'colorful'
19
- Provides-Extra: mock
20
- Requires-Dist: requests-mock >=1.9.3 ; extra == 'mock'
21
-