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