summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLars Wirzenius <liw@liw.fi>2015-04-18 10:40:37 +0300
committerLars Wirzenius <liw@liw.fi>2015-04-18 10:56:55 +0300
commitd3b79bed48895150fb7c33f577716a900fda3833 (patch)
tree7175e2b3d3dedc7aa4d4f0e26771699deec1d0d4
parent6d7daee29388fb3520cd70ed3cf0a4c085f80f69 (diff)
downloadcliapp-d3b79bed48895150fb7c33f577716a900fda3833.tar.gz
Run pep8 in "make check" and fix so it passes
-rw-r--r--Makefile1
-rw-r--r--cliapp/app.py66
-rw-r--r--cliapp/app_tests.py37
-rw-r--r--cliapp/fmt.py2
-rw-r--r--cliapp/fmt_tests.py1
-rw-r--r--cliapp/genman.py1
-rw-r--r--cliapp/hook.py1
-rw-r--r--cliapp/hook_tests.py5
-rw-r--r--cliapp/hookmgr.py1
-rw-r--r--cliapp/hookmgr_tests.py5
-rw-r--r--cliapp/plugin.py2
-rw-r--r--cliapp/plugin_tests.py1
-rw-r--r--cliapp/pluginmgr.py1
-rw-r--r--cliapp/pluginmgr_tests.py3
-rw-r--r--cliapp/runcmd.py16
-rw-r--r--cliapp/runcmd_tests.py19
-rw-r--r--cliapp/settings.py143
-rw-r--r--cliapp/settings_tests.py3
18 files changed, 166 insertions, 142 deletions
diff --git a/Makefile b/Makefile
index 9ccb5fb..a64f92c 100644
--- a/Makefile
+++ b/Makefile
@@ -25,3 +25,4 @@ clean:
check:
python -m CoverageTestRunner --ignore-missing-from=without-tests
rm .coverage
+ pep8 cliapp
diff --git a/cliapp/app.py b/cliapp/app.py
index c9112a2..dc6b860 100644
--- a/cliapp/app.py
+++ b/cliapp/app.py
@@ -48,7 +48,7 @@ class AppException(Exception):
return self.msg
-class LogHandler(logging.handlers.RotatingFileHandler): # pragma: no cover
+class LogHandler(logging.handlers.RotatingFileHandler): # pragma: no cover
'''Like RotatingFileHandler, but set permissions of new files.'''
@@ -135,7 +135,7 @@ class Application(object):
self.settings.progname = os.path.basename(sysargv[0])
envname = '%s_PROFILE' % self._envname(self.settings.progname)
profname = os.environ.get(envname, '')
- if profname: # pragma: no cover
+ if profname: # pragma: no cover
import cProfile
cProfile.runctx('run_it()', globals(), locals(), profname)
else:
@@ -153,7 +153,7 @@ class Application(object):
return ''.join(x.upper() if x in ok else '_' for x in basename)
- def _set_process_name(self): # pragma: no cover
+ def _set_process_name(self): # pragma: no cover
comm = '/proc/self/comm'
if platform.system() == 'Linux' and os.path.exists(comm):
with open('/proc/self/comm', 'w', 0) as f:
@@ -190,7 +190,7 @@ class Application(object):
self.process_args(args)
self.cleanup()
self.disable_plugins()
- except cliapp.UnknownConfigVariable, e: # pragma: no cover
+ except cliapp.UnknownConfigVariable, e: # pragma: no cover
stderr.write('ERROR: %s\n' % str(e))
sys.exit(1)
except AppException, e:
@@ -204,7 +204,7 @@ class Application(object):
sys.exit(e.code if type(e.code) == int else 1)
except KeyboardInterrupt, e:
sys.exit(255)
- except IOError, e: # pragma: no cover
+ except IOError, e: # pragma: no cover
if e.errno == errno.EPIPE and e.filename is None:
# We're writing to stdout, and it broke. This almost always
# happens when we're being piped to less, and the user quits
@@ -214,14 +214,14 @@ class Application(object):
log(traceback.format_exc())
stderr.write('ERROR: %s\n' % str(e))
sys.exit(1)
- except OSError, e: # pragma: no cover
+ except OSError, e: # pragma: no cover
log(traceback.format_exc())
if hasattr(e, 'filename') and e.filename:
stderr.write('ERROR: %s: %s\n' % (e.filename, e.strerror))
else:
stderr.write('ERROR: %s\n' % e.strerror)
sys.exit(1)
- except BaseException, e: # pragma: no cover
+ except BaseException, e: # pragma: no cover
log(traceback.format_exc())
stderr.write(traceback.format_exc())
sys.exit(1)
@@ -244,7 +244,7 @@ class Application(object):
'''
def add_subcommand(
- self, name, func, arg_synopsis=None, aliases=None, hidden=False):
+ self, name, func, arg_synopsis=None, aliases=None, hidden=False):
'''Add a subcommand.
Normally, subcommands are defined by add ``cmd_foo`` methods
@@ -261,7 +261,7 @@ class Application(object):
self.subcommands[name] = func
self.cmd_synopsis[name] = arg_synopsis
self.subcommand_aliases[name] = aliases or []
- if hidden: # pragma: no cover
+ if hidden: # pragma: no cover
self.hidden_subcommands.add(name)
def add_default_subcommands(self):
@@ -270,7 +270,7 @@ class Application(object):
if 'help-all' not in self.subcommands:
self.add_subcommand('help-all', self.help_all)
- def get_subcommand_help_formatter(self, *a, **kw): # pragma: no cover
+ def get_subcommand_help_formatter(self, *a, **kw): # pragma: no cover
'''Return class to format subcommand documentation.
The class will be used to format the full docstring of a
@@ -287,13 +287,12 @@ class Application(object):
return cliapp.TextFormat(*a, **kw)
- def _help_helper(self, args, show_all): # pragma: no cover
+ def _help_helper(self, args, show_all): # pragma: no cover
try:
width = int(os.environ.get('COLUMNS', '78'))
except ValueError:
width = 78
-
if args:
cmd = args[0]
if cmd not in self.subcommands:
@@ -311,19 +310,18 @@ class Application(object):
text = self.settings.progname.join(text.split('%prog'))
self.output.write(text)
- def help(self, args): # pragma: no cover
+ def help(self, args): # pragma: no cover
'''Print help.'''
self._help_helper(args, False)
- def help_all(self, args): # pragma: no cover
+ def help_all(self, args): # pragma: no cover
'''Print help, including hidden subcommands.'''
self._help_helper(args, True)
def _subcommand_methodnames(self):
return [x
- for x in dir(self)
- if x.startswith('cmd_') and
- inspect.ismethod(getattr(self, x))]
+ for x in dir(self)
+ if x.startswith('cmd_') and inspect.ismethod(getattr(self, x))]
def _normalize_cmd(self, cmd):
return 'cmd_%s' % cmd.replace('-', '_')
@@ -347,7 +345,7 @@ class Application(object):
else:
return None
- def _format_usage_for(self, cmd): # pragma: no cover
+ def _format_usage_for(self, cmd): # pragma: no cover
args = self.cmd_synopsis.get(cmd, '') or ''
return 'Usage: %%prog [options] %s %s' % (cmd, args)
@@ -363,7 +361,7 @@ class Application(object):
else:
return self._description
- def _format_subcommand_summary(self, cmd): # pragma: no cover
+ def _format_subcommand_summary(self, cmd): # pragma: no cover
method = self.subcommands[cmd]
doc = method.__doc__ or ''
lines = doc.splitlines()
@@ -373,7 +371,7 @@ class Application(object):
summary = ''
return '* %%prog %s: %s\n' % (cmd, summary)
- def _format_subcommand_help(self, cmd): # pragma: no cover
+ def _format_subcommand_help(self, cmd): # pragma: no cover
method = self.subcommands[cmd]
doc = method.__doc__ or ''
t = doc.split('\n', 1)
@@ -383,7 +381,7 @@ class Application(object):
first, rest = t
return first + '\n' + textwrap.dedent(rest)
- def setup_logging(self): # pragma: no cover
+ def setup_logging(self): # pragma: no cover
'''Set up logging.'''
level_name = self.settings['log-level']
@@ -410,7 +408,7 @@ class Application(object):
logger.addHandler(handler)
logger.setLevel(level)
- def setup_logging_handler_for_syslog(self): # pragma: no cover
+ def setup_logging_handler_for_syslog(self): # pragma: no cover
'''Setup a logging.Handler for logging to syslog.'''
handler = logging.handlers.SysLogHandler(address='/dev/log')
@@ -419,13 +417,13 @@ class Application(object):
return handler
- def setup_logging_formatter_for_syslog(self): # pragma: no cover
+ def setup_logging_formatter_for_syslog(self): # pragma: no cover
'''Setup a logging.Formatter for syslog.'''
progname = '%%'.join(self.settings.progname.split('%'))
fmt = progname + ": %(levelname)s %(message)s"
return logging.Formatter(fmt)
- def setup_logging_handler_for_file(self): # pragma: no cover
+ def setup_logging_handler_for_file(self): # pragma: no cover
'''Setup a logging handler for logging to a named file.'''
handler = LogHandler(
@@ -438,24 +436,24 @@ class Application(object):
handler.setFormatter(formatter)
return handler
- def setup_logging_formatter_for_file(self): # pragma: no cover
+ def setup_logging_formatter_for_file(self): # pragma: no cover
'''Setup a logging.Formatter for logging to a file.'''
fmt = '%(asctime)s %(levelname)s %(message)s'
datefmt = '%Y-%m-%d %H:%M:%S'
formatter = logging.Formatter(fmt, datefmt)
return formatter
- def setup_logging_handler_to_none(self): # pragma: no cover
+ def setup_logging_handler_to_none(self): # pragma: no cover
'''Setup a logging.Handler that does not log anything anywhere.'''
handler = logging.FileHandler('/dev/null')
return handler
- def setup_logging_format(self): # pragma: no cover
+ def setup_logging_format(self): # pragma: no cover
'''Return format string for log messages.'''
return '%(asctime)s %(levelname)s %(message)s'
- def setup_logging_timestamp(self): # pragma: no cover
+ def setup_logging_timestamp(self): # pragma: no cover
'''Return timestamp format string for log message.'''
return '%Y-%m-%d %H:%M:%S'
@@ -498,7 +496,7 @@ class Application(object):
dirname = os.path.join(self.app_directory(), self.plugin_subdir)
self.pluginmgr.locations = [dirname]
- def enable_plugins(self): # pragma: no cover
+ def enable_plugins(self): # pragma: no cover
'''Load plugins.'''
for plugin in self.pluginmgr.plugins:
plugin.app = self
@@ -549,7 +547,6 @@ class Application(object):
'''
-
if self.subcommands:
if not args:
raise SystemExit('must give subcommand')
@@ -629,13 +626,13 @@ class Application(object):
'''
- def runcmd(self, *args, **kwargs): # pragma: no cover
+ def runcmd(self, *args, **kwargs): # pragma: no cover
return cliapp.runcmd(*args, **kwargs)
- def runcmd_unchecked(self, *args, **kwargs): # pragma: no cover
+ def runcmd_unchecked(self, *args, **kwargs): # pragma: no cover
return cliapp.runcmd_unchecked(*args, **kwargs)
- def _vmrss(self): # pragma: no cover
+ def _vmrss(self): # pragma: no cover
'''Return current resident memory use, in KiB.'''
if platform.system() != 'Linux':
return 0
@@ -650,7 +647,7 @@ class Application(object):
f.close()
return rss
- def dump_memory_profile(self, msg): # pragma: no cover
+ def dump_memory_profile(self, msg): # pragma: no cover
'''Log memory profiling information.
Get the memory profiling method from the dump-memory-profile
@@ -701,4 +698,3 @@ class Application(object):
from meliae import scanner
scanner.dump_all_objects(filename)
self.memory_dump_counter += 1
-
diff --git a/cliapp/app_tests.py b/cliapp/app_tests.py
index 080a600..a65aee2 100644
--- a/cliapp/app_tests.py
+++ b/cliapp/app_tests.py
@@ -49,10 +49,13 @@ class ApplicationTests(unittest.TestCase):
def test_calls_add_settings_only_in_run(self):
class Foo(cliapp.Application):
+
def process_args(self, args):
pass
+
def add_settings(self):
self.settings.string(['foo'], '')
+
foo = Foo()
self.assertFalse('foo' in foo.settings)
foo.run(args=[])
@@ -61,18 +64,23 @@ class ApplicationTests(unittest.TestCase):
def test_run_uses_string_list_options_only_once(self):
class Foo(cliapp.Application):
+
def add_settings(self):
self.settings.string_list(['foo'], '')
+
def process_args(self, args):
pass
+
foo = Foo()
foo.run(args=['--foo=yo'])
self.assertEqual(foo.settings['foo'], ['yo'])
def test_run_sets_up_logging(self):
self.called = False
+
def setup():
self.called = True
+
self.app.setup_logging = setup
self.app.process_args = lambda args: None
self.app.run([])
@@ -133,45 +141,59 @@ class ApplicationTests(unittest.TestCase):
self.assertEqual(self.app.settings['bar'], True)
def test_calls_setup(self):
+
class App(cliapp.Application):
+
def setup(self):
self.setup_called = True
+
def process_inputs(self, args):
pass
+
app = App()
app.run(args=[])
self.assertTrue(app.setup_called)
def test_calls_cleanup(self):
+
class App(cliapp.Application):
+
def cleanup(self):
self.cleanup_called = True
+
def process_inputs(self, args):
pass
+
app = App()
app.run(args=[])
self.assertTrue(app.cleanup_called)
def test_process_args_calls_process_inputs(self):
self.called = False
+
def process_inputs(args):
self.called = True
+
self.app.process_inputs = process_inputs
self.app.process_args([])
self.assert_(self.called)
def test_process_inputs_calls_process_input_for_each_arg(self):
self.args = []
+
def process_input(arg):
self.args.append(arg)
+
self.app.process_input = process_input
self.app.process_inputs(['foo', 'bar'])
self.assertEqual(self.args, ['foo', 'bar'])
def test_process_inputs_calls_process_input_with_dash_if_no_inputs(self):
self.args = []
+
def process_input(arg):
self.args.append(arg)
+
self.app.process_input = process_input
self.app.process_inputs([])
self.assertEqual(self.args, ['-'])
@@ -190,22 +212,28 @@ class ApplicationTests(unittest.TestCase):
def test_process_input_calls_open_input(self):
self.called = None
+
def open_input(name):
self.called = name
return StringIO.StringIO('')
+
self.app.open_input = open_input
self.app.process_input('foo')
self.assertEqual(self.called, 'foo')
def test_process_input_does_not_close_stdin(self):
self.closed = False
+
def close():
self.closed = True
+
f = StringIO.StringIO('')
f.close = close
+
def open_input(name):
if name == '-':
return f
+
self.app.open_input = open_input
self.app.process_input('-', stdin=f)
self.assertEqual(self.closed, False)
@@ -213,10 +241,13 @@ class ApplicationTests(unittest.TestCase):
def test_processes_input_lines(self):
lines = []
+
class Foo(cliapp.Application):
+
def open_input(self, name):
return StringIO.StringIO(''.join('%s%d\n' % (name, i)
for i in range(2)))
+
def process_input_line(self, name, line):
lines.append(line)
@@ -226,10 +257,13 @@ class ApplicationTests(unittest.TestCase):
def test_process_input_line_can_access_counters(self):
counters = []
+
class Foo(cliapp.Application):
+
def open_input(self, name):
return StringIO.StringIO(''.join('%s%d\n' % (name, i)
for i in range(2)))
+
def process_input_line(self, name, line):
counters.append((self.fileno, self.global_lineno, self.lineno))
@@ -305,8 +339,10 @@ class SubcommandTests(unittest.TestCase):
def test_calls_subcommand_method_via_alias(self):
self.bar_called = False
+
def bar(*args):
self.bar_called = True
+
self.app.add_subcommand('bar', bar, aliases=['yoyo'])
self.app.run(['yoyo'], stderr=self.trash, log=devnull)
self.assertTrue(self.bar_called)
@@ -328,4 +364,3 @@ class ExtensibleSubcommandTests(unittest.TestCase):
help = lambda args: None
self.app.add_subcommand('foo', help)
self.assertEqual(self.app.subcommands, {'foo': help})
-
diff --git a/cliapp/fmt.py b/cliapp/fmt.py
index 1358b0a..fcafc8f 100644
--- a/cliapp/fmt.py
+++ b/cliapp/fmt.py
@@ -121,5 +121,3 @@ class TextFormat(object):
if current:
yield current
-
-
diff --git a/cliapp/fmt_tests.py b/cliapp/fmt_tests.py
index 79f1ab6..a2dd9fb 100644
--- a/cliapp/fmt_tests.py
+++ b/cliapp/fmt_tests.py
@@ -56,4 +56,3 @@ class TextFormatTests(unittest.TestCase):
self.assertEqual(
self.fmt.format('foo\nbar\n* yo\n* a\n and b\nword'),
'foo bar\n\n* yo\n* a and b\n\nword\n')
-
diff --git a/cliapp/genman.py b/cliapp/genman.py
index e81fcfe..5d47683 100644
--- a/cliapp/genman.py
+++ b/cliapp/genman.py
@@ -145,4 +145,3 @@ class ManpageGenerator(object):
else:
words += ['""']
return [' '.join(words)]
-
diff --git a/cliapp/hook.py b/cliapp/hook.py
index d453f2e..6d93108 100644
--- a/cliapp/hook.py
+++ b/cliapp/hook.py
@@ -73,4 +73,3 @@ class FilterHook(Hook):
for callback in self.callbacks:
data = callback(data, *args, **kwargs)
return data
-
diff --git a/cliapp/hook_tests.py b/cliapp/hook_tests.py
index a32f33a..3e3de6e 100644
--- a/cliapp/hook_tests.py
+++ b/cliapp/hook_tests.py
@@ -45,7 +45,7 @@ class HookTests(unittest.TestCase):
self.hook.add_callback(self.callback)
self.hook.call_callbacks('bar', kwarg='foobar')
self.assertEqual(self.args, ('bar',))
- self.assertEqual(self.kwargs, { 'kwarg': 'foobar' })
+ self.assertEqual(self.kwargs, {'kwarg': 'foobar'})
def test_removes_callback(self):
cb_id = self.hook.add_callback(self.callback)
@@ -75,5 +75,4 @@ class FilterHookTests(unittest.TestCase):
self.hook.add_callback(self.callback)
self.hook.call_callbacks(['data'], 'extra', kwextra='kwextra')
self.assertEqual(self.args, ('extra',))
- self.assertEqual(self.kwargs, { 'kwextra': 'kwextra' })
-
+ self.assertEqual(self.kwargs, {'kwextra': 'kwextra'})
diff --git a/cliapp/hookmgr.py b/cliapp/hookmgr.py
index 80db2d0..fad6bce 100644
--- a/cliapp/hookmgr.py
+++ b/cliapp/hookmgr.py
@@ -43,4 +43,3 @@ class HookManager(object):
def call(self, name, *args, **kwargs):
'''Call callbacks for a named hook, using given arguments.'''
return self.hooks[name].call_callbacks(*args, **kwargs)
-
diff --git a/cliapp/hookmgr_tests.py b/cliapp/hookmgr_tests.py
index 7abdeba..9b7a735 100644
--- a/cliapp/hookmgr_tests.py
+++ b/cliapp/hookmgr_tests.py
@@ -35,7 +35,7 @@ class HookManagerTests(unittest.TestCase):
self.assertEqual(hooks.hooks, {})
def test_adds_new_hook(self):
- self.assert_(self.hooks.hooks.has_key('foo'))
+ self.assertTrue('foo' in self.hooks.hooks)
def test_adds_callback(self):
self.hooks.add_callback('foo', self.callback)
@@ -50,10 +50,9 @@ class HookManagerTests(unittest.TestCase):
self.hooks.add_callback('foo', self.callback)
self.hooks.call('foo', 'bar', kwarg='foobar')
self.assertEqual(self.args, ('bar',))
- self.assertEqual(self.kwargs, { 'kwarg': 'foobar' })
+ self.assertEqual(self.kwargs, {'kwarg': 'foobar'})
def test_call_returns_value_of_callbacks(self):
self.hooks.new('bar', FilterHook())
self.hooks.add_callback('bar', lambda data: data + 1)
self.assertEqual(self.hooks.call('bar', 1), 2)
-
diff --git a/cliapp/plugin.py b/cliapp/plugin.py
index ac8ea0b..cf964a3 100644
--- a/cliapp/plugin.py
+++ b/cliapp/plugin.py
@@ -119,6 +119,6 @@ class Plugin(object):
'''Enable the plugin.'''
raise NotImplemented()
- def disable(self): # pragma: no cover
+ def disable(self): # pragma: no cover
'''Disable the plugin.'''
pass
diff --git a/cliapp/plugin_tests.py b/cliapp/plugin_tests.py
index 381e7c4..951547e 100644
--- a/cliapp/plugin_tests.py
+++ b/cliapp/plugin_tests.py
@@ -49,4 +49,3 @@ class PluginTests(unittest.TestCase):
self.plugin.disable = lambda: setattr(self, 'disabled', True)
self.plugin.disable_wrapper()
self.assert_(self.disabled, True)
-
diff --git a/cliapp/pluginmgr.py b/cliapp/pluginmgr.py
index 5e99523..96c726e 100644
--- a/cliapp/pluginmgr.py
+++ b/cliapp/pluginmgr.py
@@ -172,4 +172,3 @@ class PluginManager(object):
for plugin in plugins or self.plugins:
plugin.disable_wrapper()
-
diff --git a/cliapp/pluginmgr_tests.py b/cliapp/pluginmgr_tests.py
index d458ac3..ccca868 100644
--- a/cliapp/pluginmgr_tests.py
+++ b/cliapp/pluginmgr_tests.py
@@ -50,7 +50,7 @@ class PluginManagerTests(unittest.TestCase):
self.pm = PluginManager()
self.pm.locations = ['test-plugins', 'not-exist']
self.pm.plugin_arguments = ('fooarg',)
- self.pm.plugin_keyword_arguments = { 'bar': 'bararg' }
+ self.pm.plugin_keyword_arguments = {'bar': 'bararg'}
self.files = sorted(['test-plugins/hello_plugin.py',
'test-plugins/aaa_hello_plugin.py',
@@ -115,4 +115,3 @@ class PluginManagerCompatibleApplicationVersionTests(unittest.TestCase):
def test_accepts_one_two_three(self):
self.assert_(self.pm.compatible_version('1.2.3'))
-
diff --git a/cliapp/runcmd.py b/cliapp/runcmd.py
index ffd120d..6ae2524 100644
--- a/cliapp/runcmd.py
+++ b/cliapp/runcmd.py
@@ -63,6 +63,7 @@ def runcmd(argv, *args, **kwargs):
raise cliapp.AppException(msg)
return out
+
def runcmd_unchecked(argv, *argvs, **kwargs):
'''Run external command or pipeline.
@@ -103,13 +104,14 @@ def runcmd_unchecked(argv, *argvs, **kwargs):
return _run_pipeline(pipeline, feed_stdin, pipe_stdin,
pipe_stdout, pipe_stderr,
stdout_callback, stderr_callback)
- except OSError, e: # pragma: no cover
+ except OSError, e: # pragma: no cover
if e.errno == errno.ENOENT and e.filename is None:
e.filename = argv[0]
raise e
else:
raise
+
def _build_pipeline(argvs, pipe_stdin, pipe_stdout, pipe_stderr, kwargs):
procs = []
@@ -156,6 +158,7 @@ def _build_pipeline(argvs, pipe_stdin, pipe_stdout, pipe_stderr, kwargs):
return procs
+
def _run_pipeline(procs, feed_stdin, pipe_stdin, pipe_stdout, pipe_stderr,
stdout_callback, stderr_callback):
@@ -187,7 +190,7 @@ def _run_pipeline(procs, feed_stdin, pipe_stdin, pipe_stdout, pipe_stderr,
if pipe_stdout == subprocess.PIPE and not stdout_eof:
return True
if pipe_stderr == subprocess.PIPE and not stderr_eof:
- return True # pragma: no cover
+ return True # pragma: no cover
return False
while still_running():
@@ -204,16 +207,16 @@ def _run_pipeline(procs, feed_stdin, pipe_stdin, pipe_stdout, pipe_stderr,
if rlist or wlist:
try:
r, w, x = select.select(rlist, wlist, [])
- except select.error, e: # pragma: no cover
+ except select.error, e: # pragma: no cover
err, msg = e.args
if err == errno.EINTR:
break
raise
else:
- break # Let's not busywait waiting for processes to die.
+ break # Let's not busywait waiting for processes to die.
if procs[0].stdin in w and pos < len(feed_stdin):
- data = feed_stdin[pos : pos+io_size]
+ data = feed_stdin[pos:pos+io_size]
procs[0].stdin.write(data)
pos += len(data)
if pos >= len(feed_stdin):
@@ -250,7 +253,6 @@ def _run_pipeline(procs, feed_stdin, pipe_stdin, pipe_stdout, pipe_stderr,
return errorcodes[-1], ''.join(out), ''.join(err)
-
def shell_quote(s):
'''Return a shell-quoted version of s.'''
@@ -272,7 +274,7 @@ def shell_quote(s):
return ''.join(quoted)
-def ssh_runcmd(target, argv, **kwargs): # pragma: no cover
+def ssh_runcmd(target, argv, **kwargs): # pragma: no cover
'''Run command in argv on remote host target.
This is similar to runcmd, but the command is run on the remote
diff --git a/cliapp/runcmd_tests.py b/cliapp/runcmd_tests.py
index fff54ad..ce7ef8a 100644
--- a/cliapp/runcmd_tests.py
+++ b/cliapp/runcmd_tests.py
@@ -54,9 +54,9 @@ class RuncmdTests(unittest.TestCase):
'hello, world')
def test_runcmd_pipes_stdin_through_two_commands(self):
- self.assertEqual(cliapp.runcmd(
- ['cat'], ['cat'], feed_stdin='hello, world'),
- 'hello, world')
+ self.assertEqual(
+ cliapp.runcmd(['cat'], ['cat'], feed_stdin='hello, world'),
+ 'hello, world')
def test_runcmd_pipes_stdin_through_command_with_lots_of_data(self):
data = 'x' * (1024**2)
@@ -77,15 +77,14 @@ class RuncmdTests(unittest.TestCase):
(1, '', ''))
def test_runcmd_unchecked_runs_simple_pipeline(self):
- self.assertEqual(cliapp.runcmd_unchecked(
- ['echo', 'foo'], ['wc', '-c']),
- (0, '4\n', ''))
+ self.assertEqual(
+ cliapp.runcmd_unchecked(['echo', 'foo'], ['wc', '-c']),
+ (0, '4\n', ''))
def test_runcmd_unchecked_runs_longer_pipeline(self):
- self.assertEqual(cliapp.runcmd_unchecked(['echo', 'foo'],
- ['cat'],
- ['wc', '-c']),
- (0, '4\n', ''))
+ self.assertEqual(
+ cliapp.runcmd_unchecked(['echo', 'foo'], ['cat'], ['wc', '-c']),
+ (0, '4\n', ''))
def test_runcmd_redirects_stdin_from_file(self):
fd, filename = tempfile.mkstemp()
diff --git a/cliapp/settings.py b/cliapp/settings.py
index 8072a31..80fb461 100644
--- a/cliapp/settings.py
+++ b/cliapp/settings.py
@@ -42,7 +42,7 @@ class UnknownConfigVariable(cliapp.AppException):
self.msg = (
'%s: Unknown configuration variable %s' % (filename, name))
- def __str__(self): # pragma: no cover
+ def __str__(self): # pragma: no cover
return self.msg
@@ -53,8 +53,8 @@ class Setting(object):
nargs = 1
choices = None
- def __init__(
- self, names, default, help, metavar=None, group=None, hidden=False):
+ def __init__(self, names, default, help, metavar=None, group=None,
+ hidden=False):
self.names = names
self.set_value(default)
self.help = help
@@ -85,7 +85,7 @@ class Setting(object):
def parse_value(self, string):
self.value = string
- def format(self): # pragma: no cover
+ def format(self): # pragma: no cover
return str(self.value)
@@ -99,8 +99,8 @@ class StringListSetting(Setting):
action = 'append'
- def __init__(
- self, names, default, help, metavar=None, group=None, hidden=False):
+ def __init__(self, names, default, help, metavar=None, group=None,
+ hidden=False):
Setting.__init__(
self, names, [], help, metavar=metavar, group=group, hidden=hidden)
self.default = default
@@ -125,7 +125,7 @@ class StringListSetting(Setting):
def parse_value(self, string):
self.value = [s.strip() for s in string.split(',')]
- def format(self): # pragma: no cover
+ def format(self): # pragma: no cover
return ', '.join(self.value)
@@ -133,8 +133,8 @@ class ChoiceSetting(Setting):
type = 'choice'
- def __init__(
- self, names, choices, help, metavar=None, group=None, hidden=False):
+ def __init__(self, names, choices, help, metavar=None, group=None,
+ hidden=False):
Setting.__init__(
self, names, choices[0], help, metavar=metavar, group=group,
hidden=hidden)
@@ -222,7 +222,7 @@ class IntegerSetting(Setting):
class FormatHelpParagraphs(optparse.IndentedHelpFormatter):
- def _format_text(self, text): # pragma: no cover
+ def _format_text(self, text): # pragma: no cover
'''Like the default, except handle paragraphs.'''
fmt = cliapp.TextFormat(width=self.width)
@@ -292,30 +292,30 @@ class Settings(object):
self.string(['log'],
'write log entries to FILE (default is to not write log '
- 'files at all); use "syslog" to log to system log, '
- 'or "none" to disable logging',
+ 'files at all); use "syslog" to log to system log, '
+ 'or "none" to disable logging',
metavar='FILE', group=log_group_name)
self.choice(['log-level'],
['debug', 'info', 'warning', 'error', 'critical', 'fatal'],
'log at LEVEL, one of debug, info, warning, '
- 'error, critical, fatal (default: %default)',
+ 'error, critical, fatal (default: %default)',
metavar='LEVEL', group=log_group_name)
self.bytesize(['log-max'],
'rotate logs larger than SIZE, '
- 'zero for never (default: %default)',
+ 'zero for never (default: %default)',
metavar='SIZE', default=0, group=log_group_name)
self.integer(['log-keep'], 'keep last N logs (%default)',
metavar='N', default=10, group=log_group_name)
self.string(['log-mode'],
'set permissions of new log files to MODE (octal; '
- 'default %default)',
+ 'default %default)',
metavar='MODE', default='0600', group=log_group_name)
self.choice(['dump-memory-profile'],
['simple', 'none', 'meliae', 'heapy'],
'make memory profiling dumps using METHOD, which is one '
- 'of: none, simple, meliae, or heapy '
- '(default: %default)',
+ 'of: none, simple, meliae, or heapy '
+ '(default: %default)',
metavar='METHOD',
group=perf_group_name)
self.integer(['memory-dump-interval'],
@@ -403,8 +403,8 @@ class Settings(object):
for name in setting_names:
if not self._settingses[name].has_value():
- messages.append('Setting %s has no value, '
- 'but one is required' % name)
+ messages.append(
+ 'Setting %s has no value, but one is required' % name)
if len(messages) > 0:
raise cliapp.AppException('\n'.join(messages))
@@ -430,13 +430,12 @@ class Settings(object):
# Call a callback function unless we're in configs_only mode.
maybe = lambda func: (lambda *args: None) if configs_only else func
-
# Maintain lists of callback function calls that are deferred.
# We call them ourselves rather than have OptionParser call them
# directly so that we can do things like --dump-config only
# after the whole command line is parsed.
- def defer_last(func): # pragma: no cover
+ def defer_last(func): # pragma: no cover
def callback(*args):
deferred_last.append(lambda: func(*args))
return callback
@@ -485,82 +484,87 @@ class Settings(object):
# Add --dump-setting-names.
- def dump_setting_names(*args): # pragma: no cover
+ def dump_setting_names(*args): # pragma: no cover
for name in self._canonical_names:
sys.stdout.write('%s\n' % name)
sys.exit(0)
- config_group.add_option('--dump-setting-names',
- action='callback',
- nargs=0,
- callback=defer_last(maybe(dump_setting_names)),
- help=help_text(
- 'write out all names of settings and quit', True))
+ config_group.add_option(
+ '--dump-setting-names',
+ action='callback',
+ nargs=0,
+ callback=defer_last(maybe(dump_setting_names)),
+ help=help_text('write out all names of settings and quit', True))
# Add --dump-config.
- def call_dump_config(*args): # pragma: no cover
+ def call_dump_config(*args): # pragma: no cover
self.dump_config(sys.stdout)
sys.exit(0)
- config_group.add_option('--dump-config',
- action='callback',
- nargs=0,
- callback=defer_last(maybe(call_dump_config)),
- help='write out the entire current configuration')
+ config_group.add_option(
+ '--dump-config',
+ action='callback',
+ nargs=0,
+ callback=defer_last(maybe(call_dump_config)),
+ help='write out the entire current configuration')
# Add --no-default-configs.
def reset_configs(option, opt_str, value, parser):
self.config_files = []
- config_group.add_option('--no-default-configs',
- action='callback',
- nargs=0,
- callback=reset_configs,
- help='clear list of configuration files to read')
+ config_group.add_option(
+ '--no-default-configs',
+ action='callback',
+ nargs=0,
+ callback=reset_configs,
+ help='clear list of configuration files to read')
# Add --config.
def append_to_configs(option, opt_str, value, parser):
self.config_files.append(value)
- config_group.add_option('--config',
- action='callback',
- nargs=1,
- type='string',
- callback=append_to_configs,
- help='add FILE to config files',
- metavar='FILE')
+ config_group.add_option(
+ '--config',
+ action='callback',
+ nargs=1,
+ type='string',
+ callback=append_to_configs,
+ help='add FILE to config files',
+ metavar='FILE')
# Add --list-config-files.
- def list_config_files(*args): # pragma: no cover
+ def list_config_files(*args): # pragma: no cover
for filename in self.config_files:
print filename
sys.exit(0)
- config_group.add_option('--list-config-files',
- action='callback',
- nargs=0,
- callback=defer_last(maybe(list_config_files)),
- help=help_text('list all possible config files', True))
+ config_group.add_option(
+ '--list-config-files',
+ action='callback',
+ nargs=0,
+ callback=defer_last(maybe(list_config_files)),
+ help=help_text('list all possible config files', True))
# Add --generate-manpage.
self._arg_synopsis = arg_synopsis
self._cmd_synopsis = cmd_synopsis
- p.add_option('--generate-manpage',
- action='callback',
- nargs=1,
- type='string',
- callback=maybe(self._generate_manpage),
- help=help_text('fill in manual page TEMPLATE', True),
- metavar='TEMPLATE')
+ p.add_option(
+ '--generate-manpage',
+ action='callback',
+ nargs=1,
+ type='string',
+ callback=maybe(self._generate_manpage),
+ help=help_text('fill in manual page TEMPLATE', True),
+ metavar='TEMPLATE')
# Add --help-all.
- def help_all(*args): # pragma: no cover
+ def help_all(*args): # pragma: no cover
pp = self.build_parser(
configs_only=configs_only,
arg_synopsis=arg_synopsis,
@@ -635,9 +639,9 @@ class Settings(object):
return p
def parse_args(self, args, parser=None, suppress_errors=False,
- configs_only=False, arg_synopsis=None,
- cmd_synopsis=None, compute_setting_values=None,
- all_options=False):
+ configs_only=False, arg_synopsis=None,
+ cmd_synopsis=None, compute_setting_values=None,
+ all_options=False):
'''Parse the command line.
Return list of non-option arguments. ``args`` would usually
@@ -657,9 +661,9 @@ class Settings(object):
p.error = lambda msg: sys.exit(1)
options, args = p.parse_args(args)
- if compute_setting_values: # pragma: no cover
+ if compute_setting_values: # pragma: no cover
compute_setting_values(self)
- for callback in deferred_last: # pragma: no cover
+ for callback in deferred_last: # pragma: no cover
callback()
return args
@@ -680,7 +684,7 @@ class Settings(object):
configs += self._listconfs('/etc/%s' % self.progname)
configs.append(os.path.expanduser('~/.%s.conf' % self.progname))
configs += self._listconfs(
- os.path.expanduser('~/.config/%s' % self.progname))
+ os.path.expanduser('~/.config/%s' % self.progname))
return configs
@@ -716,7 +720,7 @@ class Settings(object):
def set_from_raw_string(self, pathname, name, raw_string):
'''Set value of a setting from a raw, unparsed string value.'''
if name not in self._settingses:
- raise UnknownConfigVariable(pathname, name)
+ raise UnknownConfigVariable(pathname, name)
s = self._settingses[name]
s.parse_value(raw_string)
return s
@@ -749,7 +753,7 @@ class Settings(object):
# Remember the ConfigParser for use in as_cp later on.
self._cp = cp
- def _generate_manpage(self, o, os, value, p): # pragma: no cover
+ def _generate_manpage(self, o, os, value, p): # pragma: no cover
template = open(value).read()
generator = ManpageGenerator(template, p, self._arg_synopsis,
self._cmd_synopsis)
@@ -778,7 +782,6 @@ class Settings(object):
return cp
- def dump_config(self, output): # pragma: no cover
+ def dump_config(self, output): # pragma: no cover
cp = self.as_cp()
cp.write(output)
-
diff --git a/cliapp/settings_tests.py b/cliapp/settings_tests.py
index f78d43a..b5b9eaa 100644
--- a/cliapp/settings_tests.py
+++ b/cliapp/settings_tests.py
@@ -414,7 +414,7 @@ unknown = variable
def test_require_raises_error_when_one_value_of_several_is_unset(self):
self.settings.string(['foo'], 'foo help')
- self.settings.string(['bar'], 'bar help', default=None )
+ self.settings.string(['bar'], 'bar help', default=None)
args = ['foo', 'bar']
self.assertRaises(cliapp.AppException, self.settings.require, *args)
@@ -451,4 +451,3 @@ bar = dodo
self.assertEqual(cp.get('config', 'foo'), 'yeehaa')
self.assertEqual(cp.options('other'), ['bar'])
self.assertEqual(cp.get('other', 'bar'), 'dodo')
-