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