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")
|
|
728
|
106
|
729 dgroup = grp.getgrnam("docker")[2]
|
101
|
730 if os.path.exists(self.tlog):
|
|
731 tout = open(self.tlog, "a")
|
|
732 else:
|
|
733 tout = open(self.tlog, "w")
|
|
734 planemoimage = "quay.io/fubar2/planemo-biocontainer"
|
|
735 xreal = "%s.xml" % self.tool_name
|
|
736 repname = f"{self.tool_name}_planemo_test_report.html"
|
106
|
737 ptestrep_path = os.path.join(self.repdir, repname)
|
101
|
738 tool_name = self.tool_name
|
|
739 client = docker.from_env()
|
103
|
740 tvol = client.volumes.create()
|
|
741 tvolname = tvol.name
|
|
742 destdir = "/toolfactory/ptest"
|
106
|
743 imrep = os.path.join(destdir, repname)
|
105
|
744 # need to keep the container running so sleep a while - we stop and destroy it when we are done
|
106
|
745 container = client.containers.run(
|
|
746 planemoimage,
|
|
747 "sleep 30m",
|
|
748 detach=True,
|
|
749 user="biodocker",
|
|
750 volumes={f"{tvolname}": {"bind": "/toolfactory", "mode": "rw"}},
|
|
751 )
|
103
|
752 cl = f"groupmod -g {dgroup} docker"
|
|
753 prun(container, tout, cl, user="root")
|
|
754 cl = f"mkdir -p {destdir}"
|
|
755 prun(container, tout, cl, user="root")
|
|
756 cl = f"rm -rf {destdir}/*"
|
|
757 prun(container, tout, cl, user="root")
|
106
|
758 ptestpath = os.path.join(destdir, "tfout", xreal)
|
|
759 self.copy_to_container(self.tooloutdir, destdir, container)
|
|
760 cl = "chmod -R a+rwx /toolfactory"
|
103
|
761 prun(container, tout, cl, user="root")
|
101
|
762 rlog = container.exec_run(f"ls -la {destdir}")
|
103
|
763 ptestcl = f"planemo test --update_test_data --no_cleanup --test_data {destdir}/tfout/test-data --galaxy_root /home/biodocker/galaxy-central {ptestpath}"
|
101
|
764 try:
|
|
765 rlog = container.exec_run(ptestcl)
|
|
766 except:
|
|
767 e = sys.exc_info()[0]
|
103
|
768 tout.write(f"#### error: {e} from {ptestcl}\n")
|
101
|
769 # fails - used to generate test outputs
|
103
|
770 cl = f"planemo test --test_output {imrep} --no_cleanup --test_data {destdir}/tfout/test-data --galaxy_root /home/biodocker/galaxy-central {ptestpath}"
|
101
|
771 try:
|
106
|
772 prun(container, tout, cl)
|
101
|
773 except:
|
|
774 pass
|
106
|
775 testouts = tempfile.mkdtemp(suffix=None, prefix="tftemp", dir=".")
|
|
776 self.copy_from_container(destdir, testouts, container)
|
|
777 src = os.path.join(testouts, "ptest")
|
103
|
778 if os.path.isdir(src):
|
106
|
779 shutil.copytree(src, ".", dirs_exist_ok=True)
|
103
|
780 src = repname
|
|
781 if os.path.isfile(repname):
|
106
|
782 shutil.copyfile(src, ptestrep_path)
|
103
|
783 else:
|
|
784 tout.write(f"No output from run to shutil.copytree in {src}\n")
|
101
|
785 tout.close()
|
|
786 container.stop()
|
|
787 container.remove()
|
103
|
788 tvol.remove()
|
106
|
789 # shutil.rmtree(testouts)
|
101
|
790
|
63
|
791 def shedLoad(self):
|
48
|
792 """
|
63
|
793 {'deleted': False,
|
|
794 'description': 'Tools for manipulating data',
|
|
795 'id': '175812cd7caaf439',
|
|
796 'model_class': 'Category',
|
|
797 'name': 'Text Manipulation',
|
|
798 'url': '/api/categories/175812cd7caaf439'}]
|
|
799
|
|
800
|
48
|
801 """
|
49
|
802 if os.path.exists(self.tlog):
|
63
|
803 sto = open(self.tlog, "a")
|
48
|
804 else:
|
63
|
805 sto = open(self.tlog, "w")
|
48
|
806
|
75
|
807 ts = toolshed.ToolShedInstance(
|
|
808 url=self.args.toolshed_url, key=self.args.toolshed_api_key, verify=False
|
|
809 )
|
63
|
810 repos = ts.repositories.get_repositories()
|
75
|
811 rnames = [x.get("name", "?") for x in repos]
|
|
812 rids = [x.get("id", "?") for x in repos]
|
80
|
813 sto.write(f"############names={rnames} rids={rids}\n")
|
100
|
814 sto.write(f"############names={repos}\n")
|
98
|
815 tfcat = "ToolFactory generated tools"
|
101
|
816 if self.tool_name not in rnames:
|
63
|
817 tscat = ts.categories.get_categories()
|
98
|
818 cnames = [x.get("name", "?").strip() for x in tscat]
|
75
|
819 cids = [x.get("id", "?") for x in tscat]
|
63
|
820 catID = None
|
98
|
821 if tfcat.strip() in cnames:
|
|
822 ci = cnames.index(tfcat)
|
63
|
823 catID = cids[ci]
|
75
|
824 res = ts.repositories.create_repository(
|
|
825 name=self.args.tool_name,
|
|
826 synopsis="Synopsis:%s" % self.args.tool_desc,
|
|
827 description=self.args.tool_desc,
|
|
828 type="unrestricted",
|
|
829 remote_repository_url=self.args.toolshed_url,
|
|
830 homepage_url=None,
|
|
831 category_ids=catID,
|
|
832 )
|
|
833 tid = res.get("id", None)
|
80
|
834 sto.write(f"##########create res={res}\n")
|
49
|
835 else:
|
101
|
836 i = rnames.index(self.tool_name)
|
75
|
837 tid = rids[i]
|
100
|
838 try:
|
|
839 res = ts.repositories.update_repository(
|
106
|
840 id=tid, tar_ball_path=self.newtarpath, commit_message=None
|
|
841 )
|
100
|
842 sto.write(f"#####update res={res}\n")
|
|
843 except ConnectionError:
|
106
|
844 sto.write(
|
|
845 "Probably no change to repository - bioblend shed upload failed\n"
|
|
846 )
|
63
|
847 sto.close()
|
|
848
|
48
|
849 def eph_galaxy_load(self):
|
75
|
850 """load the new tool from the local toolshed after planemo uploads it"""
|
49
|
851 if os.path.exists(self.tlog):
|
50
|
852 tout = open(self.tlog, "a")
|
49
|
853 else:
|
50
|
854 tout = open(self.tlog, "w")
|
49
|
855 cll = [
|
|
856 "shed-tools",
|
|
857 "install",
|
|
858 "-g",
|
|
859 self.args.galaxy_url,
|
|
860 "--latest",
|
|
861 "-a",
|
|
862 self.args.galaxy_api_key,
|
|
863 "--name",
|
101
|
864 self.tool_name,
|
49
|
865 "--owner",
|
|
866 "fubar",
|
|
867 "--toolshed",
|
|
868 self.args.toolshed_url,
|
75
|
869 "--section_label",
|
63
|
870 "ToolFactory",
|
49
|
871 ]
|
63
|
872 tout.write("running\n%s\n" % " ".join(cll))
|
106
|
873 subp = subprocess.run(
|
|
874 cll, env=self.ourenv, cwd=self.ourcwd, shell=False, stderr=tout, stdout=tout
|
|
875 )
|
75
|
876 tout.write(
|
101
|
877 "installed %s - got retcode %d\n" % (self.tool_name, subp.returncode)
|
75
|
878 )
|
63
|
879 tout.close()
|
98
|
880 return subp.returncode
|
63
|
881
|
99
|
882 def planemo_shedLoad(self):
|
63
|
883 """
|
|
884 planemo shed_create --shed_target testtoolshed
|
|
885 planemo shed_init --name=<name>
|
|
886 --owner=<shed_username>
|
|
887 --description=<short description>
|
|
888 [--remote_repository_url=<URL to .shed.yml on github>]
|
|
889 [--homepage_url=<Homepage for tool.>]
|
|
890 [--long_description=<long description>]
|
|
891 [--category=<category name>]*
|
66
|
892
|
|
893
|
63
|
894 planemo shed_update --check_diff --shed_target testtoolshed
|
|
895 """
|
|
896 if os.path.exists(self.tlog):
|
|
897 tout = open(self.tlog, "a")
|
48
|
898 else:
|
63
|
899 tout = open(self.tlog, "w")
|
75
|
900 ts = toolshed.ToolShedInstance(
|
|
901 url=self.args.toolshed_url, key=self.args.toolshed_api_key, verify=False
|
|
902 )
|
63
|
903 repos = ts.repositories.get_repositories()
|
75
|
904 rnames = [x.get("name", "?") for x in repos]
|
|
905 rids = [x.get("id", "?") for x in repos]
|
106
|
906 # cat = "ToolFactory generated tools"
|
101
|
907 if self.tool_name not in rnames:
|
75
|
908 cll = [
|
|
909 "planemo",
|
|
910 "shed_create",
|
|
911 "--shed_target",
|
|
912 "local",
|
|
913 "--owner",
|
|
914 "fubar",
|
|
915 "--name",
|
101
|
916 self.tool_name,
|
75
|
917 "--shed_key",
|
|
918 self.args.toolshed_api_key,
|
|
919 ]
|
63
|
920 try:
|
98
|
921 subp = subprocess.run(
|
106
|
922 cll,
|
|
923 env=self.ourenv,
|
|
924 shell=False,
|
|
925 cwd=self.tooloutdir,
|
|
926 stdout=tout,
|
|
927 stderr=tout,
|
63
|
928 )
|
|
929 except:
|
|
930 pass
|
98
|
931 if subp.returncode != 0:
|
101
|
932 tout.write("Repository %s exists\n" % self.tool_name)
|
63
|
933 else:
|
101
|
934 tout.write("initiated %s\n" % self.tool_name)
|
63
|
935 cll = [
|
|
936 "planemo",
|
|
937 "shed_upload",
|
|
938 "--shed_target",
|
|
939 "local",
|
|
940 "--owner",
|
|
941 "fubar",
|
|
942 "--name",
|
101
|
943 self.tool_name,
|
63
|
944 "--shed_key",
|
|
945 self.args.toolshed_api_key,
|
|
946 "--tar",
|
|
947 self.newtarpath,
|
|
948 ]
|
106
|
949 subp = subprocess.run(
|
|
950 cll, env=self.ourenv, cwd=self.ourcwd, shell=False, stdout=tout, stderr=tout
|
|
951 )
|
|
952 tout.write("Ran %s got %d\n" % (" ".join(cll), subp.returncode))
|
49
|
953 tout.close()
|
98
|
954 return subp.returncode
|
48
|
955
|
76
|
956 def eph_test(self, genoutputs=True):
|
106
|
957 """problem getting jobid - ephemeris upload is the job before the one we want - but depends on how many inputs"""
|
75
|
958 if os.path.exists(self.tlog):
|
|
959 tout = open(self.tlog, "a")
|
|
960 else:
|
|
961 tout = open(self.tlog, "w")
|
|
962 cll = [
|
|
963 "shed-tools",
|
|
964 "test",
|
|
965 "-g",
|
|
966 self.args.galaxy_url,
|
|
967 "-a",
|
|
968 self.args.galaxy_api_key,
|
|
969 "--name",
|
101
|
970 self.tool_name,
|
75
|
971 "--owner",
|
|
972 "fubar",
|
|
973 ]
|
76
|
974 if genoutputs:
|
|
975 dummy, tfile = tempfile.mkstemp()
|
98
|
976 subp = subprocess.run(
|
106
|
977 cll,
|
|
978 env=self.ourenv,
|
|
979 cwd=self.ourcwd,
|
|
980 shell=False,
|
|
981 stderr=dummy,
|
|
982 stdout=dummy,
|
76
|
983 )
|
|
984
|
106
|
985 with open("tool_test_output.json", "rb") as f:
|
76
|
986 s = json.loads(f.read())
|
106
|
987 print("read %s" % s)
|
|
988 cl = s["tests"][0]["data"]["job"]["command_line"].split()
|
|
989 n = cl.index("--script_path")
|
|
990 jobdir = cl[n + 1]
|
|
991 jobdir = jobdir.replace('"', "")
|
|
992 jobdir = jobdir.split("/configs")[0]
|
|
993 print("jobdir=%s" % jobdir)
|
76
|
994
|
106
|
995 # "/home/ross/galthrow/database/jobs_directory/000/649/configs/tmptfxu51gs\"
|
|
996 src = os.path.join(jobdir, "working", self.newtarpath)
|
76
|
997 if os.path.exists(src):
|
|
998 dest = os.path.join(self.testdir, self.newtarpath)
|
|
999 shutil.copyfile(src, dest)
|
|
1000 else:
|
106
|
1001 tout.write(
|
|
1002 "No toolshed archive found after first ephemeris test - not a good sign"
|
|
1003 )
|
|
1004 ephouts = os.path.join(jobdir, "working", "tfout", "test-data")
|
76
|
1005 with os.scandir(ephouts) as outs:
|
|
1006 for entry in outs:
|
|
1007 if not entry.is_file():
|
|
1008 continue
|
|
1009 dest = os.path.join(self.tooloutdir, entry.name)
|
|
1010 src = os.path.join(ephouts, entry.name)
|
|
1011 shutil.copyfile(src, dest)
|
|
1012 else:
|
98
|
1013 subp = subprocess.run(
|
106
|
1014 cll,
|
|
1015 env=self.ourenv,
|
|
1016 cwd=self.ourcwd,
|
|
1017 shell=False,
|
|
1018 stderr=tout,
|
|
1019 stdout=tout,
|
|
1020 )
|
98
|
1021 tout.write("eph_test Ran %s got %d" % (" ".join(cll), subp.returncode))
|
75
|
1022 tout.close()
|
98
|
1023 return subp.returncode
|
63
|
1024
|
83
|
1025 def planemo_test_biocontainer(self, genoutputs=True):
|
|
1026 """planemo is a requirement so is available for testing but testing in a biocontainer
|
106
|
1027 requires some fiddling to use the hacked galaxy-central .venv
|
83
|
1028
|
106
|
1029 Planemo runs:
|
|
1030 python ./scripts/functional_tests.py -v --with-nosehtml --html-report-file
|
|
1031 /export/galaxy-central/database/job_working_directory/000/17/working/TF_run_report_tempdir/tacrev_planemo_test_report.html
|
|
1032 --with-xunit --xunit-file /tmp/tmpt90p7f9h/xunit.xml --with-structureddata
|
|
1033 --structured-data-file
|
|
1034 /export/galaxy-central/database/job_working_directory/000/17/working/tfout/tool_test_output.json functional.test_toolbox
|
83
|
1035
|
|
1036
|
106
|
1037 for the planemo-biocontainer,
|
|
1038 planemo test --conda_dependency_resolution --skip_venv --galaxy_root /galthrow/ rgToolFactory2.xml
|
83
|
1039
|
|
1040 """
|
|
1041 xreal = "%s.xml" % self.tool_name
|
106
|
1042 tool_test_path = os.path.join(
|
|
1043 self.repdir, f"{self.tool_name}_planemo_test_report.html"
|
|
1044 )
|
83
|
1045 if os.path.exists(self.tlog):
|
|
1046 tout = open(self.tlog, "a")
|
|
1047 else:
|
|
1048 tout = open(self.tlog, "w")
|
|
1049 if genoutputs:
|
|
1050 dummy, tfile = tempfile.mkstemp()
|
|
1051 cll = [
|
106
|
1052 ".",
|
|
1053 os.path.join(self.args.galaxy_root, ".venv", "bin", "activate"),
|
|
1054 "&&",
|
83
|
1055 "planemo",
|
|
1056 "test",
|
106
|
1057 "--test_data",
|
|
1058 self.testdir,
|
|
1059 "--test_output",
|
|
1060 tool_test_path,
|
83
|
1061 "--skip_venv",
|
|
1062 "--galaxy_root",
|
91
|
1063 self.args.galaxy_root,
|
83
|
1064 "--update_test_data",
|
98
|
1065 xreal,
|
83
|
1066 ]
|
98
|
1067 subp = subprocess.run(
|
83
|
1068 cll,
|
101
|
1069 env=self.ourenv,
|
83
|
1070 shell=False,
|
|
1071 cwd=self.tooloutdir,
|
|
1072 stderr=dummy,
|
|
1073 stdout=dummy,
|
|
1074 )
|
|
1075
|
|
1076 else:
|
|
1077 cll = [
|
106
|
1078 ".",
|
|
1079 os.path.join(self.args.galaxy_root, ".venv", "bin", "activate"),
|
|
1080 "&&",
|
83
|
1081 "planemo",
|
|
1082 "test",
|
106
|
1083 "--test_data",
|
|
1084 os.path.self.testdir,
|
|
1085 "--test_output",
|
|
1086 os.path.tool_test_path,
|
83
|
1087 "--skip_venv",
|
|
1088 "--galaxy_root",
|
91
|
1089 self.args.galaxy_root,
|
98
|
1090 xreal,
|
83
|
1091 ]
|
98
|
1092 subp = subprocess.run(
|
106
|
1093 cll,
|
|
1094 env=self.ourenv,
|
|
1095 shell=False,
|
|
1096 cwd=self.tooloutdir,
|
|
1097 stderr=tout,
|
|
1098 stdout=tout,
|
83
|
1099 )
|
|
1100 tout.close()
|
98
|
1101 return subp.returncode
|
83
|
1102
|
48
|
1103 def writeShedyml(self):
|
75
|
1104 """for planemo"""
|
49
|
1105 yuser = self.args.user_email.split("@")[0]
|
|
1106 yfname = os.path.join(self.tooloutdir, ".shed.yml")
|
|
1107 yamlf = open(yfname, "w")
|
|
1108 odict = {
|
|
1109 "name": self.tool_name,
|
|
1110 "owner": yuser,
|
|
1111 "type": "unrestricted",
|
|
1112 "description": self.args.tool_desc,
|
50
|
1113 "synopsis": self.args.tool_desc,
|
|
1114 "category": "TF Generated Tools",
|
49
|
1115 }
|
48
|
1116 yaml.dump(odict, yamlf, allow_unicode=True)
|
|
1117 yamlf.close()
|
|
1118
|
50
|
1119 def makeTool(self):
|
75
|
1120 """write xmls and input samples into place"""
|
50
|
1121 self.makeXML()
|
|
1122 if self.args.script_path:
|
|
1123 stname = os.path.join(self.tooloutdir, "%s" % (self.sfile))
|
|
1124 if not os.path.exists(stname):
|
|
1125 shutil.copyfile(self.sfile, stname)
|
|
1126 xreal = "%s.xml" % self.tool_name
|
|
1127 xout = os.path.join(self.tooloutdir, xreal)
|
|
1128 shutil.copyfile(xreal, xout)
|
|
1129 for p in self.infiles:
|
|
1130 pth = p[IPATHPOS]
|
|
1131 dest = os.path.join(self.testdir, "%s_sample" % p[ICLPOS])
|
|
1132 shutil.copyfile(pth, dest)
|
49
|
1133
|
50
|
1134 def makeToolTar(self):
|
75
|
1135 """move outputs into test-data and prepare the tarball"""
|
101
|
1136 excludeme = "_planemo_test_report.html"
|
75
|
1137
|
66
|
1138 def exclude_function(tarinfo):
|
75
|
1139 filename = tarinfo.name
|
106
|
1140 return None if filename.endswith(excludeme) else tarinfo
|
66
|
1141
|
50
|
1142 for p in self.outfiles:
|
96
|
1143 oname = p[ONAMEPOS]
|
99
|
1144 tdest = os.path.join(self.testdir, "%s_sample" % oname)
|
|
1145 if not os.path.isfile(tdest):
|
106
|
1146 src = os.path.join(self.testdir, oname)
|
99
|
1147 if os.path.isfile(src):
|
|
1148 shutil.copyfile(src, tdest)
|
|
1149 dest = os.path.join(self.repdir, "%s.sample" % (oname))
|
|
1150 shutil.copyfile(src, dest)
|
|
1151 else:
|
|
1152 print(
|
|
1153 "### problem - output file %s not found in testdir %s"
|
|
1154 % (tdest, self.testdir)
|
|
1155 )
|
50
|
1156 tf = tarfile.open(self.newtarpath, "w:gz")
|
66
|
1157 tf.add(name=self.tooloutdir, arcname=self.tool_name, filter=exclude_function)
|
50
|
1158 tf.close()
|
|
1159 shutil.copyfile(self.newtarpath, self.args.new_tool)
|
|
1160
|
|
1161 def moveRunOutputs(self):
|
75
|
1162 """need to move planemo or run outputs into toolfactory collection"""
|
50
|
1163 with os.scandir(self.tooloutdir) as outs:
|
|
1164 for entry in outs:
|
80
|
1165 if not entry.is_file():
|
|
1166 continue
|
|
1167 if "." in entry.name:
|
|
1168 nayme, ext = os.path.splitext(entry.name)
|
106
|
1169 if ext in [".yml", ".xml", ".json", ".yaml"]:
|
|
1170 ext = f"{ext}.txt"
|
80
|
1171 else:
|
|
1172 ext = ".txt"
|
|
1173 ofn = "%s%s" % (entry.name.replace(".", "_"), ext)
|
|
1174 dest = os.path.join(self.repdir, ofn)
|
|
1175 src = os.path.join(self.tooloutdir, entry.name)
|
|
1176 shutil.copyfile(src, dest)
|
|
1177 with os.scandir(self.testdir) as outs:
|
|
1178 for entry in outs:
|
106
|
1179 if (
|
|
1180 (not entry.is_file())
|
|
1181 or entry.name.endswith("_sample")
|
|
1182 or entry.name.endswith("_planemo_test_report.html")
|
|
1183 ):
|
50
|
1184 continue
|
|
1185 if "." in entry.name:
|
|
1186 nayme, ext = os.path.splitext(entry.name)
|
|
1187 else:
|
|
1188 ext = ".txt"
|
80
|
1189 newname = f"{entry.name}{ext}"
|
|
1190 dest = os.path.join(self.repdir, newname)
|
|
1191 src = os.path.join(self.testdir, entry.name)
|
50
|
1192 shutil.copyfile(src, dest)
|
|
1193
|
49
|
1194
|
48
|
1195 def main():
|
|
1196 """
|
|
1197 This is a Galaxy wrapper. It expects to be called by a special purpose tool.xml as:
|
49
|
1198 <command interpreter="python">rgBaseScriptWrapper.py --script_path "$scriptPath"
|
|
1199 --tool_name "foo" --interpreter "Rscript"
|
48
|
1200 </command>
|
|
1201 """
|
|
1202 parser = argparse.ArgumentParser()
|
|
1203 a = parser.add_argument
|
49
|
1204 a("--script_path", default=None)
|
|
1205 a("--history_test", default=None)
|
|
1206 a("--cl_prefix", default=None)
|
|
1207 a("--sysexe", default=None)
|
|
1208 a("--packages", default=None)
|
76
|
1209 a("--tool_name", default="newtool")
|
72
|
1210 a("--tool_dir", default=None)
|
48
|
1211 a("--input_files", default=[], action="append")
|
|
1212 a("--output_files", default=[], action="append")
|
|
1213 a("--user_email", default="Unknown")
|
|
1214 a("--bad_user", default=None)
|
49
|
1215 a("--make_Tool", default="runonly")
|
48
|
1216 a("--help_text", default=None)
|
|
1217 a("--tool_desc", default=None)
|
|
1218 a("--tool_version", default=None)
|
|
1219 a("--citations", default=None)
|
49
|
1220 a("--command_override", default=None)
|
|
1221 a("--test_override", default=None)
|
48
|
1222 a("--additional_parameters", action="append", default=[])
|
|
1223 a("--edit_additional_parameters", action="store_true", default=False)
|
|
1224 a("--parampass", default="positional")
|
|
1225 a("--tfout", default="./tfout")
|
|
1226 a("--new_tool", default="new_tool")
|
49
|
1227 a("--galaxy_url", default="http://localhost:8080")
|
106
|
1228 a("--toolshed_url", default="http://localhost:9009")
|
76
|
1229 # make sure this is identical to tool_sheds_conf.xml localhost != 127.0.0.1 so validation fails
|
63
|
1230 a("--toolshed_api_key", default="fakekey")
|
50
|
1231 a("--galaxy_api_key", default="fakekey")
|
|
1232 a("--galaxy_root", default="/galaxy-central")
|
101
|
1233 a("--galaxy_venv", default="/galaxy_venv")
|
48
|
1234 args = parser.parse_args()
|
|
1235 assert not args.bad_user, (
|
|
1236 'UNAUTHORISED: %s is NOT authorized to use this tool until Galaxy admin adds %s to "admin_users" in the Galaxy configuration file'
|
|
1237 % (args.bad_user, args.bad_user)
|
|
1238 )
|
49
|
1239 assert args.tool_name, "## Tool Factory expects a tool name - eg --tool_name=DESeq"
|
48
|
1240 assert (
|
49
|
1241 args.sysexe or args.packages
|
48
|
1242 ), "## Tool Factory wrapper expects an interpreter or an executable package"
|
49
|
1243 args.input_files = [x.replace('"', "").replace("'", "") for x in args.input_files]
|
48
|
1244 # remove quotes we need to deal with spaces in CL params
|
|
1245 for i, x in enumerate(args.additional_parameters):
|
49
|
1246 args.additional_parameters[i] = args.additional_parameters[i].replace('"', "")
|
48
|
1247 r = ScriptRunner(args)
|
49
|
1248 r.writeShedyml()
|
|
1249 r.makeTool()
|
66
|
1250 if args.make_Tool == "generate":
|
106
|
1251 retcode = r.run() # for testing toolfactory itself
|
66
|
1252 r.moveRunOutputs()
|
|
1253 r.makeToolTar()
|
|
1254 else:
|
106
|
1255 r.planemo_biodocker_test() # test to make outputs and then test
|
66
|
1256 r.moveRunOutputs()
|
|
1257 r.makeToolTar()
|
101
|
1258 if args.make_Tool == "gentestinstall":
|
|
1259 r.shedLoad()
|
|
1260 r.eph_galaxy_load()
|
63
|
1261
|
48
|
1262
|
|
1263 if __name__ == "__main__":
|
|
1264 main()
|