Improves interface of PrintUI

`print_out()` is replaced by `message()`, that redirect the output to
the stdout controlled by the PrintUI instance. Other than that, can be
used the same way as `print()`.
main
Fabien Benureau 9 years ago
parent 17b420f102
commit 4b3b2a23bd

@ -135,7 +135,7 @@ def command(args):
# elif ui.input_yn('{} has been copied into pubs; should the original be removed?'.format(color.dye_out(docfile, 'bold'))): # elif ui.input_yn('{} has been copied into pubs; should the original be removed?'.format(color.dye_out(docfile, 'bold'))):
# content.remove_file(docfile) # content.remove_file(docfile)
ui.print_out('added to pubs:\n{}'.format(pretty.paper_oneliner(p))) ui.message('added to pubs:\n{}'.format(pretty.paper_oneliner(p)))
except ValueError as v: except ValueError as v:
ui.error(v.message) ui.error(v.message)
ui.exit(1) ui.exit(1)

@ -41,7 +41,7 @@ def command(args):
# if ui.input_yn('{} has been copied into pubs; should the original be removed?'.format(color.dye_out(document, 'bold'))): # if ui.input_yn('{} has been copied into pubs; should the original be removed?'.format(color.dye_out(document, 'bold'))):
# content.remove_file(document) # content.remove_file(document)
ui.print_out('{} attached to {}'.format(color.dye_out(document, 'bold'), color.dye_out(paper.citekey, color.citekey))) ui.message('{} attached to {}'.format(color.dye_out(document, 'bold'), color.dye_out(paper.citekey, color.citekey)))
except ValueError as v: except ValueError as v:
ui.error(v.message) ui.error(v.message)

@ -36,4 +36,4 @@ def command(args):
bib[p.citekey] = p.bibdata bib[p.citekey] = p.bibdata
exporter = endecoder.EnDecoder() exporter = endecoder.EnDecoder()
bibdata_raw = exporter.encode_bibdata(bib) bibdata_raw = exporter.encode_bibdata(bib)
ui.print_out(bibdata_raw) ui.message(bibdata_raw)

@ -80,7 +80,7 @@ def command(args):
ui.error('could not load entry for citekey {}.'.format(k)) ui.error('could not load entry for citekey {}.'.format(k))
else: else:
rp.push_paper(p) rp.push_paper(p)
ui.print_out('{} imported'.format(color.dye_out(p.citekey, color.citekey))) ui.message('{} imported'.format(color.dye_out(p.citekey, color.citekey)))
docfile = bibstruct.extract_docfile(p.bibdata) docfile = bibstruct.extract_docfile(p.bibdata)
if docfile is None: if docfile is None:
ui.warning("no file for {}.".format(p.citekey)) ui.warning("no file for {}.".format(p.citekey))

@ -37,7 +37,7 @@ def command(args):
color.dye_err(pubsdir, color.filepath))) color.dye_err(pubsdir, color.filepath)))
ui.exit() ui.exit()
ui.print_out('Initializing pubs in {}'.format(color.dye_out(pubsdir, color.filepath))) ui.message('Initializing pubs in {}'.format(color.dye_out(pubsdir, color.filepath)))
config().pubsdir = pubsdir config().pubsdir = pubsdir
config().docsdir = docsdir config().docsdir = docsdir

@ -49,7 +49,7 @@ def command(args):
else: else:
papers = sorted(papers, key=date_added) papers = sorted(papers, key=date_added)
if len(papers) > 0: if len(papers) > 0:
ui.print_out('\n'.join( ui.message('\n'.join(
pretty.paper_oneliner(p, citekey_only=args.citekeys) pretty.paper_oneliner(p, citekey_only=args.citekeys)
for p in papers)) for p in papers))

@ -39,7 +39,7 @@ def command(args):
cmd = with_command.split() cmd = with_command.split()
cmd.append(docpath) cmd.append(docpath)
subprocess.Popen(cmd) subprocess.Popen(cmd)
ui.print_out('{} opened.'.format(color.dye(docpath, color.filepath))) ui.message('{} opened.'.format(color.dye(docpath, color.filepath)))
except OSError: except OSError:
ui.error("Command does not exist: %s." % with_command) ui.error("Command does not exist: %s." % with_command)
ui.exit(127) ui.exit(127)

@ -27,7 +27,7 @@ def command(args):
if force or sure: if force or sure:
for c in args.citekeys: for c in args.citekeys:
rp.remove_paper(c) rp.remove_paper(c)
ui.print_out('The paper(s) [{}] were removed'.format(', '.join([color.dye_out(c, color.citekey) for c in args.citekeys]))) ui.message('The paper(s) [{}] were removed'.format(', '.join([color.dye_out(c, color.citekey) for c in args.citekeys])))
# FIXME: print should check that removal proceeded well. # FIXME: print should check that removal proceeded well.
else: else:
ui.print_out('The paper(s) [{}] were *not* removed'.format(', '.join([color.dye_out(c, color.citekey) for c in args.citekeys]))) ui.message('The paper(s) [{}] were *not* removed'.format(', '.join([color.dye_out(c, color.citekey) for c in args.citekeys])))

@ -83,12 +83,12 @@ def command(args):
rp = Repository(config()) rp = Repository(config())
if citekeyOrTag is None: if citekeyOrTag is None:
ui.print_out(color.dye_out(' '.join(sorted(rp.get_tags())), color.tag)) ui.message(color.dye_out(' '.join(sorted(rp.get_tags())), color.tag))
else: else:
if rp.databroker.exists(citekeyOrTag): if rp.databroker.exists(citekeyOrTag):
p = rp.pull_paper(citekeyOrTag) p = rp.pull_paper(citekeyOrTag)
if tags == []: if tags == []:
ui.print_out(color.dye_out(' '.join(sorted(p.tags)), ui.message(color.dye_out(' '.join(sorted(p.tags)),
color.tag)) color.tag))
else: else:
add_tags, remove_tags = _tag_groups(_parse_tags(tags)) add_tags, remove_tags = _tag_groups(_parse_tags(tags))
@ -108,5 +108,5 @@ def command(args):
len(p.tags.intersection(excluded)) == 0): len(p.tags.intersection(excluded)) == 0):
papers_list.append(p) papers_list.append(p)
ui.print_out('\n'.join(pretty.paper_oneliner(p) ui.message('\n'.join(pretty.paper_oneliner(p)
for p in papers_list)) for p in papers_list))

@ -19,10 +19,10 @@ def command(args):
repo_version = int(config().version) repo_version = int(config().version)
if repo_version == code_version: if repo_version == code_version:
ui.print_out('Your pubs repository is up-to-date.') ui.message('Your pubs repository is up-to-date.')
sys.exit(0) sys.exit(0)
elif repo_version > code_version: elif repo_version > code_version:
ui.print_out('Your repository was generated with an newer version of pubs.\n' ui.message('Your repository was generated with an newer version of pubs.\n'
'You should not use pubs until you install the newest version.') 'You should not use pubs until you install the newest version.')
sys.exit(0) sys.exit(0)
else: else:

@ -102,7 +102,7 @@ def check_content(path):
def _get_byte_url_content(path, ui=None): def _get_byte_url_content(path, ui=None):
if ui is not None: if ui is not None:
ui.print_out(u'dowloading {}'.format(path)) ui.message(u'dowloading {}'.format(path))
response = urlopen(path) response = urlopen(path)
return response.read() return response.read()

@ -48,7 +48,7 @@ def _update_check(config, ui):
'to bypass this error)') 'to bypass this error)')
sys.exit() sys.exit()
elif repo_version < code_version: elif repo_version < code_version:
ui.print_out( ui.message(
'warning: your repository version (v{})'.format(repo_version) 'warning: your repository version (v{})'.format(repo_version)
+ 'must be updated to version {}.\n'.format(code_version) + 'must be updated to version {}.\n'.format(code_version)
+ "run 'pubs update'.") + "run 'pubs update'.")

@ -55,25 +55,17 @@ class PrintUI(object):
self._stderr = codecs.getwriter(self.encoding)(_get_raw_stderr(), self._stderr = codecs.getwriter(self.encoding)(_get_raw_stderr(),
errors='replace') errors='replace')
def print_out(self, *strings, **kwargs): def message(self, *messages, **kwargs):
"""Like print, but rather than raising an error when a character kwargs['file'] = self._stdout
is not in the terminal's encoding's character set, just silently print(*messages, **kwargs)
replaces it.
"""
print(' '.join(strings), file=self._stdout, **kwargs)
def print_err(self, *strings, **kwargs):
"""Like print, but rather than raising an error when a character
is not in the terminal's encoding's character set, just silently
replaces it.
"""
print(' '.join(strings), file=self._stderr, **kwargs)
def warning(self, message): def warning(self, message, **kwargs):
self.print_err("%s: %s" % (color.dye_err('warning', 'yellow'), message)) kwargs['file'] = self._stderr
print('{}: {}'.format(color.dye_err('warning', 'yellow'), message), **kwargs)
def error(self, message): def error(self, message, **kwargs):
self.print_err('{}: {}'.format(color.dye_err('error', 'red'), message)) kwargs['file'] = self._stderr
print('{}: {}'.format(color.dye_err('error', 'red'), message), **kwargs)
def exit(self, error_code=1): def exit(self, error_code=1):
sys.exit(error_code) sys.exit(error_code)
@ -119,7 +111,7 @@ class InputUI(PrintUI):
option_str = '/'.join(["{}{}".format(color.dye_out(c, 'bold'), s[1:]) option_str = '/'.join(["{}{}".format(color.dye_out(c, 'bold'), s[1:])
for c, s in zip(displayed_chars, options)]) for c, s in zip(displayed_chars, options)])
self.print_out('{} {}: '.format(question, option_str), end='') self.message('{} {}: '.format(question, option_str), end='')
while True: while True:
answer = self.input() answer = self.input()
if answer is None or answer == '': if answer is None or answer == '':
@ -133,7 +125,7 @@ class InputUI(PrintUI):
return option_chars.index(answer.lower()) return option_chars.index(answer.lower())
except ValueError: except ValueError:
pass pass
self.print_out('Incorrect option.', option_str) self.message('Incorrect option.', option_str)
def input_choice(self, options, option_chars, default=None, question=''): def input_choice(self, options, option_chars, default=None, question=''):
@ -155,7 +147,7 @@ class InputUI(PrintUI):
for i, s in enumerate(option_chars)] for i, s in enumerate(option_chars)]
option_str = ', '.join(["[%s]%s" % (color.dye_out(c, 'cyan'), o) option_str = ', '.join(["[%s]%s" % (color.dye_out(c, 'cyan'), o)
for c, o in zip(displayed_chars, options)]) for c, o in zip(displayed_chars, options)])
self.print_out(question, option_str) self.message(question, option_str)
while True: while True:
answer = self.input() answer = self.input()
if answer is None or answer == '': if answer is None or answer == '':
@ -166,7 +158,7 @@ class InputUI(PrintUI):
return option_chars.index(answer.lower()) return option_chars.index(answer.lower())
except ValueError: except ValueError:
pass pass
self.print_out('Incorrect option.', option_str) self.message('Incorrect option.', option_str)
def input_yn(self, question='', default='y'): def input_yn(self, question='', default='y'):
d = 0 if default in (True, 'y', 'yes') else 1 d = 0 if default in (True, 'y', 'yes') else 1

@ -24,7 +24,7 @@ def resolve_citekey(repo, citekey, ui=None, exit_on_fail=True):
citekey)) citekey))
for c in citekeys: for c in citekeys:
p = repo.pull_paper(c) p = repo.pull_paper(c)
ui.print_out(u' {}'.format(pretty.paper_oneliner(p))) ui.message(u' {}'.format(pretty.paper_oneliner(p)))
if exit_on_fail: if exit_on_fail:
ui.exit() ui.exit()
return citekey return citekey

@ -17,7 +17,7 @@ from pubs.commands import init_cmd, import_cmd
# makes the tests very noisy # makes the tests very noisy
PRINT_OUTPUT=False messagePUT=False
CAPTURE_OUTPUT=True CAPTURE_OUTPUT=True
@ -102,7 +102,7 @@ class CommandTestCase(unittest.TestCase):
except fake_env.FakeInput.UnexpectedInput: except fake_env.FakeInput.UnexpectedInput:
self.fail('Unexpected input asked by command: {}.'.format( self.fail('Unexpected input asked by command: {}.'.format(
actual_cmd)) actual_cmd))
if PRINT_OUTPUT: if messagePUT:
print(outs) print(outs)
return outs return outs

Loading…
Cancel
Save