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:
|
|
211 if self.args.runmode == "Executable":
|
|
212 if self.args.script_path:
|
|
213 aCL(self.executeme)
|
|
214 aCL(self.sfile)
|
50
|
215 aXCL(self.executeme)
|
49
|
216 aXCL("$runme")
|
|
217 else:
|
|
218 aCL(self.executeme) # this little CL will just run
|
|
219 aXCL(self.executeme)
|
48
|
220 else:
|
49
|
221 if self.args.script_path:
|
|
222 aCL(self.executeme)
|
|
223 aCL(self.sfile)
|
50
|
224 aXCL(self.executeme)
|
49
|
225 aXCL("$runme")
|
|
226 else:
|
|
227 aCL(self.executeme) # this little CL will just run
|
|
228 aXCL(self.executeme)
|
50
|
229 self.elog = os.path.join(self.repdir, "%s_error_log.txt" % self.tool_name)
|
|
230 self.tlog = os.path.join(self.repdir, "%s_runner_log.txt" % self.tool_name)
|
48
|
231
|
|
232 if self.args.parampass == "0":
|
|
233 self.clsimple()
|
|
234 else:
|
|
235 clsuffix = []
|
|
236 xclsuffix = []
|
|
237 for i, p in enumerate(self.infiles):
|
|
238 if p[IOCLPOS] == "STDIN":
|
|
239 appendme = [
|
|
240 p[IOCLPOS],
|
|
241 p[ICLPOS],
|
|
242 p[IPATHPOS],
|
|
243 "< %s" % p[IPATHPOS],
|
|
244 ]
|
|
245 xappendme = [
|
|
246 p[IOCLPOS],
|
|
247 p[ICLPOS],
|
|
248 p[IPATHPOS],
|
|
249 "< $%s" % p[ICLPOS],
|
|
250 ]
|
|
251 else:
|
|
252 appendme = [p[IOCLPOS], p[ICLPOS], p[IPATHPOS], ""]
|
|
253 xappendme = [p[IOCLPOS], p[ICLPOS], "$%s" % p[ICLPOS], ""]
|
|
254 clsuffix.append(appendme)
|
|
255 xclsuffix.append(xappendme)
|
|
256 for i, p in enumerate(self.outfiles):
|
|
257 if p[OOCLPOS] == "STDOUT":
|
|
258 self.lastclredirect = [">", p[ONAMEPOS]]
|
|
259 self.lastxclredirect = [">", "$%s" % p[OCLPOS]]
|
|
260 else:
|
|
261 clsuffix.append([p[OOCLPOS], p[OCLPOS], p[ONAMEPOS], ""])
|
49
|
262 xclsuffix.append([p[OOCLPOS], p[OCLPOS], "$%s" % p[ONAMEPOS], ""])
|
48
|
263 for p in self.addpar:
|
49
|
264 clsuffix.append([p[AOCLPOS], p[ACLPOS], p[AVALPOS], p[AOVERPOS]])
|
48
|
265 xclsuffix.append(
|
|
266 [p[AOCLPOS], p[ACLPOS], '"$%s"' % p[ANAMEPOS], p[AOVERPOS]]
|
|
267 )
|
|
268 clsuffix.sort()
|
|
269 xclsuffix.sort()
|
|
270 self.xclsuffix = xclsuffix
|
|
271 self.clsuffix = clsuffix
|
|
272 if self.args.parampass == "positional":
|
|
273 self.clpositional()
|
|
274 else:
|
|
275 self.clargparse()
|
|
276
|
|
277 def prepScript(self):
|
|
278 rx = open(self.args.script_path, "r").readlines()
|
|
279 rx = [x.rstrip() for x in rx]
|
|
280 rxcheck = [x.strip() for x in rx if x.strip() > ""]
|
|
281 assert len(rxcheck) > 0, "Supplied script is empty. Cannot run"
|
|
282 self.script = "\n".join(rx)
|
|
283 fhandle, self.sfile = tempfile.mkstemp(
|
49
|
284 prefix=self.tool_name, suffix="_%s" % (self.executeme)
|
48
|
285 )
|
|
286 tscript = open(self.sfile, "w")
|
|
287 tscript.write(self.script)
|
|
288 tscript.close()
|
49
|
289 self.indentedScript = " %s" % "\n".join([" %s" % html_escape(x) for x in rx])
|
|
290 self.escapedScript = "%s" % "\n".join([" %s" % html_escape(x) for x in rx])
|
|
291 art = "%s.%s" % (self.tool_name, self.executeme)
|
48
|
292 artifact = open(art, "wb")
|
|
293 artifact.write(bytes(self.script, "utf8"))
|
|
294 artifact.close()
|
|
295
|
|
296 def cleanuppar(self):
|
|
297 """ positional parameters are complicated by their numeric ordinal"""
|
|
298 for i, p in enumerate(self.infiles):
|
|
299 if self.args.parampass == "positional":
|
|
300 assert p[ICLPOS].isdigit(), (
|
|
301 "Positional parameters must be ordinal integers - got %s for %s"
|
|
302 % (p[ICLPOS], p[ILABPOS])
|
|
303 )
|
|
304 p.append(p[ICLPOS])
|
|
305 if p[ICLPOS].isdigit() or self.args.parampass == "0":
|
|
306 scl = "input%d" % (i + 1)
|
|
307 p[ICLPOS] = scl
|
|
308 self.infiles[i] = p
|
|
309 for i, p in enumerate(
|
|
310 self.outfiles
|
|
311 ): # trying to automagically gather using extensions
|
|
312 if self.args.parampass == "positional" and p[OCLPOS] != "STDOUT":
|
|
313 assert p[OCLPOS].isdigit(), (
|
|
314 "Positional parameters must be ordinal integers - got %s for %s"
|
|
315 % (p[OCLPOS], p[ONAMEPOS])
|
|
316 )
|
|
317 p.append(p[OCLPOS])
|
|
318 if p[OCLPOS].isdigit() or p[OCLPOS] == "STDOUT":
|
|
319 scl = p[ONAMEPOS]
|
|
320 p[OCLPOS] = scl
|
|
321 self.outfiles[i] = p
|
|
322 for i, p in enumerate(self.addpar):
|
|
323 if self.args.parampass == "positional":
|
|
324 assert p[ACLPOS].isdigit(), (
|
|
325 "Positional parameters must be ordinal integers - got %s for %s"
|
|
326 % (p[ACLPOS], p[ANAMEPOS])
|
|
327 )
|
|
328 p.append(p[ACLPOS])
|
|
329 if p[ACLPOS].isdigit():
|
|
330 scl = "input%s" % p[ACLPOS]
|
|
331 p[ACLPOS] = scl
|
|
332 self.addpar[i] = p
|
|
333
|
|
334 def clsimple(self):
|
|
335 """ no parameters - uses < and > for i/o
|
|
336 """
|
|
337 aCL = self.cl.append
|
|
338 aCL("<")
|
|
339 aCL(self.infiles[0][IPATHPOS])
|
|
340 aCL(">")
|
|
341 aCL(self.outfiles[0][OCLPOS])
|
|
342 aXCL = self.xmlcl.append
|
|
343 aXCL("<")
|
|
344 aXCL("$%s" % self.infiles[0][ICLPOS])
|
|
345 aXCL(">")
|
|
346 aXCL("$%s" % self.outfiles[0][ONAMEPOS])
|
|
347
|
|
348 def clpositional(self):
|
|
349 # inputs in order then params
|
|
350 aCL = self.cl.append
|
|
351 for (o_v, k, v, koverride) in self.clsuffix:
|
|
352 if " " in v:
|
|
353 aCL("%s" % v)
|
|
354 else:
|
|
355 aCL(v)
|
|
356 aXCL = self.xmlcl.append
|
|
357 for (o_v, k, v, koverride) in self.xclsuffix:
|
|
358 aXCL(v)
|
|
359 if self.lastxclredirect:
|
|
360 aXCL(self.lastxclredirect[0])
|
|
361 aXCL(self.lastxclredirect[1])
|
|
362
|
|
363 def clargparse(self):
|
|
364 """ argparse style
|
|
365 """
|
|
366 aCL = self.cl.append
|
|
367 aXCL = self.xmlcl.append
|
|
368 # inputs then params in argparse named form
|
|
369 for (o_v, k, v, koverride) in self.xclsuffix:
|
|
370 if koverride > "":
|
|
371 k = koverride
|
|
372 elif len(k.strip()) == 1:
|
|
373 k = "-%s" % k
|
|
374 else:
|
|
375 k = "--%s" % k
|
|
376 aXCL(k)
|
|
377 aXCL(v)
|
|
378 for (o_v, k, v, koverride) in self.clsuffix:
|
|
379 if koverride > "":
|
|
380 k = koverride
|
|
381 elif len(k.strip()) == 1:
|
|
382 k = "-%s" % k
|
|
383 else:
|
|
384 k = "--%s" % k
|
|
385 aCL(k)
|
|
386 aCL(v)
|
|
387
|
|
388 def getNdash(self, newname):
|
|
389 if self.is_positional:
|
|
390 ndash = 0
|
|
391 else:
|
|
392 ndash = 2
|
|
393 if len(newname) < 2:
|
|
394 ndash = 1
|
|
395 return ndash
|
|
396
|
|
397 def doXMLparam(self):
|
|
398 """flake8 made me do this..."""
|
|
399 for p in self.outfiles:
|
49
|
400 newname, newfmt, newcl, test, oldcl = p
|
48
|
401 ndash = self.getNdash(newcl)
|
|
402 aparm = gxtp.OutputData(newcl, format=newfmt, num_dashes=ndash)
|
|
403 aparm.positional = self.is_positional
|
|
404 if self.is_positional:
|
|
405 if oldcl == "STDOUT":
|
|
406 aparm.positional = 9999999
|
|
407 aparm.command_line_override = "> $%s" % newcl
|
|
408 else:
|
|
409 aparm.positional = int(oldcl)
|
|
410 aparm.command_line_override = "$%s" % newcl
|
|
411 self.toutputs.append(aparm)
|
49
|
412 usetest = None
|
|
413 ld = None
|
50
|
414 if test > "":
|
|
415 if test.startswith("diff"):
|
|
416 usetest = "diff"
|
|
417 if test.split(":")[1].isdigit:
|
|
418 ld = int(test.split(":")[1])
|
49
|
419 else:
|
|
420 usetest = test
|
50
|
421 tp = gxtp.TestOutput(
|
|
422 name=newcl,
|
|
423 value="%s_sample" % newcl,
|
|
424 format=newfmt,
|
|
425 compare=usetest,
|
|
426 lines_diff=ld,
|
|
427 delta=None,
|
|
428 )
|
48
|
429 self.testparam.append(tp)
|
|
430 for p in self.infiles:
|
|
431 newname = p[ICLPOS]
|
|
432 newfmt = p[IFMTPOS]
|
|
433 ndash = self.getNdash(newname)
|
|
434 if not len(p[ILABPOS]) > 0:
|
|
435 alab = p[ICLPOS]
|
|
436 else:
|
|
437 alab = p[ILABPOS]
|
|
438 aninput = gxtp.DataParam(
|
|
439 newname,
|
|
440 optional=False,
|
|
441 label=alab,
|
|
442 help=p[IHELPOS],
|
|
443 format=newfmt,
|
|
444 multiple=False,
|
|
445 num_dashes=ndash,
|
|
446 )
|
|
447 aninput.positional = self.is_positional
|
|
448 self.tinputs.append(aninput)
|
|
449 tparm = gxtp.TestParam(name=newname, value="%s_sample" % newname)
|
|
450 self.testparam.append(tparm)
|
|
451 for p in self.addpar:
|
|
452 newname, newval, newlabel, newhelp, newtype, newcl, override, oldcl = p
|
|
453 if not len(newlabel) > 0:
|
|
454 newlabel = newname
|
|
455 ndash = self.getNdash(newname)
|
|
456 if newtype == "text":
|
|
457 aparm = gxtp.TextParam(
|
|
458 newname,
|
|
459 label=newlabel,
|
|
460 help=newhelp,
|
|
461 value=newval,
|
|
462 num_dashes=ndash,
|
|
463 )
|
|
464 elif newtype == "integer":
|
|
465 aparm = gxtp.IntegerParam(
|
|
466 newname,
|
|
467 label=newname,
|
|
468 help=newhelp,
|
|
469 value=newval,
|
|
470 num_dashes=ndash,
|
|
471 )
|
|
472 elif newtype == "float":
|
|
473 aparm = gxtp.FloatParam(
|
|
474 newname,
|
|
475 label=newname,
|
|
476 help=newhelp,
|
|
477 value=newval,
|
|
478 num_dashes=ndash,
|
|
479 )
|
|
480 else:
|
|
481 raise ValueError(
|
|
482 'Unrecognised parameter type "%s" for\
|
|
483 additional parameter %s in makeXML'
|
|
484 % (newtype, newname)
|
|
485 )
|
|
486 aparm.positional = self.is_positional
|
|
487 if self.is_positional:
|
|
488 aninput.positional = int(oldcl)
|
|
489 self.tinputs.append(aparm)
|
|
490 self.tparm = gxtp.TestParam(newname, value=newval)
|
|
491 self.testparam.append(tparm)
|
|
492
|
|
493 def doNoXMLparam(self):
|
49
|
494 """filter style package - stdin to stdout"""
|
48
|
495 alab = self.infiles[0][ILABPOS]
|
|
496 if len(alab) == 0:
|
|
497 alab = self.infiles[0][ICLPOS]
|
|
498 max1s = (
|
49
|
499 "Maximum one input if parampass is 0 but multiple input files supplied - %s"
|
48
|
500 % str(self.infiles)
|
|
501 )
|
|
502 assert len(self.infiles) == 1, max1s
|
|
503 newname = self.infiles[0][ICLPOS]
|
|
504 aninput = gxtp.DataParam(
|
|
505 newname,
|
|
506 optional=False,
|
|
507 label=alab,
|
|
508 help=self.infiles[0][IHELPOS],
|
|
509 format=self.infiles[0][IFMTPOS],
|
|
510 multiple=False,
|
|
511 num_dashes=0,
|
|
512 )
|
|
513 aninput.command_line_override = "< $%s" % newname
|
|
514 aninput.positional = self.is_positional
|
|
515 self.tinputs.append(aninput)
|
|
516 tp = gxtp.TestParam(name=newname, value="%s_sample" % newname)
|
|
517 self.testparam.append(tp)
|
|
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)
|
49
|
524 tp = gxtp.TestOutput(name=newname, value="%s_sample" % newname, format=newfmt)
|
48
|
525 self.testparam.append(tp)
|
|
526
|
|
527 def makeXML(self):
|
|
528 """
|
|
529 Create a Galaxy xml tool wrapper for the new script
|
|
530 Uses galaxyhtml
|
|
531 Hmmm. How to get the command line into correct order...
|
|
532 """
|
49
|
533 if self.command_override:
|
50
|
534 self.newtool.command_line_override = self.command_override # config file
|
48
|
535 else:
|
50
|
536 self.newtool.command_line_override = self.xmlcl
|
48
|
537 if self.args.help_text:
|
|
538 helptext = open(self.args.help_text, "r").readlines()
|
50
|
539 safertext = [html_escape(x) for x in helptext]
|
|
540 if self.args.script_path:
|
|
541 scrpt = self.script.split('\n')
|
|
542 scrpt.append("```\n")
|
|
543 if len(scrpt) > 300:
|
|
544 safertext = safertext + scrpt[:100] + ['>500 lines - stuff deleted','......'] + scrpt[-100:]
|
|
545 else:
|
|
546 safertext = safertext + scrpt
|
|
547 safertext.append("\n```")
|
|
548 self.newtool.help = "".join([x for x in safertext])
|
48
|
549 else:
|
50
|
550 self.newtool.help = (
|
48
|
551 "Please ask the tool author (%s) for help \
|
|
552 as none was supplied at tool generation\n"
|
|
553 % (self.args.user_email)
|
|
554 )
|
50
|
555 self.newtool.version_command = None # do not want
|
48
|
556 requirements = gxtp.Requirements()
|
49
|
557 if self.args.packages:
|
|
558 for d in self.args.packages.split(","):
|
|
559 if ":" in d:
|
|
560 packg, ver = d.split(":")
|
|
561 else:
|
|
562 packg = d
|
|
563 ver = ""
|
50
|
564 requirements.append(
|
|
565 gxtp.Requirement("package", packg.strip(), ver.strip())
|
|
566 )
|
|
567 self.newtool.requirements = requirements
|
48
|
568 if self.args.parampass == "0":
|
|
569 self.doNoXMLparam()
|
|
570 else:
|
|
571 self.doXMLparam()
|
50
|
572 self.newtool.outputs = self.toutputs
|
|
573 self.newtool.inputs = self.tinputs
|
|
574 if self.args.script_path:
|
48
|
575 configfiles = gxtp.Configfiles()
|
49
|
576 configfiles.append(gxtp.Configfile(name="runme", text=self.script))
|
50
|
577 self.newtool.configfiles = configfiles
|
48
|
578 tests = gxtp.Tests()
|
|
579 test_a = gxtp.Test()
|
|
580 for tp in self.testparam:
|
|
581 test_a.append(tp)
|
|
582 tests.append(test_a)
|
50
|
583 self.newtool.tests = tests
|
|
584 self.newtool.add_comment(
|
48
|
585 "Created by %s at %s using the Galaxy Tool Factory."
|
|
586 % (self.args.user_email, timenow())
|
|
587 )
|
50
|
588 self.newtool.add_comment("Source in git at: %s" % (toolFactoryURL))
|
|
589 self.newtool.add_comment(
|
48
|
590 "Cite: Creating re-usable tools from scripts doi: \
|
|
591 10.1093/bioinformatics/bts573"
|
|
592 )
|
50
|
593 exml0 = self.newtool.export()
|
49
|
594 exml = exml0.replace(FAKEEXE, "") # temporary work around until PR accepted
|
50
|
595 if (
|
|
596 self.test_override
|
|
597 ): # cannot do this inside galaxyxml as it expects lxml objects for tests
|
|
598 part1 = exml.split("<tests>")[0]
|
|
599 part2 = exml.split("</tests>")[1]
|
|
600 fixed = "%s\n%s\n%s" % (part1, self.test_override, part2)
|
49
|
601 exml = fixed
|
|
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
|
|
611 won't work if command or test override in play - planemo is the
|
|
612 easiest way to generate test outputs for that case so is
|
|
613 automagically selected
|
48
|
614 """
|
|
615 s = "run cl=%s" % str(self.cl)
|
|
616 logging.debug(s)
|
|
617 scl = " ".join(self.cl)
|
|
618 err = None
|
|
619 if self.args.parampass != "0":
|
|
620 ste = open(self.elog, "wb")
|
|
621 if self.lastclredirect:
|
49
|
622 sto = open(self.lastclredirect[1], "wb") # is name of an output file
|
48
|
623 else:
|
|
624 sto = open(self.tlog, "wb")
|
|
625 sto.write(
|
|
626 bytes(
|
49
|
627 "## Executing Toolfactory generated command line = %s\n" % scl,
|
48
|
628 "utf8",
|
|
629 )
|
|
630 )
|
|
631 sto.flush()
|
|
632 p = subprocess.run(self.cl, shell=False, stdout=sto, stderr=ste)
|
|
633 sto.close()
|
|
634 ste.close()
|
|
635 tmp_stderr = open(self.elog, "rb")
|
|
636 err = ""
|
|
637 buffsize = 1048576
|
|
638 try:
|
|
639 while True:
|
|
640 err += str(tmp_stderr.read(buffsize))
|
|
641 if not err or len(err) % buffsize != 0:
|
|
642 break
|
|
643 except OverflowError:
|
|
644 pass
|
|
645 tmp_stderr.close()
|
|
646 retval = p.returncode
|
49
|
647 else: # work around special case - stdin and write to stdout
|
48
|
648 sti = open(self.infiles[0][IPATHPOS], "rb")
|
|
649 sto = open(self.outfiles[0][ONAMEPOS], "wb")
|
|
650 # must use shell to redirect
|
|
651 p = subprocess.run(self.cl, shell=False, stdout=sto, stdin=sti)
|
|
652 retval = p.returncode
|
|
653 sto.close()
|
|
654 sti.close()
|
|
655 if os.path.isfile(self.tlog) and os.stat(self.tlog).st_size == 0:
|
|
656 os.unlink(self.tlog)
|
|
657 if os.path.isfile(self.elog) and os.stat(self.elog).st_size == 0:
|
|
658 os.unlink(self.elog)
|
|
659 if retval != 0 and err: # problem
|
|
660 sys.stderr.write(err)
|
|
661 logging.debug("run done")
|
|
662 return retval
|
|
663
|
|
664 def planemo_shedload(self):
|
|
665 """
|
|
666 planemo shed_create --shed_target testtoolshed
|
|
667 planemo shed_update --check_diff --shed_target testtoolshed
|
|
668 """
|
49
|
669 if os.path.exists(self.tlog):
|
50
|
670 tout = open(self.tlog, "a")
|
49
|
671 else:
|
50
|
672 tout = open(self.tlog, "w")
|
49
|
673 cll = ["planemo", "shed_create", "--shed_target", "local"]
|
|
674 try:
|
50
|
675 p = subprocess.run(
|
|
676 cll, shell=True, cwd=self.tooloutdir, stdout=tout, stderr=tout
|
|
677 )
|
49
|
678 except:
|
|
679 pass
|
48
|
680 if p.returncode != 0:
|
49
|
681 print("Repository %s exists" % self.args.tool_name)
|
48
|
682 else:
|
49
|
683 print("initiated %s" % self.args.tool_name)
|
|
684 cll = [
|
|
685 "planemo",
|
|
686 "shed_upload",
|
|
687 "--shed_target",
|
|
688 "local",
|
|
689 "--owner",
|
|
690 "fubar",
|
|
691 "--name",
|
|
692 self.args.tool_name,
|
|
693 "--shed_key",
|
|
694 self.args.toolshed_api_key,
|
|
695 "--tar",
|
|
696 self.newtarpath,
|
|
697 ]
|
50
|
698 p = subprocess.run(cll, shell=True)
|
49
|
699 print("Ran", " ".join(cll), "got", p.returncode)
|
|
700 tout.close()
|
48
|
701 return p.returncode
|
|
702
|
49
|
703 def planemo_test(self, genoutputs=True):
|
50
|
704 """planemo is a requirement so is available for testing
|
|
705 and for generating test outputs if command or test overrides are supplied
|
|
706 test outputs are sent to repdir for display
|
48
|
707 """
|
49
|
708 xreal = "%s.xml" % self.tool_name
|
|
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 if genoutputs:
|
|
714 cll = [
|
|
715 "planemo",
|
|
716 "test",
|
|
717 "--galaxy_root",
|
|
718 self.args.galaxy_root,
|
|
719 "--update_test_data",
|
50
|
720 "--galaxy_python_version",
|
|
721 "3.6",
|
|
722 "--no_conda_auto_install",
|
|
723 "--no_conda_auto_init",
|
49
|
724 xreal,
|
|
725 ]
|
|
726 else:
|
50
|
727 cll = ["planemo", "test", "--galaxy_python_version",
|
|
728 "3.6", "--galaxy_root",
|
|
729 self.args.galaxy_root,
|
|
730 "--no_conda_auto_install",
|
|
731 "--no_conda_auto_init",
|
|
732 xreal,]
|
|
733 p = subprocess.run(
|
|
734 cll, shell=True, cwd=self.tooloutdir, stderr=tout, stdout=tout
|
|
735 )
|
|
736 if genoutputs:
|
|
737 with os.scandir(self.testdir) as outs:
|
|
738 for entry in outs:
|
|
739 if entry.is_file():
|
|
740 dest = os.path.join(self.repdir, entry.name)
|
|
741 src = os.path.join(self.testdir, entry.name)
|
|
742 shutil.copyfile(src, dest)
|
|
743 tout.write(
|
|
744 "Copied output %s to %s after planemo test\n" % (src, dest)
|
|
745 )
|
49
|
746 tout.close()
|
48
|
747 return p.returncode
|
|
748
|
|
749 def eph_galaxy_load(self):
|
50
|
750 """load the new tool from the local toolshed after planemo uploads it
|
48
|
751 """
|
49
|
752 if os.path.exists(self.tlog):
|
50
|
753 tout = open(self.tlog, "a")
|
49
|
754 else:
|
50
|
755 tout = open(self.tlog, "w")
|
49
|
756 cll = [
|
|
757 "shed-tools",
|
|
758 "install",
|
|
759 "-g",
|
|
760 self.args.galaxy_url,
|
|
761 "--latest",
|
|
762 "-a",
|
|
763 self.args.galaxy_api_key,
|
|
764 "--name",
|
|
765 self.args.tool_name,
|
|
766 "--owner",
|
|
767 "fubar",
|
|
768 "--toolshed",
|
|
769 self.args.toolshed_url,
|
|
770 "--section_label",
|
|
771 "Generated Tools",
|
|
772 "--install_tool_dependencies",
|
|
773 ]
|
|
774 print("running\n", " ".join(cll))
|
|
775 p = subprocess.run(cll, shell=False, stderr=tout, stdout=tout)
|
48
|
776 if p.returncode != 0:
|
49
|
777 print(
|
|
778 "Repository %s installation returned %d"
|
|
779 % (self.args.tool_name, p.returncode)
|
|
780 )
|
48
|
781 else:
|
49
|
782 print("installed %s" % self.args.tool_name)
|
|
783 tout.close()
|
48
|
784 return p.returncode
|
|
785
|
|
786 def writeShedyml(self):
|
50
|
787 """for planemo
|
|
788 """
|
49
|
789 yuser = self.args.user_email.split("@")[0]
|
|
790 yfname = os.path.join(self.tooloutdir, ".shed.yml")
|
|
791 yamlf = open(yfname, "w")
|
|
792 odict = {
|
|
793 "name": self.tool_name,
|
|
794 "owner": yuser,
|
|
795 "type": "unrestricted",
|
|
796 "description": self.args.tool_desc,
|
50
|
797 "synopsis": self.args.tool_desc,
|
|
798 "category": "TF Generated Tools",
|
49
|
799 }
|
48
|
800 yaml.dump(odict, yamlf, allow_unicode=True)
|
|
801 yamlf.close()
|
|
802
|
50
|
803 def makeTool(self):
|
|
804 """write xmls and input samples into place
|
|
805 """
|
|
806 self.makeXML()
|
|
807 if self.args.script_path:
|
|
808 stname = os.path.join(self.tooloutdir, "%s" % (self.sfile))
|
|
809 if not os.path.exists(stname):
|
|
810 shutil.copyfile(self.sfile, stname)
|
|
811 xreal = "%s.xml" % self.tool_name
|
|
812 xout = os.path.join(self.tooloutdir, xreal)
|
|
813 shutil.copyfile(xreal, xout)
|
|
814 for p in self.infiles:
|
|
815 pth = p[IPATHPOS]
|
|
816 dest = os.path.join(self.testdir, "%s_sample" % p[ICLPOS])
|
|
817 shutil.copyfile(pth, dest)
|
|
818 dest = os.path.join(self.repdir, "%s.%s" % (p[ICLPOS], p[IFMTPOS]))
|
|
819 shutil.copyfile(pth, dest)
|
49
|
820
|
50
|
821 def makeToolTar(self):
|
|
822 """ move outputs into test-data and prepare the tarball
|
|
823 """
|
|
824 for p in self.outfiles:
|
|
825 src = p[ONAMEPOS]
|
|
826 if os.path.isfile(src):
|
|
827 dest = os.path.join(self.testdir, "%s_sample" % src)
|
|
828 shutil.copyfile(src, dest)
|
|
829 dest = os.path.join(self.repdir, "%s.%s" % (src, p[OFMTPOS]))
|
|
830 shutil.copyfile(src, dest)
|
|
831 else:
|
|
832 print(
|
|
833 "### problem - output file %s not found in tooloutdir %s"
|
|
834 % (src, self.tooloutdir)
|
|
835 )
|
|
836 self.newtarpath = "toolfactory_%s.tgz" % self.tool_name
|
|
837 tf = tarfile.open(self.newtarpath, "w:gz")
|
|
838 tf.add(name=self.tooloutdir, arcname=self.tool_name)
|
|
839 tf.close()
|
|
840 shutil.copyfile(self.newtarpath, self.args.new_tool)
|
|
841
|
|
842 def moveRunOutputs(self):
|
|
843 """need to move planemo or run outputs into toolfactory collection
|
|
844 """
|
|
845 with os.scandir(self.tooloutdir) as outs:
|
|
846 for entry in outs:
|
|
847 if not entry.is_file() or entry.name.startswith("."):
|
|
848 continue
|
|
849 if "." in entry.name:
|
|
850 nayme, ext = os.path.splitext(entry.name)
|
|
851 else:
|
|
852 ext = ".txt"
|
|
853 ofn = "%s%s" % (entry.name.replace(".", "_"), ext)
|
|
854 dest = os.path.join(self.repdir, ofn)
|
|
855 src = os.path.join(self.tooloutdir, entry.name)
|
|
856 shutil.copyfile(src, dest)
|
|
857
|
49
|
858
|
48
|
859 def main():
|
|
860 """
|
|
861 This is a Galaxy wrapper. It expects to be called by a special purpose tool.xml as:
|
49
|
862 <command interpreter="python">rgBaseScriptWrapper.py --script_path "$scriptPath"
|
|
863 --tool_name "foo" --interpreter "Rscript"
|
48
|
864 </command>
|
|
865 """
|
|
866 parser = argparse.ArgumentParser()
|
|
867 a = parser.add_argument
|
49
|
868 a("--script_path", default=None)
|
|
869 a("--history_test", default=None)
|
|
870 a("--cl_prefix", default=None)
|
|
871 a("--sysexe", default=None)
|
|
872 a("--packages", default=None)
|
48
|
873 a("--tool_name", default=None)
|
|
874 a("--input_files", default=[], action="append")
|
|
875 a("--output_files", default=[], action="append")
|
|
876 a("--user_email", default="Unknown")
|
|
877 a("--bad_user", default=None)
|
49
|
878 a("--make_Tool", default="runonly")
|
48
|
879 a("--help_text", default=None)
|
|
880 a("--tool_desc", default=None)
|
|
881 a("--tool_version", default=None)
|
|
882 a("--citations", default=None)
|
49
|
883 a("--command_override", default=None)
|
|
884 a("--test_override", default=None)
|
48
|
885 a("--additional_parameters", action="append", default=[])
|
|
886 a("--edit_additional_parameters", action="store_true", default=False)
|
|
887 a("--parampass", default="positional")
|
|
888 a("--tfout", default="./tfout")
|
|
889 a("--new_tool", default="new_tool")
|
|
890 a("--runmode", default=None)
|
49
|
891 a("--galaxy_url", default="http://localhost:8080")
|
50
|
892 a("--galaxy_api_key", default="fakekey")
|
48
|
893 a("--toolshed_url", default="http://localhost:9009")
|
50
|
894 a("--toolshed_api_key", default="fakekey")
|
|
895 a("--galaxy_root", default="/galaxy-central")
|
48
|
896
|
|
897 args = parser.parse_args()
|
|
898 assert not args.bad_user, (
|
|
899 'UNAUTHORISED: %s is NOT authorized to use this tool until Galaxy admin adds %s to "admin_users" in the Galaxy configuration file'
|
|
900 % (args.bad_user, args.bad_user)
|
|
901 )
|
49
|
902 assert args.tool_name, "## Tool Factory expects a tool name - eg --tool_name=DESeq"
|
48
|
903 assert (
|
49
|
904 args.sysexe or args.packages
|
48
|
905 ), "## Tool Factory wrapper expects an interpreter or an executable package"
|
49
|
906 args.input_files = [x.replace('"', "").replace("'", "") for x in args.input_files]
|
48
|
907 # remove quotes we need to deal with spaces in CL params
|
|
908 for i, x in enumerate(args.additional_parameters):
|
49
|
909 args.additional_parameters[i] = args.additional_parameters[i].replace('"', "")
|
48
|
910 r = ScriptRunner(args)
|
49
|
911 r.writeShedyml()
|
|
912 r.makeTool()
|
50
|
913 if args.command_override or args.test_override:
|
|
914 retcode = r.planemo_test(genoutputs=True) # this fails :( - see PR
|
|
915 r.moveRunOutputs()
|
|
916 r.makeToolTar()
|
|
917 retcode = r.planemo_test(genoutputs=False)
|
|
918 r.moveRunOutputs()
|
|
919 if args.make_Tool == "gentestinstall":
|
|
920 r.planemo_shedload()
|
|
921 r.eph_galaxy_load()
|
|
922 else:
|
49
|
923 retcode = r.run()
|
|
924 if retcode:
|
|
925 sys.stderr.write(
|
|
926 "## Run failed with return code %d. Cannot build yet. Please fix and retry"
|
|
927 % retcode
|
|
928 )
|
|
929 sys.exit(1)
|
|
930 else:
|
|
931 r.moveRunOutputs()
|
50
|
932 r.makeToolTar()
|
|
933 if args.make_Tool in ["gentestinstall", "gentest"]:
|
|
934 r.planemo_test(genoutputs=False)
|
|
935 r.moveRunOutputs()
|
|
936 if args.make_Tool == "gentestinstall":
|
|
937 r.planemo_shedload()
|
|
938 r.eph_galaxy_load()
|
48
|
939
|
|
940
|
|
941 if __name__ == "__main__":
|
|
942 main()
|