Skip to content

Commit 87e923a

Browse files
committed
add pycodestyle and fix issues.
1 parent 78b20f3 commit 87e923a

28 files changed

+329
-284
lines changed

Diff for: .github/workflows/ci.yml

+1
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ jobs:
4646
- run: pip freeze
4747
- run: pip check
4848
- run: doit pyflakes
49+
- run: doit codestyle
4950
- run: py.test -vv ${{ matrix.pytest-args }}
5051
- if: ${{ matrix.os == 'ubuntu' && matrix.python-version == '3.8' }}
5152
run: |

Diff for: dev_requirements.txt

+3-2
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@
33

44
setuptools # for plugins
55
pyflakes
6-
pytest>=5.4.1
7-
coverage>=4.0,<5
6+
pycodestyle
7+
pytest>=7.1.0
8+
coverage>=6.0
89
doit-py>=0.4.0
910
tomli; python_version<"3.11"

Diff for: dodo.py

+6
Original file line numberDiff line numberDiff line change
@@ -134,3 +134,9 @@ def task_package():
134134
yield pkg.manifest_git()
135135
yield pkg.sdist()
136136
# yield pkg.sdist_upload()
137+
138+
139+
def task_codestyle():
140+
return {
141+
'actions': ['pycodestyle doit'],
142+
}

Diff for: doit/__main__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# lazy way to ignore coverage in this file
2-
if True: # pragma: no cover
2+
if True: # pragma: no cover
33
def main():
44
import sys
55

Diff for: doit/action.py

+23-21
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22
"""
33

44
import os
5-
import subprocess, sys
5+
import sys
6+
import subprocess
67
import io
78
from io import StringIO
89
import inspect
@@ -21,6 +22,7 @@ def normalize_callable(ref):
2122
return list(ref)
2223
return [ref, (), {}]
2324

25+
2426
# Actions
2527
class BaseAction(object):
2628
"""Base class for all actions"""
@@ -45,15 +47,15 @@ def _prepare_kwargs(task, func, args, kwargs):
4547

4648
func_sig = inspect.signature(func)
4749
sig_params = func_sig.parameters.values()
48-
func_has_kwargs = any(p.kind==p.VAR_KEYWORD for p in sig_params)
50+
func_has_kwargs = any(p.kind == p.VAR_KEYWORD for p in sig_params)
4951

5052
# use task meta information as extra_args
5153
meta_args = {
5254
'task': lambda: task,
5355
'targets': lambda: list(task.targets),
5456
'dependencies': lambda: list(task.file_dep),
5557
'changed': lambda: list(task.dep_changed),
56-
}
58+
}
5759

5860
# start with dict passed together on action definition
5961
kwargs = kwargs.copy()
@@ -67,17 +69,16 @@ def _prepare_kwargs(task, func, args, kwargs):
6769

6870
# it is forbidden to use default values for this arguments
6971
# because the user might be unaware of this magic.
70-
if (sig_param.default!=sig_param.empty):
71-
msg = ("Task %s, action %s(): The argument '%s' is not "
72-
"allowed to have a default value (reserved by doit)"
73-
% (task.name, func.__name__, key))
72+
if (sig_param.default != sig_param.empty):
73+
msg = (f"Task {task.name}, action {func.__name__}():"
74+
f"The argument '{key}' is not allowed to have "
75+
"a default value (reserved by doit)")
7476
raise InvalidTask(msg)
7577

7678
# if value not taken from position parameter
7779
if key not in bound_args.arguments:
7880
kwargs[key] = meta_args[key]()
7981

80-
8182
# add tasks parameter options
8283
opt_args = dict(task.options)
8384
if task.pos_arg is not None:
@@ -120,7 +121,7 @@ class CmdAction(BaseAction):
120121

121122
def __init__(self, action, task=None, save_out=None, shell=True,
122123
encoding='utf-8', decode_error='replace', buffering=0,
123-
**pkwargs): #pylint: disable=W0231
124+
**pkwargs): # pylint: disable=W0231
124125
'''
125126
:ivar buffering: (int) stdout/stderr buffering.
126127
Not to be confused with subprocess buffering
@@ -168,7 +169,7 @@ def _print_process_output(self, process, input_, capture, realtime):
168169
while True:
169170
try:
170171
line = read().decode(self.encoding, self.decode_error)
171-
except:
172+
except Exception:
172173
# happens when fails to decoded input
173174
process.terminate()
174175
input_.read()
@@ -178,7 +179,7 @@ def _print_process_output(self, process, input_, capture, realtime):
178179
capture.write(line)
179180
if realtime:
180181
realtime.write(line)
181-
realtime.flush() # required if on byte buffering mode
182+
realtime.flush() # required if on byte buffering mode
182183

183184

184185
def execute(self, out=None, err=None):
@@ -223,7 +224,7 @@ def execute(self, out=None, err=None):
223224
process = subprocess.Popen(
224225
action,
225226
shell=self.shell,
226-
#bufsize=2, # ??? no effect use PYTHONUNBUFFERED instead
227+
# bufsize=2, # ??? no effect use PYTHONUNBUFFERED instead
227228
stdout=p_out,
228229
stderr=p_err,
229230
env=env,
@@ -283,14 +284,14 @@ def expand_action(self):
283284
elif isinstance(element, PurePath):
284285
action.append(str(element))
285286
else:
286-
msg = ("%s. CmdAction element must be a str " +
287+
msg = ("%s. CmdAction element must be a str "
287288
"or Path from pathlib. Got '%r' (%s)")
288289
raise InvalidTask(
289290
msg % (self.task.name, element, type(element)))
290291
return action
291292

292293
subs_dict = {
293-
'targets' : " ".join(self.task.targets),
294+
'targets': " ".join(self.task.targets),
294295
'dependencies': " ".join(self.task.file_dep),
295296
}
296297

@@ -330,12 +331,13 @@ def __repr__(self):
330331
class Writer(object):
331332
"""Write to N streams.
332333
333-
This is used on python-actions to allow the stream to be output to terminal and captured at the same time.
334+
This is used on python-actions to allow the stream to be output to terminal
335+
and captured at the same time.
334336
"""
335337
def __init__(self, *writers):
336338
"""@param writers - file stream like objects"""
337339
self.writers = []
338-
self.orig_stream = None # The original stream terminal/file
340+
self.orig_stream = None # The original stream terminal/file
339341
for writer in writers:
340342
self.add_writer(writer)
341343

@@ -380,7 +382,7 @@ class PythonAction(BaseAction):
380382
pm_pdb = False
381383

382384
def __init__(self, py_callable, args=None, kwargs=None, task=None):
383-
#pylint: disable=W0231
385+
# pylint: disable=W0231
384386
self.py_callable = py_callable
385387
self.task = task
386388
self.out = None
@@ -458,7 +460,7 @@ def execute(self, out=None, err=None):
458460
try:
459461
returned_value = self.py_callable(*self.args, **kwargs)
460462
except Exception as exception:
461-
if self.pm_pdb: # pragma: no cover
463+
if self.pm_pdb: # pragma: no cover
462464
# start post-mortem debugger
463465
deb = pdb.Pdb(stdin=sys.__stdin__, stdout=sys.__stdout__)
464466
deb.reset()
@@ -495,10 +497,10 @@ def execute(self, out=None, err=None):
495497

496498
def __str__(self):
497499
# get object description excluding runtime memory address
498-
return "Python: %s"% str(self.py_callable)[1:].split(' at ')[0]
500+
return "Python: %s" % str(self.py_callable)[1:].split(' at ')[0]
499501

500502
def __repr__(self):
501-
return "<PythonAction: '%s'>"% (repr(self.py_callable))
503+
return "<PythonAction: '%s'>" % (repr(self.py_callable))
502504

503505

504506
def create_action(action, task_ref, param_name):
@@ -526,7 +528,7 @@ def create_action(action, task_ref, param_name):
526528
msg = "Task '{}': invalid '{}' tuple length. got: {!r} {}".format(
527529
task_ref.name, param_name, action, type(action))
528530
raise InvalidTask(msg)
529-
py_callable, args, kwargs = (list(action) + [None]*(3-len(action)))
531+
py_callable, args, kwargs = (list(action) + [None] * (3 - len(action)))
530532
return PythonAction(py_callable, args, kwargs, task_ref)
531533

532534
if hasattr(action, '__call__'):

Diff for: doit/api.py

+8-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
1-
"""Definition of stuff that can be used directly by a user in a dodo.py file."""
1+
"""APIs to execute doit in non standard way.
2+
3+
- run(): shortcut to get tasks from current module/dict (instead of dodo.py).
4+
- run_tasks(): to be used by custom CLIs, run tasks without CLI parsing.
5+
6+
"""
27

38
import sys
49

@@ -23,7 +28,7 @@ def run_tasks(loader, tasks, extra_config=None):
2328
2429
:params tasks: list of task names (str)
2530
"""
26-
loader.task_opts = tasks # task_opts will be used as @task_param
31+
loader.task_opts = tasks # task_opts will be used as @task_param
2732
main = DoitMain(loader, extra_config=extra_config)
2833
task_names = list(tasks.keys())
2934

@@ -39,7 +44,7 @@ def run_tasks(loader, tasks, extra_config=None):
3944
bin_name=main.BIN_NAME,
4045
cmds=sub_cmds,
4146
opt_vals={},
42-
)
47+
)
4348

4449
try:
4550
return command.parse_execute(task_names)

Diff for: doit/cmd_base.py

+24-25
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ def version_tuple(ver_in):
2626
for rev in parts:
2727
try:
2828
result.append(int(rev))
29-
except:
29+
except ValueError:
3030
result.append(-1)
3131
assert len(result) == 3
3232
return result
@@ -65,7 +65,7 @@ class Command(object):
6565
# doc attributes, should be sub-classed
6666
doc_purpose = ''
6767
doc_usage = ''
68-
doc_description = None # None value will completely omit line from doc
68+
doc_description = None # None value will completely omit line from doc
6969

7070
# sequence of dicts
7171
cmd_options = tuple()
@@ -130,7 +130,7 @@ def get_options(self):
130130
return [CmdOption(opt) for opt in self.cmd_options]
131131

132132

133-
def execute(self, opt_values, pos_args): # pragma: no cover
133+
def execute(self, opt_values, pos_args): # pragma: no cover
134134
"""execute command
135135
:param opt_values: (dict) with cmd_options values
136136
:param pos_args: (list) of cmd-line positional arguments
@@ -200,7 +200,7 @@ def help(self):
200200
opt_depfile = {
201201
'section': 'DB backend',
202202
'name': 'dep_file',
203-
'short':'',
203+
'short': '',
204204
'long': 'db-file',
205205
'type': str,
206206
'default': ".doit.db",
@@ -211,7 +211,7 @@ def help(self):
211211
opt_backend = {
212212
'section': 'DB backend',
213213
'name': 'backend',
214-
'short':'',
214+
'short': '',
215215
'long': 'backend',
216216
'type': str,
217217
'default': "dbm",
@@ -251,24 +251,24 @@ def help(self):
251251
opt_dodo = {
252252
'section': 'task loader',
253253
'name': 'dodoFile',
254-
'short':'f',
254+
'short': 'f',
255255
'long': 'file',
256256
'type': str,
257257
'default': 'dodo.py',
258258
'env_var': 'DOIT_FILE',
259-
'help':"load task from dodo FILE [default: %(default)s]"
259+
'help': "load task from dodo FILE [default: %(default)s]"
260260
}
261261

262262
# cwd
263263
opt_cwd = {
264264
'section': 'task loader',
265265
'name': 'cwdPath',
266-
'short':'d',
266+
'short': 'd',
267267
'long': 'dir',
268268
'type': str,
269269
'default': None,
270-
'help':("set path to be used as cwd directory (file paths on " +
271-
"dodo file are relative to dodo.py location).")
270+
'help': ("set path to be used as cwd directory "
271+
"(file paths on dodo file are relative to dodo.py location).")
272272
}
273273

274274
# seek dodo file on parent folders
@@ -280,14 +280,14 @@ def help(self):
280280
'type': bool,
281281
'default': False,
282282
'env_var': 'DOIT_SEEK_FILE',
283-
'help': ("seek dodo file on parent folders " +
284-
"[default: %(default)s]")
283+
'help': ("seek dodo file on parent folders [default: %(default)s]")
285284
}
286285

287286

288287
class TaskLoader():
289288
def __init__(self):
290-
raise NotImplementedError('doit.cmd_base.py:TaskLoader was removed on 0.36.0, use TaskLoader2 instead')
289+
raise NotImplementedError(
290+
'doit.cmd_base.py:TaskLoader was removed on 0.36.0, use TaskLoader2 instead')
291291

292292
class TaskLoader2():
293293
"""Interface of task loaders with new-style API.
@@ -305,8 +305,8 @@ class TaskLoader2():
305305
def __init__(self):
306306
# list of command names, used to detect clash of task names and commands
307307
self.cmd_names = []
308-
self.config = None # reference to config object taken from Command
309-
self.task_opts = None # dict with task options (no need parsing, API usage)
308+
self.config = None # reference to config object taken from Command
309+
self.task_opts = None # dict with task options (no need parsing, API usage)
310310

311311
def setup(self, opt_values):
312312
"""Delayed initialization.
@@ -417,7 +417,7 @@ def get_loader(config, task_loader=None, cmds=None):
417417
loader = plugins.get_plugin(loader_name)()
418418

419419
if not loader:
420-
loader = DodoTaskLoader() # default loader
420+
loader = DodoTaskLoader() # default loader
421421

422422
if cmds:
423423
loader.cmd_names = list(sorted(cmds.keys()))
@@ -438,9 +438,9 @@ class DoitCmdBase(Command):
438438

439439
def __init__(self, task_loader, cmds=None, **kwargs):
440440
super(DoitCmdBase, self).__init__(**kwargs)
441-
self.sel_tasks = None # selected tasks for command
442-
self.sel_default_tasks = True # False if tasks were specified from command line
443-
self.dep_manager = None #
441+
self.sel_tasks = None # selected tasks for command
442+
self.sel_default_tasks = True # False if tasks were specified from command line
443+
self.dep_manager = None
444444
self.outstream = sys.stdout
445445
self.loader = task_loader
446446
self._backends = self.get_backends()
@@ -449,12 +449,11 @@ def __init__(self, task_loader, cmds=None, **kwargs):
449449
def get_options(self):
450450
"""from base class - merge base_options, loader_options and cmd_options
451451
"""
452-
opt_list = (self.base_options + self.loader.cmd_options +
453-
self.cmd_options)
452+
opt_list = (self.base_options + self.loader.cmd_options + self.cmd_options)
454453
return [CmdOption(opt) for opt in opt_list]
455454

456455

457-
def _execute(self): # pragma: no cover
456+
def _execute(self): # pragma: no cover
458457
"""to be subclassed - actual command implementation"""
459458
raise NotImplementedError
460459

@@ -508,7 +507,7 @@ def get_backends(self):
508507

509508
# set choices, sub-classes might not have this option
510509
if 'backend' in self.cmdparser:
511-
choices = {k: getattr(v, 'desc', '') for k,v in backend_map.items()}
510+
choices = {k: getattr(v, 'desc', '') for k, v in backend_map.items()}
512511
self.cmdparser['backend'].choices = choices
513512

514513
return backend_map
@@ -592,8 +591,8 @@ def tasks_and_deps_iter(tasks, sel_tasks, yield_duplicates=False):
592591
@param tasks (dict - Task)
593592
@param sel_tasks(list - str)
594593
"""
595-
processed = set() # str - task name
596-
to_process = deque(sel_tasks) # str - task name
594+
processed = set() # str - task name
595+
to_process = deque(sel_tasks) # str - task name
597596
# get initial task
598597
while to_process:
599598
task = tasks[to_process.popleft()]

0 commit comments

Comments
 (0)