Skip to content

Commit 2231714

Browse files
committed
type and lint cleanups
1 parent f1901b9 commit 2231714

File tree

7 files changed

+211
-157
lines changed

7 files changed

+211
-157
lines changed

cwltool/cwlrdf.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from typing import Any, Union, Dict, IO
77

88
def makerdf(workflow, wf, ctx):
9-
# type: (str, Dict[str,Any], Loader.ContextType) -> Graph
9+
# type: (Union[str, unicode], Dict[str,Any], Loader.ContextType) -> Graph
1010
prefixes = {}
1111
for k,v in ctx.iteritems():
1212
if isinstance(v, dict):
@@ -31,7 +31,7 @@ def makerdf(workflow, wf, ctx):
3131
return g
3232

3333
def printrdf(workflow, wf, ctx, sr, stdout):
34-
# type: (str, Dict[str,Any], Loader.ContextType, str, IO[Any]) -> None
34+
# type: (Union[str, unicode], Dict[str, Any], Loader.ContextType, str, IO[Any]) -> None
3535
stdout.write(makerdf(workflow, wf, ctx).serialize(format=sr))
3636

3737
def lastpart(uri): # type: (Any) -> str
@@ -172,7 +172,7 @@ def dot_without_parameters(g, stdout): # type: (Graph, IO[Any]) -> None
172172

173173

174174
def printdot(workflow, wf, ctx, stdout, include_parameters=False):
175-
# type: (str, Dict[str,Any], Loader.ContextType, Any, bool) -> None
175+
# type: (Union[str, unicode], Dict[str, Any], Loader.ContextType, Any, bool) -> None
176176
g = makerdf(workflow, wf, ctx)
177177

178178
stdout.write("digraph {")

cwltool/factory.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
from . import main
2+
from . import load_tool
23
from . import workflow
34
import os
45
from .process import Process
@@ -23,8 +24,9 @@ def __init__(self, makeTool=workflow.defaultMakeTool,
2324
self.executor = executor
2425
self.execkwargs = execkwargs
2526

26-
def make(self, cwl, frag=None, debug=False):
27-
l = main.load_tool(cwl, self.makeTool)
28-
if type(l) == int:
27+
def make(self, cwl):
28+
"""Instantiate a CWL object from a CWl document."""
29+
load = load_tool.load_tool(cwl, self.makeTool)
30+
if isinstance(load, int):
2931
raise Exception("Error loading tool")
30-
return Callable(l, self)
32+
return Callable(load, self)

cwltool/load_tool.py

Lines changed: 54 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,68 +1,80 @@
1+
# pylint: disable=unused-import
2+
"""Loads a CWL document."""
3+
14
import os
25
import logging
36
import re
47
import urlparse
5-
import sys
6-
import json
78
from schema_salad.ref_resolver import Loader
89
import schema_salad.validate as validate
910
import schema_salad.schema as schema
11+
from avro.schema import Names
1012
from . import update
1113
from . import process
14+
from .process import Process, shortname
15+
from .errors import WorkflowException
16+
from typing import Any, Callable, cast, Dict, Tuple, Union
1217

13-
_logger = logging.getLogger("cwltool")
1418

1519
def fetch_document(argsworkflow):
20+
# type: (Union[str, unicode, dict[unicode, Any]]) -> Tuple[Loader, Dict[unicode, Any], unicode]
21+
"""Retrieve a CWL document."""
1622
document_loader = Loader({"cwl": "https://w3id.org/cwl/cwl#", "id": "@id"})
1723

18-
jobobj = None
19-
uri = None # type: str
24+
uri = None # type: unicode
2025
workflowobj = None # type: Dict[unicode, Any]
21-
if isinstance(argsworkflow, basestring):
26+
if isinstance(argsworkflow, (str, unicode)):
2227
split = urlparse.urlsplit(argsworkflow)
2328
if split.scheme:
2429
uri = argsworkflow
2530
else:
2631
uri = "file://" + os.path.abspath(argsworkflow)
27-
fileuri, urifrag = urlparse.urldefrag(uri)
32+
fileuri = urlparse.urldefrag(uri)[0]
2833
workflowobj = document_loader.fetch(fileuri)
2934
elif isinstance(argsworkflow, dict):
3035
workflowobj = argsworkflow
3136
uri = "#" + str(id(argsworkflow))
3237
else:
33-
raise validate.ValidationException("Must be URI or object: '%s'" % argsworkflow)
38+
raise validate.ValidationException(
39+
"Must be URI or object: '%s'" % argsworkflow)
3440

3541
return document_loader, workflowobj, uri
3642

3743

3844
def validate_document(document_loader, workflowobj, uri,
3945
enable_dev=False, strict=True, preprocess_only=False):
46+
# type: (Loader, Dict[unicode, Any], unicode, bool, bool, bool) -> Tuple[Loader, Names, Any, Dict[str, str], unicode]
47+
"""Validate a CWL document."""
4048
jobobj = None
4149
if "cwl:tool" in workflowobj:
4250
jobobj = workflowobj
4351
uri = urlparse.urljoin(uri, jobobj["cwl:tool"])
4452
del jobobj["cwl:tool"]
45-
workflowobj = fetch_document(uri)
53+
workflowobj = fetch_document(uri)[1]
4654

4755
if isinstance(workflowobj, list):
4856
workflowobj = {
4957
"$graph": workflowobj
5058
}
5159

52-
fileuri, urifrag = urlparse.urldefrag(uri)
60+
fileuri = urlparse.urldefrag(uri)[0]
5361

5462
if "cwlVersion" in workflowobj:
55-
workflowobj["cwlVersion"] = re.sub(r"^(?:cwl:|https://w3id.org/cwl/cwl#)", "", workflowobj["cwlVersion"])
63+
workflowobj["cwlVersion"] = re.sub(
64+
r"^(?:cwl:|https://w3id.org/cwl/cwl#)", "",
65+
workflowobj["cwlVersion"])
5666
else:
5767
workflowobj["cwlVersion"] = "draft-2"
5868

5969
if workflowobj["cwlVersion"] == "draft-2":
60-
workflowobj = update._draft2toDraft3dev1(workflowobj, document_loader, uri, updateSteps=False)
70+
workflowobj = update._draft2toDraft3dev1(
71+
workflowobj, document_loader, uri, update_steps=False)[0]
6172
if "@graph" in workflowobj:
6273
workflowobj["$graph"] = workflowobj["@graph"]
6374
del workflowobj["@graph"]
6475

65-
(document_loader, avsc_names, schema_metadata, schema_loader) = process.get_schema(workflowobj["cwlVersion"])
76+
(document_loader, avsc_names) = \
77+
process.get_schema(workflowobj["cwlVersion"])[:2]
6678

6779
if isinstance(avsc_names, Exception):
6880
raise avsc_names
@@ -78,29 +90,36 @@ def validate_document(document_loader, workflowobj, uri,
7890

7991
if not metadata:
8092
metadata = {"$namespaces": processobj.get("$namespaces", {}),
81-
"$schemas": processobj.get("$schemas", []),
82-
"cwlVersion": processobj["cwlVersion"]}
93+
"$schemas": processobj.get("$schemas", []),
94+
"cwlVersion": processobj["cwlVersion"]}
8395

84-
if metadata.get("cwlVersion") != update.latest:
85-
processobj = update.update(processobj, document_loader, fileuri, enable_dev, metadata)
96+
if metadata.get("cwlVersion") != update.LATEST:
97+
processobj = update.update(
98+
processobj, document_loader, fileuri, enable_dev, metadata)
8699

87100
if jobobj:
88101
metadata["cwl:defaults"] = jobobj
89102

90103
return document_loader, avsc_names, processobj, metadata, uri
91104

92105

93-
def make_tool(document_loader, avsc_names, processobj, metadata, uri, makeTool, kwargs):
94-
processobj, _ = document_loader.resolve_ref(uri)
106+
def make_tool(document_loader, avsc_names, processobj, metadata, uri, makeTool,
107+
kwargs):
108+
# type: (Loader, Names, Dict[str, Any], Dict[str, Any], unicode, Callable[..., Process], Dict[str, Any]) -> Process
109+
"""Make a Python CWL object."""
110+
resolveduri = document_loader.resolve_ref(uri)[0]
95111

96-
if isinstance(processobj, list):
97-
if 1 == len(processobj):
98-
processobj = processobj[0]
112+
if isinstance(resolveduri, list):
113+
if len(resolveduri) == 1:
114+
processobj = resolveduri[0]
99115
else:
100-
raise WorkflowException(u"Tool file contains graph of multiple objects, "
101-
"must specify one of #%s" %
102-
", #".join(urlparse.urldefrag(i["id"])[1]
103-
for i in processobj if "id" in i))
116+
raise WorkflowException(
117+
u"Tool file contains graph of multiple objects, must specify "
118+
"one of #%s" % ", #".join(
119+
urlparse.urldefrag(i["id"])[1] for i in resolveduri
120+
if "id" in i))
121+
else:
122+
processobj = cast(Dict[str, Any], resolveduri)
104123

105124
kwargs = kwargs.copy()
106125
kwargs.update({
@@ -109,25 +128,24 @@ def make_tool(document_loader, avsc_names, processobj, metadata, uri, makeTool,
109128
"avsc_names": avsc_names,
110129
"metadata": metadata
111130
})
112-
t = makeTool(processobj, **kwargs)
131+
tool = makeTool(processobj, **kwargs)
113132

114133
if "cwl:defaults" in metadata:
115134
jobobj = metadata["cwl:defaults"]
116-
for inp in t.tool["inputs"]:
135+
for inp in tool.tool["inputs"]:
117136
if shortname(inp["id"]) in jobobj:
118137
inp["default"] = jobobj[shortname(inp["id"])]
119138

120-
return t
139+
return tool
121140

122141

123142
def load_tool(argsworkflow, makeTool, kwargs=None,
124143
enable_dev=False,
125144
strict=True):
126-
145+
# type: (Union[str,unicode,dict[unicode,Any]], Callable[...,Process], Dict[str, Any], bool, bool) -> Any
127146
document_loader, workflowobj, uri = fetch_document(argsworkflow)
128-
document_loader, avsc_names, processobj, metadata, uri = validate_document(document_loader,
129-
workflowobj,
130-
uri,
131-
enable_dev=enable_dev,
132-
strict=strict)
133-
return make_tool(document_loader, avsc_names, processobj, metadata, uri, makeTool, kwargs if kwargs else {})
147+
document_loader, avsc_names, processobj, metadata, uri = validate_document(
148+
document_loader, workflowobj, uri, enable_dev=enable_dev,
149+
strict=strict)
150+
return make_tool(document_loader, avsc_names, processobj, metadata, uri,
151+
makeTool, kwargs if kwargs else {})

cwltool/main.py

Lines changed: 45 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -10,22 +10,19 @@
1010
import logging
1111
from . import workflow
1212
from .errors import WorkflowException
13+
from . import process
14+
from .cwlrdf import printrdf, printdot
15+
from .process import shortname, Process
16+
from .load_tool import fetch_document, validate_document, make_tool
1317
import schema_salad.validate as validate
1418
import tempfile
1519
import schema_salad.jsonld_context
1620
import schema_salad.makedoc
1721
import yaml
1822
import urlparse
19-
from . import process
20-
from . import job
21-
from .cwlrdf import printrdf, printdot
2223
import pkg_resources # part of setuptools
23-
from . import update
24-
from .process import shortname, Process
2524
import rdflib
26-
from load_tool import load_tool, fetch_document, validate_document, make_tool
2725
import hashlib
28-
from .utils import aslist
2926
from typing import Union, Any, cast, Callable, Dict, Tuple, IO
3027

3128
_logger = logging.getLogger("cwltool")
@@ -134,14 +131,16 @@ def arg_parser(): # type: () -> argparse.ArgumentParser
134131
parser.add_argument("--relative-deps", choices=['primary', 'cwd'], default="primary",
135132
help="When using --print-deps, print paths relative to primary file or current working directory.")
136133

137-
parser.add_argument("--enable-dev", action="store_true", help="Allow loading and running development versions of CWL spec.", default=False)
134+
parser.add_argument("--enable-dev", action="store_true",
135+
help="Allow loading and running development versions "
136+
"of CWL spec.", default=False)
138137

139138
parser.add_argument("--enable-net", action="store_true",
140-
help="Use docker's default networking for containers; the default is "
141-
"to disable networking.")
139+
help="Use docker's default networking for containers;"
140+
" the default is to disable networking.")
142141
parser.add_argument("--custom-net", type=str,
143-
help="Will be passed to `docker run` as the '--net' parameter. "
144-
"Implies '--enable-net'.")
142+
help="Will be passed to `docker run` as the '--net' "
143+
"parameter. Implies '--enable-net'.")
145144

146145
parser.add_argument("workflow", type=str, nargs="?", default=None)
147146
parser.add_argument("job_order", nargs=argparse.REMAINDER)
@@ -466,11 +465,10 @@ def main(argsl=None,
466465
printdeps(workflowobj, document_loader, stdout, args.relative_deps)
467466
return 0
468467

469-
document_loader, avsc_names, processobj, metadata, uri = validate_document(document_loader,
470-
workflowobj, uri,
471-
enable_dev=args.enable_dev,
472-
strict=args.strict,
473-
preprocess_only=args.print_pre)
468+
document_loader, avsc_names, processobj, metadata, uri \
469+
= validate_document(document_loader, workflowobj, uri,
470+
enable_dev=args.enable_dev, strict=args.strict,
471+
preprocess_only=args.print_pre)
474472

475473
if args.print_pre:
476474
stdout.write(json.dumps(processobj, indent=4))
@@ -484,22 +482,26 @@ def main(argsl=None,
484482
printdot(uri, processobj, document_loader.ctx, stdout)
485483
return 0
486484

487-
t = make_tool(document_loader, avsc_names, processobj,
488-
metadata, uri, makeTool, {})
489-
except (validate.ValidationException) as e:
490-
_logger.error(u"Tool definition failed validation:\n%s", e, exc_info=(e if args.debug else False))
485+
tool = make_tool(document_loader, avsc_names, processobj, metadata,
486+
uri, makeTool, {})
487+
except (validate.ValidationException) as exc:
488+
_logger.error(u"Tool definition failed validation:\n%s", exc,
489+
exc_info=(exc if args.debug else False))
491490
return 1
492-
except (RuntimeError, WorkflowException) as e:
493-
_logger.error(u"Tool definition failed initialization:\n%s", e, exc_info=(e if args.debug else False))
491+
except (RuntimeError, WorkflowException) as exc:
492+
_logger.error(u"Tool definition failed initialization:\n%s", exc,
493+
exc_info=(exc if args.debug else False))
494494
return 1
495-
except Exception as e:
496-
_logger.error(u"I'm sorry, I couldn't load this CWL file%s",
497-
", try again with --debug for more information.\nThe error was: %s" % e if not args.debug else ". The error was:",
498-
exc_info=(e if args.debug else False))
495+
except Exception as exc:
496+
_logger.error(
497+
u"I'm sorry, I couldn't load this CWL file%s, try again with "
498+
"--debug for more information.\nThe error was: %s" % exc
499+
if not args.debug else ". The error was:",
500+
exc_info=(exc if args.debug else False))
499501
return 1
500502

501-
if isinstance(t, int):
502-
return t
503+
if isinstance(tool, int):
504+
return tool
503505

504506
if args.tmp_outdir_prefix != 'tmp':
505507
# Use user defined temp directory (if it exists)
@@ -515,7 +517,7 @@ def main(argsl=None,
515517
_logger.error("Temporary directory prefix doesn't exist.")
516518
return 1
517519

518-
job_order_object = load_job_order(args, t, parser, stdin,
520+
job_order_object = load_job_order(args, tool, parser, stdin,
519521
print_input_deps=args.print_input_deps,
520522
relative_deps=args.relative_deps,
521523
stdout=stdout)
@@ -528,7 +530,7 @@ def main(argsl=None,
528530
args.move_outputs = False
529531

530532
try:
531-
out = executor(t, job_order_object[0],
533+
out = executor(tool, job_order_object[0],
532534
job_order_object[1], args,
533535
conformance_test=args.conformance_test,
534536
dry_run=args.dry_run,
@@ -557,14 +559,20 @@ def main(argsl=None,
557559
stdout.flush()
558560
else:
559561
return 1
560-
except (validate.ValidationException) as e:
561-
_logger.error(u"Input object failed validation:\n%s", e, exc_info=(e if args.debug else False))
562+
except (validate.ValidationException) as exc:
563+
_logger.error(
564+
u"Input object failed validation:\n%s", exc,
565+
exc_info=(exc if args.debug else False))
562566
return 1
563-
except WorkflowException as e:
564-
_logger.error(u"Workflow error, try again with --debug for more information:\n %s", e, exc_info=(e if args.debug else False))
567+
except WorkflowException as exc:
568+
_logger.error(
569+
u"Workflow error, try again with --debug for more "
570+
"information:\n %s", exc, exc_info=(exc if args.debug else False))
565571
return 1
566-
except Exception as e:
567-
_logger.error(u"Unhandled error, try again with --debug for more information:\n %s", e, exc_info=(e if args.debug else False))
572+
except Exception as exc:
573+
_logger.error(
574+
u"Unhandled error, try again with --debug for more information:\n"
575+
" %s", exc, exc_info=(exc if args.debug else False))
568576
return 1
569577

570578
return 0

0 commit comments

Comments
 (0)