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