Skip to content

Commit 4ec3730

Browse files
committed
improve python3 support
1 parent 4d1395a commit 4ec3730

File tree

13 files changed

+48
-39
lines changed

13 files changed

+48
-39
lines changed

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
@@ -91,7 +92,7 @@ def revmap_file(builder, outdir, f):
9192
internal output directories to the external directory.
9293
"""
9394

94-
split = urlparse.urlsplit(outdir)
95+
split = urllib.parse.urlsplit(outdir)
9596
if not split.scheme:
9697
outdir = file_uri(str(outdir))
9798

@@ -338,7 +339,7 @@ def rm_pending_output_callback(output_callback, jobcachepending,
338339
ls.append(builder.do_eval(t))
339340
for i, t in enumerate(ls):
340341
if "entry" in t:
341-
if isinstance(t["entry"], basestring):
342+
if isinstance(t["entry"], string_types):
342343
ls[i] = {
343344
"class": "File",
344345
"basename": t["entryname"],
@@ -406,7 +407,7 @@ def collect_output_ports(self, ports, builder, outdir, compute_checksum=True):
406407
% shortname(port["id"]), exc_info=True)
407408
raise WorkflowException(
408409
u"Error collecting output for parameter '%s':\n%s"
409-
% (shortname(port["id"]), indent(unicode(e))))
410+
% (shortname(port["id"]), indent(u(e))))
410411

411412
if ret:
412413
adjustFileObjs(ret,
@@ -515,7 +516,7 @@ def collect_output(self, schema, builder, outdir, fs_access, compute_checksum=Tr
515516
for sf in aslist(schema["secondaryFiles"]):
516517
if isinstance(sf, dict) or "$(" in sf or "${" in sf:
517518
sfpath = builder.do_eval(sf, context=primary)
518-
if isinstance(sfpath, basestring):
519+
if isinstance(sfpath, string_types):
519520
sfpath = revmap({"location": sfpath, "class": "File"})
520521
else:
521522
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, 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(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
@@ -466,7 +467,7 @@ def load_job_order(args, t, stdin, print_input_deps=False, relative_deps=False,
466467

467468
if not job_order_object and len(t.tool["inputs"]) > 0:
468469
if toolparser:
469-
print u"\nOptions for %s " % args.workflow
470+
print(u"\nOptions for %s " % args.workflow)
470471
toolparser.print_help()
471472
_logger.error("")
472473
_logger.error("Input object required, use --help for details")
@@ -616,7 +617,7 @@ def main(argsl=None, # type: List[str]
616617
_logger.setLevel(logging.DEBUG)
617618

618619
if args.version:
619-
print versionfunc()
620+
print(versionfunc())
620621
return 0
621622
else:
622623
_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:

0 commit comments

Comments
 (0)