121
|
1 # replace with shebang for biocontainer
|
|
2 # see https://github.com/fubar2/toolfactory
|
|
3 #
|
|
4 # copyright ross lazarus (ross stop lazarus at gmail stop com) May 2012
|
|
5 #
|
|
6 # all rights reserved
|
|
7 # Licensed under the LGPL
|
|
8 # suggestions for improvement and bug fixes welcome at
|
|
9 # https://github.com/fubar2/toolfactory
|
|
10 #
|
|
11 # July 2020: BCC was fun and I feel like rip van winkle after 5 years.
|
|
12 # Decided to
|
|
13 # 1. Fix the toolfactory so it works - done for simplest case
|
|
14 # 2. Fix planemo so the toolfactory function works
|
|
15 # 3. Rewrite bits using galaxyxml functions where that makes sense - done
|
|
16
|
|
17 import argparse
|
|
18 import copy
|
126
|
19 import json
|
121
|
20 import logging
|
|
21 import os
|
|
22 import re
|
|
23 import shutil
|
|
24 import subprocess
|
|
25 import sys
|
|
26 import tarfile
|
|
27 import tempfile
|
|
28 import time
|
|
29
|
|
30
|
|
31 import galaxyxml.tool as gxt
|
|
32 import galaxyxml.tool.parameters as gxtp
|
|
33 import lxml
|
|
34 import yaml
|
127
|
35 from bioblend import ConnectionError
|
|
36 from bioblend import toolshed
|
121
|
37
|
126
|
38
|
|
39 myversion = "V2.2 February 2021"
|
121
|
40 verbose = True
|
|
41 debug = True
|
|
42 toolFactoryURL = "https://github.com/fubar2/toolfactory"
|
|
43 foo = len(lxml.__version__)
|
|
44 # fug you, flake8. Say my name!
|
|
45 FAKEEXE = "~~~REMOVE~~~ME~~~"
|
|
46 # need this until a PR/version bump to fix galaxyxml prepending the exe even
|
|
47 # with override.
|
|
48
|
|
49
|
|
50 def timenow():
|
|
51 """return current time as a string"""
|
|
52 return time.strftime("%d/%m/%Y %H:%M:%S", time.localtime(time.time()))
|
|
53
|
|
54
|
|
55 cheetah_escape_table = {"$": "\\$", "#": "\\#"}
|
|
56
|
|
57
|
|
58 def cheetah_escape(text):
|
|
59 """Produce entities within text."""
|
|
60 return "".join([cheetah_escape_table.get(c, c) for c in text])
|
|
61
|
|
62
|
|
63 def parse_citations(citations_text):
|
|
64 """"""
|
|
65 citations = [c for c in citations_text.split("**ENTRY**") if c.strip()]
|
|
66 citation_tuples = []
|
|
67 for citation in citations:
|
|
68 if citation.startswith("doi"):
|
|
69 citation_tuples.append(("doi", citation[len("doi") :].strip()))
|
|
70 else:
|
|
71 citation_tuples.append(("bibtex", citation[len("bibtex") :].strip()))
|
|
72 return citation_tuples
|
|
73
|
|
74
|
|
75 class ScriptRunner:
|
|
76 """Wrapper for an arbitrary script
|
|
77 uses galaxyxml
|
|
78
|
|
79 """
|
|
80
|
|
81 def __init__(self, args=None):
|
|
82 """
|
|
83 prepare command line cl for running the tool here
|
|
84 and prepare elements needed for galaxyxml tool generation
|
|
85 """
|
|
86 self.ourcwd = os.getcwd()
|
126
|
87 self.collections = []
|
|
88 if len(args.collection) > 0:
|
|
89 try:
|
|
90 self.collections = [
|
|
91 json.loads(x) for x in args.collection if len(x.strip()) > 1
|
|
92 ]
|
|
93 except Exception:
|
|
94 print(
|
|
95 f"--collections parameter {str(args.collection)} is malformed - should be a dictionary"
|
|
96 )
|
|
97 try:
|
|
98 self.infiles = [
|
|
99 json.loads(x) for x in args.input_files if len(x.strip()) > 1
|
|
100 ]
|
|
101 except Exception:
|
|
102 print(
|
|
103 f"--input_files parameter {str(args.input_files)} is malformed - should be a dictionary"
|
|
104 )
|
|
105 try:
|
|
106 self.outfiles = [
|
|
107 json.loads(x) for x in args.output_files if len(x.strip()) > 1
|
|
108 ]
|
|
109 except Exception:
|
|
110 print(
|
|
111 f"--output_files parameter {args.output_files} is malformed - should be a dictionary"
|
|
112 )
|
|
113 try:
|
|
114 self.addpar = [
|
|
115 json.loads(x) for x in args.additional_parameters if len(x.strip()) > 1
|
|
116 ]
|
|
117 except Exception:
|
|
118 print(
|
|
119 f"--additional_parameters {args.additional_parameters} is malformed - should be a dictionary"
|
|
120 )
|
|
121 try:
|
|
122 self.selpar = [
|
|
123 json.loads(x) for x in args.selecttext_parameters if len(x.strip()) > 1
|
|
124 ]
|
|
125 except Exception:
|
|
126 print(
|
|
127 f"--selecttext_parameters {args.selecttext_parameters} is malformed - should be a dictionary"
|
|
128 )
|
121
|
129 self.args = args
|
|
130 self.cleanuppar()
|
|
131 self.lastclredirect = None
|
|
132 self.lastxclredirect = None
|
|
133 self.cl = []
|
|
134 self.xmlcl = []
|
|
135 self.is_positional = self.args.parampass == "positional"
|
|
136 if self.args.sysexe:
|
126
|
137 if ' ' in self.args.sysexe:
|
|
138 self.executeme = self.args.sysexe.split(' ')
|
|
139 else:
|
|
140 self.executeme = [self.args.sysexe, ]
|
121
|
141 else:
|
|
142 if self.args.packages:
|
126
|
143 self.executeme = [self.args.packages.split(",")[0].split(":")[0].strip(), ]
|
121
|
144 else:
|
|
145 self.executeme = None
|
|
146 aCL = self.cl.append
|
|
147 aXCL = self.xmlcl.append
|
|
148 assert args.parampass in [
|
|
149 "0",
|
|
150 "argparse",
|
|
151 "positional",
|
|
152 ], 'args.parampass must be "0","positional" or "argparse"'
|
|
153 self.tool_name = re.sub("[^a-zA-Z0-9_]+", "", args.tool_name)
|
|
154 self.tool_id = self.tool_name
|
|
155 self.newtool = gxt.Tool(
|
|
156 self.tool_name,
|
|
157 self.tool_id,
|
|
158 self.args.tool_version,
|
|
159 self.args.tool_desc,
|
|
160 FAKEEXE,
|
|
161 )
|
126
|
162 self.newtarpath = "%s_toolshed.gz" % self.tool_name
|
121
|
163 self.tooloutdir = "./tfout"
|
|
164 self.repdir = "./TF_run_report_tempdir"
|
|
165 self.testdir = os.path.join(self.tooloutdir, "test-data")
|
|
166 if not os.path.exists(self.tooloutdir):
|
|
167 os.mkdir(self.tooloutdir)
|
|
168 if not os.path.exists(self.testdir):
|
|
169 os.mkdir(self.testdir)
|
|
170 if not os.path.exists(self.repdir):
|
|
171 os.mkdir(self.repdir)
|
|
172 self.tinputs = gxtp.Inputs()
|
|
173 self.toutputs = gxtp.Outputs()
|
|
174 self.testparam = []
|
|
175 if self.args.script_path:
|
|
176 self.prepScript()
|
|
177 if self.args.command_override:
|
|
178 scos = open(self.args.command_override, "r").readlines()
|
|
179 self.command_override = [x.rstrip() for x in scos]
|
|
180 else:
|
|
181 self.command_override = None
|
|
182 if self.args.test_override:
|
|
183 stos = open(self.args.test_override, "r").readlines()
|
|
184 self.test_override = [x.rstrip() for x in stos]
|
|
185 else:
|
|
186 self.test_override = None
|
126
|
187 if self.args.script_path:
|
|
188 for ex in self.executeme:
|
|
189 aCL(ex)
|
|
190 aXCL(ex)
|
|
191 aCL(self.sfile)
|
|
192 aXCL("$runme")
|
|
193 else:
|
|
194 aCL(self.executeme[0])
|
|
195 aXCL(self.executeme[0])
|
|
196 self.elog = os.path.join(self.repdir, "%s_error_log.txt" % self.tool_name)
|
|
197 self.tlog = os.path.join(self.repdir, "%s_runner_log.txt" % self.tool_name)
|
|
198 if self.args.parampass == "0":
|
|
199 self.clsimple()
|
|
200 else:
|
|
201 if self.args.parampass == "positional":
|
|
202 self.prepclpos()
|
|
203 self.clpositional()
|
|
204 else:
|
|
205 self.prepargp()
|
|
206 self.clargparse()
|
|
207 if self.args.cl_prefix: # DIY CL end - misnamed!
|
121
|
208 clp = self.args.cl_prefix.split(" ")
|
|
209 for c in clp:
|
|
210 aCL(c)
|
|
211 aXCL(c)
|
126
|
212
|
|
213 def clsimple(self):
|
|
214 """no parameters - uses < and > for i/o"""
|
|
215 aCL = self.cl.append
|
|
216 aXCL = self.xmlcl.append
|
|
217 if len(self.infiles) > 0:
|
|
218 aCL("<")
|
|
219 aCL(self.infiles[0]["infilename"])
|
|
220 aXCL("<")
|
|
221 aXCL("$%s" % self.infiles[0]["infilename"])
|
|
222 if len(self.outfiles) > 0:
|
|
223 aCL(">")
|
|
224 aCL(self.outfiles[0]["name"])
|
|
225 aXCL(">")
|
|
226 aXCL("$%s" % self.outfiles[0]["name"])
|
121
|
227
|
126
|
228 def prepargp(self):
|
|
229 clsuffix = []
|
|
230 xclsuffix = []
|
|
231 for i, p in enumerate(self.infiles):
|
|
232 if p["origCL"].strip().upper() == "STDIN":
|
|
233 appendme = [
|
|
234 p["infilename"],
|
|
235 p["infilename"],
|
|
236 "< %s" % p["infilename"],
|
|
237 ]
|
|
238 xappendme = [
|
|
239 p["infilename"],
|
|
240 p["infilename"],
|
|
241 "< $%s" % p["infilename"],
|
|
242 ]
|
|
243 else:
|
|
244 appendme = [p["CL"], p["CL"], ""]
|
|
245 xappendme = [p["CL"], "$%s" % p["CL"], ""]
|
|
246 clsuffix.append(appendme)
|
|
247 xclsuffix.append(xappendme)
|
|
248 for i, p in enumerate(self.outfiles):
|
|
249 if p["origCL"].strip().upper() == "STDOUT":
|
|
250 self.lastclredirect = [">", p["name"]]
|
|
251 self.lastxclredirect = [">", "$%s" % p["name"]]
|
121
|
252 else:
|
126
|
253 clsuffix.append([p["name"], p["name"], ""])
|
|
254 xclsuffix.append([p["name"], "$%s" % p["name"], ""])
|
|
255 for p in self.addpar:
|
|
256 clsuffix.append([p["CL"], p["name"], p["override"]])
|
|
257 xclsuffix.append([p["CL"], '"$%s"' % p["name"], p["override"]])
|
|
258 for p in self.selpar:
|
|
259 clsuffix.append([p["CL"], p["name"], p["override"]])
|
|
260 xclsuffix.append([p["CL"], '"$%s"' % p["name"], p["override"]])
|
|
261 clsuffix.sort()
|
|
262 xclsuffix.sort()
|
|
263 self.xclsuffix = xclsuffix
|
|
264 self.clsuffix = clsuffix
|
|
265
|
|
266 def prepclpos(self):
|
|
267 clsuffix = []
|
|
268 xclsuffix = []
|
|
269 for i, p in enumerate(self.infiles):
|
|
270 if p["origCL"].strip().upper() == "STDIN":
|
|
271 appendme = [
|
|
272 "999",
|
|
273 p["infilename"],
|
|
274 "< $%s" % p["infilename"],
|
|
275 ]
|
|
276 xappendme = [
|
|
277 "999",
|
|
278 p["infilename"],
|
|
279 "< $%s" % p["infilename"],
|
|
280 ]
|
|
281 else:
|
|
282 appendme = [p["CL"], p["infilename"], ""]
|
|
283 xappendme = [p["CL"], "$%s" % p["infilename"], ""]
|
|
284 clsuffix.append(appendme)
|
|
285 xclsuffix.append(xappendme)
|
|
286 for i, p in enumerate(self.outfiles):
|
|
287 if p["origCL"].strip().upper() == "STDOUT":
|
|
288 self.lastclredirect = [">", p["name"]]
|
|
289 self.lastxclredirect = [">", "$%s" % p["name"]]
|
|
290 else:
|
|
291 clsuffix.append([p["CL"], p["name"], ""])
|
|
292 xclsuffix.append([p["CL"], "$%s" % p["name"], ""])
|
|
293 for p in self.addpar:
|
|
294 clsuffix.append([p["CL"], p["name"], p["override"]])
|
|
295 xclsuffix.append([p["CL"], '"$%s"' % p["name"], p["override"]])
|
|
296 for p in self.selpar:
|
|
297 clsuffix.append([p["CL"], p["name"], p["override"]])
|
|
298 xclsuffix.append([p["CL"], '"$%s"' % p["name"], p["override"]])
|
|
299 clsuffix.sort()
|
|
300 xclsuffix.sort()
|
|
301 self.xclsuffix = xclsuffix
|
|
302 self.clsuffix = clsuffix
|
121
|
303
|
|
304 def prepScript(self):
|
|
305 rx = open(self.args.script_path, "r").readlines()
|
|
306 rx = [x.rstrip() for x in rx]
|
|
307 rxcheck = [x.strip() for x in rx if x.strip() > ""]
|
|
308 assert len(rxcheck) > 0, "Supplied script is empty. Cannot run"
|
|
309 self.script = "\n".join(rx)
|
|
310 fhandle, self.sfile = tempfile.mkstemp(
|
126
|
311 prefix=self.tool_name, suffix="_%s" % (self.executeme[0])
|
121
|
312 )
|
|
313 tscript = open(self.sfile, "w")
|
|
314 tscript.write(self.script)
|
|
315 tscript.close()
|
|
316 self.escapedScript = [cheetah_escape(x) for x in rx]
|
|
317 self.spacedScript = [f" {x}" for x in rx if x.strip() > ""]
|
126
|
318 art = "%s.%s" % (self.tool_name, self.executeme[0])
|
121
|
319 artifact = open(art, "wb")
|
|
320 artifact.write(bytes("\n".join(self.escapedScript), "utf8"))
|
|
321 artifact.close()
|
|
322
|
|
323 def cleanuppar(self):
|
|
324 """ positional parameters are complicated by their numeric ordinal"""
|
|
325 if self.args.parampass == "positional":
|
|
326 for i, p in enumerate(self.infiles):
|
|
327 assert (
|
126
|
328 p["CL"].isdigit() or p["CL"].strip().upper() == "STDIN"
|
121
|
329 ), "Positional parameters must be ordinal integers - got %s for %s" % (
|
126
|
330 p["CL"],
|
|
331 p["label"],
|
121
|
332 )
|
|
333 for i, p in enumerate(self.outfiles):
|
|
334 assert (
|
126
|
335 p["CL"].isdigit() or p["CL"].strip().upper() == "STDOUT"
|
121
|
336 ), "Positional parameters must be ordinal integers - got %s for %s" % (
|
126
|
337 p["CL"],
|
|
338 p["name"],
|
121
|
339 )
|
|
340 for i, p in enumerate(self.addpar):
|
|
341 assert p[
|
126
|
342 "CL"
|
121
|
343 ].isdigit(), "Positional parameters must be ordinal integers - got %s for %s" % (
|
126
|
344 p["CL"],
|
|
345 p["name"],
|
121
|
346 )
|
|
347 for i, p in enumerate(self.infiles):
|
|
348 infp = copy.copy(p)
|
126
|
349 infp["origCL"] = infp["CL"]
|
|
350 if self.args.parampass in ["positional", "0"]:
|
|
351 infp["infilename"] = infp["label"].replace(" ", "_")
|
|
352 else:
|
|
353 infp["infilename"] = infp["CL"]
|
121
|
354 self.infiles[i] = infp
|
|
355 for i, p in enumerate(self.outfiles):
|
126
|
356 p["origCL"] = p["CL"] # keep copy
|
121
|
357 self.outfiles[i] = p
|
|
358 for i, p in enumerate(self.addpar):
|
126
|
359 p["origCL"] = p["CL"]
|
121
|
360 self.addpar[i] = p
|
|
361
|
|
362 def clpositional(self):
|
|
363 # inputs in order then params
|
|
364 aCL = self.cl.append
|
126
|
365 for (k, v, koverride) in self.clsuffix:
|
121
|
366 if " " in v:
|
|
367 aCL("%s" % v)
|
|
368 else:
|
|
369 aCL(v)
|
|
370 aXCL = self.xmlcl.append
|
126
|
371 for (k, v, koverride) in self.xclsuffix:
|
121
|
372 aXCL(v)
|
|
373 if self.lastxclredirect:
|
|
374 aXCL(self.lastxclredirect[0])
|
|
375 aXCL(self.lastxclredirect[1])
|
|
376
|
|
377 def clargparse(self):
|
|
378 """argparse style"""
|
|
379 aCL = self.cl.append
|
|
380 aXCL = self.xmlcl.append
|
|
381 # inputs then params in argparse named form
|
|
382
|
126
|
383 for (k, v, koverride) in self.xclsuffix:
|
121
|
384 if koverride > "":
|
|
385 k = koverride
|
|
386 elif len(k.strip()) == 1:
|
|
387 k = "-%s" % k
|
|
388 else:
|
|
389 k = "--%s" % k
|
|
390 aXCL(k)
|
|
391 aXCL(v)
|
126
|
392 for (k, v, koverride) in self.clsuffix:
|
121
|
393 if koverride > "":
|
|
394 k = koverride
|
|
395 elif len(k.strip()) == 1:
|
|
396 k = "-%s" % k
|
|
397 else:
|
|
398 k = "--%s" % k
|
|
399 aCL(k)
|
|
400 aCL(v)
|
|
401
|
|
402 def getNdash(self, newname):
|
|
403 if self.is_positional:
|
|
404 ndash = 0
|
|
405 else:
|
|
406 ndash = 2
|
|
407 if len(newname) < 2:
|
|
408 ndash = 1
|
|
409 return ndash
|
|
410
|
|
411 def doXMLparam(self):
|
|
412 """flake8 made me do this..."""
|
|
413 for p in self.outfiles:
|
126
|
414 newname = p["name"]
|
|
415 newfmt = p["format"]
|
|
416 newcl = p["CL"]
|
|
417 test = p["test"]
|
|
418 oldcl = p["origCL"]
|
121
|
419 test = test.strip()
|
|
420 ndash = self.getNdash(newcl)
|
|
421 aparm = gxtp.OutputData(
|
124
|
422 name=newname, format=newfmt, num_dashes=ndash, label=newname
|
121
|
423 )
|
|
424 aparm.positional = self.is_positional
|
|
425 if self.is_positional:
|
|
426 if oldcl.upper() == "STDOUT":
|
|
427 aparm.positional = 9999999
|
|
428 aparm.command_line_override = "> $%s" % newname
|
|
429 else:
|
|
430 aparm.positional = int(oldcl)
|
|
431 aparm.command_line_override = "$%s" % newname
|
|
432 self.toutputs.append(aparm)
|
|
433 ld = None
|
|
434 if test.strip() > "":
|
|
435 if test.startswith("diff"):
|
|
436 c = "diff"
|
|
437 ld = 0
|
|
438 if test.split(":")[1].isdigit:
|
|
439 ld = int(test.split(":")[1])
|
|
440 tp = gxtp.TestOutput(
|
|
441 name=newname,
|
|
442 value="%s_sample" % newname,
|
|
443 compare=c,
|
|
444 lines_diff=ld,
|
|
445 )
|
|
446 elif test.startswith("sim_size"):
|
|
447 c = "sim_size"
|
|
448 tn = test.split(":")[1].strip()
|
|
449 if tn > "":
|
|
450 if "." in tn:
|
|
451 delta = None
|
|
452 delta_frac = min(1.0, float(tn))
|
|
453 else:
|
|
454 delta = int(tn)
|
|
455 delta_frac = None
|
|
456 tp = gxtp.TestOutput(
|
|
457 name=newname,
|
|
458 value="%s_sample" % newname,
|
|
459 compare=c,
|
|
460 delta=delta,
|
|
461 delta_frac=delta_frac,
|
|
462 )
|
126
|
463 else:
|
|
464 c = test
|
|
465 tp = gxtp.TestOutput(
|
|
466 name=newname,
|
|
467 value="%s_sample" % newname,
|
|
468 compare=c,
|
|
469 )
|
121
|
470 self.testparam.append(tp)
|
|
471 for p in self.infiles:
|
126
|
472 newname = p["infilename"]
|
|
473 newfmt = p["format"]
|
121
|
474 ndash = self.getNdash(newname)
|
126
|
475 if not len(p["label"]) > 0:
|
|
476 alab = p["CL"]
|
121
|
477 else:
|
126
|
478 alab = p["label"]
|
121
|
479 aninput = gxtp.DataParam(
|
|
480 newname,
|
|
481 optional=False,
|
|
482 label=alab,
|
126
|
483 help=p["help"],
|
121
|
484 format=newfmt,
|
|
485 multiple=False,
|
|
486 num_dashes=ndash,
|
|
487 )
|
|
488 aninput.positional = self.is_positional
|
126
|
489 if self.is_positional:
|
|
490 if p["origCL"].upper() == "STDIN":
|
127
|
491 aninput.positional = 9999998
|
|
492 aninput.command_line_override = "> $%s" % newname
|
126
|
493 else:
|
127
|
494 aninput.positional = int(p["origCL"])
|
|
495 aninput.command_line_override = "$%s" % newname
|
121
|
496 self.tinputs.append(aninput)
|
|
497 tparm = gxtp.TestParam(name=newname, value="%s_sample" % newname)
|
|
498 self.testparam.append(tparm)
|
|
499 for p in self.addpar:
|
126
|
500 newname = p["name"]
|
|
501 newval = p["value"]
|
|
502 newlabel = p["label"]
|
|
503 newhelp = p["help"]
|
|
504 newtype = p["type"]
|
|
505 newcl = p["CL"]
|
|
506 oldcl = p["origCL"]
|
121
|
507 if not len(newlabel) > 0:
|
|
508 newlabel = newname
|
|
509 ndash = self.getNdash(newname)
|
|
510 if newtype == "text":
|
|
511 aparm = gxtp.TextParam(
|
|
512 newname,
|
|
513 label=newlabel,
|
|
514 help=newhelp,
|
|
515 value=newval,
|
|
516 num_dashes=ndash,
|
|
517 )
|
|
518 elif newtype == "integer":
|
|
519 aparm = gxtp.IntegerParam(
|
|
520 newname,
|
|
521 label=newname,
|
|
522 help=newhelp,
|
|
523 value=newval,
|
|
524 num_dashes=ndash,
|
|
525 )
|
|
526 elif newtype == "float":
|
|
527 aparm = gxtp.FloatParam(
|
|
528 newname,
|
|
529 label=newname,
|
|
530 help=newhelp,
|
|
531 value=newval,
|
|
532 num_dashes=ndash,
|
|
533 )
|
126
|
534 elif newtype == "boolean":
|
|
535 aparm = gxtp.BooleanParam(
|
|
536 newname,
|
|
537 label=newname,
|
|
538 help=newhelp,
|
|
539 value=newval,
|
|
540 num_dashes=ndash,
|
|
541 )
|
121
|
542 else:
|
|
543 raise ValueError(
|
|
544 'Unrecognised parameter type "%s" for\
|
|
545 additional parameter %s in makeXML'
|
|
546 % (newtype, newname)
|
|
547 )
|
|
548 aparm.positional = self.is_positional
|
|
549 if self.is_positional:
|
|
550 aparm.positional = int(oldcl)
|
|
551 self.tinputs.append(aparm)
|
|
552 tparm = gxtp.TestParam(newname, value=newval)
|
|
553 self.testparam.append(tparm)
|
126
|
554 for p in self.selpar:
|
|
555 newname = p["name"]
|
|
556 newval = p["value"]
|
|
557 newlabel = p["label"]
|
|
558 newhelp = p["help"]
|
|
559 newtype = p["type"]
|
|
560 newcl = p["CL"]
|
|
561 if not len(newlabel) > 0:
|
|
562 newlabel = newname
|
|
563 ndash = self.getNdash(newname)
|
|
564 if newtype == "selecttext":
|
|
565 newtext = p["texts"]
|
|
566 aparm = gxtp.SelectParam(
|
|
567 newname,
|
|
568 label=newlabel,
|
|
569 help=newhelp,
|
|
570 num_dashes=ndash,
|
|
571 )
|
|
572 for i in range(len(newval)):
|
|
573 anopt = gxtp.SelectOption(
|
|
574 value=newval[i],
|
|
575 text=newtext[i],
|
|
576 )
|
|
577 aparm.append(anopt)
|
|
578 aparm.positional = self.is_positional
|
|
579 if self.is_positional:
|
|
580 aparm.positional = int(newcl)
|
|
581 self.tinputs.append(aparm)
|
|
582 tparm = gxtp.TestParam(newname, value=newval)
|
|
583 self.testparam.append(tparm)
|
|
584 else:
|
|
585 raise ValueError(
|
|
586 'Unrecognised parameter type "%s" for\
|
|
587 selecttext parameter %s in makeXML'
|
|
588 % (newtype, newname)
|
|
589 )
|
|
590 for p in self.collections:
|
|
591 newkind = p["kind"]
|
|
592 newname = p["name"]
|
|
593 newlabel = p["label"]
|
|
594 newdisc = p["discover"]
|
|
595 collect = gxtp.OutputCollection(newname, label=newlabel, type=newkind)
|
|
596 disc = gxtp.DiscoverDatasets(
|
|
597 pattern=newdisc, directory=f"{newname}", visible="false"
|
|
598 )
|
|
599 collect.append(disc)
|
|
600 self.toutputs.append(collect)
|
|
601 tparm = gxtp.TestOutput(newname, ftype="pdf")
|
|
602 self.testparam.append(tparm)
|
121
|
603
|
|
604 def doNoXMLparam(self):
|
|
605 """filter style package - stdin to stdout"""
|
|
606 if len(self.infiles) > 0:
|
126
|
607 alab = self.infiles[0]["label"]
|
121
|
608 if len(alab) == 0:
|
126
|
609 alab = self.infiles[0]["infilename"]
|
121
|
610 max1s = (
|
|
611 "Maximum one input if parampass is 0 but multiple input files supplied - %s"
|
|
612 % str(self.infiles)
|
|
613 )
|
|
614 assert len(self.infiles) == 1, max1s
|
126
|
615 newname = self.infiles[0]["infilename"]
|
121
|
616 aninput = gxtp.DataParam(
|
|
617 newname,
|
|
618 optional=False,
|
|
619 label=alab,
|
126
|
620 help=self.infiles[0]["help"],
|
|
621 format=self.infiles[0]["format"],
|
121
|
622 multiple=False,
|
|
623 num_dashes=0,
|
|
624 )
|
|
625 aninput.command_line_override = "< $%s" % newname
|
126
|
626 aninput.positional = True
|
121
|
627 self.tinputs.append(aninput)
|
|
628 tp = gxtp.TestParam(name=newname, value="%s_sample" % newname)
|
|
629 self.testparam.append(tp)
|
|
630 if len(self.outfiles) > 0:
|
126
|
631 newname = self.outfiles[0]["name"]
|
|
632 newfmt = self.outfiles[0]["format"]
|
121
|
633 anout = gxtp.OutputData(newname, format=newfmt, num_dashes=0)
|
|
634 anout.command_line_override = "> $%s" % newname
|
|
635 anout.positional = self.is_positional
|
|
636 self.toutputs.append(anout)
|
126
|
637 tp = gxtp.TestOutput(name=newname, value="%s_sample" % newname)
|
121
|
638 self.testparam.append(tp)
|
|
639
|
|
640 def makeXML(self):
|
|
641 """
|
|
642 Create a Galaxy xml tool wrapper for the new script
|
|
643 Uses galaxyhtml
|
|
644 Hmmm. How to get the command line into correct order...
|
|
645 """
|
|
646 if self.command_override:
|
|
647 self.newtool.command_override = self.command_override # config file
|
|
648 else:
|
|
649 self.newtool.command_override = self.xmlcl
|
|
650 cite = gxtp.Citations()
|
|
651 acite = gxtp.Citation(type="doi", value="10.1093/bioinformatics/bts573")
|
|
652 cite.append(acite)
|
|
653 self.newtool.citations = cite
|
|
654 safertext = ""
|
|
655 if self.args.help_text:
|
|
656 helptext = open(self.args.help_text, "r").readlines()
|
|
657 safertext = "\n".join([cheetah_escape(x) for x in helptext])
|
|
658 if len(safertext.strip()) == 0:
|
|
659 safertext = (
|
|
660 "Ask the tool author (%s) to rebuild with help text please\n"
|
|
661 % (self.args.user_email)
|
|
662 )
|
|
663 if self.args.script_path:
|
|
664 if len(safertext) > 0:
|
|
665 safertext = safertext + "\n\n------\n" # transition allowed!
|
|
666 scr = [x for x in self.spacedScript if x.strip() > ""]
|
|
667 scr.insert(0, "\n\nScript::\n")
|
|
668 if len(scr) > 300:
|
|
669 scr = (
|
122
|
670 scr[:100]
|
|
671 + [" >300 lines - stuff deleted", " ......"]
|
121
|
672 + scr[-100:]
|
|
673 )
|
|
674 scr.append("\n")
|
|
675 safertext = safertext + "\n".join(scr)
|
|
676 self.newtool.help = safertext
|
|
677 self.newtool.version_command = f'echo "{self.args.tool_version}"'
|
|
678 requirements = gxtp.Requirements()
|
|
679 if self.args.packages:
|
|
680 for d in self.args.packages.split(","):
|
|
681 ver = ""
|
|
682 d = d.replace("==", ":")
|
|
683 d = d.replace("=", ":")
|
|
684 if ":" in d:
|
|
685 packg, ver = d.split(":")
|
|
686 else:
|
|
687 packg = d
|
|
688 requirements.append(
|
|
689 gxtp.Requirement("package", packg.strip(), ver.strip())
|
|
690 )
|
|
691 self.newtool.requirements = requirements
|
|
692 if self.args.parampass == "0":
|
|
693 self.doNoXMLparam()
|
|
694 else:
|
|
695 self.doXMLparam()
|
|
696 self.newtool.outputs = self.toutputs
|
|
697 self.newtool.inputs = self.tinputs
|
|
698 if self.args.script_path:
|
|
699 configfiles = gxtp.Configfiles()
|
|
700 configfiles.append(
|
|
701 gxtp.Configfile(name="runme", text="\n".join(self.escapedScript))
|
|
702 )
|
|
703 self.newtool.configfiles = configfiles
|
|
704 tests = gxtp.Tests()
|
|
705 test_a = gxtp.Test()
|
|
706 for tp in self.testparam:
|
|
707 test_a.append(tp)
|
|
708 tests.append(test_a)
|
|
709 self.newtool.tests = tests
|
|
710 self.newtool.add_comment(
|
|
711 "Created by %s at %s using the Galaxy Tool Factory."
|
|
712 % (self.args.user_email, timenow())
|
|
713 )
|
|
714 self.newtool.add_comment("Source in git at: %s" % (toolFactoryURL))
|
|
715 exml0 = self.newtool.export()
|
|
716 exml = exml0.replace(FAKEEXE, "") # temporary work around until PR accepted
|
|
717 if (
|
|
718 self.test_override
|
|
719 ): # cannot do this inside galaxyxml as it expects lxml objects for tests
|
|
720 part1 = exml.split("<tests>")[0]
|
|
721 part2 = exml.split("</tests>")[1]
|
126
|
722 fixed = "%s\n%s\n%s" % (part1, "\n".join(self.test_override), part2)
|
121
|
723 exml = fixed
|
|
724 # exml = exml.replace('range="1:"', 'range="1000:"')
|
|
725 xf = open("%s.xml" % self.tool_name, "w")
|
|
726 xf.write(exml)
|
|
727 xf.write("\n")
|
|
728 xf.close()
|
|
729 # ready for the tarball
|
|
730
|
|
731 def run(self):
|
|
732 """
|
|
733 generate test outputs by running a command line
|
|
734 won't work if command or test override in play - planemo is the
|
|
735 easiest way to generate test outputs for that case so is
|
|
736 automagically selected
|
|
737 """
|
|
738 scl = " ".join(self.cl)
|
|
739 err = None
|
|
740 if self.args.parampass != "0":
|
|
741 if os.path.exists(self.elog):
|
|
742 ste = open(self.elog, "a")
|
|
743 else:
|
|
744 ste = open(self.elog, "w")
|
|
745 if self.lastclredirect:
|
|
746 sto = open(self.lastclredirect[1], "wb") # is name of an output file
|
|
747 else:
|
|
748 if os.path.exists(self.tlog):
|
|
749 sto = open(self.tlog, "a")
|
|
750 else:
|
|
751 sto = open(self.tlog, "w")
|
|
752 sto.write(
|
|
753 "## Executing Toolfactory generated command line = %s\n" % scl
|
|
754 )
|
|
755 sto.flush()
|
|
756 subp = subprocess.run(
|
126
|
757 self.cl, shell=False, stdout=sto, stderr=ste
|
121
|
758 )
|
|
759 sto.close()
|
|
760 ste.close()
|
|
761 retval = subp.returncode
|
|
762 else: # work around special case - stdin and write to stdout
|
|
763 if len(self.infiles) > 0:
|
126
|
764 sti = open(self.infiles[0]["name"], "rb")
|
121
|
765 else:
|
|
766 sti = sys.stdin
|
|
767 if len(self.outfiles) > 0:
|
126
|
768 sto = open(self.outfiles[0]["name"], "wb")
|
121
|
769 else:
|
|
770 sto = sys.stdout
|
|
771 subp = subprocess.run(
|
126
|
772 self.cl, shell=False, stdout=sto, stdin=sti
|
121
|
773 )
|
|
774 sto.write("## Executing Toolfactory generated command line = %s\n" % scl)
|
|
775 retval = subp.returncode
|
|
776 sto.close()
|
|
777 sti.close()
|
|
778 if os.path.isfile(self.tlog) and os.stat(self.tlog).st_size == 0:
|
|
779 os.unlink(self.tlog)
|
|
780 if os.path.isfile(self.elog) and os.stat(self.elog).st_size == 0:
|
|
781 os.unlink(self.elog)
|
|
782 if retval != 0 and err: # problem
|
|
783 sys.stderr.write(err)
|
|
784 logging.debug("run done")
|
|
785 return retval
|
|
786
|
|
787 def shedLoad(self):
|
|
788 """
|
|
789 use bioblend to create new repository
|
|
790 or update existing
|
|
791
|
|
792 """
|
|
793 if os.path.exists(self.tlog):
|
|
794 sto = open(self.tlog, "a")
|
|
795 else:
|
|
796 sto = open(self.tlog, "w")
|
|
797
|
|
798 ts = toolshed.ToolShedInstance(
|
|
799 url=self.args.toolshed_url,
|
|
800 key=self.args.toolshed_api_key,
|
|
801 verify=False,
|
|
802 )
|
|
803 repos = ts.repositories.get_repositories()
|
|
804 rnames = [x.get("name", "?") for x in repos]
|
|
805 rids = [x.get("id", "?") for x in repos]
|
|
806 tfcat = "ToolFactory generated tools"
|
|
807 if self.tool_name not in rnames:
|
|
808 tscat = ts.categories.get_categories()
|
|
809 cnames = [x.get("name", "?").strip() for x in tscat]
|
|
810 cids = [x.get("id", "?") for x in tscat]
|
|
811 catID = None
|
|
812 if tfcat.strip() in cnames:
|
|
813 ci = cnames.index(tfcat)
|
|
814 catID = cids[ci]
|
|
815 res = ts.repositories.create_repository(
|
|
816 name=self.args.tool_name,
|
|
817 synopsis="Synopsis:%s" % self.args.tool_desc,
|
|
818 description=self.args.tool_desc,
|
|
819 type="unrestricted",
|
|
820 remote_repository_url=self.args.toolshed_url,
|
|
821 homepage_url=None,
|
|
822 category_ids=catID,
|
|
823 )
|
|
824 tid = res.get("id", None)
|
|
825 sto.write(f"#create_repository {self.args.tool_name} tid={tid} res={res}\n")
|
|
826 else:
|
|
827 i = rnames.index(self.tool_name)
|
|
828 tid = rids[i]
|
|
829 try:
|
|
830 res = ts.repositories.update_repository(
|
|
831 id=tid, tar_ball_path=self.newtarpath, commit_message=None
|
|
832 )
|
|
833 sto.write(f"#update res id {id} ={res}\n")
|
|
834 except ConnectionError:
|
|
835 sto.write(
|
|
836 "####### Is the toolshed running and the API key correct? Bioblend shed upload failed\n"
|
|
837 )
|
|
838 sto.close()
|
|
839
|
|
840 def eph_galaxy_load(self):
|
|
841 """
|
|
842 use ephemeris to load the new tool from the local toolshed after planemo uploads it
|
|
843 """
|
|
844 if os.path.exists(self.tlog):
|
|
845 tout = open(self.tlog, "a")
|
|
846 else:
|
|
847 tout = open(self.tlog, "w")
|
|
848 cll = [
|
|
849 "shed-tools",
|
|
850 "install",
|
|
851 "-g",
|
|
852 self.args.galaxy_url,
|
|
853 "--latest",
|
|
854 "-a",
|
|
855 self.args.galaxy_api_key,
|
|
856 "--name",
|
|
857 self.tool_name,
|
|
858 "--owner",
|
|
859 "fubar",
|
|
860 "--toolshed",
|
|
861 self.args.toolshed_url,
|
|
862 "--section_label",
|
|
863 "ToolFactory",
|
|
864 ]
|
|
865 tout.write("running\n%s\n" % " ".join(cll))
|
|
866 subp = subprocess.run(
|
|
867 cll,
|
|
868 cwd=self.ourcwd,
|
|
869 shell=False,
|
|
870 stderr=tout,
|
|
871 stdout=tout,
|
|
872 )
|
|
873 tout.write(
|
|
874 "installed %s - got retcode %d\n" % (self.tool_name, subp.returncode)
|
|
875 )
|
|
876 tout.close()
|
|
877 return subp.returncode
|
|
878
|
|
879 def writeShedyml(self):
|
|
880 """for planemo"""
|
|
881 yuser = self.args.user_email.split("@")[0]
|
|
882 yfname = os.path.join(self.tooloutdir, ".shed.yml")
|
|
883 yamlf = open(yfname, "w")
|
|
884 odict = {
|
|
885 "name": self.tool_name,
|
|
886 "owner": yuser,
|
|
887 "type": "unrestricted",
|
|
888 "description": self.args.tool_desc,
|
|
889 "synopsis": self.args.tool_desc,
|
|
890 "category": "TF Generated Tools",
|
|
891 }
|
|
892 yaml.dump(odict, yamlf, allow_unicode=True)
|
|
893 yamlf.close()
|
|
894
|
|
895 def makeTool(self):
|
|
896 """write xmls and input samples into place"""
|
126
|
897 if self.args.parampass == 0:
|
|
898 self.doNoXMLparam()
|
|
899 else:
|
|
900 self.makeXML()
|
121
|
901 if self.args.script_path:
|
126
|
902 stname = os.path.join(self.tooloutdir, self.sfile)
|
121
|
903 if not os.path.exists(stname):
|
|
904 shutil.copyfile(self.sfile, stname)
|
|
905 xreal = "%s.xml" % self.tool_name
|
|
906 xout = os.path.join(self.tooloutdir, xreal)
|
|
907 shutil.copyfile(xreal, xout)
|
|
908 for p in self.infiles:
|
126
|
909 pth = p["name"]
|
|
910 dest = os.path.join(self.testdir, "%s_sample" % p["infilename"])
|
|
911 shutil.copyfile(pth, dest)
|
|
912 dest = os.path.join(self.repdir, "%s_sample" % p["infilename"])
|
121
|
913 shutil.copyfile(pth, dest)
|
|
914
|
126
|
915 def makeToolTar(self, report_fail=False):
|
121
|
916 """move outputs into test-data and prepare the tarball"""
|
|
917 excludeme = "_planemo_test_report.html"
|
|
918
|
|
919 def exclude_function(tarinfo):
|
|
920 filename = tarinfo.name
|
|
921 return None if filename.endswith(excludeme) else tarinfo
|
|
922
|
|
923 if os.path.exists(self.tlog):
|
|
924 tout = open(self.tlog, "a")
|
|
925 else:
|
|
926 tout = open(self.tlog, "w")
|
|
927 for p in self.outfiles:
|
126
|
928 oname = p["name"]
|
121
|
929 tdest = os.path.join(self.testdir, "%s_sample" % oname)
|
126
|
930 src = os.path.join(self.testdir, oname)
|
121
|
931 if not os.path.isfile(tdest):
|
|
932 if os.path.isfile(src):
|
|
933 shutil.copyfile(src, tdest)
|
|
934 dest = os.path.join(self.repdir, "%s.sample" % (oname))
|
|
935 shutil.copyfile(src, dest)
|
|
936 else:
|
126
|
937 if report_fail:
|
|
938 tout.write(
|
|
939 "###Tool may have failed - output file %s not found in testdir after planemo run %s."
|
|
940 % (tdest, self.testdir)
|
|
941 )
|
121
|
942 tf = tarfile.open(self.newtarpath, "w:gz")
|
|
943 tf.add(
|
|
944 name=self.tooloutdir,
|
|
945 arcname=self.tool_name,
|
|
946 filter=exclude_function,
|
|
947 )
|
|
948 tf.close()
|
|
949 shutil.copyfile(self.newtarpath, self.args.new_tool)
|
|
950
|
|
951 def moveRunOutputs(self):
|
|
952 """need to move planemo or run outputs into toolfactory collection"""
|
|
953 with os.scandir(self.tooloutdir) as outs:
|
|
954 for entry in outs:
|
|
955 if not entry.is_file():
|
|
956 continue
|
|
957 if "." in entry.name:
|
126
|
958 _, ext = os.path.splitext(entry.name)
|
|
959 if ext in [".tgz", ".json"]:
|
|
960 continue
|
|
961 if ext in [".yml", ".xml", ".yaml"]:
|
|
962 newname = f"{entry.name.replace('.','_')}.txt"
|
|
963 else:
|
|
964 newname = entry.name
|
121
|
965 else:
|
126
|
966 newname = f"{entry.name}.txt"
|
|
967 dest = os.path.join(self.repdir, newname)
|
121
|
968 src = os.path.join(self.tooloutdir, entry.name)
|
|
969 shutil.copyfile(src, dest)
|
126
|
970 if self.args.include_tests:
|
|
971 with os.scandir(self.testdir) as outs:
|
|
972 for entry in outs:
|
|
973 if (not entry.is_file()) or entry.name.endswith(
|
|
974 "_planemo_test_report.html"
|
|
975 ):
|
|
976 continue
|
|
977 if "." in entry.name:
|
|
978 _, ext = os.path.splitext(entry.name)
|
|
979 if ext in [".tgz", ".json"]:
|
|
980 continue
|
|
981 if ext in [".yml", ".xml", ".yaml"]:
|
|
982 newname = f"{entry.name.replace('.','_')}.txt"
|
|
983 else:
|
|
984 newname = entry.name
|
|
985 else:
|
|
986 newname = f"{entry.name}.txt"
|
|
987 dest = os.path.join(self.repdir, newname)
|
|
988 src = os.path.join(self.testdir, entry.name)
|
|
989 shutil.copyfile(src, dest)
|
121
|
990
|
126
|
991 def planemo_test_once(self):
|
121
|
992 """planemo is a requirement so is available for testing but needs a
|
|
993 different call if in the biocontainer - see above
|
|
994 and for generating test outputs if command or test overrides are
|
|
995 supplied test outputs are sent to repdir for display
|
|
996 """
|
|
997 xreal = "%s.xml" % self.tool_name
|
|
998 tool_test_path = os.path.join(
|
|
999 self.repdir, f"{self.tool_name}_planemo_test_report.html"
|
|
1000 )
|
|
1001 if os.path.exists(self.tlog):
|
|
1002 tout = open(self.tlog, "a")
|
|
1003 else:
|
|
1004 tout = open(self.tlog, "w")
|
126
|
1005 cll = [
|
|
1006 "planemo",
|
|
1007 "test",
|
|
1008 "--conda_auto_init",
|
|
1009 "--test_data",
|
|
1010 os.path.abspath(self.testdir),
|
|
1011 "--test_output",
|
|
1012 os.path.abspath(tool_test_path),
|
|
1013 "--galaxy_root",
|
|
1014 self.args.galaxy_root,
|
|
1015 "--update_test_data",
|
|
1016 os.path.abspath(xreal),
|
|
1017 ]
|
|
1018 p = subprocess.run(
|
|
1019 cll,
|
|
1020 shell=False,
|
|
1021 cwd=self.tooloutdir,
|
|
1022 stderr=tout,
|
|
1023 stdout=tout,
|
|
1024 )
|
121
|
1025 tout.close()
|
|
1026 return p.returncode
|
|
1027
|
|
1028
|
|
1029 def main():
|
|
1030 """
|
|
1031 This is a Galaxy wrapper.
|
|
1032 It expects to be called by a special purpose tool.xml
|
|
1033
|
|
1034 """
|
|
1035 parser = argparse.ArgumentParser()
|
|
1036 a = parser.add_argument
|
|
1037 a("--script_path", default=None)
|
|
1038 a("--history_test", default=None)
|
|
1039 a("--cl_prefix", default=None)
|
|
1040 a("--sysexe", default=None)
|
|
1041 a("--packages", default=None)
|
|
1042 a("--tool_name", default="newtool")
|
|
1043 a("--tool_dir", default=None)
|
|
1044 a("--input_files", default=[], action="append")
|
|
1045 a("--output_files", default=[], action="append")
|
|
1046 a("--user_email", default="Unknown")
|
|
1047 a("--bad_user", default=None)
|
|
1048 a("--make_Tool", default="runonly")
|
|
1049 a("--help_text", default=None)
|
|
1050 a("--tool_desc", default=None)
|
|
1051 a("--tool_version", default=None)
|
|
1052 a("--citations", default=None)
|
|
1053 a("--command_override", default=None)
|
|
1054 a("--test_override", default=None)
|
|
1055 a("--additional_parameters", action="append", default=[])
|
126
|
1056 a("--selecttext_parameters", action="append", default=[])
|
121
|
1057 a("--edit_additional_parameters", action="store_true", default=False)
|
|
1058 a("--parampass", default="positional")
|
|
1059 a("--tfout", default="./tfout")
|
|
1060 a("--new_tool", default="new_tool")
|
|
1061 a("--galaxy_url", default="http://localhost:8080")
|
|
1062 a("--toolshed_url", default="http://localhost:9009")
|
|
1063 # make sure this is identical to tool_sheds_conf.xml
|
|
1064 # localhost != 127.0.0.1 so validation fails
|
|
1065 a("--toolshed_api_key", default="fakekey")
|
|
1066 a("--galaxy_api_key", default="fakekey")
|
|
1067 a("--galaxy_root", default="/galaxy-central")
|
|
1068 a("--galaxy_venv", default="/galaxy_venv")
|
126
|
1069 a("--collection", action="append", default=[])
|
|
1070 a("--include_tests", default=False, action="store_true")
|
121
|
1071 args = parser.parse_args()
|
|
1072 assert not args.bad_user, (
|
|
1073 'UNAUTHORISED: %s is NOT authorized to use this tool until Galaxy \
|
|
1074 admin adds %s to "admin_users" in the galaxy.yml Galaxy configuration file'
|
|
1075 % (args.bad_user, args.bad_user)
|
|
1076 )
|
|
1077 assert args.tool_name, "## Tool Factory expects a tool name - eg --tool_name=DESeq"
|
|
1078 assert (
|
|
1079 args.sysexe or args.packages
|
|
1080 ), "## Tool Factory wrapper expects an interpreter \
|
|
1081 or an executable package in --sysexe or --packages"
|
|
1082 r = ScriptRunner(args)
|
|
1083 r.writeShedyml()
|
|
1084 r.makeTool()
|
|
1085 if args.make_Tool == "generate":
|
126
|
1086 r.run()
|
121
|
1087 r.moveRunOutputs()
|
|
1088 r.makeToolTar()
|
|
1089 else:
|
126
|
1090 # r.planemo_test(genoutputs=True) # this fails :( - see PR
|
|
1091 # r.moveRunOutputs()
|
|
1092 # r.makeToolTar(report_fail=False)
|
|
1093 r.planemo_test_once()
|
121
|
1094 r.moveRunOutputs()
|
126
|
1095 r.makeToolTar(report_fail=True)
|
121
|
1096 if args.make_Tool == "gentestinstall":
|
|
1097 r.shedLoad()
|
|
1098 r.eph_galaxy_load()
|
|
1099
|
|
1100
|
|
1101 if __name__ == "__main__":
|
|
1102 main()
|