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