Skip to content

Commit

Permalink
support accessing environment variables in format strings (#1968)
Browse files Browse the repository at this point in the history
{_env[HOME]} to get the value of $HOME
every other format string feature is supported as well
  • Loading branch information
mikf committed Oct 28, 2021
1 parent e4696b4 commit 38193db
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
17 changes: 16 additions & 1 deletion gallery_dl/formatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@

"""String formatters"""

import os
import json
import string
import _string
import operator
from . import text, util

_CACHE = {}
_GLOBALS = {"_env": os.environ}
_CONVERSIONS = None


Expand Down Expand Up @@ -125,6 +127,8 @@ def _field_access(self, field_name, format_spec, conversion):
], 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)
Expand All @@ -140,6 +144,17 @@ def wrap(kwdict):
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)
Expand All @@ -149,7 +164,7 @@ def _apply_list(self, lst, fmt):
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:
Expand Down
7 changes: 7 additions & 0 deletions test/test_formatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,13 @@ def test_chain_special(self):
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)
Expand Down

0 comments on commit 38193db

Please sign in to comment.