summaryrefslogtreecommitdiff
path: root/lib/template.py
diff options
context:
space:
mode:
authorTobias Brox <tobias@redpill-linpro.com>2022-09-30 01:29:58 +0200
committerTobias Brox <tobias@redpill-linpro.com>2022-10-09 01:55:25 +0200
commite9a968157e65e18d1b285a7765ecb641175ba370 (patch)
tree4c770db41f5effaa79447df59023b536a5a60738 /lib/template.py
parentfd834cd17933bad5567f1315ddc800145081dcd6 (diff)
downloadcalendar-cli-e9a968157e65e18d1b285a7765ecb641175ba370.zip
More work on the kal aka cal.py command. It can now do around 80% of all the stuff calendar-cli can do, plus more.
Diffstat (limited to 'lib/template.py')
-rw-r--r--lib/template.py49
1 files changed, 49 insertions, 0 deletions
diff --git a/lib/template.py b/lib/template.py
new file mode 100644
index 0000000..47281d9
--- /dev/null
+++ b/lib/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, "")