mirror of
https://github.com/mikf/gallery-dl.git
synced 2024-11-25 20:22:36 +01:00
support accessing environment variables in format strings (#1968)
{_env[HOME]} to get the value of $HOME every other format string feature is supported as well
This commit is contained in:
parent
e4696b40ba
commit
38193dba46
@ -8,6 +8,7 @@
|
||||
|
||||
"""String formatters"""
|
||||
|
||||
import os
|
||||
import json
|
||||
import string
|
||||
import _string
|
||||
@ -15,6 +16,7 @@ import operator
|
||||
from . import text, util
|
||||
|
||||
_CACHE = {}
|
||||
_GLOBALS = {"_env": os.environ}
|
||||
_CONVERSIONS = None
|
||||
|
||||
|
||||
@ -125,6 +127,8 @@ class StringFormatter():
|
||||
], fmt)
|
||||
else:
|
||||
key, funcs = parse_field_name(field_name)
|
||||
if key in _GLOBALS:
|
||||
return self._apply_globals(_GLOBALS[key], funcs, fmt)
|
||||
if funcs:
|
||||
return self._apply(key, funcs, fmt)
|
||||
return self._apply_simple(key, fmt)
|
||||
@ -140,6 +144,17 @@ class StringFormatter():
|
||||
return fmt(obj)
|
||||
return wrap
|
||||
|
||||
def _apply_globals(self, gobj, funcs, fmt):
|
||||
def wrap(_):
|
||||
try:
|
||||
obj = gobj
|
||||
for func in funcs:
|
||||
obj = func(obj)
|
||||
except Exception:
|
||||
obj = self.default
|
||||
return fmt(obj)
|
||||
return wrap
|
||||
|
||||
def _apply_simple(self, key, fmt):
|
||||
def wrap(kwdict):
|
||||
return fmt(kwdict[key] if key in kwdict else self.default)
|
||||
@ -149,7 +164,7 @@ class StringFormatter():
|
||||
def wrap(kwdict):
|
||||
for key, funcs in lst:
|
||||
try:
|
||||
obj = kwdict[key]
|
||||
obj = _GLOBALS[key] if key in _GLOBALS else kwdict[key]
|
||||
for func in funcs:
|
||||
obj = func(obj)
|
||||
if obj:
|
||||
|
@ -173,6 +173,13 @@ class TestFormatter(unittest.TestCase):
|
||||
self._run_test("{d[a]:?</>/L1/too long/}", "<too long>")
|
||||
self._run_test("{d[c]:?</>/L5/too long/}", "")
|
||||
|
||||
def test_environ(self):
|
||||
os.environ["FORMATTER_TEST"] = value = self.kwdict["a"]
|
||||
|
||||
self._run_test("{_env[FORMATTER_TEST]}" , value)
|
||||
self._run_test("{_env[FORMATTER_TEST]!l}", value.lower())
|
||||
self._run_test("{z|_env[FORMATTER_TEST]}", value)
|
||||
|
||||
def _run_test(self, format_string, result, default=None):
|
||||
fmt = formatter.parse(format_string, default)
|
||||
output = fmt.format_map(self.kwdict)
|
||||
|
Loading…
Reference in New Issue
Block a user