Skip to content

Commit 6161eaf

Browse files
committed
sync types
1 parent e4598ae commit 6161eaf

File tree

15 files changed

+220
-129
lines changed

15 files changed

+220
-129
lines changed

cwltool/builder.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,9 @@ class Builder(object):
3434
def __init__(self): # type: () -> None
3535
self.names = None # type: avro.schema.Names
3636
self.schemaDefs = None # type: Dict[str,Dict[unicode, Any]]
37-
self.files = None # type: List[Dict[str, str]]
37+
self.files = None # type: List[Dict[unicode, unicode]]
3838
self.fs_access = None # type: StdFsAccess
39-
self.job = None # type: Dict[str, Any]
39+
self.job = None # type: Dict[unicode, Union[Dict[unicode, Any], List, unicode]]
4040
self.requirements = None # type: List[Dict[str,Any]]
4141
self.outdir = None # type: str
4242
self.tmpdir = None # type: str

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: (Union[str, unicode], Dict[str,Any], Loader.ContextType) -> Graph
9+
# type: (Union[str, unicode], Dict[unicode, 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: (Union[str, unicode], Dict[str, Any], Loader.ContextType, str, IO[Any]) -> None
34+
# type: (Union[str, unicode], Dict[unicode, 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: (Union[str, unicode], Dict[str, Any], Loader.ContextType, Any, bool) -> None
175+
# type: (Union[str, unicode], Dict[unicode, Any], Loader.ContextType, Any, bool) -> None
176176
g = makerdf(workflow, wf, ctx)
177177

178178
stdout.write("digraph {")

cwltool/draft2tool.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030

3131
class ExpressionTool(Process):
3232
def __init__(self, toolpath_object, **kwargs):
33-
# type: (Dict[str,List[None]], **Any) -> None
33+
# type: (Dict[unicode, Any], **Any) -> None
3434
super(ExpressionTool, self).__init__(toolpath_object, **kwargs)
3535

3636
class ExpressionJob(object):
@@ -53,7 +53,7 @@ def run(self, **kwargs): # type: (**Any) -> None
5353
self.output_callback({}, "permanentFail")
5454

5555
def job(self, joborder, output_callback, **kwargs):
56-
# type: (Dict[str,str], str, Callable[[Any, Any], Any], **Any) -> Generator[ExpressionTool.ExpressionJob, None, None]
56+
# type: (Dict[unicode, unicode], Callable[[Any, Any], Any], **Any) -> Generator[ExpressionTool.ExpressionJob, None, None]
5757
builder = self._init_job(joborder, **kwargs)
5858

5959
j = ExpressionTool.ExpressionJob()
@@ -113,14 +113,14 @@ def run(self, **kwargs):
113113

114114
class CommandLineTool(Process):
115115
def __init__(self, toolpath_object, **kwargs):
116-
# type: (Dict[str,Any], **Any) -> None
116+
# type: (Dict[unicode, Any], **Any) -> None
117117
super(CommandLineTool, self).__init__(toolpath_object, **kwargs)
118118

119119
def makeJobRunner(self): # type: () -> CommandLineJob
120120
return CommandLineJob()
121121

122122
def makePathMapper(self, reffiles, **kwargs):
123-
# type: (Set[str], str, **Any) -> PathMapper
123+
# type: (Set[unicode], **Any) -> PathMapper
124124
dockerReq, _ = self.get_requirement("DockerRequirement")
125125
try:
126126
if dockerReq and kwargs.get("use_container"):
@@ -132,7 +132,7 @@ def makePathMapper(self, reffiles, **kwargs):
132132
raise WorkflowException(u"Missing input file %s" % e)
133133

134134
def job(self, joborder, output_callback, **kwargs):
135-
# type: (Dict[str,str], str, Callable[..., Any], **Any) -> Generator[Union[CommandLineJob, CallbackJob], None, None]
135+
# type: (Dict[unicode, unicode], Callable[..., Any], **Any) -> Generator[Union[CommandLineJob, CallbackJob], None, None]
136136

137137
jobname = uniquename(kwargs.get("name", shortname(self.tool.get("id", "job"))))
138138

@@ -149,7 +149,7 @@ def job(self, joborder, output_callback, **kwargs):
149149
if docker_req and kwargs.get("use_container") is not False:
150150
dockerimg = docker_req.get("dockerImageId") or docker_req.get("dockerPull")
151151
cmdline = ["docker", "run", dockerimg] + cmdline
152-
keydict = {"cmdline": cmdline}
152+
keydict = {u"cmdline": cmdline}
153153

154154
for _,f in cachebuilder.pathmapper.items():
155155
st = os.stat(f[0])
@@ -200,7 +200,7 @@ def rm_pending_output_callback(output_callback, jobcachepending,
200200

201201
builder = self._init_job(joborder, **kwargs)
202202

203-
reffiles = set((f["path"] for f in builder.files))
203+
reffiles = set((f[u"path"] for f in builder.files))
204204

205205
j = self.makeJobRunner()
206206
j.builder = builder
@@ -292,9 +292,9 @@ def _check_adjust(f): # type: (Dict[str,Any]) -> Dict[str,Any]
292292
yield j
293293

294294
def collect_output_ports(self, ports, builder, outdir):
295-
# type: (Set[Dict[str,Any]], Builder, str) -> Dict[str,Union[str,List[Any],Dict[str,Any]]]
295+
# type: (Set[Dict[str,Any]], Builder, str) -> Dict[unicode, Union[unicode, List[Any], Dict[unicode, Any]]]
296296
try:
297-
ret = {} # type: Dict[str,Union[str,List[Any],Dict[str,Any]]]
297+
ret = {} # type: Dict[unicode, Union[unicode, List[Any], Dict[unicode, Any]]]
298298
custom_output = os.path.join(outdir, "cwl.output.json")
299299
if builder.fs_access.exists(custom_output):
300300
with builder.fs_access.open(custom_output, "r") as f:
@@ -323,7 +323,7 @@ def collect_output_ports(self, ports, builder, outdir):
323323
raise WorkflowException("Error validating output record, " + str(e) + "\n in " + json.dumps(ret, indent=4))
324324

325325
def collect_output(self, schema, builder, outdir):
326-
# type: (Dict[str,Any], Builder, str) -> Union[Dict[str, Any], List[Union[Dict[str, Any], str]]]
326+
# type: (Dict[str,Any], Builder, str) -> Union[Dict[unicode, Any], List[Union[Dict[unicode, Any], unicode]]]
327327
r = [] # type: List[Any]
328328
if "outputBinding" in schema:
329329
binding = schema["outputBinding"]

cwltool/expression.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ def jshead(engineConfig, rootvars):
1919
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):
22-
# type: (Dict[str,Any], Dict[str,str], List[Dict[str, Any]], str, str, Any, bool) -> sandboxjs.JSON
22+
# type: (Dict[str, Any], Dict[unicode, Union[Dict, List, unicode]], List[Dict[str, Any]], str, str, Any, bool) -> sandboxjs.JSON
2323

2424
if ex["engine"] == "https://w3id.org/cwl/cwl#JavascriptEngine":
2525
engineConfig = [] # type: List[unicode]
@@ -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, Union[int, str]], Any, bool, int) -> Any
129+
# type: (Union[dict, unicode], Dict[unicode, Union[Dict, List, unicode]], List[Dict[str, Any]], str, str, Dict[str, Union[int, str]], Any, bool, int) -> Any
130130

131131
runtime = resources.copy()
132132
runtime["tmpdir"] = tmpdir
@@ -140,7 +140,7 @@ def do_eval(ex, jobinput, requirements, outdir, tmpdir, resources,
140140

141141
if isinstance(ex, dict) and "engine" in ex and "script" in ex:
142142
return exeval(ex, jobinput, requirements, outdir, tmpdir, context, pull_image)
143-
if isinstance(ex, basestring):
143+
if isinstance(ex, (str, unicode)):
144144
for r in requirements:
145145
if r["class"] == "InlineJavascriptRequirement":
146146
return sandboxjs.interpolate(str(ex), jshead(r.get("expressionLib", []), rootvars),

cwltool/job.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ class CommandLineJob(object):
4242

4343
def __init__(self): # type: () -> None
4444
self.builder = None # type: Builder
45-
self.joborder = None # type: Dict[str,str]
45+
self.joborder = None # type: Dict[unicode, Union[Dict[unicode, Any], List, unicode]]
4646
self.stdin = None # type: str
4747
self.stdout = None # type: str
4848
self.successCodes = None # type: Iterable[int]

cwltool/load_tool.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ def fetch_document(argsworkflow):
4444

4545
def validate_document(document_loader, workflowobj, uri,
4646
enable_dev=False, strict=True, preprocess_only=False):
47-
# type: (Loader, Dict[unicode, Any], unicode, bool, bool, bool) -> Tuple[Loader, Names, Any, Dict[str, str], unicode]
47+
# type: (Loader, Dict[unicode, Any], unicode, bool, bool, bool) -> Tuple[Loader, Names, Dict[unicode, Any], Dict[unicode, Any], unicode]
4848
"""Validate a CWL document."""
4949
jobobj = None
5050
if "cwl:tool" in workflowobj:
@@ -83,6 +83,8 @@ def validate_document(document_loader, workflowobj, uri,
8383

8484
workflowobj["id"] = fileuri
8585
processobj, metadata = document_loader.resolve_all(workflowobj, fileuri)
86+
if not isinstance(processobj, dict):
87+
raise validate.ValidationException("Workflow must be a dict.")
8688

8789
if not metadata:
8890
metadata = {"$namespaces": processobj.get("$namespaces", {}),
@@ -99,14 +101,14 @@ def validate_document(document_loader, workflowobj, uri,
99101
processobj, document_loader, fileuri, enable_dev, metadata)
100102

101103
if jobobj:
102-
metadata["cwl:defaults"] = jobobj
104+
metadata[u"cwl:defaults"] = jobobj
103105

104106
return document_loader, avsc_names, processobj, metadata, uri
105107

106108

107109
def make_tool(document_loader, avsc_names, processobj, metadata, uri, makeTool,
108110
kwargs):
109-
# type: (Loader, Names, Dict[str, Any], Dict[str, Any], unicode, Callable[..., Process], Dict[str, Any]) -> Process
111+
# type: (Loader, Names, Dict[unicode, Any], Dict[unicode, Any], unicode, Callable[..., Process], Dict[str, Any]) -> Process
110112
"""Make a Python CWL object."""
111113
resolveduri = document_loader.resolve_ref(uri)[0]
112114

@@ -120,7 +122,7 @@ def make_tool(document_loader, avsc_names, processobj, metadata, uri, makeTool,
120122
urlparse.urldefrag(i["id"])[1] for i in resolveduri
121123
if "id" in i))
122124
else:
123-
processobj = cast(Dict[str, Any], resolveduri)
125+
processobj = cast(Dict[unicode, Any], resolveduri)
124126

125127
kwargs = kwargs.copy()
126128
kwargs.update({

cwltool/main.py

Lines changed: 31 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,7 @@ def arg_parser(): # type: () -> argparse.ArgumentParser
152152

153153

154154
def single_job_executor(t, job_order_object, **kwargs):
155-
# type: (Process, Dict[str,Any], **Any) -> Union[str,Dict[str,str]]
155+
# type: (Process, Dict[unicode, Any], **Any) -> Union[str,Dict[str,str]]
156156
final_output = []
157157
final_status = []
158158

@@ -238,7 +238,7 @@ def __call__(self, parser, namespace, values, option_string=None):
238238

239239

240240
def generate_parser(toolparser, tool, namemap):
241-
# type: (argparse.ArgumentParser, Process,Dict[str,str]) -> argparse.ArgumentParser
241+
# type: (argparse.ArgumentParser, Process, Dict[unicode, unicode]) -> argparse.ArgumentParser
242242
toolparser.add_argument("job_order", nargs="?", help="Job input json file")
243243
namemap["job_order"] = "job_order"
244244

@@ -298,8 +298,9 @@ def generate_parser(toolparser, tool, namemap):
298298
else:
299299
typekw = {}
300300

301-
toolparser.add_argument(flag + name, required=required,
302-
help=ahelp, action=action, default=default, **typekw)
301+
toolparser.add_argument( # type: ignore
302+
args=flag + name, required=required, help=ahelp, action=action,
303+
default=default, **typekw)
303304

304305
return toolparser
305306

@@ -313,9 +314,9 @@ def load_job_order(args, t, stdin, print_input_deps=False, relative_deps=False,
313314
loader = Loader({})
314315
else:
315316
jobloaderctx = {
316-
"path": {"@type": "@id"},
317-
"format": {"@type": "@id"},
318-
"id": "@id"}
317+
u"path": {u"@type": u"@id"},
318+
u"format": {u"@type": u"@id"},
319+
u"id": u"@id"}
319320
jobloaderctx.update(t.metadata.get("$namespaces", {}))
320321
loader = Loader(jobloaderctx)
321322

@@ -339,7 +340,7 @@ def load_job_order(args, t, stdin, print_input_deps=False, relative_deps=False,
339340
toolparser = None
340341
else:
341342
input_basedir = args.basedir if args.basedir else os.getcwd()
342-
namemap = {} # type: Dict[str,str]
343+
namemap = {} # type: Dict[unicode, unicode]
343344
toolparser = generate_parser(argparse.ArgumentParser(prog=args.workflow), t, namemap)
344345
if toolparser:
345346
if args.tool_help:
@@ -419,7 +420,7 @@ def makeRelative(u):
419420

420421
stdout.write(json.dumps(deps, indent=4))
421422

422-
def flatten_deps(d, files):
423+
def flatten_deps(d, files): # type: (Any, Set[unicode]) -> None
423424
if isinstance(d, list):
424425
for s in d:
425426
flatten_deps(s, files)
@@ -428,41 +429,44 @@ def flatten_deps(d, files):
428429
if "secondaryFiles" in d:
429430
flatten_deps(d["secondaryFiles"], files)
430431

431-
def find_run(d, runs):
432+
def find_run(d, runs): # type: (Any, Set[unicode]) -> None
432433
if isinstance(d, list):
433434
for s in d:
434435
find_run(s, runs)
435436
elif isinstance(d, dict):
436-
if "run" in d and isinstance(d["run"], basestring):
437+
if "run" in d and isinstance(d["run"], (str, unicode)):
437438
runs.add(d["run"])
438439
for s in d.values():
439440
find_run(s, runs)
440441

441442
def replace_refs(d, rewrite, stem, newstem):
443+
# type: (Any, Dict[unicode, unicode], unicode, unicode) -> None
442444
if isinstance(d, list):
443445
for s,v in enumerate(d):
444-
if isinstance(v, basestring) and v.startswith(stem):
446+
if isinstance(v, (str, unicode)) and v.startswith(stem):
445447
d[s] = newstem + v[len(stem):]
446448
else:
447449
replace_refs(v, rewrite, stem, newstem)
448450
elif isinstance(d, dict):
449-
if "run" in d and isinstance(d["run"], basestring):
451+
if "run" in d and isinstance(d["run"], (str, unicode)):
450452
d["run"] = rewrite[d["run"]]
451453
for s,v in d.items():
452-
if isinstance(v, basestring) and v.startswith(stem):
454+
if isinstance(v, (str, unicode)) and v.startswith(stem):
453455
d[s] = newstem + v[len(stem):]
454456
replace_refs(v, rewrite, stem, newstem)
455457

456458
def print_pack(document_loader, processobj, uri, metadata):
459+
# type: (Loader, Any, unicode, Dict[unicode, unicode]) -> str
457460
def loadref(b, u):
461+
# type: (unicode, unicode) -> Union[Dict, List, unicode]
458462
return document_loader.resolve_ref(u, base_url=b)[0]
459463
deps = process.scandeps(uri, processobj,
460464
set(("run",)), set(), loadref)
461465

462466
fdeps = set((uri,))
463467
flatten_deps(deps, fdeps)
464468

465-
runs = set()
469+
runs = set() # type: Set[unicode]
466470
for f in fdeps:
467471
find_run(document_loader.idx[f], runs)
468472

@@ -476,9 +480,10 @@ def loadref(b, u):
476480
for r in runs:
477481
rewrite[r] = "#" + shortname(r)
478482

479-
packed = {"$graph": [], "cwlVersion": metadata["cwlVersion"]}
483+
packed = {"$graph": [], "cwlVersion": metadata["cwlVersion"]
484+
} # type: Dict[unicode, Any]
480485
for r,v in rewrite.items():
481-
dc = copy.deepcopy(document_loader.idx[r])
486+
dc = cast(Dict[unicode, Any], copy.deepcopy(document_loader.idx[r]))
482487
dc["id"] = v
483488
dc["name"] = v
484489
replace_refs(dc, rewrite, r+"/" if "#" in r else r+"#", v+"/")
@@ -508,7 +513,7 @@ def main(argsl=None,
508513
stderr=sys.stderr,
509514
versionfunc=versionstring,
510515
job_order_object=None):
511-
# type: (List[str], argparse.namespace, Callable[..., Union[str, Dict[str, str]]], Callable[..., Process], Callable[[Dict[str, int]], Dict[str, int]], IO[Any], IO[Any], IO[Any], Callable[[], unicode], Union[int, Tuple[Dict[str, Any], str]]) -> int
516+
# type: (List[str], argparse.Namespace, Callable[..., Union[str, Dict[str, str]]], Callable[..., Process], Callable[[Dict[str, int]], Dict[str, int]], IO[Any], IO[Any], IO[Any], Callable[[], unicode], Union[int, Tuple[Dict[str, Any], str]]) -> int
512517

513518
_logger.removeHandler(defaultStreamHandler)
514519
stderr_handler = logging.StreamHandler(stderr)
@@ -611,14 +616,15 @@ def main(argsl=None,
611616

612617
if args.tmp_outdir_prefix != 'tmp':
613618
# Use user defined temp directory (if it exists)
614-
args.tmp_outdir_prefix = os.path.abspath(args.tmp_outdir_prefix)
619+
setattr(args, 'tmp_outdir_prefix',
620+
os.path.abspath(args.tmp_outdir_prefix))
615621
if not os.path.exists(args.tmp_outdir_prefix):
616622
_logger.error("Intermediate output directory prefix doesn't exist.")
617623
return 1
618624

619625
if args.tmpdir_prefix != 'tmp':
620626
# Use user defined prefix (if the folder exists)
621-
args.tmpdir_prefix = os.path.abspath(args.tmpdir_prefix)
627+
setattr(args, 'tmpdir_prefix', os.path.abspath(args.tmpdir_prefix))
622628
if not os.path.exists(args.tmpdir_prefix):
623629
_logger.error("Temporary directory prefix doesn't exist.")
624630
return 1
@@ -633,12 +639,13 @@ def main(argsl=None,
633639
return job_order_object
634640

635641
if args.cachedir:
636-
args.cachedir = os.path.abspath(args.cachedir)
637-
args.move_outputs = False
642+
setattr(args, 'cachedir', os.path.abspath(args.cachedir))
643+
setattr(args, 'move_outputs', False)
638644

639645
try:
640-
args.tmp_outdir_prefix = args.cachedir if args.cachedir else args.tmp_outdir_prefix
641-
args.basedir = job_order_object[1]
646+
setattr(args, 'tmp_outdir_prefix',
647+
args.cachedir if args.cachedir else args.tmp_outdir_prefix)
648+
setattr(args, 'basedir', job_order_object[1])
642649
del args.workflow
643650
del args.job_order
644651
out = executor(tool, job_order_object[0],

0 commit comments

Comments
 (0)