Skip to content

Commit a0cc284

Browse files
committed
types are hard
1 parent 3a8e5be commit a0cc284

File tree

3 files changed

+40
-49
lines changed

3 files changed

+40
-49
lines changed

cwltool/command_line_tool.py

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -559,9 +559,9 @@ def calc_checksum(location: str) -> Optional[str]:
559559
runtimeContext.outdir = jobcache
560560

561561
def update_status_output_callback(
562-
output_callbacks: Callable[[List[Dict[str, Any]], str], None],
562+
output_callbacks: OutputCallbackType,
563563
jobcachelock: IO[Any],
564-
outputs: List[Dict[str, Any]],
564+
outputs: Optional[CWLObjectType],
565565
processStatus: str,
566566
) -> None:
567567
# save status to the lockfile then release the lock
@@ -624,44 +624,44 @@ def update_status_output_callback(
624624
ls = builder.do_eval(initialWorkdir["listing"])
625625
else:
626626
for t in cast(
627-
MutableSequence[Union[str, Dict[str, str]]],
627+
MutableSequence[Union[str, CWLObjectType]],
628628
initialWorkdir["listing"],
629629
):
630630
if isinstance(t, Mapping) and "entry" in t:
631-
entry_exp = builder.do_eval(t["entry"], strip_whitespace=False)
631+
entry_exp = builder.do_eval(cast(str, t["entry"]), strip_whitespace=False)
632632
for entry in aslist(entry_exp):
633633
et = {"entry": entry}
634634
if "entryname" in t:
635-
et["entryname"] = builder.do_eval(t["entryname"])
635+
et["entryname"] = builder.do_eval(cast(str, t["entryname"]))
636636
else:
637637
et["entryname"] = None
638638
et["writable"] = t.get("writable", False)
639639
if et["entry"] is not None:
640640
ls.append(et)
641641
else:
642-
initwd_item = builder.do_eval(t)
642+
initwd_item = builder.do_eval(cast(str, t))
643643
if not initwd_item:
644644
continue
645645
if isinstance(initwd_item, MutableSequence):
646646
ls.extend(initwd_item)
647647
else:
648648
ls.append(initwd_item)
649-
for i, t in enumerate(ls):
650-
if "entry" in t:
651-
if isinstance(t["entry"], str):
649+
for i, t2 in enumerate(ls):
650+
if "entry" in t2:
651+
if isinstance(t2["entry"], str):
652652
ls[i] = {
653653
"class": "File",
654-
"basename": t["entryname"],
655-
"contents": t["entry"],
656-
"writable": t.get("writable"),
654+
"basename": t2["entryname"],
655+
"contents": t2["entry"],
656+
"writable": t2.get("writable"),
657657
}
658658
else:
659-
if t.get("entryname") or t.get("writable"):
660-
t = copy.deepcopy(t)
661-
if t.get("entryname"):
662-
t["entry"]["basename"] = t["entryname"]
663-
t["entry"]["writable"] = t.get("writable")
664-
ls[i] = t["entry"]
659+
if t2.get("entryname") or t2.get("writable"):
660+
t2 = copy.deepcopy(t2)
661+
if t2.get("entryname"):
662+
t2["entry"]["basename"] = t2["entryname"]
663+
t2["entry"]["writable"] = t2.get("writable")
664+
ls[i] = t2["entry"]
665665
j.generatefiles["listing"] = ls
666666
for entry in ls:
667667
self.updatePathmap(builder.outdir, builder.pathmapper, entry)
@@ -787,8 +787,8 @@ def register_reader(f): # type: (Dict[str, Any]) -> None
787787
j.environment = {}
788788
evr, _ = self.get_requirement("EnvVarRequirement")
789789
if evr is not None:
790-
for t in cast(List[Dict[str, str]], evr["envDef"]):
791-
j.environment[t["envName"]] = builder.do_eval(t["envValue"])
790+
for t2 in cast(List[Dict[str, str]], evr["envDef"]):
791+
j.environment[t2["envName"]] = builder.do_eval(t2["envValue"])
792792

793793
shellcmd, _ = self.get_requirement("ShellCommandRequirement")
794794
if shellcmd is not None:

cwltool/provenance.py

Lines changed: 15 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1083,7 +1083,7 @@ def _initialize_bagit(self): # type: () -> None
10831083
bag_it_file.write("BagIt-Version: 0.97\n")
10841084
bag_it_file.write("Tag-File-Character-Encoding: %s\n" % ENCODING)
10851085

1086-
def open_log_file_for_activity(self, uuid_uri: str) -> WritableBagFile:
1086+
def open_log_file_for_activity(self, uuid_uri: str) -> Union[TextIOWrapper, WritableBagFile]:
10871087
self.self_check()
10881088
# Ensure valid UUID for safe filenames
10891089
activity_uuid = uuid.UUID(uuid_uri)
@@ -1140,8 +1140,7 @@ def user_provenance(self, document): # type: (ProvDocument) -> None
11401140
# get their name wrong!)
11411141
document.actedOnBehalfOf(account, user)
11421142

1143-
def write_bag_file(self, path, encoding=ENCODING):
1144-
# type: (str, Optional[str]) -> WritableBagFile
1143+
def write_bag_file(self, path: str, encoding: Optional[str]=ENCODING)-> Union[TextIOWrapper, WritableBagFile]:
11451144
"""Write the bag file into our research object."""
11461145
self.self_check()
11471146
# For some reason below throws BlockingIOError
@@ -1150,12 +1149,9 @@ def write_bag_file(self, path, encoding=ENCODING):
11501149
if encoding is not None:
11511150
# encoding: match Tag-File-Character-Encoding: UTF-8
11521151
# newline: ensure LF also on Windows
1153-
return cast(
1154-
WritableBagFile,
1155-
TextIOWrapper(
1152+
return TextIOWrapper(
11561153
cast(IO[bytes], bag_file), encoding=encoding, newline="\n"
1157-
),
1158-
)
1154+
)
11591155
return bag_file
11601156

11611157
def add_tagfile(self, path, timestamp=None):
@@ -1503,8 +1499,7 @@ def packed_workflow(self, packed): # type: (str) -> None
15031499
rel_path = str(PurePosixPath(WORKFLOW) / "packed.cwl")
15041500
# Write as binary
15051501
with self.write_bag_file(rel_path, encoding=None) as write_pack:
1506-
# YAML is always UTF8, but json.dumps gives us str in py2
1507-
write_pack.write(packed.encode(ENCODING))
1502+
write_pack.write(packed)
15081503
_logger.debug("[provenance] Added packed workflow: %s", rel_path)
15091504

15101505
def has_data_file(self, sha1hash): # type: (str) -> bool
@@ -1513,8 +1508,7 @@ def has_data_file(self, sha1hash): # type: (str) -> bool
15131508
hash_path = os.path.join(folder, sha1hash)
15141509
return os.path.isfile(hash_path)
15151510

1516-
def add_data_file(self, from_fp, timestamp=None, content_type=None):
1517-
# type: (IO[Any], Optional[datetime.datetime], Optional[str]) -> str
1511+
def add_data_file(self, from_fp: IO[Any], timestamp: Optional[datetime.datetime]=None, content_type: Optional[str]=None) -> str:
15181512
"""Copy inputs to data/ folder."""
15191513
self.self_check()
15201514
tmp_dir, tmp_prefix = os.path.split(self.temp_prefix)
@@ -1554,17 +1548,15 @@ def add_data_file(self, from_fp, timestamp=None, content_type=None):
15541548
self._content_types[rel_path] = content_type
15551549
return rel_path
15561550

1557-
def _self_made(self, timestamp=None):
1558-
# type: (Optional[datetime.datetime]) -> Dict[str, Any]
1551+
def _self_made(self, timestamp: Optional[datetime.datetime] = None) -> Dict[str, Any]:
15591552
if timestamp is None:
15601553
timestamp = datetime.datetime.now()
15611554
return {
15621555
"createdOn": timestamp.isoformat(),
15631556
"createdBy": {"uri": self.engine_uuid, "name": self.cwltool_version},
15641557
}
15651558

1566-
def add_to_manifest(self, rel_path, checksums):
1567-
# type: (str, Dict[str,str]) -> None
1559+
def add_to_manifest(self, rel_path: str, checksums: Dict[str,str]) -> None:
15681560
"""Add files to the research object manifest."""
15691561
self.self_check()
15701562
if PurePosixPath(rel_path).is_absolute():
@@ -1593,8 +1585,7 @@ def add_to_manifest(self, rel_path, checksums):
15931585
_logger.debug("[provenance] Added to %s: %s", manifestpath, line)
15941586
checksum_file.write(line)
15951587

1596-
def _add_to_bagit(self, rel_path, **checksums):
1597-
# type: (str, Any) -> None
1588+
def _add_to_bagit(self, rel_path: str, **checksums: str) -> None:
15981589
if PurePosixPath(rel_path).is_absolute():
15991590
raise ValueError("rel_path must be relative: %s" % rel_path)
16001591
local_path = os.path.join(self.folder, _local_path(rel_path))
@@ -1714,8 +1705,7 @@ def _relativise_files(
17141705
except TypeError:
17151706
pass
17161707

1717-
def close(self, save_to=None):
1718-
# type: (Optional[str]) -> None
1708+
def close(self, save_to: Optional[str]=None) -> None:
17191709
"""Close the Research Object, optionally saving to specified folder.
17201710
17211711
Closing will remove any temporary files used by this research object.
@@ -1748,11 +1738,11 @@ def close(self, save_to=None):
17481738

17491739

17501740
def checksum_copy(
1751-
src_file, # type: IO[Any]
1752-
dst_file=None, # type: Optional[IO[Any]]
1753-
hasher=Hasher, # type: Callable[[], hashlib._Hash]
1754-
buffersize=1024 * 1024, # type: int
1755-
): # type: (...) -> str
1741+
src_file: IO[Any],
1742+
dst_file: Optional[IO[Any]] = None,
1743+
hasher = Hasher, # type: Callable[[], hashlib._Hash]
1744+
buffersize: int=1024 * 1024,
1745+
) -> str:
17561746
"""Compute checksums while copying a file."""
17571747
# TODO: Use hashlib.new(Hasher_str) instead?
17581748
checksum = hasher()

cwltool/workflow.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -448,10 +448,11 @@ def postScatterEval(io: CWLObjectType) -> Optional[CWLObjectType]:
448448

449449
fs_access = getdefault(runtimeContext.make_fs_access, StdFsAccess)("")
450450
for k, v in io.items():
451-
val = cast(Dict[str, Any], v)
452-
if k in loadContents and val.get("contents") is None:
453-
with fs_access.open(val["location"], "rb") as f:
454-
val["contents"] = content_limit_respected_read(f)
451+
if k in loadContents:
452+
val = cast(Dict[str, Any], v)
453+
if val.get("contents") is None:
454+
with fs_access.open(val["location"], "rb") as f:
455+
val["contents"] = content_limit_respected_read(f)
455456

456457
def valueFromFunc(k: Any, v: Any) -> Any:
457458
if k in valueFrom:

0 commit comments

Comments
 (0)