Skip to content

Commit dd3f90a

Browse files
authored
Merge pull request #306 from common-workflow-language/gijzelaerr-py3
py3
2 parents c823085 + eb10e49 commit dd3f90a

15 files changed

+78
-46
lines changed

.travis.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@ sudo: false
22
language: python
33
python:
44
- 2.7
5+
# - 3.4
56
- 3.5
7+
# - 3.6
68
os:
79
- linux
810

Makefile

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,4 +158,15 @@ mypy: ${PYSOURCES}
158158
--warn-redundant-casts --warn-unused-ignores --fast-parser \
159159
cwltool
160160

161+
mypy3: ${PYSOURCES}
162+
rm -Rf typeshed/3/ruamel/yaml
163+
ln -s $(shell python3 -c 'from __future__ import print_function; import ruamel.yaml; import os.path; print(os.path.dirname(ruamel.yaml.__file__))') \
164+
typeshed/3/ruamel/yaml
165+
rm -Rf typeshed/3/schema_salad
166+
ln -s $(shell python3 -c 'from __future__ import print_function; import schema_salad; import os.path; print(os.path.dirname(schema_salad.__file__))') \
167+
typeshed/3/schema_salad
168+
MYPYPATH=typeshed/3 mypy --disallow-untyped-calls \
169+
--warn-redundant-casts --warn-unused-ignores --fast-parser \
170+
cwltool
171+
161172
FORCE:

cwltool/builder.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import schema_salad.validate as validate
55
from schema_salad.sourceline import SourceLine
66
from typing import Any, Callable, Text, Type, Union
7+
from six import string_types, iteritems
78

89
from . import expression
910
from .errors import WorkflowException
@@ -121,7 +122,7 @@ def bind_input(self, schema, datum, lead_pos=None, tail_pos=None):
121122
for sf in aslist(schema["secondaryFiles"]):
122123
if isinstance(sf, dict) or "$(" in sf or "${" in sf:
123124
secondary_eval = self.do_eval(sf, context=datum)
124-
if isinstance(secondary_eval, basestring):
125+
if isinstance(secondary_eval, string_types):
125126
sfpath = {"location": secondary_eval,
126127
"class": "File"}
127128
else:
@@ -203,7 +204,7 @@ def do_eval(self, ex, context=None, pull_image=True, recursive=False):
203204
# type: (Union[Dict[Text, Text], Text], Any, bool, bool) -> Any
204205
if recursive:
205206
if isinstance(ex, dict):
206-
return {k: self.do_eval(v, context, pull_image, recursive) for k, v in ex.iteritems()}
207+
return {k: self.do_eval(v, context, pull_image, recursive) for k, v in iteritems(ex)}
207208
if isinstance(ex, list):
208209
return [self.do_eval(v, context, pull_image, recursive) for v in ex]
209210

cwltool/cwlrdf.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
1-
import urlparse
2-
31
from rdflib import Graph
42
from schema_salad.jsonld_context import makerdf
53
from schema_salad.ref_resolver import ContextType
64
from typing import Any, Dict, IO, Text
5+
from six.moves import urllib
76

87
from .process import Process
98

@@ -133,7 +132,7 @@ def dot_without_parameters(g, stdout): # type: (Graph, IO[Any]) -> None
133132
currentwf = None
134133

135134
if Text(runtype) != "https://w3id.org/cwl/cwl#Workflow":
136-
stdout.write(u'"%s" [label="%s"]\n' % (dotname[step], urlparse.urldefrag(Text(step))[1]))
135+
stdout.write(u'"%s" [label="%s"]\n' % (dotname[step], urllib.parse.urldefrag(Text(step))[1]))
137136

138137
if currentwf is not None:
139138
stdout.write("}\n")

cwltool/docker_uid.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from __future__ import print_function
12
import subprocess
23

34
from typing import Text
@@ -111,4 +112,4 @@ def docker_machine_uid(): # type: () -> int
111112

112113

113114
if __name__ == '__main__':
114-
print docker_vm_uid()
115+
print(docker_vm_uid())

cwltool/draft2tool.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@
66
import re
77
import shutil
88
import tempfile
9-
import urlparse
9+
from six.moves import urllib
10+
from six import string_types, u
1011
from functools import partial
1112

1213
import schema_salad.validate as validate
@@ -95,7 +96,7 @@ def revmap_file(builder, outdir, f):
9596
internal output directories to the external directory.
9697
"""
9798

98-
split = urlparse.urlsplit(outdir)
99+
split = urllib.parse.urlsplit(outdir)
99100
if not split.scheme:
100101
outdir = file_uri(str(outdir))
101102

@@ -346,7 +347,7 @@ def rm_pending_output_callback(output_callbacks, jobcachepending,
346347
ls.append(builder.do_eval(t))
347348
for i, t in enumerate(ls):
348349
if "entry" in t:
349-
if isinstance(t["entry"], basestring):
350+
if isinstance(t["entry"], string_types):
350351
ls[i] = {
351352
"class": "File",
352353
"basename": t["entryname"],
@@ -415,7 +416,7 @@ def collect_output_ports(self, ports, builder, outdir, compute_checksum=True):
415416
% shortname(port["id"]), exc_info=True)
416417
raise WorkflowException(
417418
u"Error collecting output for parameter '%s':\n%s"
418-
% (shortname(port["id"]), indent(unicode(e))))
419+
% (shortname(port["id"]), indent(u(str(e)))))
419420

420421
if ret:
421422
adjustFileObjs(ret,
@@ -527,7 +528,7 @@ def collect_output(self, schema, builder, outdir, fs_access, compute_checksum=Tr
527528
for sf in aslist(schema["secondaryFiles"]):
528529
if isinstance(sf, dict) or "$(" in sf or "${" in sf:
529530
sfpath = builder.do_eval(sf, context=primary)
530-
if isinstance(sfpath, basestring):
531+
if isinstance(sfpath, string_types):
531532
sfpath = revmap({"location": sfpath, "class": "File"})
532533
else:
533534
sfpath = {"location": substitute(primary["location"], sf), "class": "File"}

cwltool/expression.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import re
55

66
from typing import Any, AnyStr, Union, Text, Dict, List
7+
from six import u
78

89
from . import sandboxjs
910
from .errors import WorkflowException
@@ -24,7 +25,7 @@ def jshead(engineConfig, rootvars):
2425
segment_re = re.compile(segments, flags=re.UNICODE)
2526
param_re = re.compile(r"\((%s)%s*\)$" % (seg_symbol, segments), flags=re.UNICODE)
2627

27-
JSON = Union[Dict[Any, Any], List[Any], Text, int, long, float, bool, None]
28+
JSON = Union[Dict[Any, Any], List[Any], Text, int, float, bool, None]
2829

2930

3031
class SubstitutionError(Exception):
@@ -126,7 +127,7 @@ def next_seg(remain, obj): # type: (Text, Any) -> Any
126127
try:
127128
key = int(m.group(0)[1:-1])
128129
except ValueError as v:
129-
raise WorkflowException(unicode(v))
130+
raise WorkflowException(u(str(v)))
130131
if not isinstance(obj, list):
131132
raise WorkflowException(" is a %s, cannot index on int '%s'" % (type(obj).__name__, key))
132133
if key >= len(obj):

cwltool/load_tool.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
import logging
55
import os
66
import re
7-
import urlparse
87
import uuid
98

109
import requests.sessions
@@ -15,6 +14,8 @@
1514
from schema_salad.sourceline import cmap
1615
from schema_salad.validate import ValidationException
1716
from typing import Any, Callable, cast, Dict, Text, Tuple, Union
17+
from six.moves import urllib
18+
from six import itervalues, string_types
1819

1920
from . import process
2021
from . import update
@@ -37,8 +38,8 @@ def fetch_document(argsworkflow, # type: Union[Text, dict[Text, Any]]
3738

3839
uri = None # type: Text
3940
workflowobj = None # type: CommentedMap
40-
if isinstance(argsworkflow, basestring):
41-
split = urlparse.urlsplit(argsworkflow)
41+
if isinstance(argsworkflow, string_types):
42+
split = urllib.parse.urlsplit(argsworkflow)
4243
if split.scheme:
4344
uri = argsworkflow
4445
elif os.path.exists(os.path.abspath(argsworkflow)):
@@ -52,7 +53,7 @@ def fetch_document(argsworkflow, # type: Union[Text, dict[Text, Any]]
5253
if argsworkflow != uri:
5354
_logger.info("Resolved '%s' to '%s'", argsworkflow, uri)
5455

55-
fileuri = urlparse.urldefrag(uri)[0]
56+
fileuri = urllib.parse.urldefrag(uri)[0]
5657
workflowobj = document_loader.fetch(fileuri)
5758
elif isinstance(argsworkflow, dict):
5859
uri = "#" + Text(id(argsworkflow))
@@ -101,7 +102,7 @@ def _convert_stdstreams_to_files(workflowobj):
101102
inp['id'].rpartition('#')[2]
102103
inp['type'] = 'File'
103104
else:
104-
for entry in workflowobj.itervalues():
105+
for entry in itervalues(workflowobj):
105106
_convert_stdstreams_to_files(entry)
106107
if isinstance(workflowobj, list):
107108
for entry in workflowobj:
@@ -131,11 +132,11 @@ def validate_document(document_loader, # type: Loader
131132
jobobj = None
132133
if "cwl:tool" in workflowobj:
133134
jobobj, _ = document_loader.resolve_all(workflowobj, uri)
134-
uri = urlparse.urljoin(uri, workflowobj["https://w3id.org/cwl/cwl#tool"])
135+
uri = urllib.parse.urljoin(uri, workflowobj["https://w3id.org/cwl/cwl#tool"])
135136
del cast(dict, jobobj)["https://w3id.org/cwl/cwl#tool"]
136137
workflowobj = fetch_document(uri, fetcher_constructor=fetcher_constructor)[1]
137138

138-
fileuri = urlparse.urldefrag(uri)[0]
139+
fileuri = urllib.parse.urldefrag(uri)[0]
139140

140141
if "cwlVersion" in workflowobj:
141142
if not isinstance(workflowobj["cwlVersion"], (str, Text)):
@@ -213,7 +214,7 @@ def make_tool(document_loader, # type: Loader
213214
raise WorkflowException(
214215
u"Tool file contains graph of multiple objects, must specify "
215216
"one of #%s" % ", #".join(
216-
urlparse.urldefrag(i["id"])[1] for i in resolveduri
217+
urllib.parse.urldefrag(i["id"])[1] for i in resolveduri
217218
if "id" in i))
218219
elif isinstance(resolveduri, dict):
219220
processobj = resolveduri

cwltool/main.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#!/usr/bin/env python
2+
from __future__ import print_function
23

34
import argparse
45
import functools
@@ -469,7 +470,7 @@ def load_job_order(args, t, stdin, print_input_deps=False, relative_deps=False,
469470

470471
if not job_order_object and len(t.tool["inputs"]) > 0:
471472
if toolparser:
472-
print u"\nOptions for %s " % args.workflow
473+
print(u"\nOptions for {} ".format(args.workflow))
473474
toolparser.print_help()
474475
_logger.error("")
475476
_logger.error("Input object required, use --help for details")
@@ -619,7 +620,7 @@ def main(argsl=None, # type: List[str]
619620
_logger.setLevel(logging.DEBUG)
620621

621622
if args.version:
622-
print versionfunc()
623+
print(versionfunc())
623624
return 0
624625
else:
625626
_logger.info(versionfunc())

cwltool/pack.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import copy
2-
import urlparse
32

43
from schema_salad.ref_resolver import Loader
54
from typing import Union, Any, cast, Callable, Dict, Text
5+
from six.moves import urllib
66

77
from .process import shortname, uniquename
88

@@ -82,7 +82,7 @@ def loadref(b, u):
8282
names = set() # type: Set[Text]
8383
rewrite = {} # type: Dict[Text, Text]
8484

85-
mainpath, _ = urlparse.urldefrag(uri)
85+
mainpath, _ = urllib.parse.urldefrag(uri)
8686

8787
def rewrite_id(r, mainuri):
8888
# type: (Text, Text) -> None
@@ -91,7 +91,7 @@ def rewrite_id(r, mainuri):
9191
elif r.startswith(mainuri) and r[len(mainuri)] in ("#", "/"):
9292
pass
9393
else:
94-
path, frag = urlparse.urldefrag(r)
94+
path, frag = urllib.parse.urldefrag(r)
9595
if path == mainpath:
9696
rewrite[r] = "#" + uniquename(frag, names)
9797
else:

cwltool/pathmapper.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,14 @@
22
import logging
33
import os
44
import stat
5-
import urllib
6-
import urlparse
75
import uuid
86
from functools import partial
97

108
import schema_salad.validate as validate
119
from schema_salad.ref_resolver import uri_file_path
1210
from schema_salad.sourceline import SourceLine
1311
from typing import Any, Callable, Set, Text, Tuple, Union
12+
from six.moves import urllib
1413

1514
_logger = logging.getLogger("cwltool")
1615

@@ -71,8 +70,8 @@ def addLocation(d):
7170
d["basename"] = Text(uuid.uuid4())
7271

7372
if "basename" not in d:
74-
parse = urlparse.urlparse(d["location"])
75-
d["basename"] = os.path.basename(urllib.url2pathname(parse.path))
73+
parse = urllib.parse.urlparse(d["location"])
74+
d["basename"] = os.path.basename(urllib.request.url2pathname(parse.path))
7675

7776
adjustFileObjs(job, addLocation)
7877
adjustDirObjs(job, addLocation)

cwltool/process.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -181,7 +181,7 @@ def stageFiles(pm, stageFunc, ignoreWritable=False):
181181
# type: (PathMapper, Callable[..., Any], bool) -> None
182182
for f, p in pm.items():
183183
if not os.path.exists(os.path.dirname(p.target)):
184-
os.makedirs(os.path.dirname(p.target), 0755)
184+
os.makedirs(os.path.dirname(p.target), 0o0755)
185185
if p.type == "File":
186186
stageFunc(p.resolved, p.target)
187187
elif p.type == "WritableFile" and not ignoreWritable:

cwltool/sandboxjs.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,22 @@
1-
import cStringIO
21
import errno
32
import json
43
import logging
54
import os
65
import select
76
import subprocess
87
import threading
9-
from cStringIO import StringIO
8+
from io import BytesIO
109

1110
from pkg_resources import resource_stream
1211
from typing import Any, Dict, List, Mapping, Text, Union
1312

14-
1513
class JavascriptException(Exception):
1614
pass
1715

1816

1917
_logger = logging.getLogger("cwltool")
2018

21-
JSON = Union[Dict[Text, Any], List[Any], Text, int, long, float, bool, None]
19+
JSON = Union[Dict[Text, Any], List[Any], Text, int, float, bool, None]
2220

2321
localdata = threading.local()
2422

@@ -101,11 +99,11 @@ def term():
10199
tm = threading.Timer(timeout, term)
102100
tm.start()
103101

104-
stdin_buf = StringIO(json.dumps(fn) + "\n")
105-
stdout_buf = StringIO()
106-
stderr_buf = StringIO()
102+
stdin_buf = BytesIO(json.dumps(fn) + "\n")
103+
stdout_buf = BytesIO()
104+
stderr_buf = BytesIO()
107105

108-
completed = [] # type: List[Union[cStringIO.InputType, cStringIO.OutputType]]
106+
completed = [] # type: List[BytesIO]
109107
while len(completed) < 3:
110108
rready, wready, _ = select.select([nodejs.stdout, nodejs.stderr], [nodejs.stdin], [])
111109
if nodejs.stdin in wready:

setup.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,9 @@
5151
'rdflib >= 4.2.2, < 4.3.0',
5252
'shellescape >= 3.4.1, < 3.5',
5353
'schema-salad >= 2.2.20170222151604, < 3',
54-
'typing >= 3.5.2, < 3.6'
54+
'typing >= 3.5.2, < 3.6',
55+
'six >= 1.10.0',
56+
5557
],
5658
setup_requires=[] + pytest_runner,
5759
test_suite='tests',

0 commit comments

Comments
 (0)