Skip to content

Commit 531358e

Browse files
committed
more type improvements (#72)
1 parent 2717c60 commit 531358e

File tree

14 files changed

+164
-122
lines changed

14 files changed

+164
-122
lines changed

cwltool/__main__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import main
1+
from . import main
22
import sys
33

44
sys.exit(main.main())

cwltool/builder.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -33,20 +33,20 @@ class Builder(object):
3333

3434
def __init__(self): # type: () -> None
3535
self.names = None # type: avro.schema.Names
36-
self.schemaDefs = None # type: Dict[str,Dict[str,str]]
37-
self.files = None # type: List[str]
36+
self.schemaDefs = None # type: Dict[str,Dict[unicode, Any]]
37+
self.files = None # type: List[Dict[str, str]]
3838
self.fs_access = None # type: StdFsAccess
39-
self.job = None # type: Dict[str,str]
39+
self.job = None # type: Dict[str, Any]
4040
self.requirements = None # type: List[Dict[str,Any]]
4141
self.outdir = None # type: str
4242
self.tmpdir = None # type: str
43-
self.resources = None # type: Dict[str,str]
44-
self.bindings = [] # type: List[Dict[str,str]]
43+
self.resources = None # type: Dict[str, Union[int, str]]
44+
self.bindings = [] # type: List[Dict[str, Any]]
4545
self.timeout = None # type: int
4646
self.pathmapper = None # type: PathMapper
4747

4848
def bind_input(self, schema, datum, lead_pos=[], tail_pos=[]):
49-
# type: (Dict[str,Any], Any, List[int], List[int]) -> List[Dict[str,str]]
49+
# type: (Dict[unicode, Any], Any, List[int], List[int]) -> List[Dict[str, Any]]
5050
bindings = [] # type: List[Dict[str,str]]
5151
binding = None # type: Dict[str,Any]
5252
if "inputBinding" in schema and isinstance(schema["inputBinding"], dict):
@@ -64,7 +64,7 @@ def bind_input(self, schema, datum, lead_pos=[], tail_pos=[]):
6464
# Handle union types
6565
if isinstance(schema["type"], list):
6666
for t in schema["type"]:
67-
if isinstance(t, basestring) and self.names.has_name(t, ""):
67+
if isinstance(t, (str, unicode)) and self.names.has_name(t, ""):
6868
avsc = self.names.get_name(t, "")
6969
elif isinstance(t, dict) and "name" in t and self.names.has_name(t["name"], ""):
7070
avsc = self.names.get_name(t["name"], "")
@@ -148,7 +148,7 @@ def _capture_files(f):
148148

149149
return bindings
150150

151-
def tostr(self, value): # type(Any) -> str
151+
def tostr(self, value): # type: (Any) -> str
152152
if isinstance(value, dict) and value.get("class") == "File":
153153
if "path" not in value:
154154
raise WorkflowException(u"File object must have \"path\": %s" % (value))

cwltool/cwlrdf.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,19 @@
11
import json
22
import urlparse
3+
from schema_salad.ref_resolver import Loader
34
from rdflib import Graph, plugin, URIRef
45
from rdflib.serializer import Serializer
56
from typing import Any, Union, Dict, IO
67

78
def makerdf(workflow, wf, ctx):
8-
# type: (str, Dict[str,Any], Dict[str,Union[str, Dict[str,str]]]) -> Graph
9+
# type: (str, Dict[str,Any], Loader.ContextType) -> Graph
910
prefixes = {}
1011
for k,v in ctx.iteritems():
1112
if isinstance(v, dict):
12-
v = v["@id"]
13-
doc_url, frg = urlparse.urldefrag(v)
13+
url = v["@id"]
14+
else:
15+
url = v
16+
doc_url, frg = urlparse.urldefrag(url)
1417
if "/" in frg:
1518
p, _ = frg.split("/")
1619
prefixes[p] = u"%s#%s/" % (doc_url, p)
@@ -22,13 +25,13 @@ def makerdf(workflow, wf, ctx):
2225
for s,p,o in g.triples((None, URIRef("@id"), None)):
2326
g.remove((s, p, o))
2427

25-
for k,v in prefixes.iteritems():
26-
g.namespace_manager.bind(k, v)
28+
for k2,v2 in prefixes.iteritems():
29+
g.namespace_manager.bind(k2, v2)
2730

2831
return g
2932

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

3437
def lastpart(uri): # type: (Any) -> str
@@ -158,7 +161,7 @@ def dot_without_parameters(g, stdout): # type: (Graph, IO[Any]) -> None
158161
}""")
159162

160163
for src, sink, srcrun, sinkrun in qres:
161-
attr = ""
164+
attr = u""
162165
if srcrun in clusternode:
163166
attr += u'ltail="%s"' % dotname[srcrun]
164167
src = clusternode[srcrun]
@@ -169,7 +172,7 @@ def dot_without_parameters(g, stdout): # type: (Graph, IO[Any]) -> None
169172

170173

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

175178
stdout.write("digraph {")

cwltool/cwltest.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -165,9 +165,12 @@ def main(): # type: () -> int
165165
tests = []
166166
for t in alltests:
167167
loader = schema_salad.ref_resolver.Loader({"id": "@id"})
168-
cwl, _ = loader.resolve_ref(t["tool"])
169-
if cwl["class"] == "CommandLineTool":
170-
tests.append(t)
168+
cwl = loader.resolve_ref(t["tool"])[0]
169+
if isinstance(cwl, dict):
170+
if cwl["class"] == "CommandLineTool":
171+
tests.append(t)
172+
else:
173+
raise Exception("Unexpected code path.")
171174

172175
if args.l:
173176
for i, t in enumerate(tests):

cwltool/draft2tool.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ def __init__(self, toolpath_object, **kwargs):
100100
# type: (Dict[str,Any], **Any) -> None
101101
super(CommandLineTool, self).__init__(toolpath_object, **kwargs)
102102

103-
def makeJobRunner(self):
103+
def makeJobRunner(self): # type: () -> CommandLineJob
104104
return CommandLineJob()
105105

106106
def makePathMapper(self, reffiles, input_basedir, **kwargs):
@@ -267,7 +267,7 @@ def collect_output_ports(self, ports, builder, outdir):
267267
raise WorkflowException("Error validating output record, " + str(e) + "\n in " + json.dumps(ret, indent=4))
268268

269269
def collect_output(self, schema, builder, outdir):
270-
# type: (Dict[str,Any],Builder,str) -> Union[Dict[str,Any],List[Union[Dict[str,Any],str]]]
270+
# type: (Dict[str,Any], Builder, str) -> Union[Dict[str, Any], List[Union[Dict[str, Any], str]]]
271271
r = [] # type: List[Any]
272272
if "outputBinding" in schema:
273273
binding = schema["outputBinding"]
@@ -372,9 +372,9 @@ def collect_output(self, schema, builder, outdir):
372372

373373
if (not r and isinstance(schema["type"], dict) and
374374
schema["type"]["type"] == "record"):
375-
out = {} # type: Dict[str, Any]
375+
out = {}
376376
for f in schema["type"]["fields"]:
377-
out[shortname(f["name"])] = self.collect_output(
377+
out[shortname(f["name"])] = self.collect_output( # type: ignore
378378
f, builder, outdir)
379379
return out
380380
return r

cwltool/expression.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,14 +15,14 @@
1515
_logger = logging.getLogger("cwltool")
1616

1717
def jshead(engineConfig, rootvars):
18-
# type: (List[str],Dict[str,str]) -> str
19-
return "\n".join(engineConfig + [u"var %s = %s;" % (k, json.dumps(v, indent=4)) for k, v in rootvars.items()])
18+
# type: (List[unicode],Dict[str,str]) -> unicode
19+
return u"\n".join(engineConfig + [u"var %s = %s;" % (k, json.dumps(v, indent=4)) for k, v in rootvars.items()])
2020

2121
def exeval(ex, jobinput, requirements, outdir, tmpdir, context, pull_image):
2222
# type: (Dict[str,Any], Dict[str,str], List[Dict[str, Any]], str, str, Any, bool) -> sandboxjs.JSON
2323

2424
if ex["engine"] == "https://w3id.org/cwl/cwl#JavascriptEngine":
25-
engineConfig = [] # type: List[str]
25+
engineConfig = [] # type: List[unicode]
2626
for r in reversed(requirements):
2727
if r["class"] == "ExpressionEngineRequirement" and r["id"] == "https://w3id.org/cwl/cwl#JavascriptEngine":
2828
engineConfig = r.get("engineConfig", [])
@@ -126,7 +126,7 @@ def param_interpolate(ex, obj, strip=True):
126126

127127
def do_eval(ex, jobinput, requirements, outdir, tmpdir, resources,
128128
context=None, pull_image=True, timeout=None):
129-
# type: (Any, Dict[str,str], List[Dict[str,Any]], str, str, Dict[str,str], Any, bool, int) -> Any
129+
# type: (Any, Dict[str,str], List[Dict[str,Any]], str, str, Dict[str, Union[int, str]], Any, bool, int) -> Any
130130

131131
runtime = resources.copy()
132132
runtime["tmpdir"] = tmpdir

cwltool/job.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,10 +48,10 @@ def __init__(self): # type: () -> None
4848
self.successCodes = None # type: Iterable[int]
4949
self.temporaryFailCodes = None # type: Iterable[int]
5050
self.permanentFailCodes = None # type: Iterable[int]
51-
self.requirements = None # type: Dict[str,str]
51+
self.requirements = None # type: List[Dict[str, str]]
5252
self.hints = None # type: Dict[str,str]
53-
self.name = None # type: str
54-
self.command_line = None # type: List[str]
53+
self.name = None # type: unicode
54+
self.command_line = None # type: List[unicode]
5555
self.pathmapper = None # type: PathMapper
5656
self.collect_outputs = None # type: Union[Callable[[Any], Any],functools.partial[Any]]
5757
self.output_callback = None # type: Callable[[Any, Any], Any]
@@ -69,7 +69,7 @@ def run(self, dry_run=False, pull_image=True, rm_container=True,
6969
#with open(os.path.join(outdir, "cwl.input.json"), "w") as fp:
7070
# json.dump(self.joborder, fp)
7171

72-
runtime = [] # type: List[str]
72+
runtime = [] # type: List[unicode]
7373
env = {"TMPDIR": self.tmpdir} # type: Mapping[str,str]
7474

7575
(docker_req, docker_is_req) = get_feature(self, "DockerRequirement")

cwltool/main.py

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
from .process import shortname, Process
2323
import rdflib
2424
from .utils import aslist
25-
from typing import Union, Any, cast, Callable, Tuple, IO
25+
from typing import Union, Any, cast, Callable, Dict, Tuple, IO
2626

2727
_logger = logging.getLogger("cwltool")
2828

@@ -294,15 +294,15 @@ def load_tool(argsworkflow, updateonly, strict, makeTool, debug,
294294
rdf_serializer=None,
295295
stdout=sys.stdout,
296296
urifrag=None):
297-
# type: (Union[str,unicode,dict[str,Any]], bool, bool, Callable[...,Process], bool, bool, bool, bool, bool, bool, Any, Any, Any) -> Any
297+
# type: (Union[str,unicode,dict[unicode,Any]], bool, bool, Callable[...,Process], bool, bool, bool, bool, bool, bool, Any, Any, Any) -> Any
298298
(document_loader, avsc_names, schema_metadata) = process.get_schema()
299299

300300
if isinstance(avsc_names, Exception):
301301
raise avsc_names
302302

303303
jobobj = None
304304
uri = None # type: str
305-
workflowobj = None # type: Dict[str, Any]
305+
workflowobj = None # type: Dict[unicode, Any]
306306
if isinstance(argsworkflow, (basestring)):
307307
split = urlparse.urlsplit(cast(str, argsworkflow))
308308
if split.scheme:
@@ -343,9 +343,11 @@ def load_tool(argsworkflow, updateonly, strict, makeTool, debug,
343343
return 0
344344

345345
try:
346-
processobj, metadata = schema_salad.schema.load_and_validate(document_loader, avsc_names, workflowobj, strict)
346+
processobj, metadata = schema_salad.schema.load_and_validate(
347+
document_loader, avsc_names, workflowobj, strict)
347348
except (schema_salad.validate.ValidationException, RuntimeError) as e:
348-
_logger.error(u"Tool definition failed validation:\n%s", e, exc_info=(e if debug else False))
349+
_logger.error(u"Tool definition failed validation:\n%s", e,
350+
exc_info=(e if debug else False))
349351
return 1
350352

351353
if print_pre:
@@ -401,7 +403,10 @@ def load_job_order(args, t, parser, stdin, print_input_deps=False, relative_deps
401403
if args.conformance_test:
402404
loader = Loader({})
403405
else:
404-
jobloaderctx = {"path": {"@type": "@id"}, "format": {"@type": "@id"}, "id": "@id"}
406+
jobloaderctx = {
407+
"path": {"@type": "@id"},
408+
"format": {"@type": "@id"},
409+
"id": "@id"}
405410
jobloaderctx.update(t.metadata.get("$namespaces", {}))
406411
loader = Loader(jobloaderctx)
407412

@@ -478,7 +483,7 @@ def load_job_order(args, t, parser, stdin, print_input_deps=False, relative_deps
478483

479484

480485
def printdeps(obj, document_loader, stdout, relative_deps, basedir=None):
481-
# type: (Dict[str,Any], Loader, IO[Any], bool, str) -> None
486+
# type: (Dict[unicode, Any], Loader, IO[Any], bool, str) -> None
482487
deps = {"class": "File",
483488
"path": obj.get("id", "#")}
484489

@@ -507,7 +512,7 @@ def makeRelative(u):
507512
stdout.write(json.dumps(deps, indent=4))
508513

509514
def versionstring():
510-
# type: () -> str
515+
# type: () -> unicode
511516
pkg = pkg_resources.require("cwltool")
512517
if pkg:
513518
return u"%s %s" % (sys.argv[0], pkg[0].version)
@@ -524,7 +529,7 @@ def main(argsl=None,
524529
stdout=sys.stdout,
525530
stderr=sys.stderr,
526531
versionfunc=versionstring):
527-
# type: (List[str],Callable[...,Union[str,Dict[str,str]]],Callable[...,Process],Callable[[Dict[str,int]],Dict[str,int]],argparse.ArgumentParser,IO[Any],IO[Any],IO[Any],Callable[[],str]) -> int
532+
# type: (List[str],Callable[...,Union[str,Dict[str,str]]],Callable[...,Process],Callable[[Dict[str,int]],Dict[str,int]],argparse.ArgumentParser,IO[Any],IO[Any],IO[Any],Callable[[],unicode]) -> int
528533

529534
_logger.removeHandler(defaultStreamHandler)
530535
_logger.addHandler(logging.StreamHandler(stderr))

cwltool/pathmapper.py

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,12 @@ class PathMapper(object):
2020
"""Mapping of files from relative path provided in the file to a tuple of
2121
(absolute local path, absolute container path)"""
2222

23-
def __new__(cls, referenced_files, basedir, *args, **kwargs):
24-
# type: (Set[str], str) -> Any
25-
instance = super(PathMapper,cls).__new__(cls)
26-
instance._pathmap = {} # type: Dict[str, Tuple[str, str]]
27-
return instance
28-
2923
def __init__(self, referenced_files, basedir):
24+
# type: (Set[str], str) -> None
25+
self._pathmap = {} # type: Dict[str, Tuple[str, str]]
26+
self.setup(referenced_files, basedir)
27+
28+
def setup(self, referenced_files, basedir):
3029
# type: (Set[str], str) -> None
3130
for src in referenced_files:
3231
ab = abspath(src, basedir)
@@ -52,30 +51,28 @@ def reversemap(self, target): # type: (str) -> Tuple[str, str]
5251

5352
class DockerPathMapper(PathMapper):
5453

55-
def __new__(cls, referenced_files, basedir):
56-
# type: (Set[str], str) -> None
57-
instance = super(DockerPathMapper,cls).__new__(cls, referenced_files, basedir)
58-
instance.dirs = {} # type: Dict[str, Union[bool, str]]
59-
return instance
60-
6154
def __init__(self, referenced_files, basedir):
6255
# type: (Set[str], str) -> None
56+
self.dirs = {} # type: Dict[str, Union[bool, str]]
57+
super(DockerPathMapper, self).__init__(referenced_files, basedir)
58+
59+
def setup(self, referenced_files, basedir):
6360
for src in referenced_files:
6461
ab = abspath(src, basedir)
65-
dir, fn = os.path.split(ab)
62+
dirn, fn = os.path.split(ab)
6663

6764
subdir = False
6865
for d in self.dirs:
69-
if dir.startswith(d):
66+
if dirn.startswith(d):
7067
subdir = True
7168
break
7269

7370
if not subdir:
7471
for d in list(self.dirs):
75-
if d.startswith(dir):
76-
# 'dir' is a parent of 'd'
72+
if d.startswith(dirn):
73+
# 'dirn' is a parent of 'd'
7774
del self.dirs[d]
78-
self.dirs[dir] = True
75+
self.dirs[dirn] = True
7976

8077
prefix = "job" + str(random.randint(1, 1000000000)) + "_"
8178

@@ -85,7 +82,8 @@ def __init__(self, referenced_files, basedir):
8582
i = 1
8683
while name in names:
8784
i += 1
88-
name = os.path.join("/var/lib/cwl", prefix + os.path.basename(d) + str(i))
85+
name = os.path.join("/var/lib/cwl",
86+
prefix + os.path.basename(d) + str(i))
8987
names.add(name)
9088
self.dirs[d] = name
9189

@@ -96,9 +94,11 @@ def __init__(self, referenced_files, basedir):
9694
st = os.lstat(deref)
9795
while stat.S_ISLNK(st.st_mode):
9896
rl = os.readlink(deref)
99-
deref = rl if os.path.isabs(rl) else os.path.join(os.path.dirname(deref), rl)
97+
deref = rl if os.path.isabs(rl) else os.path.join(
98+
os.path.dirname(deref), rl)
10099
st = os.lstat(deref)
101100

102101
for d in self.dirs:
103102
if ab.startswith(d):
104-
self._pathmap[src] = (deref, os.path.join(self.dirs[d], ab[len(d)+1:]))
103+
self._pathmap[src] = (deref, os.path.join(
104+
self.dirs[d], ab[len(d)+1:]))

0 commit comments

Comments
 (0)