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