Skip to content

Commit f4fcc36

Browse files
authored
Merge pull request #442 from manu-chroma/unicode_literal_usage
Working towards python3 compatible codebase
2 parents af08264 + a6bb3f9 commit f4fcc36

File tree

121 files changed

+929
-3855
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

121 files changed

+929
-3855
lines changed

.gitignore

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,3 +15,18 @@ eggs/
1515
*~
1616
\#*\#
1717
.desktop
18+
19+
# virtualenv
20+
venv/
21+
venv3/
22+
23+
# pycharm
24+
.idea/
25+
26+
# typshed repo
27+
typeshed/2and3/schema_salad
28+
typeshed/2and3/ruamel/yaml
29+
30+
31+
#mypy
32+
.mypy_cache/

Makefile

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -152,26 +152,26 @@ list-author-emails:
152152
@git log --format='%aN,%aE' | sort -u | grep -v 'root'
153153

154154

155-
mypy: ${PYSOURCES}
156-
rm -Rf typeshed/2.7/ruamel/yaml
155+
mypy2: ${PYSOURCES}
156+
rm -Rf typeshed/2and3/ruamel/yaml
157157
ln -s $(shell python -c 'from __future__ import print_function; import ruamel.yaml; import os.path; print(os.path.dirname(ruamel.yaml.__file__))') \
158-
typeshed/2.7/ruamel/yaml
159-
rm -Rf typeshed/2.7/schema_salad
158+
typeshed/2and3/ruamel/yaml
159+
rm -Rf typeshed/2and3/schema_salad
160160
ln -s $(shell python -c 'from __future__ import print_function; import schema_salad; import os.path; print(os.path.dirname(schema_salad.__file__))') \
161-
typeshed/2.7/schema_salad
162-
MYPYPATH=typeshed/2.7 mypy --py2 --disallow-untyped-calls \
163-
--warn-redundant-casts --warn-unused-ignores --fast-parser \
161+
typeshed/2and3/schema_salad
162+
MYPYPATH=$MYPYPATH:typeshed/2.7:typeshed/2and3 mypy --py2 --disallow-untyped-calls \
163+
--warn-redundant-casts --warn-unused-ignores \
164164
cwltool
165165

166166
mypy3: ${PYSOURCES}
167-
rm -Rf typeshed/3/ruamel/yaml
167+
rm -Rf typeshed/2and3/ruamel/yaml
168168
ln -s $(shell python3 -c 'from __future__ import print_function; import ruamel.yaml; import os.path; print(os.path.dirname(ruamel.yaml.__file__))') \
169-
typeshed/3/ruamel/yaml
170-
rm -Rf typeshed/3/schema_salad
169+
typeshed/2and3/ruamel/yaml
170+
rm -Rf typeshed/2and3/schema_salad
171171
ln -s $(shell python3 -c 'from __future__ import print_function; import schema_salad; import os.path; print(os.path.dirname(schema_salad.__file__))') \
172-
typeshed/3/schema_salad
173-
MYPYPATH=typeshed/3 mypy --disallow-untyped-calls \
174-
--warn-redundant-casts --warn-unused-ignores --fast-parser \
172+
typeshed/2and3/schema_salad
173+
MYPYPATH=$MYPYPATH:typeshed/3:typeshed/2and3 mypy --disallow-untyped-calls \
174+
--warn-redundant-casts --warn-unused-ignores \
175175
cwltool
176176

177177
FORCE:

cwlref-runner/setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
#!/usr/bin/env python
2-
2+
from __future__ import absolute_import
33
import os
44

55
from setuptools import setup, find_packages

cwltool.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#!/usr/bin/env python
2+
from __future__ import absolute_import
23
"""Convienance entry point for cwltool.
34
45
This can be used instead of the recommended method of `./setup.py install`

cwltool/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
1+
from __future__ import absolute_import
12
__author__ = '[email protected]'

cwltool/__main__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from __future__ import absolute_import
12
import sys
23

34
from . import main

cwltool/builder.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1+
from __future__ import absolute_import
12
import copy
2-
from typing import Any, Callable, Text, Type, Union
3+
from typing import Any, Callable, Dict, List, Text, Type, Union
34

5+
import six
46
from six import iteritems, string_types
57

68
import avro
@@ -15,6 +17,11 @@
1517
from .stdfsaccess import StdFsAccess
1618
from .utils import aslist
1719

20+
# if six.PY3:
21+
# AvroSchemaFromJSONData = avro.schema.SchemaFromJSONData
22+
# else:
23+
AvroSchemaFromJSONData = avro.schema.make_avsc_object
24+
1825
CONTENT_LIMIT = 64 * 1024
1926

2027

@@ -86,7 +93,7 @@ def bind_input(self, schema, datum, lead_pos=None, tail_pos=None):
8693
elif isinstance(t, dict) and "name" in t and self.names.has_name(t["name"], ""):
8794
avsc = self.names.get_name(t["name"], "")
8895
else:
89-
avsc = avro.schema.make_avsc_object(t, self.names)
96+
avsc = AvroSchemaFromJSONData(t, self.names)
9097
if validate.validate(avsc, datum):
9198
schema = copy.deepcopy(schema)
9299
schema["type"] = t

cwltool/cwlrdf.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from __future__ import absolute_import
12
from typing import IO, Any, Dict, Text
23

34
from rdflib import Graph

cwltool/docker.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
1+
from __future__ import absolute_import
12
import logging
23
import os
34
import re
45
import subprocess
56
import sys
67
import tempfile
7-
from typing import Text
8+
from typing import Dict, List, Text
89

910
import requests
1011

@@ -21,7 +22,7 @@ def get_image(dockerRequirement, pull_image, dry_run=False):
2122
dockerRequirement["dockerImageId"] = dockerRequirement["dockerPull"]
2223

2324
for ln in subprocess.check_output(
24-
["docker", "images", "--no-trunc", "--all"]).splitlines():
25+
["docker", "images", "--no-trunc", "--all"]).decode('utf-8').splitlines():
2526
try:
2627
m = re.match(r"^([^ ]+)\s+([^ ]+)\s+([^ ]+)", ln)
2728
sp = dockerRequirement["dockerImageId"].split(":")
@@ -46,7 +47,7 @@ def get_image(dockerRequirement, pull_image, dry_run=False):
4647
pass
4748

4849
if not found and pull_image:
49-
cmd = [] # type: List[str]
50+
cmd = [] # type: List[Text]
5051
if "dockerPull" in dockerRequirement:
5152
cmd = ["docker", "pull", str(dockerRequirement["dockerPull"])]
5253
_logger.info(Text(cmd))
@@ -55,8 +56,8 @@ def get_image(dockerRequirement, pull_image, dry_run=False):
5556
found = True
5657
elif "dockerFile" in dockerRequirement:
5758
dockerfile_dir = str(tempfile.mkdtemp())
58-
with open(os.path.join(dockerfile_dir, "Dockerfile"), "w") as df:
59-
df.write(dockerRequirement["dockerFile"])
59+
with open(os.path.join(dockerfile_dir, "Dockerfile"), str("w")) as df:
60+
df.write(dockerRequirement["dockerFile"].encode('utf-8'))
6061
cmd = ["docker", "build", "--tag=%s" %
6162
str(dockerRequirement["dockerImageId"]), dockerfile_dir]
6263
_logger.info(Text(cmd))
@@ -69,7 +70,7 @@ def get_image(dockerRequirement, pull_image, dry_run=False):
6970
if not dry_run:
7071
if os.path.exists(dockerRequirement["dockerLoad"]):
7172
_logger.info(u"Loading docker image from %s", dockerRequirement["dockerLoad"])
72-
with open(dockerRequirement["dockerLoad"], "rb") as f:
73+
with open(dockerRequirement["dockerLoad"], str("rb")) as f:
7374
loadproc = subprocess.Popen(cmd, stdin=f, stdout=sys.stderr)
7475
else:
7576
loadproc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=sys.stderr)

cwltool/docker_uid.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
from __future__ import print_function
2+
from __future__ import absolute_import
23

34
import subprocess
4-
from typing import Text
5+
from typing import List, Text
56

67

78
def docker_vm_uid(): # type: () -> int
@@ -91,6 +92,7 @@ def cmd_output_to_int(cmd): # type: (List[Text]) -> int
9192
except ValueError:
9293
# ValueError is raised if int conversion fails
9394
return None
95+
return None
9496

9597

9698
def boot2docker_uid(): # type: () -> int

cwltool/draft2tool.py

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from __future__ import absolute_import
12
import copy
23
import hashlib
34
import json
@@ -7,7 +8,7 @@
78
import shutil
89
import tempfile
910
from functools import partial
10-
from typing import Any, Callable, Dict, Generator, Optional, Text, Union, cast
11+
from typing import Any, Callable, Dict, Generator, List, Optional, Set, Text, Union, cast
1112

1213
from six import string_types, u
1314

@@ -28,6 +29,7 @@
2829
normalizeFilesDirs, shortname, uniquename)
2930
from .stdfsaccess import StdFsAccess
3031
from .utils import aslist
32+
from six.moves import map
3133

3234
ACCEPTLIST_EN_STRICT_RE = re.compile(r"^[a-zA-Z0-9._+-]+$")
3335
ACCEPTLIST_EN_RELAXED_RE = re.compile(r".*") # Accept anything
@@ -60,7 +62,7 @@ def run(self, **kwargs): # type: (**Any) -> None
6062
normalizeFilesDirs(ev)
6163
self.output_callback(ev, "success")
6264
except Exception as e:
63-
_logger.warn(u"Failed to evaluate expression:\n%s",
65+
_logger.warning(u"Failed to evaluate expression:\n%s",
6466
e, exc_info=kwargs.get('debug'))
6567
self.output_callback({}, "permanentFail")
6668

@@ -224,7 +226,7 @@ def job(self,
224226
visit_class([cachebuilder.files, cachebuilder.bindings],
225227
("File", "Directory"), _check_adjust)
226228

227-
cmdline = flatten(map(cachebuilder.generate_arg, cachebuilder.bindings))
229+
cmdline = flatten(list(map(cachebuilder.generate_arg, cachebuilder.bindings)))
228230
(docker_req, docker_is_req) = self.get_requirement("DockerRequirement")
229231
if docker_req and kwargs.get("use_container") is not False:
230232
dockerimg = docker_req.get("dockerImageId") or docker_req.get("dockerPull")
@@ -253,7 +255,7 @@ def job(self,
253255
keydict[r["class"]] = r
254256

255257
keydictstr = json.dumps(keydict, separators=(',', ':'), sort_keys=True)
256-
cachekey = hashlib.md5(keydictstr).hexdigest()
258+
cachekey = hashlib.md5(keydictstr.encode('utf-8')).hexdigest()
257259

258260
_logger.debug("[job %s] keydictstr is %s -> %s", jobname,
259261
keydictstr, cachekey)
@@ -446,7 +448,7 @@ def register_reader(f):
446448
cmd.extend(aslist(arg))
447449
j.command_line = ["/bin/sh", "-c", " ".join(cmd)]
448450
else:
449-
j.command_line = flatten(map(builder.generate_arg, builder.bindings))
451+
j.command_line = flatten(list(map(builder.generate_arg, builder.bindings)))
450452

451453
j.pathmapper = builder.pathmapper
452454
j.collect_outputs = partial(
@@ -535,7 +537,7 @@ def collect_output(self, schema, builder, outdir, fs_access, compute_checksum=Tr
535537
"class": "File" if fs_access.isfile(g) else "Directory"}
536538
for g in fs_access.glob(fs_access.join(outdir, gb))])
537539
except (OSError, IOError) as e:
538-
_logger.warn(Text(e))
540+
_logger.warning(Text(e))
539541
except:
540542
_logger.error("Unexpected error from fs_access", exc_info=True)
541543
raise
@@ -547,14 +549,14 @@ def collect_output(self, schema, builder, outdir, fs_access, compute_checksum=Tr
547549
get_listing(fs_access, files, (ll == "deep_listing"))
548550
else:
549551
with fs_access.open(files["location"], "rb") as f:
550-
contents = ""
552+
contents = b""
551553
if binding.get("loadContents") or compute_checksum:
552554
contents = f.read(CONTENT_LIMIT)
553555
if binding.get("loadContents"):
554556
files["contents"] = contents
555557
if compute_checksum:
556558
checksum = hashlib.sha1()
557-
while contents != "":
559+
while contents != b"":
558560
checksum.update(contents)
559561
contents = f.read(1024 * 1024)
560562
files["checksum"] = "sha1$%s" % checksum.hexdigest()

cwltool/expression.py

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,41 @@
1+
from __future__ import absolute_import
12
import copy
23
import json
34
import logging
45
import re
56
from typing import Any, AnyStr, Dict, List, Text, Union
6-
7+
import six
78
from six import u
89

910
from . import sandboxjs
1011
from .errors import WorkflowException
12+
from .utils import bytes2str_in_dicts
1113

1214
_logger = logging.getLogger("cwltool")
1315

1416

1517
def jshead(engineConfig, rootvars):
1618
# type: (List[Text], Dict[Text, Any]) -> Text
19+
20+
# make sure all the byte strings are converted
21+
# to str in `rootvars` dict.
22+
# TODO: need to make sure the `rootvars dict`
23+
# contains no bytes type in the first place.
24+
if six.PY3:
25+
rootvars = bytes2str_in_dicts(rootvars) # type -> ignore
26+
1727
return u"\n".join(engineConfig + [u"var %s = %s;" % (k, json.dumps(v, indent=4)) for k, v in rootvars.items()])
1828

1929

30+
# decode all raw strings to unicode
2031
seg_symbol = r"""\w+"""
2132
seg_single = r"""\['([^']|\\')+'\]"""
2233
seg_double = r"""\["([^"]|\\")+"\]"""
2334
seg_index = r"""\[[0-9]+\]"""
2435
segments = r"(\.%s|%s|%s|%s)" % (seg_symbol, seg_single, seg_double, seg_index)
25-
segment_re = re.compile(segments, flags=re.UNICODE)
26-
param_re = re.compile(r"\((%s)%s*\)$" % (seg_symbol, segments), flags=re.UNICODE)
36+
segment_re = re.compile(u(segments), flags=re.UNICODE)
37+
param_str = r"\((%s)%s*\)$" % (seg_symbol, segments)
38+
param_re = re.compile(u(param_str), flags=re.UNICODE)
2739

2840
JSON = Union[Dict[Any, Any], List[Any], Text, int, float, bool, None]
2941

@@ -110,7 +122,7 @@ def scanner(scan): # type: (Text) -> List[int]
110122
def next_seg(remain, obj): # type: (Text, Any) -> Any
111123
if remain:
112124
m = segment_re.match(remain)
113-
key = None # type: Union[str, int]
125+
key = None # type: Union[Text, int]
114126
if m.group(0)[0] == '.':
115127
key = m.group(0)[1:]
116128
elif m.group(0)[1] in ("'", '"'):

cwltool/factory.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1+
from __future__ import absolute_import
12
import os
23
from typing import Callable as tCallable
3-
from typing import Any, Text, Tuple, Union
4+
from typing import Any, Dict, Text, Tuple, Union
45

56
from . import load_tool, main, workflow
67
from .process import Process

cwltool/flatten.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from __future__ import absolute_import
12
from typing import Any, Callable, List, cast
23

34
# http://rightfootin.blogspot.com/2006/09/more-on-python-flatten.html

0 commit comments

Comments
 (0)