diff options
author | Tobias Brox <tobias@redpill-linpro.com> | 2022-11-06 10:23:24 +0100 |
---|---|---|
committer | Tobias Brox <tobias@redpill-linpro.com> | 2022-11-06 10:23:24 +0100 |
commit | 891359b85d305199a76283f412107359e8674b7d (patch) | |
tree | 924566a50b183bc311fce68b1d61699edbc1d97a /calendar_cli/template.py | |
parent | 68e2b2dfdaebd01a0bdd2b1f4d9f87f3b203a7fb (diff) | |
download | calendar-cli-891359b85d305199a76283f412107359e8674b7d.zip |
reorganized the repository - should fix https://github.com/tobixen/calendar-cli/issues/94
Diffstat (limited to 'calendar_cli/template.py')
-rw-r--r-- | calendar_cli/template.py | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/calendar_cli/template.py b/calendar_cli/template.py new file mode 100644 index 0000000..47281d9 --- /dev/null +++ b/calendar_cli/template.py @@ -0,0 +1,49 @@ +"""String formatter that allows default values to be passed in the +template string. + +This does not really belong in the calendar-cli package. I was +googling a bit, and didn't find anything like this out there ... but +I'm sure there must exist something like this?""" + +import datetime +import string +import re + +class NoValue(): + def __getattr__(self, attr): + return self + def __getitem__(self, attr): + return self + def __str__(self): + return "" + def __format__(self, spec): + try: + return "".__format__(spec) + except: + return "" + +no_value = NoValue() + +class Template(string.Formatter): + def __init__(self, template): + self.template = template + + def format(self, *pargs, **kwargs): + return super().format(self.template, *pargs, **kwargs) + + def get_value(self, key, args, kwds): + try: + return string.Formatter.get_value(self, key, args, kwds) + except: + return no_value + + def format_field(self, value, format_spec): + rx = re.match(r'\?([^\?]*)\?(.*)', format_spec) + if rx: + format_spec = rx.group(2) + if value is no_value: + value = rx.group(1) + try: + return string.Formatter.format_field(self, value, format_spec) + except: + return string.Formatter.format_field(self, value, "") |