84
|
1 # replace with shebang for biocontainer
|
48
|
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
|
49
|
8 # suggestions for improvement and bug fixes welcome at
|
|
9 # https://github.com/fubar2/toolfactory
|
48
|
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 # removed all the old complications including making the new tool use this same script
|
|
18 # galaxyxml now generates the tool xml https://github.com/hexylena/galaxyxml
|
|
19 # No support for automatic HTML file creation from arbitrary outputs
|
|
20 # essential problem is to create two command lines - one for the tool xml and a different
|
|
21 # one to run the executable with the supplied test data and settings
|
|
22 # Be simpler to write the tool, then run it with planemo and soak up the test outputs.
|
95
|
23 # well well. sh run_tests.sh --id rgtf2 --report_file tool_tests_tool_conf.html functional.test_toolbox
|
|
24 # does the needful. Use GALAXY_TEST_SAVE /foo to save outputs - only the tar.gz - not the rest sadly
|
|
25 # GALAXY_TEST_NO_CLEANUP GALAXY_TEST_TMP_DIR=wherever
|
99
|
26 # planemo test --engine docker_galaxy --test_data ./test-data/ --docker_extra_volume ./test-data rgToolFactory2.xml
|
48
|
27
|
|
28 import argparse
|
101
|
29 import copy
|
76
|
30 import datetime
|
103
|
31 import grp
|
76
|
32 import json
|
48
|
33 import logging
|
|
34 import os
|
|
35 import re
|
|
36 import shutil
|
|
37 import subprocess
|
|
38 import sys
|
|
39 import tarfile
|
|
40 import tempfile
|
|
41 import time
|
|
42
|
75
|
43
|
100
|
44 from bioblend import ConnectionError
|
63
|
45 from bioblend import toolshed
|
|
46
|
101
|
47 import docker
|
98
|
48
|
48
|
49 import galaxyxml.tool as gxt
|
|
50 import galaxyxml.tool.parameters as gxtp
|
|
51
|
|
52 import lxml
|
|
53
|
|
54 import yaml
|
|
55
|
|
56 myversion = "V2.1 July 2020"
|
|
57 verbose = True
|
|
58 debug = True
|
|
59 toolFactoryURL = "https://github.com/fubar2/toolfactory"
|
|
60 ourdelim = "~~~"
|
50
|
61 ALOT = 10000000 # srsly. command or test overrides use read() so just in case
|
49
|
62 STDIOXML = """<stdio>
|
|
63 <exit_code range="100:" level="debug" description="shite happens" />
|
|
64 </stdio>"""
|
48
|
65
|
|
66 # --input_files="$input_files~~~$CL~~~$input_formats~~~$input_label
|
|
67 # ~~~$input_help"
|
|
68 IPATHPOS = 0
|
|
69 ICLPOS = 1
|
|
70 IFMTPOS = 2
|
|
71 ILABPOS = 3
|
|
72 IHELPOS = 4
|
|
73 IOCLPOS = 5
|
|
74
|
49
|
75 # --output_files "$otab.history_name~~~$otab.history_format~~~$otab.CL~~~otab.history_test
|
48
|
76 ONAMEPOS = 0
|
|
77 OFMTPOS = 1
|
|
78 OCLPOS = 2
|
49
|
79 OTESTPOS = 3
|
|
80 OOCLPOS = 4
|
|
81
|
48
|
82
|
|
83 # --additional_parameters="$i.param_name~~~$i.param_value~~~
|
|
84 # $i.param_label~~~$i.param_help~~~$i.param_type~~~$i.CL~~~i$.param_CLoverride"
|
|
85 ANAMEPOS = 0
|
|
86 AVALPOS = 1
|
|
87 ALABPOS = 2
|
|
88 AHELPPOS = 3
|
|
89 ATYPEPOS = 4
|
|
90 ACLPOS = 5
|
|
91 AOVERPOS = 6
|
|
92 AOCLPOS = 7
|
|
93
|
|
94
|
|
95 foo = len(lxml.__version__)
|
|
96 # fug you, flake8. Say my name!
|
49
|
97 FAKEEXE = "~~~REMOVE~~~ME~~~"
|
|
98 # need this until a PR/version bump to fix galaxyxml prepending the exe even
|
|
99 # with override.
|
|
100
|
48
|
101
|
|
102 def timenow():
|
75
|
103 """return current time as a string"""
|
48
|
104 return time.strftime("%d/%m/%Y %H:%M:%S", time.localtime(time.time()))
|
|
105
|
|
106
|
|
107 def quote_non_numeric(s):
|
|
108 """return a prequoted string for non-numerics
|
|
109 useful for perl and Rscript parameter passing?
|
|
110 """
|
|
111 try:
|
|
112 _ = float(s)
|
|
113 return s
|
|
114 except ValueError:
|
|
115 return '"%s"' % s
|
|
116
|
|
117
|
|
118 html_escape_table = {"&": "&", ">": ">", "<": "<", "$": r"\$"}
|
|
119
|
|
120
|
|
121 def html_escape(text):
|
|
122 """Produce entities within text."""
|
|
123 return "".join(html_escape_table.get(c, c) for c in text)
|
|
124
|
|
125
|
|
126 def html_unescape(text):
|
|
127 """Revert entities within text. Multiple character targets so use replace"""
|
|
128 t = text.replace("&", "&")
|
|
129 t = t.replace(">", ">")
|
|
130 t = t.replace("<", "<")
|
|
131 t = t.replace("\\$", "$")
|
|
132 return t
|
|
133
|
|
134
|
|
135 def parse_citations(citations_text):
|
75
|
136 """"""
|
48
|
137 citations = [c for c in citations_text.split("**ENTRY**") if c.strip()]
|
|
138 citation_tuples = []
|
|
139 for citation in citations:
|
|
140 if citation.startswith("doi"):
|
|
141 citation_tuples.append(("doi", citation[len("doi") :].strip()))
|
|
142 else:
|
49
|
143 citation_tuples.append(("bibtex", citation[len("bibtex") :].strip()))
|
48
|
144 return citation_tuples
|
|
145
|
|
146
|
|
147 class ScriptRunner:
|
|
148 """Wrapper for an arbitrary script
|
|
149 uses galaxyxml
|
|
150
|
|
151 """
|
|
152
|
|
153 def __init__(self, args=None):
|
|
154 """
|
|
155 prepare command line cl for running the tool here
|
|
156 and prepare elements needed for galaxyxml tool generation
|
|
157 """
|
101
|
158 self.ourcwd = os.getcwd()
|
|
159 self.ourenv = copy.deepcopy(os.environ)
|
48
|
160 self.infiles = [x.split(ourdelim) for x in args.input_files]
|
|
161 self.outfiles = [x.split(ourdelim) for x in args.output_files]
|
|
162 self.addpar = [x.split(ourdelim) for x in args.additional_parameters]
|
|
163 self.args = args
|
|
164 self.cleanuppar()
|
|
165 self.lastclredirect = None
|
|
166 self.lastxclredirect = None
|
|
167 self.cl = []
|
|
168 self.xmlcl = []
|
|
169 self.is_positional = self.args.parampass == "positional"
|
63
|
170 if self.args.sysexe:
|
49
|
171 self.executeme = self.args.sysexe
|
63
|
172 else:
|
|
173 if self.args.packages:
|
|
174 self.executeme = self.args.packages.split(",")[0].split(":")[0]
|
|
175 else:
|
|
176 self.executeme = None
|
48
|
177 aCL = self.cl.append
|
49
|
178 aXCL = self.xmlcl.append
|
48
|
179 assert args.parampass in [
|
|
180 "0",
|
|
181 "argparse",
|
|
182 "positional",
|
49
|
183 ], 'args.parampass must be "0","positional" or "argparse"'
|
48
|
184 self.tool_name = re.sub("[^a-zA-Z0-9_]+", "", args.tool_name)
|
|
185 self.tool_id = self.tool_name
|
50
|
186 self.newtool = gxt.Tool(
|
101
|
187 self.tool_name,
|
48
|
188 self.tool_id,
|
|
189 self.args.tool_version,
|
|
190 self.args.tool_desc,
|
50
|
191 FAKEEXE,
|
48
|
192 )
|
76
|
193 self.newtarpath = "toolfactory_%s.tgz" % self.tool_name
|
98
|
194 self.tooloutdir = "./tfout"
|
|
195 self.repdir = "./TF_run_report_tempdir"
|
48
|
196 self.testdir = os.path.join(self.tooloutdir, "test-data")
|
|
197 if not os.path.exists(self.tooloutdir):
|
|
198 os.mkdir(self.tooloutdir)
|
|
199 if not os.path.exists(self.testdir):
|
|
200 os.mkdir(self.testdir) # make tests directory
|
|
201 if not os.path.exists(self.repdir):
|
|
202 os.mkdir(self.repdir)
|
|
203 self.tinputs = gxtp.Inputs()
|
|
204 self.toutputs = gxtp.Outputs()
|
|
205 self.testparam = []
|
49
|
206 if self.args.script_path:
|
|
207 self.prepScript()
|
|
208 if self.args.command_override:
|
|
209 scos = open(self.args.command_override, "r").readlines()
|
|
210 self.command_override = [x.rstrip() for x in scos]
|
|
211 else:
|
|
212 self.command_override = None
|
|
213 if self.args.test_override:
|
|
214 stos = open(self.args.test_override, "r").readlines()
|
|
215 self.test_override = [x.rstrip() for x in stos]
|
|
216 else:
|
|
217 self.test_override = None
|
50
|
218 if self.args.cl_prefix: # DIY CL start
|
49
|
219 clp = self.args.cl_prefix.split(" ")
|
|
220 for c in clp:
|
|
221 aCL(c)
|
|
222 aXCL(c)
|
|
223 else:
|
56
|
224 if self.args.script_path:
|
|
225 aCL(self.executeme)
|
|
226 aCL(self.sfile)
|
|
227 aXCL(self.executeme)
|
|
228 aXCL("$runme")
|
48
|
229 else:
|
56
|
230 aCL(self.executeme) # this little CL will just run
|
|
231 aXCL(self.executeme)
|
50
|
232 self.elog = os.path.join(self.repdir, "%s_error_log.txt" % self.tool_name)
|
|
233 self.tlog = os.path.join(self.repdir, "%s_runner_log.txt" % self.tool_name)
|
48
|
234
|
|
235 if self.args.parampass == "0":
|
|
236 self.clsimple()
|
|
237 else:
|
|
238 clsuffix = []
|
|
239 xclsuffix = []
|
|
240 for i, p in enumerate(self.infiles):
|
|
241 if p[IOCLPOS] == "STDIN":
|
|
242 appendme = [
|
|
243 p[IOCLPOS],
|
|
244 p[ICLPOS],
|
|
245 p[IPATHPOS],
|
|
246 "< %s" % p[IPATHPOS],
|
|
247 ]
|
|
248 xappendme = [
|
|
249 p[IOCLPOS],
|
|
250 p[ICLPOS],
|
|
251 p[IPATHPOS],
|
|
252 "< $%s" % p[ICLPOS],
|
|
253 ]
|
|
254 else:
|
|
255 appendme = [p[IOCLPOS], p[ICLPOS], p[IPATHPOS], ""]
|
|
256 xappendme = [p[IOCLPOS], p[ICLPOS], "$%s" % p[ICLPOS], ""]
|
|
257 clsuffix.append(appendme)
|
|
258 xclsuffix.append(xappendme)
|
|
259 for i, p in enumerate(self.outfiles):
|
|
260 if p[OOCLPOS] == "STDOUT":
|
|
261 self.lastclredirect = [">", p[ONAMEPOS]]
|
|
262 self.lastxclredirect = [">", "$%s" % p[OCLPOS]]
|
|
263 else:
|
|
264 clsuffix.append([p[OOCLPOS], p[OCLPOS], p[ONAMEPOS], ""])
|
49
|
265 xclsuffix.append([p[OOCLPOS], p[OCLPOS], "$%s" % p[ONAMEPOS], ""])
|
48
|
266 for p in self.addpar:
|
49
|
267 clsuffix.append([p[AOCLPOS], p[ACLPOS], p[AVALPOS], p[AOVERPOS]])
|
48
|
268 xclsuffix.append(
|
|
269 [p[AOCLPOS], p[ACLPOS], '"$%s"' % p[ANAMEPOS], p[AOVERPOS]]
|
|
270 )
|
|
271 clsuffix.sort()
|
|
272 xclsuffix.sort()
|
|
273 self.xclsuffix = xclsuffix
|
|
274 self.clsuffix = clsuffix
|
|
275 if self.args.parampass == "positional":
|
|
276 self.clpositional()
|
|
277 else:
|
|
278 self.clargparse()
|
|
279
|
|
280 def prepScript(self):
|
|
281 rx = open(self.args.script_path, "r").readlines()
|
|
282 rx = [x.rstrip() for x in rx]
|
|
283 rxcheck = [x.strip() for x in rx if x.strip() > ""]
|
|
284 assert len(rxcheck) > 0, "Supplied script is empty. Cannot run"
|
|
285 self.script = "\n".join(rx)
|
|
286 fhandle, self.sfile = tempfile.mkstemp(
|
49
|
287 prefix=self.tool_name, suffix="_%s" % (self.executeme)
|
48
|
288 )
|
|
289 tscript = open(self.sfile, "w")
|
|
290 tscript.write(self.script)
|
|
291 tscript.close()
|
49
|
292 self.indentedScript = " %s" % "\n".join([" %s" % html_escape(x) for x in rx])
|
|
293 self.escapedScript = "%s" % "\n".join([" %s" % html_escape(x) for x in rx])
|
|
294 art = "%s.%s" % (self.tool_name, self.executeme)
|
48
|
295 artifact = open(art, "wb")
|
|
296 artifact.write(bytes(self.script, "utf8"))
|
|
297 artifact.close()
|
|
298
|
|
299 def cleanuppar(self):
|
|
300 """ positional parameters are complicated by their numeric ordinal"""
|
|
301 for i, p in enumerate(self.infiles):
|
|
302 if self.args.parampass == "positional":
|
75
|
303 assert p[
|
|
304 ICLPOS
|
|
305 ].isdigit(), "Positional parameters must be ordinal integers - got %s for %s" % (
|
|
306 p[ICLPOS],
|
|
307 p[ILABPOS],
|
48
|
308 )
|
|
309 p.append(p[ICLPOS])
|
|
310 if p[ICLPOS].isdigit() or self.args.parampass == "0":
|
|
311 scl = "input%d" % (i + 1)
|
|
312 p[ICLPOS] = scl
|
|
313 self.infiles[i] = p
|
|
314 for i, p in enumerate(
|
|
315 self.outfiles
|
|
316 ): # trying to automagically gather using extensions
|
|
317 if self.args.parampass == "positional" and p[OCLPOS] != "STDOUT":
|
75
|
318 assert p[
|
|
319 OCLPOS
|
|
320 ].isdigit(), "Positional parameters must be ordinal integers - got %s for %s" % (
|
|
321 p[OCLPOS],
|
|
322 p[ONAMEPOS],
|
48
|
323 )
|
|
324 p.append(p[OCLPOS])
|
|
325 if p[OCLPOS].isdigit() or p[OCLPOS] == "STDOUT":
|
|
326 scl = p[ONAMEPOS]
|
|
327 p[OCLPOS] = scl
|
|
328 self.outfiles[i] = p
|
|
329 for i, p in enumerate(self.addpar):
|
|
330 if self.args.parampass == "positional":
|
75
|
331 assert p[
|
|
332 ACLPOS
|
|
333 ].isdigit(), "Positional parameters must be ordinal integers - got %s for %s" % (
|
|
334 p[ACLPOS],
|
|
335 p[ANAMEPOS],
|
48
|
336 )
|
|
337 p.append(p[ACLPOS])
|
|
338 if p[ACLPOS].isdigit():
|
|
339 scl = "input%s" % p[ACLPOS]
|
|
340 p[ACLPOS] = scl
|
|
341 self.addpar[i] = p
|
|
342
|
|
343 def clsimple(self):
|
75
|
344 """no parameters - uses < and > for i/o"""
|
48
|
345 aCL = self.cl.append
|
|
346 aXCL = self.xmlcl.append
|
62
|
347
|
|
348 if len(self.infiles) > 0:
|
|
349 aCL("<")
|
|
350 aCL(self.infiles[0][IPATHPOS])
|
|
351 aXCL("<")
|
|
352 aXCL("$%s" % self.infiles[0][ICLPOS])
|
|
353 if len(self.outfiles) > 0:
|
|
354 aCL(">")
|
|
355 aCL(self.outfiles[0][OCLPOS])
|
|
356 aXCL(">")
|
|
357 aXCL("$%s" % self.outfiles[0][ONAMEPOS])
|
48
|
358
|
|
359 def clpositional(self):
|
|
360 # inputs in order then params
|
|
361 aCL = self.cl.append
|
|
362 for (o_v, k, v, koverride) in self.clsuffix:
|
|
363 if " " in v:
|
|
364 aCL("%s" % v)
|
|
365 else:
|
|
366 aCL(v)
|
|
367 aXCL = self.xmlcl.append
|
|
368 for (o_v, k, v, koverride) in self.xclsuffix:
|
|
369 aXCL(v)
|
|
370 if self.lastxclredirect:
|
|
371 aXCL(self.lastxclredirect[0])
|
|
372 aXCL(self.lastxclredirect[1])
|
|
373
|
|
374 def clargparse(self):
|
75
|
375 """argparse style"""
|
48
|
376 aCL = self.cl.append
|
|
377 aXCL = self.xmlcl.append
|
|
378 # inputs then params in argparse named form
|
|
379 for (o_v, k, v, koverride) in self.xclsuffix:
|
|
380 if koverride > "":
|
|
381 k = koverride
|
|
382 elif len(k.strip()) == 1:
|
|
383 k = "-%s" % k
|
|
384 else:
|
|
385 k = "--%s" % k
|
|
386 aXCL(k)
|
|
387 aXCL(v)
|
|
388 for (o_v, k, v, koverride) in self.clsuffix:
|
|
389 if koverride > "":
|
|
390 k = koverride
|
|
391 elif len(k.strip()) == 1:
|
|
392 k = "-%s" % k
|
|
393 else:
|
|
394 k = "--%s" % k
|
|
395 aCL(k)
|
|
396 aCL(v)
|
|
397
|
|
398 def getNdash(self, newname):
|
|
399 if self.is_positional:
|
|
400 ndash = 0
|
|
401 else:
|
|
402 ndash = 2
|
|
403 if len(newname) < 2:
|
|
404 ndash = 1
|
|
405 return ndash
|
|
406
|
|
407 def doXMLparam(self):
|
|
408 """flake8 made me do this..."""
|
|
409 for p in self.outfiles:
|
49
|
410 newname, newfmt, newcl, test, oldcl = p
|
48
|
411 ndash = self.getNdash(newcl)
|
|
412 aparm = gxtp.OutputData(newcl, format=newfmt, num_dashes=ndash)
|
|
413 aparm.positional = self.is_positional
|
|
414 if self.is_positional:
|
|
415 if oldcl == "STDOUT":
|
|
416 aparm.positional = 9999999
|
|
417 aparm.command_line_override = "> $%s" % newcl
|
|
418 else:
|
|
419 aparm.positional = int(oldcl)
|
|
420 aparm.command_line_override = "$%s" % newcl
|
|
421 self.toutputs.append(aparm)
|
49
|
422 usetest = None
|
|
423 ld = None
|
50
|
424 if test > "":
|
|
425 if test.startswith("diff"):
|
|
426 usetest = "diff"
|
|
427 if test.split(":")[1].isdigit:
|
|
428 ld = int(test.split(":")[1])
|
49
|
429 else:
|
|
430 usetest = test
|
50
|
431 tp = gxtp.TestOutput(
|
|
432 name=newcl,
|
|
433 value="%s_sample" % newcl,
|
|
434 format=newfmt,
|
|
435 compare=usetest,
|
|
436 lines_diff=ld,
|
|
437 delta=None,
|
|
438 )
|
48
|
439 self.testparam.append(tp)
|
|
440 for p in self.infiles:
|
|
441 newname = p[ICLPOS]
|
|
442 newfmt = p[IFMTPOS]
|
|
443 ndash = self.getNdash(newname)
|
|
444 if not len(p[ILABPOS]) > 0:
|
|
445 alab = p[ICLPOS]
|
|
446 else:
|
|
447 alab = p[ILABPOS]
|
|
448 aninput = gxtp.DataParam(
|
|
449 newname,
|
|
450 optional=False,
|
|
451 label=alab,
|
|
452 help=p[IHELPOS],
|
|
453 format=newfmt,
|
|
454 multiple=False,
|
|
455 num_dashes=ndash,
|
|
456 )
|
|
457 aninput.positional = self.is_positional
|
|
458 self.tinputs.append(aninput)
|
|
459 tparm = gxtp.TestParam(name=newname, value="%s_sample" % newname)
|
|
460 self.testparam.append(tparm)
|
|
461 for p in self.addpar:
|
|
462 newname, newval, newlabel, newhelp, newtype, newcl, override, oldcl = p
|
|
463 if not len(newlabel) > 0:
|
|
464 newlabel = newname
|
|
465 ndash = self.getNdash(newname)
|
|
466 if newtype == "text":
|
|
467 aparm = gxtp.TextParam(
|
|
468 newname,
|
|
469 label=newlabel,
|
|
470 help=newhelp,
|
|
471 value=newval,
|
|
472 num_dashes=ndash,
|
|
473 )
|
|
474 elif newtype == "integer":
|
|
475 aparm = gxtp.IntegerParam(
|
|
476 newname,
|
|
477 label=newname,
|
|
478 help=newhelp,
|
|
479 value=newval,
|
|
480 num_dashes=ndash,
|
|
481 )
|
|
482 elif newtype == "float":
|
|
483 aparm = gxtp.FloatParam(
|
|
484 newname,
|
|
485 label=newname,
|
|
486 help=newhelp,
|
|
487 value=newval,
|
|
488 num_dashes=ndash,
|
|
489 )
|
|
490 else:
|
|
491 raise ValueError(
|
|
492 'Unrecognised parameter type "%s" for\
|
|
493 additional parameter %s in makeXML'
|
|
494 % (newtype, newname)
|
|
495 )
|
|
496 aparm.positional = self.is_positional
|
|
497 if self.is_positional:
|
63
|
498 aparm.positional = int(oldcl)
|
48
|
499 self.tinputs.append(aparm)
|
63
|
500 tparm = gxtp.TestParam(newname, value=newval)
|
48
|
501 self.testparam.append(tparm)
|
|
502
|
|
503 def doNoXMLparam(self):
|
49
|
504 """filter style package - stdin to stdout"""
|
62
|
505 if len(self.infiles) > 0:
|
|
506 alab = self.infiles[0][ILABPOS]
|
|
507 if len(alab) == 0:
|
|
508 alab = self.infiles[0][ICLPOS]
|
|
509 max1s = (
|
|
510 "Maximum one input if parampass is 0 but multiple input files supplied - %s"
|
|
511 % str(self.infiles)
|
|
512 )
|
|
513 assert len(self.infiles) == 1, max1s
|
|
514 newname = self.infiles[0][ICLPOS]
|
|
515 aninput = gxtp.DataParam(
|
|
516 newname,
|
|
517 optional=False,
|
|
518 label=alab,
|
|
519 help=self.infiles[0][IHELPOS],
|
|
520 format=self.infiles[0][IFMTPOS],
|
|
521 multiple=False,
|
|
522 num_dashes=0,
|
|
523 )
|
|
524 aninput.command_line_override = "< $%s" % newname
|
|
525 aninput.positional = self.is_positional
|
|
526 self.tinputs.append(aninput)
|
|
527 tp = gxtp.TestParam(name=newname, value="%s_sample" % newname)
|
|
528 self.testparam.append(tp)
|
63
|
529 if len(self.outfiles) > 0:
|
62
|
530 newname = self.outfiles[0][OCLPOS]
|
|
531 newfmt = self.outfiles[0][OFMTPOS]
|
|
532 anout = gxtp.OutputData(newname, format=newfmt, num_dashes=0)
|
|
533 anout.command_line_override = "> $%s" % newname
|
|
534 anout.positional = self.is_positional
|
|
535 self.toutputs.append(anout)
|
75
|
536 tp = gxtp.TestOutput(
|
|
537 name=newname, value="%s_sample" % newname, format=newfmt
|
|
538 )
|
62
|
539 self.testparam.append(tp)
|
48
|
540
|
|
541 def makeXML(self):
|
|
542 """
|
|
543 Create a Galaxy xml tool wrapper for the new script
|
|
544 Uses galaxyhtml
|
|
545 Hmmm. How to get the command line into correct order...
|
|
546 """
|
49
|
547 if self.command_override:
|
56
|
548 self.newtool.command_override = self.command_override # config file
|
48
|
549 else:
|
56
|
550 self.newtool.command_override = self.xmlcl
|
48
|
551 if self.args.help_text:
|
|
552 helptext = open(self.args.help_text, "r").readlines()
|
50
|
553 safertext = [html_escape(x) for x in helptext]
|
63
|
554 if False and self.args.script_path:
|
75
|
555 scrp = self.script.split("\n")
|
|
556 scrpt = [" %s" % x for x in scrp] # try to stop templating
|
|
557 scrpt.insert(0, "```\n")
|
50
|
558 if len(scrpt) > 300:
|
75
|
559 safertext = (
|
106
|
560 safertext
|
|
561 + scrpt[:100]
|
|
562 + [">500 lines - stuff deleted", "......"]
|
|
563 + scrpt[-100:]
|
75
|
564 )
|
50
|
565 else:
|
|
566 safertext = safertext + scrpt
|
|
567 safertext.append("\n```")
|
62
|
568 self.newtool.help = "\n".join([x for x in safertext])
|
48
|
569 else:
|
50
|
570 self.newtool.help = (
|
48
|
571 "Please ask the tool author (%s) for help \
|
|
572 as none was supplied at tool generation\n"
|
|
573 % (self.args.user_email)
|
|
574 )
|
50
|
575 self.newtool.version_command = None # do not want
|
48
|
576 requirements = gxtp.Requirements()
|
49
|
577 if self.args.packages:
|
|
578 for d in self.args.packages.split(","):
|
|
579 if ":" in d:
|
|
580 packg, ver = d.split(":")
|
|
581 else:
|
|
582 packg = d
|
|
583 ver = ""
|
50
|
584 requirements.append(
|
|
585 gxtp.Requirement("package", packg.strip(), ver.strip())
|
|
586 )
|
|
587 self.newtool.requirements = requirements
|
48
|
588 if self.args.parampass == "0":
|
|
589 self.doNoXMLparam()
|
|
590 else:
|
|
591 self.doXMLparam()
|
50
|
592 self.newtool.outputs = self.toutputs
|
|
593 self.newtool.inputs = self.tinputs
|
|
594 if self.args.script_path:
|
48
|
595 configfiles = gxtp.Configfiles()
|
49
|
596 configfiles.append(gxtp.Configfile(name="runme", text=self.script))
|
50
|
597 self.newtool.configfiles = configfiles
|
48
|
598 tests = gxtp.Tests()
|
|
599 test_a = gxtp.Test()
|
|
600 for tp in self.testparam:
|
|
601 test_a.append(tp)
|
|
602 tests.append(test_a)
|
50
|
603 self.newtool.tests = tests
|
|
604 self.newtool.add_comment(
|
48
|
605 "Created by %s at %s using the Galaxy Tool Factory."
|
|
606 % (self.args.user_email, timenow())
|
|
607 )
|
50
|
608 self.newtool.add_comment("Source in git at: %s" % (toolFactoryURL))
|
|
609 self.newtool.add_comment(
|
48
|
610 "Cite: Creating re-usable tools from scripts doi: \
|
|
611 10.1093/bioinformatics/bts573"
|
|
612 )
|
50
|
613 exml0 = self.newtool.export()
|
49
|
614 exml = exml0.replace(FAKEEXE, "") # temporary work around until PR accepted
|
50
|
615 if (
|
|
616 self.test_override
|
|
617 ): # cannot do this inside galaxyxml as it expects lxml objects for tests
|
|
618 part1 = exml.split("<tests>")[0]
|
|
619 part2 = exml.split("</tests>")[1]
|
|
620 fixed = "%s\n%s\n%s" % (part1, self.test_override, part2)
|
49
|
621 exml = fixed
|
63
|
622 exml = exml.replace('range="1:"', 'range="1000:"')
|
49
|
623 xf = open("%s.xml" % self.tool_name, "w")
|
48
|
624 xf.write(exml)
|
|
625 xf.write("\n")
|
|
626 xf.close()
|
|
627 # ready for the tarball
|
|
628
|
|
629 def run(self):
|
|
630 """
|
50
|
631 generate test outputs by running a command line
|
56
|
632 won't work if command or test override in play - planemo is the
|
50
|
633 easiest way to generate test outputs for that case so is
|
|
634 automagically selected
|
48
|
635 """
|
|
636 scl = " ".join(self.cl)
|
|
637 err = None
|
|
638 if self.args.parampass != "0":
|
56
|
639 if os.path.exists(self.elog):
|
|
640 ste = open(self.elog, "a")
|
|
641 else:
|
|
642 ste = open(self.elog, "w")
|
48
|
643 if self.lastclredirect:
|
49
|
644 sto = open(self.lastclredirect[1], "wb") # is name of an output file
|
48
|
645 else:
|
56
|
646 if os.path.exists(self.tlog):
|
|
647 sto = open(self.tlog, "a")
|
|
648 else:
|
|
649 sto = open(self.tlog, "w")
|
48
|
650 sto.write(
|
75
|
651 "## Executing Toolfactory generated command line = %s\n" % scl
|
48
|
652 )
|
|
653 sto.flush()
|
106
|
654 subp = subprocess.run(
|
|
655 self.cl, env=self.ourenv, shell=False, stdout=sto, stderr=ste
|
|
656 )
|
48
|
657 sto.close()
|
|
658 ste.close()
|
98
|
659 retval = subp.returncode
|
49
|
660 else: # work around special case - stdin and write to stdout
|
62
|
661 if len(self.infiles) > 0:
|
|
662 sti = open(self.infiles[0][IPATHPOS], "rb")
|
|
663 else:
|
63
|
664 sti = sys.stdin
|
62
|
665 if len(self.outfiles) > 0:
|
|
666 sto = open(self.outfiles[0][ONAMEPOS], "wb")
|
|
667 else:
|
|
668 sto = sys.stdout
|
106
|
669 subp = subprocess.run(
|
|
670 self.cl, env=self.ourenv, shell=False, stdout=sto, stdin=sti
|
|
671 )
|
75
|
672 sto.write("## Executing Toolfactory generated command line = %s\n" % scl)
|
98
|
673 retval = subp.returncode
|
48
|
674 sto.close()
|
|
675 sti.close()
|
|
676 if os.path.isfile(self.tlog) and os.stat(self.tlog).st_size == 0:
|
|
677 os.unlink(self.tlog)
|
|
678 if os.path.isfile(self.elog) and os.stat(self.elog).st_size == 0:
|
|
679 os.unlink(self.elog)
|
|
680 if retval != 0 and err: # problem
|
|
681 sys.stderr.write(err)
|
|
682 logging.debug("run done")
|
|
683 return retval
|
|
684
|
101
|
685 def copy_to_container(self, src, dest, container):
|
106
|
686 """Recreate the src directory tree at dest - full path included"""
|
101
|
687 idir = os.getcwd()
|
|
688 workdir = os.path.dirname(src)
|
|
689 os.chdir(workdir)
|
|
690 _, tfname = tempfile.mkstemp(suffix=".tar")
|
106
|
691 tar = tarfile.open(tfname, mode="w")
|
101
|
692 srcb = os.path.basename(src)
|
|
693 tar.add(srcb)
|
|
694 tar.close()
|
106
|
695 data = open(tfname, "rb").read()
|
101
|
696 container.put_archive(dest, data)
|
|
697 os.unlink(tfname)
|
|
698 os.chdir(idir)
|
|
699
|
|
700 def copy_from_container(self, src, dest, container):
|
106
|
701 """recreate the src directory tree at dest using docker sdk"""
|
|
702 os.makedirs(dest, exist_ok=True)
|
101
|
703 _, tfname = tempfile.mkstemp(suffix=".tar")
|
106
|
704 tf = open(tfname, "wb")
|
101
|
705 bits, stat = container.get_archive(src)
|
|
706 for chunk in bits:
|
|
707 tf.write(chunk)
|
|
708 tf.close()
|
106
|
709 tar = tarfile.open(tfname, "r")
|
101
|
710 tar.extractall(dest)
|
|
711 tar.close()
|
|
712 os.unlink(tfname)
|
|
713
|
|
714 def planemo_biodocker_test(self):
|
|
715 """planemo currently leaks dependencies if used in the same container and gets unhappy after a
|
|
716 first successful run. https://github.com/galaxyproject/planemo/issues/1078#issuecomment-731476930
|
|
717
|
|
718 Docker biocontainer has planemo with caches filled to save repeated downloads
|
|
719
|
|
720
|
99
|
721 """
|
106
|
722
|
|
723 def prun(container, tout, cl, user="biodocker"):
|
|
724 rlog = container.exec_run(cl, user=user)
|
|
725 slogl = str(rlog).split("\\n")
|
|
726 slog = "\n".join(slogl)
|
103
|
727 tout.write(f"## got rlog {slog} from {cl}\n")
|
101
|
728 if os.path.exists(self.tlog):
|
|
729 tout = open(self.tlog, "a")
|
|
730 else:
|
|
731 tout = open(self.tlog, "w")
|
|
732 planemoimage = "quay.io/fubar2/planemo-biocontainer"
|
|
733 xreal = "%s.xml" % self.tool_name
|
|
734 repname = f"{self.tool_name}_planemo_test_report.html"
|
106
|
735 ptestrep_path = os.path.join(self.repdir, repname)
|
101
|
736 tool_name = self.tool_name
|
|
737 client = docker.from_env()
|
103
|
738 tvol = client.volumes.create()
|
|
739 tvolname = tvol.name
|
|
740 destdir = "/toolfactory/ptest"
|
106
|
741 imrep = os.path.join(destdir, repname)
|
105
|
742 # need to keep the container running so sleep a while - we stop and destroy it when we are done
|
106
|
743 container = client.containers.run(
|
|
744 planemoimage,
|
|
745 "sleep 30m",
|
|
746 detach=True,
|
|
747 user="biodocker",
|
|
748 volumes={f"{tvolname}": {"bind": "/toolfactory", "mode": "rw"}},
|
|
749 )
|
103
|
750 cl = f"mkdir -p {destdir}"
|
|
751 prun(container, tout, cl, user="root")
|
|
752 cl = f"rm -rf {destdir}/*"
|
|
753 prun(container, tout, cl, user="root")
|
106
|
754 ptestpath = os.path.join(destdir, "tfout", xreal)
|
|
755 self.copy_to_container(self.tooloutdir, destdir, container)
|
107
|
756 cl = "chown -R biodocker /toolfactory"
|
103
|
757 prun(container, tout, cl, user="root")
|
101
|
758 rlog = container.exec_run(f"ls -la {destdir}")
|
103
|
759 ptestcl = f"planemo test --update_test_data --no_cleanup --test_data {destdir}/tfout/test-data --galaxy_root /home/biodocker/galaxy-central {ptestpath}"
|
101
|
760 try:
|
|
761 rlog = container.exec_run(ptestcl)
|
|
762 except:
|
|
763 e = sys.exc_info()[0]
|
103
|
764 tout.write(f"#### error: {e} from {ptestcl}\n")
|
101
|
765 # fails - used to generate test outputs
|
103
|
766 cl = f"planemo test --test_output {imrep} --no_cleanup --test_data {destdir}/tfout/test-data --galaxy_root /home/biodocker/galaxy-central {ptestpath}"
|
101
|
767 try:
|
106
|
768 prun(container, tout, cl)
|
101
|
769 except:
|
|
770 pass
|
106
|
771 testouts = tempfile.mkdtemp(suffix=None, prefix="tftemp", dir=".")
|
|
772 self.copy_from_container(destdir, testouts, container)
|
|
773 src = os.path.join(testouts, "ptest")
|
103
|
774 if os.path.isdir(src):
|
106
|
775 shutil.copytree(src, ".", dirs_exist_ok=True)
|
103
|
776 src = repname
|
|
777 if os.path.isfile(repname):
|
106
|
778 shutil.copyfile(src, ptestrep_path)
|
103
|
779 else:
|
|
780 tout.write(f"No output from run to shutil.copytree in {src}\n")
|
101
|
781 tout.close()
|
|
782 container.stop()
|
|
783 container.remove()
|
103
|
784 tvol.remove()
|
106
|
785 # shutil.rmtree(testouts)
|
101
|
786
|
63
|
787 def shedLoad(self):
|
48
|
788 """
|
63
|
789 {'deleted': False,
|
|
790 'description': 'Tools for manipulating data',
|
|
791 'id': '175812cd7caaf439',
|
|
792 'model_class': 'Category',
|
|
793 'name': 'Text Manipulation',
|
|
794 'url': '/api/categories/175812cd7caaf439'}]
|
|
795
|
|
796
|
48
|
797 """
|
49
|
798 if os.path.exists(self.tlog):
|
63
|
799 sto = open(self.tlog, "a")
|
48
|
800 else:
|
63
|
801 sto = open(self.tlog, "w")
|
48
|
802
|
75
|
803 ts = toolshed.ToolShedInstance(
|
|
804 url=self.args.toolshed_url, key=self.args.toolshed_api_key, verify=False
|
|
805 )
|
63
|
806 repos = ts.repositories.get_repositories()
|
75
|
807 rnames = [x.get("name", "?") for x in repos]
|
|
808 rids = [x.get("id", "?") for x in repos]
|
80
|
809 sto.write(f"############names={rnames} rids={rids}\n")
|
100
|
810 sto.write(f"############names={repos}\n")
|
98
|
811 tfcat = "ToolFactory generated tools"
|
101
|
812 if self.tool_name not in rnames:
|
63
|
813 tscat = ts.categories.get_categories()
|
98
|
814 cnames = [x.get("name", "?").strip() for x in tscat]
|
75
|
815 cids = [x.get("id", "?") for x in tscat]
|
63
|
816 catID = None
|
98
|
817 if tfcat.strip() in cnames:
|
|
818 ci = cnames.index(tfcat)
|
63
|
819 catID = cids[ci]
|
75
|
820 res = ts.repositories.create_repository(
|
|
821 name=self.args.tool_name,
|
|
822 synopsis="Synopsis:%s" % self.args.tool_desc,
|
|
823 description=self.args.tool_desc,
|
|
824 type="unrestricted",
|
|
825 remote_repository_url=self.args.toolshed_url,
|
|
826 homepage_url=None,
|
|
827 category_ids=catID,
|
|
828 )
|
|
829 tid = res.get("id", None)
|
80
|
830 sto.write(f"##########create res={res}\n")
|
49
|
831 else:
|
101
|
832 i = rnames.index(self.tool_name)
|
75
|
833 tid = rids[i]
|
100
|
834 try:
|
|
835 res = ts.repositories.update_repository(
|
106
|
836 id=tid, tar_ball_path=self.newtarpath, commit_message=None
|
|
837 )
|
100
|
838 sto.write(f"#####update res={res}\n")
|
|
839 except ConnectionError:
|
106
|
840 sto.write(
|
|
841 "Probably no change to repository - bioblend shed upload failed\n"
|
|
842 )
|
63
|
843 sto.close()
|
|
844
|
48
|
845 def eph_galaxy_load(self):
|
75
|
846 """load the new tool from the local toolshed after planemo uploads it"""
|
49
|
847 if os.path.exists(self.tlog):
|
50
|
848 tout = open(self.tlog, "a")
|
49
|
849 else:
|
50
|
850 tout = open(self.tlog, "w")
|
49
|
851 cll = [
|
|
852 "shed-tools",
|
|
853 "install",
|
|
854 "-g",
|
|
855 self.args.galaxy_url,
|
|
856 "--latest",
|
|
857 "-a",
|
|
858 self.args.galaxy_api_key,
|
|
859 "--name",
|
101
|
860 self.tool_name,
|
49
|
861 "--owner",
|
|
862 "fubar",
|
|
863 "--toolshed",
|
|
864 self.args.toolshed_url,
|
75
|
865 "--section_label",
|
63
|
866 "ToolFactory",
|
49
|
867 ]
|
63
|
868 tout.write("running\n%s\n" % " ".join(cll))
|
106
|
869 subp = subprocess.run(
|
|
870 cll, env=self.ourenv, cwd=self.ourcwd, shell=False, stderr=tout, stdout=tout
|
|
871 )
|
75
|
872 tout.write(
|
101
|
873 "installed %s - got retcode %d\n" % (self.tool_name, subp.returncode)
|
75
|
874 )
|
63
|
875 tout.close()
|
98
|
876 return subp.returncode
|
63
|
877
|
99
|
878 def planemo_shedLoad(self):
|
63
|
879 """
|
|
880 planemo shed_create --shed_target testtoolshed
|
|
881 planemo shed_init --name=<name>
|
|
882 --owner=<shed_username>
|
|
883 --description=<short description>
|
|
884 [--remote_repository_url=<URL to .shed.yml on github>]
|
|
885 [--homepage_url=<Homepage for tool.>]
|
|
886 [--long_description=<long description>]
|
|
887 [--category=<category name>]*
|
66
|
888
|
|
889
|
63
|
890 planemo shed_update --check_diff --shed_target testtoolshed
|
|
891 """
|
|
892 if os.path.exists(self.tlog):
|
|
893 tout = open(self.tlog, "a")
|
48
|
894 else:
|
63
|
895 tout = open(self.tlog, "w")
|
75
|
896 ts = toolshed.ToolShedInstance(
|
|
897 url=self.args.toolshed_url, key=self.args.toolshed_api_key, verify=False
|
|
898 )
|
63
|
899 repos = ts.repositories.get_repositories()
|
75
|
900 rnames = [x.get("name", "?") for x in repos]
|
|
901 rids = [x.get("id", "?") for x in repos]
|
106
|
902 # cat = "ToolFactory generated tools"
|
101
|
903 if self.tool_name not in rnames:
|
75
|
904 cll = [
|
|
905 "planemo",
|
|
906 "shed_create",
|
|
907 "--shed_target",
|
|
908 "local",
|
|
909 "--owner",
|
|
910 "fubar",
|
|
911 "--name",
|
101
|
912 self.tool_name,
|
75
|
913 "--shed_key",
|
|
914 self.args.toolshed_api_key,
|
|
915 ]
|
63
|
916 try:
|
98
|
917 subp = subprocess.run(
|
106
|
918 cll,
|
|
919 env=self.ourenv,
|
|
920 shell=False,
|
|
921 cwd=self.tooloutdir,
|
|
922 stdout=tout,
|
|
923 stderr=tout,
|
63
|
924 )
|
|
925 except:
|
|
926 pass
|
98
|
927 if subp.returncode != 0:
|
101
|
928 tout.write("Repository %s exists\n" % self.tool_name)
|
63
|
929 else:
|
101
|
930 tout.write("initiated %s\n" % self.tool_name)
|
63
|
931 cll = [
|
|
932 "planemo",
|
|
933 "shed_upload",
|
|
934 "--shed_target",
|
|
935 "local",
|
|
936 "--owner",
|
|
937 "fubar",
|
|
938 "--name",
|
101
|
939 self.tool_name,
|
63
|
940 "--shed_key",
|
|
941 self.args.toolshed_api_key,
|
|
942 "--tar",
|
|
943 self.newtarpath,
|
|
944 ]
|
106
|
945 subp = subprocess.run(
|
|
946 cll, env=self.ourenv, cwd=self.ourcwd, shell=False, stdout=tout, stderr=tout
|
|
947 )
|
|
948 tout.write("Ran %s got %d\n" % (" ".join(cll), subp.returncode))
|
49
|
949 tout.close()
|
98
|
950 return subp.returncode
|
48
|
951
|
76
|
952 def eph_test(self, genoutputs=True):
|
106
|
953 """problem getting jobid - ephemeris upload is the job before the one we want - but depends on how many inputs"""
|
75
|
954 if os.path.exists(self.tlog):
|
|
955 tout = open(self.tlog, "a")
|
|
956 else:
|
|
957 tout = open(self.tlog, "w")
|
|
958 cll = [
|
|
959 "shed-tools",
|
|
960 "test",
|
|
961 "-g",
|
|
962 self.args.galaxy_url,
|
|
963 "-a",
|
|
964 self.args.galaxy_api_key,
|
|
965 "--name",
|
101
|
966 self.tool_name,
|
75
|
967 "--owner",
|
|
968 "fubar",
|
|
969 ]
|
76
|
970 if genoutputs:
|
|
971 dummy, tfile = tempfile.mkstemp()
|
98
|
972 subp = subprocess.run(
|
106
|
973 cll,
|
|
974 env=self.ourenv,
|
|
975 cwd=self.ourcwd,
|
|
976 shell=False,
|
|
977 stderr=dummy,
|
|
978 stdout=dummy,
|
76
|
979 )
|
|
980
|
106
|
981 with open("tool_test_output.json", "rb") as f:
|
76
|
982 s = json.loads(f.read())
|
106
|
983 print("read %s" % s)
|
|
984 cl = s["tests"][0]["data"]["job"]["command_line"].split()
|
|
985 n = cl.index("--script_path")
|
|
986 jobdir = cl[n + 1]
|
|
987 jobdir = jobdir.replace('"', "")
|
|
988 jobdir = jobdir.split("/configs")[0]
|
|
989 print("jobdir=%s" % jobdir)
|
76
|
990
|
106
|
991 # "/home/ross/galthrow/database/jobs_directory/000/649/configs/tmptfxu51gs\"
|
|
992 src = os.path.join(jobdir, "working", self.newtarpath)
|
76
|
993 if os.path.exists(src):
|
|
994 dest = os.path.join(self.testdir, self.newtarpath)
|
|
995 shutil.copyfile(src, dest)
|
|
996 else:
|
106
|
997 tout.write(
|
|
998 "No toolshed archive found after first ephemeris test - not a good sign"
|
|
999 )
|
|
1000 ephouts = os.path.join(jobdir, "working", "tfout", "test-data")
|
76
|
1001 with os.scandir(ephouts) as outs:
|
|
1002 for entry in outs:
|
|
1003 if not entry.is_file():
|
|
1004 continue
|
|
1005 dest = os.path.join(self.tooloutdir, entry.name)
|
|
1006 src = os.path.join(ephouts, entry.name)
|
|
1007 shutil.copyfile(src, dest)
|
|
1008 else:
|
98
|
1009 subp = subprocess.run(
|
106
|
1010 cll,
|
|
1011 env=self.ourenv,
|
|
1012 cwd=self.ourcwd,
|
|
1013 shell=False,
|
|
1014 stderr=tout,
|
|
1015 stdout=tout,
|
|
1016 )
|
98
|
1017 tout.write("eph_test Ran %s got %d" % (" ".join(cll), subp.returncode))
|
75
|
1018 tout.close()
|
98
|
1019 return subp.returncode
|
63
|
1020
|
83
|
1021 def planemo_test_biocontainer(self, genoutputs=True):
|
|
1022 """planemo is a requirement so is available for testing but testing in a biocontainer
|
106
|
1023 requires some fiddling to use the hacked galaxy-central .venv
|
83
|
1024
|
106
|
1025 Planemo runs:
|
|
1026 python ./scripts/functional_tests.py -v --with-nosehtml --html-report-file
|
|
1027 /export/galaxy-central/database/job_working_directory/000/17/working/TF_run_report_tempdir/tacrev_planemo_test_report.html
|
|
1028 --with-xunit --xunit-file /tmp/tmpt90p7f9h/xunit.xml --with-structureddata
|
|
1029 --structured-data-file
|
|
1030 /export/galaxy-central/database/job_working_directory/000/17/working/tfout/tool_test_output.json functional.test_toolbox
|
83
|
1031
|
|
1032
|
106
|
1033 for the planemo-biocontainer,
|
|
1034 planemo test --conda_dependency_resolution --skip_venv --galaxy_root /galthrow/ rgToolFactory2.xml
|
83
|
1035
|
|
1036 """
|
|
1037 xreal = "%s.xml" % self.tool_name
|
106
|
1038 tool_test_path = os.path.join(
|
|
1039 self.repdir, f"{self.tool_name}_planemo_test_report.html"
|
|
1040 )
|
83
|
1041 if os.path.exists(self.tlog):
|
|
1042 tout = open(self.tlog, "a")
|
|
1043 else:
|
|
1044 tout = open(self.tlog, "w")
|
|
1045 if genoutputs:
|
|
1046 dummy, tfile = tempfile.mkstemp()
|
|
1047 cll = [
|
106
|
1048 ".",
|
|
1049 os.path.join(self.args.galaxy_root, ".venv", "bin", "activate"),
|
|
1050 "&&",
|
83
|
1051 "planemo",
|
|
1052 "test",
|
106
|
1053 "--test_data",
|
|
1054 self.testdir,
|
|
1055 "--test_output",
|
|
1056 tool_test_path,
|
83
|
1057 "--skip_venv",
|
|
1058 "--galaxy_root",
|
91
|
1059 self.args.galaxy_root,
|
83
|
1060 "--update_test_data",
|
98
|
1061 xreal,
|
83
|
1062 ]
|
98
|
1063 subp = subprocess.run(
|
83
|
1064 cll,
|
101
|
1065 env=self.ourenv,
|
83
|
1066 shell=False,
|
|
1067 cwd=self.tooloutdir,
|
|
1068 stderr=dummy,
|
|
1069 stdout=dummy,
|
|
1070 )
|
|
1071
|
|
1072 else:
|
|
1073 cll = [
|
106
|
1074 ".",
|
|
1075 os.path.join(self.args.galaxy_root, ".venv", "bin", "activate"),
|
|
1076 "&&",
|
83
|
1077 "planemo",
|
|
1078 "test",
|
106
|
1079 "--test_data",
|
|
1080 os.path.self.testdir,
|
|
1081 "--test_output",
|
|
1082 os.path.tool_test_path,
|
83
|
1083 "--skip_venv",
|
|
1084 "--galaxy_root",
|
91
|
1085 self.args.galaxy_root,
|
98
|
1086 xreal,
|
83
|
1087 ]
|
98
|
1088 subp = subprocess.run(
|
106
|
1089 cll,
|
|
1090 env=self.ourenv,
|
|
1091 shell=False,
|
|
1092 cwd=self.tooloutdir,
|
|
1093 stderr=tout,
|
|
1094 stdout=tout,
|
83
|
1095 )
|
|
1096 tout.close()
|
98
|
1097 return subp.returncode
|
83
|
1098
|
48
|
1099 def writeShedyml(self):
|
75
|
1100 """for planemo"""
|
49
|
1101 yuser = self.args.user_email.split("@")[0]
|
|
1102 yfname = os.path.join(self.tooloutdir, ".shed.yml")
|
|
1103 yamlf = open(yfname, "w")
|
|
1104 odict = {
|
|
1105 "name": self.tool_name,
|
|
1106 "owner": yuser,
|
|
1107 "type": "unrestricted",
|
|
1108 "description": self.args.tool_desc,
|
50
|
1109 "synopsis": self.args.tool_desc,
|
|
1110 "category": "TF Generated Tools",
|
49
|
1111 }
|
48
|
1112 yaml.dump(odict, yamlf, allow_unicode=True)
|
|
1113 yamlf.close()
|
|
1114
|
50
|
1115 def makeTool(self):
|
75
|
1116 """write xmls and input samples into place"""
|
50
|
1117 self.makeXML()
|
|
1118 if self.args.script_path:
|
|
1119 stname = os.path.join(self.tooloutdir, "%s" % (self.sfile))
|
|
1120 if not os.path.exists(stname):
|
|
1121 shutil.copyfile(self.sfile, stname)
|
|
1122 xreal = "%s.xml" % self.tool_name
|
|
1123 xout = os.path.join(self.tooloutdir, xreal)
|
|
1124 shutil.copyfile(xreal, xout)
|
|
1125 for p in self.infiles:
|
|
1126 pth = p[IPATHPOS]
|
|
1127 dest = os.path.join(self.testdir, "%s_sample" % p[ICLPOS])
|
|
1128 shutil.copyfile(pth, dest)
|
49
|
1129
|
50
|
1130 def makeToolTar(self):
|
75
|
1131 """move outputs into test-data and prepare the tarball"""
|
101
|
1132 excludeme = "_planemo_test_report.html"
|
75
|
1133
|
66
|
1134 def exclude_function(tarinfo):
|
75
|
1135 filename = tarinfo.name
|
106
|
1136 return None if filename.endswith(excludeme) else tarinfo
|
66
|
1137
|
50
|
1138 for p in self.outfiles:
|
96
|
1139 oname = p[ONAMEPOS]
|
99
|
1140 tdest = os.path.join(self.testdir, "%s_sample" % oname)
|
|
1141 if not os.path.isfile(tdest):
|
106
|
1142 src = os.path.join(self.testdir, oname)
|
99
|
1143 if os.path.isfile(src):
|
|
1144 shutil.copyfile(src, tdest)
|
|
1145 dest = os.path.join(self.repdir, "%s.sample" % (oname))
|
|
1146 shutil.copyfile(src, dest)
|
|
1147 else:
|
|
1148 print(
|
|
1149 "### problem - output file %s not found in testdir %s"
|
|
1150 % (tdest, self.testdir)
|
|
1151 )
|
50
|
1152 tf = tarfile.open(self.newtarpath, "w:gz")
|
66
|
1153 tf.add(name=self.tooloutdir, arcname=self.tool_name, filter=exclude_function)
|
50
|
1154 tf.close()
|
|
1155 shutil.copyfile(self.newtarpath, self.args.new_tool)
|
|
1156
|
|
1157 def moveRunOutputs(self):
|
75
|
1158 """need to move planemo or run outputs into toolfactory collection"""
|
50
|
1159 with os.scandir(self.tooloutdir) as outs:
|
|
1160 for entry in outs:
|
80
|
1161 if not entry.is_file():
|
|
1162 continue
|
|
1163 if "." in entry.name:
|
|
1164 nayme, ext = os.path.splitext(entry.name)
|
106
|
1165 if ext in [".yml", ".xml", ".json", ".yaml"]:
|
|
1166 ext = f"{ext}.txt"
|
80
|
1167 else:
|
|
1168 ext = ".txt"
|
|
1169 ofn = "%s%s" % (entry.name.replace(".", "_"), ext)
|
|
1170 dest = os.path.join(self.repdir, ofn)
|
|
1171 src = os.path.join(self.tooloutdir, entry.name)
|
|
1172 shutil.copyfile(src, dest)
|
|
1173 with os.scandir(self.testdir) as outs:
|
|
1174 for entry in outs:
|
106
|
1175 if (
|
|
1176 (not entry.is_file())
|
|
1177 or entry.name.endswith("_sample")
|
|
1178 or entry.name.endswith("_planemo_test_report.html")
|
|
1179 ):
|
50
|
1180 continue
|
|
1181 if "." in entry.name:
|
|
1182 nayme, ext = os.path.splitext(entry.name)
|
|
1183 else:
|
|
1184 ext = ".txt"
|
80
|
1185 newname = f"{entry.name}{ext}"
|
|
1186 dest = os.path.join(self.repdir, newname)
|
|
1187 src = os.path.join(self.testdir, entry.name)
|
50
|
1188 shutil.copyfile(src, dest)
|
|
1189
|
49
|
1190
|
48
|
1191 def main():
|
|
1192 """
|
|
1193 This is a Galaxy wrapper. It expects to be called by a special purpose tool.xml as:
|
49
|
1194 <command interpreter="python">rgBaseScriptWrapper.py --script_path "$scriptPath"
|
|
1195 --tool_name "foo" --interpreter "Rscript"
|
48
|
1196 </command>
|
|
1197 """
|
|
1198 parser = argparse.ArgumentParser()
|
|
1199 a = parser.add_argument
|
49
|
1200 a("--script_path", default=None)
|
|
1201 a("--history_test", default=None)
|
|
1202 a("--cl_prefix", default=None)
|
|
1203 a("--sysexe", default=None)
|
|
1204 a("--packages", default=None)
|
76
|
1205 a("--tool_name", default="newtool")
|
72
|
1206 a("--tool_dir", default=None)
|
48
|
1207 a("--input_files", default=[], action="append")
|
|
1208 a("--output_files", default=[], action="append")
|
|
1209 a("--user_email", default="Unknown")
|
|
1210 a("--bad_user", default=None)
|
49
|
1211 a("--make_Tool", default="runonly")
|
48
|
1212 a("--help_text", default=None)
|
|
1213 a("--tool_desc", default=None)
|
|
1214 a("--tool_version", default=None)
|
|
1215 a("--citations", default=None)
|
49
|
1216 a("--command_override", default=None)
|
|
1217 a("--test_override", default=None)
|
48
|
1218 a("--additional_parameters", action="append", default=[])
|
|
1219 a("--edit_additional_parameters", action="store_true", default=False)
|
|
1220 a("--parampass", default="positional")
|
|
1221 a("--tfout", default="./tfout")
|
|
1222 a("--new_tool", default="new_tool")
|
49
|
1223 a("--galaxy_url", default="http://localhost:8080")
|
106
|
1224 a("--toolshed_url", default="http://localhost:9009")
|
76
|
1225 # make sure this is identical to tool_sheds_conf.xml localhost != 127.0.0.1 so validation fails
|
63
|
1226 a("--toolshed_api_key", default="fakekey")
|
50
|
1227 a("--galaxy_api_key", default="fakekey")
|
|
1228 a("--galaxy_root", default="/galaxy-central")
|
101
|
1229 a("--galaxy_venv", default="/galaxy_venv")
|
48
|
1230 args = parser.parse_args()
|
|
1231 assert not args.bad_user, (
|
|
1232 'UNAUTHORISED: %s is NOT authorized to use this tool until Galaxy admin adds %s to "admin_users" in the Galaxy configuration file'
|
|
1233 % (args.bad_user, args.bad_user)
|
|
1234 )
|
49
|
1235 assert args.tool_name, "## Tool Factory expects a tool name - eg --tool_name=DESeq"
|
48
|
1236 assert (
|
49
|
1237 args.sysexe or args.packages
|
48
|
1238 ), "## Tool Factory wrapper expects an interpreter or an executable package"
|
49
|
1239 args.input_files = [x.replace('"', "").replace("'", "") for x in args.input_files]
|
48
|
1240 # remove quotes we need to deal with spaces in CL params
|
|
1241 for i, x in enumerate(args.additional_parameters):
|
49
|
1242 args.additional_parameters[i] = args.additional_parameters[i].replace('"', "")
|
48
|
1243 r = ScriptRunner(args)
|
49
|
1244 r.writeShedyml()
|
|
1245 r.makeTool()
|
66
|
1246 if args.make_Tool == "generate":
|
106
|
1247 retcode = r.run() # for testing toolfactory itself
|
66
|
1248 r.moveRunOutputs()
|
|
1249 r.makeToolTar()
|
|
1250 else:
|
106
|
1251 r.planemo_biodocker_test() # test to make outputs and then test
|
66
|
1252 r.moveRunOutputs()
|
|
1253 r.makeToolTar()
|
101
|
1254 if args.make_Tool == "gentestinstall":
|
|
1255 r.shedLoad()
|
|
1256 r.eph_galaxy_load()
|
63
|
1257
|
48
|
1258
|
|
1259 if __name__ == "__main__":
|
|
1260 main()
|