aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMykyta Holubakha <hilobakho@gmail.com>2017-07-05 20:53:10 +0300
committerMykyta Holubakha <hilobakho@gmail.com>2017-07-05 20:53:10 +0300
commit89ea936652960049bf6ad307df83f52733819683 (patch)
tree13a6d07b3a27d0e31bbe7dd63a2b6a1fc189c31a /pomu/util/query.py
parentAdded the manpage (diff)
downloadpomu-89ea936652960049bf6ad307df83f52733819683.tar.gz
pomu-89ea936652960049bf6ad307df83f52733819683.tar.bz2
pomu-89ea936652960049bf6ad307df83f52733819683.zip
Some fixes
Diffstat (limited to 'pomu/util/query.py')
-rw-r--r--pomu/util/query.py78
1 files changed, 56 insertions, 22 deletions
diff --git a/pomu/util/query.py b/pomu/util/query.py
index d9dc09e..872e0a3 100644
--- a/pomu/util/query.py
+++ b/pomu/util/query.py
@@ -3,25 +3,59 @@ A module to (non)interactively query the user for impure values
"""
from pomu.util.result import Result
-def query(name, prompt=None, default=None):
- """
- Queries the impure world for name
- Parameters:
- name - the name
- prompt - prompt text
- default - default value used for errors, forced non-interactive etc.
- TODO: non-interactive
- """
- if not prompt:
- prompt = 'Please enter ' + name
- if default: prompt += ' ({})'.format(default)
- prompt += ' > '
- res = None
- try:
- res = input(prompt)
- except EOFError: pass
- if not res:
- res = default
- if not res:
- return Result.Err('No {} or default provided'.format(name))
- return Result.Ok()
+class _query:
+ def __init__(self):
+ self.map = {}
+ self.interactive = True
+
+ def __call__(self, name, prompt=None, default=None):
+ """
+ Queries the impure world for name
+ Parameters:
+ name - the name
+ prompt - prompt text
+ default - default value used for errors, forced non-interactive etc.
+ TODO: non-interactive
+ """
+ if name in self.map:
+ return Result.Ok(self.map[name])
+ if not prompt:
+ prompt = 'Please enter ' + name
+ if default: prompt += ' ({})'.format(default)
+ prompt += ' > '
+ res = None
+ if self.interactive:
+ try:
+ res = input(prompt)
+ except EOFError: pass
+ if not res:
+ res = default
+ if not res:
+ return Result.Err('No {} or default provided'.format(name))
+ return Result.Ok(res)
+
+ def set(self, name, val):
+ old = None
+ if name in self.map:
+ old = self.map[name]
+ if val is None:
+ self.unset(name)
+ self.map[name] = val
+ return old
+
+ def unset(self, name):
+ if name in self.map:
+ del self.map[name]
+
+query = _query()
+
+class QueryContext:
+ def __init__(self, **kwargs):
+ self.map = kwargs
+
+ def __enter__(self):
+ self.map_old = {x: query.set(x, self.map[x]) for x in self.map}
+
+ def __exit__(self):
+ for x, y in self.map_old.items():
+ query.set(x, y)