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