Skip to content

Commit 279cb02

Browse files
author
Peter Amstutz
committed
Support ruamel.yaml 0.15.52+
Use isinstance(..., MutableMapping) instead of isinstance(..., dict) because CommentedMap no longer inherits from ordereddict. Also convert some instances of copy.copy() to copy.deepcopy() because using copy.copy() to make a shallow copy of CommentedMap no longer has the desired behavior.
1 parent c27774b commit 279cb02

14 files changed

+75
-73
lines changed

cwltool/argparser.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import argparse
44
import os
5-
from typing import Any, AnyStr, Dict, List, Optional, Sequence, Union, cast
5+
from typing import Any, AnyStr, Dict, List, Optional, Sequence, Union, cast, MutableMapping
66

77
from typing_extensions import Text # pylint: disable=unused-import
88
# move to a regular typing import when Python 3.3-3.6 is no longer supported
@@ -398,16 +398,16 @@ def add_argument(toolparser, name, inptype, records, description="",
398398
action = cast(argparse.Action, FileAction)
399399
elif inptype == "Directory":
400400
action = cast(argparse.Action, DirectoryAction)
401-
elif isinstance(inptype, dict) and inptype["type"] == "array":
401+
elif isinstance(inptype, MutableMapping) and inptype["type"] == "array":
402402
if inptype["items"] == "File":
403403
action = cast(argparse.Action, FileAppendAction)
404404
elif inptype["items"] == "Directory":
405405
action = cast(argparse.Action, DirectoryAppendAction)
406406
else:
407407
action = "append"
408-
elif isinstance(inptype, dict) and inptype["type"] == "enum":
408+
elif isinstance(inptype, MutableMapping) and inptype["type"] == "enum":
409409
atype = Text
410-
elif isinstance(inptype, dict) and inptype["type"] == "record":
410+
elif isinstance(inptype, MutableMapping) and inptype["type"] == "record":
411411
records.append(name)
412412
for field in inptype['fields']:
413413
fieldname = name + "." + shortname(field['name'])

cwltool/builder.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import copy
44
import logging
5-
from typing import Any, Callable, Dict, List, Optional, Set, Union, Tuple
5+
from typing import Any, Callable, Dict, List, Optional, Set, Union, Tuple, MutableMapping
66
from typing_extensions import Text, Type, TYPE_CHECKING # pylint: disable=unused-import
77
# move to a regular typing import when Python 3.3-3.6 is no longer supported
88

@@ -208,8 +208,8 @@ def bind_input(self,
208208
bindings = [] # type: List[Dict[Text,Text]]
209209
binding = None # type: Optional[Dict[Text,Any]]
210210
value_from_expression = False
211-
if "inputBinding" in schema and isinstance(schema["inputBinding"], dict):
212-
binding = copy.copy(schema["inputBinding"])
211+
if "inputBinding" in schema and isinstance(schema["inputBinding"], MutableMapping):
212+
binding = copy.deepcopy(schema["inputBinding"])
213213

214214
if "position" in binding:
215215
binding["position"] = aslist(lead_pos) + aslist(binding["position"]) + aslist(tail_pos)
@@ -226,7 +226,7 @@ def bind_input(self,
226226
for t in schema["type"]:
227227
if isinstance(t, string_types) and self.names.has_name(t, ""):
228228
avsc = self.names.get_name(t, "")
229-
elif isinstance(t, dict) and "name" in t and self.names.has_name(t["name"], ""):
229+
elif isinstance(t, MutableMapping) and "name" in t and self.names.has_name(t["name"], ""):
230230
avsc = self.names.get_name(t["name"], "")
231231
else:
232232
avsc = AvroSchemaFromJSONData(t, self.names)
@@ -240,7 +240,7 @@ def bind_input(self,
240240
bound_input = True
241241
if not bound_input:
242242
raise validate.ValidationException(u"'%s' is not a valid union %s" % (datum, schema["type"]))
243-
elif isinstance(schema["type"], dict):
243+
elif isinstance(schema["type"], MutableMapping):
244244
st = copy.deepcopy(schema["type"])
245245
if binding and "inputBinding" not in st and st["type"] == "array" and "itemSeparator" not in binding:
246246
st["inputBinding"] = {}
@@ -289,7 +289,7 @@ def bind_input(self,
289289
if "secondaryFiles" not in datum:
290290
datum["secondaryFiles"] = []
291291
for sf in aslist(schema["secondaryFiles"]):
292-
if isinstance(sf, dict) or "$(" in sf or "${" in sf:
292+
if isinstance(sf, MutableMapping) or "$(" in sf or "${" in sf:
293293
sfpath = self.do_eval(sf, context=datum)
294294
else:
295295
sfpath = substitute(datum["basename"], sf)
@@ -301,7 +301,7 @@ def bind_input(self,
301301
if d["basename"] == sfname:
302302
found = True
303303
if not found:
304-
if isinstance(sfname, dict):
304+
if isinstance(sfname, MutableMapping):
305305
datum["secondaryFiles"].append(sfname)
306306
elif discover_secondaryFiles:
307307
datum["secondaryFiles"].append({
@@ -344,7 +344,7 @@ def _capture_files(f):
344344
return bindings
345345

346346
def tostr(self, value): # type: (Any) -> Text
347-
if isinstance(value, dict) and value.get("class") in ("File", "Directory"):
347+
if isinstance(value, MutableMapping) and value.get("class") in ("File", "Directory"):
348348
if "path" not in value:
349349
raise WorkflowException(u"%s object missing \"path\": %s" % (value["class"], value))
350350

@@ -383,9 +383,9 @@ def generate_arg(self, binding): # type: (Dict[Text, Any]) -> List[Text]
383383
return [prefix]
384384
else:
385385
return []
386-
elif isinstance(value, dict) and value.get("class") in ("File", "Directory"):
386+
elif isinstance(value, MutableMapping) and value.get("class") in ("File", "Directory"):
387387
argl = [value]
388-
elif isinstance(value, dict):
388+
elif isinstance(value, MutableMapping):
389389
return [prefix] if prefix else []
390390
elif value is True and prefix:
391391
return [prefix]
@@ -407,7 +407,7 @@ def generate_arg(self, binding): # type: (Dict[Text, Any]) -> List[Text]
407407
def do_eval(self, ex, context=None, recursive=False, strip_whitespace=True):
408408
# type: (Union[Dict[Text, Text], Text], Any, bool, bool) -> Any
409409
if recursive:
410-
if isinstance(ex, dict):
410+
if isinstance(ex, MutableMapping):
411411
return {k: self.do_eval(v, context, recursive)
412412
for k, v in iteritems(ex)}
413413
if isinstance(ex, list):

cwltool/command_line_tool.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
import threading
1313
from functools import cmp_to_key, partial
1414
from typing import (Any, Callable, Dict, Generator, List, Optional, Set, Union,
15-
cast)
15+
cast, MutableMapping)
1616
from typing_extensions import Text, Type, TYPE_CHECKING # pylint: disable=unused-import
1717
# move to a regular typing import when Python 3.3-3.6 is no longer supported
1818

@@ -510,7 +510,7 @@ def register_mut(f):
510510
def register_reader(f):
511511
if f["location"] not in muts:
512512
builder.mutation_manager.register_reader(j.name, f)
513-
readers[f["location"]] = copy.copy(f)
513+
readers[f["location"]] = copy.deepcopy(f)
514514

515515
for li in j.generatefiles["listing"]:
516516
li = cast(Dict[Text, Any], li)
@@ -693,7 +693,7 @@ def collect_output(self,
693693
if binding.get("loadContents") or compute_checksum:
694694
contents = f.read(CONTENT_LIMIT)
695695
if binding.get("loadContents"):
696-
files["contents"] = contents.decode("utf-8")
696+
files["contents"] = contents.decode("utf-8")
697697
if compute_checksum:
698698
checksum = hashlib.sha1()
699699
while contents != b"":
@@ -733,11 +733,11 @@ def collect_output(self,
733733
if "secondaryFiles" in schema:
734734
with SourceLine(schema, "secondaryFiles", WorkflowException, debug):
735735
for primary in aslist(r):
736-
if isinstance(primary, dict):
736+
if isinstance(primary, MutableMapping):
737737
primary.setdefault("secondaryFiles", [])
738738
pathprefix = primary["path"][0:primary["path"].rindex("/")+1]
739739
for sf in aslist(schema["secondaryFiles"]):
740-
if isinstance(sf, dict) or "$(" in sf or "${" in sf:
740+
if isinstance(sf, MutableMapping) or "$(" in sf or "${" in sf:
741741
sfpath = builder.do_eval(sf, context=primary)
742742
subst = False
743743
else:
@@ -768,7 +768,7 @@ def collect_output(self,
768768
if not r and optional:
769769
return None
770770

771-
if (not empty_and_optional and isinstance(schema["type"], dict)
771+
if (not empty_and_optional and isinstance(schema["type"], MutableMapping)
772772
and schema["type"]["type"] == "record"):
773773
out = {}
774774
for f in schema["type"]["fields"]:

cwltool/expression.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import copy
44
import re
5-
from typing import Any, Dict, List, Optional, Union
5+
from typing import Any, Dict, List, Optional, Union, MutableMapping
66
from typing_extensions import Text # pylint: disable=unused-import
77
# move to a regular typing import when Python 3.3-3.6 is no longer supported
88
import six
@@ -132,7 +132,7 @@ def next_seg(parsed_string, remaining_string, current_value): # type: (Text, Te
132132
if key:
133133
if isinstance(current_value, list) and key == "length" and not remaining_string[m.end(0):]:
134134
return len(current_value)
135-
if not isinstance(current_value, dict):
135+
if not isinstance(current_value, MutableMapping):
136136
raise WorkflowException("%s is a %s, cannot index on string '%s'" % (parsed_string, type(current_value).__name__, key))
137137
if key not in current_value:
138138
raise WorkflowException("%s does not contain key '%s'" % (parsed_string, key))
@@ -257,7 +257,7 @@ def do_eval(ex, # type: Union[Text, Dict]
257257
strip_whitespace=True # type: bool
258258
): # type: (...) -> Any
259259

260-
runtime = copy.copy(resources) # type: Dict[str, Any]
260+
runtime = copy.deepcopy(resources) # type: Dict[str, Any]
261261
runtime["tmpdir"] = docker_windows_path_adjust(tmpdir)
262262
runtime["outdir"] = docker_windows_path_adjust(outdir)
263263

cwltool/job.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@
107107

108108

109109
def deref_links(outputs): # type: (Any) -> None
110-
if isinstance(outputs, dict):
110+
if isinstance(outputs, MutableMapping):
111111
if outputs.get("class") == "File":
112112
st = os.lstat(outputs["path"])
113113
if stat.S_ISLNK(st.st_mode):

cwltool/load_tool.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import os
77
import re
88
import uuid
9-
from typing import Any, Callable, Dict, List, Optional, Tuple, Union, cast
9+
from typing import Any, Callable, Dict, List, Optional, Tuple, Union, cast, MutableMapping
1010
from typing_extensions import Text # pylint: disable=unused-import
1111
# move to a regular typing import when Python 3.3-3.6 is no longer supported
1212

@@ -111,7 +111,7 @@ def fetch_document(argsworkflow, # type: Union[Text, Dict[Text, Any]]
111111
uri, fileuri = resolve_tool_uri(argsworkflow, resolver=resolver,
112112
document_loader=document_loader)
113113
workflowobj = document_loader.fetch(fileuri)
114-
elif isinstance(argsworkflow, dict):
114+
elif isinstance(argsworkflow, MutableMapping):
115115
uri = "#" + Text(id(argsworkflow))
116116
workflowobj = cast(CommentedMap, cmap(argsworkflow, fn=uri))
117117
else:
@@ -124,7 +124,7 @@ def fetch_document(argsworkflow, # type: Union[Text, Dict[Text, Any]]
124124
def _convert_stdstreams_to_files(workflowobj):
125125
# type: (Union[Dict[Text, Any], List[Dict[Text, Any]]]) -> None
126126

127-
if isinstance(workflowobj, dict):
127+
if isinstance(workflowobj, MutableMapping):
128128
if workflowobj.get('class') == 'CommandLineTool':
129129
with SourceLine(workflowobj, "outputs", ValidationException,
130130
_logger.isEnabledFor(logging.DEBUG)):
@@ -179,9 +179,9 @@ def _convert_stdstreams_to_files(workflowobj):
179179
def _add_blank_ids(workflowobj):
180180
# type: (Union[Dict[Text, Any], List[Dict[Text, Any]]]) -> None
181181

182-
if isinstance(workflowobj, dict):
182+
if isinstance(workflowobj, MutableMapping):
183183
if ("run" in workflowobj and
184-
isinstance(workflowobj["run"], dict) and
184+
isinstance(workflowobj["run"], MutableMapping) and
185185
"id" not in workflowobj["run"] and
186186
"$import" not in workflowobj["run"]):
187187
workflowobj["run"]["id"] = Text(uuid.uuid4())
@@ -211,7 +211,7 @@ def validate_document(document_loader, # type: Loader
211211
"$graph": workflowobj
212212
}, fn=uri)
213213

214-
if not isinstance(workflowobj, dict):
214+
if not isinstance(workflowobj, MutableMapping):
215215
raise ValueError("workflowjobj must be a dict, got '{}': {}".format(
216216
type(workflowobj), workflowobj))
217217

@@ -329,7 +329,7 @@ def make_tool(document_loader, # type: Loader
329329
"one of #%s" % ", #".join(
330330
urllib.parse.urldefrag(i["id"])[1] for i in resolveduri
331331
if "id" in i))
332-
elif isinstance(resolveduri, dict):
332+
elif isinstance(resolveduri, MutableMapping):
333333
processobj = resolveduri
334334
else:
335335
raise Exception("Must resolve to list or dict")

cwltool/pack.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from __future__ import absolute_import
22

33
import copy
4-
from typing import Any, Callable, Dict, List, Optional, Set, Union, cast
4+
from typing import Any, Callable, Dict, List, Optional, Set, Union, cast, MutableMapping
55
from typing_extensions import Text # pylint: disable=unused-import
66
# move to a regular typing import when Python 3.3-3.6 is no longer supported
77

@@ -18,7 +18,7 @@ def flatten_deps(d, files): # type: (Any, Set[Text]) -> None
1818
if isinstance(d, list):
1919
for s in d:
2020
flatten_deps(s, files)
21-
elif isinstance(d, dict):
21+
elif isinstance(d, MutableMapping):
2222
if d["class"] == "File":
2323
files.add(d["location"])
2424
if "secondaryFiles" in d:
@@ -36,7 +36,7 @@ def find_run(d, # type: Any
3636
if isinstance(d, list):
3737
for s in d:
3838
find_run(s, loadref, runs)
39-
elif isinstance(d, dict):
39+
elif isinstance(d, MutableMapping):
4040
if "run" in d and isinstance(d["run"], string_types):
4141
if d["run"] not in runs:
4242
runs.add(d["run"])
@@ -49,7 +49,7 @@ def find_ids(d, ids): # type: (Any, Set[Text]) -> None
4949
if isinstance(d, list):
5050
for s in d:
5151
find_ids(s, ids)
52-
elif isinstance(d, dict):
52+
elif isinstance(d, MutableMapping):
5353
for i in ("id", "name"):
5454
if i in d and isinstance(d[i], string_types):
5555
ids.add(d[i])
@@ -69,7 +69,7 @@ def replace_refs(d, rewrite, stem, newstem):
6969
rewrite[v] = d[s]
7070
else:
7171
replace_refs(v, rewrite, stem, newstem)
72-
elif isinstance(d, dict):
72+
elif isinstance(d, MutableMapping):
7373
for s, v in d.items():
7474
if isinstance(v, string_types):
7575
if v in rewrite:
@@ -89,7 +89,7 @@ def import_embed(d, seen):
8989
if isinstance(d, list):
9090
for v in d:
9191
import_embed(v, seen)
92-
elif isinstance(d, dict):
92+
elif isinstance(d, MutableMapping):
9393
for n in ("id", "name"):
9494
if n in d:
9595
if d[n] in seen:
@@ -114,7 +114,7 @@ def pack(document_loader, # type: Loader
114114

115115
document_loader = SubLoader(document_loader)
116116
document_loader.idx = {}
117-
if isinstance(processobj, dict):
117+
if isinstance(processobj, MutableMapping):
118118
document_loader.idx[processobj["id"]] = CommentedMap(iteritems(processobj))
119119
elif isinstance(processobj, list):
120120
_, frag = urllib.parse.urldefrag(uri)

cwltool/pathmapper.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131
def adjustFiles(rec, op): # type: (Any, Union[Callable[..., Any], partial[Any]]) -> None
3232
"""Apply a mapping function to each File path in the object `rec`."""
3333

34-
if isinstance(rec, dict):
34+
if isinstance(rec, MutableMapping):
3535
if rec.get("class") == "File":
3636
rec["path"] = op(rec["path"])
3737
for d in rec:

0 commit comments

Comments
 (0)